engines.js 1023 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. const yaml = require('js-yaml');
  3. /**
  4. * Default engines
  5. */
  6. const engines = exports = module.exports;
  7. /**
  8. * YAML
  9. */
  10. engines.yaml = {
  11. parse: yaml.safeLoad.bind(yaml),
  12. stringify: yaml.safeDump.bind(yaml)
  13. };
  14. /**
  15. * JSON
  16. */
  17. engines.json = {
  18. parse: JSON.parse.bind(JSON),
  19. stringify: function(obj, options) {
  20. const opts = Object.assign({replacer: null, space: 2}, options);
  21. return JSON.stringify(obj, opts.replacer, opts.space);
  22. }
  23. };
  24. /**
  25. * JavaScript
  26. */
  27. engines.javascript = {
  28. parse: function parse(str, options, wrap) {
  29. /* eslint no-eval: 0 */
  30. try {
  31. if (wrap !== false) {
  32. str = '(function() {\nreturn ' + str.trim() + ';\n}());';
  33. }
  34. return eval(str) || {};
  35. } catch (err) {
  36. if (wrap !== false && /(unexpected|identifier)/i.test(err.message)) {
  37. return parse(str, options, false);
  38. }
  39. throw new SyntaxError(err);
  40. }
  41. },
  42. stringify: function() {
  43. throw new Error('stringifying JavaScript is not supported');
  44. }
  45. };