namespace.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. const ROOT_NAMESPACE_NAME = '__rootNamespace__';
  2. class Namespace {
  3. constructor(name, parentNamespace) {
  4. this.name = name;
  5. this.parentNamespace = parentNamespace;
  6. this.childNamespaces = {};
  7. this.tasks = {};
  8. this.rules = {};
  9. this.path = this.getPath();
  10. }
  11. get fullName() {
  12. return this._getFullName();
  13. }
  14. addTask(task) {
  15. this.tasks[task.name] = task;
  16. task.namespace = this;
  17. }
  18. resolveTask(name) {
  19. if (!name) {
  20. return;
  21. }
  22. let taskPath = name.split(':');
  23. let taskName = taskPath.pop();
  24. let task;
  25. let ns;
  26. // Namespaced, return either relative to current, or from root
  27. if (taskPath.length) {
  28. taskPath = taskPath.join(':');
  29. ns = this.resolveNamespace(taskPath) ||
  30. Namespace.ROOT_NAMESPACE.resolveNamespace(taskPath);
  31. task = (ns && ns.resolveTask(taskName));
  32. }
  33. // Bare task, return either local, or top-level
  34. else {
  35. task = this.tasks[name] || Namespace.ROOT_NAMESPACE.tasks[name];
  36. }
  37. return task || null;
  38. }
  39. resolveNamespace(relativeName) {
  40. if (!relativeName) {
  41. return this;
  42. }
  43. let parts = relativeName.split(':');
  44. let ns = this;
  45. for (let i = 0, ii = parts.length; (ns && i < ii); i++) {
  46. ns = ns.childNamespaces[parts[i]];
  47. }
  48. return ns || null;
  49. }
  50. matchRule(relativeName) {
  51. let parts = relativeName.split(':');
  52. parts.pop();
  53. let ns = this.resolveNamespace(parts.join(':'));
  54. let rules = ns ? ns.rules : [];
  55. let r;
  56. let match;
  57. for (let p in rules) {
  58. r = rules[p];
  59. if (r.match(relativeName)) {
  60. match = r;
  61. }
  62. }
  63. return (ns && match) ||
  64. (this.parentNamespace &&
  65. this.parentNamespace.matchRule(relativeName));
  66. }
  67. getPath() {
  68. let parts = [];
  69. let next = this.parentNamespace;
  70. while (next) {
  71. parts.push(next.name);
  72. next = next.parentNamespace;
  73. }
  74. parts.pop(); // Remove '__rootNamespace__'
  75. return parts.reverse().join(':');
  76. }
  77. _getFullName() {
  78. let path = this.path;
  79. path = (path && path.split(':')) || [];
  80. path.push(this.name);
  81. return path.join(':');
  82. }
  83. isRootNamespace() {
  84. return !this.parentNamespace;
  85. }
  86. }
  87. class RootNamespace extends Namespace {
  88. constructor() {
  89. super(ROOT_NAMESPACE_NAME, null);
  90. Namespace.ROOT_NAMESPACE = this;
  91. }
  92. }
  93. module.exports.Namespace = Namespace;
  94. module.exports.RootNamespace = RootNamespace;