plugin.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. 'use strict';
  2. var Errors = require('./errors');
  3. var Plugin = function Plugin(methods) {
  4. for (var method in methods) {
  5. this[method] = typeof method === 'function' ? methods[method].bind(this) : methods[method];
  6. }
  7. this.validate();
  8. };
  9. Plugin.prototype = Object.defineProperties({
  10. /**
  11. * Plugin's name.
  12. * @type {String}
  13. */
  14. name: null,
  15. /**
  16. * List of supported syntaxes.
  17. * @type {Array}
  18. */
  19. syntax: null,
  20. /**
  21. * @type {Object}
  22. */
  23. accepts: null,
  24. /**
  25. * @type {Function}
  26. */
  27. process: null,
  28. /**
  29. * @type {Function}
  30. */
  31. lint: null,
  32. value_: null,
  33. validate: function validate() {
  34. if (typeof this.name !== 'string' || !this.name) throw new Error(Errors.missingName());
  35. if (!Array.isArray(this.syntax) || this.syntax.length === 0) throw new Error(Errors.missingSyntax());
  36. if (typeof this.accepts !== 'object' && typeof this.setValue !== 'function') throw new Error(Errors.missingSetValue());
  37. }
  38. }, {
  39. value: {
  40. get: function get() {
  41. return this.value_;
  42. },
  43. set: function set(value) {
  44. var valueType = typeof value;
  45. var pattern = this.accepts && this.accepts[valueType];
  46. if (this.setValue) {
  47. this.value_ = this.setValue(value);
  48. return this.value_;
  49. }
  50. if (!pattern) throw new Error(Errors.unacceptableValueType(valueType, this.accepts));
  51. if (valueType === 'boolean') {
  52. if (pattern.indexOf(value) < 0) throw new Error(Errors.unacceptableBoolean(pattern));
  53. this.value_ = value;
  54. return this.value_;
  55. }
  56. if (valueType === 'number') {
  57. if (value !== parseInt(value)) throw new Error(Errors.unacceptableNumber());
  58. this.value_ = new Array(value + 1).join(' ');
  59. return this.value_;
  60. }
  61. if (valueType = 'string') {
  62. if (!value.match(pattern)) throw new Error(Errors.unacceptableString(pattern));
  63. this.value_ = value;
  64. return this.value_;
  65. }
  66. throw new Error(Errors.implementSetValue(valueType));
  67. },
  68. configurable: true,
  69. enumerable: true
  70. }
  71. });
  72. module.exports = Plugin;