1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | const escape_regexp_1 = __importDefault(require("./escape_regexp"));
|
6 | const rParam = /([:*])([\w?]*)?/g;
|
7 | class Pattern {
|
8 | constructor(rule) {
|
9 | if (rule instanceof Pattern) {
|
10 | return rule;
|
11 | }
|
12 | else if (typeof rule === 'function') {
|
13 | this.match = rule;
|
14 | }
|
15 | else if (rule instanceof RegExp) {
|
16 | this.match = regexFilter(rule);
|
17 | }
|
18 | else if (typeof rule === 'string') {
|
19 | this.match = stringFilter(rule);
|
20 | }
|
21 | else {
|
22 | throw new TypeError('rule must be a function, a string or a regular expression.');
|
23 | }
|
24 | }
|
25 | test(str) {
|
26 | return Boolean(this.match(str));
|
27 | }
|
28 | }
|
29 | function regexFilter(rule) {
|
30 | return (str) => str.match(rule);
|
31 | }
|
32 | function stringFilter(rule) {
|
33 | const params = [];
|
34 | const regex = (0, escape_regexp_1.default)(rule)
|
35 | .replace(/\\([*?])/g, '$1')
|
36 | .replace(rParam, (match, operator, name) => {
|
37 | let str = '';
|
38 | if (operator === '*') {
|
39 | str = '(.*)?';
|
40 | }
|
41 | else {
|
42 | str = '([^\\/]+)';
|
43 | }
|
44 | if (name) {
|
45 | if (name[name.length - 1] === '?') {
|
46 | name = name.slice(0, name.length - 1);
|
47 | str += '?';
|
48 | }
|
49 | params.push(name);
|
50 | }
|
51 | return str;
|
52 | });
|
53 | return (str) => {
|
54 | const match = str.match(regex);
|
55 | if (!match)
|
56 | return;
|
57 | const result = {};
|
58 | for (let i = 0, len = match.length; i < len; i++) {
|
59 | const name = params[i - 1];
|
60 | result[i] = match[i];
|
61 | if (name)
|
62 | result[name] = match[i];
|
63 | }
|
64 | return result;
|
65 | };
|
66 | }
|
67 | module.exports = Pattern;
|
68 |
|
\ | No newline at end of file |