/
pointer.ts
697 lines (659 loc) · 20.1 KB
/
pointer.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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
import {
Dereference,
decodePtrInit,
compilePointerDereference,
setValueAtPath,
encodePointer,
encodeUriFragmentIdentifier,
pickDecoder,
unsetValueAtPath,
decodeRelativePointer,
} from './util';
import {
JsonStringPointer,
UriFragmentIdentifierPointer,
Pointer,
RelativeJsonPointer,
PathSegments,
Encoder,
JsonStringPointerListItem,
UriFragmentIdentifierPointerListItem,
} from './types';
/**
* Determines if the value is an object (not null)
* @param value the value
* @returns true if the value is a non-null object; otherwise false.
*
* @hidden
*/
function isObject(value: unknown): boolean {
return typeof value === 'object' && value !== null;
}
/**
* Signature of visitor functions, used with [[JsonPointer.visit]] method. Visitors are callbacks invoked for every segment/branch of a target's object graph.
*
* Tree descent occurs in-order, breadth first.
*/
export type Visitor = (ptr: JsonStringPointer, val: unknown) => void;
/** @hidden */
interface Item {
obj: unknown;
path: PathSegments;
}
/** @hidden */
function shouldDescend(obj: unknown): boolean {
return isObject(obj) && !JsonReference.isReference(obj);
}
/** @hidden */
function descendingVisit(
target: unknown,
visitor: Visitor,
encoder: Encoder,
): void {
const distinctObjects = new Map<unknown, JsonPointer>();
const q: Item[] = [{ obj: target, path: [] }];
while (q.length) {
const { obj, path } = q.shift() as Item;
visitor(encoder(path), obj);
if (shouldDescend(obj)) {
distinctObjects.set(
obj,
new JsonPointer(encodeUriFragmentIdentifier(path)),
);
if (!Array.isArray(obj)) {
const keys = Object.keys(obj as Record<string, unknown>);
const len = keys.length;
let i = -1;
while (++i < len) {
const it = (obj as Record<string, unknown>)[keys[i]];
if (isObject(it) && distinctObjects.has(it)) {
q.push({
obj: new JsonReference(distinctObjects.get(it) as JsonPointer),
path: path.concat(keys[i]),
});
} else {
q.push({
obj: it,
path: path.concat(keys[i]),
});
}
}
} else {
// handleArray
let j = -1;
const len = obj.length;
while (++j < len) {
const it = obj[j];
if (isObject(it) && distinctObjects.has(it)) {
q.push({
obj: new JsonReference(distinctObjects.get(it) as JsonPointer),
path: path.concat([j + '']),
});
} else {
q.push({
obj: it,
path: path.concat([j + '']),
});
}
}
}
}
}
}
/** @hidden */
const $ptr = Symbol('pointer');
/** @hidden */
const $frg = Symbol('fragmentId');
/** @hidden */
const $get = Symbol('getter');
/**
* Represents a JSON Pointer, capable of getting and setting the value on target
* objects at the pointer's location.
*
* While there are static variants for most operations, our recommendation is
* to use the instance level methods, which enables you avoid repeated
* compiling/emitting transient accessors. Take a look at the speed comparisons
* for our justification.
*
* In most cases, you should create and reuse instances of JsonPointer within
* scope that makes sense for your app. We often create constants for frequently
* used pointers, but your use case may vary.
*
* The following is a contrived example showing a function that uses pointers to
* deal with changes in the structure of data (a version independent function):
*
* ```ts
* import { JsonPointer } from 'json-ptr';
*
* export type SupportedVersion = '1.0' | '1.1';
*
* interface PrimaryGuestNamePointers {
* name: JsonPointer;
* surname: JsonPointer;
* honorific: JsonPointer;
* }
* const versions: Record<SupportedVersion, PrimaryGuestNamePointers> = {
* '1.0': {
* name: JsonPointer.create('/guests/0/name'),
* surname: JsonPointer.create('/guests/0/surname'),
* honorific: JsonPointer.create('/guests/0/honorific'),
* },
* '1.1': {
* name: JsonPointer.create('/primary/primaryGuest/name'),
* surname: JsonPointer.create('/primary/primaryGuest/surname'),
* honorific: JsonPointer.create('/primary/primaryGuest/honorific'),
* }
* };
*
* interface Reservation extends Record<string, unknown> {
* version?: SupportedVersion;
* }
*
* function primaryGuestName(reservation: Reservation): string {
* const pointers = versions[reservation.version || '1.0'];
* const name = pointers.name.get(reservation) as string;
* const surname = pointers.surname.get(reservation) as string;
* const honorific = pointers.honorific.get(reservation) as string;
* const names: string[] = [];
* if (honorific) names.push(honorific);
* if (name) names.push(name);
* if (surname) names.push(surname);
* return names.join(' ');
* }
*
* // The original layout of a reservation (only the parts relevant to our example)
* const reservationV1: Reservation = {
* guests: [{
* name: 'Wilbur',
* surname: 'Finkle',
* honorific: 'Mr.'
* }, {
* name: 'Wanda',
* surname: 'Finkle',
* honorific: 'Mrs.'
* }, {
* name: 'Wilma',
* surname: 'Finkle',
* honorific: 'Miss',
* child: true,
* age: 12
* }]
* // ...
* };
*
* // The new layout of a reservation (only the parts relevant to our example)
* const reservationV1_1: Reservation = {
* version: '1.1',
* primary: {
* primaryGuest: {
* name: 'Wilbur',
* surname: 'Finkle',
* honorific: 'Mr.'
* },
* additionalGuests: [{
* name: 'Wanda',
* surname: 'Finkle',
* honorific: 'Mrs.'
* }, {
* name: 'Wilma',
* surname: 'Finkle',
* honorific: 'Miss',
* child: true,
* age: 12
* }]
* // ...
* }
* // ...
* };
*
* console.log(primaryGuestName(reservationV1));
* console.log(primaryGuestName(reservationV1_1));
*
* ```
*
* There are many uses for pointers.
*/
export class JsonPointer {
/** @hidden */
private [$ptr]: JsonStringPointer;
/** @hidden */
private [$frg]: UriFragmentIdentifierPointer;
/** @hidden */
private [$get]: Dereference;
/**
* Factory function that creates a JsonPointer instance.
*
* ```ts
* const ptr = JsonPointer.create('/deeply/nested/data/0/here');
* ```
* _or_
* ```ts
* const ptr = JsonPointer.create(['deeply', 'nested', 'data', 0, 'here']);
* ```
* @param pointer the pointer or path.
*/
static create(pointer: Pointer | PathSegments): JsonPointer {
return new JsonPointer(pointer);
}
/**
* Determines if the specified `target`'s object graph has a value at the `pointer`'s location.
*
* ```ts
* const target = {
* first: 'second',
* third: ['fourth', 'fifth', { sixth: 'seventh' }],
* eighth: 'ninth'
* };
*
* console.log(JsonPointer.has(target, '/third/0'));
* // true
* console.log(JsonPointer.has(target, '/tenth'));
* // false
* ```
*
* @param target the target of the operation
* @param pointer the pointer or path
*/
static has(
target: unknown,
pointer: Pointer | PathSegments | JsonPointer,
): boolean {
if (typeof pointer === 'string' || Array.isArray(pointer)) {
pointer = new JsonPointer(pointer);
}
return (pointer as JsonPointer).has(target);
}
/**
* Gets the `target` object's value at the `pointer`'s location.
*
* ```ts
* const target = {
* first: 'second',
* third: ['fourth', 'fifth', { sixth: 'seventh' }],
* eighth: 'ninth'
* };
*
* console.log(JsonPointer.get(target, '/third/2/sixth'));
* // seventh
* console.log(JsonPointer.get(target, '/tenth'));
* // undefined
* ```
*
* @param target the target of the operation
* @param pointer the pointer or path.
*/
static get(
target: unknown,
pointer: Pointer | PathSegments | JsonPointer,
): unknown {
if (typeof pointer === 'string' || Array.isArray(pointer)) {
pointer = new JsonPointer(pointer);
}
return (pointer as JsonPointer).get(target);
}
/**
* Sets the `target` object's value, as specified, at the `pointer`'s location.
*
* ```ts
* const target = {
* first: 'second',
* third: ['fourth', 'fifth', { sixth: 'seventh' }],
* eighth: 'ninth'
* };
*
* console.log(JsonPointer.set(target, '/third/2/sixth', 'tenth'));
* // seventh
* console.log(JsonPointer.set(target, '/tenth', 'eleventh', true));
* // undefined
* console.log(JSON.stringify(target, null, ' '));
* // {
* // "first": "second",
* // "third": [
* // "fourth",
* // "fifth",
* // {
* // "sixth": "tenth"
* // }
* // ],
* // "eighth": "ninth",
* // "tenth": "eleventh"
* // }
* ```
*
* @param target the target of the operation
* @param pointer the pointer or path
* @param val a value to write into the object graph at the specified pointer location
* @param force indications whether the operation should force the pointer's location into existence in the object graph.
*
* @returns the prior value at the pointer's location in the object graph.
*/
static set(
target: unknown,
pointer: Pointer | PathSegments | JsonPointer,
val: unknown,
force = false,
): unknown {
if (typeof pointer === 'string' || Array.isArray(pointer)) {
pointer = new JsonPointer(pointer);
}
return (pointer as JsonPointer).set(target, val, force);
}
/**
* Removes the `target` object's value at the `pointer`'s location.
*
* ```ts
* const target = {
* first: 'second',
* third: ['fourth', 'fifth', { sixth: 'seventh' }],
* eighth: 'ninth'
* };
*
* console.log(JsonPointer.unset(target, '/third/2/sixth'));
* // seventh
* console.log(JsonPointer.unset(target, '/tenth'));
* // undefined
* console.log(JSON.stringify(target, null, ' '));
* // {
* // "first": "second",
* // "third": [
* // "fourth",
* // "fifth",
* // {}
* // ],
* // "eighth": "ninth",
* // }
* ```
* @param target the target of the operation
* @param pointer the pointer or path
*
* @returns the value that was removed from the object graph.
*/
static unset(
target: unknown,
pointer: Pointer | PathSegments | JsonPointer,
): unknown {
if (typeof pointer === 'string' || Array.isArray(pointer)) {
pointer = new JsonPointer(pointer);
}
return (pointer as JsonPointer).unset(target);
}
/**
* Decodes the specified pointer into path segments.
* @param pointer a string representation of a JSON Pointer
*/
static decode(pointer: Pointer): PathSegments {
return pickDecoder(pointer)(pointer);
}
/**
* Evaluates the target's object graph, calling the specified visitor for every unique pointer location discovered while walking the graph.
* @param target the target of the operation
* @param visitor a callback function invoked for each unique pointer location in the object graph
* @param fragmentId indicates whether the visitor should receive fragment identifiers or regular pointers
*/
static visit(target: unknown, visitor: Visitor, fragmentId = false): void {
descendingVisit(
target,
visitor,
fragmentId ? encodeUriFragmentIdentifier : encodePointer,
);
}
/**
* Evaluates the target's object graph, returning a [[JsonStringPointerListItem]] for each location in the graph.
* @param target the target of the operation
*/
static listPointers(target: unknown): JsonStringPointerListItem[] {
const res: JsonStringPointerListItem[] = [];
descendingVisit(
target,
(pointer, value): void => {
res.push({ pointer, value });
},
encodePointer,
);
return res;
}
/**
* Evaluates the target's object graph, returning a [[UriFragmentIdentifierPointerListItem]] for each location in the graph.
* @param target the target of the operation
*/
static listFragmentIds(
target: unknown,
): UriFragmentIdentifierPointerListItem[] {
const res: UriFragmentIdentifierPointerListItem[] = [];
descendingVisit(
target,
(fragmentId, value): void => {
res.push({ fragmentId, value });
},
encodeUriFragmentIdentifier,
);
return res;
}
/**
* Evaluates the target's object graph, returning a Record<Pointer, unknown> populated with pointers and the corresponding values from the graph.
* @param target the target of the operation
* @param fragmentId indicates whether the results are populated with fragment identifiers rather than regular pointers
*/
static flatten(
target: unknown,
fragmentId = false,
): Record<Pointer, unknown> {
const res: Record<Pointer, unknown> = {};
descendingVisit(
target,
(p, v) => {
res[p] = v;
},
fragmentId ? encodeUriFragmentIdentifier : encodePointer,
);
return res;
}
/**
* Evaluates the target's object graph, returning a Map<Pointer,unknown> populated with pointers and the corresponding values form the graph.
* @param target the target of the operation
* @param fragmentId indicates whether the results are populated with fragment identifiers rather than regular pointers
*/
static map(target: unknown, fragmentId = false): Map<Pointer, unknown> {
const res = new Map<Pointer, unknown>();
descendingVisit(
target,
res.set.bind(res),
fragmentId ? encodeUriFragmentIdentifier : encodePointer,
);
return res;
}
/**
* The pointer's decoded path segments.
*/
public readonly path: PathSegments;
/**
* Creates a new instance.
* @param ptr a string representation of a JSON Pointer, or a decoded array of path segments.
*/
constructor(ptr: Pointer | PathSegments) {
this.path = decodePtrInit(ptr);
}
/**
* Gets the target object's value at the pointer's location.
* @param target the target of the operation
*/
get(target: unknown): unknown {
if (!this[$get]) {
this[$get] = compilePointerDereference(this.path);
}
return this[$get](target);
}
/**
* Sets the target object's value, as specified, at the pointer's location.
*
* If any part of the pointer's path does not exist, the operation aborts
* without modification, unless the caller indicates that pointer's location
* should be created.
*
* @param target the target of the operation
* @param value the value to set
* @param force indicates whether the pointer's location should be created if it doesn't already exist.
*/
set(target: unknown, value: unknown, force = false): unknown {
return setValueAtPath(target, value, this.path, force);
}
/**
* Removes the target object's value at the pointer's location.
* @param target the target of the operation
*
* @returns the value that was removed from the object graph.
*/
unset(target: unknown): unknown {
return unsetValueAtPath(target, this.path);
}
/**
* Determines if the specified target's object graph has a value at the pointer's location.
* @param target the target of the operation
*/
has(target: unknown): boolean {
return typeof this.get(target) !== 'undefined';
}
/**
* Gets the value in the object graph that is the parent of the pointer location.
* @param target the target of the operation
*/
parent(target: unknown): unknown {
const p = this.path;
if (p.length == 1) return undefined;
const parent = new JsonPointer(p.slice(0, p.length - 1));
return parent.get(target);
}
/**
* Creates a new JsonPointer instance, pointing to the specified relative location in the object graph.
* @param ptr the relative pointer (relative to this)
* @returns A new instance that points to the relative location.
*/
relative(ptr: RelativeJsonPointer): JsonPointer {
const p = this.path;
const decoded = decodeRelativePointer(ptr) as string[];
const n = parseInt(decoded[0]);
if (n > p.length) throw new Error('Relative location does not exist.');
const r = p.slice(0, p.length - n).concat(decoded.slice(1));
if (decoded[0][decoded[0].length - 1] == '#') {
// It references the path segment/name, not the value
const name = r[r.length - 1] as string;
throw new Error(
`We won't compile a pointer that will always return '${name}'. Use JsonPointer.rel(target, ptr) instead.`,
);
}
return new JsonPointer(r);
}
/**
* Resolves the specified relative pointer path against the specified target object, and gets the target object's value at the relative pointer's location.
* @param target the target of the operation
* @param ptr the relative pointer (relative to this)
* @returns the value at the relative pointer's resolved path; otherwise undefined.
*/
rel(target: unknown, ptr: RelativeJsonPointer): unknown {
const p = this.path;
const decoded = decodeRelativePointer(ptr) as string[];
const n = parseInt(decoded[0]);
if (n > p.length) {
// out of bounds
return undefined;
}
const r = p.slice(0, p.length - n).concat(decoded.slice(1));
const other = new JsonPointer(r);
if (decoded[0][decoded[0].length - 1] == '#') {
// It references the path segment/name, not the value
const name = r[r.length - 1] as string;
const parent = other.parent(target);
return Array.isArray(parent) ? parseInt(name, 10) : name;
}
return other.get(target);
}
/**
* Creates a new instance by concatenating the specified pointer's path onto this pointer's path.
* @param ptr the string representation of a pointer, it's decoded path, or an instance of JsonPointer indicating the additional path to concatenate onto the pointer.
*/
concat(ptr: JsonPointer | Pointer | PathSegments): JsonPointer {
return new JsonPointer(
this.path.concat(
ptr instanceof JsonPointer ? ptr.path : decodePtrInit(ptr),
),
);
}
/**
* This pointer's JSON Pointer encoded string representation.
*/
get pointer(): JsonStringPointer {
if (this[$ptr] === undefined) {
this[$ptr] = encodePointer(this.path);
}
return this[$ptr];
}
/**
* This pointer's URI fragment identifier encoded string representation.
*/
get uriFragmentIdentifier(): UriFragmentIdentifierPointer {
if (!this[$frg]) {
this[$frg] = encodeUriFragmentIdentifier(this.path);
}
return this[$frg];
}
/**
* Emits the JSON Pointer encoded string representation.
*/
toString(): string {
return this.pointer;
}
}
/** @hidden */
const $pointer = Symbol('pointer');
/**
* A reference to a location in an object graph.
*
* This type is used by this module to break cycles in an object graph and to
* reference locations that have already been visited when enumerating pointers.
*/
export class JsonReference {
/**
* Determines if the specified `candidate` is a JsonReference.
* @param candidate the candidate
*/
static isReference(candidate: unknown): candidate is JsonReference {
if (!candidate) return false;
const ref = candidate as unknown as JsonReference;
return typeof ref.$ref === 'string' && typeof ref.resolve === 'function';
}
/** @hidden */
private readonly [$pointer]: JsonPointer;
/**
* A reference to a position if an object graph.
*/
public readonly $ref: UriFragmentIdentifierPointer;
/**
* Creates a new instance.
* @param pointer a JSON Pointer for the reference.
*/
constructor(pointer: JsonPointer | Pointer | PathSegments) {
this[$pointer] =
pointer instanceof JsonPointer ? pointer : new JsonPointer(pointer);
this.$ref = this[$pointer].uriFragmentIdentifier;
}
/**
* Resolves the reference against the `target` object, returning the value at
* the referenced pointer's location.
* @param target the target object
*/
resolve(target: unknown): unknown {
return this[$pointer].get(target);
}
/**
* Gets the reference's pointer.
*/
pointer(): JsonPointer {
return this[$pointer];
}
/**
* Gets the reference pointer's string representation (a URI fragment identifier).
*/
toString(): string {
return this.$ref;
}
}