use.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. var utils = require('../utils')
  2. , path = require('path');
  3. /**
  4. * Use the given `plugin`
  5. *
  6. * Examples:
  7. *
  8. * use("plugins/add.js")
  9. *
  10. * width add(10, 100)
  11. * // => width: 110
  12. */
  13. module.exports = function use(plugin, options){
  14. utils.assertString(plugin, 'plugin');
  15. if (options) {
  16. utils.assertType(options, 'object', 'options');
  17. options = parseObject(options);
  18. }
  19. // lookup
  20. plugin = plugin.string;
  21. var found = utils.lookup(plugin, this.options.paths, this.options.filename);
  22. if (!found) throw new Error('failed to locate plugin file "' + plugin + '"');
  23. // use
  24. var fn = require(path.resolve(found));
  25. if ('function' != typeof fn) {
  26. throw new Error('plugin "' + plugin + '" does not export a function');
  27. }
  28. this.renderer.use(fn(options || this.options));
  29. };
  30. /**
  31. * Attempt to parse object node to the javascript object.
  32. *
  33. * @param {Object} obj
  34. * @return {Object}
  35. * @api private
  36. */
  37. function parseObject(obj){
  38. obj = obj.vals;
  39. for (var key in obj) {
  40. var nodes = obj[key].nodes[0].nodes;
  41. if (nodes && nodes.length) {
  42. obj[key] = [];
  43. for (var i = 0, len = nodes.length; i < len; ++i) {
  44. obj[key].push(convert(nodes[i]));
  45. }
  46. } else {
  47. obj[key] = convert(obj[key].first);
  48. }
  49. }
  50. return obj;
  51. function convert(node){
  52. switch (node.nodeName) {
  53. case 'object':
  54. return parseObject(node);
  55. case 'boolean':
  56. return node.isTrue;
  57. case 'unit':
  58. return node.type ? node.toString() : +node.val;
  59. case 'string':
  60. case 'literal':
  61. return node.val;
  62. default:
  63. return node.toString();
  64. }
  65. }
  66. }