ccusage 16.2.5 → 17.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3733 @@
1
+ import { activityDateSchema, array, boolean, createBucket, createDailyDate, createMonthlyDate, createProjectPath, createSessionId, createWeeklyDate, dailyDateSchema, getTotalTokens, isoTimestampSchema, messageIdSchema, modelNameSchema, monthlyDateSchema, number, object, optional, parse as parse$2, projectPathSchema, requestIdSchema, safeParse, sessionIdSchema, string, union, versionSchema, weeklyDateSchema } from "./_types-CV6z8-9_.js";
2
+ import { logger } from "./logger-C_yajNg2.js";
3
+ import { createRequire } from "node:module";
4
+ import a, { readFile, stat } from "node:fs/promises";
5
+ import path, { basename, dirname, normalize, posix, relative, resolve, sep } from "node:path";
6
+ import process$1 from "node:process";
7
+ import * as nativeFs from "node:fs";
8
+ import b from "node:fs";
9
+ import F, { homedir } from "node:os";
10
+ import { fileURLToPath } from "node:url";
11
+ var __create = Object.create;
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __getProtoOf = Object.getPrototypeOf;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n$1 = keys.length, key; i < n$1; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
+ get: ((k$1) => from[k$1]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+ var __require$1 = /* @__PURE__ */ createRequire(import.meta.url);
33
+ function toArray(array$1) {
34
+ array$1 = array$1 ?? [];
35
+ return Array.isArray(array$1) ? array$1 : [array$1];
36
+ }
37
+ const isFailure = (result) => "Failure" === result.type;
38
+ const isPromise = (value) => "object" == typeof value && null !== value && "then" in value && "function" == typeof value.then && "catch" in value && "function" == typeof value.catch;
39
+ const andThen = (fn) => (result) => {
40
+ const apply = (r) => {
41
+ if (isFailure(r)) return r;
42
+ return fn(r.value);
43
+ };
44
+ return isPromise(result) ? result.then(apply) : apply(result);
45
+ };
46
+ const andThrough = (fn) => (result) => {
47
+ const apply = (r) => {
48
+ if (isFailure(r)) return r;
49
+ const next = fn(r.value);
50
+ if (isPromise(next)) return next.then((n$1) => {
51
+ if (isFailure(n$1)) return n$1;
52
+ return r;
53
+ });
54
+ if (isFailure(next)) return next;
55
+ return r;
56
+ };
57
+ return isPromise(result) ? result.then(apply) : apply(result);
58
+ };
59
+ const isSuccess = (result) => "Success" === result.type;
60
+ const succeed = (...args) => {
61
+ if (args.length <= 0) return { type: "Success" };
62
+ const value = args[0];
63
+ if (isPromise(value)) return value.then((value$1) => ({
64
+ type: "Success",
65
+ value: value$1
66
+ }));
67
+ return {
68
+ type: "Success",
69
+ value
70
+ };
71
+ };
72
+ const fail = (...args) => {
73
+ if (args.length <= 0) return { type: "Failure" };
74
+ const error = args[0];
75
+ if (isPromise(error)) return error.then((error$1) => ({
76
+ type: "Failure",
77
+ error: error$1
78
+ }));
79
+ return {
80
+ type: "Failure",
81
+ error
82
+ };
83
+ };
84
+ const inspect = (fn) => (result) => {
85
+ const apply = (r) => {
86
+ if (isSuccess(r)) fn(r.value);
87
+ return r;
88
+ };
89
+ return isPromise(result) ? result.then(apply) : apply(result);
90
+ };
91
+ const inspectError = (fn) => (result) => {
92
+ const apply = (r) => {
93
+ if (isFailure(r)) fn(r.error);
94
+ return r;
95
+ };
96
+ return isPromise(result) ? result.then(apply) : apply(result);
97
+ };
98
+ const isResult = (result) => "object" == typeof result && null !== result && "type" in result && ("Success" === result.type && "value" in result || "Failure" === result.type && "error" in result);
99
+ const map = (fn) => (result) => {
100
+ const apply = (r) => {
101
+ if (isFailure(r)) return r;
102
+ return succeed(fn(r.value));
103
+ };
104
+ if (isPromise(result)) return result.then(apply);
105
+ return apply(result);
106
+ };
107
+ const orElse = (fn) => (result) => {
108
+ const apply = (r) => {
109
+ if (isSuccess(r)) return r;
110
+ return fn(r.error);
111
+ };
112
+ return isPromise(result) ? result.then(apply) : apply(result);
113
+ };
114
+ const pipe = (value, ...functions) => {
115
+ let next = value;
116
+ for (const func of functions) next = func(next);
117
+ return next;
118
+ };
119
+ const try_ = (options) => {
120
+ if (isPromise(options.try)) {
121
+ if ("safe" in options && options.safe) return succeed(options.try);
122
+ return options.try.then((value) => succeed(value), (error) => fail(options.catch(error)));
123
+ }
124
+ return (...args) => {
125
+ try {
126
+ const output = options.try(...args);
127
+ if (isPromise(output)) {
128
+ const promise$1 = succeed(output);
129
+ if ("safe" in options && options.safe) return promise$1;
130
+ return promise$1.catch((error) => fail(options.catch(error)));
131
+ }
132
+ return succeed(output);
133
+ } catch (error) {
134
+ if ("safe" in options && options.safe) throw error;
135
+ return fail(options.catch(error));
136
+ }
137
+ };
138
+ };
139
+ const unwrap = (...args) => {
140
+ const firstArgument = args[0];
141
+ if (isResult(firstArgument) || isPromise(firstArgument)) {
142
+ const result = firstArgument;
143
+ const hasDefault$1 = 2 === args.length;
144
+ const defaultValue$1 = hasDefault$1 ? args[1] : void 0;
145
+ const apply = (r) => {
146
+ if (isFailure(r)) {
147
+ if (hasDefault$1) return defaultValue$1;
148
+ throw r.error;
149
+ }
150
+ return r.value;
151
+ };
152
+ return isPromise(result) ? result.then(apply) : apply(result);
153
+ }
154
+ const hasDefault = 1 === args.length;
155
+ const defaultValue = hasDefault ? args[0] : void 0;
156
+ return (result) => {
157
+ const apply = (r) => {
158
+ if (isFailure(r)) {
159
+ if (hasDefault) return defaultValue;
160
+ throw r.error;
161
+ }
162
+ return r.value;
163
+ };
164
+ return isPromise(result) ? result.then(apply) : apply(result);
165
+ };
166
+ };
167
+ function groupBy(arr, getKeyFromItem) {
168
+ const result = {};
169
+ for (let i = 0; i < arr.length; i++) {
170
+ const item = arr[i];
171
+ const key = getKeyFromItem(item);
172
+ if (!Object.hasOwn(result, key)) result[key] = [];
173
+ result[key].push(item);
174
+ }
175
+ return result;
176
+ }
177
+ function uniq(arr) {
178
+ return Array.from(new Set(arr));
179
+ }
180
+ var d = Object.defineProperty;
181
+ var n = (s, t) => d(s, "name", {
182
+ value: t,
183
+ configurable: !0
184
+ });
185
+ typeof Symbol.asyncDispose != "symbol" && Object.defineProperty(Symbol, "asyncDispose", {
186
+ configurable: !1,
187
+ enumerable: !1,
188
+ writable: !1,
189
+ value: Symbol.for("asyncDispose")
190
+ });
191
+ var P = class {
192
+ static {
193
+ n(this, "FsFixture");
194
+ }
195
+ path;
196
+ constructor(t) {
197
+ this.path = t;
198
+ }
199
+ getPath(...t) {
200
+ return path.join(this.path, ...t);
201
+ }
202
+ exists(t = "") {
203
+ return a.access(this.getPath(t)).then(() => !0, () => !1);
204
+ }
205
+ rm(t = "") {
206
+ return a.rm(this.getPath(t), {
207
+ recursive: !0,
208
+ force: !0
209
+ });
210
+ }
211
+ cp(t, r, i) {
212
+ return r ? r.endsWith(path.sep) && (r += path.basename(t)) : r = path.basename(t), a.cp(t, this.getPath(r), i);
213
+ }
214
+ mkdir(t) {
215
+ return a.mkdir(this.getPath(t), { recursive: !0 });
216
+ }
217
+ writeFile(t, r) {
218
+ return a.writeFile(this.getPath(t), r);
219
+ }
220
+ writeJson(t, r) {
221
+ return this.writeFile(t, JSON.stringify(r, null, 2));
222
+ }
223
+ readFile(t, r) {
224
+ return a.readFile(this.getPath(t), r);
225
+ }
226
+ async [Symbol.asyncDispose]() {
227
+ await this.rm();
228
+ }
229
+ };
230
+ const v = b.realpathSync(F.tmpdir()), D = `fs-fixture-${Date.now()}-${process.pid}`;
231
+ let m = 0;
232
+ const j = n(() => (m += 1, m), "getId");
233
+ var u = class {
234
+ static {
235
+ n(this, "Path");
236
+ }
237
+ path;
238
+ constructor(t) {
239
+ this.path = t;
240
+ }
241
+ };
242
+ var f = class extends u {
243
+ static {
244
+ n(this, "Directory");
245
+ }
246
+ };
247
+ var y = class extends u {
248
+ static {
249
+ n(this, "File");
250
+ }
251
+ content;
252
+ constructor(t, r) {
253
+ super(t), this.content = r;
254
+ }
255
+ };
256
+ var l = class {
257
+ static {
258
+ n(this, "Symlink");
259
+ }
260
+ target;
261
+ type;
262
+ path;
263
+ constructor(t, r) {
264
+ this.target = t, this.type = r;
265
+ }
266
+ };
267
+ const w = n((s, t, r) => {
268
+ const i = [];
269
+ for (const p in s) {
270
+ if (!Object.hasOwn(s, p)) continue;
271
+ const e = path.join(t, p);
272
+ let o = s[p];
273
+ if (typeof o == "function") {
274
+ const g = Object.assign(Object.create(r), { filePath: e }), h = o(g);
275
+ if (h instanceof l) {
276
+ h.path = e, i.push(h);
277
+ continue;
278
+ } else o = h;
279
+ }
280
+ typeof o == "string" ? i.push(new y(e, o)) : i.push(new f(e), ...w(o, e, r));
281
+ }
282
+ return i;
283
+ }, "flattenFileTree");
284
+ n(async (s, t) => {
285
+ const r = t?.tempDir ? path.resolve(t.tempDir) : v, i = path.join(r, `${D}-${j()}/`);
286
+ if (await a.mkdir(i, { recursive: !0 }), s) {
287
+ if (typeof s == "string") await a.cp(s, i, {
288
+ recursive: !0,
289
+ filter: t?.templateFilter
290
+ });
291
+ else if (typeof s == "object") {
292
+ const p = {
293
+ fixturePath: i,
294
+ getPath: n((...e) => path.join(i, ...e), "getPath"),
295
+ symlink: n((e, o) => new l(e, o), "symlink")
296
+ };
297
+ await Promise.all(w(s, i, p).map(async (e) => {
298
+ e instanceof f ? await a.mkdir(e.path, { recursive: !0 }) : e instanceof l ? (await a.mkdir(path.dirname(e.path), { recursive: !0 }), await a.symlink(e.target, e.path, e.type)) : e instanceof y && (await a.mkdir(path.dirname(e.path), { recursive: !0 }), await a.writeFile(e.path, e.content));
299
+ }));
300
+ }
301
+ }
302
+ return new P(i);
303
+ }, "createFixture");
304
+ async function isType(fsStatType, statsMethodName, filePath) {
305
+ if (typeof filePath !== "string") throw new TypeError(`Expected a string, got ${typeof filePath}`);
306
+ try {
307
+ return (await a[fsStatType](filePath))[statsMethodName]();
308
+ } catch (error) {
309
+ if (error.code === "ENOENT") return false;
310
+ throw error;
311
+ }
312
+ }
313
+ function isTypeSync(fsStatType, statsMethodName, filePath) {
314
+ if (typeof filePath !== "string") throw new TypeError(`Expected a string, got ${typeof filePath}`);
315
+ try {
316
+ return b[fsStatType](filePath)[statsMethodName]();
317
+ } catch (error) {
318
+ if (error.code === "ENOENT") return false;
319
+ throw error;
320
+ }
321
+ }
322
+ isType.bind(void 0, "stat", "isFile");
323
+ isType.bind(void 0, "stat", "isDirectory");
324
+ isType.bind(void 0, "lstat", "isSymbolicLink");
325
+ isTypeSync.bind(void 0, "statSync", "isFile");
326
+ const isDirectorySync = isTypeSync.bind(void 0, "statSync", "isDirectory");
327
+ isTypeSync.bind(void 0, "lstatSync", "isSymbolicLink");
328
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
329
+ function cleanPath(path$1) {
330
+ let normalized = normalize(path$1);
331
+ if (normalized.length > 1 && normalized[normalized.length - 1] === sep) normalized = normalized.substring(0, normalized.length - 1);
332
+ return normalized;
333
+ }
334
+ const SLASHES_REGEX = /[\\/]/g;
335
+ function convertSlashes(path$1, separator) {
336
+ return path$1.replace(SLASHES_REGEX, separator);
337
+ }
338
+ const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
339
+ function isRootDirectory(path$1) {
340
+ return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1);
341
+ }
342
+ function normalizePath(path$1, options) {
343
+ const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
344
+ const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith(".");
345
+ if (resolvePaths) path$1 = resolve(path$1);
346
+ if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1);
347
+ if (path$1 === ".") return "";
348
+ const needsSeperator = path$1[path$1.length - 1] !== pathSeparator;
349
+ return convertSlashes(needsSeperator ? path$1 + pathSeparator : path$1, pathSeparator);
350
+ }
351
+ function joinPathWithBasePath(filename, directoryPath) {
352
+ return directoryPath + filename;
353
+ }
354
+ function joinPathWithRelativePath(root, options) {
355
+ return function(filename, directoryPath) {
356
+ if (directoryPath.startsWith(root)) return directoryPath.slice(root.length) + filename;
357
+ else return convertSlashes(relative(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
358
+ };
359
+ }
360
+ function joinPath(filename) {
361
+ return filename;
362
+ }
363
+ function joinDirectoryPath(filename, directoryPath, separator) {
364
+ return directoryPath + filename + separator;
365
+ }
366
+ function build$7(root, options) {
367
+ const { relativePaths, includeBasePath } = options;
368
+ return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
369
+ }
370
+ function pushDirectoryWithRelativePath(root) {
371
+ return function(directoryPath, paths) {
372
+ paths.push(directoryPath.substring(root.length) || ".");
373
+ };
374
+ }
375
+ function pushDirectoryFilterWithRelativePath(root) {
376
+ return function(directoryPath, paths, filters) {
377
+ const relativePath = directoryPath.substring(root.length) || ".";
378
+ if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
379
+ };
380
+ }
381
+ const pushDirectory = (directoryPath, paths) => {
382
+ paths.push(directoryPath || ".");
383
+ };
384
+ const pushDirectoryFilter = (directoryPath, paths, filters) => {
385
+ const path$1 = directoryPath || ".";
386
+ if (filters.every((filter) => filter(path$1, true))) paths.push(path$1);
387
+ };
388
+ const empty$2 = () => {};
389
+ function build$6(root, options) {
390
+ const { includeDirs, filters, relativePaths } = options;
391
+ if (!includeDirs) return empty$2;
392
+ if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
393
+ return filters && filters.length ? pushDirectoryFilter : pushDirectory;
394
+ }
395
+ const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
396
+ if (filters.every((filter) => filter(filename, false))) counts.files++;
397
+ };
398
+ const pushFileFilter = (filename, paths, _counts, filters) => {
399
+ if (filters.every((filter) => filter(filename, false))) paths.push(filename);
400
+ };
401
+ const pushFileCount = (_filename, _paths, counts, _filters) => {
402
+ counts.files++;
403
+ };
404
+ const pushFile = (filename, paths) => {
405
+ paths.push(filename);
406
+ };
407
+ const empty$1 = () => {};
408
+ function build$5(options) {
409
+ const { excludeFiles, filters, onlyCounts } = options;
410
+ if (excludeFiles) return empty$1;
411
+ if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
412
+ else if (onlyCounts) return pushFileCount;
413
+ else return pushFile;
414
+ }
415
+ const getArray = (paths) => {
416
+ return paths;
417
+ };
418
+ const getArrayGroup = () => {
419
+ return [""].slice(0, 0);
420
+ };
421
+ function build$4(options) {
422
+ return options.group ? getArrayGroup : getArray;
423
+ }
424
+ const groupFiles = (groups, directory, files) => {
425
+ groups.push({
426
+ directory,
427
+ files,
428
+ dir: directory
429
+ });
430
+ };
431
+ const empty = () => {};
432
+ function build$3(options) {
433
+ return options.group ? groupFiles : empty;
434
+ }
435
+ const resolveSymlinksAsync = function(path$1, state, callback$1) {
436
+ const { queue, fs, options: { suppressErrors } } = state;
437
+ queue.enqueue();
438
+ fs.realpath(path$1, (error, resolvedPath) => {
439
+ if (error) return queue.dequeue(suppressErrors ? null : error, state);
440
+ fs.stat(resolvedPath, (error$1, stat$1) => {
441
+ if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
442
+ if (stat$1.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state);
443
+ callback$1(stat$1, resolvedPath);
444
+ queue.dequeue(null, state);
445
+ });
446
+ });
447
+ };
448
+ const resolveSymlinks = function(path$1, state, callback$1) {
449
+ const { queue, fs, options: { suppressErrors } } = state;
450
+ queue.enqueue();
451
+ try {
452
+ const resolvedPath = fs.realpathSync(path$1);
453
+ const stat$1 = fs.statSync(resolvedPath);
454
+ if (stat$1.isDirectory() && isRecursive(path$1, resolvedPath, state)) return;
455
+ callback$1(stat$1, resolvedPath);
456
+ } catch (e) {
457
+ if (!suppressErrors) throw e;
458
+ }
459
+ };
460
+ function build$2(options, isSynchronous) {
461
+ if (!options.resolveSymlinks || options.excludeSymlinks) return null;
462
+ return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
463
+ }
464
+ function isRecursive(path$1, resolved, state) {
465
+ if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
466
+ let parent = dirname(path$1);
467
+ let depth$1 = 1;
468
+ while (parent !== state.root && depth$1 < 2) {
469
+ const resolvedPath = state.symlinks.get(parent);
470
+ if (!!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath))) depth$1++;
471
+ else parent = dirname(parent);
472
+ }
473
+ state.symlinks.set(path$1, resolved);
474
+ return depth$1 > 1;
475
+ }
476
+ function isRecursiveUsingRealPaths(resolved, state) {
477
+ return state.visited.includes(resolved + state.options.pathSeparator);
478
+ }
479
+ const onlyCountsSync = (state) => {
480
+ return state.counts;
481
+ };
482
+ const groupsSync = (state) => {
483
+ return state.groups;
484
+ };
485
+ const defaultSync = (state) => {
486
+ return state.paths;
487
+ };
488
+ const limitFilesSync = (state) => {
489
+ return state.paths.slice(0, state.options.maxFiles);
490
+ };
491
+ const onlyCountsAsync = (state, error, callback$1) => {
492
+ report(error, callback$1, state.counts, state.options.suppressErrors);
493
+ return null;
494
+ };
495
+ const defaultAsync = (state, error, callback$1) => {
496
+ report(error, callback$1, state.paths, state.options.suppressErrors);
497
+ return null;
498
+ };
499
+ const limitFilesAsync = (state, error, callback$1) => {
500
+ report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
501
+ return null;
502
+ };
503
+ const groupsAsync = (state, error, callback$1) => {
504
+ report(error, callback$1, state.groups, state.options.suppressErrors);
505
+ return null;
506
+ };
507
+ function report(error, callback$1, output, suppressErrors) {
508
+ if (error && !suppressErrors) callback$1(error, output);
509
+ else callback$1(null, output);
510
+ }
511
+ function build$1(options, isSynchronous) {
512
+ const { onlyCounts, group, maxFiles } = options;
513
+ if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
514
+ else if (group) return isSynchronous ? groupsSync : groupsAsync;
515
+ else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
516
+ else return isSynchronous ? defaultSync : defaultAsync;
517
+ }
518
+ const readdirOpts = { withFileTypes: true };
519
+ const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
520
+ state.queue.enqueue();
521
+ if (currentDepth < 0) return state.queue.dequeue(null, state);
522
+ const { fs } = state;
523
+ state.visited.push(crawlPath);
524
+ state.counts.directories++;
525
+ fs.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
526
+ callback$1(entries, directoryPath, currentDepth);
527
+ state.queue.dequeue(state.options.suppressErrors ? null : error, state);
528
+ });
529
+ };
530
+ const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
531
+ const { fs } = state;
532
+ if (currentDepth < 0) return;
533
+ state.visited.push(crawlPath);
534
+ state.counts.directories++;
535
+ let entries = [];
536
+ try {
537
+ entries = fs.readdirSync(crawlPath || ".", readdirOpts);
538
+ } catch (e) {
539
+ if (!state.options.suppressErrors) throw e;
540
+ }
541
+ callback$1(entries, directoryPath, currentDepth);
542
+ };
543
+ function build(isSynchronous) {
544
+ return isSynchronous ? walkSync : walkAsync;
545
+ }
546
+ var Queue = class {
547
+ count = 0;
548
+ constructor(onQueueEmpty) {
549
+ this.onQueueEmpty = onQueueEmpty;
550
+ }
551
+ enqueue() {
552
+ this.count++;
553
+ return this.count;
554
+ }
555
+ dequeue(error, output) {
556
+ if (this.onQueueEmpty && (--this.count <= 0 || error)) {
557
+ this.onQueueEmpty(error, output);
558
+ if (error) {
559
+ output.controller.abort();
560
+ this.onQueueEmpty = void 0;
561
+ }
562
+ }
563
+ }
564
+ };
565
+ var Counter = class {
566
+ _files = 0;
567
+ _directories = 0;
568
+ set files(num) {
569
+ this._files = num;
570
+ }
571
+ get files() {
572
+ return this._files;
573
+ }
574
+ set directories(num) {
575
+ this._directories = num;
576
+ }
577
+ get directories() {
578
+ return this._directories;
579
+ }
580
+ /* c8 ignore next 3 */
581
+ get dirs() {
582
+ return this._directories;
583
+ }
584
+ };
585
+ var Aborter = class {
586
+ aborted = false;
587
+ abort() {
588
+ this.aborted = true;
589
+ }
590
+ };
591
+ var Walker = class {
592
+ root;
593
+ isSynchronous;
594
+ state;
595
+ joinPath;
596
+ pushDirectory;
597
+ pushFile;
598
+ getArray;
599
+ groupFiles;
600
+ resolveSymlink;
601
+ walkDirectory;
602
+ callbackInvoker;
603
+ constructor(root, options, callback$1) {
604
+ this.isSynchronous = !callback$1;
605
+ this.callbackInvoker = build$1(options, this.isSynchronous);
606
+ this.root = normalizePath(root, options);
607
+ this.state = {
608
+ root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
609
+ paths: [""].slice(0, 0),
610
+ groups: [],
611
+ counts: new Counter(),
612
+ options,
613
+ queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
614
+ symlinks: /* @__PURE__ */ new Map(),
615
+ visited: [""].slice(0, 0),
616
+ controller: new Aborter(),
617
+ fs: options.fs || nativeFs
618
+ };
619
+ this.joinPath = build$7(this.root, options);
620
+ this.pushDirectory = build$6(this.root, options);
621
+ this.pushFile = build$5(options);
622
+ this.getArray = build$4(options);
623
+ this.groupFiles = build$3(options);
624
+ this.resolveSymlink = build$2(options, this.isSynchronous);
625
+ this.walkDirectory = build(this.isSynchronous);
626
+ }
627
+ start() {
628
+ this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
629
+ this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
630
+ return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
631
+ }
632
+ walk = (entries, directoryPath, depth$1) => {
633
+ const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
634
+ if (controller.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
635
+ const files = this.getArray(this.state.paths);
636
+ for (let i = 0; i < entries.length; ++i) {
637
+ const entry = entries[i];
638
+ if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
639
+ const filename = this.joinPath(entry.name, directoryPath);
640
+ this.pushFile(filename, files, this.state.counts, filters);
641
+ } else if (entry.isDirectory()) {
642
+ let path$1 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
643
+ if (exclude && exclude(entry.name, path$1)) continue;
644
+ this.pushDirectory(path$1, paths, filters);
645
+ this.walkDirectory(this.state, path$1, path$1, depth$1 - 1, this.walk);
646
+ } else if (this.resolveSymlink && entry.isSymbolicLink()) {
647
+ let path$1 = joinPathWithBasePath(entry.name, directoryPath);
648
+ this.resolveSymlink(path$1, this.state, (stat$1, resolvedPath) => {
649
+ if (stat$1.isDirectory()) {
650
+ resolvedPath = normalizePath(resolvedPath, this.state.options);
651
+ if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return;
652
+ this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth$1 - 1, this.walk);
653
+ } else {
654
+ resolvedPath = useRealPaths ? resolvedPath : path$1;
655
+ const filename = basename(resolvedPath);
656
+ const directoryPath$1 = normalizePath(dirname(resolvedPath), this.state.options);
657
+ resolvedPath = this.joinPath(filename, directoryPath$1);
658
+ this.pushFile(resolvedPath, files, this.state.counts, filters);
659
+ }
660
+ });
661
+ }
662
+ }
663
+ this.groupFiles(this.state.groups, directoryPath, files);
664
+ };
665
+ };
666
+ function promise(root, options) {
667
+ return new Promise((resolve$1, reject) => {
668
+ callback(root, options, (err, output) => {
669
+ if (err) return reject(err);
670
+ resolve$1(output);
671
+ });
672
+ });
673
+ }
674
+ function callback(root, options, callback$1) {
675
+ new Walker(root, options, callback$1).start();
676
+ }
677
+ function sync(root, options) {
678
+ return new Walker(root, options).start();
679
+ }
680
+ var APIBuilder = class {
681
+ constructor(root, options) {
682
+ this.root = root;
683
+ this.options = options;
684
+ }
685
+ withPromise() {
686
+ return promise(this.root, this.options);
687
+ }
688
+ withCallback(cb) {
689
+ callback(this.root, this.options, cb);
690
+ }
691
+ sync() {
692
+ return sync(this.root, this.options);
693
+ }
694
+ };
695
+ let pm = null;
696
+ /* c8 ignore next 6 */
697
+ try {
698
+ __require.resolve("picomatch");
699
+ pm = __require("picomatch");
700
+ } catch {}
701
+ var Builder = class {
702
+ globCache = {};
703
+ options = {
704
+ maxDepth: Infinity,
705
+ suppressErrors: true,
706
+ pathSeparator: sep,
707
+ filters: []
708
+ };
709
+ globFunction;
710
+ constructor(options) {
711
+ this.options = {
712
+ ...this.options,
713
+ ...options
714
+ };
715
+ this.globFunction = this.options.globFunction;
716
+ }
717
+ group() {
718
+ this.options.group = true;
719
+ return this;
720
+ }
721
+ withPathSeparator(separator) {
722
+ this.options.pathSeparator = separator;
723
+ return this;
724
+ }
725
+ withBasePath() {
726
+ this.options.includeBasePath = true;
727
+ return this;
728
+ }
729
+ withRelativePaths() {
730
+ this.options.relativePaths = true;
731
+ return this;
732
+ }
733
+ withDirs() {
734
+ this.options.includeDirs = true;
735
+ return this;
736
+ }
737
+ withMaxDepth(depth$1) {
738
+ this.options.maxDepth = depth$1;
739
+ return this;
740
+ }
741
+ withMaxFiles(limit) {
742
+ this.options.maxFiles = limit;
743
+ return this;
744
+ }
745
+ withFullPaths() {
746
+ this.options.resolvePaths = true;
747
+ this.options.includeBasePath = true;
748
+ return this;
749
+ }
750
+ withErrors() {
751
+ this.options.suppressErrors = false;
752
+ return this;
753
+ }
754
+ withSymlinks({ resolvePaths = true } = {}) {
755
+ this.options.resolveSymlinks = true;
756
+ this.options.useRealPaths = resolvePaths;
757
+ return this.withFullPaths();
758
+ }
759
+ withAbortSignal(signal) {
760
+ this.options.signal = signal;
761
+ return this;
762
+ }
763
+ normalize() {
764
+ this.options.normalizePath = true;
765
+ return this;
766
+ }
767
+ filter(predicate) {
768
+ this.options.filters.push(predicate);
769
+ return this;
770
+ }
771
+ onlyDirs() {
772
+ this.options.excludeFiles = true;
773
+ this.options.includeDirs = true;
774
+ return this;
775
+ }
776
+ exclude(predicate) {
777
+ this.options.exclude = predicate;
778
+ return this;
779
+ }
780
+ onlyCounts() {
781
+ this.options.onlyCounts = true;
782
+ return this;
783
+ }
784
+ crawl(root) {
785
+ return new APIBuilder(root || ".", this.options);
786
+ }
787
+ withGlobFunction(fn) {
788
+ this.globFunction = fn;
789
+ return this;
790
+ }
791
+ /* c8 ignore next 4 */
792
+ crawlWithOptions(root, options) {
793
+ this.options = {
794
+ ...this.options,
795
+ ...options
796
+ };
797
+ return new APIBuilder(root || ".", this.options);
798
+ }
799
+ glob(...patterns) {
800
+ if (this.globFunction) return this.globWithOptions(patterns);
801
+ return this.globWithOptions(patterns, ...[{ dot: true }]);
802
+ }
803
+ globWithOptions(patterns, ...options) {
804
+ const globFn = this.globFunction || pm;
805
+ /* c8 ignore next 5 */
806
+ if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
807
+ var isMatch = this.globCache[patterns.join("\0")];
808
+ if (!isMatch) {
809
+ isMatch = globFn(patterns, ...options);
810
+ this.globCache[patterns.join("\0")] = isMatch;
811
+ }
812
+ this.options.filters.push((path$1) => isMatch(path$1));
813
+ return this;
814
+ }
815
+ };
816
+ var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
817
+ const WIN_SLASH = "\\\\/";
818
+ const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
819
+ const DOT_LITERAL = "\\.";
820
+ const PLUS_LITERAL = "\\+";
821
+ const QMARK_LITERAL = "\\?";
822
+ const SLASH_LITERAL = "\\/";
823
+ const ONE_CHAR = "(?=.)";
824
+ const QMARK = "[^/]";
825
+ const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
826
+ const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
827
+ const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
828
+ const NO_DOT = `(?!${DOT_LITERAL})`;
829
+ const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
830
+ const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
831
+ const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
832
+ const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
833
+ const STAR = `${QMARK}*?`;
834
+ const POSIX_CHARS = {
835
+ DOT_LITERAL,
836
+ PLUS_LITERAL,
837
+ QMARK_LITERAL,
838
+ SLASH_LITERAL,
839
+ ONE_CHAR,
840
+ QMARK,
841
+ END_ANCHOR,
842
+ DOTS_SLASH,
843
+ NO_DOT,
844
+ NO_DOTS,
845
+ NO_DOT_SLASH,
846
+ NO_DOTS_SLASH,
847
+ QMARK_NO_DOT,
848
+ STAR,
849
+ START_ANCHOR,
850
+ SEP: "/"
851
+ };
852
+ const WINDOWS_CHARS = {
853
+ ...POSIX_CHARS,
854
+ SLASH_LITERAL: `[${WIN_SLASH}]`,
855
+ QMARK: WIN_NO_SLASH,
856
+ STAR: `${WIN_NO_SLASH}*?`,
857
+ DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
858
+ NO_DOT: `(?!${DOT_LITERAL})`,
859
+ NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
860
+ NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
861
+ NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
862
+ QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
863
+ START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
864
+ END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
865
+ SEP: "\\"
866
+ };
867
+ module.exports = {
868
+ MAX_LENGTH: 1024 * 64,
869
+ POSIX_REGEX_SOURCE: {
870
+ alnum: "a-zA-Z0-9",
871
+ alpha: "a-zA-Z",
872
+ ascii: "\\x00-\\x7F",
873
+ blank: " \\t",
874
+ cntrl: "\\x00-\\x1F\\x7F",
875
+ digit: "0-9",
876
+ graph: "\\x21-\\x7E",
877
+ lower: "a-z",
878
+ print: "\\x20-\\x7E ",
879
+ punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
880
+ space: " \\t\\r\\n\\v\\f",
881
+ upper: "A-Z",
882
+ word: "A-Za-z0-9_",
883
+ xdigit: "A-Fa-f0-9"
884
+ },
885
+ REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
886
+ REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
887
+ REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
888
+ REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
889
+ REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
890
+ REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
891
+ REPLACEMENTS: {
892
+ __proto__: null,
893
+ "***": "*",
894
+ "**/**": "**",
895
+ "**/**/**": "**"
896
+ },
897
+ CHAR_0: 48,
898
+ CHAR_9: 57,
899
+ CHAR_UPPERCASE_A: 65,
900
+ CHAR_LOWERCASE_A: 97,
901
+ CHAR_UPPERCASE_Z: 90,
902
+ CHAR_LOWERCASE_Z: 122,
903
+ CHAR_LEFT_PARENTHESES: 40,
904
+ CHAR_RIGHT_PARENTHESES: 41,
905
+ CHAR_ASTERISK: 42,
906
+ CHAR_AMPERSAND: 38,
907
+ CHAR_AT: 64,
908
+ CHAR_BACKWARD_SLASH: 92,
909
+ CHAR_CARRIAGE_RETURN: 13,
910
+ CHAR_CIRCUMFLEX_ACCENT: 94,
911
+ CHAR_COLON: 58,
912
+ CHAR_COMMA: 44,
913
+ CHAR_DOT: 46,
914
+ CHAR_DOUBLE_QUOTE: 34,
915
+ CHAR_EQUAL: 61,
916
+ CHAR_EXCLAMATION_MARK: 33,
917
+ CHAR_FORM_FEED: 12,
918
+ CHAR_FORWARD_SLASH: 47,
919
+ CHAR_GRAVE_ACCENT: 96,
920
+ CHAR_HASH: 35,
921
+ CHAR_HYPHEN_MINUS: 45,
922
+ CHAR_LEFT_ANGLE_BRACKET: 60,
923
+ CHAR_LEFT_CURLY_BRACE: 123,
924
+ CHAR_LEFT_SQUARE_BRACKET: 91,
925
+ CHAR_LINE_FEED: 10,
926
+ CHAR_NO_BREAK_SPACE: 160,
927
+ CHAR_PERCENT: 37,
928
+ CHAR_PLUS: 43,
929
+ CHAR_QUESTION_MARK: 63,
930
+ CHAR_RIGHT_ANGLE_BRACKET: 62,
931
+ CHAR_RIGHT_CURLY_BRACE: 125,
932
+ CHAR_RIGHT_SQUARE_BRACKET: 93,
933
+ CHAR_SEMICOLON: 59,
934
+ CHAR_SINGLE_QUOTE: 39,
935
+ CHAR_SPACE: 32,
936
+ CHAR_TAB: 9,
937
+ CHAR_UNDERSCORE: 95,
938
+ CHAR_VERTICAL_LINE: 124,
939
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
940
+ extglobChars(chars) {
941
+ return {
942
+ "!": {
943
+ type: "negate",
944
+ open: "(?:(?!(?:",
945
+ close: `))${chars.STAR})`
946
+ },
947
+ "?": {
948
+ type: "qmark",
949
+ open: "(?:",
950
+ close: ")?"
951
+ },
952
+ "+": {
953
+ type: "plus",
954
+ open: "(?:",
955
+ close: ")+"
956
+ },
957
+ "*": {
958
+ type: "star",
959
+ open: "(?:",
960
+ close: ")*"
961
+ },
962
+ "@": {
963
+ type: "at",
964
+ open: "(?:",
965
+ close: ")"
966
+ }
967
+ };
968
+ },
969
+ globChars(win32) {
970
+ return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
971
+ }
972
+ };
973
+ }));
974
+ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
975
+ const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
976
+ exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val);
977
+ exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str);
978
+ exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str);
979
+ exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1");
980
+ exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/");
981
+ exports.isWindows = () => {
982
+ if (typeof navigator !== "undefined" && navigator.platform) {
983
+ const platform = navigator.platform.toLowerCase();
984
+ return platform === "win32" || platform === "windows";
985
+ }
986
+ if (typeof process !== "undefined" && process.platform) return process.platform === "win32";
987
+ return false;
988
+ };
989
+ exports.removeBackslashes = (str) => {
990
+ return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
991
+ return match === "\\" ? "" : match;
992
+ });
993
+ };
994
+ exports.escapeLast = (input, char, lastIdx) => {
995
+ const idx = input.lastIndexOf(char, lastIdx);
996
+ if (idx === -1) return input;
997
+ if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
998
+ return `${input.slice(0, idx)}\\${input.slice(idx)}`;
999
+ };
1000
+ exports.removePrefix = (input, state = {}) => {
1001
+ let output = input;
1002
+ if (output.startsWith("./")) {
1003
+ output = output.slice(2);
1004
+ state.prefix = "./";
1005
+ }
1006
+ return output;
1007
+ };
1008
+ exports.wrapOutput = (input, state = {}, options = {}) => {
1009
+ const prepend = options.contains ? "" : "^";
1010
+ const append = options.contains ? "" : "$";
1011
+ let output = `${prepend}(?:${input})${append}`;
1012
+ if (state.negated === true) output = `(?:^(?!${output}).*$)`;
1013
+ return output;
1014
+ };
1015
+ exports.basename = (path$1, { windows } = {}) => {
1016
+ const segs = path$1.split(windows ? /[\\/]/ : "/");
1017
+ const last = segs[segs.length - 1];
1018
+ if (last === "") return segs[segs.length - 2];
1019
+ return last;
1020
+ };
1021
+ }));
1022
+ var require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1023
+ const utils$3 = require_utils();
1024
+ const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
1025
+ const isPathSeparator = (code) => {
1026
+ return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
1027
+ };
1028
+ const depth = (token) => {
1029
+ if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1;
1030
+ };
1031
+ const scan$1 = (input, options) => {
1032
+ const opts = options || {};
1033
+ const length = input.length - 1;
1034
+ const scanToEnd = opts.parts === true || opts.scanToEnd === true;
1035
+ const slashes = [];
1036
+ const tokens = [];
1037
+ const parts = [];
1038
+ let str = input;
1039
+ let index = -1;
1040
+ let start = 0;
1041
+ let lastIndex = 0;
1042
+ let isBrace = false;
1043
+ let isBracket = false;
1044
+ let isGlob = false;
1045
+ let isExtglob = false;
1046
+ let isGlobstar = false;
1047
+ let braceEscaped = false;
1048
+ let backslashes = false;
1049
+ let negated = false;
1050
+ let negatedExtglob = false;
1051
+ let finished = false;
1052
+ let braces = 0;
1053
+ let prev;
1054
+ let code;
1055
+ let token = {
1056
+ value: "",
1057
+ depth: 0,
1058
+ isGlob: false
1059
+ };
1060
+ const eos = () => index >= length;
1061
+ const peek = () => str.charCodeAt(index + 1);
1062
+ const advance = () => {
1063
+ prev = code;
1064
+ return str.charCodeAt(++index);
1065
+ };
1066
+ while (index < length) {
1067
+ code = advance();
1068
+ let next;
1069
+ if (code === CHAR_BACKWARD_SLASH) {
1070
+ backslashes = token.backslashes = true;
1071
+ code = advance();
1072
+ if (code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true;
1073
+ continue;
1074
+ }
1075
+ if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
1076
+ braces++;
1077
+ while (eos() !== true && (code = advance())) {
1078
+ if (code === CHAR_BACKWARD_SLASH) {
1079
+ backslashes = token.backslashes = true;
1080
+ advance();
1081
+ continue;
1082
+ }
1083
+ if (code === CHAR_LEFT_CURLY_BRACE) {
1084
+ braces++;
1085
+ continue;
1086
+ }
1087
+ if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
1088
+ isBrace = token.isBrace = true;
1089
+ isGlob = token.isGlob = true;
1090
+ finished = true;
1091
+ if (scanToEnd === true) continue;
1092
+ break;
1093
+ }
1094
+ if (braceEscaped !== true && code === CHAR_COMMA) {
1095
+ isBrace = token.isBrace = true;
1096
+ isGlob = token.isGlob = true;
1097
+ finished = true;
1098
+ if (scanToEnd === true) continue;
1099
+ break;
1100
+ }
1101
+ if (code === CHAR_RIGHT_CURLY_BRACE) {
1102
+ braces--;
1103
+ if (braces === 0) {
1104
+ braceEscaped = false;
1105
+ isBrace = token.isBrace = true;
1106
+ finished = true;
1107
+ break;
1108
+ }
1109
+ }
1110
+ }
1111
+ if (scanToEnd === true) continue;
1112
+ break;
1113
+ }
1114
+ if (code === CHAR_FORWARD_SLASH) {
1115
+ slashes.push(index);
1116
+ tokens.push(token);
1117
+ token = {
1118
+ value: "",
1119
+ depth: 0,
1120
+ isGlob: false
1121
+ };
1122
+ if (finished === true) continue;
1123
+ if (prev === CHAR_DOT && index === start + 1) {
1124
+ start += 2;
1125
+ continue;
1126
+ }
1127
+ lastIndex = index + 1;
1128
+ continue;
1129
+ }
1130
+ if (opts.noext !== true) {
1131
+ if ((code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK) === true && peek() === CHAR_LEFT_PARENTHESES) {
1132
+ isGlob = token.isGlob = true;
1133
+ isExtglob = token.isExtglob = true;
1134
+ finished = true;
1135
+ if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true;
1136
+ if (scanToEnd === true) {
1137
+ while (eos() !== true && (code = advance())) {
1138
+ if (code === CHAR_BACKWARD_SLASH) {
1139
+ backslashes = token.backslashes = true;
1140
+ code = advance();
1141
+ continue;
1142
+ }
1143
+ if (code === CHAR_RIGHT_PARENTHESES) {
1144
+ isGlob = token.isGlob = true;
1145
+ finished = true;
1146
+ break;
1147
+ }
1148
+ }
1149
+ continue;
1150
+ }
1151
+ break;
1152
+ }
1153
+ }
1154
+ if (code === CHAR_ASTERISK) {
1155
+ if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
1156
+ isGlob = token.isGlob = true;
1157
+ finished = true;
1158
+ if (scanToEnd === true) continue;
1159
+ break;
1160
+ }
1161
+ if (code === CHAR_QUESTION_MARK) {
1162
+ isGlob = token.isGlob = true;
1163
+ finished = true;
1164
+ if (scanToEnd === true) continue;
1165
+ break;
1166
+ }
1167
+ if (code === CHAR_LEFT_SQUARE_BRACKET) {
1168
+ while (eos() !== true && (next = advance())) {
1169
+ if (next === CHAR_BACKWARD_SLASH) {
1170
+ backslashes = token.backslashes = true;
1171
+ advance();
1172
+ continue;
1173
+ }
1174
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
1175
+ isBracket = token.isBracket = true;
1176
+ isGlob = token.isGlob = true;
1177
+ finished = true;
1178
+ break;
1179
+ }
1180
+ }
1181
+ if (scanToEnd === true) continue;
1182
+ break;
1183
+ }
1184
+ if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
1185
+ negated = token.negated = true;
1186
+ start++;
1187
+ continue;
1188
+ }
1189
+ if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
1190
+ isGlob = token.isGlob = true;
1191
+ if (scanToEnd === true) {
1192
+ while (eos() !== true && (code = advance())) {
1193
+ if (code === CHAR_LEFT_PARENTHESES) {
1194
+ backslashes = token.backslashes = true;
1195
+ code = advance();
1196
+ continue;
1197
+ }
1198
+ if (code === CHAR_RIGHT_PARENTHESES) {
1199
+ finished = true;
1200
+ break;
1201
+ }
1202
+ }
1203
+ continue;
1204
+ }
1205
+ break;
1206
+ }
1207
+ if (isGlob === true) {
1208
+ finished = true;
1209
+ if (scanToEnd === true) continue;
1210
+ break;
1211
+ }
1212
+ }
1213
+ if (opts.noext === true) {
1214
+ isExtglob = false;
1215
+ isGlob = false;
1216
+ }
1217
+ let base = str;
1218
+ let prefix = "";
1219
+ let glob$1 = "";
1220
+ if (start > 0) {
1221
+ prefix = str.slice(0, start);
1222
+ str = str.slice(start);
1223
+ lastIndex -= start;
1224
+ }
1225
+ if (base && isGlob === true && lastIndex > 0) {
1226
+ base = str.slice(0, lastIndex);
1227
+ glob$1 = str.slice(lastIndex);
1228
+ } else if (isGlob === true) {
1229
+ base = "";
1230
+ glob$1 = str;
1231
+ } else base = str;
1232
+ if (base && base !== "" && base !== "/" && base !== str) {
1233
+ if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1);
1234
+ }
1235
+ if (opts.unescape === true) {
1236
+ if (glob$1) glob$1 = utils$3.removeBackslashes(glob$1);
1237
+ if (base && backslashes === true) base = utils$3.removeBackslashes(base);
1238
+ }
1239
+ const state = {
1240
+ prefix,
1241
+ input,
1242
+ start,
1243
+ base,
1244
+ glob: glob$1,
1245
+ isBrace,
1246
+ isBracket,
1247
+ isGlob,
1248
+ isExtglob,
1249
+ isGlobstar,
1250
+ negated,
1251
+ negatedExtglob
1252
+ };
1253
+ if (opts.tokens === true) {
1254
+ state.maxDepth = 0;
1255
+ if (!isPathSeparator(code)) tokens.push(token);
1256
+ state.tokens = tokens;
1257
+ }
1258
+ if (opts.parts === true || opts.tokens === true) {
1259
+ let prevIndex;
1260
+ for (let idx = 0; idx < slashes.length; idx++) {
1261
+ const n$1 = prevIndex ? prevIndex + 1 : start;
1262
+ const i = slashes[idx];
1263
+ const value = input.slice(n$1, i);
1264
+ if (opts.tokens) {
1265
+ if (idx === 0 && start !== 0) {
1266
+ tokens[idx].isPrefix = true;
1267
+ tokens[idx].value = prefix;
1268
+ } else tokens[idx].value = value;
1269
+ depth(tokens[idx]);
1270
+ state.maxDepth += tokens[idx].depth;
1271
+ }
1272
+ if (idx !== 0 || value !== "") parts.push(value);
1273
+ prevIndex = i;
1274
+ }
1275
+ if (prevIndex && prevIndex + 1 < input.length) {
1276
+ const value = input.slice(prevIndex + 1);
1277
+ parts.push(value);
1278
+ if (opts.tokens) {
1279
+ tokens[tokens.length - 1].value = value;
1280
+ depth(tokens[tokens.length - 1]);
1281
+ state.maxDepth += tokens[tokens.length - 1].depth;
1282
+ }
1283
+ }
1284
+ state.slashes = slashes;
1285
+ state.parts = parts;
1286
+ }
1287
+ return state;
1288
+ };
1289
+ module.exports = scan$1;
1290
+ }));
1291
+ var require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1292
+ const constants$1 = require_constants();
1293
+ const utils$2 = require_utils();
1294
+ const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
1295
+ const expandRange = (args, options) => {
1296
+ if (typeof options.expandRange === "function") return options.expandRange(...args, options);
1297
+ args.sort();
1298
+ const value = `[${args.join("-")}]`;
1299
+ try {
1300
+ new RegExp(value);
1301
+ } catch (ex) {
1302
+ return args.map((v$1) => utils$2.escapeRegex(v$1)).join("..");
1303
+ }
1304
+ return value;
1305
+ };
1306
+ const syntaxError = (type, char) => {
1307
+ return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
1308
+ };
1309
+ const parse$1 = (input, options) => {
1310
+ if (typeof input !== "string") throw new TypeError("Expected a string");
1311
+ input = REPLACEMENTS[input] || input;
1312
+ const opts = { ...options };
1313
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1314
+ let len = input.length;
1315
+ if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1316
+ const bos = {
1317
+ type: "bos",
1318
+ value: "",
1319
+ output: opts.prepend || ""
1320
+ };
1321
+ const tokens = [bos];
1322
+ const capture = opts.capture ? "" : "?:";
1323
+ const PLATFORM_CHARS = constants$1.globChars(opts.windows);
1324
+ const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
1325
+ const { DOT_LITERAL: DOT_LITERAL$1, PLUS_LITERAL: PLUS_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT: NO_DOT$1, NO_DOT_SLASH: NO_DOT_SLASH$1, NO_DOTS_SLASH: NO_DOTS_SLASH$1, QMARK: QMARK$1, QMARK_NO_DOT: QMARK_NO_DOT$1, STAR: STAR$1, START_ANCHOR: START_ANCHOR$1 } = PLATFORM_CHARS;
1326
+ const globstar = (opts$1) => {
1327
+ return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
1328
+ };
1329
+ const nodot = opts.dot ? "" : NO_DOT$1;
1330
+ const qmarkNoDot = opts.dot ? QMARK$1 : QMARK_NO_DOT$1;
1331
+ let star = opts.bash === true ? globstar(opts) : STAR$1;
1332
+ if (opts.capture) star = `(${star})`;
1333
+ if (typeof opts.noext === "boolean") opts.noextglob = opts.noext;
1334
+ const state = {
1335
+ input,
1336
+ index: -1,
1337
+ start: 0,
1338
+ dot: opts.dot === true,
1339
+ consumed: "",
1340
+ output: "",
1341
+ prefix: "",
1342
+ backtrack: false,
1343
+ negated: false,
1344
+ brackets: 0,
1345
+ braces: 0,
1346
+ parens: 0,
1347
+ quotes: 0,
1348
+ globstar: false,
1349
+ tokens
1350
+ };
1351
+ input = utils$2.removePrefix(input, state);
1352
+ len = input.length;
1353
+ const extglobs = [];
1354
+ const braces = [];
1355
+ const stack = [];
1356
+ let prev = bos;
1357
+ let value;
1358
+ const eos = () => state.index === len - 1;
1359
+ const peek = state.peek = (n$1 = 1) => input[state.index + n$1];
1360
+ const advance = state.advance = () => input[++state.index] || "";
1361
+ const remaining = () => input.slice(state.index + 1);
1362
+ const consume = (value$1 = "", num = 0) => {
1363
+ state.consumed += value$1;
1364
+ state.index += num;
1365
+ };
1366
+ const append = (token) => {
1367
+ state.output += token.output != null ? token.output : token.value;
1368
+ consume(token.value);
1369
+ };
1370
+ const negate = () => {
1371
+ let count = 1;
1372
+ while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) {
1373
+ advance();
1374
+ state.start++;
1375
+ count++;
1376
+ }
1377
+ if (count % 2 === 0) return false;
1378
+ state.negated = true;
1379
+ state.start++;
1380
+ return true;
1381
+ };
1382
+ const increment = (type) => {
1383
+ state[type]++;
1384
+ stack.push(type);
1385
+ };
1386
+ const decrement = (type) => {
1387
+ state[type]--;
1388
+ stack.pop();
1389
+ };
1390
+ const push = (tok) => {
1391
+ if (prev.type === "globstar") {
1392
+ const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace");
1393
+ const isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
1394
+ if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) {
1395
+ state.output = state.output.slice(0, -prev.output.length);
1396
+ prev.type = "star";
1397
+ prev.value = "*";
1398
+ prev.output = star;
1399
+ state.output += prev.output;
1400
+ }
1401
+ }
1402
+ if (extglobs.length && tok.type !== "paren") extglobs[extglobs.length - 1].inner += tok.value;
1403
+ if (tok.value || tok.output) append(tok);
1404
+ if (prev && prev.type === "text" && tok.type === "text") {
1405
+ prev.output = (prev.output || prev.value) + tok.value;
1406
+ prev.value += tok.value;
1407
+ return;
1408
+ }
1409
+ tok.prev = prev;
1410
+ tokens.push(tok);
1411
+ prev = tok;
1412
+ };
1413
+ const extglobOpen = (type, value$1) => {
1414
+ const token = {
1415
+ ...EXTGLOB_CHARS[value$1],
1416
+ conditions: 1,
1417
+ inner: ""
1418
+ };
1419
+ token.prev = prev;
1420
+ token.parens = state.parens;
1421
+ token.output = state.output;
1422
+ const output = (opts.capture ? "(" : "") + token.open;
1423
+ increment("parens");
1424
+ push({
1425
+ type,
1426
+ value: value$1,
1427
+ output: state.output ? "" : ONE_CHAR$1
1428
+ });
1429
+ push({
1430
+ type: "paren",
1431
+ extglob: true,
1432
+ value: advance(),
1433
+ output
1434
+ });
1435
+ extglobs.push(token);
1436
+ };
1437
+ const extglobClose = (token) => {
1438
+ let output = token.close + (opts.capture ? ")" : "");
1439
+ let rest;
1440
+ if (token.type === "negate") {
1441
+ let extglobStar = star;
1442
+ if (token.inner && token.inner.length > 1 && token.inner.includes("/")) extglobStar = globstar(opts);
1443
+ if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) output = token.close = `)$))${extglobStar}`;
1444
+ if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) output = token.close = `)${parse$1(rest, {
1445
+ ...options,
1446
+ fastpaths: false
1447
+ }).output})${extglobStar})`;
1448
+ if (token.prev.type === "bos") state.negatedExtglob = true;
1449
+ }
1450
+ push({
1451
+ type: "paren",
1452
+ extglob: true,
1453
+ value,
1454
+ output
1455
+ });
1456
+ decrement("parens");
1457
+ };
1458
+ if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
1459
+ let backslashes = false;
1460
+ let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m$1, esc, chars, first, rest, index) => {
1461
+ if (first === "\\") {
1462
+ backslashes = true;
1463
+ return m$1;
1464
+ }
1465
+ if (first === "?") {
1466
+ if (esc) return esc + first + (rest ? QMARK$1.repeat(rest.length) : "");
1467
+ if (index === 0) return qmarkNoDot + (rest ? QMARK$1.repeat(rest.length) : "");
1468
+ return QMARK$1.repeat(chars.length);
1469
+ }
1470
+ if (first === ".") return DOT_LITERAL$1.repeat(chars.length);
1471
+ if (first === "*") {
1472
+ if (esc) return esc + first + (rest ? star : "");
1473
+ return star;
1474
+ }
1475
+ return esc ? m$1 : `\\${m$1}`;
1476
+ });
1477
+ if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, "");
1478
+ else output = output.replace(/\\+/g, (m$1) => {
1479
+ return m$1.length % 2 === 0 ? "\\\\" : m$1 ? "\\" : "";
1480
+ });
1481
+ if (output === input && opts.contains === true) {
1482
+ state.output = input;
1483
+ return state;
1484
+ }
1485
+ state.output = utils$2.wrapOutput(output, state, options);
1486
+ return state;
1487
+ }
1488
+ while (!eos()) {
1489
+ value = advance();
1490
+ if (value === "\0") continue;
1491
+ if (value === "\\") {
1492
+ const next = peek();
1493
+ if (next === "/" && opts.bash !== true) continue;
1494
+ if (next === "." || next === ";") continue;
1495
+ if (!next) {
1496
+ value += "\\";
1497
+ push({
1498
+ type: "text",
1499
+ value
1500
+ });
1501
+ continue;
1502
+ }
1503
+ const match = /^\\+/.exec(remaining());
1504
+ let slashes = 0;
1505
+ if (match && match[0].length > 2) {
1506
+ slashes = match[0].length;
1507
+ state.index += slashes;
1508
+ if (slashes % 2 !== 0) value += "\\";
1509
+ }
1510
+ if (opts.unescape === true) value = advance();
1511
+ else value += advance();
1512
+ if (state.brackets === 0) {
1513
+ push({
1514
+ type: "text",
1515
+ value
1516
+ });
1517
+ continue;
1518
+ }
1519
+ }
1520
+ if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
1521
+ if (opts.posix !== false && value === ":") {
1522
+ const inner = prev.value.slice(1);
1523
+ if (inner.includes("[")) {
1524
+ prev.posix = true;
1525
+ if (inner.includes(":")) {
1526
+ const idx = prev.value.lastIndexOf("[");
1527
+ const pre = prev.value.slice(0, idx);
1528
+ const rest$1 = prev.value.slice(idx + 2);
1529
+ const posix$1 = POSIX_REGEX_SOURCE[rest$1];
1530
+ if (posix$1) {
1531
+ prev.value = pre + posix$1;
1532
+ state.backtrack = true;
1533
+ advance();
1534
+ if (!bos.output && tokens.indexOf(prev) === 1) bos.output = ONE_CHAR$1;
1535
+ continue;
1536
+ }
1537
+ }
1538
+ }
1539
+ }
1540
+ if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") value = `\\${value}`;
1541
+ if (value === "]" && (prev.value === "[" || prev.value === "[^")) value = `\\${value}`;
1542
+ if (opts.posix === true && value === "!" && prev.value === "[") value = "^";
1543
+ prev.value += value;
1544
+ append({ value });
1545
+ continue;
1546
+ }
1547
+ if (state.quotes === 1 && value !== "\"") {
1548
+ value = utils$2.escapeRegex(value);
1549
+ prev.value += value;
1550
+ append({ value });
1551
+ continue;
1552
+ }
1553
+ if (value === "\"") {
1554
+ state.quotes = state.quotes === 1 ? 0 : 1;
1555
+ if (opts.keepQuotes === true) push({
1556
+ type: "text",
1557
+ value
1558
+ });
1559
+ continue;
1560
+ }
1561
+ if (value === "(") {
1562
+ increment("parens");
1563
+ push({
1564
+ type: "paren",
1565
+ value
1566
+ });
1567
+ continue;
1568
+ }
1569
+ if (value === ")") {
1570
+ if (state.parens === 0 && opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "("));
1571
+ const extglob = extglobs[extglobs.length - 1];
1572
+ if (extglob && state.parens === extglob.parens + 1) {
1573
+ extglobClose(extglobs.pop());
1574
+ continue;
1575
+ }
1576
+ push({
1577
+ type: "paren",
1578
+ value,
1579
+ output: state.parens ? ")" : "\\)"
1580
+ });
1581
+ decrement("parens");
1582
+ continue;
1583
+ }
1584
+ if (value === "[") {
1585
+ if (opts.nobracket === true || !remaining().includes("]")) {
1586
+ if (opts.nobracket !== true && opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
1587
+ value = `\\${value}`;
1588
+ } else increment("brackets");
1589
+ push({
1590
+ type: "bracket",
1591
+ value
1592
+ });
1593
+ continue;
1594
+ }
1595
+ if (value === "]") {
1596
+ if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
1597
+ push({
1598
+ type: "text",
1599
+ value,
1600
+ output: `\\${value}`
1601
+ });
1602
+ continue;
1603
+ }
1604
+ if (state.brackets === 0) {
1605
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "["));
1606
+ push({
1607
+ type: "text",
1608
+ value,
1609
+ output: `\\${value}`
1610
+ });
1611
+ continue;
1612
+ }
1613
+ decrement("brackets");
1614
+ const prevValue = prev.value.slice(1);
1615
+ if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) value = `/${value}`;
1616
+ prev.value += value;
1617
+ append({ value });
1618
+ if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) continue;
1619
+ const escaped = utils$2.escapeRegex(prev.value);
1620
+ state.output = state.output.slice(0, -prev.value.length);
1621
+ if (opts.literalBrackets === true) {
1622
+ state.output += escaped;
1623
+ prev.value = escaped;
1624
+ continue;
1625
+ }
1626
+ prev.value = `(${capture}${escaped}|${prev.value})`;
1627
+ state.output += prev.value;
1628
+ continue;
1629
+ }
1630
+ if (value === "{" && opts.nobrace !== true) {
1631
+ increment("braces");
1632
+ const open = {
1633
+ type: "brace",
1634
+ value,
1635
+ output: "(",
1636
+ outputIndex: state.output.length,
1637
+ tokensIndex: state.tokens.length
1638
+ };
1639
+ braces.push(open);
1640
+ push(open);
1641
+ continue;
1642
+ }
1643
+ if (value === "}") {
1644
+ const brace = braces[braces.length - 1];
1645
+ if (opts.nobrace === true || !brace) {
1646
+ push({
1647
+ type: "text",
1648
+ value,
1649
+ output: value
1650
+ });
1651
+ continue;
1652
+ }
1653
+ let output = ")";
1654
+ if (brace.dots === true) {
1655
+ const arr = tokens.slice();
1656
+ const range = [];
1657
+ for (let i = arr.length - 1; i >= 0; i--) {
1658
+ tokens.pop();
1659
+ if (arr[i].type === "brace") break;
1660
+ if (arr[i].type !== "dots") range.unshift(arr[i].value);
1661
+ }
1662
+ output = expandRange(range, opts);
1663
+ state.backtrack = true;
1664
+ }
1665
+ if (brace.comma !== true && brace.dots !== true) {
1666
+ const out = state.output.slice(0, brace.outputIndex);
1667
+ const toks = state.tokens.slice(brace.tokensIndex);
1668
+ brace.value = brace.output = "\\{";
1669
+ value = output = "\\}";
1670
+ state.output = out;
1671
+ for (const t of toks) state.output += t.output || t.value;
1672
+ }
1673
+ push({
1674
+ type: "brace",
1675
+ value,
1676
+ output
1677
+ });
1678
+ decrement("braces");
1679
+ braces.pop();
1680
+ continue;
1681
+ }
1682
+ if (value === "|") {
1683
+ if (extglobs.length > 0) extglobs[extglobs.length - 1].conditions++;
1684
+ push({
1685
+ type: "text",
1686
+ value
1687
+ });
1688
+ continue;
1689
+ }
1690
+ if (value === ",") {
1691
+ let output = value;
1692
+ const brace = braces[braces.length - 1];
1693
+ if (brace && stack[stack.length - 1] === "braces") {
1694
+ brace.comma = true;
1695
+ output = "|";
1696
+ }
1697
+ push({
1698
+ type: "comma",
1699
+ value,
1700
+ output
1701
+ });
1702
+ continue;
1703
+ }
1704
+ if (value === "/") {
1705
+ if (prev.type === "dot" && state.index === state.start + 1) {
1706
+ state.start = state.index + 1;
1707
+ state.consumed = "";
1708
+ state.output = "";
1709
+ tokens.pop();
1710
+ prev = bos;
1711
+ continue;
1712
+ }
1713
+ push({
1714
+ type: "slash",
1715
+ value,
1716
+ output: SLASH_LITERAL$1
1717
+ });
1718
+ continue;
1719
+ }
1720
+ if (value === ".") {
1721
+ if (state.braces > 0 && prev.type === "dot") {
1722
+ if (prev.value === ".") prev.output = DOT_LITERAL$1;
1723
+ const brace = braces[braces.length - 1];
1724
+ prev.type = "dots";
1725
+ prev.output += value;
1726
+ prev.value += value;
1727
+ brace.dots = true;
1728
+ continue;
1729
+ }
1730
+ if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
1731
+ push({
1732
+ type: "text",
1733
+ value,
1734
+ output: DOT_LITERAL$1
1735
+ });
1736
+ continue;
1737
+ }
1738
+ push({
1739
+ type: "dot",
1740
+ value,
1741
+ output: DOT_LITERAL$1
1742
+ });
1743
+ continue;
1744
+ }
1745
+ if (value === "?") {
1746
+ if (!(prev && prev.value === "(") && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1747
+ extglobOpen("qmark", value);
1748
+ continue;
1749
+ }
1750
+ if (prev && prev.type === "paren") {
1751
+ const next = peek();
1752
+ let output = value;
1753
+ if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) output = `\\${value}`;
1754
+ push({
1755
+ type: "text",
1756
+ value,
1757
+ output
1758
+ });
1759
+ continue;
1760
+ }
1761
+ if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
1762
+ push({
1763
+ type: "qmark",
1764
+ value,
1765
+ output: QMARK_NO_DOT$1
1766
+ });
1767
+ continue;
1768
+ }
1769
+ push({
1770
+ type: "qmark",
1771
+ value,
1772
+ output: QMARK$1
1773
+ });
1774
+ continue;
1775
+ }
1776
+ if (value === "!") {
1777
+ if (opts.noextglob !== true && peek() === "(") {
1778
+ if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
1779
+ extglobOpen("negate", value);
1780
+ continue;
1781
+ }
1782
+ }
1783
+ if (opts.nonegate !== true && state.index === 0) {
1784
+ negate();
1785
+ continue;
1786
+ }
1787
+ }
1788
+ if (value === "+") {
1789
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1790
+ extglobOpen("plus", value);
1791
+ continue;
1792
+ }
1793
+ if (prev && prev.value === "(" || opts.regex === false) {
1794
+ push({
1795
+ type: "plus",
1796
+ value,
1797
+ output: PLUS_LITERAL$1
1798
+ });
1799
+ continue;
1800
+ }
1801
+ if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
1802
+ push({
1803
+ type: "plus",
1804
+ value
1805
+ });
1806
+ continue;
1807
+ }
1808
+ push({
1809
+ type: "plus",
1810
+ value: PLUS_LITERAL$1
1811
+ });
1812
+ continue;
1813
+ }
1814
+ if (value === "@") {
1815
+ if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1816
+ push({
1817
+ type: "at",
1818
+ extglob: true,
1819
+ value,
1820
+ output: ""
1821
+ });
1822
+ continue;
1823
+ }
1824
+ push({
1825
+ type: "text",
1826
+ value
1827
+ });
1828
+ continue;
1829
+ }
1830
+ if (value !== "*") {
1831
+ if (value === "$" || value === "^") value = `\\${value}`;
1832
+ const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
1833
+ if (match) {
1834
+ value += match[0];
1835
+ state.index += match[0].length;
1836
+ }
1837
+ push({
1838
+ type: "text",
1839
+ value
1840
+ });
1841
+ continue;
1842
+ }
1843
+ if (prev && (prev.type === "globstar" || prev.star === true)) {
1844
+ prev.type = "star";
1845
+ prev.star = true;
1846
+ prev.value += value;
1847
+ prev.output = star;
1848
+ state.backtrack = true;
1849
+ state.globstar = true;
1850
+ consume(value);
1851
+ continue;
1852
+ }
1853
+ let rest = remaining();
1854
+ if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
1855
+ extglobOpen("star", value);
1856
+ continue;
1857
+ }
1858
+ if (prev.type === "star") {
1859
+ if (opts.noglobstar === true) {
1860
+ consume(value);
1861
+ continue;
1862
+ }
1863
+ const prior = prev.prev;
1864
+ const before = prior.prev;
1865
+ const isStart = prior.type === "slash" || prior.type === "bos";
1866
+ const afterStar = before && (before.type === "star" || before.type === "globstar");
1867
+ if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
1868
+ push({
1869
+ type: "star",
1870
+ value,
1871
+ output: ""
1872
+ });
1873
+ continue;
1874
+ }
1875
+ const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace");
1876
+ const isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
1877
+ if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
1878
+ push({
1879
+ type: "star",
1880
+ value,
1881
+ output: ""
1882
+ });
1883
+ continue;
1884
+ }
1885
+ while (rest.slice(0, 3) === "/**") {
1886
+ const after = input[state.index + 4];
1887
+ if (after && after !== "/") break;
1888
+ rest = rest.slice(3);
1889
+ consume("/**", 3);
1890
+ }
1891
+ if (prior.type === "bos" && eos()) {
1892
+ prev.type = "globstar";
1893
+ prev.value += value;
1894
+ prev.output = globstar(opts);
1895
+ state.output = prev.output;
1896
+ state.globstar = true;
1897
+ consume(value);
1898
+ continue;
1899
+ }
1900
+ if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
1901
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1902
+ prior.output = `(?:${prior.output}`;
1903
+ prev.type = "globstar";
1904
+ prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)");
1905
+ prev.value += value;
1906
+ state.globstar = true;
1907
+ state.output += prior.output + prev.output;
1908
+ consume(value);
1909
+ continue;
1910
+ }
1911
+ if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
1912
+ const end = rest[1] !== void 0 ? "|$" : "";
1913
+ state.output = state.output.slice(0, -(prior.output + prev.output).length);
1914
+ prior.output = `(?:${prior.output}`;
1915
+ prev.type = "globstar";
1916
+ prev.output = `${globstar(opts)}${SLASH_LITERAL$1}|${SLASH_LITERAL$1}${end})`;
1917
+ prev.value += value;
1918
+ state.output += prior.output + prev.output;
1919
+ state.globstar = true;
1920
+ consume(value + advance());
1921
+ push({
1922
+ type: "slash",
1923
+ value: "/",
1924
+ output: ""
1925
+ });
1926
+ continue;
1927
+ }
1928
+ if (prior.type === "bos" && rest[0] === "/") {
1929
+ prev.type = "globstar";
1930
+ prev.value += value;
1931
+ prev.output = `(?:^|${SLASH_LITERAL$1}|${globstar(opts)}${SLASH_LITERAL$1})`;
1932
+ state.output = prev.output;
1933
+ state.globstar = true;
1934
+ consume(value + advance());
1935
+ push({
1936
+ type: "slash",
1937
+ value: "/",
1938
+ output: ""
1939
+ });
1940
+ continue;
1941
+ }
1942
+ state.output = state.output.slice(0, -prev.output.length);
1943
+ prev.type = "globstar";
1944
+ prev.output = globstar(opts);
1945
+ prev.value += value;
1946
+ state.output += prev.output;
1947
+ state.globstar = true;
1948
+ consume(value);
1949
+ continue;
1950
+ }
1951
+ const token = {
1952
+ type: "star",
1953
+ value,
1954
+ output: star
1955
+ };
1956
+ if (opts.bash === true) {
1957
+ token.output = ".*?";
1958
+ if (prev.type === "bos" || prev.type === "slash") token.output = nodot + token.output;
1959
+ push(token);
1960
+ continue;
1961
+ }
1962
+ if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
1963
+ token.output = value;
1964
+ push(token);
1965
+ continue;
1966
+ }
1967
+ if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
1968
+ if (prev.type === "dot") {
1969
+ state.output += NO_DOT_SLASH$1;
1970
+ prev.output += NO_DOT_SLASH$1;
1971
+ } else if (opts.dot === true) {
1972
+ state.output += NO_DOTS_SLASH$1;
1973
+ prev.output += NO_DOTS_SLASH$1;
1974
+ } else {
1975
+ state.output += nodot;
1976
+ prev.output += nodot;
1977
+ }
1978
+ if (peek() !== "*") {
1979
+ state.output += ONE_CHAR$1;
1980
+ prev.output += ONE_CHAR$1;
1981
+ }
1982
+ }
1983
+ push(token);
1984
+ }
1985
+ while (state.brackets > 0) {
1986
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
1987
+ state.output = utils$2.escapeLast(state.output, "[");
1988
+ decrement("brackets");
1989
+ }
1990
+ while (state.parens > 0) {
1991
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
1992
+ state.output = utils$2.escapeLast(state.output, "(");
1993
+ decrement("parens");
1994
+ }
1995
+ while (state.braces > 0) {
1996
+ if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
1997
+ state.output = utils$2.escapeLast(state.output, "{");
1998
+ decrement("braces");
1999
+ }
2000
+ if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) push({
2001
+ type: "maybe_slash",
2002
+ value: "",
2003
+ output: `${SLASH_LITERAL$1}?`
2004
+ });
2005
+ if (state.backtrack === true) {
2006
+ state.output = "";
2007
+ for (const token of state.tokens) {
2008
+ state.output += token.output != null ? token.output : token.value;
2009
+ if (token.suffix) state.output += token.suffix;
2010
+ }
2011
+ }
2012
+ return state;
2013
+ };
2014
+ parse$1.fastpaths = (input, options) => {
2015
+ const opts = { ...options };
2016
+ const max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
2017
+ const len = input.length;
2018
+ if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
2019
+ input = REPLACEMENTS[input] || input;
2020
+ const { DOT_LITERAL: DOT_LITERAL$1, SLASH_LITERAL: SLASH_LITERAL$1, ONE_CHAR: ONE_CHAR$1, DOTS_SLASH: DOTS_SLASH$1, NO_DOT: NO_DOT$1, NO_DOTS: NO_DOTS$1, NO_DOTS_SLASH: NO_DOTS_SLASH$1, STAR: STAR$1, START_ANCHOR: START_ANCHOR$1 } = constants$1.globChars(opts.windows);
2021
+ const nodot = opts.dot ? NO_DOTS$1 : NO_DOT$1;
2022
+ const slashDot = opts.dot ? NO_DOTS_SLASH$1 : NO_DOT$1;
2023
+ const capture = opts.capture ? "" : "?:";
2024
+ const state = {
2025
+ negated: false,
2026
+ prefix: ""
2027
+ };
2028
+ let star = opts.bash === true ? ".*?" : STAR$1;
2029
+ if (opts.capture) star = `(${star})`;
2030
+ const globstar = (opts$1) => {
2031
+ if (opts$1.noglobstar === true) return star;
2032
+ return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
2033
+ };
2034
+ const create = (str) => {
2035
+ switch (str) {
2036
+ case "*": return `${nodot}${ONE_CHAR$1}${star}`;
2037
+ case ".*": return `${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
2038
+ case "*.*": return `${nodot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
2039
+ case "*/*": return `${nodot}${star}${SLASH_LITERAL$1}${ONE_CHAR$1}${slashDot}${star}`;
2040
+ case "**": return nodot + globstar(opts);
2041
+ case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${ONE_CHAR$1}${star}`;
2042
+ case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
2043
+ case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
2044
+ default: {
2045
+ const match = /^(.*?)\.(\w+)$/.exec(str);
2046
+ if (!match) return;
2047
+ const source$1 = create(match[1]);
2048
+ if (!source$1) return;
2049
+ return source$1 + DOT_LITERAL$1 + match[2];
2050
+ }
2051
+ }
2052
+ };
2053
+ const output = utils$2.removePrefix(input, state);
2054
+ let source = create(output);
2055
+ if (source && opts.strictSlashes !== true) source += `${SLASH_LITERAL$1}?`;
2056
+ return source;
2057
+ };
2058
+ module.exports = parse$1;
2059
+ }));
2060
+ var require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
2061
+ const scan = require_scan();
2062
+ const parse = require_parse();
2063
+ const utils$1 = require_utils();
2064
+ const constants = require_constants();
2065
+ const isObject = (val) => val && typeof val === "object" && !Array.isArray(val);
2066
+ const picomatch$2 = (glob$1, options, returnState = false) => {
2067
+ if (Array.isArray(glob$1)) {
2068
+ const fns = glob$1.map((input) => picomatch$2(input, options, returnState));
2069
+ const arrayMatcher = (str) => {
2070
+ for (const isMatch of fns) {
2071
+ const state$1 = isMatch(str);
2072
+ if (state$1) return state$1;
2073
+ }
2074
+ return false;
2075
+ };
2076
+ return arrayMatcher;
2077
+ }
2078
+ const isState = isObject(glob$1) && glob$1.tokens && glob$1.input;
2079
+ if (glob$1 === "" || typeof glob$1 !== "string" && !isState) throw new TypeError("Expected pattern to be a non-empty string");
2080
+ const opts = options || {};
2081
+ const posix$1 = opts.windows;
2082
+ const regex = isState ? picomatch$2.compileRe(glob$1, options) : picomatch$2.makeRe(glob$1, options, false, true);
2083
+ const state = regex.state;
2084
+ delete regex.state;
2085
+ let isIgnored = () => false;
2086
+ if (opts.ignore) {
2087
+ const ignoreOpts = {
2088
+ ...options,
2089
+ ignore: null,
2090
+ onMatch: null,
2091
+ onResult: null
2092
+ };
2093
+ isIgnored = picomatch$2(opts.ignore, ignoreOpts, returnState);
2094
+ }
2095
+ const matcher = (input, returnObject = false) => {
2096
+ const { isMatch, match, output } = picomatch$2.test(input, regex, options, {
2097
+ glob: glob$1,
2098
+ posix: posix$1
2099
+ });
2100
+ const result = {
2101
+ glob: glob$1,
2102
+ state,
2103
+ regex,
2104
+ posix: posix$1,
2105
+ input,
2106
+ output,
2107
+ match,
2108
+ isMatch
2109
+ };
2110
+ if (typeof opts.onResult === "function") opts.onResult(result);
2111
+ if (isMatch === false) {
2112
+ result.isMatch = false;
2113
+ return returnObject ? result : false;
2114
+ }
2115
+ if (isIgnored(input)) {
2116
+ if (typeof opts.onIgnore === "function") opts.onIgnore(result);
2117
+ result.isMatch = false;
2118
+ return returnObject ? result : false;
2119
+ }
2120
+ if (typeof opts.onMatch === "function") opts.onMatch(result);
2121
+ return returnObject ? result : true;
2122
+ };
2123
+ if (returnState) matcher.state = state;
2124
+ return matcher;
2125
+ };
2126
+ picomatch$2.test = (input, regex, options, { glob: glob$1, posix: posix$1 } = {}) => {
2127
+ if (typeof input !== "string") throw new TypeError("Expected input to be a string");
2128
+ if (input === "") return {
2129
+ isMatch: false,
2130
+ output: ""
2131
+ };
2132
+ const opts = options || {};
2133
+ const format = opts.format || (posix$1 ? utils$1.toPosixSlashes : null);
2134
+ let match = input === glob$1;
2135
+ let output = match && format ? format(input) : input;
2136
+ if (match === false) {
2137
+ output = format ? format(input) : input;
2138
+ match = output === glob$1;
2139
+ }
2140
+ if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch$2.matchBase(input, regex, options, posix$1);
2141
+ else match = regex.exec(output);
2142
+ return {
2143
+ isMatch: Boolean(match),
2144
+ match,
2145
+ output
2146
+ };
2147
+ };
2148
+ picomatch$2.matchBase = (input, glob$1, options) => {
2149
+ return (glob$1 instanceof RegExp ? glob$1 : picomatch$2.makeRe(glob$1, options)).test(utils$1.basename(input));
2150
+ };
2151
+ picomatch$2.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str);
2152
+ picomatch$2.parse = (pattern, options) => {
2153
+ if (Array.isArray(pattern)) return pattern.map((p) => picomatch$2.parse(p, options));
2154
+ return parse(pattern, {
2155
+ ...options,
2156
+ fastpaths: false
2157
+ });
2158
+ };
2159
+ picomatch$2.scan = (input, options) => scan(input, options);
2160
+ picomatch$2.compileRe = (state, options, returnOutput = false, returnState = false) => {
2161
+ if (returnOutput === true) return state.output;
2162
+ const opts = options || {};
2163
+ const prepend = opts.contains ? "" : "^";
2164
+ const append = opts.contains ? "" : "$";
2165
+ let source = `${prepend}(?:${state.output})${append}`;
2166
+ if (state && state.negated === true) source = `^(?!${source}).*$`;
2167
+ const regex = picomatch$2.toRegex(source, options);
2168
+ if (returnState === true) regex.state = state;
2169
+ return regex;
2170
+ };
2171
+ picomatch$2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
2172
+ if (!input || typeof input !== "string") throw new TypeError("Expected a non-empty string");
2173
+ let parsed = {
2174
+ negated: false,
2175
+ fastpaths: true
2176
+ };
2177
+ if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) parsed.output = parse.fastpaths(input, options);
2178
+ if (!parsed.output) parsed = parse(input, options);
2179
+ return picomatch$2.compileRe(parsed, options, returnOutput, returnState);
2180
+ };
2181
+ picomatch$2.toRegex = (source, options) => {
2182
+ try {
2183
+ const opts = options || {};
2184
+ return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
2185
+ } catch (err) {
2186
+ if (options && options.debug === true) throw err;
2187
+ return /$^/;
2188
+ }
2189
+ };
2190
+ picomatch$2.constants = constants;
2191
+ module.exports = picomatch$2;
2192
+ }));
2193
+ var import_picomatch = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
2194
+ const pico = require_picomatch$1();
2195
+ const utils = require_utils();
2196
+ function picomatch$1(glob$1, options, returnState = false) {
2197
+ if (options && (options.windows === null || options.windows === void 0)) options = {
2198
+ ...options,
2199
+ windows: utils.isWindows()
2200
+ };
2201
+ return pico(glob$1, options, returnState);
2202
+ }
2203
+ Object.assign(picomatch$1, pico);
2204
+ module.exports = picomatch$1;
2205
+ })))(), 1);
2206
+ const isReadonlyArray = Array.isArray;
2207
+ const isWin = process.platform === "win32";
2208
+ const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
2209
+ function getPartialMatcher(patterns, options = {}) {
2210
+ const patternsCount = patterns.length;
2211
+ const patternsParts = Array(patternsCount);
2212
+ const matchers = Array(patternsCount);
2213
+ const globstarEnabled = !options.noglobstar;
2214
+ for (let i = 0; i < patternsCount; i++) {
2215
+ const parts = splitPattern(patterns[i]);
2216
+ patternsParts[i] = parts;
2217
+ const partsCount = parts.length;
2218
+ const partMatchers = Array(partsCount);
2219
+ for (let j$1 = 0; j$1 < partsCount; j$1++) partMatchers[j$1] = (0, import_picomatch.default)(parts[j$1], options);
2220
+ matchers[i] = partMatchers;
2221
+ }
2222
+ return (input) => {
2223
+ const inputParts = input.split("/");
2224
+ if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
2225
+ for (let i = 0; i < patterns.length; i++) {
2226
+ const patternParts = patternsParts[i];
2227
+ const matcher = matchers[i];
2228
+ const inputPatternCount = inputParts.length;
2229
+ const minParts = Math.min(inputPatternCount, patternParts.length);
2230
+ let j$1 = 0;
2231
+ while (j$1 < minParts) {
2232
+ const part = patternParts[j$1];
2233
+ if (part.includes("/")) return true;
2234
+ if (!matcher[j$1](inputParts[j$1])) break;
2235
+ if (globstarEnabled && part === "**") return true;
2236
+ j$1++;
2237
+ }
2238
+ if (j$1 === inputPatternCount) return true;
2239
+ }
2240
+ return false;
2241
+ };
2242
+ }
2243
+ /* node:coverage ignore next 2 */
2244
+ const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
2245
+ const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
2246
+ function buildFormat(cwd, root, absolute) {
2247
+ if (cwd === root || root.startsWith(`${cwd}/`)) {
2248
+ if (absolute) {
2249
+ const start = isRoot(cwd) ? cwd.length : cwd.length + 1;
2250
+ return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
2251
+ }
2252
+ const prefix = root.slice(cwd.length + 1);
2253
+ if (prefix) return (p, isDir) => {
2254
+ if (p === ".") return prefix;
2255
+ const result = `${prefix}/${p}`;
2256
+ return isDir ? result.slice(0, -1) : result;
2257
+ };
2258
+ return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
2259
+ }
2260
+ if (absolute) return (p) => posix.relative(cwd, p) || ".";
2261
+ return (p) => posix.relative(cwd, `${root}/${p}`) || ".";
2262
+ }
2263
+ function buildRelative(cwd, root) {
2264
+ if (root.startsWith(`${cwd}/`)) {
2265
+ const prefix = root.slice(cwd.length + 1);
2266
+ return (p) => `${prefix}/${p}`;
2267
+ }
2268
+ return (p) => {
2269
+ const result = posix.relative(cwd, `${root}/${p}`);
2270
+ if (p.endsWith("/") && result !== "") return `${result}/`;
2271
+ return result || ".";
2272
+ };
2273
+ }
2274
+ const splitPatternOptions = { parts: true };
2275
+ function splitPattern(path$1) {
2276
+ var _result$parts;
2277
+ const result = import_picomatch.default.scan(path$1, splitPatternOptions);
2278
+ return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1];
2279
+ }
2280
+ const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
2281
+ const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
2282
+ const escapePosixPath = (path$1) => path$1.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
2283
+ const escapeWin32Path = (path$1) => path$1.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
2284
+ /* node:coverage ignore next */
2285
+ const escapePath = isWin ? escapeWin32Path : escapePosixPath;
2286
+ function isDynamicPattern(pattern, options) {
2287
+ if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
2288
+ const scan$2 = import_picomatch.default.scan(pattern);
2289
+ return scan$2.isGlob || scan$2.negated;
2290
+ }
2291
+ function log(...tasks) {
2292
+ console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
2293
+ }
2294
+ const PARENT_DIRECTORY = /^(\/?\.\.)+/;
2295
+ const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
2296
+ const BACKSLASHES = /\\/g;
2297
+ function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) {
2298
+ let result = pattern;
2299
+ if (pattern.endsWith("/")) result = pattern.slice(0, -1);
2300
+ if (!result.endsWith("*") && expandDirectories) result += "/**";
2301
+ const escapedCwd = escapePath(cwd);
2302
+ if (path.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = posix.relative(escapedCwd, result);
2303
+ else result = posix.normalize(result);
2304
+ const parentDirectoryMatch = PARENT_DIRECTORY.exec(result);
2305
+ const parts = splitPattern(result);
2306
+ if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) {
2307
+ const n$1 = (parentDirectoryMatch[0].length + 1) / 3;
2308
+ let i = 0;
2309
+ const cwdParts = escapedCwd.split("/");
2310
+ while (i < n$1 && parts[i + n$1] === cwdParts[cwdParts.length + i - n$1]) {
2311
+ result = result.slice(0, (n$1 - i - 1) * 3) + result.slice((n$1 - i) * 3 + parts[i + n$1].length + 1) || ".";
2312
+ i++;
2313
+ }
2314
+ const potentialRoot = posix.join(cwd, parentDirectoryMatch[0].slice(i * 3));
2315
+ if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) {
2316
+ props.root = potentialRoot;
2317
+ props.depthOffset = -n$1 + i;
2318
+ }
2319
+ }
2320
+ if (!isIgnore && props.depthOffset >= 0) {
2321
+ var _props$commonPath;
2322
+ (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
2323
+ const newCommonPath = [];
2324
+ const length = Math.min(props.commonPath.length, parts.length);
2325
+ for (let i = 0; i < length; i++) {
2326
+ const part = parts[i];
2327
+ if (part === "**" && !parts[i + 1]) {
2328
+ newCommonPath.pop();
2329
+ break;
2330
+ }
2331
+ if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break;
2332
+ newCommonPath.push(part);
2333
+ }
2334
+ props.depthOffset = newCommonPath.length;
2335
+ props.commonPath = newCommonPath;
2336
+ props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd;
2337
+ }
2338
+ return result;
2339
+ }
2340
+ function processPatterns({ patterns = ["**/*"], ignore = [], expandDirectories = true }, cwd, props) {
2341
+ if (typeof patterns === "string") patterns = [patterns];
2342
+ if (typeof ignore === "string") ignore = [ignore];
2343
+ const matchPatterns = [];
2344
+ const ignorePatterns = [];
2345
+ for (const pattern of ignore) {
2346
+ if (!pattern) continue;
2347
+ if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true));
2348
+ }
2349
+ for (const pattern of patterns) {
2350
+ if (!pattern) continue;
2351
+ if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false));
2352
+ else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true));
2353
+ }
2354
+ return {
2355
+ match: matchPatterns,
2356
+ ignore: ignorePatterns
2357
+ };
2358
+ }
2359
+ function formatPaths(paths, relative$1) {
2360
+ for (let i = paths.length - 1; i >= 0; i--) {
2361
+ const path$1 = paths[i];
2362
+ paths[i] = relative$1(path$1);
2363
+ }
2364
+ return paths;
2365
+ }
2366
+ function normalizeCwd(cwd) {
2367
+ if (!cwd) return process.cwd().replace(BACKSLASHES, "/");
2368
+ if (cwd instanceof URL) return fileURLToPath(cwd).replace(BACKSLASHES, "/");
2369
+ return path.resolve(cwd).replace(BACKSLASHES, "/");
2370
+ }
2371
+ function getCrawler(patterns, inputOptions = {}) {
2372
+ const options = process.env.TINYGLOBBY_DEBUG ? {
2373
+ ...inputOptions,
2374
+ debug: true
2375
+ } : inputOptions;
2376
+ const cwd = normalizeCwd(options.cwd);
2377
+ if (options.debug) log("globbing with:", {
2378
+ patterns,
2379
+ options,
2380
+ cwd
2381
+ });
2382
+ if (Array.isArray(patterns) && patterns.length === 0) return [{
2383
+ sync: () => [],
2384
+ withPromise: async () => []
2385
+ }, false];
2386
+ const props = {
2387
+ root: cwd,
2388
+ commonPath: null,
2389
+ depthOffset: 0
2390
+ };
2391
+ const processed = processPatterns({
2392
+ ...options,
2393
+ patterns
2394
+ }, cwd, props);
2395
+ if (options.debug) log("internal processing patterns:", processed);
2396
+ const matchOptions = {
2397
+ dot: options.dot,
2398
+ nobrace: options.braceExpansion === false,
2399
+ nocase: options.caseSensitiveMatch === false,
2400
+ noextglob: options.extglob === false,
2401
+ noglobstar: options.globstar === false,
2402
+ posix: true
2403
+ };
2404
+ const matcher = (0, import_picomatch.default)(processed.match, {
2405
+ ...matchOptions,
2406
+ ignore: processed.ignore
2407
+ });
2408
+ const ignore = (0, import_picomatch.default)(processed.ignore, matchOptions);
2409
+ const partialMatcher = getPartialMatcher(processed.match, matchOptions);
2410
+ const format = buildFormat(cwd, props.root, options.absolute);
2411
+ const formatExclude = options.absolute ? format : buildFormat(cwd, props.root, true);
2412
+ const fdirOptions = {
2413
+ filters: [options.debug ? (p, isDirectory$1) => {
2414
+ const path$1 = format(p, isDirectory$1);
2415
+ const matches = matcher(path$1);
2416
+ if (matches) log(`matched ${path$1}`);
2417
+ return matches;
2418
+ } : (p, isDirectory$1) => matcher(format(p, isDirectory$1))],
2419
+ exclude: options.debug ? (_, p) => {
2420
+ const relativePath = formatExclude(p, true);
2421
+ const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
2422
+ if (skipped) log(`skipped ${p}`);
2423
+ else log(`crawling ${p}`);
2424
+ return skipped;
2425
+ } : (_, p) => {
2426
+ const relativePath = formatExclude(p, true);
2427
+ return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
2428
+ },
2429
+ fs: options.fs ? {
2430
+ readdir: options.fs.readdir || b.readdir,
2431
+ readdirSync: options.fs.readdirSync || b.readdirSync,
2432
+ realpath: options.fs.realpath || b.realpath,
2433
+ realpathSync: options.fs.realpathSync || b.realpathSync,
2434
+ stat: options.fs.stat || b.stat,
2435
+ statSync: options.fs.statSync || b.statSync
2436
+ } : void 0,
2437
+ pathSeparator: "/",
2438
+ relativePaths: true,
2439
+ resolveSymlinks: true,
2440
+ signal: options.signal
2441
+ };
2442
+ if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset);
2443
+ if (options.absolute) {
2444
+ fdirOptions.relativePaths = false;
2445
+ fdirOptions.resolvePaths = true;
2446
+ fdirOptions.includeBasePath = true;
2447
+ }
2448
+ if (options.followSymbolicLinks === false) {
2449
+ fdirOptions.resolveSymlinks = false;
2450
+ fdirOptions.excludeSymlinks = true;
2451
+ }
2452
+ if (options.onlyDirectories) {
2453
+ fdirOptions.excludeFiles = true;
2454
+ fdirOptions.includeDirs = true;
2455
+ } else if (options.onlyFiles === false) fdirOptions.includeDirs = true;
2456
+ props.root = props.root.replace(BACKSLASHES, "");
2457
+ const root = props.root;
2458
+ if (options.debug) log("internal properties:", props);
2459
+ const relative$1 = cwd !== root && !options.absolute && buildRelative(cwd, props.root);
2460
+ return [new Builder(fdirOptions).crawl(root), relative$1];
2461
+ }
2462
+ async function glob(patternsOrOptions, options) {
2463
+ if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
2464
+ const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string";
2465
+ const opts = isModern ? options : patternsOrOptions;
2466
+ const patterns = isModern ? patternsOrOptions : patternsOrOptions.patterns;
2467
+ const [crawler, relative$1] = getCrawler(patterns, opts);
2468
+ if (!relative$1) return crawler.withPromise();
2469
+ return formatPaths(await crawler.withPromise(), relative$1);
2470
+ }
2471
+ const homeDirectory = F.homedir();
2472
+ const { env } = process;
2473
+ const xdgData = env.XDG_DATA_HOME || (homeDirectory ? path.join(homeDirectory, ".local", "share") : void 0);
2474
+ const xdgConfig = env.XDG_CONFIG_HOME || (homeDirectory ? path.join(homeDirectory, ".config") : void 0);
2475
+ env.XDG_STATE_HOME || homeDirectory && path.join(homeDirectory, ".local", "state");
2476
+ env.XDG_CACHE_HOME || homeDirectory && path.join(homeDirectory, ".cache");
2477
+ env.XDG_RUNTIME_DIR;
2478
+ const xdgDataDirectories = (env.XDG_DATA_DIRS || "/usr/local/share/:/usr/share/").split(":");
2479
+ if (xdgData) xdgDataDirectories.unshift(xdgData);
2480
+ const xdgConfigDirectories = (env.XDG_CONFIG_DIRS || "/etc/xdg").split(":");
2481
+ if (xdgConfig) xdgConfigDirectories.unshift(xdgConfig);
2482
+ const DEFAULT_RECENT_DAYS = 3;
2483
+ const BLOCKS_WARNING_THRESHOLD = .8;
2484
+ const BLOCKS_COMPACT_WIDTH_THRESHOLD = 120;
2485
+ const BLOCKS_DEFAULT_TERMINAL_WIDTH = 120;
2486
+ const DEBUG_MATCH_THRESHOLD_PERCENT = .1;
2487
+ const USER_HOME_DIR = homedir();
2488
+ const XDG_CONFIG_DIR = xdgConfig ?? `${USER_HOME_DIR}/.config`;
2489
+ const DEFAULT_CLAUDE_CODE_PATH = ".claude";
2490
+ const DEFAULT_CLAUDE_CONFIG_PATH = `${XDG_CONFIG_DIR}/claude`;
2491
+ const CLAUDE_CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR";
2492
+ const CLAUDE_PROJECTS_DIR_NAME = "projects";
2493
+ const USAGE_DATA_GLOB_PATTERN = "**/*.jsonl";
2494
+ const DEFAULT_REFRESH_INTERVAL_SECONDS = 1;
2495
+ const MIN_REFRESH_INTERVAL_SECONDS = 1;
2496
+ const MAX_REFRESH_INTERVAL_SECONDS = 60;
2497
+ const MIN_RENDER_INTERVAL_MS = 16;
2498
+ const BURN_RATE_THRESHOLDS = {
2499
+ HIGH: 1e3,
2500
+ MODERATE: 500
2501
+ };
2502
+ const DEFAULT_CONTEXT_USAGE_THRESHOLDS = {
2503
+ LOW: 50,
2504
+ MEDIUM: 80
2505
+ };
2506
+ const WEEK_DAYS = [
2507
+ "sunday",
2508
+ "monday",
2509
+ "tuesday",
2510
+ "wednesday",
2511
+ "thursday",
2512
+ "friday",
2513
+ "saturday"
2514
+ ];
2515
+ const CONFIG_FILE_NAME = "ccusage.json";
2516
+ const DEFAULT_LOCALE = "en-CA";
2517
+ var castComparer = function(comparer) {
2518
+ return function(a$1, b$1, order) {
2519
+ return comparer(a$1, b$1, order) * order;
2520
+ };
2521
+ };
2522
+ var throwInvalidConfigErrorIfTrue = function(condition, context) {
2523
+ if (condition) throw Error("Invalid sort config: " + context);
2524
+ };
2525
+ var unpackObjectSorter = function(sortByObj) {
2526
+ var _a = sortByObj || {}, asc = _a.asc, desc = _a.desc;
2527
+ var order = asc ? 1 : -1;
2528
+ var sortBy = asc || desc;
2529
+ throwInvalidConfigErrorIfTrue(!sortBy, "Expected `asc` or `desc` property");
2530
+ throwInvalidConfigErrorIfTrue(asc && desc, "Ambiguous object with `asc` and `desc` config properties");
2531
+ var comparer = sortByObj.comparer && castComparer(sortByObj.comparer);
2532
+ return {
2533
+ order,
2534
+ sortBy,
2535
+ comparer
2536
+ };
2537
+ };
2538
+ var multiPropertySorterProvider = function(defaultComparer$1) {
2539
+ return function multiPropertySorter(sortBy, sortByArr, depth$1, order, comparer, a$1, b$1) {
2540
+ var valA;
2541
+ var valB;
2542
+ if (typeof sortBy === "string") {
2543
+ valA = a$1[sortBy];
2544
+ valB = b$1[sortBy];
2545
+ } else if (typeof sortBy === "function") {
2546
+ valA = sortBy(a$1);
2547
+ valB = sortBy(b$1);
2548
+ } else {
2549
+ var objectSorterConfig = unpackObjectSorter(sortBy);
2550
+ return multiPropertySorter(objectSorterConfig.sortBy, sortByArr, depth$1, objectSorterConfig.order, objectSorterConfig.comparer || defaultComparer$1, a$1, b$1);
2551
+ }
2552
+ var equality = comparer(valA, valB, order);
2553
+ if ((equality === 0 || valA == null && valB == null) && sortByArr.length > depth$1) return multiPropertySorter(sortByArr[depth$1], sortByArr, depth$1 + 1, order, comparer, a$1, b$1);
2554
+ return equality;
2555
+ };
2556
+ };
2557
+ function getSortStrategy(sortBy, comparer, order) {
2558
+ if (sortBy === void 0 || sortBy === true) return function(a$1, b$1) {
2559
+ return comparer(a$1, b$1, order);
2560
+ };
2561
+ if (typeof sortBy === "string") {
2562
+ throwInvalidConfigErrorIfTrue(sortBy.includes("."), "String syntax not allowed for nested properties.");
2563
+ return function(a$1, b$1) {
2564
+ return comparer(a$1[sortBy], b$1[sortBy], order);
2565
+ };
2566
+ }
2567
+ if (typeof sortBy === "function") return function(a$1, b$1) {
2568
+ return comparer(sortBy(a$1), sortBy(b$1), order);
2569
+ };
2570
+ if (Array.isArray(sortBy)) {
2571
+ var multiPropSorter_1 = multiPropertySorterProvider(comparer);
2572
+ return function(a$1, b$1) {
2573
+ return multiPropSorter_1(sortBy[0], sortBy, 1, order, comparer, a$1, b$1);
2574
+ };
2575
+ }
2576
+ var objectSorterConfig = unpackObjectSorter(sortBy);
2577
+ return getSortStrategy(objectSorterConfig.sortBy, objectSorterConfig.comparer || comparer, objectSorterConfig.order);
2578
+ }
2579
+ var sortArray = function(order, ctx, sortBy, comparer) {
2580
+ var _a;
2581
+ if (!Array.isArray(ctx)) return ctx;
2582
+ if (Array.isArray(sortBy) && sortBy.length < 2) _a = sortBy, sortBy = _a[0];
2583
+ return ctx.sort(getSortStrategy(sortBy, comparer, order));
2584
+ };
2585
+ function createNewSortInstance(opts) {
2586
+ var comparer = castComparer(opts.comparer);
2587
+ return function(arrayToSort) {
2588
+ var ctx = Array.isArray(arrayToSort) && !opts.inPlaceSorting ? arrayToSort.slice() : arrayToSort;
2589
+ return {
2590
+ asc: function(sortBy) {
2591
+ return sortArray(1, ctx, sortBy, comparer);
2592
+ },
2593
+ desc: function(sortBy) {
2594
+ return sortArray(-1, ctx, sortBy, comparer);
2595
+ },
2596
+ by: function(sortBy) {
2597
+ return sortArray(1, ctx, sortBy, comparer);
2598
+ }
2599
+ };
2600
+ };
2601
+ }
2602
+ var defaultComparer = function(a$1, b$1, order) {
2603
+ if (a$1 == null) return order;
2604
+ if (b$1 == null) return -order;
2605
+ if (typeof a$1 !== typeof b$1) return typeof a$1 < typeof b$1 ? -1 : 1;
2606
+ if (a$1 < b$1) return -1;
2607
+ if (a$1 > b$1) return 1;
2608
+ return 0;
2609
+ };
2610
+ var sort = createNewSortInstance({ comparer: defaultComparer });
2611
+ createNewSortInstance({
2612
+ comparer: defaultComparer,
2613
+ inPlaceSorting: true
2614
+ });
2615
+ function _usingCtx() {
2616
+ var r = "function" == typeof SuppressedError ? SuppressedError : function(r$1, e$1) {
2617
+ var n$2 = Error();
2618
+ return n$2.name = "SuppressedError", n$2.error = r$1, n$2.suppressed = e$1, n$2;
2619
+ }, e = {}, n$1 = [];
2620
+ function using(r$1, e$1) {
2621
+ if (null != e$1) {
2622
+ if (Object(e$1) !== e$1) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
2623
+ if (r$1) var o = e$1[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
2624
+ if (void 0 === o && (o = e$1[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r$1)) var t = o;
2625
+ if ("function" != typeof o) throw new TypeError("Object is not disposable.");
2626
+ t && (o = function o$1() {
2627
+ try {
2628
+ t.call(e$1);
2629
+ } catch (r$2) {
2630
+ return Promise.reject(r$2);
2631
+ }
2632
+ }), n$1.push({
2633
+ v: e$1,
2634
+ d: o,
2635
+ a: r$1
2636
+ });
2637
+ } else r$1 && n$1.push({
2638
+ d: e$1,
2639
+ a: r$1
2640
+ });
2641
+ return e$1;
2642
+ }
2643
+ return {
2644
+ e,
2645
+ u: using.bind(null, !1),
2646
+ a: using.bind(null, !0),
2647
+ d: function d$1() {
2648
+ var o, t = this.e, s = 0;
2649
+ function next() {
2650
+ for (; o = n$1.pop();) try {
2651
+ if (!o.a && 1 === s) return s = 0, n$1.push(o), Promise.resolve().then(next);
2652
+ if (o.d) {
2653
+ var r$1 = o.d.call(o.v);
2654
+ if (o.a) return s |= 2, Promise.resolve(r$1).then(next, err);
2655
+ } else s |= 1;
2656
+ } catch (r$2) {
2657
+ return err(r$2);
2658
+ }
2659
+ if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
2660
+ if (t !== e) throw t;
2661
+ }
2662
+ function err(n$2) {
2663
+ return t = t !== e ? new r(n$2, t) : n$2, next();
2664
+ }
2665
+ return next();
2666
+ }
2667
+ };
2668
+ }
2669
+ function unreachable(value) {
2670
+ throw new Error(`Unreachable code reached with value: ${value}`);
2671
+ }
2672
+ async function getFileModifiedTime(filePath) {
2673
+ return pipe(try_({
2674
+ try: stat(filePath),
2675
+ catch: (error) => error
2676
+ }), map((stats) => stats.mtime.getTime()), unwrap(0));
2677
+ }
2678
+ function createDateFormatter(timezone, locale) {
2679
+ return new Intl.DateTimeFormat(locale, {
2680
+ year: "numeric",
2681
+ month: "2-digit",
2682
+ day: "2-digit",
2683
+ timeZone: timezone
2684
+ });
2685
+ }
2686
+ function createDatePartsFormatter(timezone, locale) {
2687
+ return new Intl.DateTimeFormat(locale, {
2688
+ year: "numeric",
2689
+ month: "2-digit",
2690
+ day: "2-digit",
2691
+ timeZone: timezone
2692
+ });
2693
+ }
2694
+ function formatDate(dateStr, timezone, locale) {
2695
+ const date = new Date(dateStr);
2696
+ return createDateFormatter(timezone, locale ?? DEFAULT_LOCALE).format(date);
2697
+ }
2698
+ function formatDateCompact(dateStr, timezone, locale) {
2699
+ const date = safeParse(dailyDateSchema, dateStr).success ? timezone != null ? /* @__PURE__ */ new Date(`${dateStr}T00:00:00Z`) : /* @__PURE__ */ new Date(`${dateStr}T00:00:00`) : new Date(dateStr);
2700
+ const parts = createDatePartsFormatter(timezone, locale).formatToParts(date);
2701
+ const year = parts.find((p) => p.type === "year")?.value ?? "";
2702
+ const month = parts.find((p) => p.type === "month")?.value ?? "";
2703
+ const day = parts.find((p) => p.type === "day")?.value ?? "";
2704
+ return `${year}\n${month}-${day}`;
2705
+ }
2706
+ function sortByDate(items, getDate, order = "desc") {
2707
+ const sorted = sort(items);
2708
+ switch (order) {
2709
+ case "desc": return sorted.desc((item) => new Date(getDate(item)).getTime());
2710
+ case "asc": return sorted.asc((item) => new Date(getDate(item)).getTime());
2711
+ default: unreachable(order);
2712
+ }
2713
+ }
2714
+ function filterByDateRange(items, getDate, since, until) {
2715
+ if (since == null && until == null) return items;
2716
+ return items.filter((item) => {
2717
+ const dateStr = getDate(item).substring(0, 10).replace(/-/g, "");
2718
+ if (since != null && dateStr < since) return false;
2719
+ if (until != null && dateStr > until) return false;
2720
+ return true;
2721
+ });
2722
+ }
2723
+ function getDateWeek(date, startDay) {
2724
+ const d$1 = new Date(date);
2725
+ const shift = (d$1.getDay() - startDay + 7) % 7;
2726
+ d$1.setDate(d$1.getDate() - shift);
2727
+ return createWeeklyDate(d$1.toISOString().substring(0, 10));
2728
+ }
2729
+ function getDayNumber(day) {
2730
+ return {
2731
+ sunday: 0,
2732
+ monday: 1,
2733
+ tuesday: 2,
2734
+ wednesday: 3,
2735
+ thursday: 4,
2736
+ friday: 5,
2737
+ saturday: 6
2738
+ }[day];
2739
+ }
2740
+ const LITELLM_PRICING_URL = "https://raw.githubusercontent.com/BerriAI/litellm/main/model_prices_and_context_window.json";
2741
+ const DEFAULT_TIERED_THRESHOLD = 2e5;
2742
+ const liteLLMModelPricingSchema = object({
2743
+ input_cost_per_token: optional(number()),
2744
+ output_cost_per_token: optional(number()),
2745
+ cache_creation_input_token_cost: optional(number()),
2746
+ cache_read_input_token_cost: optional(number()),
2747
+ max_tokens: optional(number()),
2748
+ max_input_tokens: optional(number()),
2749
+ max_output_tokens: optional(number()),
2750
+ input_cost_per_token_above_200k_tokens: optional(number()),
2751
+ output_cost_per_token_above_200k_tokens: optional(number()),
2752
+ cache_creation_input_token_cost_above_200k_tokens: optional(number()),
2753
+ cache_read_input_token_cost_above_200k_tokens: optional(number()),
2754
+ input_cost_per_token_above_128k_tokens: optional(number()),
2755
+ output_cost_per_token_above_128k_tokens: optional(number())
2756
+ });
2757
+ const DEFAULT_PROVIDER_PREFIXES = [
2758
+ "anthropic/",
2759
+ "claude-3-5-",
2760
+ "claude-3-",
2761
+ "claude-",
2762
+ "openai/",
2763
+ "azure/",
2764
+ "openrouter/openai/"
2765
+ ];
2766
+ function createLogger(logger$1) {
2767
+ if (logger$1 != null) return logger$1;
2768
+ return {
2769
+ debug: () => {},
2770
+ error: () => {},
2771
+ info: () => {},
2772
+ warn: () => {}
2773
+ };
2774
+ }
2775
+ var LiteLLMPricingFetcher = class {
2776
+ cachedPricing = null;
2777
+ logger;
2778
+ offline;
2779
+ offlineLoader;
2780
+ url;
2781
+ providerPrefixes;
2782
+ constructor(options = {}) {
2783
+ this.logger = createLogger(options.logger);
2784
+ this.offline = Boolean(options.offline);
2785
+ this.offlineLoader = options.offlineLoader;
2786
+ this.url = options.url ?? LITELLM_PRICING_URL;
2787
+ this.providerPrefixes = options.providerPrefixes ?? DEFAULT_PROVIDER_PREFIXES;
2788
+ }
2789
+ [Symbol.dispose]() {
2790
+ this.clearCache();
2791
+ }
2792
+ clearCache() {
2793
+ this.cachedPricing = null;
2794
+ }
2795
+ loadOfflinePricing = try_({
2796
+ try: async () => {
2797
+ if (this.offlineLoader == null) throw new Error("Offline loader was not provided");
2798
+ const pricing = new Map(Object.entries(await this.offlineLoader()));
2799
+ this.cachedPricing = pricing;
2800
+ return pricing;
2801
+ },
2802
+ catch: (error) => new Error("Failed to load offline pricing data", { cause: error })
2803
+ });
2804
+ async handleFallbackToCachedPricing(originalError) {
2805
+ this.logger.warn("Failed to fetch model pricing from LiteLLM, falling back to cached pricing data");
2806
+ this.logger.debug("Fetch error details:", originalError);
2807
+ return pipe(this.loadOfflinePricing(), inspect((pricing) => {
2808
+ this.logger.info(`Using cached pricing data for ${pricing.size} models`);
2809
+ }), inspectError((error) => {
2810
+ this.logger.error("Failed to load cached pricing data as fallback:", error);
2811
+ this.logger.error("Original fetch error:", originalError);
2812
+ }));
2813
+ }
2814
+ async ensurePricingLoaded() {
2815
+ return pipe(this.cachedPricing != null ? succeed(this.cachedPricing) : fail(/* @__PURE__ */ new Error("Cached pricing not available")), orElse(async () => {
2816
+ if (this.offline) return this.loadOfflinePricing();
2817
+ this.logger.warn("Fetching latest model pricing from LiteLLM...");
2818
+ return pipe(try_({
2819
+ try: fetch(this.url),
2820
+ catch: (error) => new Error("Failed to fetch model pricing from LiteLLM", { cause: error })
2821
+ }), andThrough((response) => {
2822
+ if (!response.ok) return fail(/* @__PURE__ */ new Error(`Failed to fetch pricing data: ${response.statusText}`));
2823
+ return succeed();
2824
+ }), andThen(async (response) => try_({
2825
+ try: response.json(),
2826
+ catch: (error) => new Error("Failed to parse pricing data", { cause: error })
2827
+ })), map((data) => {
2828
+ const pricing = /* @__PURE__ */ new Map();
2829
+ for (const [modelName, modelData] of Object.entries(data)) {
2830
+ if (typeof modelData !== "object" || modelData == null) continue;
2831
+ const parsed = safeParse(liteLLMModelPricingSchema, modelData);
2832
+ if (!parsed.success) continue;
2833
+ pricing.set(modelName, parsed.output);
2834
+ }
2835
+ return pricing;
2836
+ }), inspect((pricing) => {
2837
+ this.cachedPricing = pricing;
2838
+ this.logger.info(`Loaded pricing for ${pricing.size} models`);
2839
+ }), orElse(async (error) => this.handleFallbackToCachedPricing(error)));
2840
+ }));
2841
+ }
2842
+ async fetchModelPricing() {
2843
+ return this.ensurePricingLoaded();
2844
+ }
2845
+ createMatchingCandidates(modelName) {
2846
+ const candidates = /* @__PURE__ */ new Set();
2847
+ candidates.add(modelName);
2848
+ for (const prefix of this.providerPrefixes) candidates.add(`${prefix}${modelName}`);
2849
+ return Array.from(candidates);
2850
+ }
2851
+ async getModelPricing(modelName) {
2852
+ return pipe(this.ensurePricingLoaded(), map((pricing) => {
2853
+ for (const candidate of this.createMatchingCandidates(modelName)) {
2854
+ const direct = pricing.get(candidate);
2855
+ if (direct != null) return direct;
2856
+ }
2857
+ const lower = modelName.toLowerCase();
2858
+ for (const [key, value] of pricing) {
2859
+ const comparison = key.toLowerCase();
2860
+ if (comparison.includes(lower) || lower.includes(comparison)) return value;
2861
+ }
2862
+ return null;
2863
+ }));
2864
+ }
2865
+ async getModelContextLimit(modelName) {
2866
+ return pipe(this.getModelPricing(modelName), map((pricing) => pricing?.max_input_tokens ?? null));
2867
+ }
2868
+ calculateCostFromPricing(tokens, pricing) {
2869
+ const calculateTieredCost = (totalTokens, basePrice, tieredPrice, threshold = DEFAULT_TIERED_THRESHOLD) => {
2870
+ if (totalTokens == null || totalTokens <= 0) return 0;
2871
+ if (totalTokens > threshold && tieredPrice != null) {
2872
+ const tokensBelowThreshold = Math.min(totalTokens, threshold);
2873
+ let tieredCost = Math.max(0, totalTokens - threshold) * tieredPrice;
2874
+ if (basePrice != null) tieredCost += tokensBelowThreshold * basePrice;
2875
+ return tieredCost;
2876
+ }
2877
+ if (basePrice != null) return totalTokens * basePrice;
2878
+ return 0;
2879
+ };
2880
+ const inputCost = calculateTieredCost(tokens.input_tokens, pricing.input_cost_per_token, pricing.input_cost_per_token_above_200k_tokens);
2881
+ const outputCost = calculateTieredCost(tokens.output_tokens, pricing.output_cost_per_token, pricing.output_cost_per_token_above_200k_tokens);
2882
+ const cacheCreationCost = calculateTieredCost(tokens.cache_creation_input_tokens, pricing.cache_creation_input_token_cost, pricing.cache_creation_input_token_cost_above_200k_tokens);
2883
+ const cacheReadCost = calculateTieredCost(tokens.cache_read_input_tokens, pricing.cache_read_input_token_cost, pricing.cache_read_input_token_cost_above_200k_tokens);
2884
+ return inputCost + outputCost + cacheCreationCost + cacheReadCost;
2885
+ }
2886
+ async calculateCostFromTokens(tokens, modelName) {
2887
+ if (modelName == null || modelName === "") return succeed(0);
2888
+ return pipe(this.getModelPricing(modelName), andThen((pricing) => {
2889
+ if (pricing == null) return fail(/* @__PURE__ */ new Error(`Model pricing not found for ${modelName}`));
2890
+ return succeed(this.calculateCostFromPricing(tokens, pricing));
2891
+ }));
2892
+ }
2893
+ };
2894
+ function createPricingDataset() {
2895
+ return Object.create(null);
2896
+ }
2897
+ async function fetchLiteLLMPricingDataset() {
2898
+ const response = await fetch(LITELLM_PRICING_URL);
2899
+ if (!response.ok) throw new Error(`Failed to fetch pricing data: ${response.status} ${response.statusText}`);
2900
+ const rawDataset = await response.json();
2901
+ const dataset = createPricingDataset();
2902
+ for (const [modelName, modelData] of Object.entries(rawDataset)) {
2903
+ if (modelData == null || typeof modelData !== "object") continue;
2904
+ const parsed = safeParse(liteLLMModelPricingSchema, modelData);
2905
+ if (!parsed.success) continue;
2906
+ dataset[modelName] = parsed.output;
2907
+ }
2908
+ return dataset;
2909
+ }
2910
+ function filterPricingDataset(dataset, predicate) {
2911
+ const filtered = createPricingDataset();
2912
+ for (const [modelName, pricing] of Object.entries(dataset)) if (predicate(modelName, pricing)) filtered[modelName] = pricing;
2913
+ return filtered;
2914
+ }
2915
+ function isClaudeModel(modelName, _pricing) {
2916
+ return modelName.startsWith("claude-");
2917
+ }
2918
+ async function prefetchClaudePricing() {
2919
+ if (process$1.env.OFFLINE === "true") return createPricingDataset();
2920
+ try {
2921
+ const dataset = await fetchLiteLLMPricingDataset();
2922
+ return filterPricingDataset(dataset, isClaudeModel);
2923
+ } catch (error) {
2924
+ console.warn("Failed to prefetch Claude pricing data, proceeding with empty cache.", error);
2925
+ return createPricingDataset();
2926
+ }
2927
+ }
2928
+ const CLAUDE_PROVIDER_PREFIXES = [
2929
+ "anthropic/",
2930
+ "claude-3-5-",
2931
+ "claude-3-",
2932
+ "claude-",
2933
+ "openrouter/openai/"
2934
+ ];
2935
+ const PREFETCHED_CLAUDE_PRICING = prefetchClaudePricing();
2936
+ var PricingFetcher = class extends LiteLLMPricingFetcher {
2937
+ constructor(offline = false) {
2938
+ super({
2939
+ offline,
2940
+ offlineLoader: async () => PREFETCHED_CLAUDE_PRICING,
2941
+ logger,
2942
+ providerPrefixes: CLAUDE_PROVIDER_PREFIXES
2943
+ });
2944
+ }
2945
+ };
2946
+ const DEFAULT_SESSION_DURATION_HOURS = 5;
2947
+ function floorToHour(timestamp) {
2948
+ const floored = new Date(timestamp);
2949
+ floored.setUTCMinutes(0, 0, 0);
2950
+ return floored;
2951
+ }
2952
+ function identifySessionBlocks(entries, sessionDurationHours = DEFAULT_SESSION_DURATION_HOURS) {
2953
+ if (entries.length === 0) return [];
2954
+ const sessionDurationMs = sessionDurationHours * 60 * 60 * 1e3;
2955
+ const blocks = [];
2956
+ const sortedEntries = [...entries].sort((a$1, b$1) => a$1.timestamp.getTime() - b$1.timestamp.getTime());
2957
+ let currentBlockStart = null;
2958
+ let currentBlockEntries = [];
2959
+ const now = /* @__PURE__ */ new Date();
2960
+ for (const entry of sortedEntries) {
2961
+ const entryTime = entry.timestamp;
2962
+ if (currentBlockStart == null) {
2963
+ currentBlockStart = floorToHour(entryTime);
2964
+ currentBlockEntries = [entry];
2965
+ } else {
2966
+ const timeSinceBlockStart = entryTime.getTime() - currentBlockStart.getTime();
2967
+ const lastEntry = currentBlockEntries.at(-1);
2968
+ if (lastEntry == null) continue;
2969
+ const lastEntryTime = lastEntry.timestamp;
2970
+ const timeSinceLastEntry = entryTime.getTime() - lastEntryTime.getTime();
2971
+ if (timeSinceBlockStart > sessionDurationMs || timeSinceLastEntry > sessionDurationMs) {
2972
+ const block = createBlock(currentBlockStart, currentBlockEntries, now, sessionDurationMs);
2973
+ blocks.push(block);
2974
+ if (timeSinceLastEntry > sessionDurationMs) {
2975
+ const gapBlock = createGapBlock(lastEntryTime, entryTime, sessionDurationMs);
2976
+ if (gapBlock != null) blocks.push(gapBlock);
2977
+ }
2978
+ currentBlockStart = floorToHour(entryTime);
2979
+ currentBlockEntries = [entry];
2980
+ } else currentBlockEntries.push(entry);
2981
+ }
2982
+ }
2983
+ if (currentBlockStart != null && currentBlockEntries.length > 0) {
2984
+ const block = createBlock(currentBlockStart, currentBlockEntries, now, sessionDurationMs);
2985
+ blocks.push(block);
2986
+ }
2987
+ return blocks;
2988
+ }
2989
+ function createBlock(startTime, entries, now, sessionDurationMs) {
2990
+ const endTime = new Date(startTime.getTime() + sessionDurationMs);
2991
+ const lastEntry = entries[entries.length - 1];
2992
+ const actualEndTime = lastEntry != null ? lastEntry.timestamp : startTime;
2993
+ const isActive = now.getTime() - actualEndTime.getTime() < sessionDurationMs && now < endTime;
2994
+ const tokenCounts = {
2995
+ inputTokens: 0,
2996
+ outputTokens: 0,
2997
+ cacheCreationInputTokens: 0,
2998
+ cacheReadInputTokens: 0
2999
+ };
3000
+ let costUSD = 0;
3001
+ const models = [];
3002
+ let usageLimitResetTime;
3003
+ for (const entry of entries) {
3004
+ tokenCounts.inputTokens += entry.usage.inputTokens;
3005
+ tokenCounts.outputTokens += entry.usage.outputTokens;
3006
+ tokenCounts.cacheCreationInputTokens += entry.usage.cacheCreationInputTokens;
3007
+ tokenCounts.cacheReadInputTokens += entry.usage.cacheReadInputTokens;
3008
+ costUSD += entry.costUSD ?? 0;
3009
+ usageLimitResetTime = entry.usageLimitResetTime ?? usageLimitResetTime;
3010
+ models.push(entry.model);
3011
+ }
3012
+ return {
3013
+ id: startTime.toISOString(),
3014
+ startTime,
3015
+ endTime,
3016
+ actualEndTime,
3017
+ isActive,
3018
+ entries,
3019
+ tokenCounts,
3020
+ costUSD,
3021
+ models: uniq(models),
3022
+ usageLimitResetTime
3023
+ };
3024
+ }
3025
+ function createGapBlock(lastActivityTime, nextActivityTime, sessionDurationMs) {
3026
+ if (nextActivityTime.getTime() - lastActivityTime.getTime() <= sessionDurationMs) return null;
3027
+ const gapStart = new Date(lastActivityTime.getTime() + sessionDurationMs);
3028
+ const gapEnd = nextActivityTime;
3029
+ return {
3030
+ id: `gap-${gapStart.toISOString()}`,
3031
+ startTime: gapStart,
3032
+ endTime: gapEnd,
3033
+ isActive: false,
3034
+ isGap: true,
3035
+ entries: [],
3036
+ tokenCounts: {
3037
+ inputTokens: 0,
3038
+ outputTokens: 0,
3039
+ cacheCreationInputTokens: 0,
3040
+ cacheReadInputTokens: 0
3041
+ },
3042
+ costUSD: 0,
3043
+ models: []
3044
+ };
3045
+ }
3046
+ function calculateBurnRate(block) {
3047
+ if (block.entries.length === 0 || (block.isGap ?? false)) return null;
3048
+ const firstEntryData = block.entries[0];
3049
+ const lastEntryData = block.entries[block.entries.length - 1];
3050
+ if (firstEntryData == null || lastEntryData == null) return null;
3051
+ const firstEntry = firstEntryData.timestamp;
3052
+ const durationMinutes = (lastEntryData.timestamp.getTime() - firstEntry.getTime()) / (1e3 * 60);
3053
+ if (durationMinutes <= 0) return null;
3054
+ const tokensPerMinute = getTotalTokens(block.tokenCounts) / durationMinutes;
3055
+ const tokensPerMinuteForIndicator = ((block.tokenCounts.inputTokens ?? 0) + (block.tokenCounts.outputTokens ?? 0)) / durationMinutes;
3056
+ const costPerHour = block.costUSD / durationMinutes * 60;
3057
+ return {
3058
+ tokensPerMinute,
3059
+ tokensPerMinuteForIndicator,
3060
+ costPerHour
3061
+ };
3062
+ }
3063
+ function projectBlockUsage(block) {
3064
+ if (!block.isActive || (block.isGap ?? false)) return null;
3065
+ const burnRate = calculateBurnRate(block);
3066
+ if (burnRate == null) return null;
3067
+ const now = /* @__PURE__ */ new Date();
3068
+ const remainingTime = block.endTime.getTime() - now.getTime();
3069
+ const remainingMinutes = Math.max(0, remainingTime / (1e3 * 60));
3070
+ const currentTokens = getTotalTokens(block.tokenCounts);
3071
+ const projectedAdditionalTokens = burnRate.tokensPerMinute * remainingMinutes;
3072
+ const totalTokens = currentTokens + projectedAdditionalTokens;
3073
+ const projectedAdditionalCost = burnRate.costPerHour / 60 * remainingMinutes;
3074
+ const totalCost = block.costUSD + projectedAdditionalCost;
3075
+ return {
3076
+ totalTokens: Math.round(totalTokens),
3077
+ totalCost: Math.round(totalCost * 100) / 100,
3078
+ remainingMinutes: Math.round(remainingMinutes)
3079
+ };
3080
+ }
3081
+ function filterRecentBlocks(blocks, days = DEFAULT_RECENT_DAYS) {
3082
+ const now = /* @__PURE__ */ new Date();
3083
+ const cutoffTime = /* @__PURE__ */ new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
3084
+ return blocks.filter((block) => {
3085
+ return block.startTime >= cutoffTime || block.isActive;
3086
+ });
3087
+ }
3088
+ function getClaudePaths() {
3089
+ const paths = [];
3090
+ const normalizedPaths = /* @__PURE__ */ new Set();
3091
+ const envPaths = (process$1.env[CLAUDE_CONFIG_DIR_ENV] ?? "").trim();
3092
+ if (envPaths !== "") {
3093
+ const envPathList = envPaths.split(",").map((p) => p.trim()).filter((p) => p !== "");
3094
+ for (const envPath of envPathList) {
3095
+ const normalizedPath = path.resolve(envPath);
3096
+ if (isDirectorySync(normalizedPath)) {
3097
+ const projectsPath = path.join(normalizedPath, CLAUDE_PROJECTS_DIR_NAME);
3098
+ if (isDirectorySync(projectsPath)) {
3099
+ if (!normalizedPaths.has(normalizedPath)) {
3100
+ normalizedPaths.add(normalizedPath);
3101
+ paths.push(normalizedPath);
3102
+ }
3103
+ }
3104
+ }
3105
+ }
3106
+ if (paths.length > 0) return paths;
3107
+ throw new Error(`No valid Claude data directories found in CLAUDE_CONFIG_DIR. Please ensure the following exists:
3108
+ - ${envPaths}/${CLAUDE_PROJECTS_DIR_NAME}`.trim());
3109
+ }
3110
+ const defaultPaths = [DEFAULT_CLAUDE_CONFIG_PATH, path.join(USER_HOME_DIR, DEFAULT_CLAUDE_CODE_PATH)];
3111
+ for (const defaultPath of defaultPaths) {
3112
+ const normalizedPath = path.resolve(defaultPath);
3113
+ if (isDirectorySync(normalizedPath)) {
3114
+ const projectsPath = path.join(normalizedPath, CLAUDE_PROJECTS_DIR_NAME);
3115
+ if (isDirectorySync(projectsPath)) {
3116
+ if (!normalizedPaths.has(normalizedPath)) {
3117
+ normalizedPaths.add(normalizedPath);
3118
+ paths.push(normalizedPath);
3119
+ }
3120
+ }
3121
+ }
3122
+ }
3123
+ if (paths.length === 0) throw new Error(`No valid Claude data directories found. Please ensure at least one of the following exists:
3124
+ - ${path.join(DEFAULT_CLAUDE_CONFIG_PATH, CLAUDE_PROJECTS_DIR_NAME)}
3125
+ - ${path.join(USER_HOME_DIR, DEFAULT_CLAUDE_CODE_PATH, CLAUDE_PROJECTS_DIR_NAME)}
3126
+ - Or set ${CLAUDE_CONFIG_DIR_ENV} environment variable to valid directory path(s) containing a '${CLAUDE_PROJECTS_DIR_NAME}' subdirectory`.trim());
3127
+ return paths;
3128
+ }
3129
+ function extractProjectFromPath(jsonlPath) {
3130
+ const segments = jsonlPath.replace(/[/\\]/g, path.sep).split(path.sep);
3131
+ const projectsIndex = segments.findIndex((segment) => segment === CLAUDE_PROJECTS_DIR_NAME);
3132
+ if (projectsIndex === -1 || projectsIndex + 1 >= segments.length) return "unknown";
3133
+ const projectName = segments[projectsIndex + 1];
3134
+ return projectName != null && projectName.trim() !== "" ? projectName : "unknown";
3135
+ }
3136
+ const usageDataSchema = object({
3137
+ cwd: optional(string()),
3138
+ sessionId: optional(sessionIdSchema),
3139
+ timestamp: isoTimestampSchema,
3140
+ version: optional(versionSchema),
3141
+ message: object({
3142
+ usage: object({
3143
+ input_tokens: number(),
3144
+ output_tokens: number(),
3145
+ cache_creation_input_tokens: optional(number()),
3146
+ cache_read_input_tokens: optional(number())
3147
+ }),
3148
+ model: optional(modelNameSchema),
3149
+ id: optional(messageIdSchema),
3150
+ content: optional(array(object({ text: optional(string()) })))
3151
+ }),
3152
+ costUSD: optional(number()),
3153
+ requestId: optional(requestIdSchema),
3154
+ isApiErrorMessage: optional(boolean())
3155
+ });
3156
+ const transcriptUsageSchema = object({
3157
+ input_tokens: optional(number()),
3158
+ cache_creation_input_tokens: optional(number()),
3159
+ cache_read_input_tokens: optional(number()),
3160
+ output_tokens: optional(number())
3161
+ });
3162
+ const transcriptMessageSchema = object({
3163
+ type: optional(string()),
3164
+ message: optional(object({ usage: optional(transcriptUsageSchema) }))
3165
+ });
3166
+ const modelBreakdownSchema = object({
3167
+ modelName: modelNameSchema,
3168
+ inputTokens: number(),
3169
+ outputTokens: number(),
3170
+ cacheCreationTokens: number(),
3171
+ cacheReadTokens: number(),
3172
+ cost: number()
3173
+ });
3174
+ const dailyUsageSchema = object({
3175
+ date: dailyDateSchema,
3176
+ inputTokens: number(),
3177
+ outputTokens: number(),
3178
+ cacheCreationTokens: number(),
3179
+ cacheReadTokens: number(),
3180
+ totalCost: number(),
3181
+ modelsUsed: array(modelNameSchema),
3182
+ modelBreakdowns: array(modelBreakdownSchema),
3183
+ project: optional(string())
3184
+ });
3185
+ const sessionUsageSchema = object({
3186
+ sessionId: sessionIdSchema,
3187
+ projectPath: projectPathSchema,
3188
+ inputTokens: number(),
3189
+ outputTokens: number(),
3190
+ cacheCreationTokens: number(),
3191
+ cacheReadTokens: number(),
3192
+ totalCost: number(),
3193
+ lastActivity: activityDateSchema,
3194
+ versions: array(versionSchema),
3195
+ modelsUsed: array(modelNameSchema),
3196
+ modelBreakdowns: array(modelBreakdownSchema)
3197
+ });
3198
+ const monthlyUsageSchema = object({
3199
+ month: monthlyDateSchema,
3200
+ inputTokens: number(),
3201
+ outputTokens: number(),
3202
+ cacheCreationTokens: number(),
3203
+ cacheReadTokens: number(),
3204
+ totalCost: number(),
3205
+ modelsUsed: array(modelNameSchema),
3206
+ modelBreakdowns: array(modelBreakdownSchema),
3207
+ project: optional(string())
3208
+ });
3209
+ const weeklyUsageSchema = object({
3210
+ week: weeklyDateSchema,
3211
+ inputTokens: number(),
3212
+ outputTokens: number(),
3213
+ cacheCreationTokens: number(),
3214
+ cacheReadTokens: number(),
3215
+ totalCost: number(),
3216
+ modelsUsed: array(modelNameSchema),
3217
+ modelBreakdowns: array(modelBreakdownSchema),
3218
+ project: optional(string())
3219
+ });
3220
+ const bucketUsageSchema = object({
3221
+ bucket: union([weeklyDateSchema, monthlyDateSchema]),
3222
+ inputTokens: number(),
3223
+ outputTokens: number(),
3224
+ cacheCreationTokens: number(),
3225
+ cacheReadTokens: number(),
3226
+ totalCost: number(),
3227
+ modelsUsed: array(modelNameSchema),
3228
+ modelBreakdowns: array(modelBreakdownSchema),
3229
+ project: optional(string())
3230
+ });
3231
+ function aggregateByModel(entries, getModel, getUsage, getCost) {
3232
+ const modelAggregates = /* @__PURE__ */ new Map();
3233
+ const defaultStats = {
3234
+ inputTokens: 0,
3235
+ outputTokens: 0,
3236
+ cacheCreationTokens: 0,
3237
+ cacheReadTokens: 0,
3238
+ cost: 0
3239
+ };
3240
+ for (const entry of entries) {
3241
+ const modelName = getModel(entry) ?? "unknown";
3242
+ if (modelName === "<synthetic>") continue;
3243
+ const usage = getUsage(entry);
3244
+ const cost = getCost(entry);
3245
+ const existing = modelAggregates.get(modelName) ?? defaultStats;
3246
+ modelAggregates.set(modelName, {
3247
+ inputTokens: existing.inputTokens + (usage.input_tokens ?? 0),
3248
+ outputTokens: existing.outputTokens + (usage.output_tokens ?? 0),
3249
+ cacheCreationTokens: existing.cacheCreationTokens + (usage.cache_creation_input_tokens ?? 0),
3250
+ cacheReadTokens: existing.cacheReadTokens + (usage.cache_read_input_tokens ?? 0),
3251
+ cost: existing.cost + cost
3252
+ });
3253
+ }
3254
+ return modelAggregates;
3255
+ }
3256
+ function aggregateModelBreakdowns(breakdowns) {
3257
+ const modelAggregates = /* @__PURE__ */ new Map();
3258
+ const defaultStats = {
3259
+ inputTokens: 0,
3260
+ outputTokens: 0,
3261
+ cacheCreationTokens: 0,
3262
+ cacheReadTokens: 0,
3263
+ cost: 0
3264
+ };
3265
+ for (const breakdown of breakdowns) {
3266
+ if (breakdown.modelName === "<synthetic>") continue;
3267
+ const existing = modelAggregates.get(breakdown.modelName) ?? defaultStats;
3268
+ modelAggregates.set(breakdown.modelName, {
3269
+ inputTokens: existing.inputTokens + breakdown.inputTokens,
3270
+ outputTokens: existing.outputTokens + breakdown.outputTokens,
3271
+ cacheCreationTokens: existing.cacheCreationTokens + breakdown.cacheCreationTokens,
3272
+ cacheReadTokens: existing.cacheReadTokens + breakdown.cacheReadTokens,
3273
+ cost: existing.cost + breakdown.cost
3274
+ });
3275
+ }
3276
+ return modelAggregates;
3277
+ }
3278
+ function createModelBreakdowns(modelAggregates) {
3279
+ return Array.from(modelAggregates.entries()).map(([modelName, stats]) => ({
3280
+ modelName,
3281
+ ...stats
3282
+ })).sort((a$1, b$1) => b$1.cost - a$1.cost);
3283
+ }
3284
+ function calculateTotals(entries, getUsage, getCost) {
3285
+ return entries.reduce((acc, entry) => {
3286
+ const usage = getUsage(entry);
3287
+ const cost = getCost(entry);
3288
+ return {
3289
+ inputTokens: acc.inputTokens + (usage.input_tokens ?? 0),
3290
+ outputTokens: acc.outputTokens + (usage.output_tokens ?? 0),
3291
+ cacheCreationTokens: acc.cacheCreationTokens + (usage.cache_creation_input_tokens ?? 0),
3292
+ cacheReadTokens: acc.cacheReadTokens + (usage.cache_read_input_tokens ?? 0),
3293
+ cost: acc.cost + cost,
3294
+ totalCost: acc.totalCost + cost
3295
+ };
3296
+ }, {
3297
+ inputTokens: 0,
3298
+ outputTokens: 0,
3299
+ cacheCreationTokens: 0,
3300
+ cacheReadTokens: 0,
3301
+ cost: 0,
3302
+ totalCost: 0
3303
+ });
3304
+ }
3305
+ function filterByProject(items, getProject, projectFilter) {
3306
+ if (projectFilter == null) return items;
3307
+ return items.filter((item) => {
3308
+ return getProject(item) === projectFilter;
3309
+ });
3310
+ }
3311
+ function isDuplicateEntry(uniqueHash, processedHashes) {
3312
+ if (uniqueHash == null) return false;
3313
+ return processedHashes.has(uniqueHash);
3314
+ }
3315
+ function markAsProcessed(uniqueHash, processedHashes) {
3316
+ if (uniqueHash != null) processedHashes.add(uniqueHash);
3317
+ }
3318
+ function extractUniqueModels(entries, getModel) {
3319
+ return uniq(entries.map(getModel).filter((m$1) => m$1 != null && m$1 !== "<synthetic>"));
3320
+ }
3321
+ function createUniqueHash(data) {
3322
+ const messageId = data.message.id;
3323
+ const requestId = data.requestId;
3324
+ if (messageId == null || requestId == null) return null;
3325
+ return `${messageId}:${requestId}`;
3326
+ }
3327
+ async function getEarliestTimestamp(filePath) {
3328
+ try {
3329
+ const lines = (await readFile(filePath, "utf-8")).trim().split("\n");
3330
+ let earliestDate = null;
3331
+ for (const line of lines) {
3332
+ if (line.trim() === "") continue;
3333
+ try {
3334
+ const json = JSON.parse(line);
3335
+ if (json.timestamp != null && typeof json.timestamp === "string") {
3336
+ const date = new Date(json.timestamp);
3337
+ if (!Number.isNaN(date.getTime())) {
3338
+ if (earliestDate == null || date < earliestDate) earliestDate = date;
3339
+ }
3340
+ }
3341
+ } catch {
3342
+ continue;
3343
+ }
3344
+ }
3345
+ return earliestDate;
3346
+ } catch (error) {
3347
+ logger.debug(`Failed to get earliest timestamp for ${filePath}:`, error);
3348
+ return null;
3349
+ }
3350
+ }
3351
+ async function sortFilesByTimestamp(files) {
3352
+ return (await Promise.all(files.map(async (file) => ({
3353
+ file,
3354
+ timestamp: await getEarliestTimestamp(file)
3355
+ })))).sort((a$1, b$1) => {
3356
+ if (a$1.timestamp == null && b$1.timestamp == null) return 0;
3357
+ if (a$1.timestamp == null) return 1;
3358
+ if (b$1.timestamp == null) return -1;
3359
+ return a$1.timestamp.getTime() - b$1.timestamp.getTime();
3360
+ }).map((item) => item.file);
3361
+ }
3362
+ async function calculateCostForEntry(data, mode, fetcher) {
3363
+ if (mode === "display") return data.costUSD ?? 0;
3364
+ if (mode === "calculate") {
3365
+ if (data.message.model != null) return unwrap(fetcher.calculateCostFromTokens(data.message.usage, data.message.model), 0);
3366
+ return 0;
3367
+ }
3368
+ if (mode === "auto") {
3369
+ if (data.costUSD != null) return data.costUSD;
3370
+ if (data.message.model != null) return unwrap(fetcher.calculateCostFromTokens(data.message.usage, data.message.model), 0);
3371
+ return 0;
3372
+ }
3373
+ unreachable(mode);
3374
+ }
3375
+ function getUsageLimitResetTime(data) {
3376
+ let resetTime = null;
3377
+ if (data.isApiErrorMessage === true) {
3378
+ const timestampMatch = data.message?.content?.find((c) => c.text != null && c.text.includes("Claude AI usage limit reached"))?.text?.match(/\|(\d+)/) ?? null;
3379
+ if (timestampMatch?.[1] != null) {
3380
+ const resetTimestamp = Number.parseInt(timestampMatch[1]);
3381
+ resetTime = resetTimestamp > 0 ? /* @__PURE__ */ new Date(resetTimestamp * 1e3) : null;
3382
+ }
3383
+ }
3384
+ return resetTime;
3385
+ }
3386
+ async function globUsageFiles(claudePaths) {
3387
+ const filePromises = claudePaths.map(async (claudePath) => {
3388
+ const claudeDir = path.join(claudePath, CLAUDE_PROJECTS_DIR_NAME);
3389
+ return (await glob([USAGE_DATA_GLOB_PATTERN], {
3390
+ cwd: claudeDir,
3391
+ absolute: true
3392
+ }).catch(() => [])).map((file) => ({
3393
+ file,
3394
+ baseDir: claudeDir
3395
+ }));
3396
+ });
3397
+ return (await Promise.all(filePromises)).flat();
3398
+ }
3399
+ async function loadDailyUsageData(options) {
3400
+ try {
3401
+ var _usingCtx$1 = _usingCtx();
3402
+ const claudePaths = toArray(options?.claudePath ?? getClaudePaths());
3403
+ const fileList = (await globUsageFiles(claudePaths)).map((f$1) => f$1.file);
3404
+ if (fileList.length === 0) return [];
3405
+ const projectFilteredFiles = filterByProject(fileList, (filePath) => extractProjectFromPath(filePath), options?.project);
3406
+ const sortedFiles = await sortFilesByTimestamp(projectFilteredFiles);
3407
+ const mode = options?.mode ?? "auto";
3408
+ const fetcher = _usingCtx$1.u(mode === "display" ? null : new PricingFetcher(options?.offline));
3409
+ const processedHashes = /* @__PURE__ */ new Set();
3410
+ const allEntries = [];
3411
+ for (const file of sortedFiles) {
3412
+ const lines = (await readFile(file, "utf-8")).trim().split("\n").filter((line) => line.length > 0);
3413
+ for (const line of lines) try {
3414
+ const parsed = JSON.parse(line);
3415
+ const result = safeParse(usageDataSchema, parsed);
3416
+ if (!result.success) continue;
3417
+ const data = result.output;
3418
+ const uniqueHash = createUniqueHash(data);
3419
+ if (isDuplicateEntry(uniqueHash, processedHashes)) continue;
3420
+ markAsProcessed(uniqueHash, processedHashes);
3421
+ const date = formatDate(data.timestamp, options?.timezone, DEFAULT_LOCALE);
3422
+ const cost = fetcher != null ? await calculateCostForEntry(data, mode, fetcher) : data.costUSD ?? 0;
3423
+ const project = extractProjectFromPath(file);
3424
+ allEntries.push({
3425
+ data,
3426
+ date,
3427
+ cost,
3428
+ model: data.message.model,
3429
+ project
3430
+ });
3431
+ } catch {}
3432
+ }
3433
+ const groupingKey = options?.groupByProject === true || options?.project != null ? (entry) => `${entry.date}\x00${entry.project}` : (entry) => entry.date;
3434
+ const groupedData = groupBy(allEntries, groupingKey);
3435
+ const results = Object.entries(groupedData).map(([groupKey, entries]) => {
3436
+ if (entries == null) return;
3437
+ const parts = groupKey.split("\0");
3438
+ const date = parts[0] ?? groupKey;
3439
+ const project = parts.length > 1 ? parts[1] : void 0;
3440
+ const modelAggregates = aggregateByModel(entries, (entry) => entry.model, (entry) => entry.data.message.usage, (entry) => entry.cost);
3441
+ const modelBreakdowns = createModelBreakdowns(modelAggregates);
3442
+ const totals = calculateTotals(entries, (entry) => entry.data.message.usage, (entry) => entry.cost);
3443
+ const modelsUsed = extractUniqueModels(entries, (e) => e.model);
3444
+ return {
3445
+ date: createDailyDate(date),
3446
+ ...totals,
3447
+ modelsUsed,
3448
+ modelBreakdowns,
3449
+ ...project != null && { project }
3450
+ };
3451
+ }).filter((item) => item != null);
3452
+ const dateFiltered = filterByDateRange(results, (item) => item.date, options?.since, options?.until);
3453
+ const finalFiltered = filterByProject(dateFiltered, (item) => item.project, options?.project);
3454
+ return sortByDate(finalFiltered, (item) => item.date, options?.order);
3455
+ } catch (_) {
3456
+ _usingCtx$1.e = _;
3457
+ } finally {
3458
+ _usingCtx$1.d();
3459
+ }
3460
+ }
3461
+ async function loadSessionData(options) {
3462
+ try {
3463
+ var _usingCtx3 = _usingCtx();
3464
+ const claudePaths = toArray(options?.claudePath ?? getClaudePaths());
3465
+ const filesWithBase = await globUsageFiles(claudePaths);
3466
+ if (filesWithBase.length === 0) return [];
3467
+ const projectFilteredWithBase = filterByProject(filesWithBase, (item) => extractProjectFromPath(item.file), options?.project);
3468
+ const fileToBaseMap = new Map(projectFilteredWithBase.map((f$1) => [f$1.file, f$1.baseDir]));
3469
+ const sortedFilesWithBase = await sortFilesByTimestamp(projectFilteredWithBase.map((f$1) => f$1.file)).then((sortedFiles) => sortedFiles.map((file) => ({
3470
+ file,
3471
+ baseDir: fileToBaseMap.get(file) ?? ""
3472
+ })));
3473
+ const mode = options?.mode ?? "auto";
3474
+ const fetcher = _usingCtx3.u(mode === "display" ? null : new PricingFetcher(options?.offline));
3475
+ const processedHashes = /* @__PURE__ */ new Set();
3476
+ const allEntries = [];
3477
+ for (const { file, baseDir } of sortedFilesWithBase) {
3478
+ const parts = path.relative(baseDir, file).split(path.sep);
3479
+ const sessionId = parts[parts.length - 2] ?? "unknown";
3480
+ const joinedPath = parts.slice(0, -2).join(path.sep);
3481
+ const projectPath = joinedPath.length > 0 ? joinedPath : "Unknown Project";
3482
+ const lines = (await readFile(file, "utf-8")).trim().split("\n").filter((line) => line.length > 0);
3483
+ for (const line of lines) try {
3484
+ const parsed = JSON.parse(line);
3485
+ const result = safeParse(usageDataSchema, parsed);
3486
+ if (!result.success) continue;
3487
+ const data = result.output;
3488
+ const uniqueHash = createUniqueHash(data);
3489
+ if (isDuplicateEntry(uniqueHash, processedHashes)) continue;
3490
+ markAsProcessed(uniqueHash, processedHashes);
3491
+ const sessionKey = `${projectPath}/${sessionId}`;
3492
+ const cost = fetcher != null ? await calculateCostForEntry(data, mode, fetcher) : data.costUSD ?? 0;
3493
+ allEntries.push({
3494
+ data,
3495
+ sessionKey,
3496
+ sessionId,
3497
+ projectPath,
3498
+ cost,
3499
+ timestamp: data.timestamp,
3500
+ model: data.message.model
3501
+ });
3502
+ } catch {}
3503
+ }
3504
+ const groupedBySessions = groupBy(allEntries, (entry) => entry.sessionKey);
3505
+ const results = Object.entries(groupedBySessions).map(([_, entries]) => {
3506
+ if (entries == null) return;
3507
+ const latestEntry = entries.reduce((latest, current) => current.timestamp > latest.timestamp ? current : latest);
3508
+ const versions = [];
3509
+ for (const entry of entries) if (entry.data.version != null) versions.push(entry.data.version);
3510
+ const modelAggregates = aggregateByModel(entries, (entry) => entry.model, (entry) => entry.data.message.usage, (entry) => entry.cost);
3511
+ const modelBreakdowns = createModelBreakdowns(modelAggregates);
3512
+ const totals = calculateTotals(entries, (entry) => entry.data.message.usage, (entry) => entry.cost);
3513
+ const modelsUsed = extractUniqueModels(entries, (e) => e.model);
3514
+ return {
3515
+ sessionId: createSessionId(latestEntry.sessionId),
3516
+ projectPath: createProjectPath(latestEntry.projectPath),
3517
+ ...totals,
3518
+ lastActivity: formatDate(latestEntry.timestamp, options?.timezone, DEFAULT_LOCALE),
3519
+ versions: uniq(versions).sort(),
3520
+ modelsUsed,
3521
+ modelBreakdowns
3522
+ };
3523
+ }).filter((item) => item != null);
3524
+ const dateFiltered = filterByDateRange(results, (item) => item.lastActivity, options?.since, options?.until);
3525
+ const sessionFiltered = filterByProject(dateFiltered, (item) => item.projectPath, options?.project);
3526
+ return sortByDate(sessionFiltered, (item) => item.lastActivity, options?.order);
3527
+ } catch (_) {
3528
+ _usingCtx3.e = _;
3529
+ } finally {
3530
+ _usingCtx3.d();
3531
+ }
3532
+ }
3533
+ async function loadMonthlyUsageData(options) {
3534
+ return loadBucketUsageData((data) => createMonthlyDate(data.date.slice(0, 7)), options).then((usages) => usages.map(({ bucket,...rest }) => ({
3535
+ month: parse$2(monthlyDateSchema, bucket),
3536
+ ...rest
3537
+ })));
3538
+ }
3539
+ async function loadWeeklyUsageData(options) {
3540
+ const startDay = options?.startOfWeek != null ? getDayNumber(options.startOfWeek) : getDayNumber("sunday");
3541
+ return loadBucketUsageData((data) => getDateWeek(new Date(data.date), startDay), options).then((usages) => usages.map(({ bucket,...rest }) => ({
3542
+ week: parse$2(weeklyDateSchema, bucket),
3543
+ ...rest
3544
+ })));
3545
+ }
3546
+ async function loadSessionUsageById(sessionId, options) {
3547
+ try {
3548
+ var _usingCtx4 = _usingCtx();
3549
+ const patterns = getClaudePaths().map((p) => path.join(p, "projects", "**", `${sessionId}.jsonl`).replace(/\\/g, "/"));
3550
+ const jsonlFiles = await glob(patterns);
3551
+ if (jsonlFiles.length === 0) return null;
3552
+ const file = jsonlFiles[0];
3553
+ if (file == null) return null;
3554
+ const lines = (await readFile(file, "utf-8")).trim().split("\n").filter((line) => line.length > 0);
3555
+ const mode = options?.mode ?? "auto";
3556
+ const fetcher = _usingCtx4.u(mode === "display" ? null : new PricingFetcher(options?.offline));
3557
+ const entries = [];
3558
+ let totalCost = 0;
3559
+ for (const line of lines) try {
3560
+ const parsed = JSON.parse(line);
3561
+ const result = safeParse(usageDataSchema, parsed);
3562
+ if (!result.success) continue;
3563
+ const data = result.output;
3564
+ const cost = fetcher != null ? await calculateCostForEntry(data, mode, fetcher) : data.costUSD ?? 0;
3565
+ totalCost += cost;
3566
+ entries.push(data);
3567
+ } catch {}
3568
+ return {
3569
+ totalCost,
3570
+ entries
3571
+ };
3572
+ } catch (_) {
3573
+ _usingCtx4.e = _;
3574
+ } finally {
3575
+ _usingCtx4.d();
3576
+ }
3577
+ }
3578
+ async function loadBucketUsageData(groupingFn, options) {
3579
+ const dailyData = await loadDailyUsageData(options);
3580
+ const groupingKey = options?.groupByProject === true || options?.project != null ? (data) => {
3581
+ const bucketValue = groupingFn(data);
3582
+ const projectSegment = data.project ?? "unknown";
3583
+ return `${bucketValue}\x00${projectSegment}`;
3584
+ } : (data) => `${groupingFn(data)}`;
3585
+ const grouped = groupBy(dailyData, groupingKey);
3586
+ const buckets = [];
3587
+ for (const [groupKey, dailyEntries] of Object.entries(grouped)) {
3588
+ if (dailyEntries == null) continue;
3589
+ const parts = groupKey.split("\0");
3590
+ const bucket = createBucket(parts[0] ?? groupKey);
3591
+ const project = parts.length > 1 ? parts[1] : void 0;
3592
+ const allBreakdowns = dailyEntries.flatMap((daily) => daily.modelBreakdowns);
3593
+ const modelAggregates = aggregateModelBreakdowns(allBreakdowns);
3594
+ const modelBreakdowns = createModelBreakdowns(modelAggregates);
3595
+ const models = [];
3596
+ for (const data of dailyEntries) for (const model of data.modelsUsed) if (model !== "<synthetic>") models.push(model);
3597
+ let totalInputTokens = 0;
3598
+ let totalOutputTokens = 0;
3599
+ let totalCacheCreationTokens = 0;
3600
+ let totalCacheReadTokens = 0;
3601
+ let totalCost = 0;
3602
+ for (const daily of dailyEntries) {
3603
+ totalInputTokens += daily.inputTokens;
3604
+ totalOutputTokens += daily.outputTokens;
3605
+ totalCacheCreationTokens += daily.cacheCreationTokens;
3606
+ totalCacheReadTokens += daily.cacheReadTokens;
3607
+ totalCost += daily.totalCost;
3608
+ }
3609
+ const bucketUsage = {
3610
+ bucket,
3611
+ inputTokens: totalInputTokens,
3612
+ outputTokens: totalOutputTokens,
3613
+ cacheCreationTokens: totalCacheCreationTokens,
3614
+ cacheReadTokens: totalCacheReadTokens,
3615
+ totalCost,
3616
+ modelsUsed: uniq(models),
3617
+ modelBreakdowns,
3618
+ ...project != null && { project }
3619
+ };
3620
+ buckets.push(bucketUsage);
3621
+ }
3622
+ return sortByDate(buckets, (item) => item.bucket, options?.order);
3623
+ }
3624
+ async function calculateContextTokens(transcriptPath, modelId, offline = false) {
3625
+ let content;
3626
+ try {
3627
+ content = await readFile(transcriptPath, "utf-8");
3628
+ } catch (error) {
3629
+ logger.debug(`Failed to read transcript file: ${String(error)}`);
3630
+ return null;
3631
+ }
3632
+ const lines = content.split("\n").reverse();
3633
+ for (const line of lines) {
3634
+ const trimmedLine = line.trim();
3635
+ if (trimmedLine === "") continue;
3636
+ try {
3637
+ const parsed = JSON.parse(trimmedLine);
3638
+ const result = safeParse(transcriptMessageSchema, parsed);
3639
+ if (!result.success) continue;
3640
+ const obj = result.output;
3641
+ if (obj.type === "assistant" && obj.message != null && obj.message.usage != null && obj.message.usage.input_tokens != null) {
3642
+ const usage = obj.message.usage;
3643
+ const inputTokens = usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0);
3644
+ let contextLimit = 2e5;
3645
+ if (modelId != null && modelId !== "") try {
3646
+ var _usingCtx5 = _usingCtx();
3647
+ const contextLimitResult = await _usingCtx5.u(new PricingFetcher(offline)).getModelContextLimit(modelId);
3648
+ if (isSuccess(contextLimitResult) && contextLimitResult.value != null) contextLimit = contextLimitResult.value;
3649
+ else if (isSuccess(contextLimitResult)) logger.debug(`No context limit data available for model ${modelId} in LiteLLM`);
3650
+ else logger.debug(`Failed to get context limit for model ${modelId}: ${contextLimitResult.error.message}`);
3651
+ } catch (_) {
3652
+ _usingCtx5.e = _;
3653
+ } finally {
3654
+ _usingCtx5.d();
3655
+ }
3656
+ const percentage = Math.min(100, Math.max(0, Math.round(inputTokens / contextLimit * 100)));
3657
+ return {
3658
+ inputTokens,
3659
+ percentage,
3660
+ contextLimit
3661
+ };
3662
+ }
3663
+ } catch {
3664
+ continue;
3665
+ }
3666
+ }
3667
+ logger.debug("No usage information found in transcript");
3668
+ return null;
3669
+ }
3670
+ async function loadSessionBlockData(options) {
3671
+ try {
3672
+ var _usingCtx6 = _usingCtx();
3673
+ const claudePaths = toArray(options?.claudePath ?? getClaudePaths());
3674
+ const allFiles = [];
3675
+ for (const claudePath of claudePaths) {
3676
+ const claudeDir = path.join(claudePath, CLAUDE_PROJECTS_DIR_NAME);
3677
+ const files = await glob([USAGE_DATA_GLOB_PATTERN], {
3678
+ cwd: claudeDir,
3679
+ absolute: true
3680
+ });
3681
+ allFiles.push(...files);
3682
+ }
3683
+ if (allFiles.length === 0) return [];
3684
+ const blocksFilteredFiles = filterByProject(allFiles, (filePath) => extractProjectFromPath(filePath), options?.project);
3685
+ const sortedFiles = await sortFilesByTimestamp(blocksFilteredFiles);
3686
+ const mode = options?.mode ?? "auto";
3687
+ const fetcher = _usingCtx6.u(mode === "display" ? null : new PricingFetcher(options?.offline));
3688
+ const processedHashes = /* @__PURE__ */ new Set();
3689
+ const allEntries = [];
3690
+ for (const file of sortedFiles) {
3691
+ const lines = (await readFile(file, "utf-8")).trim().split("\n").filter((line) => line.length > 0);
3692
+ for (const line of lines) try {
3693
+ const parsed = JSON.parse(line);
3694
+ const result = safeParse(usageDataSchema, parsed);
3695
+ if (!result.success) continue;
3696
+ const data = result.output;
3697
+ const uniqueHash = createUniqueHash(data);
3698
+ if (isDuplicateEntry(uniqueHash, processedHashes)) continue;
3699
+ markAsProcessed(uniqueHash, processedHashes);
3700
+ const cost = fetcher != null ? await calculateCostForEntry(data, mode, fetcher) : data.costUSD ?? 0;
3701
+ const usageLimitResetTime = getUsageLimitResetTime(data);
3702
+ allEntries.push({
3703
+ timestamp: new Date(data.timestamp),
3704
+ usage: {
3705
+ inputTokens: data.message.usage.input_tokens,
3706
+ outputTokens: data.message.usage.output_tokens,
3707
+ cacheCreationInputTokens: data.message.usage.cache_creation_input_tokens ?? 0,
3708
+ cacheReadInputTokens: data.message.usage.cache_read_input_tokens ?? 0
3709
+ },
3710
+ costUSD: cost,
3711
+ model: data.message.model ?? "unknown",
3712
+ version: data.version,
3713
+ usageLimitResetTime: usageLimitResetTime ?? void 0
3714
+ });
3715
+ } catch (error) {
3716
+ logger.debug(`Skipping invalid JSON line in 5-hour blocks: ${error instanceof Error ? error.message : String(error)}`);
3717
+ }
3718
+ }
3719
+ const blocks = identifySessionBlocks(allEntries, options?.sessionDurationHours);
3720
+ const dateFiltered = options?.since != null && options.since !== "" || options?.until != null && options.until !== "" ? blocks.filter((block) => {
3721
+ const blockDateStr = formatDate(block.startTime.toISOString(), options?.timezone, DEFAULT_LOCALE).replace(/-/g, "");
3722
+ if (options.since != null && options.since !== "" && blockDateStr < options.since) return false;
3723
+ if (options.until != null && options.until !== "" && blockDateStr > options.until) return false;
3724
+ return true;
3725
+ }) : blocks;
3726
+ return sortByDate(dateFiltered, (block) => block.startTime, options?.order);
3727
+ } catch (_) {
3728
+ _usingCtx6.e = _;
3729
+ } finally {
3730
+ _usingCtx6.d();
3731
+ }
3732
+ }
3733
+ export { BLOCKS_COMPACT_WIDTH_THRESHOLD, BLOCKS_DEFAULT_TERMINAL_WIDTH, BLOCKS_WARNING_THRESHOLD, BURN_RATE_THRESHOLDS, CLAUDE_PROJECTS_DIR_NAME, CONFIG_FILE_NAME, DEBUG_MATCH_THRESHOLD_PERCENT, DEFAULT_CONTEXT_USAGE_THRESHOLDS, DEFAULT_LOCALE, DEFAULT_RECENT_DAYS, DEFAULT_REFRESH_INTERVAL_SECONDS, DEFAULT_SESSION_DURATION_HOURS, MAX_REFRESH_INTERVAL_SECONDS, MIN_REFRESH_INTERVAL_SECONDS, MIN_RENDER_INTERVAL_MS, PricingFetcher, USAGE_DATA_GLOB_PATTERN, WEEK_DAYS, __commonJSMin, __require$1 as __require, __toESM, _usingCtx, andThen, bucketUsageSchema, calculateBurnRate, calculateContextTokens, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, fail, filterRecentBlocks, formatDateCompact, getClaudePaths, getEarliestTimestamp, getFileModifiedTime, getUsageLimitResetTime, glob, globUsageFiles, identifySessionBlocks, inspect, inspectError, isFailure, isSuccess, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, map, modelBreakdownSchema, monthlyUsageSchema, pipe, projectBlockUsage, sessionUsageSchema, sortFilesByTimestamp, succeed, toArray, transcriptMessageSchema, transcriptUsageSchema, try_, uniq, unreachable, unwrap, usageDataSchema, weeklyUsageSchema };