You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. const trimRepeated = require('trim-repeated');
  3. const filenameReservedRegex = require('filename-reserved-regex');
  4. const stripOuter = require('strip-outer');
  5. // Doesn't make sense to have longer filenames
  6. const MAX_FILENAME_LENGTH = 100;
  7. const reControlChars = /[\u0000-\u001f\u0080-\u009f]/g; // eslint-disable-line no-control-regex
  8. const reRelativePath = /^\.+/;
  9. const reTrailingPeriods = /\.+$/;
  10. const filenamify = (string, options = {}) => {
  11. if (typeof string !== 'string') {
  12. throw new TypeError('Expected a string');
  13. }
  14. const replacement = options.replacement === undefined ? '!' : options.replacement;
  15. if (filenameReservedRegex().test(replacement) && reControlChars.test(replacement)) {
  16. throw new Error('Replacement string cannot contain reserved filename characters');
  17. }
  18. string = string.replace(filenameReservedRegex(), replacement);
  19. string = string.replace(reControlChars, replacement);
  20. string = string.replace(reRelativePath, replacement);
  21. string = string.replace(reTrailingPeriods, '');
  22. if (replacement.length > 0) {
  23. string = trimRepeated(string, replacement);
  24. string = string.length > 1 ? stripOuter(string, replacement) : string;
  25. }
  26. string = filenameReservedRegex.windowsNames().test(string) ? string + replacement : string;
  27. string = string.slice(0, typeof options.maxLength === 'number' ? options.maxLength : MAX_FILENAME_LENGTH);
  28. return string;
  29. };
  30. module.exports = filenamify;