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