index.cjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. //#region rolldown:runtime
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __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. };
  18. var __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. //#endregion
  23. const path = __toESM(require("path"));
  24. const fs = __toESM(require("fs"));
  25. //#region src/utils.ts
  26. function cleanPath(path$1) {
  27. let normalized = (0, path.normalize)(path$1);
  28. if (normalized.length > 1 && normalized[normalized.length - 1] === path.sep) normalized = normalized.substring(0, normalized.length - 1);
  29. return normalized;
  30. }
  31. const SLASHES_REGEX = /[\\/]/g;
  32. function convertSlashes(path$1, separator) {
  33. return path$1.replace(SLASHES_REGEX, separator);
  34. }
  35. const WINDOWS_ROOT_DIR_REGEX = /^[a-z]:[\\/]$/i;
  36. function isRootDirectory(path$1) {
  37. return path$1 === "/" || WINDOWS_ROOT_DIR_REGEX.test(path$1);
  38. }
  39. function normalizePath(path$1, options) {
  40. const { resolvePaths, normalizePath: normalizePath$1, pathSeparator } = options;
  41. const pathNeedsCleaning = process.platform === "win32" && path$1.includes("/") || path$1.startsWith(".");
  42. if (resolvePaths) path$1 = (0, path.resolve)(path$1);
  43. if (normalizePath$1 || pathNeedsCleaning) path$1 = cleanPath(path$1);
  44. if (path$1 === ".") return "";
  45. const needsSeperator = path$1[path$1.length - 1] !== pathSeparator;
  46. return convertSlashes(needsSeperator ? path$1 + pathSeparator : path$1, pathSeparator);
  47. }
  48. //#endregion
  49. //#region src/api/functions/join-path.ts
  50. function joinPathWithBasePath(filename, directoryPath) {
  51. return directoryPath + filename;
  52. }
  53. function joinPathWithRelativePath(root, options) {
  54. return function(filename, directoryPath) {
  55. const sameRoot = directoryPath.startsWith(root);
  56. if (sameRoot) return directoryPath.replace(root, "") + filename;
  57. else return convertSlashes((0, path.relative)(root, directoryPath), options.pathSeparator) + options.pathSeparator + filename;
  58. };
  59. }
  60. function joinPath(filename) {
  61. return filename;
  62. }
  63. function joinDirectoryPath(filename, directoryPath, separator) {
  64. return directoryPath + filename + separator;
  65. }
  66. function build$7(root, options) {
  67. const { relativePaths, includeBasePath } = options;
  68. return relativePaths && root ? joinPathWithRelativePath(root, options) : includeBasePath ? joinPathWithBasePath : joinPath;
  69. }
  70. //#endregion
  71. //#region src/api/functions/push-directory.ts
  72. function pushDirectoryWithRelativePath(root) {
  73. return function(directoryPath, paths) {
  74. paths.push(directoryPath.substring(root.length) || ".");
  75. };
  76. }
  77. function pushDirectoryFilterWithRelativePath(root) {
  78. return function(directoryPath, paths, filters) {
  79. const relativePath = directoryPath.substring(root.length) || ".";
  80. if (filters.every((filter) => filter(relativePath, true))) paths.push(relativePath);
  81. };
  82. }
  83. const pushDirectory = (directoryPath, paths) => {
  84. paths.push(directoryPath || ".");
  85. };
  86. const pushDirectoryFilter = (directoryPath, paths, filters) => {
  87. const path$1 = directoryPath || ".";
  88. if (filters.every((filter) => filter(path$1, true))) paths.push(path$1);
  89. };
  90. const empty$2 = () => {};
  91. function build$6(root, options) {
  92. const { includeDirs, filters, relativePaths } = options;
  93. if (!includeDirs) return empty$2;
  94. if (relativePaths) return filters && filters.length ? pushDirectoryFilterWithRelativePath(root) : pushDirectoryWithRelativePath(root);
  95. return filters && filters.length ? pushDirectoryFilter : pushDirectory;
  96. }
  97. //#endregion
  98. //#region src/api/functions/push-file.ts
  99. const pushFileFilterAndCount = (filename, _paths, counts, filters) => {
  100. if (filters.every((filter) => filter(filename, false))) counts.files++;
  101. };
  102. const pushFileFilter = (filename, paths, _counts, filters) => {
  103. if (filters.every((filter) => filter(filename, false))) paths.push(filename);
  104. };
  105. const pushFileCount = (_filename, _paths, counts, _filters) => {
  106. counts.files++;
  107. };
  108. const pushFile = (filename, paths) => {
  109. paths.push(filename);
  110. };
  111. const empty$1 = () => {};
  112. function build$5(options) {
  113. const { excludeFiles, filters, onlyCounts } = options;
  114. if (excludeFiles) return empty$1;
  115. if (filters && filters.length) return onlyCounts ? pushFileFilterAndCount : pushFileFilter;
  116. else if (onlyCounts) return pushFileCount;
  117. else return pushFile;
  118. }
  119. //#endregion
  120. //#region src/api/functions/get-array.ts
  121. const getArray = (paths) => {
  122. return paths;
  123. };
  124. const getArrayGroup = () => {
  125. return [""].slice(0, 0);
  126. };
  127. function build$4(options) {
  128. return options.group ? getArrayGroup : getArray;
  129. }
  130. //#endregion
  131. //#region src/api/functions/group-files.ts
  132. const groupFiles = (groups, directory, files) => {
  133. groups.push({
  134. directory,
  135. files,
  136. dir: directory
  137. });
  138. };
  139. const empty = () => {};
  140. function build$3(options) {
  141. return options.group ? groupFiles : empty;
  142. }
  143. //#endregion
  144. //#region src/api/functions/resolve-symlink.ts
  145. const resolveSymlinksAsync = function(path$1, state, callback$1) {
  146. const { queue, options: { suppressErrors } } = state;
  147. queue.enqueue();
  148. fs.default.realpath(path$1, (error, resolvedPath) => {
  149. if (error) return queue.dequeue(suppressErrors ? null : error, state);
  150. fs.default.stat(resolvedPath, (error$1, stat) => {
  151. if (error$1) return queue.dequeue(suppressErrors ? null : error$1, state);
  152. if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return queue.dequeue(null, state);
  153. callback$1(stat, resolvedPath);
  154. queue.dequeue(null, state);
  155. });
  156. });
  157. };
  158. const resolveSymlinks = function(path$1, state, callback$1) {
  159. const { queue, options: { suppressErrors } } = state;
  160. queue.enqueue();
  161. try {
  162. const resolvedPath = fs.default.realpathSync(path$1);
  163. const stat = fs.default.statSync(resolvedPath);
  164. if (stat.isDirectory() && isRecursive(path$1, resolvedPath, state)) return;
  165. callback$1(stat, resolvedPath);
  166. } catch (e) {
  167. if (!suppressErrors) throw e;
  168. }
  169. };
  170. function build$2(options, isSynchronous) {
  171. if (!options.resolveSymlinks || options.excludeSymlinks) return null;
  172. return isSynchronous ? resolveSymlinks : resolveSymlinksAsync;
  173. }
  174. function isRecursive(path$1, resolved, state) {
  175. if (state.options.useRealPaths) return isRecursiveUsingRealPaths(resolved, state);
  176. let parent = (0, path.dirname)(path$1);
  177. let depth = 1;
  178. while (parent !== state.root && depth < 2) {
  179. const resolvedPath = state.symlinks.get(parent);
  180. const isSameRoot = !!resolvedPath && (resolvedPath === resolved || resolvedPath.startsWith(resolved) || resolved.startsWith(resolvedPath));
  181. if (isSameRoot) depth++;
  182. else parent = (0, path.dirname)(parent);
  183. }
  184. state.symlinks.set(path$1, resolved);
  185. return depth > 1;
  186. }
  187. function isRecursiveUsingRealPaths(resolved, state) {
  188. return state.visited.includes(resolved + state.options.pathSeparator);
  189. }
  190. //#endregion
  191. //#region src/api/functions/invoke-callback.ts
  192. const onlyCountsSync = (state) => {
  193. return state.counts;
  194. };
  195. const groupsSync = (state) => {
  196. return state.groups;
  197. };
  198. const defaultSync = (state) => {
  199. return state.paths;
  200. };
  201. const limitFilesSync = (state) => {
  202. return state.paths.slice(0, state.options.maxFiles);
  203. };
  204. const onlyCountsAsync = (state, error, callback$1) => {
  205. report(error, callback$1, state.counts, state.options.suppressErrors);
  206. return null;
  207. };
  208. const defaultAsync = (state, error, callback$1) => {
  209. report(error, callback$1, state.paths, state.options.suppressErrors);
  210. return null;
  211. };
  212. const limitFilesAsync = (state, error, callback$1) => {
  213. report(error, callback$1, state.paths.slice(0, state.options.maxFiles), state.options.suppressErrors);
  214. return null;
  215. };
  216. const groupsAsync = (state, error, callback$1) => {
  217. report(error, callback$1, state.groups, state.options.suppressErrors);
  218. return null;
  219. };
  220. function report(error, callback$1, output, suppressErrors) {
  221. if (error && !suppressErrors) callback$1(error, output);
  222. else callback$1(null, output);
  223. }
  224. function build$1(options, isSynchronous) {
  225. const { onlyCounts, group, maxFiles } = options;
  226. if (onlyCounts) return isSynchronous ? onlyCountsSync : onlyCountsAsync;
  227. else if (group) return isSynchronous ? groupsSync : groupsAsync;
  228. else if (maxFiles) return isSynchronous ? limitFilesSync : limitFilesAsync;
  229. else return isSynchronous ? defaultSync : defaultAsync;
  230. }
  231. //#endregion
  232. //#region src/api/functions/walk-directory.ts
  233. const readdirOpts = { withFileTypes: true };
  234. const walkAsync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
  235. state.queue.enqueue();
  236. if (currentDepth <= 0) return state.queue.dequeue(null, state);
  237. state.visited.push(crawlPath);
  238. state.counts.directories++;
  239. fs.default.readdir(crawlPath || ".", readdirOpts, (error, entries = []) => {
  240. callback$1(entries, directoryPath, currentDepth);
  241. state.queue.dequeue(state.options.suppressErrors ? null : error, state);
  242. });
  243. };
  244. const walkSync = (state, crawlPath, directoryPath, currentDepth, callback$1) => {
  245. if (currentDepth <= 0) return;
  246. state.visited.push(crawlPath);
  247. state.counts.directories++;
  248. let entries = [];
  249. try {
  250. entries = fs.default.readdirSync(crawlPath || ".", readdirOpts);
  251. } catch (e) {
  252. if (!state.options.suppressErrors) throw e;
  253. }
  254. callback$1(entries, directoryPath, currentDepth);
  255. };
  256. function build(isSynchronous) {
  257. return isSynchronous ? walkSync : walkAsync;
  258. }
  259. //#endregion
  260. //#region src/api/queue.ts
  261. /**
  262. * This is a custom stateless queue to track concurrent async fs calls.
  263. * It increments a counter whenever a call is queued and decrements it
  264. * as soon as it completes. When the counter hits 0, it calls onQueueEmpty.
  265. */
  266. var Queue = class {
  267. count = 0;
  268. constructor(onQueueEmpty) {
  269. this.onQueueEmpty = onQueueEmpty;
  270. }
  271. enqueue() {
  272. this.count++;
  273. return this.count;
  274. }
  275. dequeue(error, output) {
  276. if (this.onQueueEmpty && (--this.count <= 0 || error)) {
  277. this.onQueueEmpty(error, output);
  278. if (error) {
  279. output.controller.abort();
  280. this.onQueueEmpty = void 0;
  281. }
  282. }
  283. }
  284. };
  285. //#endregion
  286. //#region src/api/counter.ts
  287. var Counter = class {
  288. _files = 0;
  289. _directories = 0;
  290. set files(num) {
  291. this._files = num;
  292. }
  293. get files() {
  294. return this._files;
  295. }
  296. set directories(num) {
  297. this._directories = num;
  298. }
  299. get directories() {
  300. return this._directories;
  301. }
  302. /**
  303. * @deprecated use `directories` instead
  304. */
  305. /* c8 ignore next 3 */
  306. get dirs() {
  307. return this._directories;
  308. }
  309. };
  310. //#endregion
  311. //#region src/api/walker.ts
  312. var Walker = class {
  313. root;
  314. isSynchronous;
  315. state;
  316. joinPath;
  317. pushDirectory;
  318. pushFile;
  319. getArray;
  320. groupFiles;
  321. resolveSymlink;
  322. walkDirectory;
  323. callbackInvoker;
  324. constructor(root, options, callback$1) {
  325. this.isSynchronous = !callback$1;
  326. this.callbackInvoker = build$1(options, this.isSynchronous);
  327. this.root = normalizePath(root, options);
  328. this.state = {
  329. root: isRootDirectory(this.root) ? this.root : this.root.slice(0, -1),
  330. paths: [""].slice(0, 0),
  331. groups: [],
  332. counts: new Counter(),
  333. options,
  334. queue: new Queue((error, state) => this.callbackInvoker(state, error, callback$1)),
  335. symlinks: /* @__PURE__ */ new Map(),
  336. visited: [""].slice(0, 0),
  337. controller: new AbortController()
  338. };
  339. this.joinPath = build$7(this.root, options);
  340. this.pushDirectory = build$6(this.root, options);
  341. this.pushFile = build$5(options);
  342. this.getArray = build$4(options);
  343. this.groupFiles = build$3(options);
  344. this.resolveSymlink = build$2(options, this.isSynchronous);
  345. this.walkDirectory = build(this.isSynchronous);
  346. }
  347. start() {
  348. this.pushDirectory(this.root, this.state.paths, this.state.options.filters);
  349. this.walkDirectory(this.state, this.root, this.root, this.state.options.maxDepth, this.walk);
  350. return this.isSynchronous ? this.callbackInvoker(this.state, null) : null;
  351. }
  352. walk = (entries, directoryPath, depth) => {
  353. const { paths, options: { filters, resolveSymlinks: resolveSymlinks$1, excludeSymlinks, exclude, maxFiles, signal, useRealPaths, pathSeparator }, controller } = this.state;
  354. if (controller.signal.aborted || signal && signal.aborted || maxFiles && paths.length > maxFiles) return;
  355. const files = this.getArray(this.state.paths);
  356. for (let i = 0; i < entries.length; ++i) {
  357. const entry = entries[i];
  358. if (entry.isFile() || entry.isSymbolicLink() && !resolveSymlinks$1 && !excludeSymlinks) {
  359. const filename = this.joinPath(entry.name, directoryPath);
  360. this.pushFile(filename, files, this.state.counts, filters);
  361. } else if (entry.isDirectory()) {
  362. let path$1 = joinDirectoryPath(entry.name, directoryPath, this.state.options.pathSeparator);
  363. if (exclude && exclude(entry.name, path$1)) continue;
  364. this.pushDirectory(path$1, paths, filters);
  365. this.walkDirectory(this.state, path$1, path$1, depth - 1, this.walk);
  366. } else if (this.resolveSymlink && entry.isSymbolicLink()) {
  367. let path$1 = joinPathWithBasePath(entry.name, directoryPath);
  368. this.resolveSymlink(path$1, this.state, (stat, resolvedPath) => {
  369. if (stat.isDirectory()) {
  370. resolvedPath = normalizePath(resolvedPath, this.state.options);
  371. if (exclude && exclude(entry.name, useRealPaths ? resolvedPath : path$1 + pathSeparator)) return;
  372. this.walkDirectory(this.state, resolvedPath, useRealPaths ? resolvedPath : path$1 + pathSeparator, depth - 1, this.walk);
  373. } else {
  374. resolvedPath = useRealPaths ? resolvedPath : path$1;
  375. const filename = (0, path.basename)(resolvedPath);
  376. const directoryPath$1 = normalizePath((0, path.dirname)(resolvedPath), this.state.options);
  377. resolvedPath = this.joinPath(filename, directoryPath$1);
  378. this.pushFile(resolvedPath, files, this.state.counts, filters);
  379. }
  380. });
  381. }
  382. }
  383. this.groupFiles(this.state.groups, directoryPath, files);
  384. };
  385. };
  386. //#endregion
  387. //#region src/api/async.ts
  388. function promise(root, options) {
  389. return new Promise((resolve$1, reject) => {
  390. callback(root, options, (err, output) => {
  391. if (err) return reject(err);
  392. resolve$1(output);
  393. });
  394. });
  395. }
  396. function callback(root, options, callback$1) {
  397. let walker = new Walker(root, options, callback$1);
  398. walker.start();
  399. }
  400. //#endregion
  401. //#region src/api/sync.ts
  402. function sync(root, options) {
  403. const walker = new Walker(root, options);
  404. return walker.start();
  405. }
  406. //#endregion
  407. //#region src/builder/api-builder.ts
  408. var APIBuilder = class {
  409. constructor(root, options) {
  410. this.root = root;
  411. this.options = options;
  412. }
  413. withPromise() {
  414. return promise(this.root, this.options);
  415. }
  416. withCallback(cb) {
  417. callback(this.root, this.options, cb);
  418. }
  419. sync() {
  420. return sync(this.root, this.options);
  421. }
  422. };
  423. //#endregion
  424. //#region src/builder/index.ts
  425. var pm = null;
  426. /* c8 ignore next 6 */
  427. try {
  428. require.resolve("picomatch");
  429. pm = require("picomatch");
  430. } catch (_e) {}
  431. var Builder = class {
  432. globCache = {};
  433. options = {
  434. maxDepth: Infinity,
  435. suppressErrors: true,
  436. pathSeparator: path.sep,
  437. filters: []
  438. };
  439. globFunction;
  440. constructor(options) {
  441. this.options = {
  442. ...this.options,
  443. ...options
  444. };
  445. this.globFunction = this.options.globFunction;
  446. }
  447. group() {
  448. this.options.group = true;
  449. return this;
  450. }
  451. withPathSeparator(separator) {
  452. this.options.pathSeparator = separator;
  453. return this;
  454. }
  455. withBasePath() {
  456. this.options.includeBasePath = true;
  457. return this;
  458. }
  459. withRelativePaths() {
  460. this.options.relativePaths = true;
  461. return this;
  462. }
  463. withDirs() {
  464. this.options.includeDirs = true;
  465. return this;
  466. }
  467. withMaxDepth(depth) {
  468. this.options.maxDepth = depth;
  469. return this;
  470. }
  471. withMaxFiles(limit) {
  472. this.options.maxFiles = limit;
  473. return this;
  474. }
  475. withFullPaths() {
  476. this.options.resolvePaths = true;
  477. this.options.includeBasePath = true;
  478. return this;
  479. }
  480. withErrors() {
  481. this.options.suppressErrors = false;
  482. return this;
  483. }
  484. withSymlinks({ resolvePaths = true } = {}) {
  485. this.options.resolveSymlinks = true;
  486. this.options.useRealPaths = resolvePaths;
  487. return this.withFullPaths();
  488. }
  489. withAbortSignal(signal) {
  490. this.options.signal = signal;
  491. return this;
  492. }
  493. normalize() {
  494. this.options.normalizePath = true;
  495. return this;
  496. }
  497. filter(predicate) {
  498. this.options.filters.push(predicate);
  499. return this;
  500. }
  501. onlyDirs() {
  502. this.options.excludeFiles = true;
  503. this.options.includeDirs = true;
  504. return this;
  505. }
  506. exclude(predicate) {
  507. this.options.exclude = predicate;
  508. return this;
  509. }
  510. onlyCounts() {
  511. this.options.onlyCounts = true;
  512. return this;
  513. }
  514. crawl(root) {
  515. return new APIBuilder(root || ".", this.options);
  516. }
  517. withGlobFunction(fn) {
  518. this.globFunction = fn;
  519. return this;
  520. }
  521. /**
  522. * @deprecated Pass options using the constructor instead:
  523. * ```ts
  524. * new fdir(options).crawl("/path/to/root");
  525. * ```
  526. * This method will be removed in v7.0
  527. */
  528. /* c8 ignore next 4 */
  529. crawlWithOptions(root, options) {
  530. this.options = {
  531. ...this.options,
  532. ...options
  533. };
  534. return new APIBuilder(root || ".", this.options);
  535. }
  536. glob(...patterns) {
  537. if (this.globFunction) return this.globWithOptions(patterns);
  538. return this.globWithOptions(patterns, ...[{ dot: true }]);
  539. }
  540. globWithOptions(patterns, ...options) {
  541. const globFn = this.globFunction || pm;
  542. /* c8 ignore next 5 */
  543. if (!globFn) throw new Error("Please specify a glob function to use glob matching.");
  544. var isMatch = this.globCache[patterns.join("\0")];
  545. if (!isMatch) {
  546. isMatch = globFn(patterns, ...options);
  547. this.globCache[patterns.join("\0")] = isMatch;
  548. }
  549. this.options.filters.push((path$1) => isMatch(path$1));
  550. return this;
  551. }
  552. };
  553. //#endregion
  554. exports.fdir = Builder;