UNPKG

2.51 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.matchPathFilter = void 0;
4const isGlob = require("is-glob");
5const micromatch = require("micromatch");
6const url = require("url");
7const errors_1 = require("./errors");
8function matchPathFilter(pathFilter = '/', uri, req) {
9 // single path
10 if (isStringPath(pathFilter)) {
11 return matchSingleStringPath(pathFilter, uri);
12 }
13 // single glob path
14 if (isGlobPath(pathFilter)) {
15 return matchSingleGlobPath(pathFilter, uri);
16 }
17 // multi path
18 if (Array.isArray(pathFilter)) {
19 if (pathFilter.every(isStringPath)) {
20 return matchMultiPath(pathFilter, uri);
21 }
22 if (pathFilter.every(isGlobPath)) {
23 return matchMultiGlobPath(pathFilter, uri);
24 }
25 throw new Error(errors_1.ERRORS.ERR_CONTEXT_MATCHER_INVALID_ARRAY);
26 }
27 // custom matching
28 if (typeof pathFilter === 'function') {
29 const pathname = getUrlPathName(uri);
30 return pathFilter(pathname, req);
31 }
32 throw new Error(errors_1.ERRORS.ERR_CONTEXT_MATCHER_GENERIC);
33}
34exports.matchPathFilter = matchPathFilter;
35/**
36 * @param {String} pathFilter '/api'
37 * @param {String} uri 'http://example.org/api/b/c/d.html'
38 * @return {Boolean}
39 */
40function matchSingleStringPath(pathFilter, uri) {
41 const pathname = getUrlPathName(uri);
42 return pathname?.indexOf(pathFilter) === 0;
43}
44function matchSingleGlobPath(pattern, uri) {
45 const pathname = getUrlPathName(uri);
46 const matches = micromatch([pathname], pattern);
47 return matches && matches.length > 0;
48}
49function matchMultiGlobPath(patternList, uri) {
50 return matchSingleGlobPath(patternList, uri);
51}
52/**
53 * @param {String} pathFilterList ['/api', '/ajax']
54 * @param {String} uri 'http://example.org/api/b/c/d.html'
55 * @return {Boolean}
56 */
57function matchMultiPath(pathFilterList, uri) {
58 let isMultiPath = false;
59 for (const context of pathFilterList) {
60 if (matchSingleStringPath(context, uri)) {
61 isMultiPath = true;
62 break;
63 }
64 }
65 return isMultiPath;
66}
67/**
68 * Parses URI and returns RFC 3986 path
69 *
70 * @param {String} uri from req.url
71 * @return {String} RFC 3986 path
72 */
73function getUrlPathName(uri) {
74 return uri && url.parse(uri).pathname;
75}
76function isStringPath(pathFilter) {
77 return typeof pathFilter === 'string' && !isGlob(pathFilter);
78}
79function isGlobPath(pathFilter) {
80 return isGlob(pathFilter);
81}