Repository navigation
Expand file tree
/
Copy pathpath_recognizer.ts
More file actions
302 lines (254 loc) · 8.96 KB
/
Copy pathpath_recognizer.ts
File metadata and controls
302 lines (254 loc) · 8.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import {
RegExp,
RegExpWrapper,
RegExpMatcherWrapper,
StringWrapper,
isPresent,
isBlank,
BaseException
} from 'angular2/src/facade/lang';
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {
Map,
MapWrapper,
StringMap,
StringMapWrapper,
List,
ListWrapper
} from 'angular2/src/facade/collection';
import {IMPLEMENTS} from 'angular2/src/facade/lang';
import {parseAndAssignParamString} from 'angular2/src/router/helpers';
import {escapeRegex} from './url';
import {RouteHandler} from './route_handler';
// TODO(jeffbcross): implement as interface when ts2dart adds support:
// https://github.com/angular/ts2dart/issues/173
export class Segment {
name: string;
regex: string;
generate(params: TouchMap): string { return ''; }
}
class TouchMap {
map: StringMap<string, string> = StringMapWrapper.create();
keys: StringMap<string, boolean> = StringMapWrapper.create();
constructor(map: StringMap<string, any>) {
if (isPresent(map)) {
StringMapWrapper.forEach(map, (value, key) => {
this.map[key] = isPresent(value) ? value.toString() : null;
this.keys[key] = true;
});
}
}
get(key: string): string {
StringMapWrapper.delete(this.keys, key);
return this.map[key];
}
getUnused(): StringMap<string, any> {
var unused: StringMap<string, any> = StringMapWrapper.create();
var keys = StringMapWrapper.keys(this.keys);
ListWrapper.forEach(keys, (key) => { unused[key] = StringMapWrapper.get(this.map, key); });
return unused;
}
}
function normalizeString(obj: any): string {
if (isBlank(obj)) {
return null;
} else {
return obj.toString();
}
}
class ContinuationSegment extends Segment {}
class StaticSegment extends Segment {
regex: string;
name: string = '';
constructor(public string: string) {
super();
this.regex = escapeRegex(string);
// we add this property so that the route matcher still sees
// this segment as a valid path even if do not use the matrix
// parameters
this.regex += '(;[^\/]+)?';
}
generate(params: TouchMap): string { return this.string; }
}
@IMPLEMENTS(Segment)
class DynamicSegment {
regex: string = "([^/]+)";
constructor(public name: string) {}
generate(params: TouchMap): string {
if (!StringMapWrapper.contains(params.map, this.name)) {
throw new BaseException(
`Route generator for '${this.name}' was not included in parameters passed.`);
}
return normalizeString(params.get(this.name));
}
}
class StarSegment {
regex: string = "(.+)";
constructor(public name: string) {}
generate(params: TouchMap): string { return normalizeString(params.get(this.name)); }
}
var paramMatcher = /^:([^\/]+)$/g;
var wildcardMatcher = /^\*([^\/]+)$/g;
function parsePathString(route: string): StringMap<string, any> {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (StringWrapper.startsWith(route, "/")) {
route = StringWrapper.substring(route, 1);
}
var segments = splitBySlash(route);
var results = [];
var specificity = 0;
// The "specificity" of a path is used to determine which route is used when multiple routes match
// a URL.
// Static segments (like "/foo") are the most specific, followed by dynamic segments (like
// "/:id"). Star segments
// add no specificity. Segments at the start of the path are more specific than proceeding ones.
// The code below uses place values to combine the different types of segments into a single
// integer that we can
// sort later. Each static segment is worth hundreds of points of specificity (10000, 9900, ...,
// 200), and each
// dynamic segment is worth single points of specificity (100, 99, ... 2).
if (segments.length > 98) {
throw new BaseException(`'${route}' has more than the maximum supported number of segments.`);
}
var limit = segments.length - 1;
for (var i = 0; i <= limit; i++) {
var segment = segments[i], match;
if (isPresent(match = RegExpWrapper.firstMatch(paramMatcher, segment))) {
results.push(new DynamicSegment(match[1]));
specificity += (100 - i);
} else if (isPresent(match = RegExpWrapper.firstMatch(wildcardMatcher, segment))) {
results.push(new StarSegment(match[1]));
} else if (segment == '...') {
if (i < limit) {
// TODO (matsko): setup a proper error here `
throw new BaseException(`Unexpected "..." before the end of the path for "${route}".`);
}
results.push(new ContinuationSegment());
} else if (segment.length > 0) {
results.push(new StaticSegment(segment));
specificity += 100 * (100 - i);
}
}
var result = StringMapWrapper.create();
StringMapWrapper.set(result, 'segments', results);
StringMapWrapper.set(result, 'specificity', specificity);
return result;
}
function splitBySlash(url: string): List<string> {
return url.split('/');
}
var RESERVED_CHARS = RegExpWrapper.create('//|\\(|\\)|;|\\?|=');
function assertPath(path: string) {
if (StringWrapper.contains(path, '#')) {
throw new BaseException(
`Path "${path}" should not include "#". Use "HashLocationStrategy" instead.`);
}
var illegalCharacter = RegExpWrapper.firstMatch(RESERVED_CHARS, path);
if (isPresent(illegalCharacter)) {
throw new BaseException(
`Path "${path}" contains "${illegalCharacter[0]}" which is not allowed in a route config.`);
}
}
// represents something like '/foo/:bar'
export class PathRecognizer {
segments: List<Segment>;
regex: RegExp;
specificity: number;
terminal: boolean = true;
static matrixRegex: RegExp = RegExpWrapper.create('^(.*\/[^\/]+?)(;[^\/]+)?\/?$');
static queryRegex: RegExp = RegExpWrapper.create('^(.*\/[^\/]+?)(\\?[^\/]+)?$');
constructor(public path: string, public handler: RouteHandler, public isRoot: boolean = false) {
assertPath(path);
var parsed = parsePathString(path);
var specificity = parsed['specificity'];
var segments = parsed['segments'];
var regexString = '^';
ListWrapper.forEach(segments, (segment) => {
if (segment instanceof ContinuationSegment) {
this.terminal = false;
} else {
regexString += '/' + segment.regex;
}
});
if (this.terminal) {
regexString += '$';
}
this.regex = RegExpWrapper.create(regexString);
this.segments = segments;
this.specificity = specificity;
}
parseParams(url: string): StringMap<string, string> {
// the last segment is always the star one since it's terminal
var segmentsLimit = this.segments.length - 1;
var containsStarSegment =
segmentsLimit >= 0 && this.segments[segmentsLimit] instanceof StarSegment;
var paramsString, useQueryString = this.isRoot && this.terminal;
if (!containsStarSegment) {
var matches = RegExpWrapper.firstMatch(
useQueryString ? PathRecognizer.queryRegex : PathRecognizer.matrixRegex, url);
if (isPresent(matches)) {
url = matches[1];
paramsString = matches[2];
}
url = StringWrapper.replaceAll(url, /(;[^\/]+)(?=(\/|$))/g, '');
}
var params = StringMapWrapper.create();
var urlPart = url;
for (var i = 0; i <= segmentsLimit; i++) {
var segment = this.segments[i];
if (segment instanceof ContinuationSegment) {
continue;
}
var match = RegExpWrapper.firstMatch(RegExpWrapper.create('/' + segment.regex), urlPart);
urlPart = StringWrapper.substring(urlPart, match[0].length);
if (segment.name.length > 0) {
params[segment.name] = match[1];
}
}
if (isPresent(paramsString) && paramsString.length > 0) {
var expectedStartingValue = useQueryString ? '?' : ';';
if (paramsString[0] == expectedStartingValue) {
parseAndAssignParamString(expectedStartingValue, paramsString, params);
}
}
return params;
}
generate(params: StringMap<string, any>): string {
var paramTokens = new TouchMap(params);
var applyLeadingSlash = false;
var useQueryString = this.isRoot && this.terminal;
var url = '';
for (var i = 0; i < this.segments.length; i++) {
let segment = this.segments[i];
let s = segment.generate(paramTokens);
applyLeadingSlash = applyLeadingSlash || (segment instanceof ContinuationSegment);
if (s.length > 0) {
url += (i > 0 ? '/' : '') + s;
}
}
var unusedParams = paramTokens.getUnused();
if (!StringMapWrapper.isEmpty(unusedParams)) {
url += useQueryString ? '?' : ';';
var paramToken = useQueryString ? '&' : ';';
var i = 0;
StringMapWrapper.forEach(unusedParams, (value, key) => {
if (i++ > 0) {
url += paramToken;
}
url += key;
if (!isPresent(value) && useQueryString) {
value = 'true';
}
if (isPresent(value)) {
url += '=' + value;
}
});
}
if (applyLeadingSlash) {
url += '/';
}
return url;
}
resolveComponentType(): Promise<any> { return this.handler.resolveComponentType(); }
}