codekingpro/portable-devtools
115k
1import nativeFs from "fs";
2import path, { posix } from "path";
3import { fileURLToPath } from "url";
4import { fdir } from "fdir";
5import picomatch from "picomatch";
6
7//#region src/utils.ts
8const isReadonlyArray = Array.isArray;
9const isWin = process.platform === "win32";
10const ONLY_PARENT_DIRECTORIES = /^(\/?\.\.)+$/;
11function getPartialMatcher(patterns, options = {}) {
12 const patternsCount = patterns.length;
13 const patternsParts = Array(patternsCount);
14 const matchers = Array(patternsCount);
15 const globstarEnabled = !options.noglobstar;
16 for (let i = 0; i < patternsCount; i++) {
17 const parts = splitPattern(patterns[i]);
18 patternsParts[i] = parts;
19 const partsCount = parts.length;
20 const partMatchers = Array(partsCount);
21 for (let j = 0; j < partsCount; j++) partMatchers[j] = picomatch(parts[j], options);
22 matchers[i] = partMatchers;
23 }
24 return (input) => {
25 const inputParts = input.split("/");
26 if (inputParts[0] === ".." && ONLY_PARENT_DIRECTORIES.test(input)) return true;
27 for (let i = 0; i < patterns.length; i++) {
28 const patternParts = patternsParts[i];
29 const matcher = matchers[i];
30 const inputPatternCount = inputParts.length;
31 const minParts = Math.min(inputPatternCount, patternParts.length);
32 let j = 0;
33 while (j < minParts) {
34 const part = patternParts[j];
35 if (part.includes("/")) return true;
36 const match = matcher[j](inputParts[j]);
37 if (!match) break;
38 if (globstarEnabled && part === "**") return true;
39 j++;
40 }
41 if (j === inputPatternCount) return true;
42 }
43 return false;
44 };
45}
46/* node:coverage ignore next 2 */
47const WIN32_ROOT_DIR = /^[A-Z]:\/$/i;
48const isRoot = isWin ? (p) => WIN32_ROOT_DIR.test(p) : (p) => p === "/";
49function buildFormat(cwd, root, absolute) {
50 if (cwd === root || root.startsWith(`${cwd}/`)) {
51 if (absolute) {
52 const start = isRoot(cwd) ? cwd.length : cwd.length + 1;
53 return (p, isDir) => p.slice(start, isDir ? -1 : void 0) || ".";
54 }
55 const prefix = root.slice(cwd.length + 1);
56 if (prefix) return (p, isDir) => {
57 if (p === ".") return prefix;
58 const result = `${prefix}/${p}`;
59 return isDir ? result.slice(0, -1) : result;
60 };
61 return (p, isDir) => isDir && p !== "." ? p.slice(0, -1) : p;
62 }
63 if (absolute) return (p) => posix.relative(cwd, p) || ".";
64 return (p) => posix.relative(cwd, `${root}/${p}`) || ".";
65}
66function buildRelative(cwd, root) {
67 if (root.startsWith(`${cwd}/`)) {
68 const prefix = root.slice(cwd.length + 1);
69 return (p) => `${prefix}/${p}`;
70 }
71 return (p) => {
72 const result = posix.relative(cwd, `${root}/${p}`);
73 if (p.endsWith("/") && result !== "") return `${result}/`;
74 return result || ".";
75 };
76}
77const splitPatternOptions = { parts: true };
78function splitPattern(path$1) {
79 var _result$parts;
80 const result = picomatch.scan(path$1, splitPatternOptions);
81 return ((_result$parts = result.parts) === null || _result$parts === void 0 ? void 0 : _result$parts.length) ? result.parts : [path$1];
82}
83const ESCAPED_WIN32_BACKSLASHES = /\\(?![()[\]{}!+@])/g;
84function convertPosixPathToPattern(path$1) {
85 return escapePosixPath(path$1);
86}
87function convertWin32PathToPattern(path$1) {
88 return escapeWin32Path(path$1).replace(ESCAPED_WIN32_BACKSLASHES, "/");
89}
90/**
91* Converts a path to a pattern depending on the platform.
92* Identical to {@link escapePath} on POSIX systems.
93* @see {@link https://superchupu.dev/tinyglobby/documentation#convertPathToPattern}
94*/
95/* node:coverage ignore next 3 */
96const convertPathToPattern = isWin ? convertWin32PathToPattern : convertPosixPathToPattern;
97const POSIX_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}*?|]|^!|[!+@](?=\()|\\(?![()[\]{}!*+?@|]))/g;
98const WIN32_UNESCAPED_GLOB_SYMBOLS = /(?<!\\)([()[\]{}]|^!|[!+@](?=\())/g;
99const escapePosixPath = (path$1) => path$1.replace(POSIX_UNESCAPED_GLOB_SYMBOLS, "\\$&");
100const escapeWin32Path = (path$1) => path$1.replace(WIN32_UNESCAPED_GLOB_SYMBOLS, "\\$&");
101/**
102* Escapes a path's special characters depending on the platform.
103* @see {@link https://superchupu.dev/tinyglobby/documentation#escapePath}
104*/
105/* node:coverage ignore next */
106const escapePath = isWin ? escapeWin32Path : escapePosixPath;
107/**
108* Checks if a pattern has dynamic parts.
109*
110* Has a few minor differences with [`fast-glob`](https://github.com/mrmlnc/fast-glob) for better accuracy:
111*
112* - Doesn't necessarily return `false` on patterns that include `\`.
113* - Returns `true` if the pattern includes parentheses, regardless of them representing one single pattern or not.
114* - Returns `true` for unfinished glob extensions i.e. `(h`, `+(h`.
115* - Returns `true` for unfinished brace expansions as long as they include `,` or `..`.
116*
117* @see {@link https://superchupu.dev/tinyglobby/documentation#isDynamicPattern}
118*/
119function isDynamicPattern(pattern, options) {
120 if ((options === null || options === void 0 ? void 0 : options.caseSensitiveMatch) === false) return true;
121 const scan = picomatch.scan(pattern);
122 return scan.isGlob || scan.negated;
123}
124function log(...tasks) {
125 console.log(`[tinyglobby ${(/* @__PURE__ */ new Date()).toLocaleTimeString("es")}]`, ...tasks);
126}
127
128//#endregion
129//#region src/index.ts
130const PARENT_DIRECTORY = /^(\/?\.\.)+/;
131const ESCAPING_BACKSLASHES = /\\(?=[()[\]{}!*+?@|])/g;
132const BACKSLASHES = /\\/g;
133function normalizePattern(pattern, expandDirectories, cwd, props, isIgnore) {
134 let result = pattern;
135 if (pattern.endsWith("/")) result = pattern.slice(0, -1);
136 if (!result.endsWith("*") && expandDirectories) result += "/**";
137 const escapedCwd = escapePath(cwd);
138 if (path.isAbsolute(result.replace(ESCAPING_BACKSLASHES, ""))) result = posix.relative(escapedCwd, result);
139 else result = posix.normalize(result);
140 const parentDirectoryMatch = PARENT_DIRECTORY.exec(result);
141 const parts = splitPattern(result);
142 if (parentDirectoryMatch === null || parentDirectoryMatch === void 0 ? void 0 : parentDirectoryMatch[0]) {
143 const n = (parentDirectoryMatch[0].length + 1) / 3;
144 let i = 0;
145 const cwdParts = escapedCwd.split("/");
146 while (i < n && parts[i + n] === cwdParts[cwdParts.length + i - n]) {
147 result = result.slice(0, (n - i - 1) * 3) + result.slice((n - i) * 3 + parts[i + n].length + 1) || ".";
148 i++;
149 }
150 const potentialRoot = posix.join(cwd, parentDirectoryMatch[0].slice(i * 3));
151 if (!potentialRoot.startsWith(".") && props.root.length > potentialRoot.length) {
152 props.root = potentialRoot;
153 props.depthOffset = -n + i;
154 }
155 }
156 if (!isIgnore && props.depthOffset >= 0) {
157 var _props$commonPath;
158 (_props$commonPath = props.commonPath) !== null && _props$commonPath !== void 0 || (props.commonPath = parts);
159 const newCommonPath = [];
160 const length = Math.min(props.commonPath.length, parts.length);
161 for (let i = 0; i < length; i++) {
162 const part = parts[i];
163 if (part === "**" && !parts[i + 1]) {
164 newCommonPath.pop();
165 break;
166 }
167 if (part !== props.commonPath[i] || isDynamicPattern(part) || i === parts.length - 1) break;
168 newCommonPath.push(part);
169 }
170 props.depthOffset = newCommonPath.length;
171 props.commonPath = newCommonPath;
172 props.root = newCommonPath.length > 0 ? posix.join(cwd, ...newCommonPath) : cwd;
173 }
174 return result;
175}
176function processPatterns({ patterns = ["**/*"], ignore = [], expandDirectories = true }, cwd, props) {
177 if (typeof patterns === "string") patterns = [patterns];
178 if (typeof ignore === "string") ignore = [ignore];
179 const matchPatterns = [];
180 const ignorePatterns = [];
181 for (const pattern of ignore) {
182 if (!pattern) continue;
183 if (pattern[0] !== "!" || pattern[1] === "(") ignorePatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, true));
184 }
185 for (const pattern of patterns) {
186 if (!pattern) continue;
187 if (pattern[0] !== "!" || pattern[1] === "(") matchPatterns.push(normalizePattern(pattern, expandDirectories, cwd, props, false));
188 else if (pattern[1] !== "!" || pattern[2] === "(") ignorePatterns.push(normalizePattern(pattern.slice(1), expandDirectories, cwd, props, true));
189 }
190 return {
191 match: matchPatterns,
192 ignore: ignorePatterns
193 };
194}
195function formatPaths(paths, relative) {
196 for (let i = paths.length - 1; i >= 0; i--) {
197 const path$1 = paths[i];
198 paths[i] = relative(path$1);
199 }
200 return paths;
201}
202function normalizeCwd(cwd) {
203 if (!cwd) return process.cwd().replace(BACKSLASHES, "/");
204 if (cwd instanceof URL) return fileURLToPath(cwd).replace(BACKSLASHES, "/");
205 return path.resolve(cwd).replace(BACKSLASHES, "/");
206}
207function getCrawler(patterns, inputOptions = {}) {
208 const options = process.env.TINYGLOBBY_DEBUG ? {
209 ...inputOptions,
210 debug: true
211 } : inputOptions;
212 const cwd = normalizeCwd(options.cwd);
213 if (options.debug) log("globbing with:", {
214 patterns,
215 options,
216 cwd
217 });
218 if (Array.isArray(patterns) && patterns.length === 0) return [{
219 sync: () => [],
220 withPromise: async () => []
221 }, false];
222 const props = {
223 root: cwd,
224 commonPath: null,
225 depthOffset: 0
226 };
227 const processed = processPatterns({
228 ...options,
229 patterns
230 }, cwd, props);
231 if (options.debug) log("internal processing patterns:", processed);
232 const matchOptions = {
233 dot: options.dot,
234 nobrace: options.braceExpansion === false,
235 nocase: options.caseSensitiveMatch === false,
236 noextglob: options.extglob === false,
237 noglobstar: options.globstar === false,
238 posix: true
239 };
240 const matcher = picomatch(processed.match, {
241 ...matchOptions,
242 ignore: processed.ignore
243 });
244 const ignore = picomatch(processed.ignore, matchOptions);
245 const partialMatcher = getPartialMatcher(processed.match, matchOptions);
246 const format = buildFormat(cwd, props.root, options.absolute);
247 const formatExclude = options.absolute ? format : buildFormat(cwd, props.root, true);
248 const fdirOptions = {
249 filters: [options.debug ? (p, isDirectory) => {
250 const path$1 = format(p, isDirectory);
251 const matches = matcher(path$1);
252 if (matches) log(`matched ${path$1}`);
253 return matches;
254 } : (p, isDirectory) => matcher(format(p, isDirectory))],
255 exclude: options.debug ? (_, p) => {
256 const relativePath = formatExclude(p, true);
257 const skipped = relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
258 if (skipped) log(`skipped ${p}`);
259 else log(`crawling ${p}`);
260 return skipped;
261 } : (_, p) => {
262 const relativePath = formatExclude(p, true);
263 return relativePath !== "." && !partialMatcher(relativePath) || ignore(relativePath);
264 },
265 fs: options.fs ? {
266 readdir: options.fs.readdir || nativeFs.readdir,
267 readdirSync: options.fs.readdirSync || nativeFs.readdirSync,
268 realpath: options.fs.realpath || nativeFs.realpath,
269 realpathSync: options.fs.realpathSync || nativeFs.realpathSync,
270 stat: options.fs.stat || nativeFs.stat,
271 statSync: options.fs.statSync || nativeFs.statSync
272 } : void 0,
273 pathSeparator: "/",
274 relativePaths: true,
275 resolveSymlinks: true,
276 signal: options.signal
277 };
278 if (options.deep !== void 0) fdirOptions.maxDepth = Math.round(options.deep - props.depthOffset);
279 if (options.absolute) {
280 fdirOptions.relativePaths = false;
281 fdirOptions.resolvePaths = true;
282 fdirOptions.includeBasePath = true;
283 }
284 if (options.followSymbolicLinks === false) {
285 fdirOptions.resolveSymlinks = false;
286 fdirOptions.excludeSymlinks = true;
287 }
288 if (options.onlyDirectories) {
289 fdirOptions.excludeFiles = true;
290 fdirOptions.includeDirs = true;
291 } else if (options.onlyFiles === false) fdirOptions.includeDirs = true;
292 props.root = props.root.replace(BACKSLASHES, "");
293 const root = props.root;
294 if (options.debug) log("internal properties:", props);
295 const relative = cwd !== root && !options.absolute && buildRelative(cwd, props.root);
296 return [new fdir(fdirOptions).crawl(root), relative];
297}
298async function glob(patternsOrOptions, options) {
299 if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
300 const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string";
301 const opts = isModern ? options : patternsOrOptions;
302 const patterns = isModern ? patternsOrOptions : patternsOrOptions.patterns;
303 const [crawler, relative] = getCrawler(patterns, opts);
304 if (!relative) return crawler.withPromise();
305 return formatPaths(await crawler.withPromise(), relative);
306}
307function globSync(patternsOrOptions, options) {
308 if (patternsOrOptions && (options === null || options === void 0 ? void 0 : options.patterns)) throw new Error("Cannot pass patterns as both an argument and an option");
309 const isModern = isReadonlyArray(patternsOrOptions) || typeof patternsOrOptions === "string";
310 const opts = isModern ? options : patternsOrOptions;
311 const patterns = isModern ? patternsOrOptions : patternsOrOptions.patterns;
312 const [crawler, relative] = getCrawler(patterns, opts);
313 if (!relative) return crawler.sync();
314 return formatPaths(crawler.sync(), relative);
315}
316
317//#endregion
318export { convertPathToPattern, escapePath, glob, globSync, isDynamicPattern };