utils.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.jsonStringifyReplacerSortKeys = void 0;
  6. exports.parseFiles = parseFiles;
  7. exports.parseFoldersToGlobs = parseFoldersToGlobs;
  8. var _path = require("path");
  9. var _fs = require("fs");
  10. var _normalizePath = _interopRequireDefault(require("normalize-path"));
  11. var _arrify = _interopRequireDefault(require("arrify"));
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. // @ts-ignore
  14. // @ts-ignore
  15. /**
  16. * @param {string|(string|undefined)[]} files
  17. * @param {string} context
  18. * @returns {string[]}
  19. */
  20. function parseFiles(files, context) {
  21. return (0, _arrify.default)(files).filter((
  22. /** @type {string} */
  23. file) => typeof file === 'string').map((
  24. /** @type {string} */
  25. file) => (0, _normalizePath.default)((0, _path.resolve)(context, file)));
  26. }
  27. /**
  28. * @param {string|string[]} patterns
  29. * @param {string|string[]} extensions
  30. * @returns {string[]}
  31. */
  32. function parseFoldersToGlobs(patterns, extensions = []) {
  33. const extensionsList = (0, _arrify.default)(extensions);
  34. const [prefix, postfix] = extensionsList.length > 1 ? ['{', '}'] : ['', ''];
  35. const extensionsGlob = extensionsList.map((
  36. /** @type {string} */
  37. extension) => extension.replace(/^\./u, '')).join(',');
  38. return (0, _arrify.default)(patterns).map((
  39. /** @type {string} */
  40. pattern) => {
  41. try {
  42. // The patterns are absolute because they are prepended with the context.
  43. const stats = (0, _fs.statSync)(pattern);
  44. /* istanbul ignore else */
  45. if (stats.isDirectory()) {
  46. return pattern.replace(/[/\\]*?$/u, `/**${extensionsGlob ? `/*.${prefix + extensionsGlob + postfix}` : ''}`);
  47. }
  48. } catch (_) {// Return the pattern as is on error.
  49. }
  50. return pattern;
  51. });
  52. }
  53. /**
  54. *
  55. * @param {string} _ key, but unused
  56. * @param {any} value
  57. */
  58. const jsonStringifyReplacerSortKeys = (_, value) => {
  59. /**
  60. * @param {{ [x: string]: any; }} sorted
  61. * @param {string | number} key
  62. */
  63. const insert = (sorted, key) => {
  64. // eslint-disable-next-line no-param-reassign
  65. sorted[key] = value[key];
  66. return sorted;
  67. };
  68. return value instanceof Object && !(value instanceof Array) ? Object.keys(value).sort().reduce(insert, {}) : value;
  69. };
  70. exports.jsonStringifyReplacerSortKeys = jsonStringifyReplacerSortKeys;