-
Notifications
You must be signed in to change notification settings - Fork 923
/
Copy pathpath.ts
411 lines (357 loc) · 10.9 KB
/
path.ts
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Integer } from '@firebase/webchannel-wrapper/bloom-blob';
import { debugAssert, fail } from '../util/assert';
import { Code, FirestoreError } from '../util/error';
import { compareUtf8Strings, primitiveComparator } from '../util/misc';
export const DOCUMENT_KEY_NAME = '__name__';
/**
* Path represents an ordered sequence of string segments.
*/
abstract class BasePath<B extends BasePath<B>> {
private segments: string[];
private offset: number;
private len: number;
constructor(segments: string[], offset?: number, length?: number) {
if (offset === undefined) {
offset = 0;
} else if (offset > segments.length) {
fail('offset ' + offset + ' out of range ' + segments.length);
}
if (length === undefined) {
length = segments.length - offset;
} else if (length > segments.length - offset) {
fail('length ' + length + ' out of range ' + (segments.length - offset));
}
this.segments = segments;
this.offset = offset;
this.len = length;
}
/**
* Abstract constructor method to construct an instance of B with the given
* parameters.
*/
protected abstract construct(
segments: string[],
offset?: number,
length?: number
): B;
/**
* Returns a String representation.
*
* Implementing classes are required to provide deterministic implementations as
* the String representation is used to obtain canonical Query IDs.
*/
abstract toString(): string;
get length(): number {
return this.len;
}
isEqual(other: B): boolean {
return BasePath.comparator(this, other) === 0;
}
child(nameOrPath: string | B): B {
const segments = this.segments.slice(this.offset, this.limit());
if (nameOrPath instanceof BasePath) {
nameOrPath.forEach(segment => {
segments.push(segment);
});
} else {
segments.push(nameOrPath);
}
return this.construct(segments);
}
/** The index of one past the last segment of the path. */
private limit(): number {
return this.offset + this.length;
}
popFirst(size?: number): B {
size = size === undefined ? 1 : size;
debugAssert(
this.length >= size,
"Can't call popFirst() with less segments"
);
return this.construct(
this.segments,
this.offset + size,
this.length - size
);
}
popLast(): B {
debugAssert(!this.isEmpty(), "Can't call popLast() on empty path");
return this.construct(this.segments, this.offset, this.length - 1);
}
firstSegment(): string {
debugAssert(!this.isEmpty(), "Can't call firstSegment() on empty path");
return this.segments[this.offset];
}
lastSegment(): string {
debugAssert(!this.isEmpty(), "Can't call lastSegment() on empty path");
return this.get(this.length - 1);
}
get(index: number): string {
debugAssert(index < this.length, 'Index out of range');
return this.segments[this.offset + index];
}
isEmpty(): boolean {
return this.length === 0;
}
isPrefixOf(other: this): boolean {
if (other.length < this.length) {
return false;
}
for (let i = 0; i < this.length; i++) {
if (this.get(i) !== other.get(i)) {
return false;
}
}
return true;
}
isImmediateParentOf(potentialChild: this): boolean {
if (this.length + 1 !== potentialChild.length) {
return false;
}
for (let i = 0; i < this.length; i++) {
if (this.get(i) !== potentialChild.get(i)) {
return false;
}
}
return true;
}
forEach(fn: (segment: string) => void): void {
for (let i = this.offset, end = this.limit(); i < end; i++) {
fn(this.segments[i]);
}
}
toArray(): string[] {
return this.segments.slice(this.offset, this.limit());
}
/**
* Compare 2 paths segment by segment, prioritizing numeric IDs
* (e.g., "__id123__") in numeric ascending order, followed by string
* segments in lexicographical order.
*/
static comparator<T extends BasePath<T>>(
p1: BasePath<T>,
p2: BasePath<T>
): number {
const len = Math.min(p1.length, p2.length);
for (let i = 0; i < len; i++) {
const comparison = BasePath.compareSegments(p1.get(i), p2.get(i));
if (comparison !== 0) {
return comparison;
}
}
return primitiveComparator(p1.length, p2.length);
}
private static compareSegments(lhs: string, rhs: string): number {
const isLhsNumeric = BasePath.isNumericId(lhs);
const isRhsNumeric = BasePath.isNumericId(rhs);
if (isLhsNumeric && !isRhsNumeric) {
// Only lhs is numeric
return -1;
} else if (!isLhsNumeric && isRhsNumeric) {
// Only rhs is numeric
return 1;
} else if (isLhsNumeric && isRhsNumeric) {
// both numeric
return BasePath.extractNumericId(lhs).compare(
BasePath.extractNumericId(rhs)
);
} else {
// both non-numeric
return compareUtf8Strings(lhs, rhs);
}
}
// Checks if a segment is a numeric ID (starts with "__id" and ends with "__").
private static isNumericId(segment: string): boolean {
return segment.startsWith('__id') && segment.endsWith('__');
}
private static extractNumericId(segment: string): Integer {
return Integer.fromString(segment.substring(4, segment.length - 2));
}
}
/**
* A slash-separated path for navigating resources (documents and collections)
* within Firestore.
*
* @internal
*/
export class ResourcePath extends BasePath<ResourcePath> {
protected construct(
segments: string[],
offset?: number,
length?: number
): ResourcePath {
return new ResourcePath(segments, offset, length);
}
canonicalString(): string {
// NOTE: The client is ignorant of any path segments containing escape
// sequences (e.g. __id123__) and just passes them through raw (they exist
// for legacy reasons and should not be used frequently).
return this.toArray().join('/');
}
toString(): string {
return this.canonicalString();
}
/**
* Returns a string representation of this path
* where each path segment has been encoded with
* `encodeURIComponent`.
*/
toUriEncodedString(): string {
return this.toArray().map(encodeURIComponent).join('/');
}
/**
* Creates a resource path from the given slash-delimited string. If multiple
* arguments are provided, all components are combined. Leading and trailing
* slashes from all components are ignored.
*/
static fromString(...pathComponents: string[]): ResourcePath {
// NOTE: The client is ignorant of any path segments containing escape
// sequences (e.g. __id123__) and just passes them through raw (they exist
// for legacy reasons and should not be used frequently).
const segments: string[] = [];
for (const path of pathComponents) {
if (path.indexOf('//') >= 0) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
`Invalid segment (${path}). Paths must not contain // in them.`
);
}
// Strip leading and trailing slashed.
segments.push(...path.split('/').filter(segment => segment.length > 0));
}
return new ResourcePath(segments);
}
static emptyPath(): ResourcePath {
return new ResourcePath([]);
}
}
const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;
/**
* A dot-separated path for navigating sub-objects within a document.
* @internal
*/
export class FieldPath extends BasePath<FieldPath> {
protected construct(
segments: string[],
offset?: number,
length?: number
): FieldPath {
return new FieldPath(segments, offset, length);
}
/**
* Returns true if the string could be used as a segment in a field path
* without escaping.
*/
private static isValidIdentifier(segment: string): boolean {
return identifierRegExp.test(segment);
}
canonicalString(): string {
return this.toArray()
.map(str => {
str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`');
if (!FieldPath.isValidIdentifier(str)) {
str = '`' + str + '`';
}
return str;
})
.join('.');
}
toString(): string {
return this.canonicalString();
}
/**
* Returns true if this field references the key of a document.
*/
isKeyField(): boolean {
return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;
}
/**
* The field designating the key of a document.
*/
static keyField(): FieldPath {
return new FieldPath([DOCUMENT_KEY_NAME]);
}
/**
* Parses a field string from the given server-formatted string.
*
* - Splitting the empty string is not allowed (for now at least).
* - Empty segments within the string (e.g. if there are two consecutive
* separators) are not allowed.
*
* TODO(b/37244157): we should make this more strict. Right now, it allows
* non-identifier path components, even if they aren't escaped.
*/
static fromServerFormat(path: string): FieldPath {
const segments: string[] = [];
let current = '';
let i = 0;
const addCurrentSegment = (): void => {
if (current.length === 0) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
`Invalid field path (${path}). Paths must not be empty, begin ` +
`with '.', end with '.', or contain '..'`
);
}
segments.push(current);
current = '';
};
let inBackticks = false;
while (i < path.length) {
const c = path[i];
if (c === '\\') {
if (i + 1 === path.length) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
'Path has trailing escape character: ' + path
);
}
const next = path[i + 1];
if (!(next === '\\' || next === '.' || next === '`')) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
'Path has invalid escape sequence: ' + path
);
}
current += next;
i += 2;
} else if (c === '`') {
inBackticks = !inBackticks;
i++;
} else if (c === '.' && !inBackticks) {
addCurrentSegment();
i++;
} else {
current += c;
i++;
}
}
addCurrentSegment();
if (inBackticks) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
'Unterminated ` in path: ' + path
);
}
return new FieldPath(segments);
}
static emptyPath(): FieldPath {
return new FieldPath([]);
}
}