ccusage 16.2.5 → 17.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2681 +0,0 @@
1
- import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_LOCALE, DEFAULT_RECENT_DAYS, PricingFetcher, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR, __commonJSMin, __require, __toESM, isFailure, isPromise, isSuccess, map, pipe, require_usingCtx, try_ } from "./pricing-fetcher-BtUY4dRM.js";
2
- import { getTotalTokens } from "./_token-utils-WjkbrjKv.js";
3
- import { activityDateSchema, arrayType, booleanType, createBucket, createDailyDate, createMonthlyDate, createProjectPath, createSessionId, createWeeklyDate, dailyDateSchema, isoTimestampSchema, messageIdSchema, modelNameSchema, monthlyDateSchema, numberType, objectType, projectPathSchema, requestIdSchema, sessionIdSchema, stringType, unionType, versionSchema, weeklyDateSchema } from "./_types-DIdtMJ6V.js";
4
- import { logger } from "./logger-wHijzbnK.js";
5
- import a, { readFile, stat } from "node:fs/promises";
6
- import path, { posix } from "node:path";
7
- import process$1 from "node:process";
8
- import b from "node:fs";
9
- import F from "node:os";
10
- function toArray(array) {
11
- return array = array ?? [], Array.isArray(array) ? array : [array];
12
- }
13
- const VOID = Symbol("p-void"), isResult = (result) => "object" == typeof result && null !== result && "type" in result && ("Success" === result.type && "value" in result || "Failure" === result.type && "error" in result), unwrap = (...args) => {
14
- const firstArgument = args[0];
15
- if (isResult(firstArgument) || isPromise(firstArgument)) {
16
- const result = firstArgument, hasDefault$1 = 2 === args.length, defaultValue$1 = hasDefault$1 ? args[1] : void 0, apply = (r) => {
17
- if (isFailure(r)) {
18
- if (hasDefault$1) return defaultValue$1;
19
- throw r.error;
20
- }
21
- return r.value;
22
- };
23
- return isPromise(result) ? result.then(apply) : apply(result);
24
- }
25
- const hasDefault = 1 === args.length, defaultValue = hasDefault ? args[0] : void 0;
26
- return (result) => {
27
- const apply = (r) => {
28
- if (isFailure(r)) {
29
- if (hasDefault) return defaultValue;
30
- throw r.error;
31
- }
32
- return r.value;
33
- };
34
- return isPromise(result) ? result.then(apply) : apply(result);
35
- };
36
- };
37
- function groupBy(arr, getKeyFromItem) {
38
- const result = {};
39
- for (let i = 0; i < arr.length; i++) {
40
- const item = arr[i], key = getKeyFromItem(item);
41
- if (!Object.hasOwn(result, key)) result[key] = [];
42
- result[key].push(item);
43
- }
44
- return result;
45
- }
46
- function uniq(arr) {
47
- return Array.from(new Set(arr));
48
- }
49
- var d = Object.defineProperty, n = (s, t) => d(s, "name", {
50
- value: t,
51
- configurable: !0
52
- });
53
- typeof Symbol.asyncDispose != "symbol" && Object.defineProperty(Symbol, "asyncDispose", {
54
- configurable: !1,
55
- enumerable: !1,
56
- writable: !1,
57
- value: Symbol.for("asyncDispose")
58
- });
59
- var P = class {
60
- static {
61
- n(this, "FsFixture");
62
- }
63
- path;
64
- constructor(t) {
65
- this.path = t;
66
- }
67
- getPath(...t) {
68
- return path.join(this.path, ...t);
69
- }
70
- exists(t = "") {
71
- return a.access(this.getPath(t)).then(() => !0, () => !1);
72
- }
73
- rm(t = "") {
74
- return a.rm(this.getPath(t), {
75
- recursive: !0,
76
- force: !0
77
- });
78
- }
79
- cp(t, r, i) {
80
- return r ? r.endsWith(path.sep) && (r += path.basename(t)) : r = path.basename(t), a.cp(t, this.getPath(r), i);
81
- }
82
- mkdir(t) {
83
- return a.mkdir(this.getPath(t), { recursive: !0 });
84
- }
85
- writeFile(t, r) {
86
- return a.writeFile(this.getPath(t), r);
87
- }
88
- writeJson(t, r) {
89
- return this.writeFile(t, JSON.stringify(r, null, 2));
90
- }
91
- readFile(t, r) {
92
- return a.readFile(this.getPath(t), r);
93
- }
94
- async [Symbol.asyncDispose]() {
95
- await this.rm();
96
- }
97
- };
98
- const v = b.realpathSync(F.tmpdir()), D = `fs-fixture-${Date.now()}-${process.pid}`;
99
- let m = 0;
100
- const j = n(() => (m += 1, m), "getId");
101
- var u = class {
102
- static {
103
- n(this, "Path");
104
- }
105
- path;
106
- constructor(t) {
107
- this.path = t;
108
- }
109
- }, f = class extends u {
110
- static {
111
- n(this, "Directory");
112
- }
113
- }, y = class extends u {
114
- static {
115
- n(this, "File");
116
- }
117
- content;
118
- constructor(t, r) {
119
- super(t), this.content = r;
120
- }
121
- }, l = class {
122
- static {
123
- n(this, "Symlink");
124
- }
125
- target;
126
- type;
127
- path;
128
- constructor(t, r) {
129
- this.target = t, this.type = r;
130
- }
131
- };
132
- const w = n((s, t, r) => {
133
- const i = [];
134
- for (const p in s) {
135
- if (!Object.hasOwn(s, p)) continue;
136
- const e = path.join(t, p);
137
- let o = s[p];
138
- if (typeof o == "function") {
139
- const g = Object.assign(Object.create(r), { filePath: e }), h = o(g);
140
- if (h instanceof l) {
141
- h.path = e, i.push(h);
142
- continue;
143
- } else o = h;
144
- }
145
- typeof o == "string" ? i.push(new y(e, o)) : i.push(new f(e), ...w(o, e, r));
146
- }
147
- return i;
148
- }, "flattenFileTree"), k = n(async (s, t) => {
149
- const r = t?.tempDir ? path.resolve(t.tempDir) : v, i = path.join(r, `${D}-${j()}/`);
150
- if (await a.mkdir(i, { recursive: !0 }), s) {
151
- if (typeof s == "string") await a.cp(s, i, {
152
- recursive: !0,
153
- filter: t?.templateFilter
154
- });
155
- else if (typeof s == "object") {
156
- const p = {
157
- fixturePath: i,
158
- getPath: n((...e) => path.join(i, ...e), "getPath"),
159
- symlink: n((e, o) => new l(e, o), "symlink")
160
- };
161
- await Promise.all(w(s, i, p).map(async (e) => {
162
- 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));
163
- }));
164
- }
165
- }
166
- return new P(i);
167
- }, "createFixture");
168
- async function isType(fsStatType, statsMethodName, filePath) {
169
- if (typeof filePath !== "string") throw new TypeError(`Expected a string, got ${typeof filePath}`);
170
- try {
171
- const stats = await a[fsStatType](filePath);
172
- return stats[statsMethodName]();
173
- } catch (error) {
174
- if (error.code === "ENOENT") return false;
175
- throw error;
176
- }
177
- }
178
- function isTypeSync(fsStatType, statsMethodName, filePath) {
179
- if (typeof filePath !== "string") throw new TypeError(`Expected a string, got ${typeof filePath}`);
180
- try {
181
- return b[fsStatType](filePath)[statsMethodName]();
182
- } catch (error) {
183
- if (error.code === "ENOENT") return false;
184
- throw error;
185
- }
186
- }
187
- const isFile = isType.bind(void 0, "stat", "isFile"), isDirectory = isType.bind(void 0, "stat", "isDirectory"), isSymlink = isType.bind(void 0, "lstat", "isSymbolicLink"), isFileSync = isTypeSync.bind(void 0, "statSync", "isFile"), isDirectorySync = isTypeSync.bind(void 0, "statSync", "isDirectory"), isSymlinkSync = isTypeSync.bind(void 0, "lstatSync", "isSymbolicLink");
188
- var require_utils$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
189
- Object.defineProperty(exports, "__esModule", { value: true }), exports.normalizePath = exports.isRootDirectory = exports.convertSlashes = exports.cleanPath = void 0;
190
- const path_1$4 = __require("node:path");
191
- function cleanPath(path$1) {
192
- let normalized = (0, path_1$4.normalize)(path$1);
193
- if (normalized.length > 1 && normalized[normalized.length - 1] === path_1$4.sep) normalized = normalized.substring(0, normalized.length - 1);
194
- return normalized;
195
- }
196
- exports.cleanPath = cleanPath;
197
- const SLASHES_REGEX = /[\\/]/g;
198
- function convertSlashes(path$1, separator) {
199
- return path$1.replace(SLASHES_REGEX, separator);
200
- }
201
- exports.convertSlashes = convertSlashes;
202
- const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
203
- function isRootDirectory(path$1) {
204
- return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1);
205
- }
206
- exports.isRootDirectory = isRootDirectory;
207
- function normalizePath(path$1, options) {
208
- const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options, pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith(".");
209
- if (resolvePaths) path$1 = (0, path_1$4.resolve)(path$1);
210
- if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1);
211
- if (path$1 === ".") return "";
212
- const needsSeperator = path$1[path$1.length - 1] !== pathSeparator;
213
- return convertSlashes(needsSeperator ? path$1 + pathSeparator : path$1, pathSeparator);
214
- }
215
- exports.normalizePath = normalizePath;
216
- })), require_join_path = /* @__PURE__ */ __commonJSMin(((exports) => {
217
- Object.defineProperty(exports, "__esModule", { value: true }), exports.build = exports.joinDirectoryPath = exports.joinPathWithBasePath = void 0;
218
- const path_1$3 = __require("node:path"), utils_1$1 = require_utils$1();
219
- function joinPathWithBasePath(filename, directoryPath) {
220
- return directoryPath + filename;
221
- }
222
- exports.joinPathWithBasePath = joinPathWithBasePath;
223
- function joinPathWithRelativePath(root, options) {
224
- return function(filename, directoryPath) {
225
- const sameRoot = directoryPath.startsWith(root);
226
- return sameRoot ? directoryPath.replace(root, "") + filename : (0, utils_1$1.convertSlashes)((0, path_1$3.relative)(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
227
- };
228
- }
229
- function joinPath$1(filename) {
230
- return filename;
231
- }
232
- function joinDirectoryPath(filename, directoryPath, separator) {
233
- return directoryPath + filename + separator;
234
- }
235
- exports.joinDirectoryPath = joinDirectoryPath;
236
- function build$7(root, options) {
237
- const { relativePaths, includeBasePath } = options;
238
- return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath$1;
239
- }
240
- exports.build = build$7;
241
- })), require_push_directory = /* @__PURE__ */ __commonJSMin(((exports) => {
242
- Object.defineProperty(exports, "__esModule", { value: true }), exports.build = void 0;
243
- function pushDirectoryWithRelativePath(root) {
244
- return function(directoryPath, paths) {
245
- paths.push(directoryPath.substring(root.length) || ".");
246
- };
247
- }
248
- function pushDirectoryFilterWithRelativePath(root) {
249
- return function(directoryPath, paths, filters) {
250
- const relativePath = directoryPath.substring(root.length) || ".";
251
- if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
252
- };
253
- }
254
- const pushDirectory$1 = (directoryPath, paths) => {
255
- paths.push(directoryPath || ".");
256
- }, pushDirectoryFilter = (directoryPath, paths, filters) => {
257
- const path$1 = directoryPath || ".";
258
- if (filters.every((filter) => filter(path$1, true))) paths.push(path$1);
259
- }, empty$2 = () => {};
260
- function build$6(root, options) {
261
- const { includeDirs, filters, relativePaths } = options;
262
- return includeDirs ? relativePaths ? filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root) : filters && filters.length ? pushDirectoryFilter : pushDirectory$1 : empty$2;
263
- }
264
- exports.build = build$6;
265
- })), require_push_file = /* @__PURE__ */ __commonJSMin(((exports) => {
266
- Object.defineProperty(exports, "__esModule", { value: true }), exports.build = void 0;
267
- const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
268
- if (filters.every((filter) => filter(filename, false))) counts.files++;
269
- }, pushFileFilter = (filename, paths, _counts, filters) => {
270
- if (filters.every((filter) => filter(filename, false))) paths.push(filename);
271
- }, pushFileCount = (_filename, _paths, counts, _filters) => {
272
- counts.files++;
273
- }, pushFile$1 = (filename, paths) => {
274
- paths.push(filename);
275
- }, empty$1 = () => {};
276
- function build$5(options) {
277
- const { excludeFiles, filters, onlyCounts } = options;
278
- return excludeFiles ? empty$1 : filters && filters.length ? onlyCounts ? pushFileFilterAndCount : pushFileFilter : onlyCounts ? pushFileCount : pushFile$1;
279
- }
280
- exports.build = build$5;
281
- })), require_get_array = /* @__PURE__ */ __commonJSMin(((exports) => {
282
- Object.defineProperty(exports, "__esModule", { value: true }), exports.build = void 0;
283
- const getArray$1 = (paths) => {
284
- return paths;
285
- }, getArrayGroup = () => {
286
- return [""].slice(0, 0);
287
- };
288
- function build$4(options) {
289
- return options.group ? getArrayGroup : getArray$1;
290
- }
291
- exports.build = build$4;
292
- })), require_group_files = /* @__PURE__ */ __commonJSMin(((exports) => {
293
- Object.defineProperty(exports, "__esModule", { value: true }), exports.build = void 0;
294
- const groupFiles$1 = (groups, directory, files) => {
295
- groups.push({
296
- directory,
297
- files,
298
- dir: directory
299
- });
300
- }, empty = () => {};
301
- function build$3(options) {
302
- return options.group ? groupFiles$1 : empty;
303
- }
304
- exports.build = build$3;
305
- })), require_resolve_symlink = /* @__PURE__ */ __commonJSMin(((exports) => {
306
- var __importDefault$1 = exports && exports.__importDefault || function(mod) {
307
- return mod && mod.__esModule ? mod : { "default": mod };
308
- };
309
- Object.defineProperty(exports, "__esModule", { value: true }), exports.build = void 0;
310
- const fs_1$1 = __importDefault$1(__require("node:fs")), path_1$2 = __require("node:path"), resolveSymlinksAsync = function(path$1, state, callback$1) {
311
- const { queue, options: { suppressErrors } } = state;
312
- queue.enqueue(), fs_1$1.default.realpath(path$1, (error, resolvedPath) => {
313
- if (error) return queue.dequeue(suppressErrors ? null : error, state);
314
- fs_1$1.default.stat(resolvedPath, (error$1, stat$1) => {
315
- if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
316
- if (stat$1.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state);
317
- callback$1(stat$1, resolvedPath), queue.dequeue(null, state);
318
- });
319
- });
320
- }, resolveSymlinks = function(path$1, state, callback$1) {
321
- const { queue, options: { suppressErrors } } = state;
322
- queue.enqueue();
323
- try {
324
- const resolvedPath = fs_1$1.default.realpathSync(path$1), stat$1 = fs_1$1.default.statSync(resolvedPath);
325
- if (stat$1.isDirectory() && isRecursive(path$1, resolvedPath, state)) return;
326
- callback$1(stat$1, resolvedPath);
327
- } catch (e) {
328
- if (!suppressErrors) throw e;
329
- }
330
- };
331
- function build$2(options, isSynchronous) {
332
- return !options.resolveSymlinks || options.excludeSymlinks ? null : isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
333
- }
334
- exports.build = build$2;
335
- function isRecursive(path$1, resolved, state) {
336
- if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
337
- let parent = (0, path_1$2.dirname)(path$1), depth$1 = 1;
338
- while (parent !== state.root && depth$1 < 2) {
339
- const resolvedPath = state.symlinks.get(parent), isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath));
340
- if (isSameRoot) depth$1++;
341
- else parent = (0, path_1$2.dirname)(parent);
342
- }
343
- return state.symlinks.set(path$1, resolved), depth$1 > 1;
344
- }
345
- function isRecursiveUsingRealPaths(resolved, state) {
346
- return state.visited.includes(resolved + state.options.pathSeparator);
347
- }
348
- })), require_invoke_callback = /* @__PURE__ */ __commonJSMin(((exports) => {
349
- Object.defineProperty(exports, "__esModule", { value: true }), exports.build = void 0;
350
- const onlyCountsSync = (state) => {
351
- return state.counts;
352
- }, groupsSync = (state) => {
353
- return state.groups;
354
- }, defaultSync = (state) => {
355
- return state.paths;
356
- }, limitFilesSync = (state) => {
357
- return state.paths.slice(0, state.options.maxFiles);
358
- }, onlyCountsAsync = (state, error, callback$1) => {
359
- return report(error, callback$1, state.counts, state.options.suppressErrors), null;
360
- }, defaultAsync = (state, error, callback$1) => {
361
- return report(error, callback$1, state.paths, state.options.suppressErrors), null;
362
- }, limitFilesAsync = (state, error, callback$1) => {
363
- return report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors), null;
364
- }, groupsAsync = (state, error, callback$1) => {
365
- return report(error, callback$1, state.groups, state.options.suppressErrors), null;
366
- };
367
- function report(error, callback$1, output, suppressErrors) {
368
- if (error && !suppressErrors) callback$1(error, output);
369
- else callback$1(null, output);
370
- }
371
- function build$1(options, isSynchronous) {
372
- const { onlyCounts, group, maxFiles } = options;
373
- return onlyCounts ? isSynchronous ? onlyCountsSync : onlyCountsAsync : group ? isSynchronous ? groupsSync : groupsAsync : maxFiles ? isSynchronous ? limitFilesSync : limitFilesAsync : isSynchronous ? defaultSync : defaultAsync;
374
- }
375
- exports.build = build$1;
376
- })), require_walk_directory = /* @__PURE__ */ __commonJSMin(((exports) => {
377
- var __importDefault = exports && exports.__importDefault || function(mod) {
378
- return mod && mod.__esModule ? mod : { "default": mod };
379
- };
380
- Object.defineProperty(exports, "__esModule", { value: true }), exports.build = void 0;
381
- const fs_1 = __importDefault(__require("node:fs")), readdirOpts = { withFileTypes: true }, walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
382
- if (state.queue.enqueue(), currentDepth < 0) return state.queue.dequeue(null, state);
383
- state.visited.push(crawlPath), state.counts.directories++, fs_1.default.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
384
- callback$1(entries, directoryPath, currentDepth), state.queue.dequeue(state.options.suppressErrors ? null : error, state);
385
- });
386
- }, walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
387
- if (currentDepth < 0) return;
388
- state.visited.push(crawlPath), state.counts.directories++;
389
- let entries = [];
390
- try {
391
- entries = fs_1.default.readdirSync(crawlPath || ".", readdirOpts);
392
- } catch (e) {
393
- if (!state.options.suppressErrors) throw e;
394
- }
395
- callback$1(entries, directoryPath, currentDepth);
396
- };
397
- function build(isSynchronous) {
398
- return isSynchronous ? walkSync : walkAsync;
399
- }
400
- exports.build = build;
401
- })), require_queue = /* @__PURE__ */ __commonJSMin(((exports) => {
402
- Object.defineProperty(exports, "__esModule", { value: true }), exports.Queue = void 0;
403
- var Queue = class {
404
- onQueueEmpty;
405
- count = 0;
406
- constructor(onQueueEmpty) {
407
- this.onQueueEmpty = onQueueEmpty;
408
- }
409
- enqueue() {
410
- return this.count++, this.count;
411
- }
412
- dequeue(error, output) {
413
- if (this.onQueueEmpty && (--this.count <= 0 || error)) {
414
- if (this.onQueueEmpty(error, output), error) output.controller.abort(), this.onQueueEmpty = void 0;
415
- }
416
- }
417
- };
418
- exports.Queue = Queue;
419
- })), require_counter = /* @__PURE__ */ __commonJSMin(((exports) => {
420
- Object.defineProperty(exports, "__esModule", { value: true }), exports.Counter = void 0;
421
- var Counter = class {
422
- _files = 0;
423
- _directories = 0;
424
- set files(num) {
425
- this._files = num;
426
- }
427
- get files() {
428
- return this._files;
429
- }
430
- set directories(num) {
431
- this._directories = num;
432
- }
433
- get directories() {
434
- return this._directories;
435
- }
436
- /* c8 ignore next 3 */
437
- get dirs() {
438
- return this._directories;
439
- }
440
- };
441
- exports.Counter = Counter;
442
- })), require_walker = /* @__PURE__ */ __commonJSMin(((exports) => {
443
- var __createBinding$1 = exports && exports.__createBinding || (Object.create ? (function(o, m$1, k$1, k2) {
444
- if (k2 === void 0) k2 = k$1;
445
- var desc = Object.getOwnPropertyDescriptor(m$1, k$1);
446
- if (!desc || ("get" in desc ? !m$1.__esModule : desc.writable || desc.configurable)) desc = {
447
- enumerable: true,
448
- get: function() {
449
- return m$1[k$1];
450
- }
451
- };
452
- Object.defineProperty(o, k2, desc);
453
- }) : (function(o, m$1, k$1, k2) {
454
- if (k2 === void 0) k2 = k$1;
455
- o[k2] = m$1[k$1];
456
- })), __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? (function(o, v$1) {
457
- Object.defineProperty(o, "default", {
458
- enumerable: true,
459
- value: v$1
460
- });
461
- }) : function(o, v$1) {
462
- o["default"] = v$1;
463
- }), __importStar = exports && exports.__importStar || function(mod) {
464
- if (mod && mod.__esModule) return mod;
465
- var result = {};
466
- if (mod != null) {
467
- for (var k$1 in mod) if (k$1 !== "default" && Object.prototype.hasOwnProperty.call(mod, k$1)) __createBinding$1(result, mod, k$1);
468
- }
469
- return __setModuleDefault(result, mod), result;
470
- };
471
- Object.defineProperty(exports, "__esModule", { value: true }), exports.Walker = void 0;
472
- const path_1$1 = __require("node:path"), utils_1 = require_utils$1(), joinPath = __importStar(require_join_path()), pushDirectory = __importStar(require_push_directory()), pushFile = __importStar(require_push_file()), getArray = __importStar(require_get_array()), groupFiles = __importStar(require_group_files()), resolveSymlink = __importStar(require_resolve_symlink()), invokeCallback = __importStar(require_invoke_callback()), walkDirectory = __importStar(require_walk_directory()), queue_1 = require_queue(), counter_1 = require_counter();
473
- var Walker = class {
474
- root;
475
- isSynchronous;
476
- state;
477
- joinPath;
478
- pushDirectory;
479
- pushFile;
480
- getArray;
481
- groupFiles;
482
- resolveSymlink;
483
- walkDirectory;
484
- callbackInvoker;
485
- constructor(root, options, callback$1) {
486
- this.isSynchronous = !callback$1, this.callbackInvoker = invokeCallback.build(options, this.isSynchronous), this.root = (0, utils_1.normalizePath)(root, options), this.state = {
487
- root: (0, utils_1.isRootDirectory)(this.root) ? this.root : this.root.slice(0, -1),
488
- paths: [""].slice(0, 0),
489
- groups: [],
490
- counts: new counter_1.Counter(),
491
- options,
492
- queue: new queue_1.Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
493
- symlinks: /* @__PURE__ */ new Map(),
494
- visited: [""].slice(0, 0),
495
- controller: new AbortController()
496
- }, this.joinPath = joinPath.build(this.root, options), this.pushDirectory = pushDirectory.build(this.root, options), this.pushFile = pushFile.build(options), this.getArray = getArray.build(options), this.groupFiles = groupFiles.build(options), this.resolveSymlink = resolveSymlink.build(options, this.isSynchronous), this.walkDirectory = walkDirectory.build(this.isSynchronous);
497
- }
498
- start() {
499
- return this.pushDirectory(this.root, this.state.paths, this.state.options.filters), this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk), this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
500
- }
501
- walk = (entries, directoryPath, depth$1) => {
502
- const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
503
- if (controller.signal.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
504
- const files = this.getArray(this.state.paths);
505
- for (let i = 0; i < entries.length; ++i) {
506
- const entry = entries[i];
507
- if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
508
- const filename = this.joinPath(entry.name, directoryPath);
509
- this.pushFile(filename, files, this.state.counts, filters);
510
- } else if (entry.isDirectory()) {
511
- let path$1 = joinPath.joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
512
- if (exclude && exclude(entry.name, path$1)) continue;
513
- this.pushDirectory(path$1, paths, filters), this.walkDirectory(this.state, path$1, path$1, depth$1 - 1, this.walk);
514
- } else if (this.resolveSymlink && entry.isSymbolicLink()) {
515
- let path$1 = joinPath.joinPathWithBasePath(entry.name, directoryPath);
516
- this.resolveSymlink(path$1, this.state, (stat$1, resolvedPath) => {
517
- if (stat$1.isDirectory()) {
518
- if (resolvedPath = (0, utils_1.normalizePath)(resolvedPath, this.state.options), exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return;
519
- this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth$1 - 1, this.walk);
520
- } else {
521
- resolvedPath = useRealPaths ? resolvedPath : path$1;
522
- const filename = (0, path_1$1.basename)(resolvedPath), directoryPath$1 = (0, utils_1.normalizePath)((0, path_1$1.dirname)(resolvedPath), this.state.options);
523
- resolvedPath = this.joinPath(filename, directoryPath$1), this.pushFile(resolvedPath, files, this.state.counts, filters);
524
- }
525
- });
526
- }
527
- }
528
- this.groupFiles(this.state.groups, directoryPath, files);
529
- };
530
- };
531
- exports.Walker = Walker;
532
- })), require_async = /* @__PURE__ */ __commonJSMin(((exports) => {
533
- Object.defineProperty(exports, "__esModule", { value: true }), exports.callback = exports.promise = void 0;
534
- const walker_1$1 = require_walker();
535
- function promise(root, options) {
536
- return new Promise((resolve, reject) => {
537
- callback(root, options, (err, output) => {
538
- if (err) return reject(err);
539
- resolve(output);
540
- });
541
- });
542
- }
543
- exports.promise = promise;
544
- function callback(root, options, callback$1) {
545
- let walker = new walker_1$1.Walker(root, options, callback$1);
546
- walker.start();
547
- }
548
- exports.callback = callback;
549
- })), require_sync = /* @__PURE__ */ __commonJSMin(((exports) => {
550
- Object.defineProperty(exports, "__esModule", { value: true }), exports.sync = void 0;
551
- const walker_1 = require_walker();
552
- function sync(root, options) {
553
- const walker = new walker_1.Walker(root, options);
554
- return walker.start();
555
- }
556
- exports.sync = sync;
557
- })), require_api_builder = /* @__PURE__ */ __commonJSMin(((exports) => {
558
- Object.defineProperty(exports, "__esModule", { value: true }), exports.APIBuilder = void 0;
559
- const async_1 = require_async(), sync_1 = require_sync();
560
- var APIBuilder = class {
561
- root;
562
- options;
563
- constructor(root, options) {
564
- this.root = root, this.options = options;
565
- }
566
- withPromise() {
567
- return (0, async_1.promise)(this.root, this.options);
568
- }
569
- withCallback(cb) {
570
- (0, async_1.callback)(this.root, this.options, cb);
571
- }
572
- sync() {
573
- return (0, sync_1.sync)(this.root, this.options);
574
- }
575
- };
576
- exports.APIBuilder = APIBuilder;
577
- })), require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
578
- const WIN_SLASH = "\\\\/", WIN_NO_SLASH = `[^${WIN_SLASH}]`, DOT_LITERAL = "\\.", PLUS_LITERAL = "\\+", QMARK_LITERAL = "\\?", SLASH_LITERAL = "\\/", ONE_CHAR = "(?=.)", QMARK = "[^/]", END_ANCHOR = `(?:${SLASH_LITERAL}|$)`, START_ANCHOR = `(?:^|${SLASH_LITERAL})`, DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`, NO_DOT = `(?!${DOT_LITERAL})`, NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`, NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`, NO_DOTS_SLASH = `(?!${DOTS_SLASH})`, QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`, STAR = `${QMARK}*?`, SEP = "/", POSIX_CHARS = {
579
- DOT_LITERAL,
580
- PLUS_LITERAL,
581
- QMARK_LITERAL,
582
- SLASH_LITERAL,
583
- ONE_CHAR,
584
- QMARK,
585
- END_ANCHOR,
586
- DOTS_SLASH,
587
- NO_DOT,
588
- NO_DOTS,
589
- NO_DOT_SLASH,
590
- NO_DOTS_SLASH,
591
- QMARK_NO_DOT,
592
- STAR,
593
- START_ANCHOR,
594
- SEP
595
- }, WINDOWS_CHARS = {
596
- ...POSIX_CHARS,
597
- SLASH_LITERAL: `[${WIN_SLASH}]`,
598
- QMARK: WIN_NO_SLASH,
599
- STAR: `${WIN_NO_SLASH}*?`,
600
- DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
601
- NO_DOT: `(?!${DOT_LITERAL})`,
602
- NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
603
- NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
604
- NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
605
- QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
606
- START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
607
- END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
608
- SEP: "\\"
609
- }, POSIX_REGEX_SOURCE$1 = {
610
- alnum: "a-zA-Z0-9",
611
- alpha: "a-zA-Z",
612
- ascii: "\\x00-\\x7F",
613
- blank: " \\t",
614
- cntrl: "\\x00-\\x1F\\x7F",
615
- digit: "0-9",
616
- graph: "\\x21-\\x7E",
617
- lower: "a-z",
618
- print: "\\x20-\\x7E ",
619
- punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
620
- space: " \\t\\r\\n\\v\\f",
621
- upper: "A-Z",
622
- word: "A-Za-z0-9_",
623
- xdigit: "A-Fa-f0-9"
624
- };
625
- module.exports = {
626
- MAX_LENGTH: 1024 * 64,
627
- POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
628
- REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
629
- REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
630
- REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
631
- REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
632
- REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
633
- REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
634
- REPLACEMENTS: {
635
- "***": "*",
636
- "**/**": "**",
637
- "**/**/**": "**"
638
- },
639
- CHAR_0: 48,
640
- CHAR_9: 57,
641
- CHAR_UPPERCASE_A: 65,
642
- CHAR_LOWERCASE_A: 97,
643
- CHAR_UPPERCASE_Z: 90,
644
- CHAR_LOWERCASE_Z: 122,
645
- CHAR_LEFT_PARENTHESES: 40,
646
- CHAR_RIGHT_PARENTHESES: 41,
647
- CHAR_ASTERISK: 42,
648
- CHAR_AMPERSAND: 38,
649
- CHAR_AT: 64,
650
- CHAR_BACKWARD_SLASH: 92,
651
- CHAR_CARRIAGE_RETURN: 13,
652
- CHAR_CIRCUMFLEX_ACCENT: 94,
653
- CHAR_COLON: 58,
654
- CHAR_COMMA: 44,
655
- CHAR_DOT: 46,
656
- CHAR_DOUBLE_QUOTE: 34,
657
- CHAR_EQUAL: 61,
658
- CHAR_EXCLAMATION_MARK: 33,
659
- CHAR_FORM_FEED: 12,
660
- CHAR_FORWARD_SLASH: 47,
661
- CHAR_GRAVE_ACCENT: 96,
662
- CHAR_HASH: 35,
663
- CHAR_HYPHEN_MINUS: 45,
664
- CHAR_LEFT_ANGLE_BRACKET: 60,
665
- CHAR_LEFT_CURLY_BRACE: 123,
666
- CHAR_LEFT_SQUARE_BRACKET: 91,
667
- CHAR_LINE_FEED: 10,
668
- CHAR_NO_BREAK_SPACE: 160,
669
- CHAR_PERCENT: 37,
670
- CHAR_PLUS: 43,
671
- CHAR_QUESTION_MARK: 63,
672
- CHAR_RIGHT_ANGLE_BRACKET: 62,
673
- CHAR_RIGHT_CURLY_BRACE: 125,
674
- CHAR_RIGHT_SQUARE_BRACKET: 93,
675
- CHAR_SEMICOLON: 59,
676
- CHAR_SINGLE_QUOTE: 39,
677
- CHAR_SPACE: 32,
678
- CHAR_TAB: 9,
679
- CHAR_UNDERSCORE: 95,
680
- CHAR_VERTICAL_LINE: 124,
681
- CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
682
- extglobChars(chars) {
683
- return {
684
- "!": {
685
- type: "negate",
686
- open: "(?:(?!(?:",
687
- close: `))${chars.STAR})`
688
- },
689
- "?": {
690
- type: "qmark",
691
- open: "(?:",
692
- close: ")?"
693
- },
694
- "+": {
695
- type: "plus",
696
- open: "(?:",
697
- close: ")+"
698
- },
699
- "*": {
700
- type: "star",
701
- open: "(?:",
702
- close: ")*"
703
- },
704
- "@": {
705
- type: "at",
706
- open: "(?:",
707
- close: ")"
708
- }
709
- };
710
- },
711
- globChars(win32) {
712
- return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
713
- }
714
- };
715
- })), require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
716
- const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
717
- exports.isObject = (val) => val !== null && typeof val === "object" && !Array.isArray(val), exports.hasRegexChars = (str) => REGEX_SPECIAL_CHARS.test(str), exports.isRegexChar = (str) => str.length === 1 && exports.hasRegexChars(str), exports.escapeRegex = (str) => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, "\\$1"), exports.toPosixSlashes = (str) => str.replace(REGEX_BACKSLASH, "/"), exports.isWindows = () => {
718
- if (typeof navigator !== "undefined" && navigator.platform) {
719
- const platform = navigator.platform.toLowerCase();
720
- return platform === "win32" || platform === "windows";
721
- }
722
- return typeof process !== "undefined" && process.platform ? process.platform === "win32" : false;
723
- }, exports.removeBackslashes = (str) => {
724
- return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
725
- return match === "\\" ? "" : match;
726
- });
727
- }, exports.escapeLast = (input, char, lastIdx) => {
728
- const idx = input.lastIndexOf(char, lastIdx);
729
- return idx === -1 ? input : input[idx - 1] === "\\" ? exports.escapeLast(input, char, idx - 1) : `${input.slice(0, idx)}\\${input.slice(idx)}`;
730
- }, exports.removePrefix = (input, state = {}) => {
731
- let output = input;
732
- if (output.startsWith("./")) output = output.slice(2), state.prefix = "./";
733
- return output;
734
- }, exports.wrapOutput = (input, state = {}, options = {}) => {
735
- const prepend = options.contains ? "" : "^", append = options.contains ? "" : "$";
736
- let output = `${prepend}(?:${input})${append}`;
737
- if (state.negated === true) output = `(?:^(?!${output}).*$)`;
738
- return output;
739
- }, exports.basename = (path$1, { windows } = {}) => {
740
- const segs = path$1.split(windows ? /[\\/]/ : "/"), last = segs[segs.length - 1];
741
- return last === "" ? segs[segs.length - 2] : last;
742
- };
743
- })), require_scan = /* @__PURE__ */ __commonJSMin(((exports, module) => {
744
- const utils$3 = require_utils(), { 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(), isPathSeparator = (code) => {
745
- return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
746
- }, depth = (token) => {
747
- if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1;
748
- }, scan$1 = (input, options) => {
749
- const opts = options || {}, length = input.length - 1, scanToEnd = opts.parts === true || opts.scanToEnd === true, slashes = [], tokens = [], parts = [];
750
- let str = input, index = -1, start = 0, lastIndex = 0, isBrace = false, isBracket = false, isGlob = false, isExtglob = false, isGlobstar = false, braceEscaped = false, backslashes = false, negated = false, negatedExtglob = false, finished = false, braces = 0, prev, code, token = {
751
- value: "",
752
- depth: 0,
753
- isGlob: false
754
- };
755
- const eos = () => index >= length, peek = () => str.charCodeAt(index + 1), advance = () => {
756
- return prev = code, str.charCodeAt(++index);
757
- };
758
- while (index < length) {
759
- code = advance();
760
- let next;
761
- if (code === CHAR_BACKWARD_SLASH) {
762
- if (backslashes = token.backslashes = true, code = advance(), code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true;
763
- continue;
764
- }
765
- if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
766
- braces++;
767
- while (eos() !== true && (code = advance())) {
768
- if (code === CHAR_BACKWARD_SLASH) {
769
- backslashes = token.backslashes = true, advance();
770
- continue;
771
- }
772
- if (code === CHAR_LEFT_CURLY_BRACE) {
773
- braces++;
774
- continue;
775
- }
776
- if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
777
- if (isBrace = token.isBrace = true, isGlob = token.isGlob = true, finished = true, scanToEnd === true) continue;
778
- break;
779
- }
780
- if (braceEscaped !== true && code === CHAR_COMMA) {
781
- if (isBrace = token.isBrace = true, isGlob = token.isGlob = true, finished = true, scanToEnd === true) continue;
782
- break;
783
- }
784
- if (code === CHAR_RIGHT_CURLY_BRACE) {
785
- if (braces--, braces === 0) {
786
- braceEscaped = false, isBrace = token.isBrace = true, finished = true;
787
- break;
788
- }
789
- }
790
- }
791
- if (scanToEnd === true) continue;
792
- break;
793
- }
794
- if (code === CHAR_FORWARD_SLASH) {
795
- if (slashes.push(index), tokens.push(token), token = {
796
- value: "",
797
- depth: 0,
798
- isGlob: false
799
- }, finished === true) continue;
800
- if (prev === CHAR_DOT && index === start + 1) {
801
- start += 2;
802
- continue;
803
- }
804
- lastIndex = index + 1;
805
- continue;
806
- }
807
- if (opts.noext !== true) {
808
- const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
809
- if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
810
- if (isGlob = token.isGlob = true, isExtglob = token.isExtglob = true, finished = true, code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true;
811
- if (scanToEnd === true) {
812
- while (eos() !== true && (code = advance())) {
813
- if (code === CHAR_BACKWARD_SLASH) {
814
- backslashes = token.backslashes = true, code = advance();
815
- continue;
816
- }
817
- if (code === CHAR_RIGHT_PARENTHESES) {
818
- isGlob = token.isGlob = true, finished = true;
819
- break;
820
- }
821
- }
822
- continue;
823
- }
824
- break;
825
- }
826
- }
827
- if (code === CHAR_ASTERISK) {
828
- if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
829
- if (isGlob = token.isGlob = true, finished = true, scanToEnd === true) continue;
830
- break;
831
- }
832
- if (code === CHAR_QUESTION_MARK) {
833
- if (isGlob = token.isGlob = true, finished = true, scanToEnd === true) continue;
834
- break;
835
- }
836
- if (code === CHAR_LEFT_SQUARE_BRACKET) {
837
- while (eos() !== true && (next = advance())) {
838
- if (next === CHAR_BACKWARD_SLASH) {
839
- backslashes = token.backslashes = true, advance();
840
- continue;
841
- }
842
- if (next === CHAR_RIGHT_SQUARE_BRACKET) {
843
- isBracket = token.isBracket = true, isGlob = token.isGlob = true, finished = true;
844
- break;
845
- }
846
- }
847
- if (scanToEnd === true) continue;
848
- break;
849
- }
850
- if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
851
- negated = token.negated = true, start++;
852
- continue;
853
- }
854
- if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
855
- if (isGlob = token.isGlob = true, scanToEnd === true) {
856
- while (eos() !== true && (code = advance())) {
857
- if (code === CHAR_LEFT_PARENTHESES) {
858
- backslashes = token.backslashes = true, code = advance();
859
- continue;
860
- }
861
- if (code === CHAR_RIGHT_PARENTHESES) {
862
- finished = true;
863
- break;
864
- }
865
- }
866
- continue;
867
- }
868
- break;
869
- }
870
- if (isGlob === true) {
871
- if (finished = true, scanToEnd === true) continue;
872
- break;
873
- }
874
- }
875
- if (opts.noext === true) isExtglob = false, isGlob = false;
876
- let base = str, prefix = "", glob$1 = "";
877
- if (start > 0) prefix = str.slice(0, start), str = str.slice(start), lastIndex -= start;
878
- if (base && isGlob === true && lastIndex > 0) base = str.slice(0, lastIndex), glob$1 = str.slice(lastIndex);
879
- else if (isGlob === true) base = "", glob$1 = str;
880
- else base = str;
881
- if (base && base !== "" && base !== "/" && base !== str) {
882
- if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1);
883
- }
884
- if (opts.unescape === true) {
885
- if (glob$1) glob$1 = utils$3.removeBackslashes(glob$1);
886
- if (base && backslashes === true) base = utils$3.removeBackslashes(base);
887
- }
888
- const state = {
889
- prefix,
890
- input,
891
- start,
892
- base,
893
- glob: glob$1,
894
- isBrace,
895
- isBracket,
896
- isGlob,
897
- isExtglob,
898
- isGlobstar,
899
- negated,
900
- negatedExtglob
901
- };
902
- if (opts.tokens === true) {
903
- if (state.maxDepth = 0, !isPathSeparator(code)) tokens.push(token);
904
- state.tokens = tokens;
905
- }
906
- if (opts.parts === true || opts.tokens === true) {
907
- let prevIndex;
908
- for (let idx = 0; idx < slashes.length; idx++) {
909
- const n$1 = prevIndex ? prevIndex + 1 : start, i = slashes[idx], value = input.slice(n$1, i);
910
- if (opts.tokens) {
911
- if (idx === 0 && start !== 0) tokens[idx].isPrefix = true, tokens[idx].value = prefix;
912
- else tokens[idx].value = value;
913
- depth(tokens[idx]), state.maxDepth += tokens[idx].depth;
914
- }
915
- if (idx !== 0 || value !== "") parts.push(value);
916
- prevIndex = i;
917
- }
918
- if (prevIndex && prevIndex + 1 < input.length) {
919
- const value = input.slice(prevIndex + 1);
920
- if (parts.push(value), opts.tokens) tokens[tokens.length - 1].value = value, depth(tokens[tokens.length - 1]), state.maxDepth += tokens[tokens.length - 1].depth;
921
- }
922
- state.slashes = slashes, state.parts = parts;
923
- }
924
- return state;
925
- };
926
- module.exports = scan$1;
927
- })), require_parse = /* @__PURE__ */ __commonJSMin(((exports, module) => {
928
- const constants$1 = require_constants(), utils$2 = require_utils(), { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1, expandRange = (args, options) => {
929
- if (typeof options.expandRange === "function") return options.expandRange(...args, options);
930
- args.sort();
931
- const value = `[${args.join("-")}]`;
932
- try {
933
- new RegExp(value);
934
- } catch (ex) {
935
- return args.map((v$1) => utils$2.escapeRegex(v$1)).join("..");
936
- }
937
- return value;
938
- }, syntaxError = (type, char) => {
939
- return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
940
- }, parse$1 = (input, options) => {
941
- if (typeof input !== "string") throw new TypeError("Expected a string");
942
- input = REPLACEMENTS[input] || input;
943
- const opts = { ...options }, max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
944
- let len = input.length;
945
- if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
946
- const bos = {
947
- type: "bos",
948
- value: "",
949
- output: opts.prepend || ""
950
- }, tokens = [bos], capture = opts.capture ? "" : "?:", PLATFORM_CHARS = constants$1.globChars(opts.windows), EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS), { 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, globstar = (opts$1) => {
951
- return `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
952
- }, nodot = opts.dot ? "" : NO_DOT$1, qmarkNoDot = opts.dot ? QMARK$1 : QMARK_NO_DOT$1;
953
- let star = opts.bash === true ? globstar(opts) : STAR$1;
954
- if (opts.capture) star = `(${star})`;
955
- if (typeof opts.noext === "boolean") opts.noextglob = opts.noext;
956
- const state = {
957
- input,
958
- index: -1,
959
- start: 0,
960
- dot: opts.dot === true,
961
- consumed: "",
962
- output: "",
963
- prefix: "",
964
- backtrack: false,
965
- negated: false,
966
- brackets: 0,
967
- braces: 0,
968
- parens: 0,
969
- quotes: 0,
970
- globstar: false,
971
- tokens
972
- };
973
- input = utils$2.removePrefix(input, state), len = input.length;
974
- const extglobs = [], braces = [], stack = [];
975
- let prev = bos, value;
976
- const eos = () => state.index === len - 1, peek = state.peek = (n$1 = 1) => input[state.index + n$1], advance = state.advance = () => input[++state.index] || "", remaining = () => input.slice(state.index + 1), consume = (value$1 = "", num = 0) => {
977
- state.consumed += value$1, state.index += num;
978
- }, append = (token) => {
979
- state.output += token.output != null ? token.output : token.value, consume(token.value);
980
- }, negate = () => {
981
- let count = 1;
982
- while (peek() === "!" && (peek(2) !== "(" || peek(3) === "?")) advance(), state.start++, count++;
983
- return count % 2 === 0 ? false : (state.negated = true, state.start++, true);
984
- }, increment = (type) => {
985
- state[type]++, stack.push(type);
986
- }, decrement = (type) => {
987
- state[type]--, stack.pop();
988
- }, push = (tok) => {
989
- if (prev.type === "globstar") {
990
- const isBrace = state.braces > 0 && (tok.type === "comma" || tok.type === "brace"), isExtglob = tok.extglob === true || extglobs.length && (tok.type === "pipe" || tok.type === "paren");
991
- if (tok.type !== "slash" && tok.type !== "paren" && !isBrace && !isExtglob) state.output = state.output.slice(0, -prev.output.length), prev.type = "star", prev.value = "*", prev.output = star, state.output += prev.output;
992
- }
993
- if (extglobs.length && tok.type !== "paren") extglobs[extglobs.length - 1].inner += tok.value;
994
- if (tok.value || tok.output) append(tok);
995
- if (prev && prev.type === "text" && tok.type === "text") {
996
- prev.output = (prev.output || prev.value) + tok.value, prev.value += tok.value;
997
- return;
998
- }
999
- tok.prev = prev, tokens.push(tok), prev = tok;
1000
- }, extglobOpen = (type, value$1) => {
1001
- const token = {
1002
- ...EXTGLOB_CHARS[value$1],
1003
- conditions: 1,
1004
- inner: ""
1005
- };
1006
- token.prev = prev, token.parens = state.parens, token.output = state.output;
1007
- const output = (opts.capture ? "(" : "") + token.open;
1008
- increment("parens"), push({
1009
- type,
1010
- value: value$1,
1011
- output: state.output ? "" : ONE_CHAR$1
1012
- }), push({
1013
- type: "paren",
1014
- extglob: true,
1015
- value: advance(),
1016
- output
1017
- }), extglobs.push(token);
1018
- }, extglobClose = (token) => {
1019
- let output = token.close + (opts.capture ? ")" : ""), rest;
1020
- if (token.type === "negate") {
1021
- let extglobStar = star;
1022
- if (token.inner && token.inner.length > 1 && token.inner.includes("/")) extglobStar = globstar(opts);
1023
- if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) output = token.close = `)$))${extglobStar}`;
1024
- if (token.inner.includes("*") && (rest = remaining()) && /^\.[^\\/.]+$/.test(rest)) {
1025
- const expression = parse$1(rest, {
1026
- ...options,
1027
- fastpaths: false
1028
- }).output;
1029
- output = token.close = `)${expression})${extglobStar})`;
1030
- }
1031
- if (token.prev.type === "bos") state.negatedExtglob = true;
1032
- }
1033
- push({
1034
- type: "paren",
1035
- extglob: true,
1036
- value,
1037
- output
1038
- }), decrement("parens");
1039
- };
1040
- if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) {
1041
- let backslashes = false, output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m$1, esc, chars, first, rest, index) => {
1042
- return first === "\\" ? (backslashes = true, m$1) : first === "?" ? esc ? esc + first + (rest ? QMARK$1.repeat(rest.length) : "") : index === 0 ? qmarkNoDot + (rest ? QMARK$1.repeat(rest.length) : "") : QMARK$1.repeat(chars.length) : first === "." ? DOT_LITERAL$1.repeat(chars.length) : first === "*" ? esc ? esc + first + (rest ? star : "") : star : esc ? m$1 : `\\${m$1}`;
1043
- });
1044
- if (backslashes === true) if (opts.unescape === true) output = output.replace(/\\/g, "");
1045
- else output = output.replace(/\\+/g, (m$1) => {
1046
- return m$1.length % 2 === 0 ? "\\\\" : m$1 ? "\\" : "";
1047
- });
1048
- return output === input && opts.contains === true ? (state.output = input, state) : (state.output = utils$2.wrapOutput(output, state, options), state);
1049
- }
1050
- while (!eos()) {
1051
- if (value = advance(), value === "\0") continue;
1052
- if (value === "\\") {
1053
- const next = peek();
1054
- if (next === "/" && opts.bash !== true || next === "." || next === ";") continue;
1055
- if (!next) {
1056
- value += "\\", push({
1057
- type: "text",
1058
- value
1059
- });
1060
- continue;
1061
- }
1062
- const match = /^\\+/.exec(remaining());
1063
- let slashes = 0;
1064
- if (match && match[0].length > 2) {
1065
- if (slashes = match[0].length, state.index += slashes, slashes % 2 !== 0) value += "\\";
1066
- }
1067
- if (opts.unescape === true) value = advance();
1068
- else value += advance();
1069
- if (state.brackets === 0) {
1070
- push({
1071
- type: "text",
1072
- value
1073
- });
1074
- continue;
1075
- }
1076
- }
1077
- if (state.brackets > 0 && (value !== "]" || prev.value === "[" || prev.value === "[^")) {
1078
- if (opts.posix !== false && value === ":") {
1079
- const inner = prev.value.slice(1);
1080
- if (inner.includes("[")) {
1081
- if (prev.posix = true, inner.includes(":")) {
1082
- const idx = prev.value.lastIndexOf("["), pre = prev.value.slice(0, idx), rest$1 = prev.value.slice(idx + 2), posix$1 = POSIX_REGEX_SOURCE[rest$1];
1083
- if (posix$1) {
1084
- if (prev.value = pre + posix$1, state.backtrack = true, advance(), !bos.output && tokens.indexOf(prev) === 1) bos.output = ONE_CHAR$1;
1085
- continue;
1086
- }
1087
- }
1088
- }
1089
- }
1090
- if (value === "[" && peek() !== ":" || value === "-" && peek() === "]") value = `\\${value}`;
1091
- if (value === "]" && (prev.value === "[" || prev.value === "[^")) value = `\\${value}`;
1092
- if (opts.posix === true && value === "!" && prev.value === "[") value = "^";
1093
- prev.value += value, append({ value });
1094
- continue;
1095
- }
1096
- if (state.quotes === 1 && value !== "\"") {
1097
- value = utils$2.escapeRegex(value), prev.value += value, append({ value });
1098
- continue;
1099
- }
1100
- if (value === "\"") {
1101
- if (state.quotes = state.quotes === 1 ? 0 : 1, opts.keepQuotes === true) push({
1102
- type: "text",
1103
- value
1104
- });
1105
- continue;
1106
- }
1107
- if (value === "(") {
1108
- increment("parens"), push({
1109
- type: "paren",
1110
- value
1111
- });
1112
- continue;
1113
- }
1114
- if (value === ")") {
1115
- if (state.parens === 0 && opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "("));
1116
- const extglob = extglobs[extglobs.length - 1];
1117
- if (extglob && state.parens === extglob.parens + 1) {
1118
- extglobClose(extglobs.pop());
1119
- continue;
1120
- }
1121
- push({
1122
- type: "paren",
1123
- value,
1124
- output: state.parens ? ")" : "\\)"
1125
- }), decrement("parens");
1126
- continue;
1127
- }
1128
- if (value === "[") {
1129
- if (opts.nobracket === true || !remaining().includes("]")) {
1130
- if (opts.nobracket !== true && opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
1131
- value = `\\${value}`;
1132
- } else increment("brackets");
1133
- push({
1134
- type: "bracket",
1135
- value
1136
- });
1137
- continue;
1138
- }
1139
- if (value === "]") {
1140
- if (opts.nobracket === true || prev && prev.type === "bracket" && prev.value.length === 1) {
1141
- push({
1142
- type: "text",
1143
- value,
1144
- output: `\\${value}`
1145
- });
1146
- continue;
1147
- }
1148
- if (state.brackets === 0) {
1149
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("opening", "["));
1150
- push({
1151
- type: "text",
1152
- value,
1153
- output: `\\${value}`
1154
- });
1155
- continue;
1156
- }
1157
- decrement("brackets");
1158
- const prevValue = prev.value.slice(1);
1159
- if (prev.posix !== true && prevValue[0] === "^" && !prevValue.includes("/")) value = `/${value}`;
1160
- if (prev.value += value, append({ value }), opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) continue;
1161
- const escaped = utils$2.escapeRegex(prev.value);
1162
- if (state.output = state.output.slice(0, -prev.value.length), opts.literalBrackets === true) {
1163
- state.output += escaped, prev.value = escaped;
1164
- continue;
1165
- }
1166
- prev.value = `(${capture}${escaped}|${prev.value})`, state.output += prev.value;
1167
- continue;
1168
- }
1169
- if (value === "{" && opts.nobrace !== true) {
1170
- increment("braces");
1171
- const open = {
1172
- type: "brace",
1173
- value,
1174
- output: "(",
1175
- outputIndex: state.output.length,
1176
- tokensIndex: state.tokens.length
1177
- };
1178
- braces.push(open), push(open);
1179
- continue;
1180
- }
1181
- if (value === "}") {
1182
- const brace = braces[braces.length - 1];
1183
- if (opts.nobrace === true || !brace) {
1184
- push({
1185
- type: "text",
1186
- value,
1187
- output: value
1188
- });
1189
- continue;
1190
- }
1191
- let output = ")";
1192
- if (brace.dots === true) {
1193
- const arr = tokens.slice(), range = [];
1194
- for (let i = arr.length - 1; i >= 0; i--) {
1195
- if (tokens.pop(), arr[i].type === "brace") break;
1196
- if (arr[i].type !== "dots") range.unshift(arr[i].value);
1197
- }
1198
- output = expandRange(range, opts), state.backtrack = true;
1199
- }
1200
- if (brace.comma !== true && brace.dots !== true) {
1201
- const out = state.output.slice(0, brace.outputIndex), toks = state.tokens.slice(brace.tokensIndex);
1202
- brace.value = brace.output = "\\{", value = output = "\\}", state.output = out;
1203
- for (const t of toks) state.output += t.output || t.value;
1204
- }
1205
- push({
1206
- type: "brace",
1207
- value,
1208
- output
1209
- }), decrement("braces"), braces.pop();
1210
- continue;
1211
- }
1212
- if (value === "|") {
1213
- if (extglobs.length > 0) extglobs[extglobs.length - 1].conditions++;
1214
- push({
1215
- type: "text",
1216
- value
1217
- });
1218
- continue;
1219
- }
1220
- if (value === ",") {
1221
- let output = value;
1222
- const brace = braces[braces.length - 1];
1223
- if (brace && stack[stack.length - 1] === "braces") brace.comma = true, output = "|";
1224
- push({
1225
- type: "comma",
1226
- value,
1227
- output
1228
- });
1229
- continue;
1230
- }
1231
- if (value === "/") {
1232
- if (prev.type === "dot" && state.index === state.start + 1) {
1233
- state.start = state.index + 1, state.consumed = "", state.output = "", tokens.pop(), prev = bos;
1234
- continue;
1235
- }
1236
- push({
1237
- type: "slash",
1238
- value,
1239
- output: SLASH_LITERAL$1
1240
- });
1241
- continue;
1242
- }
1243
- if (value === ".") {
1244
- if (state.braces > 0 && prev.type === "dot") {
1245
- if (prev.value === ".") prev.output = DOT_LITERAL$1;
1246
- const brace = braces[braces.length - 1];
1247
- prev.type = "dots", prev.output += value, prev.value += value, brace.dots = true;
1248
- continue;
1249
- }
1250
- if (state.braces + state.parens === 0 && prev.type !== "bos" && prev.type !== "slash") {
1251
- push({
1252
- type: "text",
1253
- value,
1254
- output: DOT_LITERAL$1
1255
- });
1256
- continue;
1257
- }
1258
- push({
1259
- type: "dot",
1260
- value,
1261
- output: DOT_LITERAL$1
1262
- });
1263
- continue;
1264
- }
1265
- if (value === "?") {
1266
- const isGroup = prev && prev.value === "(";
1267
- if (!isGroup && opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1268
- extglobOpen("qmark", value);
1269
- continue;
1270
- }
1271
- if (prev && prev.type === "paren") {
1272
- const next = peek();
1273
- let output = value;
1274
- if (prev.value === "(" && !/[!=<:]/.test(next) || next === "<" && !/<([!=]|\w+>)/.test(remaining())) output = `\\${value}`;
1275
- push({
1276
- type: "text",
1277
- value,
1278
- output
1279
- });
1280
- continue;
1281
- }
1282
- if (opts.dot !== true && (prev.type === "slash" || prev.type === "bos")) {
1283
- push({
1284
- type: "qmark",
1285
- value,
1286
- output: QMARK_NO_DOT$1
1287
- });
1288
- continue;
1289
- }
1290
- push({
1291
- type: "qmark",
1292
- value,
1293
- output: QMARK$1
1294
- });
1295
- continue;
1296
- }
1297
- if (value === "!") {
1298
- if (opts.noextglob !== true && peek() === "(") {
1299
- if (peek(2) !== "?" || !/[!=<:]/.test(peek(3))) {
1300
- extglobOpen("negate", value);
1301
- continue;
1302
- }
1303
- }
1304
- if (opts.nonegate !== true && state.index === 0) {
1305
- negate();
1306
- continue;
1307
- }
1308
- }
1309
- if (value === "+") {
1310
- if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1311
- extglobOpen("plus", value);
1312
- continue;
1313
- }
1314
- if (prev && prev.value === "(" || opts.regex === false) {
1315
- push({
1316
- type: "plus",
1317
- value,
1318
- output: PLUS_LITERAL$1
1319
- });
1320
- continue;
1321
- }
1322
- if (prev && (prev.type === "bracket" || prev.type === "paren" || prev.type === "brace") || state.parens > 0) {
1323
- push({
1324
- type: "plus",
1325
- value
1326
- });
1327
- continue;
1328
- }
1329
- push({
1330
- type: "plus",
1331
- value: PLUS_LITERAL$1
1332
- });
1333
- continue;
1334
- }
1335
- if (value === "@") {
1336
- if (opts.noextglob !== true && peek() === "(" && peek(2) !== "?") {
1337
- push({
1338
- type: "at",
1339
- extglob: true,
1340
- value,
1341
- output: ""
1342
- });
1343
- continue;
1344
- }
1345
- push({
1346
- type: "text",
1347
- value
1348
- });
1349
- continue;
1350
- }
1351
- if (value !== "*") {
1352
- if (value === "$" || value === "^") value = `\\${value}`;
1353
- const match = REGEX_NON_SPECIAL_CHARS.exec(remaining());
1354
- if (match) value += match[0], state.index += match[0].length;
1355
- push({
1356
- type: "text",
1357
- value
1358
- });
1359
- continue;
1360
- }
1361
- if (prev && (prev.type === "globstar" || prev.star === true)) {
1362
- prev.type = "star", prev.star = true, prev.value += value, prev.output = star, state.backtrack = true, state.globstar = true, consume(value);
1363
- continue;
1364
- }
1365
- let rest = remaining();
1366
- if (opts.noextglob !== true && /^\([^?]/.test(rest)) {
1367
- extglobOpen("star", value);
1368
- continue;
1369
- }
1370
- if (prev.type === "star") {
1371
- if (opts.noglobstar === true) {
1372
- consume(value);
1373
- continue;
1374
- }
1375
- const prior = prev.prev, before = prior.prev, isStart = prior.type === "slash" || prior.type === "bos", afterStar = before && (before.type === "star" || before.type === "globstar");
1376
- if (opts.bash === true && (!isStart || rest[0] && rest[0] !== "/")) {
1377
- push({
1378
- type: "star",
1379
- value,
1380
- output: ""
1381
- });
1382
- continue;
1383
- }
1384
- const isBrace = state.braces > 0 && (prior.type === "comma" || prior.type === "brace"), isExtglob = extglobs.length && (prior.type === "pipe" || prior.type === "paren");
1385
- if (!isStart && prior.type !== "paren" && !isBrace && !isExtglob) {
1386
- push({
1387
- type: "star",
1388
- value,
1389
- output: ""
1390
- });
1391
- continue;
1392
- }
1393
- while (rest.slice(0, 3) === "/**") {
1394
- const after = input[state.index + 4];
1395
- if (after && after !== "/") break;
1396
- rest = rest.slice(3), consume("/**", 3);
1397
- }
1398
- if (prior.type === "bos" && eos()) {
1399
- prev.type = "globstar", prev.value += value, prev.output = globstar(opts), state.output = prev.output, state.globstar = true, consume(value);
1400
- continue;
1401
- }
1402
- if (prior.type === "slash" && prior.prev.type !== "bos" && !afterStar && eos()) {
1403
- state.output = state.output.slice(0, -(prior.output + prev.output).length), prior.output = `(?:${prior.output}`, prev.type = "globstar", prev.output = globstar(opts) + (opts.strictSlashes ? ")" : "|$)"), prev.value += value, state.globstar = true, state.output += prior.output + prev.output, consume(value);
1404
- continue;
1405
- }
1406
- if (prior.type === "slash" && prior.prev.type !== "bos" && rest[0] === "/") {
1407
- const end = rest[1] !== void 0 ? "|$" : "";
1408
- state.output = state.output.slice(0, -(prior.output + prev.output).length), prior.output = `(?:${prior.output}`, prev.type = "globstar", prev.output = `${globstar(opts)}${SLASH_LITERAL$1}|${SLASH_LITERAL$1}${end})`, prev.value += value, state.output += prior.output + prev.output, state.globstar = true, consume(value + advance()), push({
1409
- type: "slash",
1410
- value: "/",
1411
- output: ""
1412
- });
1413
- continue;
1414
- }
1415
- if (prior.type === "bos" && rest[0] === "/") {
1416
- prev.type = "globstar", prev.value += value, prev.output = `(?:^|${SLASH_LITERAL$1}|${globstar(opts)}${SLASH_LITERAL$1})`, state.output = prev.output, state.globstar = true, consume(value + advance()), push({
1417
- type: "slash",
1418
- value: "/",
1419
- output: ""
1420
- });
1421
- continue;
1422
- }
1423
- state.output = state.output.slice(0, -prev.output.length), prev.type = "globstar", prev.output = globstar(opts), prev.value += value, state.output += prev.output, state.globstar = true, consume(value);
1424
- continue;
1425
- }
1426
- const token = {
1427
- type: "star",
1428
- value,
1429
- output: star
1430
- };
1431
- if (opts.bash === true) {
1432
- if (token.output = ".*?", prev.type === "bos" || prev.type === "slash") token.output = nodot + token.output;
1433
- push(token);
1434
- continue;
1435
- }
1436
- if (prev && (prev.type === "bracket" || prev.type === "paren") && opts.regex === true) {
1437
- token.output = value, push(token);
1438
- continue;
1439
- }
1440
- if (state.index === state.start || prev.type === "slash" || prev.type === "dot") {
1441
- if (prev.type === "dot") state.output += NO_DOT_SLASH$1, prev.output += NO_DOT_SLASH$1;
1442
- else if (opts.dot === true) state.output += NO_DOTS_SLASH$1, prev.output += NO_DOTS_SLASH$1;
1443
- else state.output += nodot, prev.output += nodot;
1444
- if (peek() !== "*") state.output += ONE_CHAR$1, prev.output += ONE_CHAR$1;
1445
- }
1446
- push(token);
1447
- }
1448
- while (state.brackets > 0) {
1449
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "]"));
1450
- state.output = utils$2.escapeLast(state.output, "["), decrement("brackets");
1451
- }
1452
- while (state.parens > 0) {
1453
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", ")"));
1454
- state.output = utils$2.escapeLast(state.output, "("), decrement("parens");
1455
- }
1456
- while (state.braces > 0) {
1457
- if (opts.strictBrackets === true) throw new SyntaxError(syntaxError("closing", "}"));
1458
- state.output = utils$2.escapeLast(state.output, "{"), decrement("braces");
1459
- }
1460
- if (opts.strictSlashes !== true && (prev.type === "star" || prev.type === "bracket")) push({
1461
- type: "maybe_slash",
1462
- value: "",
1463
- output: `${SLASH_LITERAL$1}?`
1464
- });
1465
- if (state.backtrack === true) {
1466
- state.output = "";
1467
- for (const token of state.tokens) if (state.output += token.output != null ? token.output : token.value, token.suffix) state.output += token.suffix;
1468
- }
1469
- return state;
1470
- };
1471
- parse$1.fastpaths = (input, options) => {
1472
- const opts = { ...options }, max = typeof opts.maxLength === "number" ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH, len = input.length;
1473
- if (len > max) throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
1474
- input = REPLACEMENTS[input] || input;
1475
- 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), nodot = opts.dot ? NO_DOTS$1 : NO_DOT$1, slashDot = opts.dot ? NO_DOTS_SLASH$1 : NO_DOT$1, capture = opts.capture ? "" : "?:", state = {
1476
- negated: false,
1477
- prefix: ""
1478
- };
1479
- let star = opts.bash === true ? ".*?" : STAR$1;
1480
- if (opts.capture) star = `(${star})`;
1481
- const globstar = (opts$1) => {
1482
- return opts$1.noglobstar === true ? star : `(${capture}(?:(?!${START_ANCHOR$1}${opts$1.dot ? DOTS_SLASH$1 : DOT_LITERAL$1}).)*?)`;
1483
- }, create = (str) => {
1484
- switch (str) {
1485
- case "*": return `${nodot}${ONE_CHAR$1}${star}`;
1486
- case ".*": return `${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
1487
- case "*.*": return `${nodot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
1488
- case "*/*": return `${nodot}${star}${SLASH_LITERAL$1}${ONE_CHAR$1}${slashDot}${star}`;
1489
- case "**": return nodot + globstar(opts);
1490
- case "**/*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${ONE_CHAR$1}${star}`;
1491
- case "**/*.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${slashDot}${star}${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
1492
- case "**/.*": return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL$1})?${DOT_LITERAL$1}${ONE_CHAR$1}${star}`;
1493
- default: {
1494
- const match = /^(.*?)\.(\w+)$/.exec(str);
1495
- if (!match) return;
1496
- const source$1 = create(match[1]);
1497
- return source$1 ? source$1 + DOT_LITERAL$1 + match[2] : void 0;
1498
- }
1499
- }
1500
- }, output = utils$2.removePrefix(input, state);
1501
- let source = create(output);
1502
- if (source && opts.strictSlashes !== true) source += `${SLASH_LITERAL$1}?`;
1503
- return source;
1504
- }, module.exports = parse$1;
1505
- })), require_picomatch$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1506
- const scan = require_scan(), parse = require_parse(), utils$1 = require_utils(), constants = require_constants(), isObject = (val) => val && typeof val === "object" && !Array.isArray(val), picomatch$2 = (glob$1, options, returnState = false) => {
1507
- if (Array.isArray(glob$1)) {
1508
- const fns = glob$1.map((input) => picomatch$2(input, options, returnState)), arrayMatcher = (str) => {
1509
- for (const isMatch of fns) {
1510
- const state$1 = isMatch(str);
1511
- if (state$1) return state$1;
1512
- }
1513
- return false;
1514
- };
1515
- return arrayMatcher;
1516
- }
1517
- const isState = isObject(glob$1) && glob$1.tokens && glob$1.input;
1518
- if (glob$1 === "" || typeof glob$1 !== "string" && !isState) throw new TypeError("Expected pattern to be a non-empty string");
1519
- const opts = options || {}, posix$1 = opts.windows, regex = isState ? picomatch$2.compileRe(glob$1, options) : picomatch$2.makeRe(glob$1, options, false, true), state = regex.state;
1520
- delete regex.state;
1521
- let isIgnored = () => false;
1522
- if (opts.ignore) {
1523
- const ignoreOpts = {
1524
- ...options,
1525
- ignore: null,
1526
- onMatch: null,
1527
- onResult: null
1528
- };
1529
- isIgnored = picomatch$2(opts.ignore, ignoreOpts, returnState);
1530
- }
1531
- const matcher = (input, returnObject = false) => {
1532
- const { isMatch, match, output } = picomatch$2.test(input, regex, options, {
1533
- glob: glob$1,
1534
- posix: posix$1
1535
- }), result = {
1536
- glob: glob$1,
1537
- state,
1538
- regex,
1539
- posix: posix$1,
1540
- input,
1541
- output,
1542
- match,
1543
- isMatch
1544
- };
1545
- if (typeof opts.onResult === "function") opts.onResult(result);
1546
- if (isMatch === false) return result.isMatch = false, returnObject ? result : false;
1547
- if (isIgnored(input)) {
1548
- if (typeof opts.onIgnore === "function") opts.onIgnore(result);
1549
- return result.isMatch = false, returnObject ? result : false;
1550
- }
1551
- if (typeof opts.onMatch === "function") opts.onMatch(result);
1552
- return returnObject ? result : true;
1553
- };
1554
- if (returnState) matcher.state = state;
1555
- return matcher;
1556
- };
1557
- picomatch$2.test = (input, regex, options, { glob: glob$1, posix: posix$1 } = {}) => {
1558
- if (typeof input !== "string") throw new TypeError("Expected input to be a string");
1559
- if (input === "") return {
1560
- isMatch: false,
1561
- output: ""
1562
- };
1563
- const opts = options || {}, format = opts.format || (posix$1 ? utils$1.toPosixSlashes : null);
1564
- let match = input === glob$1, output = match && format ? format(input) : input;
1565
- if (match === false) output = format ? format(input) : input, match = output === glob$1;
1566
- if (match === false || opts.capture === true) if (opts.matchBase === true || opts.basename === true) match = picomatch$2.matchBase(input, regex, options, posix$1);
1567
- else match = regex.exec(output);
1568
- return {
1569
- isMatch: Boolean(match),
1570
- match,
1571
- output
1572
- };
1573
- }, picomatch$2.matchBase = (input, glob$1, options) => {
1574
- const regex = glob$1 instanceof RegExp ? glob$1 : picomatch$2.makeRe(glob$1, options);
1575
- return regex.test(utils$1.basename(input));
1576
- }, picomatch$2.isMatch = (str, patterns, options) => picomatch$2(patterns, options)(str), picomatch$2.parse = (pattern, options) => {
1577
- return Array.isArray(pattern) ? pattern.map((p) => picomatch$2.parse(p, options)) : parse(pattern, {
1578
- ...options,
1579
- fastpaths: false
1580
- });
1581
- }, picomatch$2.scan = (input, options) => scan(input, options), picomatch$2.compileRe = (state, options, returnOutput = false, returnState = false) => {
1582
- if (returnOutput === true) return state.output;
1583
- const opts = options || {}, prepend = opts.contains ? "" : "^", append = opts.contains ? "" : "$";
1584
- let source = `${prepend}(?:${state.output})${append}`;
1585
- if (state && state.negated === true) source = `^(?!${source}).*$`;
1586
- const regex = picomatch$2.toRegex(source, options);
1587
- if (returnState === true) regex.state = state;
1588
- return regex;
1589
- }, picomatch$2.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
1590
- if (!input || typeof input !== "string") throw new TypeError("Expected a non-empty string");
1591
- let parsed = {
1592
- negated: false,
1593
- fastpaths: true
1594
- };
1595
- if (options.fastpaths !== false && (input[0] === "." || input[0] === "*")) parsed.output = parse.fastpaths(input, options);
1596
- if (!parsed.output) parsed = parse(input, options);
1597
- return picomatch$2.compileRe(parsed, options, returnOutput, returnState);
1598
- }, picomatch$2.toRegex = (source, options) => {
1599
- try {
1600
- const opts = options || {};
1601
- return new RegExp(source, opts.flags || (opts.nocase ? "i" : ""));
1602
- } catch (err) {
1603
- if (options && options.debug === true) throw err;
1604
- return /$^/;
1605
- }
1606
- }, picomatch$2.constants = constants, module.exports = picomatch$2;
1607
- })), require_picomatch = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1608
- const pico = require_picomatch$1(), utils = require_utils();
1609
- function picomatch$1(glob$1, options, returnState = false) {
1610
- if (options && (options.windows === null || options.windows === void 0)) options = {
1611
- ...options,
1612
- windows: utils.isWindows()
1613
- };
1614
- return pico(glob$1, options, returnState);
1615
- }
1616
- Object.assign(picomatch$1, pico), module.exports = picomatch$1;
1617
- })), require_builder = /* @__PURE__ */ __commonJSMin(((exports) => {
1618
- Object.defineProperty(exports, "__esModule", { value: true }), exports.Builder = void 0;
1619
- const path_1 = __require("node:path"), api_builder_1 = require_api_builder();
1620
- var pm = null;
1621
- /* c8 ignore next 6 */
1622
- try {
1623
- __require.resolve("picomatch"), pm = require_picomatch();
1624
- } catch (_e) {}
1625
- var Builder = class {
1626
- globCache = {};
1627
- options = {
1628
- maxDepth: Infinity,
1629
- suppressErrors: true,
1630
- pathSeparator: path_1.sep,
1631
- filters: []
1632
- };
1633
- globFunction;
1634
- constructor(options) {
1635
- this.options = {
1636
- ...this.options,
1637
- ...options
1638
- }, this.globFunction = this.options.globFunction;
1639
- }
1640
- group() {
1641
- return this.options.group = true, this;
1642
- }
1643
- withPathSeparator(separator) {
1644
- return this.options.pathSeparator = separator, this;
1645
- }
1646
- withBasePath() {
1647
- return this.options.includeBasePath = true, this;
1648
- }
1649
- withRelativePaths() {
1650
- return this.options.relativePaths = true, this;
1651
- }
1652
- withDirs() {
1653
- return this.options.includeDirs = true, this;
1654
- }
1655
- withMaxDepth(depth$1) {
1656
- return this.options.maxDepth = depth$1, this;
1657
- }
1658
- withMaxFiles(limit) {
1659
- return this.options.maxFiles = limit, this;
1660
- }
1661
- withFullPaths() {
1662
- return this.options.resolvePaths = true, this.options.includeBasePath = true, this;
1663
- }
1664
- withErrors() {
1665
- return this.options.suppressErrors = false, this;
1666
- }
1667
- withSymlinks({ resolvePaths = true } = {}) {
1668
- return this.options.resolveSymlinks = true, this.options.useRealPaths = resolvePaths, this.withFullPaths();
1669
- }
1670
- withAbortSignal(signal) {
1671
- return this.options.signal = signal, this;
1672
- }
1673
- normalize() {
1674
- return this.options.normalizePath = true, this;
1675
- }
1676
- filter(predicate) {
1677
- return this.options.filters.push(predicate), this;
1678
- }
1679
- onlyDirs() {
1680
- return this.options.excludeFiles = true, this.options.includeDirs = true, this;
1681
- }
1682
- exclude(predicate) {
1683
- return this.options.exclude = predicate, this;
1684
- }
1685
- onlyCounts() {
1686
- return this.options.onlyCounts = true, this;
1687
- }
1688
- crawl(root) {
1689
- return new api_builder_1.APIBuilder(root || ".", this.options);
1690
- }
1691
- withGlobFunction(fn) {
1692
- return this.globFunction = fn, this;
1693
- }
1694
- /* c8 ignore next 4 */
1695
- crawlWithOptions(root, options) {
1696
- return this.options = {
1697
- ...this.options,
1698
- ...options
1699
- }, new api_builder_1.APIBuilder(root || ".", this.options);
1700
- }
1701
- glob(...patterns) {
1702
- return this.globFunction ? this.globWithOptions(patterns) : this.globWithOptions(patterns, ...[{ dot: true }]);
1703
- }
1704
- globWithOptions(patterns, ...options) {
1705
- const globFn = this.globFunction || pm;
1706
- /* c8 ignore next 5 */
1707
- if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
1708
- var isMatch = this.globCache[patterns.join("\0")];
1709
- if (!isMatch) isMatch = globFn(patterns, ...options), this.globCache[patterns.join("\0")] = isMatch;
1710
- return this.options.filters.push((path$1) => isMatch(path$1)), this;
1711
- }
1712
- };
1713
- exports.Builder = Builder;
1714
- })), require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
1715
- Object.defineProperty(exports, "__esModule", { value: true });
1716
- })), require_dist = /* @__PURE__ */ __commonJSMin(((exports) => {
1717
- var __createBinding = exports && exports.__createBinding || (Object.create ? (function(o, m$1, k$1, k2) {
1718
- if (k2 === void 0) k2 = k$1;
1719
- var desc = Object.getOwnPropertyDescriptor(m$1, k$1);
1720
- if (!desc || ("get" in desc ? !m$1.__esModule : desc.writable || desc.configurable)) desc = {
1721
- enumerable: true,
1722
- get: function() {
1723
- return m$1[k$1];
1724
- }
1725
- };
1726
- Object.defineProperty(o, k2, desc);
1727
- }) : (function(o, m$1, k$1, k2) {
1728
- if (k2 === void 0) k2 = k$1;
1729
- o[k2] = m$1[k$1];
1730
- })), __exportStar = exports && exports.__exportStar || function(m$1, exports$1) {
1731
- for (var p in m$1) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m$1, p);
1732
- };
1733
- Object.defineProperty(exports, "__esModule", { value: true }), exports.fdir = void 0;
1734
- const builder_1 = require_builder();
1735
- Object.defineProperty(exports, "fdir", {
1736
- enumerable: true,
1737
- get: function() {
1738
- return builder_1.Builder;
1739
- }
1740
- }), __exportStar(require_types(), exports);
1741
- })), import_dist = /* @__PURE__ */ __toESM(require_dist(), 1), import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
1742
- const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
1743
- function getPartialMatcher(patterns, options) {
1744
- const patternsCount = patterns.length, patternsParts = Array(patternsCount), regexes = Array(patternsCount);
1745
- for (let i = 0; i < patternsCount; i++) {
1746
- const parts = splitPattern(patterns[i]);
1747
- patternsParts[i] = parts;
1748
- const partsCount = parts.length, partRegexes = Array(partsCount);
1749
- for (let j$1 = 0; j$1 < partsCount; j$1++) partRegexes[j$1] = import_picomatch.default.makeRe(parts[j$1], options);
1750
- regexes[i] = partRegexes;
1751
- }
1752
- return (input) => {
1753
- const inputParts = input.split("/");
1754
- if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
1755
- for (let i = 0; i < patterns.length; i++) {
1756
- const patternParts = patternsParts[i], regex = regexes[i], inputPatternCount = inputParts.length, minParts = Math.min(inputPatternCount, patternParts.length);
1757
- let j$1 = 0;
1758
- while (j$1 < minParts) {
1759
- const part = patternParts[j$1];
1760
- if (part.includes("/")) return true;
1761
- const match = regex[j$1].test(inputParts[j$1]);
1762
- if (!match) break;
1763
- if (part === "**") return true;
1764
- j$1++;
1765
- }
1766
- if (j$1 === inputPatternCount) return true;
1767
- }
1768
- return false;
1769
- };
1770
- }
1771
- const splitPatternOptions = { parts: true };
1772
- function splitPattern(path$1) {
1773
- var _result$parts;
1774
- const result = import_picomatch.default.scan(path$1, splitPatternOptions);
1775
- return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1];
1776
- }
1777
- const isWin = process.platform === "win32", POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g, WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g, escapePosixPath = (path$1) => path$1.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&"), escapeWin32Path = (path$1) => path$1.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&"), escapePath = isWin ? escapeWin32Path : escapePosixPath;
1778
- function isDynamicPattern(pattern, options) {
1779
- if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
1780
- const scan$2 = import_picomatch.default.scan(pattern);
1781
- return scan$2.isGlob || scan$2.negated;
1782
- }
1783
- function log(...tasks) {
1784
- console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
1785
- }
1786
- const PARENT_DIRECTORY = /^(\/?\.\.)+/, ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g, BACKSLASHES = /\\/g;
1787
- function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) {
1788
- let result = pattern;
1789
- if (pattern.endsWith("/")) result = pattern.slice(0, -1);
1790
- if (!result.endsWith("*") && expandDirectories) result += "/**";
1791
- const escapedCwd = escapePath(cwd);
1792
- if (path.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = posix.relative(escapedCwd, result);
1793
- else result = posix.normalize(result);
1794
- const parentDirectoryMatch = PARENT_DIRECTORY.exec(result), parts = splitPattern(result);
1795
- if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) {
1796
- const n$1 = (parentDirectoryMatch[0].length + 1) / 3;
1797
- let i = 0;
1798
- const cwdParts = escapedCwd.split("/");
1799
- while (i < n$1 && parts[i + n$1] === cwdParts[cwdParts.length + i - n$1]) result = result.slice(0, (n$1 - i - 1) * 3) + result.slice((n$1 - i) * 3 + parts[i + n$1].length + 1) || ".", i++;
1800
- const potentialRoot = posix.join(cwd, parentDirectoryMatch[0].slice(i * 3));
1801
- if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) props.root = potentialRoot, props.depthOffset = -n$1 + i;
1802
- }
1803
- if (!isIgnore && props.depthOffset >= 0) {
1804
- var _props$commonPath;
1805
- (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
1806
- const newCommonPath = [], length = Math.min(props.commonPath.length, parts.length);
1807
- for (let i = 0; i < length; i++) {
1808
- const part = parts[i];
1809
- if (part === "**" && !parts[i + 1]) {
1810
- newCommonPath.pop();
1811
- break;
1812
- }
1813
- if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break;
1814
- newCommonPath.push(part);
1815
- }
1816
- props.depthOffset = newCommonPath.length, props.commonPath = newCommonPath, props.root = newCommonPath.length > 0 ? path.posix.join(cwd, ...newCommonPath) : cwd;
1817
- }
1818
- return result;
1819
- }
1820
- function processPatterns({ patterns, ignore = [], expandDirectories = true }, cwd, props) {
1821
- if (typeof patterns === "string") patterns = [patterns];
1822
- else if (!patterns) patterns = ["**/*"];
1823
- if (typeof ignore === "string") ignore = [ignore];
1824
- const matchPatterns = [], ignorePatterns = [];
1825
- for (const pattern of ignore) {
1826
- if (!pattern) continue;
1827
- if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true));
1828
- }
1829
- for (const pattern of patterns) {
1830
- if (!pattern) continue;
1831
- if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false));
1832
- else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true));
1833
- }
1834
- return {
1835
- match: matchPatterns,
1836
- ignore: ignorePatterns
1837
- };
1838
- }
1839
- function getRelativePath(path$1, cwd, root) {
1840
- return posix.relative(cwd, `${root}/${path$1}`) || ".";
1841
- }
1842
- function processPath(path$1, cwd, root, isDirectory$1, absolute) {
1843
- const relativePath = absolute ? path$1.slice(root === "/" ? 1 : root.length + 1) || "." : path$1;
1844
- return root === cwd ? isDirectory$1 && relativePath !== "." ? relativePath.slice(0, -1) : relativePath : getRelativePath(relativePath, cwd, root);
1845
- }
1846
- function formatPaths(paths, cwd, root) {
1847
- for (let i = paths.length - 1; i >= 0; i--) {
1848
- const path$1 = paths[i];
1849
- paths[i] = getRelativePath(path$1, cwd, root) + (!path$1 || path$1.endsWith("/") ? "/" : "");
1850
- }
1851
- return paths;
1852
- }
1853
- function crawl(options, cwd, sync$1) {
1854
- if (process.env.TINYGLOBBY_DEBUG) options.debug = true;
1855
- if (options.debug) log("globbing with options:", options, "cwd:", cwd);
1856
- if (Array.isArray(options.patterns) && options.patterns.length === 0) return sync$1 ? [] : Promise.resolve([]);
1857
- const props = {
1858
- root: cwd,
1859
- commonPath: null,
1860
- depthOffset: 0
1861
- }, processed = processPatterns(options, cwd, props), nocase = options.caseSensitiveMatch === false;
1862
- if (options.debug) log("internal processing patterns:", processed);
1863
- const matcher = (0, import_picomatch.default)(processed.match, {
1864
- dot: options.dot,
1865
- nocase,
1866
- ignore: processed.ignore
1867
- }), ignore = (0, import_picomatch.default)(processed.ignore, {
1868
- dot: options.dot,
1869
- nocase
1870
- }), partialMatcher = getPartialMatcher(processed.match, {
1871
- dot: options.dot,
1872
- nocase
1873
- }), fdirOptions = {
1874
- filters: [options.debug ? (p, isDirectory$1) => {
1875
- const path$1 = processPath(p, cwd, props.root, isDirectory$1, options.absolute), matches = matcher(path$1);
1876
- if (matches) log(`matched ${path$1}`);
1877
- return matches;
1878
- } : (p, isDirectory$1) => matcher(processPath(p, cwd, props.root, isDirectory$1, options.absolute))],
1879
- exclude: options.debug ? (_, p) => {
1880
- const relativePath = processPath(p, cwd, props.root, true, true), skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
1881
- if (skipped) log(`skipped ${p}`);
1882
- else log(`crawling ${p}`);
1883
- return skipped;
1884
- } : (_, p) => {
1885
- const relativePath = processPath(p, cwd, props.root, true, true);
1886
- return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
1887
- },
1888
- pathSeparator: "/",
1889
- relativePaths: true,
1890
- resolveSymlinks: true
1891
- };
1892
- if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset);
1893
- if (options.absolute) fdirOptions.relativePaths = false, fdirOptions.resolvePaths = true, fdirOptions.includeBasePath = true;
1894
- if (options.followSymbolicLinks === false) fdirOptions.resolveSymlinks = false, fdirOptions.excludeSymlinks = true;
1895
- if (options.onlyDirectories) fdirOptions.excludeFiles = true, fdirOptions.includeDirs = true;
1896
- else if (options.onlyFiles === false) fdirOptions.includeDirs = true;
1897
- props.root = props.root.replace(BACKSLASHES, "");
1898
- const root = props.root;
1899
- if (options.debug) log("internal properties:", props);
1900
- const api = new import_dist.fdir(fdirOptions).crawl(root);
1901
- return cwd === root || options.absolute ? sync$1 ? api.sync() : api.withPromise() : sync$1 ? formatPaths(api.sync(), cwd, root) : api.withPromise().then((paths) => formatPaths(paths, cwd, root));
1902
- }
1903
- async function glob(patternsOrOptions, options) {
1904
- if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
1905
- const opts = Array.isArray(patternsOrOptions) || typeof patternsOrOptions === "string" ? {
1906
- ...options,
1907
- patterns: patternsOrOptions
1908
- } : patternsOrOptions, cwd = opts.cwd ? path.resolve(opts.cwd).replace(BACKSLASHES, "/") : process.cwd().replace(BACKSLASHES, "/");
1909
- return crawl(opts, cwd, false);
1910
- }
1911
- var castComparer = function(comparer) {
1912
- return function(a$1, b$1, order) {
1913
- return comparer(a$1, b$1, order) * order;
1914
- };
1915
- }, throwInvalidConfigErrorIfTrue = function(condition, context) {
1916
- if (condition) throw Error("Invalid sort config: " + context);
1917
- }, unpackObjectSorter = function(sortByObj) {
1918
- var _a = sortByObj || {}, asc = _a.asc, desc = _a.desc, order = asc ? 1 : -1, sortBy = asc || desc;
1919
- throwInvalidConfigErrorIfTrue(!sortBy, "Expected `asc` or `desc` property"), throwInvalidConfigErrorIfTrue(asc && desc, "Ambiguous object with `asc` and `desc` config properties");
1920
- var comparer = sortByObj.comparer && castComparer(sortByObj.comparer);
1921
- return {
1922
- order,
1923
- sortBy,
1924
- comparer
1925
- };
1926
- }, multiPropertySorterProvider = function(defaultComparer$1) {
1927
- return function multiPropertySorter(sortBy, sortByArr, depth$1, order, comparer, a$1, b$1) {
1928
- var valA, valB;
1929
- if (typeof sortBy === "string") valA = a$1[sortBy], valB = b$1[sortBy];
1930
- else if (typeof sortBy === "function") valA = sortBy(a$1), valB = sortBy(b$1);
1931
- else {
1932
- var objectSorterConfig = unpackObjectSorter(sortBy);
1933
- return multiPropertySorter(objectSorterConfig.sortBy, sortByArr, depth$1, objectSorterConfig.order, objectSorterConfig.comparer || defaultComparer$1, a$1, b$1);
1934
- }
1935
- var equality = comparer(valA, valB, order);
1936
- return (equality === 0 || valA == null && valB == null) && sortByArr.length > depth$1 ? multiPropertySorter(sortByArr[depth$1], sortByArr, depth$1 + 1, order, comparer, a$1, b$1) : equality;
1937
- };
1938
- };
1939
- function getSortStrategy(sortBy, comparer, order) {
1940
- if (sortBy === void 0 || sortBy === true) return function(a$1, b$1) {
1941
- return comparer(a$1, b$1, order);
1942
- };
1943
- if (typeof sortBy === "string") return throwInvalidConfigErrorIfTrue(sortBy.includes("."), "String syntax not allowed for nested properties."), function(a$1, b$1) {
1944
- return comparer(a$1[sortBy], b$1[sortBy], order);
1945
- };
1946
- if (typeof sortBy === "function") return function(a$1, b$1) {
1947
- return comparer(sortBy(a$1), sortBy(b$1), order);
1948
- };
1949
- if (Array.isArray(sortBy)) {
1950
- var multiPropSorter_1 = multiPropertySorterProvider(comparer);
1951
- return function(a$1, b$1) {
1952
- return multiPropSorter_1(sortBy[0], sortBy, 1, order, comparer, a$1, b$1);
1953
- };
1954
- }
1955
- var objectSorterConfig = unpackObjectSorter(sortBy);
1956
- return getSortStrategy(objectSorterConfig.sortBy, objectSorterConfig.comparer || comparer, objectSorterConfig.order);
1957
- }
1958
- var sortArray = function(order, ctx, sortBy, comparer) {
1959
- var _a;
1960
- if (!Array.isArray(ctx)) return ctx;
1961
- if (Array.isArray(sortBy) && sortBy.length < 2) _a = sortBy, sortBy = _a[0];
1962
- return ctx.sort(getSortStrategy(sortBy, comparer, order));
1963
- };
1964
- function createNewSortInstance(opts) {
1965
- var comparer = castComparer(opts.comparer);
1966
- return function(arrayToSort) {
1967
- var ctx = Array.isArray(arrayToSort) && !opts.inPlaceSorting ? arrayToSort.slice() : arrayToSort;
1968
- return {
1969
- asc: function(sortBy) {
1970
- return sortArray(1, ctx, sortBy, comparer);
1971
- },
1972
- desc: function(sortBy) {
1973
- return sortArray(-1, ctx, sortBy, comparer);
1974
- },
1975
- by: function(sortBy) {
1976
- return sortArray(1, ctx, sortBy, comparer);
1977
- }
1978
- };
1979
- };
1980
- }
1981
- var defaultComparer = function(a$1, b$1, order) {
1982
- return a$1 == null ? order : b$1 == null ? -order : typeof a$1 === typeof b$1 ? a$1 < b$1 ? -1 : a$1 > b$1 ? 1 : 0 : typeof a$1 < typeof b$1 ? -1 : 1;
1983
- }, sort = createNewSortInstance({ comparer: defaultComparer }), inPlaceSort = createNewSortInstance({
1984
- comparer: defaultComparer,
1985
- inPlaceSorting: true
1986
- }), import_usingCtx$1 = /* @__PURE__ */ __toESM(require_usingCtx(), 1);
1987
- function unreachable(value) {
1988
- throw new Error(`Unreachable code reached with value: ${value}`);
1989
- }
1990
- async function getFileModifiedTime(filePath) {
1991
- return pipe(try_({
1992
- try: stat(filePath),
1993
- catch: (error) => error
1994
- }), map((stats) => stats.mtime.getTime()), unwrap(0));
1995
- }
1996
- function createDateFormatter(timezone, locale) {
1997
- return new Intl.DateTimeFormat(locale, {
1998
- year: "numeric",
1999
- month: "2-digit",
2000
- day: "2-digit",
2001
- timeZone: timezone
2002
- });
2003
- }
2004
- function createDatePartsFormatter(timezone, locale) {
2005
- return new Intl.DateTimeFormat(locale, {
2006
- year: "numeric",
2007
- month: "2-digit",
2008
- day: "2-digit",
2009
- timeZone: timezone
2010
- });
2011
- }
2012
- function formatDate(dateStr, timezone, locale) {
2013
- const date = new Date(dateStr), formatter = createDateFormatter(timezone, locale ?? DEFAULT_LOCALE);
2014
- return formatter.format(date);
2015
- }
2016
- function formatDateCompact(dateStr, timezone, locale) {
2017
- const parseResult = dailyDateSchema.safeParse(dateStr), date = parseResult.success ? timezone != null ? /* @__PURE__ */ new Date(`${dateStr}T00:00:00Z`) : /* @__PURE__ */ new Date(`${dateStr}T00:00:00`) : new Date(dateStr), formatter = createDatePartsFormatter(timezone, locale), parts = formatter.formatToParts(date), year = parts.find((p) => p.type === "year")?.value ?? "", month = parts.find((p) => p.type === "month")?.value ?? "", day = parts.find((p) => p.type === "day")?.value ?? "";
2018
- return `${year}\n${month}-${day}`;
2019
- }
2020
- function sortByDate(items, getDate, order = "desc") {
2021
- const sorted = sort(items);
2022
- switch (order) {
2023
- case "desc": return sorted.desc((item) => new Date(getDate(item)).getTime());
2024
- case "asc": return sorted.asc((item) => new Date(getDate(item)).getTime());
2025
- default: unreachable(order);
2026
- }
2027
- }
2028
- function filterByDateRange(items, getDate, since, until) {
2029
- return since == null && until == null ? items : items.filter((item) => {
2030
- const dateStr = getDate(item).substring(0, 10).replace(/-/g, "");
2031
- return !(since != null && dateStr < since || until != null && dateStr > until);
2032
- });
2033
- }
2034
- function getDateWeek(date, startDay) {
2035
- const d$1 = new Date(date), day = d$1.getDay(), shift = (day - startDay + 7) % 7;
2036
- return d$1.setDate(d$1.getDate() - shift), createWeeklyDate(d$1.toISOString().substring(0, 10));
2037
- }
2038
- function getDayNumber(day) {
2039
- const dayMap = {
2040
- sunday: 0,
2041
- monday: 1,
2042
- tuesday: 2,
2043
- wednesday: 3,
2044
- thursday: 4,
2045
- friday: 5,
2046
- saturday: 6
2047
- };
2048
- return dayMap[day];
2049
- }
2050
- const DEFAULT_SESSION_DURATION_HOURS = 5;
2051
- function floorToHour(timestamp) {
2052
- const floored = new Date(timestamp);
2053
- return floored.setUTCMinutes(0, 0, 0), floored;
2054
- }
2055
- function identifySessionBlocks(entries, sessionDurationHours = DEFAULT_SESSION_DURATION_HOURS) {
2056
- if (entries.length === 0) return [];
2057
- const sessionDurationMs = sessionDurationHours * 60 * 60 * 1e3, blocks = [], sortedEntries = [...entries].sort((a$1, b$1) => a$1.timestamp.getTime() - b$1.timestamp.getTime());
2058
- let currentBlockStart = null, currentBlockEntries = [];
2059
- const now = /* @__PURE__ */ new Date();
2060
- for (const entry of sortedEntries) {
2061
- const entryTime = entry.timestamp;
2062
- if (currentBlockStart == null) currentBlockStart = floorToHour(entryTime), currentBlockEntries = [entry];
2063
- else {
2064
- const timeSinceBlockStart = entryTime.getTime() - currentBlockStart.getTime(), lastEntry = currentBlockEntries.at(-1);
2065
- if (lastEntry == null) continue;
2066
- const lastEntryTime = lastEntry.timestamp, timeSinceLastEntry = entryTime.getTime() - lastEntryTime.getTime();
2067
- if (timeSinceBlockStart > sessionDurationMs || timeSinceLastEntry > sessionDurationMs) {
2068
- const block = createBlock(currentBlockStart, currentBlockEntries, now, sessionDurationMs);
2069
- if (blocks.push(block), timeSinceLastEntry > sessionDurationMs) {
2070
- const gapBlock = createGapBlock(lastEntryTime, entryTime, sessionDurationMs);
2071
- if (gapBlock != null) blocks.push(gapBlock);
2072
- }
2073
- currentBlockStart = floorToHour(entryTime), currentBlockEntries = [entry];
2074
- } else currentBlockEntries.push(entry);
2075
- }
2076
- }
2077
- if (currentBlockStart != null && currentBlockEntries.length > 0) {
2078
- const block = createBlock(currentBlockStart, currentBlockEntries, now, sessionDurationMs);
2079
- blocks.push(block);
2080
- }
2081
- return blocks;
2082
- }
2083
- function createBlock(startTime, entries, now, sessionDurationMs) {
2084
- const endTime = new Date(startTime.getTime() + sessionDurationMs), lastEntry = entries[entries.length - 1], actualEndTime = lastEntry != null ? lastEntry.timestamp : startTime, isActive = now.getTime() - actualEndTime.getTime() < sessionDurationMs && now < endTime, tokenCounts = {
2085
- inputTokens: 0,
2086
- outputTokens: 0,
2087
- cacheCreationInputTokens: 0,
2088
- cacheReadInputTokens: 0
2089
- };
2090
- let costUSD = 0;
2091
- const models = [];
2092
- let usageLimitResetTime;
2093
- for (const entry of entries) tokenCounts.inputTokens += entry.usage.inputTokens, tokenCounts.outputTokens += entry.usage.outputTokens, tokenCounts.cacheCreationInputTokens += entry.usage.cacheCreationInputTokens, tokenCounts.cacheReadInputTokens += entry.usage.cacheReadInputTokens, costUSD += entry.costUSD ?? 0, usageLimitResetTime = entry.usageLimitResetTime ?? usageLimitResetTime, models.push(entry.model);
2094
- return {
2095
- id: startTime.toISOString(),
2096
- startTime,
2097
- endTime,
2098
- actualEndTime,
2099
- isActive,
2100
- entries,
2101
- tokenCounts,
2102
- costUSD,
2103
- models: uniq(models),
2104
- usageLimitResetTime
2105
- };
2106
- }
2107
- function createGapBlock(lastActivityTime, nextActivityTime, sessionDurationMs) {
2108
- const gapDuration = nextActivityTime.getTime() - lastActivityTime.getTime();
2109
- if (gapDuration <= sessionDurationMs) return null;
2110
- const gapStart = new Date(lastActivityTime.getTime() + sessionDurationMs), gapEnd = nextActivityTime;
2111
- return {
2112
- id: `gap-${gapStart.toISOString()}`,
2113
- startTime: gapStart,
2114
- endTime: gapEnd,
2115
- isActive: false,
2116
- isGap: true,
2117
- entries: [],
2118
- tokenCounts: {
2119
- inputTokens: 0,
2120
- outputTokens: 0,
2121
- cacheCreationInputTokens: 0,
2122
- cacheReadInputTokens: 0
2123
- },
2124
- costUSD: 0,
2125
- models: []
2126
- };
2127
- }
2128
- function calculateBurnRate(block) {
2129
- if (block.entries.length === 0 || (block.isGap ?? false)) return null;
2130
- const firstEntryData = block.entries[0], lastEntryData = block.entries[block.entries.length - 1];
2131
- if (firstEntryData == null || lastEntryData == null) return null;
2132
- const firstEntry = firstEntryData.timestamp, lastEntry = lastEntryData.timestamp, durationMinutes = (lastEntry.getTime() - firstEntry.getTime()) / (1e3 * 60);
2133
- if (durationMinutes <= 0) return null;
2134
- const totalTokens = getTotalTokens(block.tokenCounts), tokensPerMinute = totalTokens / durationMinutes, nonCacheTokens = (block.tokenCounts.inputTokens ?? 0) + (block.tokenCounts.outputTokens ?? 0), tokensPerMinuteForIndicator = nonCacheTokens / durationMinutes, costPerHour = block.costUSD / durationMinutes * 60;
2135
- return {
2136
- tokensPerMinute,
2137
- tokensPerMinuteForIndicator,
2138
- costPerHour
2139
- };
2140
- }
2141
- function projectBlockUsage(block) {
2142
- if (!block.isActive || (block.isGap ?? false)) return null;
2143
- const burnRate = calculateBurnRate(block);
2144
- if (burnRate == null) return null;
2145
- const now = /* @__PURE__ */ new Date(), remainingTime = block.endTime.getTime() - now.getTime(), remainingMinutes = Math.max(0, remainingTime / (1e3 * 60)), currentTokens = getTotalTokens(block.tokenCounts), projectedAdditionalTokens = burnRate.tokensPerMinute * remainingMinutes, totalTokens = currentTokens + projectedAdditionalTokens, projectedAdditionalCost = burnRate.costPerHour / 60 * remainingMinutes, totalCost = block.costUSD + projectedAdditionalCost;
2146
- return {
2147
- totalTokens: Math.round(totalTokens),
2148
- totalCost: Math.round(totalCost * 100) / 100,
2149
- remainingMinutes: Math.round(remainingMinutes)
2150
- };
2151
- }
2152
- function filterRecentBlocks(blocks, days = DEFAULT_RECENT_DAYS) {
2153
- const now = /* @__PURE__ */ new Date(), cutoffTime = /* @__PURE__ */ new Date(now.getTime() - days * 24 * 60 * 60 * 1e3);
2154
- return blocks.filter((block) => {
2155
- return block.startTime >= cutoffTime || block.isActive;
2156
- });
2157
- }
2158
- var import_usingCtx = /* @__PURE__ */ __toESM(require_usingCtx(), 1);
2159
- function getClaudePaths() {
2160
- const paths = [], normalizedPaths = /* @__PURE__ */ new Set(), envPaths = (process$1.env[CLAUDE_CONFIG_DIR_ENV] ?? "").trim();
2161
- if (envPaths !== "") {
2162
- const envPathList = envPaths.split(",").map((p) => p.trim()).filter((p) => p !== "");
2163
- for (const envPath of envPathList) {
2164
- const normalizedPath = path.resolve(envPath);
2165
- if (isDirectorySync(normalizedPath)) {
2166
- const projectsPath = path.join(normalizedPath, CLAUDE_PROJECTS_DIR_NAME);
2167
- if (isDirectorySync(projectsPath)) {
2168
- if (!normalizedPaths.has(normalizedPath)) normalizedPaths.add(normalizedPath), paths.push(normalizedPath);
2169
- }
2170
- }
2171
- }
2172
- if (paths.length > 0) return paths;
2173
- throw new Error(`No valid Claude data directories found in CLAUDE_CONFIG_DIR. Please ensure the following exists:
2174
- - ${envPaths}/${CLAUDE_PROJECTS_DIR_NAME}`.trim());
2175
- }
2176
- const defaultPaths = [DEFAULT_CLAUDE_CONFIG_PATH, path.join(USER_HOME_DIR, DEFAULT_CLAUDE_CODE_PATH)];
2177
- for (const defaultPath of defaultPaths) {
2178
- const normalizedPath = path.resolve(defaultPath);
2179
- if (isDirectorySync(normalizedPath)) {
2180
- const projectsPath = path.join(normalizedPath, CLAUDE_PROJECTS_DIR_NAME);
2181
- if (isDirectorySync(projectsPath)) {
2182
- if (!normalizedPaths.has(normalizedPath)) normalizedPaths.add(normalizedPath), paths.push(normalizedPath);
2183
- }
2184
- }
2185
- }
2186
- if (paths.length === 0) throw new Error(`No valid Claude data directories found. Please ensure at least one of the following exists:
2187
- - ${path.join(DEFAULT_CLAUDE_CONFIG_PATH, CLAUDE_PROJECTS_DIR_NAME)}
2188
- - ${path.join(USER_HOME_DIR, DEFAULT_CLAUDE_CODE_PATH, CLAUDE_PROJECTS_DIR_NAME)}
2189
- - Or set ${CLAUDE_CONFIG_DIR_ENV} environment variable to valid directory path(s) containing a '${CLAUDE_PROJECTS_DIR_NAME}' subdirectory`.trim());
2190
- return paths;
2191
- }
2192
- function extractProjectFromPath(jsonlPath) {
2193
- const normalizedPath = jsonlPath.replace(/[/\\]/g, path.sep), segments = normalizedPath.split(path.sep), projectsIndex = segments.findIndex((segment) => segment === CLAUDE_PROJECTS_DIR_NAME);
2194
- if (projectsIndex === -1 || projectsIndex + 1 >= segments.length) return "unknown";
2195
- const projectName = segments[projectsIndex + 1];
2196
- return projectName != null && projectName.trim() !== "" ? projectName : "unknown";
2197
- }
2198
- const usageDataSchema = objectType({
2199
- cwd: stringType().optional(),
2200
- sessionId: sessionIdSchema.optional(),
2201
- timestamp: isoTimestampSchema,
2202
- version: versionSchema.optional(),
2203
- message: objectType({
2204
- usage: objectType({
2205
- input_tokens: numberType(),
2206
- output_tokens: numberType(),
2207
- cache_creation_input_tokens: numberType().optional(),
2208
- cache_read_input_tokens: numberType().optional()
2209
- }),
2210
- model: modelNameSchema.optional(),
2211
- id: messageIdSchema.optional(),
2212
- content: arrayType(objectType({ text: stringType().optional() })).optional()
2213
- }),
2214
- costUSD: numberType().optional(),
2215
- requestId: requestIdSchema.optional(),
2216
- isApiErrorMessage: booleanType().optional()
2217
- }), transcriptUsageSchema = objectType({
2218
- input_tokens: numberType().optional(),
2219
- cache_creation_input_tokens: numberType().optional(),
2220
- cache_read_input_tokens: numberType().optional(),
2221
- output_tokens: numberType().optional()
2222
- }), transcriptMessageSchema = objectType({
2223
- type: stringType().optional(),
2224
- message: objectType({ usage: transcriptUsageSchema.optional() }).optional()
2225
- }), modelBreakdownSchema = objectType({
2226
- modelName: modelNameSchema,
2227
- inputTokens: numberType(),
2228
- outputTokens: numberType(),
2229
- cacheCreationTokens: numberType(),
2230
- cacheReadTokens: numberType(),
2231
- cost: numberType()
2232
- }), dailyUsageSchema = objectType({
2233
- date: dailyDateSchema,
2234
- inputTokens: numberType(),
2235
- outputTokens: numberType(),
2236
- cacheCreationTokens: numberType(),
2237
- cacheReadTokens: numberType(),
2238
- totalCost: numberType(),
2239
- modelsUsed: arrayType(modelNameSchema),
2240
- modelBreakdowns: arrayType(modelBreakdownSchema),
2241
- project: stringType().optional()
2242
- }), sessionUsageSchema = objectType({
2243
- sessionId: sessionIdSchema,
2244
- projectPath: projectPathSchema,
2245
- inputTokens: numberType(),
2246
- outputTokens: numberType(),
2247
- cacheCreationTokens: numberType(),
2248
- cacheReadTokens: numberType(),
2249
- totalCost: numberType(),
2250
- lastActivity: activityDateSchema,
2251
- versions: arrayType(versionSchema),
2252
- modelsUsed: arrayType(modelNameSchema),
2253
- modelBreakdowns: arrayType(modelBreakdownSchema)
2254
- }), monthlyUsageSchema = objectType({
2255
- month: monthlyDateSchema,
2256
- inputTokens: numberType(),
2257
- outputTokens: numberType(),
2258
- cacheCreationTokens: numberType(),
2259
- cacheReadTokens: numberType(),
2260
- totalCost: numberType(),
2261
- modelsUsed: arrayType(modelNameSchema),
2262
- modelBreakdowns: arrayType(modelBreakdownSchema),
2263
- project: stringType().optional()
2264
- }), weeklyUsageSchema = objectType({
2265
- week: weeklyDateSchema,
2266
- inputTokens: numberType(),
2267
- outputTokens: numberType(),
2268
- cacheCreationTokens: numberType(),
2269
- cacheReadTokens: numberType(),
2270
- totalCost: numberType(),
2271
- modelsUsed: arrayType(modelNameSchema),
2272
- modelBreakdowns: arrayType(modelBreakdownSchema),
2273
- project: stringType().optional()
2274
- }), bucketUsageSchema = objectType({
2275
- bucket: unionType([weeklyDateSchema, monthlyDateSchema]),
2276
- inputTokens: numberType(),
2277
- outputTokens: numberType(),
2278
- cacheCreationTokens: numberType(),
2279
- cacheReadTokens: numberType(),
2280
- totalCost: numberType(),
2281
- modelsUsed: arrayType(modelNameSchema),
2282
- modelBreakdowns: arrayType(modelBreakdownSchema),
2283
- project: stringType().optional()
2284
- });
2285
- function aggregateByModel(entries, getModel, getUsage, getCost) {
2286
- const modelAggregates = /* @__PURE__ */ new Map(), defaultStats = {
2287
- inputTokens: 0,
2288
- outputTokens: 0,
2289
- cacheCreationTokens: 0,
2290
- cacheReadTokens: 0,
2291
- cost: 0
2292
- };
2293
- for (const entry of entries) {
2294
- const modelName = getModel(entry) ?? "unknown";
2295
- if (modelName === "<synthetic>") continue;
2296
- const usage = getUsage(entry), cost = getCost(entry), existing = modelAggregates.get(modelName) ?? defaultStats;
2297
- modelAggregates.set(modelName, {
2298
- inputTokens: existing.inputTokens + (usage.input_tokens ?? 0),
2299
- outputTokens: existing.outputTokens + (usage.output_tokens ?? 0),
2300
- cacheCreationTokens: existing.cacheCreationTokens + (usage.cache_creation_input_tokens ?? 0),
2301
- cacheReadTokens: existing.cacheReadTokens + (usage.cache_read_input_tokens ?? 0),
2302
- cost: existing.cost + cost
2303
- });
2304
- }
2305
- return modelAggregates;
2306
- }
2307
- function aggregateModelBreakdowns(breakdowns) {
2308
- const modelAggregates = /* @__PURE__ */ new Map(), defaultStats = {
2309
- inputTokens: 0,
2310
- outputTokens: 0,
2311
- cacheCreationTokens: 0,
2312
- cacheReadTokens: 0,
2313
- cost: 0
2314
- };
2315
- for (const breakdown of breakdowns) {
2316
- if (breakdown.modelName === "<synthetic>") continue;
2317
- const existing = modelAggregates.get(breakdown.modelName) ?? defaultStats;
2318
- modelAggregates.set(breakdown.modelName, {
2319
- inputTokens: existing.inputTokens + breakdown.inputTokens,
2320
- outputTokens: existing.outputTokens + breakdown.outputTokens,
2321
- cacheCreationTokens: existing.cacheCreationTokens + breakdown.cacheCreationTokens,
2322
- cacheReadTokens: existing.cacheReadTokens + breakdown.cacheReadTokens,
2323
- cost: existing.cost + breakdown.cost
2324
- });
2325
- }
2326
- return modelAggregates;
2327
- }
2328
- function createModelBreakdowns(modelAggregates) {
2329
- return Array.from(modelAggregates.entries()).map(([modelName, stats]) => ({
2330
- modelName,
2331
- ...stats
2332
- })).sort((a$1, b$1) => b$1.cost - a$1.cost);
2333
- }
2334
- function calculateTotals(entries, getUsage, getCost) {
2335
- return entries.reduce((acc, entry) => {
2336
- const usage = getUsage(entry), cost = getCost(entry);
2337
- return {
2338
- inputTokens: acc.inputTokens + (usage.input_tokens ?? 0),
2339
- outputTokens: acc.outputTokens + (usage.output_tokens ?? 0),
2340
- cacheCreationTokens: acc.cacheCreationTokens + (usage.cache_creation_input_tokens ?? 0),
2341
- cacheReadTokens: acc.cacheReadTokens + (usage.cache_read_input_tokens ?? 0),
2342
- cost: acc.cost + cost,
2343
- totalCost: acc.totalCost + cost
2344
- };
2345
- }, {
2346
- inputTokens: 0,
2347
- outputTokens: 0,
2348
- cacheCreationTokens: 0,
2349
- cacheReadTokens: 0,
2350
- cost: 0,
2351
- totalCost: 0
2352
- });
2353
- }
2354
- function filterByProject(items, getProject, projectFilter) {
2355
- return projectFilter == null ? items : items.filter((item) => {
2356
- const projectName = getProject(item);
2357
- return projectName === projectFilter;
2358
- });
2359
- }
2360
- function isDuplicateEntry(uniqueHash, processedHashes) {
2361
- return uniqueHash == null ? false : processedHashes.has(uniqueHash);
2362
- }
2363
- function markAsProcessed(uniqueHash, processedHashes) {
2364
- if (uniqueHash != null) processedHashes.add(uniqueHash);
2365
- }
2366
- function extractUniqueModels(entries, getModel) {
2367
- return uniq(entries.map(getModel).filter((m$1) => m$1 != null && m$1 !== "<synthetic>"));
2368
- }
2369
- function createUniqueHash(data) {
2370
- const messageId = data.message.id, requestId = data.requestId;
2371
- return messageId == null || requestId == null ? null : `${messageId}:${requestId}`;
2372
- }
2373
- async function getEarliestTimestamp(filePath) {
2374
- try {
2375
- const content = await readFile(filePath, "utf-8"), lines = content.trim().split("\n");
2376
- let earliestDate = null;
2377
- for (const line of lines) {
2378
- if (line.trim() === "") continue;
2379
- try {
2380
- const json = JSON.parse(line);
2381
- if (json.timestamp != null && typeof json.timestamp === "string") {
2382
- const date = new Date(json.timestamp);
2383
- if (!Number.isNaN(date.getTime())) {
2384
- if (earliestDate == null || date < earliestDate) earliestDate = date;
2385
- }
2386
- }
2387
- } catch {
2388
- continue;
2389
- }
2390
- }
2391
- return earliestDate;
2392
- } catch (error) {
2393
- return logger.debug(`Failed to get earliest timestamp for ${filePath}:`, error), null;
2394
- }
2395
- }
2396
- async function sortFilesByTimestamp(files) {
2397
- const filesWithTimestamps = await Promise.all(files.map(async (file) => ({
2398
- file,
2399
- timestamp: await getEarliestTimestamp(file)
2400
- })));
2401
- return filesWithTimestamps.sort((a$1, b$1) => {
2402
- return a$1.timestamp == null && b$1.timestamp == null ? 0 : a$1.timestamp == null ? 1 : b$1.timestamp == null ? -1 : a$1.timestamp.getTime() - b$1.timestamp.getTime();
2403
- }).map((item) => item.file);
2404
- }
2405
- async function calculateCostForEntry(data, mode, fetcher) {
2406
- if (mode === "display") return data.costUSD ?? 0;
2407
- if (mode === "calculate") return data.message.model == null ? 0 : unwrap(fetcher.calculateCostFromTokens(data.message.usage, data.message.model), 0);
2408
- if (mode === "auto") return data.costUSD == null ? data.message.model == null ? 0 : unwrap(fetcher.calculateCostFromTokens(data.message.usage, data.message.model), 0) : data.costUSD;
2409
- unreachable(mode);
2410
- }
2411
- function getUsageLimitResetTime(data) {
2412
- let resetTime = null;
2413
- if (data.isApiErrorMessage === true) {
2414
- const timestampMatch = data.message?.content?.find((c) => c.text != null && c.text.includes("Claude AI usage limit reached"))?.text?.match(/\|(\d+)/) ?? null;
2415
- if (timestampMatch?.[1] != null) {
2416
- const resetTimestamp = Number.parseInt(timestampMatch[1]);
2417
- resetTime = resetTimestamp > 0 ? /* @__PURE__ */ new Date(resetTimestamp * 1e3) : null;
2418
- }
2419
- }
2420
- return resetTime;
2421
- }
2422
- async function globUsageFiles(claudePaths) {
2423
- const filePromises = claudePaths.map(async (claudePath) => {
2424
- const claudeDir = path.join(claudePath, CLAUDE_PROJECTS_DIR_NAME), files = await glob([USAGE_DATA_GLOB_PATTERN], {
2425
- cwd: claudeDir,
2426
- absolute: true
2427
- }).catch(() => []);
2428
- return files.map((file) => ({
2429
- file,
2430
- baseDir: claudeDir
2431
- }));
2432
- });
2433
- return (await Promise.all(filePromises)).flat();
2434
- }
2435
- async function loadDailyUsageData(options) {
2436
- try {
2437
- var _usingCtx = (0, import_usingCtx.default)();
2438
- const claudePaths = toArray(options?.claudePath ?? getClaudePaths()), allFiles = await globUsageFiles(claudePaths), fileList = allFiles.map((f$1) => f$1.file);
2439
- if (fileList.length === 0) return [];
2440
- const projectFilteredFiles = filterByProject(fileList, (filePath) => extractProjectFromPath(filePath), options?.project), sortedFiles = await sortFilesByTimestamp(projectFilteredFiles), mode = options?.mode ?? "auto", fetcher = _usingCtx.u(mode === "display" ? null : new PricingFetcher(options?.offline)), processedHashes = /* @__PURE__ */ new Set(), allEntries = [];
2441
- for (const file of sortedFiles) {
2442
- const content = await readFile(file, "utf-8"), lines = content.trim().split("\n").filter((line) => line.length > 0);
2443
- for (const line of lines) try {
2444
- const parsed = JSON.parse(line), result = usageDataSchema.safeParse(parsed);
2445
- if (!result.success) continue;
2446
- const data = result.data, uniqueHash = createUniqueHash(data);
2447
- if (isDuplicateEntry(uniqueHash, processedHashes)) continue;
2448
- markAsProcessed(uniqueHash, processedHashes);
2449
- const date = formatDate(data.timestamp, options?.timezone, DEFAULT_LOCALE), cost = fetcher != null ? await calculateCostForEntry(data, mode, fetcher) : data.costUSD ?? 0, project = extractProjectFromPath(file);
2450
- allEntries.push({
2451
- data,
2452
- date,
2453
- cost,
2454
- model: data.message.model,
2455
- project
2456
- });
2457
- } catch {}
2458
- }
2459
- const needsProjectGrouping = options?.groupByProject === true || options?.project != null, groupingKey = needsProjectGrouping ? (entry) => `${entry.date}\x00${entry.project}` : (entry) => entry.date, groupedData = groupBy(allEntries, groupingKey), results = Object.entries(groupedData).map(([groupKey, entries]) => {
2460
- if (entries == null) return void 0;
2461
- const parts = groupKey.split("\0"), date = parts[0] ?? groupKey, project = parts.length > 1 ? parts[1] : void 0, modelAggregates = aggregateByModel(entries, (entry) => entry.model, (entry) => entry.data.message.usage, (entry) => entry.cost), modelBreakdowns = createModelBreakdowns(modelAggregates), totals = calculateTotals(entries, (entry) => entry.data.message.usage, (entry) => entry.cost), modelsUsed = extractUniqueModels(entries, (e) => e.model);
2462
- return {
2463
- date: createDailyDate(date),
2464
- ...totals,
2465
- modelsUsed,
2466
- modelBreakdowns,
2467
- ...project != null && { project }
2468
- };
2469
- }).filter((item) => item != null), dateFiltered = filterByDateRange(results, (item) => item.date, options?.since, options?.until), finalFiltered = filterByProject(dateFiltered, (item) => item.project, options?.project);
2470
- return sortByDate(finalFiltered, (item) => item.date, options?.order);
2471
- } catch (_) {
2472
- _usingCtx.e = _;
2473
- } finally {
2474
- _usingCtx.d();
2475
- }
2476
- }
2477
- async function loadSessionData(options) {
2478
- try {
2479
- var _usingCtx3 = (0, import_usingCtx.default)();
2480
- const claudePaths = toArray(options?.claudePath ?? getClaudePaths()), filesWithBase = await globUsageFiles(claudePaths);
2481
- if (filesWithBase.length === 0) return [];
2482
- const projectFilteredWithBase = filterByProject(filesWithBase, (item) => extractProjectFromPath(item.file), options?.project), fileToBaseMap = new Map(projectFilteredWithBase.map((f$1) => [f$1.file, f$1.baseDir])), sortedFilesWithBase = await sortFilesByTimestamp(projectFilteredWithBase.map((f$1) => f$1.file)).then((sortedFiles) => sortedFiles.map((file) => ({
2483
- file,
2484
- baseDir: fileToBaseMap.get(file) ?? ""
2485
- }))), mode = options?.mode ?? "auto", fetcher = _usingCtx3.u(mode === "display" ? null : new PricingFetcher(options?.offline)), processedHashes = /* @__PURE__ */ new Set(), allEntries = [];
2486
- for (const { file, baseDir } of sortedFilesWithBase) {
2487
- const relativePath = path.relative(baseDir, file), parts = relativePath.split(path.sep), sessionId = parts[parts.length - 2] ?? "unknown", joinedPath = parts.slice(0, -2).join(path.sep), projectPath = joinedPath.length > 0 ? joinedPath : "Unknown Project", content = await readFile(file, "utf-8"), lines = content.trim().split("\n").filter((line) => line.length > 0);
2488
- for (const line of lines) try {
2489
- const parsed = JSON.parse(line), result = usageDataSchema.safeParse(parsed);
2490
- if (!result.success) continue;
2491
- const data = result.data, uniqueHash = createUniqueHash(data);
2492
- if (isDuplicateEntry(uniqueHash, processedHashes)) continue;
2493
- markAsProcessed(uniqueHash, processedHashes);
2494
- const sessionKey = `${projectPath}/${sessionId}`, cost = fetcher != null ? await calculateCostForEntry(data, mode, fetcher) : data.costUSD ?? 0;
2495
- allEntries.push({
2496
- data,
2497
- sessionKey,
2498
- sessionId,
2499
- projectPath,
2500
- cost,
2501
- timestamp: data.timestamp,
2502
- model: data.message.model
2503
- });
2504
- } catch {}
2505
- }
2506
- const groupedBySessions = groupBy(allEntries, (entry) => entry.sessionKey), results = Object.entries(groupedBySessions).map(([_, entries]) => {
2507
- if (entries == null) return void 0;
2508
- const latestEntry = entries.reduce((latest, current) => current.timestamp > latest.timestamp ? current : latest), versions = [];
2509
- for (const entry of entries) if (entry.data.version != null) versions.push(entry.data.version);
2510
- const modelAggregates = aggregateByModel(entries, (entry) => entry.model, (entry) => entry.data.message.usage, (entry) => entry.cost), modelBreakdowns = createModelBreakdowns(modelAggregates), totals = calculateTotals(entries, (entry) => entry.data.message.usage, (entry) => entry.cost), modelsUsed = extractUniqueModels(entries, (e) => e.model);
2511
- return {
2512
- sessionId: createSessionId(latestEntry.sessionId),
2513
- projectPath: createProjectPath(latestEntry.projectPath),
2514
- ...totals,
2515
- lastActivity: formatDate(latestEntry.timestamp, options?.timezone, DEFAULT_LOCALE),
2516
- versions: uniq(versions).sort(),
2517
- modelsUsed,
2518
- modelBreakdowns
2519
- };
2520
- }).filter((item) => item != null), dateFiltered = filterByDateRange(results, (item) => item.lastActivity, options?.since, options?.until), sessionFiltered = filterByProject(dateFiltered, (item) => item.projectPath, options?.project);
2521
- return sortByDate(sessionFiltered, (item) => item.lastActivity, options?.order);
2522
- } catch (_) {
2523
- _usingCtx3.e = _;
2524
- } finally {
2525
- _usingCtx3.d();
2526
- }
2527
- }
2528
- async function loadMonthlyUsageData(options) {
2529
- return loadBucketUsageData((data) => createMonthlyDate(data.date.substring(0, 7)), options).then((usages) => usages.map(({ bucket,...rest }) => ({
2530
- month: createMonthlyDate(bucket.toString()),
2531
- ...rest
2532
- })));
2533
- }
2534
- async function loadWeeklyUsageData(options) {
2535
- const startDay = options?.startOfWeek != null ? getDayNumber(options.startOfWeek) : getDayNumber("sunday");
2536
- return loadBucketUsageData((data) => getDateWeek(new Date(data.date), startDay), options).then((usages) => usages.map(({ bucket,...rest }) => ({
2537
- week: createWeeklyDate(bucket.toString()),
2538
- ...rest
2539
- })));
2540
- }
2541
- async function loadSessionUsageById(sessionId, options) {
2542
- try {
2543
- var _usingCtx4 = (0, import_usingCtx.default)();
2544
- const claudePaths = getClaudePaths(), patterns = claudePaths.map((p) => path.join(p, "projects", "**", `${sessionId}.jsonl`).replace(/\\/g, "/")), jsonlFiles = await glob(patterns);
2545
- if (jsonlFiles.length === 0) return null;
2546
- const file = jsonlFiles[0];
2547
- if (file == null) return null;
2548
- const content = await readFile(file, "utf-8"), lines = content.trim().split("\n").filter((line) => line.length > 0), mode = options?.mode ?? "auto", fetcher = _usingCtx4.u(mode === "display" ? null : new PricingFetcher(options?.offline)), entries = [];
2549
- let totalCost = 0;
2550
- for (const line of lines) try {
2551
- const parsed = JSON.parse(line), result = usageDataSchema.safeParse(parsed);
2552
- if (!result.success) continue;
2553
- const data = result.data, cost = fetcher != null ? await calculateCostForEntry(data, mode, fetcher) : data.costUSD ?? 0;
2554
- totalCost += cost, entries.push(data);
2555
- } catch {}
2556
- return {
2557
- totalCost,
2558
- entries
2559
- };
2560
- } catch (_) {
2561
- _usingCtx4.e = _;
2562
- } finally {
2563
- _usingCtx4.d();
2564
- }
2565
- }
2566
- async function loadBucketUsageData(groupingFn, options) {
2567
- const dailyData = await loadDailyUsageData(options), needsProjectGrouping = options?.groupByProject === true || options?.project != null, groupingKey = needsProjectGrouping ? (data) => `${groupingFn(data)}\x00${data.project ?? "unknown"}` : (data) => `${groupingFn(data)}`, grouped = groupBy(dailyData, groupingKey), buckets = [];
2568
- for (const [groupKey, dailyEntries] of Object.entries(grouped)) {
2569
- if (dailyEntries == null) continue;
2570
- const parts = groupKey.split("\0"), bucket = createBucket(parts[0] ?? groupKey), project = parts.length > 1 ? parts[1] : void 0, allBreakdowns = dailyEntries.flatMap((daily) => daily.modelBreakdowns), modelAggregates = aggregateModelBreakdowns(allBreakdowns), modelBreakdowns = createModelBreakdowns(modelAggregates), models = [];
2571
- for (const data of dailyEntries) for (const model of data.modelsUsed) if (model !== "<synthetic>") models.push(model);
2572
- let totalInputTokens = 0, totalOutputTokens = 0, totalCacheCreationTokens = 0, totalCacheReadTokens = 0, totalCost = 0;
2573
- for (const daily of dailyEntries) totalInputTokens += daily.inputTokens, totalOutputTokens += daily.outputTokens, totalCacheCreationTokens += daily.cacheCreationTokens, totalCacheReadTokens += daily.cacheReadTokens, totalCost += daily.totalCost;
2574
- const bucketUsage = {
2575
- bucket,
2576
- inputTokens: totalInputTokens,
2577
- outputTokens: totalOutputTokens,
2578
- cacheCreationTokens: totalCacheCreationTokens,
2579
- cacheReadTokens: totalCacheReadTokens,
2580
- totalCost,
2581
- modelsUsed: uniq(models),
2582
- modelBreakdowns,
2583
- ...project != null && { project }
2584
- };
2585
- buckets.push(bucketUsage);
2586
- }
2587
- return sortByDate(buckets, (item) => item.bucket, options?.order);
2588
- }
2589
- async function calculateContextTokens(transcriptPath, modelId, offline = false) {
2590
- let content;
2591
- try {
2592
- content = await readFile(transcriptPath, "utf-8");
2593
- } catch (error) {
2594
- return logger.debug(`Failed to read transcript file: ${String(error)}`), null;
2595
- }
2596
- const lines = content.split("\n").reverse();
2597
- for (const line of lines) {
2598
- const trimmedLine = line.trim();
2599
- if (trimmedLine === "") continue;
2600
- try {
2601
- const parsed = JSON.parse(trimmedLine), result = transcriptMessageSchema.safeParse(parsed);
2602
- if (!result.success) continue;
2603
- const obj = result.data;
2604
- if (obj.type === "assistant" && obj.message != null && obj.message.usage != null && obj.message.usage.input_tokens != null) {
2605
- const usage = obj.message.usage, inputTokens = usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0);
2606
- let contextLimit = 2e5;
2607
- if (modelId != null && modelId !== "") try {
2608
- var _usingCtx5 = (0, import_usingCtx.default)();
2609
- const fetcher = _usingCtx5.u(new PricingFetcher(offline)), contextLimitResult = await fetcher.getModelContextLimit(modelId);
2610
- if (isSuccess(contextLimitResult) && contextLimitResult.value != null) contextLimit = contextLimitResult.value;
2611
- else if (isSuccess(contextLimitResult)) logger.debug(`No context limit data available for model ${modelId} in LiteLLM`);
2612
- else logger.debug(`Failed to get context limit for model ${modelId}: ${contextLimitResult.error.message}`);
2613
- } catch (_) {
2614
- _usingCtx5.e = _;
2615
- } finally {
2616
- _usingCtx5.d();
2617
- }
2618
- const percentage = Math.min(100, Math.max(0, Math.round(inputTokens / contextLimit * 100)));
2619
- return {
2620
- inputTokens,
2621
- percentage,
2622
- contextLimit
2623
- };
2624
- }
2625
- } catch {
2626
- continue;
2627
- }
2628
- }
2629
- return logger.debug("No usage information found in transcript"), null;
2630
- }
2631
- async function loadSessionBlockData(options) {
2632
- try {
2633
- var _usingCtx6 = (0, import_usingCtx.default)();
2634
- const claudePaths = toArray(options?.claudePath ?? getClaudePaths()), allFiles = [];
2635
- for (const claudePath of claudePaths) {
2636
- const claudeDir = path.join(claudePath, CLAUDE_PROJECTS_DIR_NAME), files = await glob([USAGE_DATA_GLOB_PATTERN], {
2637
- cwd: claudeDir,
2638
- absolute: true
2639
- });
2640
- allFiles.push(...files);
2641
- }
2642
- if (allFiles.length === 0) return [];
2643
- const blocksFilteredFiles = filterByProject(allFiles, (filePath) => extractProjectFromPath(filePath), options?.project), sortedFiles = await sortFilesByTimestamp(blocksFilteredFiles), mode = options?.mode ?? "auto", fetcher = _usingCtx6.u(mode === "display" ? null : new PricingFetcher(options?.offline)), processedHashes = /* @__PURE__ */ new Set(), allEntries = [];
2644
- for (const file of sortedFiles) {
2645
- const content = await readFile(file, "utf-8"), lines = content.trim().split("\n").filter((line) => line.length > 0);
2646
- for (const line of lines) try {
2647
- const parsed = JSON.parse(line), result = usageDataSchema.safeParse(parsed);
2648
- if (!result.success) continue;
2649
- const data = result.data, uniqueHash = createUniqueHash(data);
2650
- if (isDuplicateEntry(uniqueHash, processedHashes)) continue;
2651
- markAsProcessed(uniqueHash, processedHashes);
2652
- const cost = fetcher != null ? await calculateCostForEntry(data, mode, fetcher) : data.costUSD ?? 0, usageLimitResetTime = getUsageLimitResetTime(data);
2653
- allEntries.push({
2654
- timestamp: new Date(data.timestamp),
2655
- usage: {
2656
- inputTokens: data.message.usage.input_tokens,
2657
- outputTokens: data.message.usage.output_tokens,
2658
- cacheCreationInputTokens: data.message.usage.cache_creation_input_tokens ?? 0,
2659
- cacheReadInputTokens: data.message.usage.cache_read_input_tokens ?? 0
2660
- },
2661
- costUSD: cost,
2662
- model: data.message.model ?? "unknown",
2663
- version: data.version,
2664
- usageLimitResetTime: usageLimitResetTime ?? void 0
2665
- });
2666
- } catch (error) {
2667
- logger.debug(`Skipping invalid JSON line in 5-hour blocks: ${error instanceof Error ? error.message : String(error)}`);
2668
- }
2669
- }
2670
- const blocks = identifySessionBlocks(allEntries, options?.sessionDurationHours), dateFiltered = options?.since != null && options.since !== "" || options?.until != null && options.until !== "" ? blocks.filter((block) => {
2671
- const blockDateStr = formatDate(block.startTime.toISOString(), options?.timezone, DEFAULT_LOCALE).replace(/-/g, "");
2672
- return !(options.since != null && options.since !== "" && blockDateStr < options.since || options.until != null && options.until !== "" && blockDateStr > options.until);
2673
- }) : blocks;
2674
- return sortByDate(dateFiltered, (block) => block.startTime, options?.order);
2675
- } catch (_) {
2676
- _usingCtx6.e = _;
2677
- } finally {
2678
- _usingCtx6.d();
2679
- }
2680
- }
2681
- export { DEFAULT_SESSION_DURATION_HOURS, bucketUsageSchema, calculateBurnRate, calculateContextTokens, calculateCostForEntry, createUniqueHash, dailyUsageSchema, extractProjectFromPath, filterRecentBlocks, formatDateCompact, getClaudePaths, getEarliestTimestamp, getFileModifiedTime, getUsageLimitResetTime, glob, globUsageFiles, identifySessionBlocks, loadBucketUsageData, loadDailyUsageData, loadMonthlyUsageData, loadSessionBlockData, loadSessionData, loadSessionUsageById, loadWeeklyUsageData, modelBreakdownSchema, monthlyUsageSchema, projectBlockUsage, sessionUsageSchema, sortFilesByTimestamp, toArray, transcriptMessageSchema, transcriptUsageSchema, uniq, unreachable, unwrap, usageDataSchema, weeklyUsageSchema };