ccusage
Version:
Usage analysis tool for Claude Code
1,533 lines • 130 kB
JavaScript
import { CLAUDE_CONFIG_DIR_ENV, CLAUDE_PROJECTS_DIR_NAME, DEFAULT_CLAUDE_CODE_PATH, DEFAULT_CLAUDE_CONFIG_PATH, DEFAULT_RECENT_DAYS, PricingFetcher, USAGE_DATA_GLOB_PATTERN, USER_HOME_DIR, __commonJSMin, __require, __toESM, require_usingCtx } from "./pricing-fetcher-Dm8hcn_h.js";
import { activityDateSchema, arrayType, createDailyDate, createMonthlyDate, createProjectPath, createSessionId, dailyDateSchema, isoTimestampSchema, messageIdSchema, modelNameSchema, monthlyDateSchema, numberType, objectType, projectPathSchema, requestIdSchema, sessionIdSchema, versionSchema } from "./_types-Cr2YEzKm.js";
import { logger } from "./logger-Cke8hliP.js";
import a, { readFile } from "node:fs/promises";
import F, { homedir } from "node:os";
import path, { posix } from "node:path";
import process$1 from "node:process";
import b from "node:fs";
function toArray(array) {
array = array ?? [];
return Array.isArray(array) ? array : [array];
}
const VOID = Symbol("p-void");
/**
* Return `true` if the type of `x` is `string`.
*
* ```ts
* import { is } from "@core/unknownutil";
*
* const a: unknown = "a";
* if (is.String(a)) {
* const _: string = a;
* }
* ```
*/ function isString(x) {
return typeof x === "string";
}
/**
* Return `true` if the type of `x` satisfies `Record<PropertyKey, unknown>`.
*
* Note that this function returns `true` for ambiguous instances like `Set`, `Map`, `Date`, `Promise`, etc.
* Use {@linkcode [is/record-object].isRecordObject|isRecordObject} instead if you want to check if `x` is an instance of `Object`.
*
* ```ts
* import { is } from "@core/unknownutil";
*
* const a: unknown = {"a": 0, "b": 1};
* if (is.Record(a)) {
* const _: Record<PropertyKey, unknown> = a;
* }
*
* const b: unknown = new Set();
* if (is.Record(b)) {
* const _: Record<PropertyKey, unknown> = b;
* }
* ```
*/ function isRecord(x) {
return x != null && !Array.isArray(x) && typeof x === "object";
}
const defaultThreshold = 20;
/**
* Inspect a value
*/ function inspect(value, options = {}) {
if (value === null) return "null";
else if (Array.isArray(value)) return inspectArray(value, options);
switch (typeof value) {
case "string": return JSON.stringify(value);
case "bigint": return `${value}n`;
case "object":
if (value.constructor?.name !== "Object") return value.constructor?.name;
return inspectRecord(value, options);
case "function": return value.name || "(anonymous)";
}
return value?.toString() ?? "undefined";
}
function inspectArray(value, options) {
const { threshold = defaultThreshold } = options;
const vs = value.map((v$1) => inspect(v$1, options));
const s = vs.join(", ");
if (s.length <= threshold) return `[${s}]`;
const m$1 = vs.join(",\n");
return `[\n${indent(2, m$1)}\n]`;
}
function inspectRecord(value, options) {
const { threshold = defaultThreshold } = options;
const vs = [...Object.keys(value), ...Object.getOwnPropertySymbols(value)].map((k$1) => `${k$1.toString()}: ${inspect(value[k$1], options)}`);
const s = vs.join(", ");
if (s.length <= threshold) return `{${s}}`;
const m$1 = vs.join(",\n");
return `{\n${indent(2, m$1)}\n}`;
}
function indent(level, text) {
const prefix = " ".repeat(level);
return text.split("\n").map((line) => `${prefix}${line}`).join("\n");
}
/**
* Rewrite the function name.
*/ function rewriteName(fn, name, ...args) {
let cachedName;
return Object.defineProperties(fn, { name: { get: () => {
if (cachedName) return cachedName;
cachedName = `${name}(${args.map((v$1) => inspect(v$1)).join(", ")})`;
return cachedName;
} } });
}
function annotate(fn, name, value) {
return Object.defineProperties(fn, { [name]: { value } });
}
function hasAnnotation(fn, name) {
return !!fn[name];
}
/**
* Return a type predicate function that returns `true` if the type of `x` is `ObjectOf<T>`.
*
* Use {@linkcode [is/record-of].isRecordOf|isRecordOf} if you want to check if the type of `x` is a record of `T`.
*
* If {@linkcode [as/optional].asOptional|asOptional} is specified in the predicate function in `predObj`, the property becomes optional.
* If {@linkcode [as/readonly].asReadonly|asReadonly} is specified in the predicate function in `predObj`, the property becomes readonly.
*
* The number of keys of `x` must be greater than or equal to the number of keys of `predObj`.
* Use {@linkcode [is/strict-of].isStrictOf|isStrictOf} if you want to check the exact number of keys.
*
* To enhance performance, users are advised to cache the return value of this function and mitigate the creation cost.
*
* ```ts
* import { as, is } from "@core/unknownutil";
*
* const isMyType = is.ObjectOf({
* a: is.Number,
* b: is.String,
* c: as.Optional(is.Boolean),
* d: as.Readonly(is.String),
* });
* const a: unknown = { a: 0, b: "a", d: "d" };
* if (isMyType(a)) {
* const _: { a: number; b: string; c?: boolean | undefined, readonly d: string } = a;
* }
* ```
*/ function isObjectOf(predObj) {
const preds = [...Object.keys(predObj), ...Object.getOwnPropertySymbols(predObj)].map((k$1) => [k$1, predObj[k$1]]);
const pred = rewriteName((x) => {
if (!isObject$1(x)) return false;
return preds.every(([k$1, pred$1]) => pred$1(x[k$1]));
}, "isObjectOf", predObj);
return annotate(pred, "predObj", predObj);
}
function isObject$1(x) {
if (x == null) return false;
if (typeof x !== "object" && typeof x !== "function") return false;
if (Array.isArray(x)) return false;
return true;
}
/**
* Annotate the given predicate function as optional.
*
* Use this function to annotate a predicate function of `predObj` in {@linkcode [is/object-of].isObjectOf|isObjectOf}.
*
* Note that the annotated predicate function will return `true` if the type of `x` is `T` or `undefined`, indicating that
* this function is not just for annotation but it also changes the behavior of the predicate function.
*
* Use {@linkcode asUnoptional} to remove the annotation.
* Use {@linkcode hasOptional} to check if a predicate function has annotated with this function.
*
* To enhance performance, users are advised to cache the return value of this function and mitigate the creation cost.
*
* ```ts
* import { as, is } from "@core/unknownutil";
*
* const isMyType = is.ObjectOf({
* foo: as.Optional(is.String),
* });
* const a: unknown = {};
* if (isMyType(a)) {
* const _: {foo?: string} = a;
* }
* ```
*/ function asOptional(pred) {
if (hasAnnotation(pred, "optional")) return pred;
return rewriteName(annotate((x) => x === void 0 || pred(x), "optional", pred), "asOptional", pred);
}
/**
* Check if a value is an error object
*/ const isErrorObject = isObjectOf({
proto: isString,
name: isString,
message: isString,
stack: asOptional(isString),
attributes: isRecord
});
/**
* Error indicating that this part is unreachable.
*/ var UnreachableError = class UnreachableError extends Error {
args;
constructor(args) {
super(`unreachable: ${args}`);
if (Error.captureStackTrace) Error.captureStackTrace(this, UnreachableError);
this.name = this.constructor.name;
this.args = args;
}
};
/**
* Function indicating that this part is unreachable.
*
* For example, the following code passed type checking.
*
* ```ts
* import { unreachable } from "@core/errorutil/unreachable";
*
* type Animal = "dog" | "cat";
*
* function say(animal: Animal): void {
* switch (animal) {
* case "dog":
* console.log("dog");
* break;
* case "cat":
* console.log("dog");
* break;
* default:
* unreachable(animal);
* }
* }
* say("dog");
* ```
*
* But the following code because a case for "bird" is missing.
*
* ```ts
* import { unreachable } from "@core/errorutil/unreachable";
*
* type Animal = "dog" | "cat" | "bird";
*
* function say(animal: Animal): void {
* switch (animal) {
* case "dog":
* console.log("dog");
* break;
* case "cat":
* console.log("dog");
* break;
* default: {
* // The line below causes a type error if we uncomment it.
* // error: TS2345 [ERROR]: Argument of type 'string' is not assignable to parameter of type 'never'.
* //unreachable(animal);
* }
* }
* }
* say("dog");
* ```
*/ function unreachable(...args) {
throw new UnreachableError(args);
}
function groupBy(arr, getKeyFromItem) {
const result = {};
for (let i = 0; i < arr.length; i++) {
const item = arr[i];
const key = getKeyFromItem(item);
if (!Object.hasOwn(result, key)) result[key] = [];
result[key].push(item);
}
return result;
}
function uniq(arr) {
return Array.from(new Set(arr));
}
var castComparer = function(comparer) {
return function(a$1, b$1, order) {
return comparer(a$1, b$1, order) * order;
};
};
var throwInvalidConfigErrorIfTrue = function(condition, context) {
if (condition) throw Error("Invalid sort config: " + context);
};
var unpackObjectSorter = function(sortByObj) {
var _a = sortByObj || {}, asc = _a.asc, desc = _a.desc;
var order = asc ? 1 : -1;
var sortBy = asc || desc;
throwInvalidConfigErrorIfTrue(!sortBy, "Expected `asc` or `desc` property");
throwInvalidConfigErrorIfTrue(asc && desc, "Ambiguous object with `asc` and `desc` config properties");
var comparer = sortByObj.comparer && castComparer(sortByObj.comparer);
return {
order,
sortBy,
comparer
};
};
var multiPropertySorterProvider = function(defaultComparer$1) {
return function multiPropertySorter(sortBy, sortByArr, depth$1, order, comparer, a$1, b$1) {
var valA;
var valB;
if (typeof sortBy === "string") {
valA = a$1[sortBy];
valB = b$1[sortBy];
} else if (typeof sortBy === "function") {
valA = sortBy(a$1);
valB = sortBy(b$1);
} else {
var objectSorterConfig = unpackObjectSorter(sortBy);
return multiPropertySorter(objectSorterConfig.sortBy, sortByArr, depth$1, objectSorterConfig.order, objectSorterConfig.comparer || defaultComparer$1, a$1, b$1);
}
var equality = comparer(valA, valB, order);
if ((equality === 0 || valA == null && valB == null) && sortByArr.length > depth$1) return multiPropertySorter(sortByArr[depth$1], sortByArr, depth$1 + 1, order, comparer, a$1, b$1);
return equality;
};
};
function getSortStrategy(sortBy, comparer, order) {
if (sortBy === void 0 || sortBy === true) return function(a$1, b$1) {
return comparer(a$1, b$1, order);
};
if (typeof sortBy === "string") {
throwInvalidConfigErrorIfTrue(sortBy.includes("."), "String syntax not allowed for nested properties.");
return function(a$1, b$1) {
return comparer(a$1[sortBy], b$1[sortBy], order);
};
}
if (typeof sortBy === "function") return function(a$1, b$1) {
return comparer(sortBy(a$1), sortBy(b$1), order);
};
if (Array.isArray(sortBy)) {
var multiPropSorter_1 = multiPropertySorterProvider(comparer);
return function(a$1, b$1) {
return multiPropSorter_1(sortBy[0], sortBy, 1, order, comparer, a$1, b$1);
};
}
var objectSorterConfig = unpackObjectSorter(sortBy);
return getSortStrategy(objectSorterConfig.sortBy, objectSorterConfig.comparer || comparer, objectSorterConfig.order);
}
var sortArray = function(order, ctx, sortBy, comparer) {
var _a;
if (!Array.isArray(ctx)) return ctx;
if (Array.isArray(sortBy) && sortBy.length < 2) _a = sortBy, sortBy = _a[0];
return ctx.sort(getSortStrategy(sortBy, comparer, order));
};
function createNewSortInstance(opts) {
var comparer = castComparer(opts.comparer);
return function(arrayToSort) {
var ctx = Array.isArray(arrayToSort) && !opts.inPlaceSorting ? arrayToSort.slice() : arrayToSort;
return {
asc: function(sortBy) {
return sortArray(1, ctx, sortBy, comparer);
},
desc: function(sortBy) {
return sortArray(-1, ctx, sortBy, comparer);
},
by: function(sortBy) {
return sortArray(1, ctx, sortBy, comparer);
}
};
};
}
var defaultComparer = function(a$1, b$1, order) {
if (a$1 == null) return order;
if (b$1 == null) return -order;
if (typeof a$1 !== typeof b$1) return typeof a$1 < typeof b$1 ? -1 : 1;
if (a$1 < b$1) return -1;
if (a$1 > b$1) return 1;
return 0;
};
var sort = createNewSortInstance({ comparer: defaultComparer });
var inPlaceSort = createNewSortInstance({
comparer: defaultComparer,
inPlaceSorting: true
});
var d = Object.defineProperty;
var n = (s, t) => d(s, "name", {
value: t,
configurable: !0
});
typeof Symbol.asyncDispose != "symbol" && Object.defineProperty(Symbol, "asyncDispose", {
configurable: !1,
enumerable: !1,
writable: !1,
value: Symbol.for("asyncDispose")
});
var P = class {
static {
n(this, "FsFixture");
}
path;
constructor(t) {
this.path = t;
}
getPath(...t) {
return path.join(this.path, ...t);
}
exists(t = "") {
return a.access(this.getPath(t)).then(() => !0, () => !1);
}
rm(t = "") {
return a.rm(this.getPath(t), {
recursive: !0,
force: !0
});
}
cp(t, r, i) {
return r ? r.endsWith(path.sep) && (r += path.basename(t)) : r = path.basename(t), a.cp(t, this.getPath(r), i);
}
mkdir(t) {
return a.mkdir(this.getPath(t), { recursive: !0 });
}
writeFile(t, r) {
return a.writeFile(this.getPath(t), r);
}
writeJson(t, r) {
return this.writeFile(t, JSON.stringify(r, null, 2));
}
readFile(t, r) {
return a.readFile(this.getPath(t), r);
}
async [Symbol.asyncDispose]() {
await this.rm();
}
};
const v = b.realpathSync(F.tmpdir()), D = `fs-fixture-${Date.now()}-${process.pid}`;
let m = 0;
const j = n(() => (m += 1, m), "getId");
var u = class {
static {
n(this, "Path");
}
path;
constructor(t) {
this.path = t;
}
};
var f = class extends u {
static {
n(this, "Directory");
}
};
var y = class extends u {
static {
n(this, "File");
}
content;
constructor(t, r) {
super(t), this.content = r;
}
};
var l = class {
static {
n(this, "Symlink");
}
target;
type;
path;
constructor(t, r) {
this.target = t, this.type = r;
}
};
const w = n((s, t, r) => {
const i = [];
for (const p in s) {
if (!Object.hasOwn(s, p)) continue;
const e = path.join(t, p);
let o = s[p];
if (typeof o == "function") {
const g = Object.assign(Object.create(r), { filePath: e }), h = o(g);
if (h instanceof l) {
h.path = e, i.push(h);
continue;
} else o = h;
}
typeof o == "string" ? i.push(new y(e, o)) : i.push(new f(e), ...w(o, e, r));
}
return i;
}, "flattenFileTree"), k = n(async (s, t) => {
const r = t?.tempDir ? path.resolve(t.tempDir) : v, i = path.join(r, `${D}-${j()}/`);
if (await a.mkdir(i, { recursive: !0 }), s) {
if (typeof s == "string") await a.cp(s, i, {
recursive: !0,
filter: t?.templateFilter
});
else if (typeof s == "object") {
const p = {
fixturePath: i,
getPath: n((...e) => path.join(i, ...e), "getPath"),
symlink: n((e, o) => new l(e, o), "symlink")
};
await Promise.all(w(s, i, p).map(async (e) => {
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));
}));
}
}
return new P(i);
}, "createFixture");
async function isType(fsStatType, statsMethodName, filePath) {
if (typeof filePath !== "string") throw new TypeError(`Expected a string, got ${typeof filePath}`);
try {
const stats = await a[fsStatType](filePath);
return stats[statsMethodName]();
} catch (error) {
if (error.code === "ENOENT") return false;
throw error;
}
}
function isTypeSync(fsStatType, statsMethodName, filePath) {
if (typeof filePath !== "string") throw new TypeError(`Expected a string, got ${typeof filePath}`);
try {
return b[fsStatType](filePath)[statsMethodName]();
} catch (error) {
if (error.code === "ENOENT") return false;
throw error;
}
}
const isFile = isType.bind(void 0, "stat", "isFile");
const isDirectory = isType.bind(void 0, "stat", "isDirectory");
const isSymlink = isType.bind(void 0, "lstat", "isSymbolicLink");
const isFileSync = isTypeSync.bind(void 0, "statSync", "isFile");
const isDirectorySync = isTypeSync.bind(void 0, "statSync", "isDirectory");
const isSymlinkSync = isTypeSync.bind(void 0, "lstatSync", "isSymbolicLink");
var require_utils$1 = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizePath = exports.isRootDirectory = exports.convertSlashes = exports.cleanPath = void 0;
const path_1$4 = __require("node:path");
function cleanPath(path$1) {
let normalized = (0, path_1$4.normalize)(path$1);
if (normalized.length > 1 && normalized[normalized.length - 1] === path_1$4.sep) normalized = normalized.substring(0, normalized.length - 1);
return normalized;
}
exports.cleanPath = cleanPath;
const SLASHES_REGEX = /[\\/]/g;
function convertSlashes(path$1, separator) {
return path$1.replace(SLASHES_REGEX, separator);
}
exports.convertSlashes = convertSlashes;
const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
function isRootDirectory(path$1) {
return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1);
}
exports.isRootDirectory = isRootDirectory;
function normalizePath(path$1, options) {
const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith(".");
if (resolvePaths) path$1 = (0, path_1$4.resolve)(path$1);
if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1);
if (path$1 === ".") return "";
const needsSeperator = path$1[path$1.length - 1] !== pathSeparator;
return convertSlashes(needsSeperator ? path$1 + pathSeparator : path$1, pathSeparator);
}
exports.normalizePath = normalizePath;
});
var require_join_path = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = exports.joinDirectoryPath = exports.joinPathWithBasePath = void 0;
const path_1$3 = __require("node:path");
const utils_1$1 = require_utils$1();
function joinPathWithBasePath(filename, directoryPath) {
return directoryPath + filename;
}
exports.joinPathWithBasePath = joinPathWithBasePath;
function joinPathWithRelativePath(root, options) {
return function(filename, directoryPath) {
const sameRoot = directoryPath.startsWith(root);
if (sameRoot) return directoryPath.replace(root, "") + filename;
else return (0, utils_1$1.convertSlashes)((0, path_1$3.relative)(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
};
}
function joinPath$1(filename) {
return filename;
}
function joinDirectoryPath(filename, directoryPath, separator) {
return directoryPath + filename + separator;
}
exports.joinDirectoryPath = joinDirectoryPath;
function build$7(root, options) {
const { relativePaths, includeBasePath } = options;
return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath$1;
}
exports.build = build$7;
});
var require_push_directory = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
function pushDirectoryWithRelativePath(root) {
return function(directoryPath, paths) {
paths.push(directoryPath.substring(root.length) || ".");
};
}
function pushDirectoryFilterWithRelativePath(root) {
return function(directoryPath, paths, filters) {
const relativePath = directoryPath.substring(root.length) || ".";
if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
};
}
const pushDirectory$1 = (directoryPath, paths) => {
paths.push(directoryPath || ".");
};
const pushDirectoryFilter = (directoryPath, paths, filters) => {
const path$1 = directoryPath || ".";
if (filters.every((filter) => filter(path$1, true))) paths.push(path$1);
};
const empty$2 = () => {};
function build$6(root, options) {
const { includeDirs, filters, relativePaths } = options;
if (!includeDirs) return empty$2;
if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
return filters && filters.length ? pushDirectoryFilter : pushDirectory$1;
}
exports.build = build$6;
});
var require_push_file = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
if (filters.every((filter) => filter(filename, false))) counts.files++;
};
const pushFileFilter = (filename, paths, _counts, filters) => {
if (filters.every((filter) => filter(filename, false))) paths.push(filename);
};
const pushFileCount = (_filename, _paths, counts, _filters) => {
counts.files++;
};
const pushFile$1 = (filename, paths) => {
paths.push(filename);
};
const empty$1 = () => {};
function build$5(options) {
const { excludeFiles, filters, onlyCounts } = options;
if (excludeFiles) return empty$1;
if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
else if (onlyCounts) return pushFileCount;
else return pushFile$1;
}
exports.build = build$5;
});
var require_get_array = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const getArray$1 = (paths) => {
return paths;
};
const getArrayGroup = () => {
return [""].slice(0, 0);
};
function build$4(options) {
return options.group ? getArrayGroup : getArray$1;
}
exports.build = build$4;
});
var require_group_files = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const groupFiles$1 = (groups, directory, files) => {
groups.push({
directory,
files,
dir: directory
});
};
const empty = () => {};
function build$3(options) {
return options.group ? groupFiles$1 : empty;
}
exports.build = build$3;
});
var require_resolve_symlink = __commonJSMin((exports) => {
var __importDefault$1 = function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const fs_1$1 = __importDefault$1(__require("node:fs"));
const path_1$2 = __require("node:path");
const resolveSymlinksAsync = function(path$1, state, callback$1) {
const { queue, options: { suppressErrors } } = state;
queue.enqueue();
fs_1$1.default.realpath(path$1, (error, resolvedPath) => {
if (error) return queue.dequeue(suppressErrors ? null : error, state);
fs_1$1.default.stat(resolvedPath, (error$1, stat) => {
if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state);
callback$1(stat, resolvedPath);
queue.dequeue(null, state);
});
});
};
const resolveSymlinks = function(path$1, state, callback$1) {
const { queue, options: { suppressErrors } } = state;
queue.enqueue();
try {
const resolvedPath = fs_1$1.default.realpathSync(path$1);
const stat = fs_1$1.default.statSync(resolvedPath);
if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return;
callback$1(stat, resolvedPath);
} catch (e) {
if (!suppressErrors) throw e;
}
};
function build$2(options, isSynchronous) {
if (!options.resolveSymlinks || options.excludeSymlinks) return null;
return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
}
exports.build = build$2;
function isRecursive(path$1, resolved, state) {
if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
let parent = (0, path_1$2.dirname)(path$1);
let depth$1 = 1;
while (parent !== state.root && depth$1 < 2) {
const resolvedPath = state.symlinks.get(parent);
const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath));
if (isSameRoot) depth$1++;
else parent = (0, path_1$2.dirname)(parent);
}
state.symlinks.set(path$1, resolved);
return depth$1 > 1;
}
function isRecursiveUsingRealPaths(resolved, state) {
return state.visited.includes(resolved + state.options.pathSeparator);
}
});
var require_invoke_callback = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const onlyCountsSync = (state) => {
return state.counts;
};
const groupsSync = (state) => {
return state.groups;
};
const defaultSync = (state) => {
return state.paths;
};
const limitFilesSync = (state) => {
return state.paths.slice(0, state.options.maxFiles);
};
const onlyCountsAsync = (state, error, callback$1) => {
report(error, callback$1, state.counts, state.options.suppressErrors);
return null;
};
const defaultAsync = (state, error, callback$1) => {
report(error, callback$1, state.paths, state.options.suppressErrors);
return null;
};
const limitFilesAsync = (state, error, callback$1) => {
report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
return null;
};
const groupsAsync = (state, error, callback$1) => {
report(error, callback$1, state.groups, state.options.suppressErrors);
return null;
};
function report(error, callback$1, output, suppressErrors) {
if (error && !suppressErrors) callback$1(error, output);
else callback$1(null, output);
}
function build$1(options, isSynchronous) {
const { onlyCounts, group, maxFiles } = options;
if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
else if (group) return isSynchronous ? groupsSync : groupsAsync;
else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
else return isSynchronous ? defaultSync : defaultAsync;
}
exports.build = build$1;
});
var require_walk_directory = __commonJSMin((exports) => {
var __importDefault = function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.build = void 0;
const fs_1 = __importDefault(__require("node:fs"));
const readdirOpts = { withFileTypes: true };
const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
state.queue.enqueue();
if (currentDepth < 0) return state.queue.dequeue(null, state);
state.visited.push(crawlPath);
state.counts.directories++;
fs_1.default.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
callback$1(entries, directoryPath, currentDepth);
state.queue.dequeue(state.options.suppressErrors ? null : error, state);
});
};
const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
if (currentDepth < 0) return;
state.visited.push(crawlPath);
state.counts.directories++;
let entries = [];
try {
entries = fs_1.default.readdirSync(crawlPath || ".", readdirOpts);
} catch (e) {
if (!state.options.suppressErrors) throw e;
}
callback$1(entries, directoryPath, currentDepth);
};
function build(isSynchronous) {
return isSynchronous ? walkSync : walkAsync;
}
exports.build = build;
});
var require_queue = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Queue = void 0;
/**
* This is a custom stateless queue to track concurrent async fs calls.
* It increments a counter whenever a call is queued and decrements it
* as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
*/
var Queue = class {
onQueueEmpty;
count = 0;
constructor(onQueueEmpty) {
this.onQueueEmpty = onQueueEmpty;
}
enqueue() {
this.count++;
return this.count;
}
dequeue(error, output) {
if (this.onQueueEmpty && (--this.count <= 0 || error)) {
this.onQueueEmpty(error, output);
if (error) {
output.controller.abort();
this.onQueueEmpty = void 0;
}
}
}
};
exports.Queue = Queue;
});
var require_counter = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Counter = void 0;
var Counter = class {
_files = 0;
_directories = 0;
set files(num) {
this._files = num;
}
get files() {
return this._files;
}
set directories(num) {
this._directories = num;
}
get directories() {
return this._directories;
}
/**
* @deprecated use `directories` instead
*/
/* c8 ignore next 3 */
get dirs() {
return this._directories;
}
};
exports.Counter = Counter;
});
var require_walker = __commonJSMin((exports) => {
var __createBinding$1 = Object.create ? function(o, m$1, k$1, k2) {
if (k2 === void 0) k2 = k$1;
var desc = Object.getOwnPropertyDescriptor(m$1, k$1);
if (!desc || ("get" in desc ? !m$1.__esModule : desc.writable || desc.configurable)) desc = {
enumerable: true,
get: function() {
return m$1[k$1];
}
};
Object.defineProperty(o, k2, desc);
} : function(o, m$1, k$1, k2) {
if (k2 === void 0) k2 = k$1;
o[k2] = m$1[k$1];
};
var __setModuleDefault = Object.create ? function(o, v$1) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v$1
});
} : function(o, v$1) {
o["default"] = v$1;
};
var __importStar = function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k$1 in mod) if (k$1 !== "default" && Object.prototype.hasOwnProperty.call(mod, k$1)) __createBinding$1(result, mod, k$1);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Walker = void 0;
const path_1$1 = __require("node:path");
const utils_1 = require_utils$1();
const joinPath = __importStar(require_join_path());
const pushDirectory = __importStar(require_push_directory());
const pushFile = __importStar(require_push_file());
const getArray = __importStar(require_get_array());
const groupFiles = __importStar(require_group_files());
const resolveSymlink = __importStar(require_resolve_symlink());
const invokeCallback = __importStar(require_invoke_callback());
const walkDirectory = __importStar(require_walk_directory());
const queue_1 = require_queue();
const counter_1 = require_counter();
var Walker = class {
root;
isSynchronous;
state;
joinPath;
pushDirectory;
pushFile;
getArray;
groupFiles;
resolveSymlink;
walkDirectory;
callbackInvoker;
constructor(root, options, callback$1) {
this.isSynchronous = !callback$1;
this.callbackInvoker = invokeCallback.build(options, this.isSynchronous);
this.root = (0, utils_1.normalizePath)(root, options);
this.state = {
root: (0, utils_1.isRootDirectory)(this.root) ? this.root : this.root.slice(0, -1),
paths: [""].slice(0, 0),
groups: [],
counts: new counter_1.Counter(),
options,
queue: new queue_1.Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
symlinks: /* @__PURE__ */ new Map(),
visited: [""].slice(0, 0),
controller: new AbortController()
};
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);
}
start() {
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);
return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
}
walk = (entries, directoryPath, depth$1) => {
const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
if (controller.signal.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
const files = this.getArray(this.state.paths);
for (let i = 0; i < entries.length; ++i) {
const entry = entries[i];
if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
const filename = this.joinPath(entry.name, directoryPath);
this.pushFile(filename, files, this.state.counts, filters);
} else if (entry.isDirectory()) {
let path$1 = joinPath.joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
if (exclude && exclude(entry.name, path$1)) continue;
this.pushDirectory(path$1, paths, filters);
this.walkDirectory(this.state, path$1, path$1, depth$1 - 1, this.walk);
} else if (this.resolveSymlink && entry.isSymbolicLink()) {
let path$1 = joinPath.joinPathWithBasePath(entry.name, directoryPath);
this.resolveSymlink(path$1, this.state, (stat, resolvedPath) => {
if (stat.isDirectory()) {
resolvedPath = (0, utils_1.normalizePath)(resolvedPath, this.state.options);
if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return;
this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth$1 - 1, this.walk);
} else {
resolvedPath = useRealPaths ? resolvedPath : path$1;
const filename = (0, path_1$1.basename)(resolvedPath);
const directoryPath$1 = (0, utils_1.normalizePath)((0, path_1$1.dirname)(resolvedPath), this.state.options);
resolvedPath = this.joinPath(filename, directoryPath$1);
this.pushFile(resolvedPath, files, this.state.counts, filters);
}
});
}
}
this.groupFiles(this.state.groups, directoryPath, files);
};
};
exports.Walker = Walker;
});
var require_async = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.callback = exports.promise = void 0;
const walker_1$1 = require_walker();
function promise(root, options) {
return new Promise((resolve, reject) => {
callback(root, options, (err, output) => {
if (err) return reject(err);
resolve(output);
});
});
}
exports.promise = promise;
function callback(root, options, callback$1) {
let walker = new walker_1$1.Walker(root, options, callback$1);
walker.start();
}
exports.callback = callback;
});
var require_sync = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.sync = void 0;
const walker_1 = require_walker();
function sync(root, options) {
const walker = new walker_1.Walker(root, options);
return walker.start();
}
exports.sync = sync;
});
var require_api_builder = __commonJSMin((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIBuilder = void 0;
const async_1 = require_async();
const sync_1 = require_sync();
var APIBuilder = class {
root;
options;
constructor(root, options) {
this.root = root;
this.options = options;
}
withPromise() {
return (0, async_1.promise)(this.root, this.options);
}
withCallback(cb) {
(0, async_1.callback)(this.root, this.options, cb);
}
sync() {
return (0, sync_1.sync)(this.root, this.options);
}
};
exports.APIBuilder = APIBuilder;
});
var require_constants = __commonJSMin((exports, module) => {
const WIN_SLASH = "\\\\/";
const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
/**
* Posix glob regex
*/
const DOT_LITERAL = "\\.";
const PLUS_LITERAL = "\\+";
const QMARK_LITERAL = "\\?";
const SLASH_LITERAL = "\\/";
const ONE_CHAR = "(?=.)";
const QMARK = "[^/]";
const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
const NO_DOT = `(?!${DOT_LITERAL})`;
const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
const STAR = `${QMARK}*?`;
const SEP = "/";
const POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR,
START_ANCHOR,
SEP
};
/**
* Windows glob regex
*/
const WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
SEP: "\\"
};
/**
* POSIX Bracket Regex
*/
const POSIX_REGEX_SOURCE$1 = {
alnum: "a-zA-Z0-9",
alpha: "a-zA-Z",
ascii: "\\x00-\\x7F",
blank: " \\t",
cntrl: "\\x00-\\x1F\\x7F",
digit: "0-9",
graph: "\\x21-\\x7E",
lower: "a-z",
print: "\\x20-\\x7E ",
punct: "\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",
space: " \\t\\r\\n\\v\\f",
upper: "A-Z",
word: "A-Za-z0-9_",
xdigit: "A-Fa-f0-9"
};
module.exports = {
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1,
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
REPLACEMENTS: {
"***": "*",
"**/**": "**",
"**/**/**": "**"
},
CHAR_0: 48,
CHAR_9: 57,
CHAR_UPPERCASE_A: 65,
CHAR_LOWERCASE_A: 97,
CHAR_UPPERCASE_Z: 90,
CHAR_LOWERCASE_Z: 122,
CHAR_LEFT_PARENTHESES: 40,
CHAR_RIGHT_PARENTHESES: 41,
CHAR_ASTERISK: 42,
CHAR_AMPERSAND: 38,
CHAR_AT: 64,
CHAR_BACKWARD_SLASH: 92,
CHAR_CARRIAGE_RETURN: 13,
CHAR_CIRCUMFLEX_ACCENT: 94,
CHAR_COLON: 58,
CHAR_COMMA: 44,
CHAR_DOT: 46,
CHAR_DOUBLE_QUOTE: 34,
CHAR_EQUAL: 61,
CHAR_EXCLAMATION_MARK: 33,
CHAR_FORM_FEED: 12,
CHAR_FORWARD_SLASH: 47,
CHAR_GRAVE_ACCENT: 96,
CHAR_HASH: 35,
CHAR_HYPHEN_MINUS: 45,
CHAR_LEFT_ANGLE_BRACKET: 60,
CHAR_LEFT_CURLY_BRACE: 123,
CHAR_LEFT_SQUARE_BRACKET: 91,
CHAR_LINE_FEED: 10,
CHAR_NO_BREAK_SPACE: 160,
CHAR_PERCENT: 37,
CHAR_PLUS: 43,
CHAR_QUESTION_MARK: 63,
CHAR_RIGHT_ANGLE_BRACKET: 62,
CHAR_RIGHT_CURLY_BRACE: 125,
CHAR_RIGHT_SQUARE_BRACKET: 93,
CHAR_SEMICOLON: 59,
CHAR_SINGLE_QUOTE: 39,
CHAR_SPACE: 32,
CHAR_TAB: 9,
CHAR_UNDERSCORE: 95,
CHAR_VERTICAL_LINE: 124,
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
extglobChars(chars) {
return {
"!": {
type: "negate",
open: "(?:(?!(?:",
close: `))${chars.STAR})`
},
"?": {
type: "qmark",
open: "(?:",
close: ")?"
},
"+": {
type: "plus",
open: "(?:",
close: ")+"
},
"*": {
type: "star",
open: "(?:",
close: ")*"
},
"@": {
type: "at",
open: "(?:",
close: ")"
}
};
},
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
});
var require_utils = __commonJSMin((exports) => {
const { REGEX_BACKSLASH, REGEX_REMOVE_BACKSLASH, REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL } = require_constants();
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 = () => {
if (typeof navigator !== "undefined" && navigator.platform) {
const platform = navigator.platform.toLowerCase();
return platform === "win32" || platform === "windows";
}
if (typeof process !== "undefined" && process.platform) return process.platform === "win32";
return false;
};
exports.removeBackslashes = (str) => {
return str.replace(REGEX_REMOVE_BACKSLASH, (match) => {
return match === "\\" ? "" : match;
});
};
exports.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1) return input;
if (input[idx - 1] === "\\") return exports.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports.removePrefix = (input, state = {}) => {
let output = input;
if (output.startsWith("./")) {
output = output.slice(2);
state.prefix = "./";
}
return output;
};
exports.wrapOutput = (input, state = {}, options = {}) => {
const prepend = options.contains ? "" : "^";
const append = options.contains ? "" : "$";
let output = `${prepend}(?:${input})${append}`;
if (state.negated === true) output = `(?:^(?!${output}).*$)`;
return output;
};
exports.basename = (path$1, { windows } = {}) => {
const segs = path$1.split(windows ? /[\\/]/ : "/");
const last = segs[segs.length - 1];
if (last === "") return segs[segs.length - 2];
return last;
};
});
var require_scan = __commonJSMin((exports, module) => {
const utils$3 = require_utils();
const { CHAR_ASTERISK, CHAR_AT, CHAR_BACKWARD_SLASH, CHAR_COMMA, CHAR_DOT, CHAR_EXCLAMATION_MARK, CHAR_FORWARD_SLASH, CHAR_LEFT_CURLY_BRACE, CHAR_LEFT_PARENTHESES, CHAR_LEFT_SQUARE_BRACKET, CHAR_PLUS, CHAR_QUESTION_MARK, CHAR_RIGHT_CURLY_BRACE, CHAR_RIGHT_PARENTHESES, CHAR_RIGHT_SQUARE_BRACKET } = require_constants();
const isPathSeparator = (code) => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
const depth = (token) => {
if (token.isPrefix !== true) token.depth = token.isGlobstar ? Infinity : 1;
};
/**
* Quickly scans a glob pattern and returns an object with a handful of
* useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
* `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
* with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
*
* ```js
* const pm = require('picomatch');
* console.log(pm.scan('foo/bar/*.js'));
* { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {Object} Returns an object with tokens and regex source string.
* @api public
*/
const scan$1 = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished = false;
let braces = 0;
let prev;
let code;
let token = {
value: "",
depth: 0,
isGlob: false
};
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
};
while (index < length) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
if (code === CHAR_LEFT_CURLY_BRACE) braceEscaped = true;
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) continue;
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = true;
break;
}
}
}
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = {
value: "",
depth: 0,
isGlob: false
};
if (finished === true) continue;
if (prev === CHAR_DOT && index === start + 1) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK;
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) negatedExtglob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
isGlob = token.isGlob = true;
finished = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) continue;
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished = true;
break;
}
}
if (scanToEnd === true) continue;
break;
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
if (scanToEnd === true) {
while (eos() !== true && (code = advance())) {
if (code === CHAR_LEFT_PARENTHESES) {
backslashes = token.backslashes = true;
code = advance();
continue;
}
if (code === CHAR_RIGHT_PARENTHESES) {
finished = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished = true;
if (scanToEnd === true) continue;
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base = str;
let prefix = "";
let glob$1 = "";
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob$1 = str.slice(lastIndex);
} else if (isGlob === true) {
base = "";
glob$1 = str;
} else base = str;
if (base && base !== "" && base !== "/" && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) base = base.slice(0, -1);
}
if (opts.unescape === true) {
if (glob$1) glob$1 = utils$3.removeBackslashes(glob$1);
if (base && backslashes === true) base = utils$3.removeBackslashes(base);
}
const state = {
prefix,
input,
start,
base,
glob: glob$1,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) tokens.push(token);
state.tokens = tokens;
}
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
for (let idx = 0; idx < slashes.length; idx++) {
const n$1 = prevIndex ? prevIndex + 1 : start;
const i = slashes[idx];
const value = input.slice(n$1, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else tokens[idx].value = value;
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (idx !== 0 || value !== "") parts.push(value);
prevIndex = i;
}
if (prevIndex && prevIndex + 1 < input.length) {
const value = input.slice(prevIndex + 1);
parts.push(value);
if (opts.tokens) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
module.exports = scan$1;
});
var require_parse = __commonJSMin((exports, module) => {
const constants$1 = require_constants();
const utils$2 = require_utils();
/**
* Constants
*/
const { MAX_LENGTH, POSIX_REGEX_SOURCE, REGEX_NON_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
/**
* Helpers
*/
const expandRange = (args, options) => {
if (typeof options.expandRange === "function") return options.expandRange(...args, options);
args.sort();
const value = `[${args.join("-")}]`;
try {
new RegExp(value);
} catch (ex) {
return args.map((v$1) => utils$2.escapeRegex(v$1