1
0

pathTemplate.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. "use strict";
  2. /**
  3. * Copyright 2020 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. Object.defineProperty(exports, "__esModule", { value: true });
  18. exports.PathTemplate = void 0;
  19. class PathTemplate {
  20. /**
  21. * @param {String} data the of the template
  22. *
  23. * @constructor
  24. */
  25. constructor(data) {
  26. this.bindings = {};
  27. this.data = data;
  28. this.segments = this.parsePathTemplate(data);
  29. this.size = this.segments.length;
  30. }
  31. /**
  32. * Matches a fully-qualified path template string.
  33. *
  34. * @param {String} path a fully-qualified path template string
  35. * @return {Object} contains const names matched to binding values
  36. * @throws {TypeError} if path can't be matched to this template
  37. */
  38. match(path) {
  39. let pathSegments = path.split('/');
  40. const bindings = {};
  41. if (pathSegments.length !== this.segments.length) {
  42. // if the path contains a wildcard, then the length may differ by 1.
  43. if (!this.data.includes('**')) {
  44. throw new TypeError(`This path ${path} does not match path template ${this.data}, the number of parameters is not same.`);
  45. }
  46. else if (pathSegments.length !== this.segments.length + 1) {
  47. throw new TypeError(`This path ${path} does not match path template ${this.data}, the number of parameters is not same with one wildcard.`);
  48. }
  49. }
  50. for (let index = 0; index < this.segments.length && pathSegments.length > 0; index++) {
  51. if (this.segments[index] !== pathSegments[0]) {
  52. if (!this.segments[index].includes('*')) {
  53. throw new TypeError(`segment does not match, ${this.segments[index]} and ${pathSegments[index]}.`);
  54. }
  55. else {
  56. let segment = this.segments[index];
  57. const matches = segment.match(/\{[$0-9a-zA-Z_]+=.*?\}/g);
  58. if (!matches) {
  59. throw new Error(`Error processing path template segment ${segment}`);
  60. }
  61. const variables = matches.map(str => str.replace(/^\{/, '').replace(/=.*/, ''));
  62. if (segment.includes('**')) {
  63. bindings[variables[0]] = pathSegments[0] + '/' + pathSegments[1];
  64. pathSegments = pathSegments.slice(2);
  65. }
  66. else {
  67. // atomic resource
  68. if (variables.length === 1) {
  69. bindings[variables[0]] = pathSegments[0];
  70. }
  71. else {
  72. // non-slash resource
  73. // segment: {blurb_id=*}.{legacy_user=*} to match pathSegments: ['bar.user2']
  74. // split the match pathSegments[0] -> value: ['bar', 'user2']
  75. // compare the length of two arrays, and compare array items
  76. const value = pathSegments[0].split(/[-_.~]/);
  77. if (value.length !== variables.length) {
  78. throw new Error(`segment ${segment} does not match ${pathSegments[0]}`);
  79. }
  80. for (const v of variables) {
  81. bindings[v] = value[0];
  82. segment = segment.replace(`{${v}=*}`, `${value[0]}`);
  83. value.shift();
  84. }
  85. // segment: {blurb_id=*}.{legacy_user=*} matching pathSegments: ['bar~user2'] should fail
  86. if (segment !== pathSegments[0]) {
  87. throw new TypeError(`non slash resource pattern ${this.segments[index]} and ${pathSegments[0]} should have same separator`);
  88. }
  89. }
  90. pathSegments.shift();
  91. }
  92. }
  93. }
  94. else {
  95. pathSegments.shift();
  96. }
  97. }
  98. return bindings;
  99. }
  100. /**
  101. * Renders a path template using the provided bindings.
  102. *
  103. * @param {Object} bindings a mapping of const names to binding strings
  104. * @return {String} a rendered representation of the path template
  105. * @throws {TypeError} if a key is missing, or if a sub-template cannot be
  106. * parsed
  107. */
  108. render(bindings) {
  109. if (Object.keys(bindings).length !== Object.keys(this.bindings).length) {
  110. throw new TypeError(`The number of variables ${Object.keys(bindings).length} does not match the number of needed variables ${Object.keys(this.bindings).length}`);
  111. }
  112. let path = this.inspect();
  113. for (const key of Object.keys(bindings)) {
  114. const b = bindings[key].toString();
  115. if (!this.bindings[key]) {
  116. throw new TypeError(`render fails for not matching ${bindings[key]}`);
  117. }
  118. const variable = this.bindings[key];
  119. if (variable === '*') {
  120. if (!b.match(/[^/{}]+/)) {
  121. throw new TypeError(`render fails for not matching ${b}`);
  122. }
  123. path = path.replace(`{${key}=*}`, `${b}`);
  124. }
  125. else if (variable === '**') {
  126. if (!b.match(/[^{}]+/)) {
  127. throw new TypeError(`render fails for not matching ${b}`);
  128. }
  129. path = path.replace(`{${key}=**}`, `${b}`);
  130. }
  131. }
  132. return path;
  133. }
  134. /**
  135. * Renders the path template.
  136. *
  137. * @return {string} contains const names matched to binding values
  138. */
  139. inspect() {
  140. return this.segments.join('/');
  141. }
  142. /**
  143. * Parse the path template.
  144. *
  145. * @return {string[]} return segments of the input path.
  146. * For example: 'buckets/{hello}'' will give back ['buckets', {hello=*}]
  147. */
  148. parsePathTemplate(data) {
  149. const pathSegments = splitPathTemplate(data);
  150. let index = 0;
  151. let wildCardCount = 0;
  152. const segments = [];
  153. let matches;
  154. pathSegments.forEach(segment => {
  155. // * or ** -> segments.push('{$0=*}');
  156. // -> bindings['$0'] = '*'
  157. if (segment === '*' || segment === '**') {
  158. this.bindings[`$${index}`] = segment;
  159. segments.push(`{$${index}=${segment}}`);
  160. index = index + 1;
  161. if (segment === '**') {
  162. ++wildCardCount;
  163. }
  164. }
  165. else if ((matches = segment.match(/\{[0-9a-zA-Z-.~_]+(?:=.*?)?\}/g))) {
  166. for (const subsegment of matches) {
  167. const pairMatch = subsegment.match(/^\{([0-9a-zA-Z-.~_]+)(?:=(.*?))?\}$/);
  168. if (!pairMatch) {
  169. throw new Error(`Cannot process path template segment ${subsegment}`);
  170. }
  171. const key = pairMatch[1];
  172. let value = pairMatch[2];
  173. if (!value) {
  174. value = '*';
  175. segment = segment.replace(key, key + '=*');
  176. this.bindings[key] = value;
  177. }
  178. else if (value === '*') {
  179. this.bindings[key] = value;
  180. }
  181. else if (value === '**') {
  182. ++wildCardCount;
  183. this.bindings[key] = value;
  184. }
  185. }
  186. segments.push(segment);
  187. }
  188. else if (segment.match(/[0-9a-zA-Z-.~_]+/)) {
  189. segments.push(segment);
  190. }
  191. });
  192. if (wildCardCount > 1) {
  193. throw new TypeError('Can not have more than one wildcard.');
  194. }
  195. return segments;
  196. }
  197. }
  198. exports.PathTemplate = PathTemplate;
  199. /**
  200. * Split the path template by `/`.
  201. * It can not be simply splitted by `/` because there might be `/` in the segments.
  202. * For example: 'a/b/{a=hello/world}' we do not want to break the brackets pair
  203. * so above path will be splitted as ['a', 'b', '{a=hello/world}']
  204. */
  205. function splitPathTemplate(data) {
  206. let left = 0;
  207. let right = 0;
  208. let bracketCount = 0;
  209. const segments = [];
  210. while (right >= left && right < data.length) {
  211. if (data.charAt(right) === '{') {
  212. bracketCount = bracketCount + 1;
  213. }
  214. else if (data.charAt(right) === '}') {
  215. bracketCount = bracketCount - 1;
  216. }
  217. else if (data.charAt(right) === '/') {
  218. if (right === data.length - 1) {
  219. throw new TypeError('Invalid path, it can not be ended by /');
  220. }
  221. if (bracketCount === 0) {
  222. // complete bracket, to avoid the case a/b/**/*/{a=hello/world}
  223. segments.push(data.substring(left, right));
  224. left = right + 1;
  225. }
  226. }
  227. if (right === data.length - 1) {
  228. if (bracketCount !== 0) {
  229. throw new TypeError('Brackets are invalid.');
  230. }
  231. segments.push(data.substring(left));
  232. }
  233. right = right + 1;
  234. }
  235. return segments;
  236. }
  237. //# sourceMappingURL=pathTemplate.js.map