gulp-sanitize-translations.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var through = require('through2');
  2. var gutil = require('gulp-util');
  3. var PluginError = gutil.PluginError;
  4. var sanitize = require('sanitize-html');
  5. const PLUGIN_NAME = 'gulp-sanitize-translations.js';
  6. module.exports = function(options) {
  7. // Creating a stream through which each file will pass
  8. var stream = through.obj(function(file, enc, callback) {
  9. if (file.isBuffer()) {
  10. var content = file.contents.toString();
  11. var parsed = JSON.parse(content);
  12. var lang = Object.keys(parsed)[0];
  13. for (var i in parsed[lang]) {
  14. if (Array.isArray(parsed[lang][i])) {
  15. for (var n in parsed[lang][i]) {
  16. parsed[lang][i][n] = sanitize(parsed[lang][i][n]);
  17. }
  18. } else {
  19. parsed[lang][i] = sanitize(parsed[lang][i]);
  20. }
  21. }
  22. file.contents = new Buffer(JSON.stringify(parsed), 'utf-8');
  23. } else if (file.isStream()) {
  24. // Streams not supported.
  25. this.emit(
  26. 'error',
  27. new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported.')
  28. );
  29. return callback();
  30. }
  31. // Anything else just falls through.
  32. this.push(file);
  33. return callback();
  34. });
  35. // returning the file stream
  36. return stream;
  37. };