index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. /**
  2. * Tokenize input string.
  3. */
  4. function lexer(str) {
  5. var tokens = [];
  6. var i = 0;
  7. while (i < str.length) {
  8. var char = str[i];
  9. if (char === "*" || char === "+" || char === "?") {
  10. tokens.push({ type: "MODIFIER", index: i, value: str[i++] });
  11. continue;
  12. }
  13. if (char === "\\") {
  14. tokens.push({ type: "ESCAPED_CHAR", index: i++, value: str[i++] });
  15. continue;
  16. }
  17. if (char === "{") {
  18. tokens.push({ type: "OPEN", index: i, value: str[i++] });
  19. continue;
  20. }
  21. if (char === "}") {
  22. tokens.push({ type: "CLOSE", index: i, value: str[i++] });
  23. continue;
  24. }
  25. if (char === ":") {
  26. var name = "";
  27. var j = i + 1;
  28. while (j < str.length) {
  29. var code = str.charCodeAt(j);
  30. if (
  31. // `0-9`
  32. (code >= 48 && code <= 57) ||
  33. // `A-Z`
  34. (code >= 65 && code <= 90) ||
  35. // `a-z`
  36. (code >= 97 && code <= 122) ||
  37. // `_`
  38. code === 95) {
  39. name += str[j++];
  40. continue;
  41. }
  42. break;
  43. }
  44. if (!name)
  45. throw new TypeError("Missing parameter name at ".concat(i));
  46. tokens.push({ type: "NAME", index: i, value: name });
  47. i = j;
  48. continue;
  49. }
  50. if (char === "(") {
  51. var count = 1;
  52. var pattern = "";
  53. var j = i + 1;
  54. if (str[j] === "?") {
  55. throw new TypeError("Pattern cannot start with \"?\" at ".concat(j));
  56. }
  57. while (j < str.length) {
  58. if (str[j] === "\\") {
  59. pattern += str[j++] + str[j++];
  60. continue;
  61. }
  62. if (str[j] === ")") {
  63. count--;
  64. if (count === 0) {
  65. j++;
  66. break;
  67. }
  68. }
  69. else if (str[j] === "(") {
  70. count++;
  71. if (str[j + 1] !== "?") {
  72. throw new TypeError("Capturing groups are not allowed at ".concat(j));
  73. }
  74. }
  75. pattern += str[j++];
  76. }
  77. if (count)
  78. throw new TypeError("Unbalanced pattern at ".concat(i));
  79. if (!pattern)
  80. throw new TypeError("Missing pattern at ".concat(i));
  81. tokens.push({ type: "PATTERN", index: i, value: pattern });
  82. i = j;
  83. continue;
  84. }
  85. tokens.push({ type: "CHAR", index: i, value: str[i++] });
  86. }
  87. tokens.push({ type: "END", index: i, value: "" });
  88. return tokens;
  89. }
  90. /**
  91. * Parse a string for the raw tokens.
  92. */
  93. export function parse(str, options) {
  94. if (options === void 0) { options = {}; }
  95. var tokens = lexer(str);
  96. var _a = options.prefixes, prefixes = _a === void 0 ? "./" : _a;
  97. var defaultPattern = "[^".concat(escapeString(options.delimiter || "/#?"), "]+?");
  98. var result = [];
  99. var key = 0;
  100. var i = 0;
  101. var path = "";
  102. var tryConsume = function (type) {
  103. if (i < tokens.length && tokens[i].type === type)
  104. return tokens[i++].value;
  105. };
  106. var mustConsume = function (type) {
  107. var value = tryConsume(type);
  108. if (value !== undefined)
  109. return value;
  110. var _a = tokens[i], nextType = _a.type, index = _a.index;
  111. throw new TypeError("Unexpected ".concat(nextType, " at ").concat(index, ", expected ").concat(type));
  112. };
  113. var consumeText = function () {
  114. var result = "";
  115. var value;
  116. while ((value = tryConsume("CHAR") || tryConsume("ESCAPED_CHAR"))) {
  117. result += value;
  118. }
  119. return result;
  120. };
  121. while (i < tokens.length) {
  122. var char = tryConsume("CHAR");
  123. var name = tryConsume("NAME");
  124. var pattern = tryConsume("PATTERN");
  125. if (name || pattern) {
  126. var prefix = char || "";
  127. if (prefixes.indexOf(prefix) === -1) {
  128. path += prefix;
  129. prefix = "";
  130. }
  131. if (path) {
  132. result.push(path);
  133. path = "";
  134. }
  135. result.push({
  136. name: name || key++,
  137. prefix: prefix,
  138. suffix: "",
  139. pattern: pattern || defaultPattern,
  140. modifier: tryConsume("MODIFIER") || "",
  141. });
  142. continue;
  143. }
  144. var value = char || tryConsume("ESCAPED_CHAR");
  145. if (value) {
  146. path += value;
  147. continue;
  148. }
  149. if (path) {
  150. result.push(path);
  151. path = "";
  152. }
  153. var open = tryConsume("OPEN");
  154. if (open) {
  155. var prefix = consumeText();
  156. var name_1 = tryConsume("NAME") || "";
  157. var pattern_1 = tryConsume("PATTERN") || "";
  158. var suffix = consumeText();
  159. mustConsume("CLOSE");
  160. result.push({
  161. name: name_1 || (pattern_1 ? key++ : ""),
  162. pattern: name_1 && !pattern_1 ? defaultPattern : pattern_1,
  163. prefix: prefix,
  164. suffix: suffix,
  165. modifier: tryConsume("MODIFIER") || "",
  166. });
  167. continue;
  168. }
  169. mustConsume("END");
  170. }
  171. return result;
  172. }
  173. /**
  174. * Compile a string to a template function for the path.
  175. */
  176. export function compile(str, options) {
  177. return tokensToFunction(parse(str, options), options);
  178. }
  179. /**
  180. * Expose a method for transforming tokens into the path function.
  181. */
  182. export function tokensToFunction(tokens, options) {
  183. if (options === void 0) { options = {}; }
  184. var reFlags = flags(options);
  185. var _a = options.encode, encode = _a === void 0 ? function (x) { return x; } : _a, _b = options.validate, validate = _b === void 0 ? true : _b;
  186. // Compile all the tokens into regexps.
  187. var matches = tokens.map(function (token) {
  188. if (typeof token === "object") {
  189. return new RegExp("^(?:".concat(token.pattern, ")$"), reFlags);
  190. }
  191. });
  192. return function (data) {
  193. var path = "";
  194. for (var i = 0; i < tokens.length; i++) {
  195. var token = tokens[i];
  196. if (typeof token === "string") {
  197. path += token;
  198. continue;
  199. }
  200. var value = data ? data[token.name] : undefined;
  201. var optional = token.modifier === "?" || token.modifier === "*";
  202. var repeat = token.modifier === "*" || token.modifier === "+";
  203. if (Array.isArray(value)) {
  204. if (!repeat) {
  205. throw new TypeError("Expected \"".concat(token.name, "\" to not repeat, but got an array"));
  206. }
  207. if (value.length === 0) {
  208. if (optional)
  209. continue;
  210. throw new TypeError("Expected \"".concat(token.name, "\" to not be empty"));
  211. }
  212. for (var j = 0; j < value.length; j++) {
  213. var segment = encode(value[j], token);
  214. if (validate && !matches[i].test(segment)) {
  215. throw new TypeError("Expected all \"".concat(token.name, "\" to match \"").concat(token.pattern, "\", but got \"").concat(segment, "\""));
  216. }
  217. path += token.prefix + segment + token.suffix;
  218. }
  219. continue;
  220. }
  221. if (typeof value === "string" || typeof value === "number") {
  222. var segment = encode(String(value), token);
  223. if (validate && !matches[i].test(segment)) {
  224. throw new TypeError("Expected \"".concat(token.name, "\" to match \"").concat(token.pattern, "\", but got \"").concat(segment, "\""));
  225. }
  226. path += token.prefix + segment + token.suffix;
  227. continue;
  228. }
  229. if (optional)
  230. continue;
  231. var typeOfMessage = repeat ? "an array" : "a string";
  232. throw new TypeError("Expected \"".concat(token.name, "\" to be ").concat(typeOfMessage));
  233. }
  234. return path;
  235. };
  236. }
  237. /**
  238. * Create path match function from `path-to-regexp` spec.
  239. */
  240. export function match(str, options) {
  241. var keys = [];
  242. var re = pathToRegexp(str, keys, options);
  243. return regexpToFunction(re, keys, options);
  244. }
  245. /**
  246. * Create a path match function from `path-to-regexp` output.
  247. */
  248. export function regexpToFunction(re, keys, options) {
  249. if (options === void 0) { options = {}; }
  250. var _a = options.decode, decode = _a === void 0 ? function (x) { return x; } : _a;
  251. return function (pathname) {
  252. var m = re.exec(pathname);
  253. if (!m)
  254. return false;
  255. var path = m[0], index = m.index;
  256. var params = Object.create(null);
  257. var _loop_1 = function (i) {
  258. if (m[i] === undefined)
  259. return "continue";
  260. var key = keys[i - 1];
  261. if (key.modifier === "*" || key.modifier === "+") {
  262. params[key.name] = m[i].split(key.prefix + key.suffix).map(function (value) {
  263. return decode(value, key);
  264. });
  265. }
  266. else {
  267. params[key.name] = decode(m[i], key);
  268. }
  269. };
  270. for (var i = 1; i < m.length; i++) {
  271. _loop_1(i);
  272. }
  273. return { path: path, index: index, params: params };
  274. };
  275. }
  276. /**
  277. * Escape a regular expression string.
  278. */
  279. function escapeString(str) {
  280. return str.replace(/([.+*?=^!:${}()[\]|/\\])/g, "\\$1");
  281. }
  282. /**
  283. * Get the flags for a regexp from the options.
  284. */
  285. function flags(options) {
  286. return options && options.sensitive ? "" : "i";
  287. }
  288. /**
  289. * Pull out keys from a regexp.
  290. */
  291. function regexpToRegexp(path, keys) {
  292. if (!keys)
  293. return path;
  294. var groupsRegex = /\((?:\?<(.*?)>)?(?!\?)/g;
  295. var index = 0;
  296. var execResult = groupsRegex.exec(path.source);
  297. while (execResult) {
  298. keys.push({
  299. // Use parenthesized substring match if available, index otherwise
  300. name: execResult[1] || index++,
  301. prefix: "",
  302. suffix: "",
  303. modifier: "",
  304. pattern: "",
  305. });
  306. execResult = groupsRegex.exec(path.source);
  307. }
  308. return path;
  309. }
  310. /**
  311. * Transform an array into a regexp.
  312. */
  313. function arrayToRegexp(paths, keys, options) {
  314. var parts = paths.map(function (path) { return pathToRegexp(path, keys, options).source; });
  315. return new RegExp("(?:".concat(parts.join("|"), ")"), flags(options));
  316. }
  317. /**
  318. * Create a path regexp from string input.
  319. */
  320. function stringToRegexp(path, keys, options) {
  321. return tokensToRegexp(parse(path, options), keys, options);
  322. }
  323. /**
  324. * Expose a function for taking tokens and returning a RegExp.
  325. */
  326. export function tokensToRegexp(tokens, keys, options) {
  327. if (options === void 0) { options = {}; }
  328. var _a = options.strict, strict = _a === void 0 ? false : _a, _b = options.start, start = _b === void 0 ? true : _b, _c = options.end, end = _c === void 0 ? true : _c, _d = options.encode, encode = _d === void 0 ? function (x) { return x; } : _d, _e = options.delimiter, delimiter = _e === void 0 ? "/#?" : _e, _f = options.endsWith, endsWith = _f === void 0 ? "" : _f;
  329. var endsWithRe = "[".concat(escapeString(endsWith), "]|$");
  330. var delimiterRe = "[".concat(escapeString(delimiter), "]");
  331. var route = start ? "^" : "";
  332. // Iterate over the tokens and create our regexp string.
  333. for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
  334. var token = tokens_1[_i];
  335. if (typeof token === "string") {
  336. route += escapeString(encode(token));
  337. }
  338. else {
  339. var prefix = escapeString(encode(token.prefix));
  340. var suffix = escapeString(encode(token.suffix));
  341. if (token.pattern) {
  342. if (keys)
  343. keys.push(token);
  344. if (prefix || suffix) {
  345. if (token.modifier === "+" || token.modifier === "*") {
  346. var mod = token.modifier === "*" ? "?" : "";
  347. route += "(?:".concat(prefix, "((?:").concat(token.pattern, ")(?:").concat(suffix).concat(prefix, "(?:").concat(token.pattern, "))*)").concat(suffix, ")").concat(mod);
  348. }
  349. else {
  350. route += "(?:".concat(prefix, "(").concat(token.pattern, ")").concat(suffix, ")").concat(token.modifier);
  351. }
  352. }
  353. else {
  354. if (token.modifier === "+" || token.modifier === "*") {
  355. route += "((?:".concat(token.pattern, ")").concat(token.modifier, ")");
  356. }
  357. else {
  358. route += "(".concat(token.pattern, ")").concat(token.modifier);
  359. }
  360. }
  361. }
  362. else {
  363. route += "(?:".concat(prefix).concat(suffix, ")").concat(token.modifier);
  364. }
  365. }
  366. }
  367. if (end) {
  368. if (!strict)
  369. route += "".concat(delimiterRe, "?");
  370. route += !options.endsWith ? "$" : "(?=".concat(endsWithRe, ")");
  371. }
  372. else {
  373. var endToken = tokens[tokens.length - 1];
  374. var isEndDelimited = typeof endToken === "string"
  375. ? delimiterRe.indexOf(endToken[endToken.length - 1]) > -1
  376. : endToken === undefined;
  377. if (!strict) {
  378. route += "(?:".concat(delimiterRe, "(?=").concat(endsWithRe, "))?");
  379. }
  380. if (!isEndDelimited) {
  381. route += "(?=".concat(delimiterRe, "|").concat(endsWithRe, ")");
  382. }
  383. }
  384. return new RegExp(route, flags(options));
  385. }
  386. /**
  387. * Normalize the given path string, returning a regular expression.
  388. *
  389. * An empty array can be passed in for the keys, which will hold the
  390. * placeholder key descriptions. For example, using `/user/:id`, `keys` will
  391. * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
  392. */
  393. export function pathToRegexp(path, keys, options) {
  394. if (path instanceof RegExp)
  395. return regexpToRegexp(path, keys);
  396. if (Array.isArray(path))
  397. return arrayToRegexp(path, keys, options);
  398. return stringToRegexp(path, keys, options);
  399. }
  400. //# sourceMappingURL=index.js.map