-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathStructUtility.ts
More file actions
3123 lines (2632 loc) · 81.7 KB
/
StructUtility.ts
File metadata and controls
3123 lines (2632 loc) · 81.7 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
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
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2025-2026 Voxgig Ltd. MIT LICENSE. */
// VERSION: @voxgig/struct 0.1.0
/* Voxgig Struct
* =============
*
* Utility functions to manipulate in-memory JSON-like data
* structures. These structures assumed to be composed of nested
* "nodes", where a node is a list or map, and has named or indexed
* fields. The general design principle is "by-example". Transform
* specifications mirror the desired output. This implementation is
* designed for porting to multiple language, and to be tolerant of
* undefined values.
*
* Main utilities
* - getpath: get the value at a key path deep inside an object.
* - merge: merge multiple nodes, overriding values in earlier nodes.
* - walk: walk a node tree, applying a function at each node and leaf.
* - inject: inject values from a data store into a new data structure.
* - transform: transform a data structure to an example structure.
* - validate: valiate a data structure against a shape specification.
*
* Minor utilities
* - isnode, islist, ismap, iskey, isfunc: identify value kinds.
* - isempty: undefined values, or empty nodes.
* - keysof: sorted list of node keys (ascending).
* - haskey: true if key value is defined.
* - clone: create a copy of a JSON-like data structure.
* - items: list entries of a map or list as [key, value] pairs.
* - getprop: safely get a property value by key.
* - setprop: safely set a property value by key.
* - stringify: human-friendly string version of a value.
* - escre: escape a regular expresion string.
* - escurl: escape a url.
* - join: join parts of a url, merging forward slashes.
*
* This set of functions and supporting utilities is designed to work
* uniformly across many languages, meaning that some code that may be
* functionally redundant in specific languages is still retained to
* keep the code human comparable.
*
* NOTE: Lists are assumed to be mutable and reference stable.
*
* NOTE: In this code JSON nulls are in general *not* considered the
* same as the undefined value in the given language. However most
* JSON parsers do use the undefined value to represent JSON
* null. This is ambiguous as JSON null is a separate value, not an
* undefined value. You should convert such values to a special value
* to represent JSON null, if this ambiguity creates issues
* (thankfully in most APIs, JSON nulls are not used). For example,
* the unit tests use the string "__NULL__" where necessary.
*
*/
// String constants are explicitly defined.
// Mode value for inject step (bitfield).
const M_KEYPRE = 1
const M_KEYPOST = 2
const M_VAL = 4
// Special strings.
const S_BKEY = '`$KEY`'
const S_BANNO = '`$ANNO`'
const S_BEXACT = '`$EXACT`'
const S_BVAL = '`$VAL`'
const S_DKEY = '$KEY'
const S_DTOP = '$TOP'
const S_DERRS = '$ERRS'
const S_DSPEC = '$SPEC'
// General strings.
const S_list = 'list'
const S_base = 'base'
const S_boolean = 'boolean'
const S_function = 'function'
const S_symbol = 'symbol'
const S_instance = 'instance'
const S_key = 'key'
const S_any = 'any'
const S_nil = 'nil'
const S_null = 'null'
const S_number = 'number'
const S_object = 'object'
const S_string = 'string'
const S_decimal = 'decimal'
const S_integer = 'integer'
const S_map = 'map'
const S_scalar = 'scalar'
const S_node = 'node'
// Character strings.
const S_BT = '`'
const S_CN = ':'
const S_CS = ']'
const S_DS = '$'
const S_DT = '.'
const S_FS = '/'
const S_KEY = 'KEY'
const S_MT = ''
const S_OS = '['
const S_SP = ' '
const S_CM = ','
const S_VIZ = ': '
// Types
let t = 31
const T_any = (1 << t--) - 1
const T_noval = 1 << t-- // Means property absent, undefined. Also NOT a scalar!
const T_boolean = 1 << t--
const T_decimal = 1 << t--
const T_integer = 1 << t--
const T_number = 1 << t--
const T_string = 1 << t--
const T_function = 1 << t--
const T_symbol = 1 << t--
const T_null = 1 << t-- // The actual JSON null value.
t -= 7
const T_list = 1 << t--
const T_map = 1 << t--
const T_instance = 1 << t--
t -= 4
const T_scalar = 1 << t--
const T_node = 1 << t--
const TYPENAME = [
S_any,
S_nil,
S_boolean,
S_decimal,
S_integer,
S_number,
S_string,
S_function,
S_symbol,
S_null,
'',
'',
'',
'',
'',
'',
'',
S_list,
S_map,
S_instance,
'',
'',
'',
'',
S_scalar,
S_node,
]
// The standard undefined value for this language.
const NONE = undefined
// Private markers
const SKIP = { '`$SKIP`': true }
const DELETE = { '`$DELETE`': true }
// Regular expression constants
const R_INTEGER_KEY = /^[-0-9]+$/ // Match integer keys (including <0).
const R_ESCAPE_REGEXP = /[.*+?^${}()|[\]\\]/g // Chars that need escaping in regexp.
const R_QUOTES = /"/g // Double quotes for removal.
const R_DOT = /\./g // Dots in path strings.
const R_CLONE_REF = /^`\$REF:([0-9]+)`$/ // Copy reference in cloning.
const R_META_PATH = /^([^$]+)\$([=~])(.+)$/ // Meta path syntax.
const R_DOUBLE_DOLLAR = /\$\$/g // Double dollar escape sequence.
const R_TRANSFORM_NAME = /`\$([A-Z]+)`/g // Transform command names.
const R_INJECTION_FULL = /^`(\$[A-Z]+|[^`]*)[0-9]*`$/ // Full string injection pattern.
const R_BT_ESCAPE = /\$BT/g // Backtick escape sequence.
const R_DS_ESCAPE = /\$DS/g // Dollar sign escape sequence.
const R_INJECTION_PARTIAL = /`([^`]+)`/g // Partial string injection pattern.
// Default max depth (for walk etc).
const MAXDEPTH = 32
// Keys are strings for maps, or integers for lists.
type PropKey = string | number
// Type that can be indexed by both string and number keys.
type Indexable = { [key: string]: any } & { [key: number]: any }
// For each key in a node (map or list), perform value injections in
// three phases: on key value, before child, and then on key value again.
// This mode is passed via the Injection structure.
type InjectMode = number
// Handle value injections using backtick escape sequences:
// - `a.b.c`: insert value at {a:{b:{c:1}}}
// - `$FOO`: apply transform FOO
type Injector = (
inj: Injection, // Injection state.
val: any, // Injection value specification.
ref: string, // Original injection reference string.
store: any, // Current source root value.
) => any
// Apply a custom modification to injections.
type Modify = (
val: any, // Value.
key?: PropKey, // Value key, if any,
parent?: any, // Parent node, if any.
inj?: Injection, // Injection state, if any.
store?: any, // Store, if any
) => void
// Function applied to each node and leaf when walking a node structure depth first.
// For {a:{b:1}} the call sequence args will be: b, 1, {b:1}, [a,b].
// NOTE: the `path` array passed to the callback is reused across calls during
// a single walk (one shared array per depth). It is valid only for the
// duration of the callback invocation. If a callback needs to retain the
// path, it MUST clone it (e.g. `path.slice()`).
type WalkApply = (
// Map keys are strings, list keys are numbers, top key is NONE
key: string | number | undefined,
val: any,
parent: any,
path: string[],
) => any
// Return type string for narrowest type.
function typename(t: number) {
return getelem(TYPENAME, Math.clz32(t), TYPENAME[0])
}
// Get a defined value. Returns alt if val is undefined.
function getdef(val: any, alt: any) {
if (NONE === val) {
return alt
}
return val
}
// Value is a node - defined, and a map (hash) or list (array).
// NOTE: typescript
// things
function isnode(val: any): val is Indexable {
return null != val && S_object == typeof val
}
// Value is a defined map (hash) with string keys.
function ismap(val: any): val is { [key: string]: any } {
return null != val && S_object == typeof val && !Array.isArray(val)
}
// Value is a defined list (array) with integer keys (indexes).
function islist(val: any): val is any[] {
return Array.isArray(val)
}
// Value is a defined string (non-empty) or integer key.
function iskey(key: any): key is PropKey {
const keytype = typeof key
return (S_string === keytype && S_MT !== key) || S_number === keytype
}
// Check for an "empty" value - undefined, empty string, array, object.
function isempty(val: any) {
return (
null == val ||
S_MT === val ||
(Array.isArray(val) && 0 === val.length) ||
(S_object === typeof val && 0 === Object.keys(val).length)
)
}
// Value is a function.
function isfunc(val: any): val is (...args: any[]) => any {
return S_function === typeof val
}
// The integer size of the value. For arrays and strings, the length,
// for numbers, the integer part, for boolean, true is 1 and falso 0, for all other values, 0.
function size(val: any): number {
if (islist(val)) {
return val.length
} else if (ismap(val)) {
return Object.keys(val).length
}
const valtype = typeof val
if (S_string == valtype) {
return val.length
} else if (S_number == typeof val) {
return Math.floor(val)
} else if (S_boolean == typeof val) {
return true === val ? 1 : 0
} else {
return 0
}
}
// Extract part of an array or string into a new value, from the start
// point to the end point. If no end is specified, extract to the
// full length of the value. Negative arguments count from the end of
// the value. For numbers, perform min and max bounding, where start
// is inclusive, and end is *exclusive*.
// NOTE: input lists are not mutated by default. Use the mutate
// argument to mutate lists in place.
function slice<V>(val: V, start?: number, end?: number, mutate?: boolean): V {
if (S_number === typeof val) {
start = null == start || S_number !== typeof start ? Number.MIN_SAFE_INTEGER : start
end = (null == end || S_number !== typeof end ? Number.MAX_SAFE_INTEGER : end) - 1
return Math.min(Math.max(val as number, start), end) as V
}
const vlen = size(val)
if (null != end && null == start) {
start = 0
}
if (null != start) {
if (start < 0) {
end = vlen + start
if (end < 0) {
end = 0
}
start = 0
} else if (null != end) {
if (end < 0) {
end = vlen + end
if (end < 0) {
end = 0
}
} else if (vlen < end) {
end = vlen
}
} else {
end = vlen
}
if (vlen < start) {
start = vlen
}
if (-1 < start && start <= end && end <= vlen) {
if (islist(val)) {
if (mutate) {
for (let i = 0, j = start; j < end; i++, j++) {
val[i] = val[j]
}
val.length = end - start
} else {
val = val.slice(start, end) as V
}
} else if (S_string === typeof val) {
val = (val as string).substring(start, end) as V
}
} else {
if (islist(val)) {
val = [] as V
} else if (S_string === typeof val) {
val = S_MT as V
}
}
}
return val
}
// String padding.
function pad(str: any, padding?: number, padchar?: string): string {
str = S_string === typeof str ? str : stringify(str)
padding = null == padding ? 44 : padding
padchar = null == padchar ? S_SP : (padchar + S_SP)[0]
return -1 < padding ? str.padEnd(padding, padchar) : str.padStart(0 - padding, padchar)
}
// Determine the type of a value as a bit code.
function typify(value: any): number {
if (undefined === value) {
return T_noval
}
const typestr = typeof value
if (null === value) {
return T_scalar | T_null
} else if (S_number === typestr) {
if (Number.isInteger(value)) {
return T_scalar | T_number | T_integer
} else if (isNaN(value)) {
return T_noval
} else {
return T_scalar | T_number | T_decimal
}
} else if (S_string === typestr) {
return T_scalar | T_string
} else if (S_boolean === typestr) {
return T_scalar | T_boolean
} else if (S_function === typestr) {
return T_scalar | T_function
}
// For languages that have symbolic atoms.
else if (S_symbol === typestr) {
return T_scalar | T_symbol
} else if (Array.isArray(value)) {
return T_node | T_list
} else if (S_object === typestr) {
if (value.constructor instanceof Function) {
const cname = value.constructor.name
if ('Object' !== cname && 'Array' !== cname) {
return T_node | T_instance
}
}
return T_node | T_map
}
// Anything else (e.g. bigint) is considered T_any
return T_any
}
// Get a list element. The key should be an integer, or a string
// that can parse to an integer only. Negative integers count from the end of the list.
function getelem(val: any, key: any, alt?: any) {
let out = NONE
if (NONE === val || NONE === key) {
return alt
}
if (islist(val)) {
const nkey = parseInt(key)
if (Number.isInteger(nkey) && re_test(R_INTEGER_KEY, '' + key)) {
if (nkey < 0) {
key = val.length + nkey
}
out = val[key]
}
}
// null at a slot counts as "no value" — same Group A rule as getprop.
if (null == out) {
return 0 < (T_function & typify(alt)) ? alt() : alt
}
return out
}
// Safely get a property of a node. Undefined arguments return undefined.
// If the key is not found, return the alternative value, if any.
function getprop(val: any, key: any, alt?: any) {
let out = alt
if (NONE === val || NONE === key) {
return alt
}
if (isnode(val)) {
out = val[key]
}
// JSON null at a key is treated as "no value" for the default-substitution
// rule. This unifies cross-port behaviour: every host language conflates
// null and absent at the value level either always or via positional
// checks; the library follows that constraint on observation.
if (null == out) {
return alt
}
return out
}
// Internal: literal value lookup that preserves stored JSON null. Group B
// callers (validate / transform commands / builders / inject internals) use
// this when they need to inspect the raw stored value at a slot regardless
// of whether it is null. The public getprop / getelem / haskey APIs treat
// null as absent (Group A) per UNDEF_SPEC.md.
function _lookup(val: any, key: any): any {
if (NONE === val || NONE === key) return NONE
if (isnode(val)) return val[key]
return NONE
}
// Convert different types of keys to string representation.
// String keys are returned as is.
// Number keys are converted to strings.
// Floats are truncated to integers.
// Booleans, objects, arrays, null, undefined all return empty string.
function strkey(key: any = NONE): string {
if (NONE === key) {
return S_MT
}
const t = typify(key)
if (0 < (T_string & t)) {
return key
} else if (0 < (T_boolean & t)) {
return S_MT
} else if (0 < (T_number & t)) {
return key % 1 === 0 ? String(key) : String(Math.floor(key))
}
return S_MT
}
// Sorted keys of a map, or indexes (as strings) of a list.
// Root utility - only uses language facilities.
function keysof(val: any): string[] {
return !isnode(val)
? []
: ismap(val)
? Object.keys(val).sort()
: (val as any).map((_n: any, i: number) => S_MT + i)
}
// Value of property with name key in node val is defined.
// Root utility - only uses language facilities.
function haskey(val: any, key: any) {
// null at a key counts as "no value" — same rule as getprop.
return null != getprop(val, key)
}
// List the sorted keys of a map or list as an array of tuples of the form [key, value].
// As with keysof, list indexes are converted to strings.
// Root utility - only uses language facilities.
function items(val: any): [string, any][]
function items<T>(val: any, apply: (item: [string, any]) => T): T[]
function items(val: any, apply?: (item: [string, any]) => any): any[] {
let out: [string, any][] = keysof(val).map((k: any) => [k, val[k]])
if (null != apply) {
out = out.map(apply)
}
return out
}
// To replicate the array spread operator:
// a=1, b=[2,3], c=[4,5]
// [a,...b,c] -> [1,2,3,[4,5]]
// flatten([a,b,[c]]) -> [1,2,3,[4,5]]
// NOTE: [c] ensures c is not expanded
function flatten(list: any[], depth?: number) {
if (!islist(list)) {
return list
}
return list.flat(getdef(depth, 1))
}
// Filter item values using check function.
function filter(val: any, check: (item: [string, any]) => boolean): any[] {
const all = items(val)
const numall = size(all)
const out = []
for (let i = 0; i < numall; i++) {
if (check(all[i])) {
out.push(all[i][1])
}
}
return out
}
// Escape regular expression.
function escre(s: string) {
return re_replace(R_ESCAPE_REGEXP, s, '\\$&')
}
// Alias so call sites read naturally next to the other re_* helpers.
function re_escape(s: string) {
return escre(s)
}
// Escape URLs.
function escurl(s: string) {
s = null == s ? S_MT : s
return encodeURIComponent(s)
}
// ===========================================================================
// Regex utility — uniform API. Every port exposes these same names. The
// dialect is the RE2 subset documented in /REGEX.md. Internal library code
// uses these helpers instead of host-language regex methods directly.
// ===========================================================================
// Compile a regex (or return as-is if already compiled). Cached behaviour is
// up to the port; in TS we just construct a RegExp.
function re_compile(pattern: string | RegExp, flags?: string): RegExp {
if (pattern instanceof RegExp) {
return pattern
}
return new RegExp(pattern, flags)
}
// First match. Returns [whole, capture1, ...] or null.
function re_find(pattern: string | RegExp, input: string): RegExpMatchArray | null {
const re = pattern instanceof RegExp ? pattern : new RegExp(pattern)
return input.match(re)
}
// All non-overlapping matches, left to right. Each element is the same shape
// as re_find's array.
function re_find_all(pattern: string | RegExp, input: string): RegExpMatchArray[] {
let re: RegExp
if (pattern instanceof RegExp) {
re = pattern.global ? pattern : new RegExp(pattern.source, pattern.flags + 'g')
} else {
re = new RegExp(pattern, 'g')
}
const out: RegExpMatchArray[] = []
let m: RegExpExecArray | null
while ((m = re.exec(input)) !== null) {
out.push(m as unknown as RegExpMatchArray)
if (m[0] === '') re.lastIndex++ // avoid infinite loop on empty match
}
return out
}
// Replace every match. `replacement` is either a string (with $& and $1..$9)
// or a callback receiving the same array as re_find returns.
function re_replace(
pattern: string | RegExp,
input: string,
replacement: string | ((m: RegExpMatchArray) => string),
): string {
let re: RegExp
if (pattern instanceof RegExp) {
re = pattern.global ? pattern : new RegExp(pattern.source, pattern.flags + 'g')
} else {
re = new RegExp(pattern, 'g')
}
if (typeof replacement === 'function') {
return input.replace(re, (...args: any[]) => {
// Strip the trailing offset + full string args String.prototype.replace passes.
// The callback below receives just the capture groups (whole at [0]).
const groups = args.slice(0, -2) as unknown as RegExpMatchArray
return replacement(groups)
})
}
return input.replace(re, replacement)
}
// Boolean test for any match.
function re_test(pattern: string | RegExp, input: string): boolean {
const re = pattern instanceof RegExp ? pattern : new RegExp(pattern)
return re.test(input)
}
// Replace a search string (all), or a regexp, in a source string.
function replace(s: string, from: string | RegExp, to: any) {
let rs = s
const ts = typify(s)
if (0 === (T_string & ts)) {
rs = stringify(s)
} else if (0 < ((T_noval | T_null) & ts)) {
rs = S_MT
} else {
rs = stringify(s)
}
return rs.replace(from, to)
}
// Concatenate url part strings, merging sep char as needed.
function join(arr: any[], sep?: string, url?: boolean) {
const sarr = size(arr)
const sepdef = getdef(sep, S_CM)
const sepre = 1 === size(sepdef) ? escre(sepdef) : NONE
const out = filter(
items(
// filter(arr, (n) => null != n[1] && S_MT !== n[1]),
filter(arr, (n) => 0 < (T_string & typify(n[1])) && S_MT !== n[1]),
(n) => {
const i = +n[0]
let s = n[1]
if (NONE !== sepre && S_MT !== sepre) {
if (url && 0 === i) {
s = re_replace(re_compile(sepre + '+$'), s, S_MT)
return s
}
if (0 < i) {
s = re_replace(re_compile('^' + sepre + '+'), s, S_MT)
}
if (i < sarr - 1 || !url) {
s = re_replace(re_compile(sepre + '+$'), s, S_MT)
}
s = re_replace(
re_compile('([^' + sepre + '])' + sepre + '+([^' + sepre + '])'),
s,
'$1' + sepdef + '$2',
)
}
return s
},
),
(n) => S_MT !== n[1],
).join(sepdef)
return out
}
// Output JSON in a "standard" format, with 2 space indents, each property on a new line,
// and spaces after {[: and before ]}. Any "wierd" values (NaN, etc) are output as null.
// In general, the behaivor of of JavaScript's JSON.stringify(val,null,2) is followed.
function jsonify(val: any, flags?: { indent?: number; offset?: number }) {
let str = S_null
if (null != val) {
try {
const indent = getprop(flags, 'indent', 2)
str = JSON.stringify(val, null, indent)
if (NONE === str) {
str = S_null
}
const offset = getprop(flags, 'offset', 0)
if (0 < offset) {
// Left offset entire indented JSON so that it aligns with surrounding code
// indented by offset. Assume first brace is on line with asignment, so not offset.
str =
'{\n' +
join(
items(slice(str.split('\n'), 1), (n: any) => pad(n[1], 0 - offset - size(n[1]))),
'\n',
)
}
} catch {
str = '__JSONIFY_FAILED__'
}
}
return str
}
// Safely stringify a value for humans (NOT JSON!).
function stringify(val: any, maxlen?: number, pretty?: any): string {
let valstr = S_MT
pretty = !!pretty
if (NONE === val) {
return pretty ? '<>' : valstr
}
if (S_string === typeof val) {
valstr = val
} else {
try {
valstr = JSON.stringify(val, function (_key: string, val: any) {
if (val !== null && typeof val === 'object' && !Array.isArray(val)) {
const sortedObj: any = {}
items(val, (n) => {
sortedObj[n[0]] = val[n[0]]
})
return sortedObj
}
return val
})
valstr = re_replace(R_QUOTES, valstr, S_MT)
} catch {
valstr = '__STRINGIFY_FAILED__'
}
}
if (null != maxlen && -1 < maxlen) {
const js = valstr.substring(0, maxlen)
valstr = maxlen < valstr.length ? js.substring(0, maxlen - 3) + '...' : valstr
}
if (pretty) {
// Indicate deeper JSON levels with different terminal colors (simplistic wrt strings).
const c = items(
[81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69],
(n) => '\x1b[38;5;' + n[1] + 'm',
)
const r = '\x1b[0m'
let d = 0,
o = c[0],
t = o
for (const ch of valstr) {
if (ch === '{' || ch === '[') {
d++
o = c[d % c.length]
t += o + ch
} else if (ch === '}' || ch === ']') {
t += o + ch
d--
o = c[d % c.length]
} else {
t += o + ch
}
}
return t + r
}
return valstr
}
// Build a human friendly path string.
function pathify(val: any, startin?: number, endin?: number) {
let pathstr: string | undefined = NONE
let path: any[] | undefined = islist(val)
? val
: S_string == typeof val
? [val]
: S_number == typeof val
? [val]
: NONE
const start = null == startin ? 0 : -1 < startin ? startin : 0
const end = null == endin ? 0 : -1 < endin ? endin : 0
if (NONE != path && 0 <= start) {
path = slice(path, start, path.length - end)
if (0 === path.length) {
pathstr = '<root>'
} else {
pathstr = join(
items(
filter(path, (n) => iskey(n[1])),
(n) => {
const p = n[1]
return S_number === typeof p ? S_MT + Math.floor(p) : re_replace(R_DOT, p, S_MT)
},
),
S_DT,
)
}
}
if (NONE === pathstr) {
pathstr = '<unknown-path' + (NONE === val ? S_MT : S_CN + stringify(val, 47)) + '>'
}
return pathstr
}
// Clone a JSON-like data structure.
// NOTE: function and instance values are copied, *not* cloned.
function clone(val: any): any {
const refs: any[] = []
const reftype = T_function | T_instance
const replacer: any = (_k: any, v: any) =>
0 < (reftype & typify(v)) ? (refs.push(v), '`$REF:' + (refs.length - 1) + '`') : v
const reviver: any = (_k: any, v: any, m: any) =>
S_string === typeof v ? ((m = re_find(R_CLONE_REF, v)), m ? refs[m[1]] : v) : v
const out = NONE === val ? NONE : JSON.parse(JSON.stringify(val, replacer), reviver)
return out
}
// Define a JSON Object using function arguments.
function jm(...kv: any[]): Record<string, any> {
const kvsize = size(kv)
const o: any = {}
for (let i = 0; i < kvsize; i += 2) {
// Builders are Group B (value processing): preserve literal stored
// values, including null. Direct array index distinguishes "slot exists
// with value null" from "slot beyond end of kv".
let k = i < kv.length ? kv[i] : '$KEY' + i
k = 'string' === typeof k ? k : stringify(k)
o[k] = i + 1 < kv.length ? kv[i + 1] : null
}
return o
}
// Define a JSON Array using function arguments.
function jt(...v: any[]): any[] {
const vsize = size(v)
const a: any = new Array(vsize)
for (let i = 0; i < vsize; i++) {
a[i] = getprop(v, i, null)
}
return a
}
// Safely delete a property from an object or array element.
// Undefined arguments and invalid keys are ignored.
// Returns the (possibly modified) parent.
// For objects, the property is deleted using the delete operator.
// For arrays, the element at the index is removed and remaining elements are shifted down.
// NOTE: parent list may be new list, thus update references.
function delprop<PARENT>(parent: PARENT, key: any): PARENT {
if (!iskey(key)) {
return parent
}
if (ismap(parent)) {
key = strkey(key)
delete (parent as any)[key]
} else if (islist(parent)) {
// Ensure key is an integer.
let keyI = +key
if (isNaN(keyI)) {
return parent
}
keyI = Math.floor(keyI)
// Delete list element at position keyI, shifting later elements down.
const psize = size(parent)
if (0 <= keyI && keyI < psize) {
for (let pI = keyI; pI < psize - 1; pI++) {
parent[pI] = parent[pI + 1]
}
parent.length = parent.length - 1
}
}
return parent
}
// Safely set a property. Undefined arguments and invalid keys are ignored.
// Returns the (possibly modified) parent.
// If the parent is a list, and the key is negative, prepend the value.
// NOTE: If the key is above the list size, append the value; below, prepend.
// NOTE: parent list may be new list, thus update references.
function setprop<PARENT>(parent: PARENT, key: any, val: any): PARENT {
if (!iskey(key)) {
return parent
}
if (ismap(parent)) {
key = S_MT + key
const pany = parent as any
pany[key] = val
} else if (islist(parent)) {
// Ensure key is an integer.
let keyI = +key
if (isNaN(keyI)) {
return parent
}
keyI = Math.floor(keyI)
// TODO: DELETE list element
// Set or append value at position keyI, or append if keyI out of bounds.
if (0 <= keyI) {
parent[slice(keyI, 0, size(parent) + 1)] = val
}
// Prepend value if keyI is negative
else {
parent.unshift(val)
}
}
return parent
}
// Walk a data structure depth first, applying a function to each value.
// The `path` argument passed to the before/after callbacks is a single
// mutable array per depth, shared across all callback invocations for the
// lifetime of this top-level walk call. Callbacks that need to store the
// path MUST clone it (e.g. `path.slice()`); the contents will otherwise
// be overwritten by subsequent visits.
function walk(
// These arguments are the public interface.
val: any,
// Before descending into a node.
before?: WalkApply,
// After descending into a node.
after?: WalkApply,
// Maximum recursive depth, default: 32. Use null for infinite depth.
maxdepth?: number,
// These areguments are used for recursive state.
key?: string | number,
parent?: any,
path?: string[],
pool?: string[][],
): any {
if (NONE === pool) {
pool = [[]]
}
if (NONE === path) {
path = pool[0]
}
const depth = path.length
let out = null == before ? val : before(key, val, parent, path)
maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : MAXDEPTH
if (0 === maxdepth || (0 < maxdepth && maxdepth <= depth)) {
return out
}
if (isnode(out)) {
const childDepth = depth + 1
let childPath = pool[childDepth]
if (NONE === childPath) {
childPath = new Array(childDepth)
pool[childDepth] = childPath