index.js 15 KB

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