@voxgig/struct 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- /* Copyright (c) 2025 Voxgig Ltd. MIT LICENSE. */
1
+ /* Copyright (c) 2025-2026 Voxgig Ltd. MIT LICENSE. */
2
2
 
3
- // VERSION: @voxgig/struct 0.0.9
3
+ // VERSION: @voxgig/struct 0.0.10
4
4
 
5
5
  /* Voxgig Struct
6
6
  * =============
@@ -33,13 +33,15 @@
33
33
  * - stringify: human-friendly string version of a value.
34
34
  * - escre: escape a regular expresion string.
35
35
  * - escurl: escape a url.
36
- * - joinurl: join parts of a url, merging forward slashes.
36
+ * - join: join parts of a url, merging forward slashes.
37
37
  *
38
38
  * This set of functions and supporting utilities is designed to work
39
39
  * uniformly across many languages, meaning that some code that may be
40
40
  * functionally redundant in specific languages is still retained to
41
41
  * keep the code human comparable.
42
42
  *
43
+ * NOTE: Lists are assumed to be mutable and reference stable.
44
+ *
43
45
  * NOTE: In this code JSON nulls are in general *not* considered the
44
46
  * same as the undefined value in the given language. However most
45
47
  * JSON parsers do use the undefined value to represent JSON
@@ -54,16 +56,16 @@
54
56
 
55
57
  // String constants are explicitly defined.
56
58
 
57
- // Mode value for inject step.
58
- const S_MKEYPRE = 'key:pre'
59
- const S_MKEYPOST = 'key:post'
60
- const S_MVAL = 'val'
61
- const S_MKEY = 'key'
59
+ // Mode value for inject step (bitfield).
60
+ const M_KEYPRE = 1
61
+ const M_KEYPOST = 2
62
+ const M_VAL = 4
62
63
 
63
- // Special keys.
64
+ // Special strings.
64
65
  const S_BKEY = '`$KEY`'
65
66
  const S_BANNO = '`$ANNO`'
66
67
  const S_BEXACT = '`$EXACT`'
68
+ const S_BVAL = '`$VAL`'
67
69
 
68
70
  const S_DKEY = '$KEY'
69
71
  const S_DTOP = '$TOP'
@@ -71,16 +73,26 @@ const S_DERRS = '$ERRS'
71
73
  const S_DSPEC = '$SPEC'
72
74
 
73
75
  // General strings.
74
- const S_array = 'array'
76
+ const S_list = 'list'
75
77
  const S_base = 'base'
76
78
  const S_boolean = 'boolean'
77
79
  const S_function = 'function'
80
+ const S_symbol = 'symbol'
78
81
  const S_instance = 'instance'
79
82
  const S_key = 'key'
83
+ const S_any = 'any'
84
+ const S_nil = 'nil'
80
85
  const S_null = 'null'
81
86
  const S_number = 'number'
82
87
  const S_object = 'object'
83
88
  const S_string = 'string'
89
+ const S_decimal = 'decimal'
90
+ const S_integer = 'integer'
91
+ const S_map = 'map'
92
+ const S_scalar = 'scalar'
93
+ const S_node = 'node'
94
+
95
+ // Character strings.
84
96
  const S_BT = '`'
85
97
  const S_CN = ':'
86
98
  const S_CS = ']'
@@ -91,14 +103,57 @@ const S_KEY = 'KEY'
91
103
  const S_MT = ''
92
104
  const S_OS = '['
93
105
  const S_SP = ' '
106
+ const S_CM = ','
94
107
  const S_VIZ = ': '
95
108
 
109
+ // Types
110
+ let t = 31
111
+ const T_any = (1 << t--) - 1
112
+ const T_noval = 1 << t-- // Means property absent, undefined. Also NOT a scalar!
113
+ const T_boolean = 1 << t--
114
+ const T_decimal = 1 << t--
115
+ const T_integer = 1 << t--
116
+ const T_number = 1 << t--
117
+ const T_string = 1 << t--
118
+ const T_function = 1 << t--
119
+ const T_symbol = 1 << t--
120
+ const T_null = 1 << t-- // The actual JSON null value.
121
+ t -= 7
122
+ const T_list = 1 << t--
123
+ const T_map = 1 << t--
124
+ const T_instance = 1 << t--
125
+ t -= 4
126
+ const T_scalar = 1 << t--
127
+ const T_node = 1 << t--
128
+
129
+ const TYPENAME = [
130
+ S_any,
131
+ S_nil,
132
+ S_boolean,
133
+ S_decimal,
134
+ S_integer,
135
+ S_number,
136
+ S_string,
137
+ S_function,
138
+ S_symbol,
139
+ S_null,
140
+ '', '', '',
141
+ '', '', '', '',
142
+ S_list,
143
+ S_map,
144
+ S_instance,
145
+ '', '', '', '',
146
+ S_scalar,
147
+ S_node,
148
+ ]
96
149
 
97
150
  // The standard undefined value for this language.
98
- const UNDEF = undefined
151
+ const NONE = undefined
99
152
 
100
- // Private marker to indicate a skippable value.
153
+ // Private markers
101
154
  const SKIP = { '`$SKIP`': true }
155
+ const DELETE = { '`$DELETE`': true }
156
+
102
157
 
103
158
  // Regular expression constants
104
159
  const R_INTEGER_KEY = /^[-0-9]+$/ // Match integer keys (including <0).
@@ -108,7 +163,7 @@ const R_LEADING_TRAILING_SLASH = /([^\/])\/+/ // Multiple slashes in UR
108
163
  const R_LEADING_SLASH = /^\/+/ // Leading slashes in URLs.
109
164
  const R_QUOTES = /"/g // Double quotes for removal.
110
165
  const R_DOT = /\./g // Dots in path strings.
111
- const R_FUNCTION_REF = /^`\$FUNCTION:([0-9]+)`$/ // Function reference in clone.
166
+ const R_CLONE_REF = /^`\$REF:([0-9]+)`$/ // Copy reference in cloning.
112
167
  const R_META_PATH = /^([^$]+)\$([=~])(.+)$/ // Meta path syntax.
113
168
  const R_DOUBLE_DOLLAR = /\$\$/g // Double dollar escape sequence.
114
169
  const R_TRANSFORM_NAME = /`\$([A-Z]+)`/g // Transform command names.
@@ -117,6 +172,8 @@ const R_BT_ESCAPE = /\$BT/g // Backtick escape sequen
117
172
  const R_DS_ESCAPE = /\$DS/g // Dollar sign escape sequence.
118
173
  const R_INJECTION_PARTIAL = /`([^`]+)`/g // Partial string injection pattern.
119
174
 
175
+ // Default max depth (for walk etc).
176
+ const MAXDEPTH = 32
120
177
 
121
178
  // Keys are strings for maps, or integers for lists.
122
179
  type PropKey = string | number
@@ -128,8 +185,7 @@ type Indexable = { [key: string]: any } & { [key: number]: any }
128
185
  // For each key in a node (map or list), perform value injections in
129
186
  // three phases: on key value, before child, and then on key value again.
130
187
  // This mode is passed via the Injection structure.
131
- type InjectMode = 'key:pre' | 'key:post' | 'val'
132
-
188
+ type InjectMode = number
133
189
 
134
190
  // Handle value injections using backtick escape sequences:
135
191
  // - `a.b.c`: insert value at {a:{b:{c:1}}}
@@ -141,7 +197,6 @@ type Injector = (
141
197
  store: any, // Current source root value.
142
198
  ) => any
143
199
 
144
-
145
200
  // Apply a custom modification to injections.
146
201
  type Modify = (
147
202
  val: any, // Value.
@@ -151,11 +206,10 @@ type Modify = (
151
206
  store?: any, // Store, if any
152
207
  ) => void
153
208
 
154
-
155
209
  // Function applied to each node and leaf when walking a node structure depth first.
156
210
  // For {a:{b:1}} the call sequence args will be: b, 1, {b:1}, [a,b].
157
211
  type WalkApply = (
158
- // Map keys are strings, list keys are numbers, top key is UNDEF
212
+ // Map keys are strings, list keys are numbers, top key is NONE
159
213
  key: string | number | undefined,
160
214
  val: any,
161
215
  parent: any,
@@ -163,6 +217,20 @@ type WalkApply = (
163
217
  ) => any
164
218
 
165
219
 
220
+ // Return type string for narrowest type.
221
+ function typename(t: number) {
222
+ return getelem(TYPENAME, Math.clz32(t), TYPENAME[0])
223
+ }
224
+
225
+
226
+ // Get a defined value. Returns alt if val is undefined.
227
+ function getdef(val: any, alt: any) {
228
+ if (NONE === val) {
229
+ return alt
230
+ }
231
+ return val
232
+ }
233
+
166
234
 
167
235
  // Value is a node - defined, and a map (hash) or list (array).
168
236
  // NOTE: typescript
@@ -232,11 +300,14 @@ function size(val: any): number {
232
300
  }
233
301
 
234
302
 
235
- // Extract part of an array or string into a new value, from the start point to the end point.
236
- // If no end is specified, extract to the full length of the value. Negative arguments count
237
- // from the end of the value. For numbers, perform min and max bounding, where start is
238
- // inclusive, and end is *exclusive*.
239
- function slice<V extends any>(val: V, start?: number, end?: number): V {
303
+ // Extract part of an array or string into a new value, from the start
304
+ // point to the end point. If no end is specified, extract to the
305
+ // full length of the value. Negative arguments count from the end of
306
+ // the value. For numbers, perform min and max bounding, where start
307
+ // is inclusive, and end is *exclusive*.
308
+ // NOTE: input lists are not mutated by default. Use the mutate
309
+ // argument to mutate lists in place.
310
+ function slice<V extends any>(val: V, start?: number, end?: number, mutate?: boolean): V {
240
311
  if (S_number === typeof val) {
241
312
  start = null == start || S_number !== typeof start ? Number.MIN_SAFE_INTEGER : start
242
313
  end = (null == end || S_number !== typeof end ? Number.MAX_SAFE_INTEGER : end) - 1
@@ -280,7 +351,15 @@ function slice<V extends any>(val: V, start?: number, end?: number): V {
280
351
 
281
352
  if (-1 < start && start <= end && end <= vlen) {
282
353
  if (islist(val)) {
283
- val = val.slice(start, end) as V
354
+ if (mutate) {
355
+ for (let i = 0, j = start; j < end; i++, j++) {
356
+ val[i] = val[j]
357
+ }
358
+ val.length = (end - start)
359
+ }
360
+ else {
361
+ val = val.slice(start, end) as V
362
+ }
284
363
  }
285
364
  else if (S_string === typeof val) {
286
365
  val = (val as string).substring(start, end) as V
@@ -300,6 +379,7 @@ function slice<V extends any>(val: V, start?: number, end?: number): V {
300
379
  }
301
380
 
302
381
 
382
+ // String padding.
303
383
  function pad(str: any, padding?: number, padchar?: string): string {
304
384
  str = S_string === typeof str ? str : stringify(str)
305
385
  padding = null == padding ? 44 : padding
@@ -308,48 +388,71 @@ function pad(str: any, padding?: number, padchar?: string): string {
308
388
  }
309
389
 
310
390
 
311
- // Determine the type of a value as a string.
312
- // Returns one of:
313
- // 'null', 'string', 'number', 'boolean', 'function', 'array', 'object', 'instance'
314
- // where 'instance' is an instance of a class, and 'null' is undefined, null, or NaN.
315
- // Normalizes and simplifies JavaScript's type system for consistency.
316
- function typify(value: any): string {
317
- if (value === null || value === undefined) {
318
- return S_null
391
+ // Determine the type of a value as a bit code.
392
+ function typify(value: any): number {
393
+
394
+ if (undefined === value) {
395
+ return T_noval
319
396
  }
320
397
 
321
- const type = typeof value
398
+ const typestr = typeof value
322
399
 
323
- if (S_number === type && isNaN(value)) {
324
- return S_null
400
+ if (null === value) {
401
+ return T_scalar | T_null
402
+ }
403
+ else if (S_number === typestr) {
404
+ if (Number.isInteger(value)) {
405
+ return T_scalar | T_number | T_integer
406
+ }
407
+ else if (isNaN(value)) {
408
+ return T_noval
409
+ }
410
+ else {
411
+ return T_scalar | T_number | T_decimal
412
+ }
413
+ }
414
+ else if (S_string === typestr) {
415
+ return T_scalar | T_string
416
+ }
417
+ else if (S_boolean === typestr) {
418
+ return T_scalar | T_boolean
419
+ }
420
+ else if (S_function === typestr) {
421
+ return T_scalar | T_function
325
422
  }
326
423
 
327
- if (Array.isArray(value)) {
328
- return S_array
424
+ // For languages that have symbolic atoms.
425
+ else if (S_symbol === typestr) {
426
+ return T_scalar | T_symbol
329
427
  }
330
428
 
331
- if (type === 'object') {
429
+ else if (Array.isArray(value)) {
430
+ return T_node | T_list
431
+ }
432
+
433
+ else if (S_object === typestr) {
332
434
 
333
435
  if (value.constructor instanceof Function) {
334
436
  let cname = value.constructor.name
335
437
  if ('Object' !== cname && 'Array' !== cname) {
336
- return S_instance
438
+ return T_node | T_instance
337
439
  }
338
440
  }
339
441
 
340
- return S_object
442
+ return T_node | T_map
341
443
  }
342
444
 
343
- return type
445
+ // Anything else (e.g. bigint) is considered T_any
446
+ return T_any
344
447
  }
345
448
 
346
449
 
347
450
  // Get a list element. The key should be an integer, or a string
348
451
  // that can parse to an integer only. Negative integers count from the end of the list.
349
452
  function getelem(val: any, key: any, alt?: any) {
350
- let out = UNDEF
453
+ let out = NONE
351
454
 
352
- if (UNDEF === val || UNDEF === key) {
455
+ if (NONE === val || NONE === key) {
353
456
  return alt
354
457
  }
355
458
 
@@ -363,8 +466,8 @@ function getelem(val: any, key: any, alt?: any) {
363
466
  }
364
467
  }
365
468
 
366
- if (UNDEF === out) {
367
- return alt
469
+ if (NONE === out) {
470
+ return 0 < (T_function & typify(alt)) ? alt() : alt
368
471
  }
369
472
 
370
473
  return out
@@ -376,7 +479,7 @@ function getelem(val: any, key: any, alt?: any) {
376
479
  function getprop(val: any, key: any, alt?: any) {
377
480
  let out = alt
378
481
 
379
- if (UNDEF === val || UNDEF === key) {
482
+ if (NONE === val || NONE === key) {
380
483
  return alt
381
484
  }
382
485
 
@@ -384,7 +487,7 @@ function getprop(val: any, key: any, alt?: any) {
384
487
  out = val[key]
385
488
  }
386
489
 
387
- if (UNDEF === out) {
490
+ if (NONE === out) {
388
491
  return alt
389
492
  }
390
493
 
@@ -397,20 +500,20 @@ function getprop(val: any, key: any, alt?: any) {
397
500
  // Number keys are converted to strings.
398
501
  // Floats are truncated to integers.
399
502
  // Booleans, objects, arrays, null, undefined all return empty string.
400
- function strkey(key: any = UNDEF): string {
401
- if (UNDEF === key) {
503
+ function strkey(key: any = NONE): string {
504
+ if (NONE === key) {
402
505
  return S_MT
403
506
  }
404
507
 
405
- if (typeof key === S_string) {
508
+ const t = typify(key)
509
+
510
+ if (0 < (T_string & t)) {
406
511
  return key
407
512
  }
408
-
409
- if (typeof key === S_boolean) {
513
+ else if (0 < (T_boolean & t)) {
410
514
  return S_MT
411
515
  }
412
-
413
- if (typeof key === S_number) {
516
+ else if (0 < (T_number & t)) {
414
517
  return key % 1 === 0 ? String(key) : String(Math.floor(key))
415
518
  }
416
519
 
@@ -419,6 +522,7 @@ function strkey(key: any = UNDEF): string {
419
522
 
420
523
 
421
524
  // Sorted keys of a map, or indexes (as strings) of a list.
525
+ // Root utility - only uses language facilities.
422
526
  function keysof(val: any): string[] {
423
527
  return !isnode(val) ? [] :
424
528
  ismap(val) ? Object.keys(val).sort() : (val as any).map((_n: any, i: number) => S_MT + i)
@@ -426,22 +530,60 @@ function keysof(val: any): string[] {
426
530
 
427
531
 
428
532
  // Value of property with name key in node val is defined.
533
+ // Root utility - only uses language facilities.
429
534
  function haskey(val: any, key: any) {
430
- return UNDEF !== getprop(val, key)
535
+ return NONE !== getprop(val, key)
431
536
  }
432
537
 
433
538
 
434
539
  // List the sorted keys of a map or list as an array of tuples of the form [key, value].
435
540
  // As with keysof, list indexes are converted to strings.
436
- function items(val: any): [string, any][] {
437
- return keysof(val).map((k: any) => [k, val[k]])
541
+ // Root utility - only uses language facilities.
542
+ function items(val: any): [string, any][];
543
+ function items<T>(val: any, apply: (item: [string, any]) => T): T[];
544
+ function items(
545
+ val: any,
546
+ apply?: (item: [string, any]) => any
547
+ ): any[] {
548
+ let out: [string, any][] = keysof(val).map((k: any) => [k, val[k]])
549
+ if (null != apply) {
550
+ out = out.map(apply)
551
+ }
552
+ return out
553
+ }
554
+
555
+
556
+ // To replicate the array spread operator:
557
+ // a=1, b=[2,3], c=[4,5]
558
+ // [a,...b,c] -> [1,2,3,[4,5]]
559
+ // flatten([a,b,[c]]) -> [1,2,3,[4,5]]
560
+ // NOTE: [c] ensures c is not expanded
561
+ function flatten(list: any[], depth?: number) {
562
+ if (!islist(list)) {
563
+ return list
564
+ }
565
+ return list.flat(getdef(depth, 1))
566
+ }
567
+
568
+
569
+ // Filter item values using check function.
570
+ function filter(val: any, check: (item: [string, any]) => boolean): any[] {
571
+ let all = items(val)
572
+ let numall = size(all)
573
+ let out = []
574
+ for (let i = 0; i < numall; i++) {
575
+ if (check(all[i])) {
576
+ out.push(all[i][1])
577
+ }
578
+ }
579
+ return out
438
580
  }
439
581
 
440
582
 
441
583
  // Escape regular expression.
442
584
  function escre(s: string) {
443
- s = null == s ? S_MT : s
444
- return s.replace(R_ESCAPE_REGEXP, '\\$&')
585
+ // s = null == s ? S_MT : s
586
+ return replace(s, R_ESCAPE_REGEXP, '\\$&')
445
587
  }
446
588
 
447
589
 
@@ -452,16 +594,59 @@ function escurl(s: string) {
452
594
  }
453
595
 
454
596
 
455
- // Concatenate url part strings, merging forward slashes as needed.
456
- function joinurl(sarr: any[]) {
457
- return sarr
458
- .filter(s => null != s && S_MT !== s)
459
- .map((s, i) => 0 === i ? s.replace(R_TRAILING_SLASH, S_MT) :
460
- s.replace(R_LEADING_TRAILING_SLASH, '$1/')
461
- .replace(R_LEADING_SLASH, S_MT)
462
- .replace(R_TRAILING_SLASH, S_MT))
463
- .filter(s => S_MT !== s)
464
- .join(S_FS)
597
+ // Replace a search string (all), or a regexp, in a source string.
598
+ function replace(s: string, from: string | RegExp, to: any) {
599
+ let rs = s
600
+ let ts = typify(s)
601
+ if (0 === (T_string & ts)) {
602
+ rs = stringify(s)
603
+ }
604
+ else if (0 < ((T_noval | T_null) & ts)) {
605
+ rs = S_MT
606
+ }
607
+ else {
608
+ rs = stringify(s)
609
+ }
610
+ return rs.replace(from, to)
611
+ }
612
+
613
+
614
+ // Concatenate url part strings, merging sep char as needed.
615
+ function join(arr: any[], sep?: string, url?: boolean) {
616
+ const sarr = size(arr)
617
+ const sepdef = getdef(sep, S_CM)
618
+ const sepre = 1 === size(sepdef) ? escre(sepdef) : NONE
619
+ const out = filter(
620
+ items(
621
+ // filter(arr, (n) => null != n[1] && S_MT !== n[1]),
622
+ filter(arr, (n) => (0 < (T_string & typify(n[1]))) && S_MT !== n[1]),
623
+ (n) => {
624
+ let i = +n[0]
625
+ let s = n[1]
626
+
627
+ if (NONE !== sepre && S_MT !== sepre) {
628
+ if (url && 0 === i) {
629
+ s = replace(s, RegExp(sepre + '+$'), S_MT)
630
+ return s
631
+ }
632
+
633
+ if (0 < i) {
634
+ s = replace(s, RegExp('^' + sepre + '+'), S_MT)
635
+ }
636
+
637
+ if (i < sarr - 1 || !url) {
638
+ s = replace(s, RegExp(sepre + '+$'), S_MT)
639
+ }
640
+
641
+ s = replace(s, RegExp('([^' + sepre + '])' + sepre + '+([^' + sepre + '])'),
642
+ '$1' + sepdef + '$2')
643
+ }
644
+
645
+ return s
646
+ }), (n) => S_MT !== n[1])
647
+ .join(sepdef)
648
+
649
+ return out
465
650
  }
466
651
 
467
652
 
@@ -470,19 +655,27 @@ function joinurl(sarr: any[]) {
470
655
  // In general, the behaivor of of JavaScript's JSON.stringify(val,null,2) is followed.
471
656
  function jsonify(val: any, flags?: { indent?: number, offset?: number }) {
472
657
  let str = S_null
658
+
473
659
  if (null != val) {
474
- const indent = getprop(flags, 'indent', 2)
475
- str = JSON.stringify(val, null, indent)
476
- if (UNDEF === str) {
477
- str = S_null
660
+ try {
661
+ const indent = getprop(flags, 'indent', 2)
662
+ str = JSON.stringify(val, null, indent)
663
+ if (NONE === str) {
664
+ str = S_null
665
+ }
666
+ const offset = getprop(flags, 'offset', 0)
667
+ if (0 < offset) {
668
+ // Left offset entire indented JSON so that it aligns with surrounding code
669
+ // indented by offset. Assume first brace is on line with asignment, so not offset.
670
+ str = '{\n' +
671
+ join(
672
+ items(
673
+ slice(str.split('\n'), 1),
674
+ (n: any) => pad(n[1], 0 - offset - size(n[1]))), '\n')
675
+ }
478
676
  }
479
- const offset = getprop(flags, 'offset', 0)
480
- if (0 < offset) {
481
- // Left offset entire indented JSON so that it aligns with surrounding code
482
- // indented by offset.
483
- str = '{\n' + str.split('\n').slice(1)
484
- .map(n => pad(n, 0 - offset - size(n)))
485
- .join('\n')
677
+ catch (e: any) {
678
+ str = '__JSONIFY_FAILED__'
486
679
  }
487
680
  }
488
681
 
@@ -495,7 +688,7 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
495
688
  let valstr = S_MT
496
689
  pretty = !!pretty
497
690
 
498
- if (UNDEF === val) {
691
+ if (NONE === val) {
499
692
  return pretty ? '<>' : valstr
500
693
  }
501
694
 
@@ -511,9 +704,9 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
511
704
  !Array.isArray(val)
512
705
  ) {
513
706
  const sortedObj: any = {}
514
- for (const k of Object.keys(val).sort()) {
515
- sortedObj[k] = val[k]
516
- }
707
+ items(val, (n) => {
708
+ sortedObj[n[0]] = val[n[0]]
709
+ })
517
710
  return sortedObj
518
711
  }
519
712
  return val
@@ -521,7 +714,7 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
521
714
  valstr = valstr.replace(R_QUOTES, S_MT)
522
715
  }
523
716
  catch (err: any) {
524
- valstr = S_MT + val
717
+ valstr = '__STRINGIFY_FAILED__'
525
718
  }
526
719
  }
527
720
 
@@ -532,8 +725,9 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
532
725
 
533
726
  if (pretty) {
534
727
  // Indicate deeper JSON levels with different terminal colors (simplistic wrt strings).
535
- let c = [81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69]
536
- .map(n => `\x1b[38;5;${n}m`),
728
+ let c = items(
729
+ [81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69],
730
+ (n) => '\x1b[38;5;' + n[1] + 'm'),
537
731
  r = '\x1b[0m', d = 0, o = c[0], t = o
538
732
  for (const ch of valstr) {
539
733
  if (ch === '{' || ch === '[') {
@@ -554,34 +748,34 @@ function stringify(val: any, maxlen?: number, pretty?: any): string {
554
748
 
555
749
  // Build a human friendly path string.
556
750
  function pathify(val: any, startin?: number, endin?: number) {
557
- let pathstr: string | undefined = UNDEF
751
+ let pathstr: string | undefined = NONE
558
752
 
559
753
  let path: any[] | undefined = islist(val) ? val :
560
754
  S_string == typeof val ? [val] :
561
755
  S_number == typeof val ? [val] :
562
- UNDEF
756
+ NONE
563
757
 
564
758
  const start = null == startin ? 0 : -1 < startin ? startin : 0
565
759
  const end = null == endin ? 0 : -1 < endin ? endin : 0
566
760
 
567
- if (UNDEF != path && 0 <= start) {
761
+ if (NONE != path && 0 <= start) {
568
762
  path = slice(path, start, path.length - end)
569
763
  if (0 === path.length) {
570
764
  pathstr = '<root>'
571
765
  }
572
766
  else {
573
- pathstr = path
574
- // .filter((p: any, t: any) => (t = typeof p, S_string === t || S_number === t))
575
- .filter((p: any) => iskey(p))
576
- .map((p: any) =>
577
- S_number === typeof p ? S_MT + Math.floor(p) :
578
- p.replace(R_DOT, S_MT))
579
- .join(S_DT)
767
+ pathstr = join(
768
+ items(
769
+ filter(path, (n) => iskey(n[1])), (n) => {
770
+ let p = n[1]
771
+ return S_number === typeof p ? S_MT + Math.floor(p) :
772
+ p.replace(R_DOT, S_MT)
773
+ }), S_DT)
580
774
  }
581
775
  }
582
776
 
583
- if (UNDEF === pathstr) {
584
- pathstr = '<unknown-path' + (UNDEF === val ? S_MT : S_CN + stringify(val, 47)) + '>'
777
+ if (NONE === pathstr) {
778
+ pathstr = '<unknown-path' + (NONE === val ? S_MT : S_CN + stringify(val, 47)) + '>'
585
779
  }
586
780
 
587
781
  return pathstr
@@ -589,19 +783,21 @@ function pathify(val: any, startin?: number, endin?: number) {
589
783
 
590
784
 
591
785
  // Clone a JSON-like data structure.
592
- // NOTE: function value references are copied, *not* cloned.
786
+ // NOTE: function and instance values are copied, *not* cloned.
593
787
  function clone(val: any): any {
594
788
  const refs: any[] = []
595
- const replacer: any = (_k: any, v: any) => S_function === typeof v ?
596
- (refs.push(v), '`$FUNCTION:' + (refs.length - 1) + '`') : v
789
+ const reftype = T_function | T_instance
790
+ const replacer: any = (_k: any, v: any) => 0 < (reftype & typify(v)) ?
791
+ (refs.push(v), '`$REF:' + (refs.length - 1) + '`') : v
597
792
  const reviver: any = (_k: any, v: any, m: any) => S_string === typeof v ?
598
- (m = v.match(R_FUNCTION_REF), m ? refs[m[1]] : v) : v
599
- return UNDEF === val ? UNDEF : JSON.parse(JSON.stringify(val, replacer), reviver)
793
+ (m = v.match(R_CLONE_REF), m ? refs[m[1]] : v) : v
794
+ const out = NONE === val ? NONE : JSON.parse(JSON.stringify(val, replacer), reviver)
795
+ return out
600
796
  }
601
797
 
602
798
 
603
799
  // Define a JSON Object using function arguments.
604
- function jo(...kv: any[]): Record<string, any> {
800
+ function jm(...kv: any[]): Record<string, any> {
605
801
  const kvsize = size(kv)
606
802
  const o: any = {}
607
803
  for (let i = 0; i < kvsize; i += 2) {
@@ -614,7 +810,7 @@ function jo(...kv: any[]): Record<string, any> {
614
810
 
615
811
 
616
812
  // Define a JSON Array using function arguments.
617
- function ja(...v: any[]): any[] {
813
+ function jt(...v: any[]): any[] {
618
814
  const vsize = size(v)
619
815
  const a: any = new Array(vsize)
620
816
  for (let i = 0; i < vsize; i++) {
@@ -624,19 +820,18 @@ function ja(...v: any[]): any[] {
624
820
  }
625
821
 
626
822
 
627
-
628
823
  // Safely delete a property from an object or array element.
629
824
  // Undefined arguments and invalid keys are ignored.
630
825
  // Returns the (possibly modified) parent.
631
826
  // For objects, the property is deleted using the delete operator.
632
827
  // For arrays, the element at the index is removed and remaining elements are shifted down.
828
+ // NOTE: parent list may be new list, thus update references.
633
829
  function delprop<PARENT>(parent: PARENT, key: any): PARENT {
634
830
  if (!iskey(key)) {
635
831
  return parent
636
832
  }
637
833
 
638
834
  if (ismap(parent)) {
639
- // key = S_MT + key
640
835
  key = strkey(key)
641
836
  delete (parent as any)[key]
642
837
  }
@@ -651,10 +846,12 @@ function delprop<PARENT>(parent: PARENT, key: any): PARENT {
651
846
  keyI = Math.floor(keyI)
652
847
 
653
848
  // Delete list element at position keyI, shifting later elements down.
654
- if (0 <= keyI && keyI < parent.length) {
655
- for (let pI = keyI; pI < parent.length - 1; pI++) {
849
+ const psize = size(parent)
850
+ if (0 <= keyI && keyI < psize) {
851
+ for (let pI = keyI; pI < psize - 1; pI++) {
656
852
  parent[pI] = parent[pI + 1]
657
853
  }
854
+
658
855
  parent.length = parent.length - 1
659
856
  }
660
857
  }
@@ -667,6 +864,7 @@ function delprop<PARENT>(parent: PARENT, key: any): PARENT {
667
864
  // Returns the (possibly modified) parent.
668
865
  // If the parent is a list, and the key is negative, prepend the value.
669
866
  // NOTE: If the key is above the list size, append the value; below, prepend.
867
+ // NOTE: parent list may be new list, thus update references.
670
868
  function setprop<PARENT>(parent: PARENT, key: any, val: any): PARENT {
671
869
  if (!iskey(key)) {
672
870
  return parent
@@ -687,9 +885,11 @@ function setprop<PARENT>(parent: PARENT, key: any, val: any): PARENT {
687
885
 
688
886
  keyI = Math.floor(keyI)
689
887
 
888
+ // TODO: DELETE list element
889
+
690
890
  // Set or append value at position keyI, or append if keyI out of bounds.
691
891
  if (0 <= keyI) {
692
- parent[parent.length < keyI ? parent.length : keyI] = val
892
+ parent[slice(keyI, 0, size(parent) + 1)] = val
693
893
  }
694
894
 
695
895
  // Prepend value if keyI is negative
@@ -721,9 +921,13 @@ function walk(
721
921
  parent?: any,
722
922
  path?: string[]
723
923
  ): any {
724
- let out = null == before ? val : before(key, val, parent, path || [])
924
+ if (NONE === path) {
925
+ path = []
926
+ }
725
927
 
726
- maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : 32
928
+ let out = null == before ? val : before(key, val, parent, path)
929
+
930
+ maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : MAXDEPTH
727
931
  if (0 === maxdepth || (null != path && 0 < maxdepth && maxdepth <= path.length)) {
728
932
  return out
729
933
  }
@@ -731,11 +935,13 @@ function walk(
731
935
  if (isnode(out)) {
732
936
  for (let [ckey, child] of items(out)) {
733
937
  setprop(out, ckey, walk(
734
- child, before, after, maxdepth, ckey, out, [...(path || []), S_MT + ckey]))
938
+ child, before, after, maxdepth, ckey, out,
939
+ flatten([getdef(path, []), S_MT + ckey])
940
+ ))
735
941
  }
736
942
  }
737
943
 
738
- out = null == after ? out : after(key, out, parent, path || [])
944
+ out = null == after ? out : after(key, out, parent, path)
739
945
 
740
946
  return out
741
947
  }
@@ -746,7 +952,9 @@ function walk(
746
952
  // override each other, and do *not* merge. The first element is
747
953
  // modified.
748
954
  function merge(val: any, maxdepth?: number): any {
749
- let out: any = UNDEF
955
+ // const md: number = null == maxdepth ? MAXDEPTH : maxdepth < 0 ? 0 : maxdepth
956
+ const md: number = slice(maxdepth ?? MAXDEPTH, 0)
957
+ let out: any = NONE
750
958
 
751
959
  // Handle edge cases.
752
960
  if (!islist(val)) {
@@ -757,7 +965,7 @@ function merge(val: any, maxdepth?: number): any {
757
965
  const lenlist = list.length
758
966
 
759
967
  if (0 === lenlist) {
760
- return UNDEF
968
+ return NONE
761
969
  }
762
970
  else if (1 === lenlist) {
763
971
  return list[0]
@@ -788,8 +996,12 @@ function merge(val: any, maxdepth?: number): any {
788
996
  ) {
789
997
  const pI = size(path)
790
998
 
999
+ if (md <= pI) {
1000
+ setprop(cur[pI - 1], key, val)
1001
+ }
1002
+
791
1003
  // Scalars just override directly.
792
- if (!isnode(val)) {
1004
+ else if (!isnode(val)) {
793
1005
  cur[pI] = val
794
1006
  }
795
1007
 
@@ -801,7 +1013,7 @@ function merge(val: any, maxdepth?: number): any {
801
1013
  const tval = dst[pI]
802
1014
 
803
1015
  // Destination empty, so create node (unless override is class instance).
804
- if (UNDEF === tval && S_instance !== typify(val)) {
1016
+ if (NONE === tval && 0 === (T_instance & typify(val))) {
805
1017
  cur[pI] = islist(val) ? [] : {}
806
1018
  }
807
1019
 
@@ -815,7 +1027,7 @@ function merge(val: any, maxdepth?: number): any {
815
1027
  cur[pI] = val
816
1028
 
817
1029
  // No need to descend when override wins (destination is discarded).
818
- val = UNDEF
1030
+ val = NONE
819
1031
  }
820
1032
  }
821
1033
 
@@ -826,7 +1038,6 @@ function merge(val: any, maxdepth?: number): any {
826
1038
  return val
827
1039
  }
828
1040
 
829
-
830
1041
  function after(
831
1042
  key: string | number | undefined,
832
1043
  _val: any,
@@ -837,7 +1048,7 @@ function merge(val: any, maxdepth?: number): any {
837
1048
  const target = cur[cI - 1]
838
1049
  const value = cur[cI]
839
1050
 
840
- // console.log('AFTER-PREP', pathify(path), '@', cI,
1051
+ // console.log('AFTER-PREP', pathify(path), '@', cI, cur, '|',
841
1052
  // stringify(key, -1, 1), stringify(value, -1, 1), 'T=', stringify(target, -1, 1))
842
1053
 
843
1054
  setprop(target, key, value)
@@ -846,22 +1057,71 @@ function merge(val: any, maxdepth?: number): any {
846
1057
 
847
1058
  // Walk overriding node, creating paths in output as needed.
848
1059
  out = walk(obj, before, after, maxdepth)
1060
+ // console.log('WALK-DONE', out, obj)
849
1061
  }
850
1062
  }
851
1063
 
1064
+ if (0 === md) {
1065
+ out = getelem(list, -1)
1066
+ out = islist(out) ? [] : ismap(out) ? {} : out
1067
+ }
1068
+
852
1069
  return out
853
1070
  }
854
1071
 
855
1072
 
1073
+ // Set a value using a path. Missing path parts are created.
1074
+ // String paths create only maps. Use a string list to create list parts.
1075
+ function setpath(
1076
+ store: any,
1077
+ path: number | string | string[],
1078
+ val: any,
1079
+ injdef?: Partial<Injection>
1080
+ ) {
1081
+ const pathType = typify(path)
1082
+
1083
+ const parts = 0 < (T_list & pathType) ? path :
1084
+ 0 < (T_string & pathType) ? (path as string).split(S_DT) :
1085
+ 0 < (T_number & pathType) ? [path] : NONE
1086
+
1087
+ if (NONE === parts) {
1088
+ return NONE
1089
+ }
1090
+
1091
+ const base = getprop(injdef, S_base)
1092
+ const numparts = size(parts)
1093
+ let parent = getprop(store, base, store)
1094
+
1095
+ for (let pI = 0; pI < numparts - 1; pI++) {
1096
+ const partKey = getelem(parts, pI)
1097
+ let nextParent = getprop(parent, partKey)
1098
+ if (!isnode(nextParent)) {
1099
+ nextParent = 0 < (T_number & typify(getelem(parts, pI + 1))) ? [] : {}
1100
+ setprop(parent, partKey, nextParent)
1101
+ }
1102
+ parent = nextParent
1103
+ }
1104
+
1105
+ if (DELETE === val) {
1106
+ delprop(parent, getelem(parts, -1))
1107
+ }
1108
+ else {
1109
+ setprop(parent, getelem(parts, -1), val)
1110
+ }
1111
+
1112
+ return parent
1113
+ }
1114
+
1115
+
856
1116
  function getpath(store: any, path: number | string | string[], injdef?: Partial<Injection>) {
857
1117
 
858
1118
  // Operate on a string array.
859
1119
  const parts = islist(path) ? path :
860
1120
  'string' === typeof path ? path.split(S_DT) :
861
- 'number' === typeof path ? [strkey(path)] : UNDEF
1121
+ 'number' === typeof path ? [strkey(path)] : NONE
862
1122
 
863
- if (UNDEF === parts) {
864
- return UNDEF
1123
+ if (NONE === parts) {
1124
+ return NONE
865
1125
  }
866
1126
 
867
1127
  // let root = store
@@ -893,7 +1153,7 @@ function getpath(store: any, path: number | string | string[], injdef?: Partial<
893
1153
 
894
1154
  const dpath = getprop(injdef, 'dpath')
895
1155
 
896
- for (let pI = 0; UNDEF !== val && pI < parts.length; pI++) {
1156
+ for (let pI = 0; NONE !== val && pI < numparts; pI++) {
897
1157
  let part = parts[pI]
898
1158
 
899
1159
  if (injdef && S_DKEY === part) {
@@ -901,15 +1161,15 @@ function getpath(store: any, path: number | string | string[], injdef?: Partial<
901
1161
  }
902
1162
  else if (injdef && part.startsWith('$GET:')) {
903
1163
  // $GET:path$ -> get store value, use as path part (string)
904
- part = stringify(getpath(src, part.substring(5, part.length - 1)))
1164
+ part = stringify(getpath(src, slice(part, 5, -1)))
905
1165
  }
906
1166
  else if (injdef && part.startsWith('$REF:')) {
907
1167
  // $REF:refpath$ -> get spec value, use as path part (string)
908
- part = stringify(getpath(getprop(store, S_DSPEC), part.substring(5, part.length - 1)))
1168
+ part = stringify(getpath(getprop(store, S_DSPEC), slice(part, 5, -1)))
909
1169
  }
910
1170
  else if (injdef && part.startsWith('$META:')) {
911
1171
  // $META:metapath$ -> get meta value, use as path part (string)
912
- part = stringify(getpath(getprop(injdef, 'meta'), part.substring(6, part.length - 1)))
1172
+ part = stringify(getpath(getprop(injdef, 'meta'), slice(part, 6, -1)))
913
1173
  }
914
1174
 
915
1175
  // $$ escapes $
@@ -932,14 +1192,16 @@ function getpath(store: any, path: number | string | string[], injdef?: Partial<
932
1192
  val = dparent
933
1193
  }
934
1194
  else {
935
- const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1))
1195
+ // const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1))
1196
+ const fullpath = flatten([slice(dpath, 0 - ascends), parts.slice(pI + 1)])
936
1197
 
937
1198
  if (ascends <= size(dpath)) {
938
1199
  val = getpath(store, fullpath)
939
1200
  }
940
1201
  else {
941
- val = UNDEF
1202
+ val = NONE
942
1203
  }
1204
+
943
1205
  break
944
1206
  }
945
1207
  }
@@ -961,13 +1223,14 @@ function getpath(store: any, path: number | string | string[], injdef?: Partial<
961
1223
  val = handler(injdef, val, ref, store)
962
1224
  }
963
1225
 
1226
+ // console.log('GETPATH', path, val)
1227
+
964
1228
  return val
965
1229
  }
966
1230
 
967
1231
 
968
-
969
1232
  // Inject values from a data store into a node recursively, resolving
970
- // paths against the store, or current if they are local. THe modify
1233
+ // paths against the store, or current if they are local. The modify
971
1234
  // argument allows custom modification of the result. The inj
972
1235
  // (Injection) argument is used to maintain recursive state.
973
1236
  function inject(
@@ -980,14 +1243,14 @@ function inject(
980
1243
 
981
1244
  // Create state if at root of injection. The input value is placed
982
1245
  // inside a virtual parent holder to simplify edge cases.
983
- if (UNDEF === injdef || null == injdef.mode) {
1246
+ if (NONE === injdef || null == injdef.mode) {
984
1247
  // Set up state assuming we are starting in the virtual parent.
985
1248
  inj = new Injection(val, { [S_DTOP]: val })
986
1249
  inj.dparent = store
987
1250
  inj.errs = getprop(store, S_DERRS, [])
988
1251
  inj.meta.__d = 0
989
1252
 
990
- if (UNDEF !== injdef) {
1253
+ if (NONE !== injdef) {
991
1254
  inj.modify = null == injdef.modify ? inj.modify : injdef.modify
992
1255
  inj.extra = null == injdef.extra ? inj.extra : injdef.extra
993
1256
  inj.meta = null == injdef.meta ? inj.meta : injdef.meta
@@ -997,6 +1260,9 @@ function inject(
997
1260
 
998
1261
  inj.descend()
999
1262
 
1263
+ // console.log('INJ-START', val, inj.mode, inj.key, inj.val,
1264
+ // 't=', inj.path, 'P=', inj.parent, 'dp=', inj.dparent, 'ST=', store.$TOP)
1265
+
1000
1266
  // Descend into node.
1001
1267
  if (isnode(val)) {
1002
1268
 
@@ -1004,21 +1270,29 @@ function inject(
1004
1270
  // Injection transforms ($FOO) are processed *after* other keys.
1005
1271
  // NOTE: the optional digits suffix of the transform can thus be
1006
1272
  // used to order the transforms.
1007
- let nodekeys = ismap(val) ? [
1008
- ...Object.keys(val).filter(k => !k.includes(S_DS)).sort(),
1009
- ...Object.keys(val).filter(k => k.includes(S_DS)).sort(),
1010
- ] : (val as any).map((_n: any, i: number) => i)
1011
1273
 
1274
+ let nodekeys: any[]
1275
+ nodekeys = keysof(val)
1276
+
1277
+ if (ismap(val)) {
1278
+ nodekeys = flatten([
1279
+ filter(nodekeys, (n => !n[1].includes(S_DS))),
1280
+ filter(nodekeys, (n => n[1].includes(S_DS))),
1281
+ ])
1282
+ }
1283
+ else {
1284
+ nodekeys = keysof(val)
1285
+ }
1012
1286
 
1013
1287
  // Each child key-value pair is processed in three injection phases:
1014
- // 1. inj.mode='key:pre' - Key string is injected, returning a possibly altered key.
1015
- // 2. inj.mode='val' - The child value is injected.
1016
- // 3. inj.mode='key:post' - Key string is injected again, allowing child mutation.
1288
+ // 1. inj.mode=M_KEYPRE - Key string is injected, returning a possibly altered key.
1289
+ // 2. inj.mode=M_VAL - The child value is injected.
1290
+ // 3. inj.mode=M_KEYPOST - Key string is injected again, allowing child mutation.
1017
1291
  for (let nkI = 0; nkI < nodekeys.length; nkI++) {
1018
1292
 
1019
1293
  const childinj = inj.child(nkI, nodekeys)
1020
1294
  const nodekey = childinj.key
1021
- childinj.mode = S_MKEYPRE
1295
+ childinj.mode = M_KEYPRE
1022
1296
 
1023
1297
  // Peform the key:pre mode injection on the child key.
1024
1298
  const prekey = _injectstr(nodekey, store, childinj)
@@ -1028,9 +1302,9 @@ function inject(
1028
1302
  nodekeys = childinj.keys
1029
1303
 
1030
1304
  // Prevent further processing by returning an undefined prekey
1031
- if (UNDEF !== prekey) {
1305
+ if (NONE !== prekey) {
1032
1306
  childinj.val = getprop(val, prekey)
1033
- childinj.mode = S_MVAL as InjectMode
1307
+ childinj.mode = M_VAL
1034
1308
 
1035
1309
  // Perform the val mode injection on the child value.
1036
1310
  // NOTE: return value is not used.
@@ -1041,7 +1315,7 @@ function inject(
1041
1315
  nodekeys = childinj.keys
1042
1316
 
1043
1317
  // Peform the key:post mode injection on the child key.
1044
- childinj.mode = S_MKEYPOST as InjectMode
1318
+ childinj.mode = M_KEYPOST
1045
1319
  _injectstr(nodekey, store, childinj)
1046
1320
 
1047
1321
  // The injection may modify child processing.
@@ -1053,7 +1327,7 @@ function inject(
1053
1327
 
1054
1328
  // Inject paths into string scalars.
1055
1329
  else if (S_string === valtype) {
1056
- inj.mode = S_MVAL as InjectMode
1330
+ inj.mode = M_VAL
1057
1331
  val = _injectstr(val, store, inj)
1058
1332
  if (SKIP !== val) {
1059
1333
  inj.setval(val)
@@ -1075,6 +1349,8 @@ function inject(
1075
1349
  )
1076
1350
  }
1077
1351
 
1352
+ // console.log('INJ-VAL', val)
1353
+
1078
1354
  inj.val = val
1079
1355
 
1080
1356
  // Original val reference may no longer be correct.
@@ -1087,21 +1363,22 @@ function inject(
1087
1363
 
1088
1364
  // Delete a key from a map or list.
1089
1365
  const transform_DELETE: Injector = (inj: Injection) => {
1090
- inj.setval(UNDEF)
1091
- return UNDEF
1366
+ inj.setval(NONE)
1367
+ return NONE
1092
1368
  }
1093
1369
 
1094
1370
 
1095
1371
  // Copy value from source data.
1096
1372
  const transform_COPY: Injector = (inj: Injection, _val: any) => {
1097
- const { mode, key } = inj
1373
+ const ijname = 'COPY'
1098
1374
 
1099
- let out = key
1100
- if (!mode.startsWith(S_MKEY)) {
1101
- out = getprop(inj.dparent, key)
1102
- inj.setval(out)
1375
+ if (!checkPlacement(M_VAL, ijname, T_any, inj)) {
1376
+ return NONE
1103
1377
  }
1104
1378
 
1379
+ let out = getprop(inj.dparent, inj.key)
1380
+ inj.setval(out)
1381
+
1105
1382
  return out
1106
1383
  }
1107
1384
 
@@ -1111,29 +1388,30 @@ const transform_COPY: Injector = (inj: Injection, _val: any) => {
1111
1388
  const transform_KEY: Injector = (inj: Injection) => {
1112
1389
  const { mode, path, parent } = inj
1113
1390
 
1114
- // Do nothing in val mode.
1115
- if (S_MVAL !== mode) {
1116
- return UNDEF
1391
+ // Do nothing in val mode - not an error.
1392
+ if (M_VAL !== mode) {
1393
+ return NONE
1117
1394
  }
1118
1395
 
1119
1396
  // Key is defined by $KEY meta property.
1120
1397
  const keyspec = getprop(parent, S_BKEY)
1121
- if (UNDEF !== keyspec) {
1398
+ if (NONE !== keyspec) {
1122
1399
  delprop(parent, S_BKEY)
1123
1400
  return getprop(inj.dparent, keyspec)
1124
1401
  }
1125
1402
 
1126
1403
  // Key is defined within general purpose $META object.
1127
- return getprop(getprop(parent, S_BANNO), S_KEY, getprop(path, path.length - 2))
1404
+ // return getprop(getprop(parent, S_BANNO), S_KEY, getprop(path, path.length - 2))
1405
+ return getprop(getprop(parent, S_BANNO), S_KEY, getelem(path, -2))
1128
1406
  }
1129
1407
 
1130
1408
 
1131
- // Annotatea node. Does nothing itself, just used by
1409
+ // Annotate node. Does nothing itself, just used by
1132
1410
  // other injectors, and is removed when called.
1133
1411
  const transform_ANNO: Injector = (inj: Injection) => {
1134
1412
  const { parent } = inj
1135
1413
  delprop(parent, S_BANNO)
1136
- return UNDEF
1414
+ return NONE
1137
1415
  }
1138
1416
 
1139
1417
 
@@ -1146,29 +1424,27 @@ const transform_MERGE: Injector = (inj: Injection) => {
1146
1424
  const { mode, key, parent } = inj
1147
1425
 
1148
1426
  // Ensures $MERGE is removed from parent list (val mode).
1149
- let out: any = UNDEF
1427
+ let out: any = NONE
1150
1428
 
1151
- if (S_MKEYPRE === mode) {
1429
+ if (M_KEYPRE === mode) {
1152
1430
  out = key
1153
1431
  }
1154
1432
 
1155
1433
  // Operate after child values have been transformed.
1156
- else if (S_MKEYPOST === mode) {
1434
+ else if (M_KEYPOST === mode) {
1157
1435
  out = key
1158
1436
 
1159
1437
  let args = getprop(parent, key)
1160
1438
  args = Array.isArray(args) ? args : [args]
1161
1439
 
1162
1440
  // Remove the $MERGE command from a parent map.
1163
- inj.setval(UNDEF)
1441
+ inj.setval(NONE)
1164
1442
 
1165
1443
  // Literals in the parent have precedence, but we still merge onto
1166
1444
  // the parent object, so that node tree references are not changed.
1167
- const mergelist = [parent, ...args, clone(parent)]
1445
+ const mergelist = flatten([[parent], args, [clone(parent)]])
1168
1446
 
1169
1447
  merge(mergelist)
1170
-
1171
- // return key
1172
1448
  }
1173
1449
 
1174
1450
  return out
@@ -1183,65 +1459,63 @@ const transform_EACH: Injector = (
1183
1459
  _ref: string,
1184
1460
  store: any
1185
1461
  ) => {
1462
+ const ijname = 'EACH'
1186
1463
 
1187
- // Remove arguments to avoid spurious processing.
1188
- if (null != inj.keys) {
1189
- inj.keys.length = 1
1464
+ if (!checkPlacement(M_VAL, ijname, T_list, inj)) {
1465
+ return NONE
1190
1466
  }
1191
1467
 
1192
- if (S_MVAL !== inj.mode) {
1193
- return UNDEF
1194
- }
1468
+ // Remove remaining keys to avoid spurious processing.
1469
+ slice(inj.keys, 0, 1, true)
1195
1470
 
1196
- // Get arguments: ['`$EACH`', 'source-path', child-template].
1197
- const srcpath = getprop(inj.parent, 1)
1198
- const child = clone(getprop(inj.parent, 2))
1471
+ // const [err, srcpath, child] = injectorArgs([T_string, T_any], inj)
1472
+ const [err, srcpath, child] = injectorArgs([T_string, T_any], slice(inj.parent, 1))
1473
+ if (NONE !== err) {
1474
+ inj.errs.push('$' + ijname + ': ' + err)
1475
+ return NONE
1476
+ }
1199
1477
 
1200
1478
  // Source data.
1201
1479
  const srcstore = getprop(store, inj.base, store)
1202
1480
 
1203
1481
  const src = getpath(srcstore, srcpath, inj)
1482
+ const srctype = typify(src)
1204
1483
 
1205
1484
  // Create parallel data structures:
1206
1485
  // source entries :: child templates
1207
1486
  let tcur: any = []
1208
1487
  let tval: any = []
1209
1488
 
1210
- const tkey = inj.path[inj.path.length - 2]
1211
- const target = inj.nodes[inj.nodes.length - 2] || inj.nodes[inj.nodes.length - 1]
1489
+ const tkey = getelem(inj.path, -2)
1490
+ const target = getelem(inj.nodes, - 2, () => getelem(inj.nodes, -1))
1212
1491
 
1213
1492
  // Create clones of the child template for each value of the current soruce.
1214
- if (islist(src)) {
1215
- tval = src.map(() => clone(child))
1493
+ if (0 < (T_list & srctype)) {
1494
+ tval = items(src, () => clone(child))
1216
1495
  }
1217
- else if (ismap(src)) {
1218
- tval = Object.entries(src).map(n => ({
1219
- ...clone(child),
1220
-
1496
+ else if (0 < (T_map & srctype)) {
1497
+ tval = items(src, (n => merge([
1498
+ clone(child),
1221
1499
  // Make a note of the key for $KEY transforms.
1222
- [S_BANNO]: { KEY: n[0] }
1223
- }))
1500
+ { [S_BANNO]: { KEY: n[0] } }
1501
+ ], 1)))
1224
1502
  }
1225
1503
 
1226
1504
  let rval = []
1227
1505
 
1228
1506
  if (0 < size(tval)) {
1229
- tcur = null == src ? UNDEF : Object.values(src)
1507
+ tcur = null == src ? NONE : Object.values(src)
1230
1508
 
1231
1509
  const ckey = getelem(inj.path, -2)
1232
1510
 
1233
1511
  const tpath = slice(inj.path, -1)
1234
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey]
1235
-
1512
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey])
1236
1513
 
1237
1514
  // Parent structure.
1238
-
1239
- // const ckey = getelem(cpath, -1)
1240
1515
  tcur = { [ckey]: tcur }
1241
1516
 
1242
- if (1 < tpath.length) {
1517
+ if (1 < size(tpath)) {
1243
1518
  const pkey = getelem(inj.path, -3, S_DTOP)
1244
- // const pkey = getelem(cpath, -2, S_DTOP)
1245
1519
  tcur = { [pkey]: tcur }
1246
1520
  dpath.push('$:' + pkey)
1247
1521
  }
@@ -1261,7 +1535,8 @@ const transform_EACH: Injector = (
1261
1535
  rval = tinj.val
1262
1536
  }
1263
1537
 
1264
- _updateAncestors(inj, target, tkey, rval)
1538
+ // _updateAncestors(inj, target, tkey, rval)
1539
+ setprop(target, tkey, rval)
1265
1540
 
1266
1541
  // Prevent callee from damaging first list entry (since we are in `val` mode).
1267
1542
  return rval[0]
@@ -1269,7 +1544,7 @@ const transform_EACH: Injector = (
1269
1544
 
1270
1545
 
1271
1546
  // Convert a node to a map.
1272
- // Format: { '`$PACK`':['`source-path`', child-template]}
1547
+ // Format: { '`$PACK`':['source-path', child-template]}
1273
1548
  const transform_PACK: Injector = (
1274
1549
  inj: Injection,
1275
1550
  _val: any,
@@ -1278,78 +1553,105 @@ const transform_PACK: Injector = (
1278
1553
  ) => {
1279
1554
  const { mode, key, path, parent, nodes } = inj
1280
1555
 
1281
- // Defensive context checks.
1282
- if (S_MKEYPRE !== mode || S_string !== typeof key || null == path || null == nodes) {
1283
- return UNDEF
1556
+ const ijname = 'EACH'
1557
+
1558
+ if (!checkPlacement(M_KEYPRE, ijname, T_map, inj)) {
1559
+ return NONE
1284
1560
  }
1285
1561
 
1286
1562
  // Get arguments.
1287
- const args = parent[key]
1288
- const srcpath = args[0] // Path to source data.
1289
- const child = clone(args[1]) // Child template.
1563
+ const args = getprop(parent, key)
1564
+ const [err, srcpath, origchildspec] = injectorArgs([T_string, T_any], args)
1565
+ if (NONE !== err) {
1566
+ inj.errs.push('$' + ijname + ': ' + err)
1567
+ return NONE
1568
+ }
1290
1569
 
1291
1570
  // Find key and target node.
1292
- const keyprop = child[S_BKEY]
1293
1571
  const tkey = getelem(path, -2)
1294
- const target = nodes[path.length - 2] || nodes[path.length - 1]
1572
+ const pathsize = size(path)
1573
+ const target = getelem(nodes, pathsize - 2, () => getelem(nodes, pathsize - 1))
1295
1574
 
1296
1575
  // Source data
1297
1576
  const srcstore = getprop(store, inj.base, store)
1298
-
1299
1577
  let src = getpath(srcstore, srcpath, inj)
1300
1578
 
1301
1579
  // Prepare source as a list.
1302
- src = islist(src) ? src :
1303
- ismap(src) ? Object.entries(src)
1304
- .reduce((a: any[], n: any) =>
1305
- (n[1][S_BANNO] = { KEY: n[0] }, a.push(n[1]), a), []) :
1306
- UNDEF
1580
+ if (!islist(src)) {
1581
+ if (ismap(src)) {
1582
+ src = items(src, (item: [string, any]) => {
1583
+ setprop(item[1], S_BANNO, { KEY: item[0] })
1584
+ return item[1]
1585
+ })
1586
+ }
1587
+ else {
1588
+ src = NONE
1589
+ }
1590
+ }
1307
1591
 
1308
1592
  if (null == src) {
1309
- return UNDEF
1593
+ return NONE
1310
1594
  }
1311
1595
 
1312
- // Get key if specified.
1313
- let childkey: PropKey | undefined = getprop(child, S_BKEY)
1314
- let keyname = UNDEF === childkey ? keyprop : childkey
1315
- delprop(child, S_BKEY)
1596
+ // Get keypath.
1597
+ const keypath = getprop(origchildspec, S_BKEY)
1598
+ const childspec = delprop(origchildspec, S_BKEY)
1599
+
1600
+ const child = getprop(childspec, S_BVAL, childspec)
1316
1601
 
1317
1602
  // Build parallel target object.
1318
1603
  let tval: any = {}
1319
- tval = src.reduce((a: any, n: any) => {
1320
- let kn = getprop(n, keyname)
1321
- setprop(a, kn, clone(child))
1322
- const nchild = getprop(a, kn)
1323
- const mval = getprop(n, S_BANNO)
1324
- if (UNDEF === mval) {
1325
- delprop(nchild, S_BANNO)
1604
+
1605
+ items(src, (item: [string, any]) => {
1606
+ const srckey = item[0]
1607
+ const srcnode = item[1]
1608
+
1609
+ let key: string = srckey
1610
+ if (NONE !== keypath) {
1611
+ if (keypath.startsWith('`')) {
1612
+ key = inject(keypath, merge([{}, store, { $TOP: srcnode }], 1))
1613
+ }
1614
+ else {
1615
+ key = getpath(srcnode, keypath, inj)
1616
+ }
1617
+ }
1618
+
1619
+ const tchild = clone(child)
1620
+ setprop(tval, key, tchild)
1621
+
1622
+ const anno = getprop(srcnode, S_BANNO)
1623
+ if (NONE === anno) {
1624
+ delprop(tchild, S_BANNO)
1326
1625
  }
1327
1626
  else {
1328
- setprop(nchild, S_BANNO, mval)
1627
+ setprop(tchild, S_BANNO, anno)
1329
1628
  }
1330
- return a
1331
- }, tval)
1629
+ })
1332
1630
 
1333
1631
  let rval = {}
1334
1632
 
1335
- if (0 < size(tval)) {
1633
+ if (!isempty(tval)) {
1336
1634
 
1337
1635
  // Build parallel source object.
1338
- let tcur: any = {}
1339
- src.reduce((a: any, n: any) => {
1340
- let kn = getprop(n, keyname)
1636
+ let tsrc: any = {}
1637
+ src.reduce((a: any, n: any, i: any) => {
1638
+ let kn = null == keypath ? i :
1639
+ keypath.startsWith('`') ?
1640
+ inject(keypath, merge([{}, store, { $TOP: n }], 1)) :
1641
+ getpath(n, keypath, inj)
1642
+
1341
1643
  setprop(a, kn, n)
1342
1644
  return a
1343
- }, tcur)
1645
+ }, tsrc)
1344
1646
 
1345
1647
  const tpath = slice(inj.path, -1)
1346
1648
 
1347
1649
  const ckey = getelem(inj.path, -2)
1348
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey]
1650
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey])
1349
1651
 
1350
- tcur = { [ckey]: tcur }
1652
+ let tcur = { [ckey]: tsrc }
1351
1653
 
1352
- if (1 < tpath.length) {
1654
+ if (1 < size(tpath)) {
1353
1655
  const pkey = getelem(inj.path, -3, S_DTOP)
1354
1656
  tcur = { [pkey]: tcur }
1355
1657
  dpath.push('$:' + pkey)
@@ -1359,7 +1661,6 @@ const transform_PACK: Injector = (
1359
1661
  tinj.path = tpath
1360
1662
  tinj.nodes = slice(inj.nodes, -1)
1361
1663
 
1362
- // tinj.parent = tcur
1363
1664
  tinj.parent = getelem(tinj.nodes, -1)
1364
1665
  tinj.val = tval
1365
1666
 
@@ -1370,14 +1671,15 @@ const transform_PACK: Injector = (
1370
1671
  rval = tinj.val
1371
1672
  }
1372
1673
 
1373
- _updateAncestors(inj, target, tkey, rval)
1674
+ // _updateAncestors(inj, target, tkey, rval)
1675
+ setprop(target, tkey, rval)
1374
1676
 
1375
1677
  // Drop transform key.
1376
- return UNDEF
1678
+ return NONE
1377
1679
  }
1378
1680
 
1379
1681
 
1380
- // TODO: not found ref should removed key (setprop UNDEF)
1682
+ // TODO: not found ref should removed key (setprop NONE)
1381
1683
  // Reference original spec (enables recursice transformations)
1382
1684
  // Format: ['`$REF`', '`spec-path`']
1383
1685
  const transform_REF: Injector = (
@@ -1388,21 +1690,24 @@ const transform_REF: Injector = (
1388
1690
  ) => {
1389
1691
  const { nodes } = inj
1390
1692
 
1391
- if (S_MVAL !== inj.mode) {
1392
- return UNDEF
1693
+ if (M_VAL !== inj.mode) {
1694
+ return NONE
1393
1695
  }
1394
1696
 
1395
1697
  // Get arguments: ['`$REF`', 'ref-path'].
1396
1698
  const refpath = getprop(inj.parent, 1)
1397
- inj.keyI = inj.keys.length
1699
+ inj.keyI = size(inj.keys)
1398
1700
 
1399
1701
  // Spec reference.
1400
1702
  const spec = getprop(store, S_DSPEC)()
1401
1703
 
1704
+ const dpath = slice(inj.path, 1)
1402
1705
  const ref = getpath(spec, refpath, {
1403
1706
  // TODO: test relative refs
1404
- dpath: inj.path.slice(1),
1405
- dparent: getpath(spec, inj.path.slice(1))
1707
+ // dpath: inj.path.slice(1),
1708
+ dpath,
1709
+ // dparent: getpath(spec, inj.path.slice(1))
1710
+ dparent: getpath(spec, dpath),
1406
1711
  })
1407
1712
 
1408
1713
  let hasSubRef = false
@@ -1421,9 +1726,9 @@ const transform_REF: Injector = (
1421
1726
  const tpath = slice(inj.path, -1)
1422
1727
  let tcur = getpath(store, cpath)
1423
1728
  let tval = getpath(store, tpath)
1424
- let rval = UNDEF
1729
+ let rval = NONE
1425
1730
 
1426
- if (!hasSubRef || UNDEF !== tval) {
1731
+ if (!hasSubRef || NONE !== tval) {
1427
1732
  const tinj = inj.child(0, [getelem(tpath, -1)])
1428
1733
 
1429
1734
  tinj.path = tpath
@@ -1431,7 +1736,7 @@ const transform_REF: Injector = (
1431
1736
  tinj.parent = getelem(nodes, -2)
1432
1737
  tinj.val = tref
1433
1738
 
1434
- tinj.dpath = [...cpath]
1739
+ tinj.dpath = flatten([cpath])
1435
1740
  tinj.dparent = tcur
1436
1741
 
1437
1742
  inject(tref, store, tinj)
@@ -1439,7 +1744,7 @@ const transform_REF: Injector = (
1439
1744
  rval = tinj.val
1440
1745
  }
1441
1746
  else {
1442
- rval = UNDEF
1747
+ rval = NONE
1443
1748
  }
1444
1749
 
1445
1750
  const grandparent = inj.setval(rval, 2)
@@ -1452,6 +1757,117 @@ const transform_REF: Injector = (
1452
1757
  }
1453
1758
 
1454
1759
 
1760
+ const transform_FORMAT: Injector = (
1761
+ inj: Injection,
1762
+ _val: any,
1763
+ _ref: string,
1764
+ store: any
1765
+ ) => {
1766
+ // console.log('FORMAT-START', inj, _val)
1767
+
1768
+ // Remove remaining keys to avoid spurious processing.
1769
+ slice(inj.keys, 0, 1, true)
1770
+
1771
+ if (M_VAL !== inj.mode) {
1772
+ return NONE
1773
+ }
1774
+
1775
+ // Get arguments: ['`$FORMAT`', 'name', child].
1776
+ // TODO: EACH and PACK should accept customm functions too
1777
+ const name = getprop(inj.parent, 1)
1778
+ const child = getprop(inj.parent, 2)
1779
+
1780
+ // Source data.
1781
+ const tkey = getelem(inj.path, -2)
1782
+ const target = getelem(inj.nodes, - 2, () => getelem(inj.nodes, -1))
1783
+
1784
+ const cinj = injectChild(child, store, inj)
1785
+ const resolved = cinj.val
1786
+
1787
+ let formatter = 0 < (T_function & typify(name)) ? name : getprop(FORMATTER, name)
1788
+
1789
+ if (NONE === formatter) {
1790
+ inj.errs.push('$FORMAT: unknown format: ' + name + '.')
1791
+ return NONE
1792
+ }
1793
+
1794
+ let out = walk(resolved, formatter)
1795
+
1796
+ setprop(target, tkey, out)
1797
+ // _updateAncestors(inj, target, tkey, out)
1798
+
1799
+ return out
1800
+ }
1801
+
1802
+
1803
+ const FORMATTER: Record<string, WalkApply> = {
1804
+ identity: (_k: any, v: any) => v,
1805
+ upper: (_k: any, v: any) => isnode(v) ? v : ('' + v).toUpperCase(),
1806
+ lower: (_k: any, v: any) => isnode(v) ? v : ('' + v).toLowerCase(),
1807
+ string: (_k: any, v: any) => isnode(v) ? v : ('' + v),
1808
+ number: (_k: any, v: any) => {
1809
+ if (isnode(v)) {
1810
+ return v
1811
+ }
1812
+ else {
1813
+ let n = Number(v)
1814
+ if (isNaN(n)) {
1815
+ n = 0
1816
+ }
1817
+ return n
1818
+ }
1819
+ },
1820
+ integer: (_k: any, v: any) => {
1821
+ if (isnode(v)) {
1822
+ return v
1823
+ }
1824
+ else {
1825
+ let n = Number(v)
1826
+ if (isNaN(n)) {
1827
+ n = 0
1828
+ }
1829
+ return n | 0
1830
+ }
1831
+ },
1832
+ concat: (k: any, v: any) =>
1833
+ null == k && islist(v) ? join(items(v, (n => isnode(n[1]) ? S_MT : (S_MT + n[1]))), S_MT) : v
1834
+ }
1835
+
1836
+
1837
+
1838
+ const transform_APPLY: Injector = (
1839
+ inj: Injection,
1840
+ _val: any,
1841
+ _ref: string,
1842
+ store: any
1843
+ ) => {
1844
+ const ijname = 'APPLY'
1845
+
1846
+ if (!checkPlacement(M_VAL, ijname, T_list, inj)) {
1847
+ return NONE
1848
+ }
1849
+
1850
+ // const [err, apply, child] = injectorArgs([T_function, T_any], inj)
1851
+ const [err, apply, child] = injectorArgs([T_function, T_any], slice(inj.parent, 1))
1852
+ if (NONE !== err) {
1853
+ inj.errs.push('$' + ijname + ': ' + err)
1854
+ return NONE
1855
+ }
1856
+
1857
+ const tkey = getelem(inj.path, -2)
1858
+ const target = getelem(inj.nodes, - 2, () => getelem(inj.nodes, -1))
1859
+
1860
+ const cinj = injectChild(child, store, inj)
1861
+ const resolved = cinj.val
1862
+
1863
+ const out = apply(resolved, store, cinj)
1864
+
1865
+ setprop(target, tkey, out)
1866
+
1867
+ return out
1868
+ }
1869
+
1870
+
1455
1871
  // Transform data using spec.
1456
1872
  // Only operates on static JSON-like data.
1457
1873
  // Arrays are treated as if they are objects with indices as keys.
@@ -1465,51 +1881,66 @@ function transform(
1465
1881
  spec = clone(origspec)
1466
1882
 
1467
1883
  const extra = injdef?.extra
1468
- // const modify = injdef?.modify
1884
+
1885
+ const collect = null != injdef?.errs
1886
+ const errs = injdef?.errs || []
1469
1887
 
1470
1888
  const extraTransforms: any = {}
1471
- const extraData = null == extra ? UNDEF : items(extra)
1889
+ const extraData = null == extra ? NONE : items(extra)
1472
1890
  .reduce((a: any, n: any[]) =>
1473
1891
  (n[0].startsWith(S_DS) ? extraTransforms[n[0]] = n[1] : (a[n[0]] = n[1]), a), {})
1474
1892
 
1475
1893
  const dataClone = merge([
1476
- isempty(extraData) ? UNDEF : clone(extraData),
1894
+ isempty(extraData) ? NONE : clone(extraData),
1477
1895
  clone(data),
1478
1896
  ])
1479
1897
 
1480
1898
  // Define a top level store that provides transform operations.
1481
- const store = {
1482
-
1483
- // The inject function recognises this special location for the root of the source data.
1484
- // NOTE: to escape data that contains "`$FOO`" keys at the top level,
1485
- // place that data inside a holding map: { myholder: mydata }.
1486
- $TOP: dataClone,
1899
+ const store = merge([
1900
+ {
1901
+ // The inject function recognises this special location for the root of the source data.
1902
+ // NOTE: to escape data that contains "`$FOO`" keys at the top level,
1903
+ // place that data inside a holding map: { myholder: mydata }.
1904
+ $TOP: dataClone,
1905
+
1906
+ $SPEC: () => origspec,
1907
+
1908
+ // Escape backtick (this also works inside backticks).
1909
+ $BT: () => S_BT,
1910
+
1911
+ // Escape dollar sign (this also works inside backticks).
1912
+ $DS: () => S_DS,
1913
+
1914
+ // Insert current date and time as an ISO string.
1915
+ $WHEN: () => new Date().toISOString(),
1916
+
1917
+ $DELETE: transform_DELETE,
1918
+ $COPY: transform_COPY,
1919
+ $KEY: transform_KEY,
1920
+ $ANNO: transform_ANNO,
1921
+ $MERGE: transform_MERGE,
1922
+ $EACH: transform_EACH,
1923
+ $PACK: transform_PACK,
1924
+ $REF: transform_REF,
1925
+ $FORMAT: transform_FORMAT,
1926
+ $APPLY: transform_APPLY,
1927
+ },
1487
1928
 
1488
- $SPEC: () => origspec,
1489
-
1490
- // Escape backtick (this also works inside backticks).
1491
- $BT: () => S_BT,
1492
-
1493
- // Escape dollar sign (this also works inside backticks).
1494
- $DS: () => S_DS,
1929
+ // Custom extra transforms, if any.
1930
+ extraTransforms,
1495
1931
 
1496
- // Insert current date and time as an ISO string.
1497
- $WHEN: () => new Date().toISOString(),
1932
+ {
1933
+ $ERRS: errs,
1934
+ }
1935
+ ], 1)
1498
1936
 
1499
- $DELETE: transform_DELETE,
1500
- $COPY: transform_COPY,
1501
- $KEY: transform_KEY,
1502
- $ANNO: transform_ANNO,
1503
- $MERGE: transform_MERGE,
1504
- $EACH: transform_EACH,
1505
- $PACK: transform_PACK,
1506
- $REF: transform_REF,
1937
+ const out = inject(spec, store, injdef)
1507
1938
 
1508
- // Custom extra transforms, if any.
1509
- ...extraTransforms,
1939
+ const generr = (0 < size(errs) && !collect)
1940
+ if (generr) {
1941
+ throw new Error(join(errs, ' | '))
1510
1942
  }
1511
1943
 
1512
- const out = inject(spec, store, injdef)
1513
1944
  return out
1514
1945
  }
1515
1946
 
@@ -1519,16 +1950,16 @@ const validate_STRING: Injector = (inj: Injection) => {
1519
1950
  let out = getprop(inj.dparent, inj.key)
1520
1951
 
1521
1952
  const t = typify(out)
1522
- if (S_string !== t) {
1953
+ if (0 === (T_string & t)) {
1523
1954
  let msg = _invalidTypeMsg(inj.path, S_string, t, out, 'V1010')
1524
1955
  inj.errs.push(msg)
1525
- return UNDEF
1956
+ return NONE
1526
1957
  }
1527
1958
 
1528
1959
  if (S_MT === out) {
1529
1960
  let msg = 'Empty string at ' + pathify(inj.path, 1)
1530
1961
  inj.errs.push(msg)
1531
- return UNDEF
1962
+ return NONE
1532
1963
  }
1533
1964
 
1534
1965
  return out
@@ -1538,13 +1969,17 @@ const validate_STRING: Injector = (inj: Injection) => {
1538
1969
 
1539
1970
 
1540
1971
  const validate_TYPE: Injector = (inj: Injection, _val: any, ref: string) => {
1541
- let tname = slice(ref, 1).toLowerCase()
1972
+ const tname = slice(ref, 1).toLowerCase()
1973
+ const typev = 1 << (31 - TYPENAME.indexOf(tname))
1542
1974
  let out = getprop(inj.dparent, inj.key)
1543
1975
 
1544
1976
  const t = typify(out)
1545
- if (t !== tname) {
1977
+
1978
+ // console.log('TYPE', tname, typev, tn(typev), 'O=', t, tn(t), out, 'C=', t & typev)
1979
+
1980
+ if (0 === (t & typev)) {
1546
1981
  inj.errs.push(_invalidTypeMsg(inj.path, tname, t, out, 'V1001'))
1547
- return UNDEF
1982
+ return NONE
1548
1983
  }
1549
1984
 
1550
1985
  return out
@@ -1568,20 +2003,20 @@ const validate_CHILD: Injector = (inj: Injection) => {
1568
2003
  // Setup data structures for validation by cloning child template.
1569
2004
 
1570
2005
  // Map syntax.
1571
- if (S_MKEYPRE === mode) {
2006
+ if (M_KEYPRE === mode) {
1572
2007
  const childtm = getprop(parent, key)
1573
2008
 
1574
2009
  // Get corresponding current object.
1575
- const pkey = getprop(path, path.length - 2)
2010
+ const pkey = getelem(path, -2)
1576
2011
  let tval = getprop(inj.dparent, pkey)
1577
2012
 
1578
- if (UNDEF == tval) {
2013
+ if (NONE == tval) {
1579
2014
  tval = {}
1580
2015
  }
1581
2016
  else if (!ismap(tval)) {
1582
2017
  inj.errs.push(_invalidTypeMsg(
1583
2018
  slice(inj.path, -1), S_object, typify(tval), tval), 'V0220')
1584
- return UNDEF
2019
+ return NONE
1585
2020
  }
1586
2021
 
1587
2022
  const ckeys = keysof(tval)
@@ -1593,52 +2028,56 @@ const validate_CHILD: Injector = (inj: Injection) => {
1593
2028
  }
1594
2029
 
1595
2030
  // Remove $CHILD to cleanup ouput.
1596
- inj.setval(UNDEF)
1597
- return UNDEF
2031
+ inj.setval(NONE)
2032
+ return NONE
1598
2033
  }
1599
2034
 
1600
2035
  // List syntax.
1601
- if (S_MVAL === mode) {
2036
+ if (M_VAL === mode) {
1602
2037
 
1603
2038
  if (!islist(parent)) {
1604
2039
  // $CHILD was not inside a list.
1605
2040
  inj.errs.push('Invalid $CHILD as value')
1606
- return UNDEF
2041
+ return NONE
1607
2042
  }
1608
2043
 
1609
2044
  const childtm = getprop(parent, 1)
1610
2045
 
1611
- if (UNDEF === inj.dparent) {
2046
+ if (NONE === inj.dparent) {
1612
2047
  // Empty list as default.
1613
- parent.length = 0
1614
- return UNDEF
2048
+ // parent.length = 0
2049
+ slice(parent, 0, 0, true)
2050
+ return NONE
1615
2051
  }
1616
2052
 
1617
2053
  if (!islist(inj.dparent)) {
1618
2054
  const msg = _invalidTypeMsg(
1619
- slice(inj.path, -1), S_array, typify(inj.dparent), inj.dparent, 'V0230')
2055
+ slice(inj.path, -1), S_list, typify(inj.dparent), inj.dparent, 'V0230')
1620
2056
  inj.errs.push(msg)
1621
- inj.keyI = parent.length
2057
+ inj.keyI = size(parent)
1622
2058
  return inj.dparent
1623
2059
  }
1624
2060
 
1625
2061
  // Clone children abd reset inj key index.
1626
2062
  // The inject child loop will now iterate over the cloned children,
1627
2063
  // validating them againt the current list values.
1628
-
1629
- inj.dparent.map((_n, i) => parent[i] = clone(childtm))
1630
- parent.length = inj.dparent.length
2064
+ items(inj.dparent, (n) => setprop(parent, n[0], clone(childtm)))
2065
+ slice(parent, 0, inj.dparent.length, true)
1631
2066
  inj.keyI = 0
2067
+
1632
2068
  const out = getprop(inj.dparent, 0)
1633
2069
  return out
1634
2070
  }
1635
2071
 
1636
- return UNDEF
2072
+ return NONE
1637
2073
  }
1638
2074
 
1639
2075
 
2076
+ // TODO: implement SOME, ALL
2077
+ // FIX: ONE should mean exactly one, not at least one (=SOME)
2078
+ // TODO: implement a generate validate_ALT to do all of these
1640
2079
  // Match at least one of the specified shapes.
1641
- // Syntax: ['`$ONE`', alt0, alt1, ...]okI
2080
+ // Syntax: ['`$ONE`', alt0, alt1, ...]
1642
2081
  const validate_ONE: Injector = (
1643
2082
  inj: Injection,
1644
2083
  _val: any,
@@ -1648,7 +2087,7 @@ const validate_ONE: Injector = (
1648
2087
  const { mode, parent, keyI } = inj
1649
2088
 
1650
2089
  // Only operate in val mode, since parent is a list.
1651
- if (S_MVAL === mode) {
2090
+ if (M_VAL === mode) {
1652
2091
  if (!islist(parent) || 0 !== keyI) {
1653
2092
  inj.errs.push('The $ONE validator at field ' +
1654
2093
  pathify(inj.path, 1, 1) +
@@ -1656,7 +2095,7 @@ const validate_ONE: Injector = (
1656
2095
  return
1657
2096
  }
1658
2097
 
1659
- inj.keyI = inj.keys.length
2098
+ inj.keyI = size(inj.keys)
1660
2099
 
1661
2100
  // Clean up structure, replacing [$ONE, ...] with current
1662
2101
  inj.setval(inj.dparent, 2)
@@ -1665,7 +2104,7 @@ const validate_ONE: Injector = (
1665
2104
  inj.key = getelem(inj.path, -1)
1666
2105
 
1667
2106
  let tvals = slice(parent, 1)
1668
- if (0 === tvals.length) {
2107
+ if (0 === size(tvals)) {
1669
2108
  inj.errs.push('The $ONE validator at field ' +
1670
2109
  pathify(inj.path, 1, 1) +
1671
2110
  ' must have at least one argument.')
@@ -1678,7 +2117,7 @@ const validate_ONE: Injector = (
1678
2117
  // If match, then errs.length = 0
1679
2118
  let terrs: any[] = []
1680
2119
 
1681
- const vstore = { ...store }
2120
+ const vstore = merge([{}, store], 1)
1682
2121
  vstore.$TOP = inj.dparent
1683
2122
 
1684
2123
  const vcurrent = validate(inj.dparent, tval, {
@@ -1690,21 +2129,19 @@ const validate_ONE: Injector = (
1690
2129
  inj.setval(vcurrent, -2)
1691
2130
 
1692
2131
  // Accept current value if there was a match
1693
- if (0 === terrs.length) {
2132
+ if (0 === size(terrs)) {
1694
2133
  return
1695
2134
  }
1696
2135
  }
1697
2136
 
1698
2137
  // There was no match.
1699
-
1700
- const valdesc = tvals
1701
- .map((v: any) => stringify(v))
1702
- .join(', ')
1703
- .replace(R_TRANSFORM_NAME, (_m: any, p1: string) => p1.toLowerCase())
2138
+ const valdesc =
2139
+ replace(join(items(tvals, (n) => stringify(n[1])), ', '),
2140
+ R_TRANSFORM_NAME, (_m: any, p1: string) => p1.toLowerCase())
1704
2141
 
1705
2142
  inj.errs.push(_invalidTypeMsg(
1706
2143
  inj.path,
1707
- (1 < tvals.length ? 'one of ' : '') + valdesc,
2144
+ (1 < size(tvals) ? 'one of ' : '') + valdesc,
1708
2145
  typify(inj.dparent), inj.dparent, 'V0210'))
1709
2146
  }
1710
2147
  }
@@ -1714,7 +2151,7 @@ const validate_EXACT: Injector = (inj: Injection) => {
1714
2151
  const { mode, parent, key, keyI } = inj
1715
2152
 
1716
2153
  // Only operate in val mode, since parent is a list.
1717
- if (S_MVAL === mode) {
2154
+ if (M_VAL === mode) {
1718
2155
  if (!islist(parent) || 0 !== keyI) {
1719
2156
  inj.errs.push('The $EXACT validator at field ' +
1720
2157
  pathify(inj.path, 1, 1) +
@@ -1722,16 +2159,17 @@ const validate_EXACT: Injector = (inj: Injection) => {
1722
2159
  return
1723
2160
  }
1724
2161
 
1725
- inj.keyI = inj.keys.length
2162
+ inj.keyI = size(inj.keys)
1726
2163
 
1727
2164
  // Clean up structure, replacing [$EXACT, ...] with current data parent
1728
2165
  inj.setval(inj.dparent, 2)
1729
2166
 
1730
- inj.path = slice(inj.path, 0, inj.path.length - 1)
2167
+ // inj.path = slice(inj.path, 0, size(inj.path) - 1)
2168
+ inj.path = slice(inj.path, 0, -1)
1731
2169
  inj.key = getelem(inj.path, -1)
1732
2170
 
1733
2171
  let tvals = slice(parent, 1)
1734
- if (0 === tvals.length) {
2172
+ if (0 === size(tvals)) {
1735
2173
  inj.errs.push('The $EXACT validator at field ' +
1736
2174
  pathify(inj.path, 1, 1) +
1737
2175
  ' must have at least one argument.')
@@ -1754,15 +2192,15 @@ const validate_EXACT: Injector = (inj: Injection) => {
1754
2192
  }
1755
2193
  }
1756
2194
 
1757
- const valdesc = tvals
1758
- .map((v: any) => stringify(v))
1759
- .join(', ')
1760
- .replace(R_TRANSFORM_NAME, (_m: any, p1: string) => p1.toLowerCase())
2195
+ // There was no match.
2196
+ const valdesc =
2197
+ replace(join(items(tvals, (n) => stringify(n[1])), ', '),
2198
+ R_TRANSFORM_NAME, (_m: any, p1: string) => p1.toLowerCase())
1761
2199
 
1762
2200
  inj.errs.push(_invalidTypeMsg(
1763
2201
  inj.path,
1764
- (1 < inj.path.length ? '' : 'value ') +
1765
- 'exactly equal to ' + (1 === tvals.length ? '' : 'one of ') + valdesc,
2202
+ (1 < size(inj.path) ? '' : 'value ') +
2203
+ 'exactly equal to ' + (1 === size(tvals) ? '' : 'one of ') + valdesc,
1766
2204
  typify(inj.dparent), inj.dparent, 'V0110'))
1767
2205
  }
1768
2206
  else {
@@ -1780,7 +2218,7 @@ const _validation: Modify = (
1780
2218
  inj?: Injection,
1781
2219
  ) => {
1782
2220
 
1783
- if (UNDEF === inj) {
2221
+ if (NONE === inj) {
1784
2222
  return
1785
2223
  }
1786
2224
 
@@ -1794,28 +2232,28 @@ const _validation: Modify = (
1794
2232
  // Current val to verify.
1795
2233
  const cval = getprop(inj.dparent, key)
1796
2234
 
1797
- if (UNDEF === inj || (!exact && UNDEF === cval)) {
2235
+ if (NONE === inj || (!exact && NONE === cval)) {
1798
2236
  return
1799
2237
  }
1800
2238
 
1801
2239
  const ptype = typify(pval)
1802
2240
 
1803
2241
  // Delete any special commands remaining.
1804
- if (S_string === ptype && pval.includes(S_DS)) {
2242
+ if (0 < (T_string & ptype) && pval.includes(S_DS)) {
1805
2243
  return
1806
2244
  }
1807
2245
 
1808
2246
  const ctype = typify(cval)
1809
2247
 
1810
2248
  // Type mismatch.
1811
- if (ptype !== ctype && UNDEF !== pval) {
1812
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0010'))
2249
+ if (ptype !== ctype && NONE !== pval) {
2250
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0010'))
1813
2251
  return
1814
2252
  }
1815
2253
 
1816
2254
  if (ismap(cval)) {
1817
2255
  if (!ismap(pval)) {
1818
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0020'))
2256
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0020'))
1819
2257
  return
1820
2258
  }
1821
2259
 
@@ -1823,7 +2261,7 @@ const _validation: Modify = (
1823
2261
  const pkeys = keysof(pval)
1824
2262
 
1825
2263
  // Empty spec object {} means object can be open (any keys).
1826
- if (0 < pkeys.length && true !== getprop(pval, '`$OPEN`')) {
2264
+ if (0 < size(pkeys) && true !== getprop(pval, '`$OPEN`')) {
1827
2265
  const badkeys = []
1828
2266
  for (let ckey of ckeys) {
1829
2267
  if (!haskey(pval, ckey)) {
@@ -1832,9 +2270,9 @@ const _validation: Modify = (
1832
2270
  }
1833
2271
 
1834
2272
  // Closed object, so reject extra keys not in shape.
1835
- if (0 < badkeys.length) {
2273
+ if (0 < size(badkeys)) {
1836
2274
  const msg =
1837
- 'Unexpected keys at field ' + pathify(inj.path, 1) + S_VIZ + badkeys.join(', ')
2275
+ 'Unexpected keys at field ' + pathify(inj.path, 1) + S_VIZ + join(badkeys, ', ')
1838
2276
  inj.errs.push(msg)
1839
2277
  }
1840
2278
  }
@@ -1848,7 +2286,7 @@ const _validation: Modify = (
1848
2286
  }
1849
2287
  else if (islist(cval)) {
1850
2288
  if (!islist(pval)) {
1851
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0030'))
2289
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0030'))
1852
2290
  }
1853
2291
  }
1854
2292
  else if (exact) {
@@ -1888,34 +2326,42 @@ function validate(
1888
2326
  const collect = null != injdef?.errs
1889
2327
  const errs = injdef?.errs || []
1890
2328
 
1891
- const store = {
1892
- // Remove the transform commands.
1893
- $DELETE: null,
1894
- $COPY: null,
1895
- $KEY: null,
1896
- $META: null,
1897
- $MERGE: null,
1898
- $EACH: null,
1899
- $PACK: null,
1900
-
1901
- $STRING: validate_STRING,
1902
- $NUMBER: validate_TYPE,
1903
- $BOOLEAN: validate_TYPE,
1904
- $OBJECT: validate_TYPE,
1905
- $ARRAY: validate_TYPE,
1906
- $FUNCTION: validate_TYPE,
1907
- $INSTANCE: validate_TYPE,
1908
- $ANY: validate_ANY,
1909
- $CHILD: validate_CHILD,
1910
- $ONE: validate_ONE,
1911
- $EXACT: validate_EXACT,
1912
-
1913
- ...(extra || {}),
2329
+ const store = merge([
2330
+ {
2331
+ // Remove the transform commands.
2332
+ $DELETE: null,
2333
+ $COPY: null,
2334
+ $KEY: null,
2335
+ $META: null,
2336
+ $MERGE: null,
2337
+ $EACH: null,
2338
+ $PACK: null,
2339
+
2340
+ $STRING: validate_STRING,
2341
+ $NUMBER: validate_TYPE,
2342
+ $INTEGER: validate_TYPE,
2343
+ $DECIMAL: validate_TYPE,
2344
+ $BOOLEAN: validate_TYPE,
2345
+ $NULL: validate_TYPE,
2346
+ $NIL: validate_TYPE,
2347
+ $MAP: validate_TYPE,
2348
+ $LIST: validate_TYPE,
2349
+ $FUNCTION: validate_TYPE,
2350
+ $INSTANCE: validate_TYPE,
2351
+ $ANY: validate_ANY,
2352
+ $CHILD: validate_CHILD,
2353
+ $ONE: validate_ONE,
2354
+ $EXACT: validate_EXACT,
2355
+ },
2356
+
2357
+ getdef(extra, {}),
1914
2358
 
1915
2359
  // A special top level value to collect errors.
1916
- // NOTE: collecterrs paramter always wins.
1917
- $ERRS: errs,
1918
- }
2360
+ // NOTE: collecterrs parameter always wins.
2361
+ {
2362
+ $ERRS: errs,
2363
+ }
2364
+ ], 1)
1919
2365
 
1920
2366
  let meta = getprop(injdef, 'meta', {})
1921
2367
  setprop(meta, S_BEXACT, getprop(meta, S_BEXACT, false))
@@ -1924,12 +2370,13 @@ function validate(
1924
2370
  meta,
1925
2371
  extra: store,
1926
2372
  modify: _validation,
1927
- handler: _validatehandler
2373
+ handler: _validatehandler,
2374
+ errs,
1928
2375
  })
1929
2376
 
1930
- const generr = (0 < errs.length && !collect)
2377
+ const generr = (0 < size(errs) && !collect)
1931
2378
  if (generr) {
1932
- throw new Error('Invalid data: ' + errs.join(' | '))
2379
+ throw new Error(join(errs, ' | '))
1933
2380
  }
1934
2381
 
1935
2382
  return out
@@ -1937,18 +2384,16 @@ function validate(
1937
2384
 
1938
2385
 
1939
2386
  const select_AND: Injector = (inj: Injection, _val: any, _ref: string, store: any) => {
1940
- if (S_MKEYPRE === inj.mode) {
2387
+ if (M_KEYPRE === inj.mode) {
1941
2388
  const terms = getprop(inj.parent, inj.key)
1942
2389
 
1943
2390
  const ppath = slice(inj.path, -1)
1944
2391
  const point = getpath(store, ppath)
1945
2392
 
1946
- const vstore = { ...store }
2393
+ const vstore = merge([{}, store], 1)
1947
2394
  vstore.$TOP = point
1948
2395
 
1949
2396
  for (let term of terms) {
1950
- // setprop(term, '`$OPEN`', getprop(term, '`$OPEN`', true))
1951
-
1952
2397
  let terrs: any[] = []
1953
2398
 
1954
2399
  validate(point, term, {
@@ -1957,7 +2402,7 @@ const select_AND: Injector = (inj: Injection, _val: any, _ref: string, store: an
1957
2402
  meta: inj.meta,
1958
2403
  })
1959
2404
 
1960
- if (0 != terrs.length) {
2405
+ if (0 != size(terrs)) {
1961
2406
  inj.errs.push(
1962
2407
  'AND:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(terms))
1963
2408
  }
@@ -1971,13 +2416,13 @@ const select_AND: Injector = (inj: Injection, _val: any, _ref: string, store: an
1971
2416
 
1972
2417
 
1973
2418
  const select_OR: Injector = (inj: Injection, _val: any, _ref: string, store: any) => {
1974
- if (S_MKEYPRE === inj.mode) {
2419
+ if (M_KEYPRE === inj.mode) {
1975
2420
  const terms = getprop(inj.parent, inj.key)
1976
2421
 
1977
2422
  const ppath = slice(inj.path, -1)
1978
2423
  const point = getpath(store, ppath)
1979
2424
 
1980
- const vstore = { ...store }
2425
+ const vstore = merge([{}, store], 1)
1981
2426
  vstore.$TOP = point
1982
2427
 
1983
2428
  for (let term of terms) {
@@ -1989,7 +2434,7 @@ const select_OR: Injector = (inj: Injection, _val: any, _ref: string, store: any
1989
2434
  meta: inj.meta,
1990
2435
  })
1991
2436
 
1992
- if (0 === terrs.length) {
2437
+ if (0 === size(terrs)) {
1993
2438
  const gkey = getelem(inj.path, -2)
1994
2439
  const gp = getelem(inj.nodes, -2)
1995
2440
  setprop(gp, gkey, point)
@@ -2005,13 +2450,13 @@ const select_OR: Injector = (inj: Injection, _val: any, _ref: string, store: any
2005
2450
 
2006
2451
 
2007
2452
  const select_NOT: Injector = (inj: Injection, _val: any, _ref: string, store: any) => {
2008
- if (S_MKEYPRE === inj.mode) {
2453
+ if (M_KEYPRE === inj.mode) {
2009
2454
  const term = getprop(inj.parent, inj.key)
2010
2455
 
2011
2456
  const ppath = slice(inj.path, -1)
2012
2457
  const point = getpath(store, ppath)
2013
2458
 
2014
- const vstore = { ...store }
2459
+ const vstore = merge([{}, store], 1)
2015
2460
  vstore.$TOP = point
2016
2461
 
2017
2462
  let terrs: any[] = []
@@ -2022,7 +2467,7 @@ const select_NOT: Injector = (inj: Injection, _val: any, _ref: string, store: an
2022
2467
  meta: inj.meta,
2023
2468
  })
2024
2469
 
2025
- if (0 == terrs.length) {
2470
+ if (0 == size(terrs)) {
2026
2471
  inj.errs.push(
2027
2472
  'NOT:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(term))
2028
2473
  }
@@ -2035,7 +2480,7 @@ const select_NOT: Injector = (inj: Injection, _val: any, _ref: string, store: an
2035
2480
 
2036
2481
 
2037
2482
  const select_CMP: Injector = (inj: Injection, _val: any, ref: string, store: any) => {
2038
- if (S_MKEYPRE === inj.mode) {
2483
+ if (M_KEYPRE === inj.mode) {
2039
2484
  const term = getprop(inj.parent, inj.key)
2040
2485
  // const src = getprop(store, inj.base, store)
2041
2486
  const gkey = getelem(inj.path, -2)
@@ -2074,7 +2519,7 @@ const select_CMP: Injector = (inj: Injection, _val: any, ref: string, store: any
2074
2519
  }
2075
2520
  }
2076
2521
 
2077
- return UNDEF
2522
+ return NONE
2078
2523
  }
2079
2524
 
2080
2525
 
@@ -2088,10 +2533,13 @@ function select(children: any, query: any): any[] {
2088
2533
  }
2089
2534
 
2090
2535
  if (ismap(children)) {
2091
- children = items(children).map(n => (n[1][S_DKEY] = n[0], n[1]))
2536
+ children = items(children, n => {
2537
+ setprop(n[1], S_DKEY, n[0])
2538
+ return n[1]
2539
+ })
2092
2540
  }
2093
2541
  else {
2094
- children = (children as any[]).map((n, i) => ((ismap(n) ? n[S_DKEY] = i : null), n))
2542
+ children = items(children, (n) => (setprop(n[1], S_DKEY, +n[0]), n[1]))
2095
2543
  }
2096
2544
 
2097
2545
  const results: any[] = []
@@ -2133,10 +2581,9 @@ function select(children: any, query: any): any[] {
2133
2581
  }
2134
2582
 
2135
2583
 
2136
-
2137
2584
  // Injection state used for recursive injection into JSON - like data structures.
2138
2585
  class Injection {
2139
- mode: InjectMode // Injection mode: key:pre, val, key:post.
2586
+ mode: InjectMode // Injection mode: M_KEYPRE, M_VAL, M_KEYPOST.
2140
2587
  full: boolean // Transform escape was full key name.
2141
2588
  keyI: number // Index of parent key in list of parent keys.
2142
2589
  keys: string[] // List of parent keys.
@@ -2160,10 +2607,10 @@ class Injection {
2160
2607
  this.parent = parent
2161
2608
  this.errs = []
2162
2609
 
2163
- this.dparent = UNDEF
2610
+ this.dparent = NONE
2164
2611
  this.dpath = [S_DTOP]
2165
2612
 
2166
- this.mode = S_MVAL as InjectMode
2613
+ this.mode = M_VAL
2167
2614
  this.full = false
2168
2615
  this.keyI = 0
2169
2616
  this.keys = [S_DTOP]
@@ -2179,7 +2626,7 @@ class Injection {
2179
2626
  toString(prefix?: string) {
2180
2627
  return 'INJ' + (null == prefix ? '' : S_FS + prefix) + S_CN +
2181
2628
  pad(pathify(this.path, 1)) +
2182
- this.mode + (this.full ? '/full' : '') + S_CN +
2629
+ MODENAME[this.mode] + (this.full ? '/full' : '') + S_CN +
2183
2630
  'key=' + this.keyI + S_FS + this.key + S_FS + S_OS + this.keys + S_CS +
2184
2631
  ' p=' + stringify(this.parent, -1, 1) +
2185
2632
  ' m=' + stringify(this.meta, -1, 1) +
@@ -2193,12 +2640,12 @@ class Injection {
2193
2640
  const parentkey = getelem(this.path, -2)
2194
2641
 
2195
2642
  // Resolve current node in store for local paths.
2196
- if (UNDEF === this.dparent) {
2643
+ if (NONE === this.dparent) {
2197
2644
 
2198
2645
  // Even if there's no data, dpath should continue to match path, so that
2199
2646
  // relative paths work properly.
2200
- if (1 < this.dpath.length) {
2201
- this.dpath = [...this.dpath, parentkey]
2647
+ if (1 < size(this.dpath)) {
2648
+ this.dpath = flatten([this.dpath, parentkey])
2202
2649
  }
2203
2650
  }
2204
2651
  else {
@@ -2211,7 +2658,7 @@ class Injection {
2211
2658
  this.dpath = slice(this.dpath, -1)
2212
2659
  }
2213
2660
  else {
2214
- this.dpath = [...this.dpath, parentkey]
2661
+ this.dpath = flatten([this.dpath, parentkey])
2215
2662
  }
2216
2663
  }
2217
2664
  }
@@ -2230,8 +2677,8 @@ class Injection {
2230
2677
  cinj.keys = keys
2231
2678
  cinj.key = key
2232
2679
 
2233
- cinj.path = [...(this.path || []), key]
2234
- cinj.nodes = [...(this.nodes || []), val]
2680
+ cinj.path = flatten([getdef(this.path, []), key])
2681
+ cinj.nodes = flatten([getdef(this.nodes, []), [val]])
2235
2682
 
2236
2683
  cinj.mode = this.mode
2237
2684
  cinj.handler = this.handler
@@ -2241,7 +2688,7 @@ class Injection {
2241
2688
  cinj.errs = this.errs
2242
2689
  cinj.prior = this
2243
2690
 
2244
- cinj.dpath = [...this.dpath]
2691
+ cinj.dpath = flatten([this.dpath])
2245
2692
  cinj.dparent = this.dparent
2246
2693
 
2247
2694
  return cinj
@@ -2249,18 +2696,22 @@ class Injection {
2249
2696
 
2250
2697
 
2251
2698
  setval(val: any, ancestor?: number) {
2699
+ let parent = NONE
2252
2700
  if (null == ancestor || ancestor < 2) {
2253
- return UNDEF === val ?
2254
- delprop(this.parent, this.key) :
2701
+ parent = NONE === val ?
2702
+ this.parent = delprop(this.parent, this.key) :
2255
2703
  setprop(this.parent, this.key, val)
2256
2704
  }
2257
2705
  else {
2258
2706
  const aval = getelem(this.nodes, 0 - ancestor)
2259
2707
  const akey = getelem(this.path, 0 - ancestor)
2260
- return UNDEF === val ?
2708
+ parent = NONE === val ?
2261
2709
  delprop(aval, akey) :
2262
2710
  setprop(aval, akey, val)
2263
2711
  }
2712
+
2713
+ // console.log('SETVAL', val, this.key, this.parent)
2714
+ return parent
2264
2715
  }
2265
2716
  }
2266
2717
 
@@ -2269,21 +2720,21 @@ class Injection {
2269
2720
  // ==================
2270
2721
 
2271
2722
 
2272
- // Update all references to target in inj.nodes.
2273
- function _updateAncestors(_inj: Injection, target: any, tkey: any, tval: any) {
2274
- // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
2275
- setprop(target, tkey, tval)
2276
- }
2723
+ // // Update all references to target in inj.nodes.
2724
+ // function _updateAncestors(_inj: Injection, target: any, tkey: any, tval: any) {
2725
+ // // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
2726
+ // setprop(target, tkey, tval)
2727
+ // }
2277
2728
 
2278
2729
 
2279
2730
  // Build a type validation error message.
2280
- function _invalidTypeMsg(path: any, needtype: string, vt: string, v: any, _whence?: string) {
2731
+ function _invalidTypeMsg(path: any, needtype: string, vt: number, v: any, _whence?: string) {
2281
2732
  let vs = null == v ? 'no value' : stringify(v)
2282
2733
 
2283
2734
  return 'Expected ' +
2284
- (1 < path.length ? ('field ' + pathify(path, 1) + ' to be ') : '') +
2735
+ (1 < size(path) ? ('field ' + pathify(path, 1) + ' to be ') : '') +
2285
2736
  needtype + ', but found ' +
2286
- (null != v ? vt + S_VIZ : '') + vs +
2737
+ (null != v ? typename(vt) + S_VIZ : '') + vs +
2287
2738
 
2288
2739
  // Uncomment to help debug validation errors.
2289
2740
  // ' [' + _whence + ']' +
@@ -2301,7 +2752,7 @@ const _injecthandler: Injector = (
2301
2752
  store: any
2302
2753
  ): any => {
2303
2754
  let out = val
2304
- const iscmd = isfunc(val) && (UNDEF === ref || ref.startsWith(S_DS))
2755
+ const iscmd = isfunc(val) && (NONE === ref || ref.startsWith(S_DS))
2305
2756
 
2306
2757
  // Only call val function if it is a special command ($NAME format).
2307
2758
  // TODO: OR if meta.'$CALL'
@@ -2311,7 +2762,7 @@ const _injecthandler: Injector = (
2311
2762
  }
2312
2763
 
2313
2764
  // Update parent with value. Ensures references remain in node tree.
2314
- else if (S_MVAL === inj.mode && inj.full) {
2765
+ else if (M_VAL === inj.mode && inj.full) {
2315
2766
  inj.setval(val)
2316
2767
  }
2317
2768
 
@@ -2381,9 +2832,9 @@ function _injectstr(
2381
2832
  let pathref = m[1]
2382
2833
 
2383
2834
  // Special escapes inside injection.
2384
- pathref = 3 < pathref.length ?
2385
- pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS) :
2386
- pathref
2835
+ if (3 < size(pathref)) {
2836
+ pathref = pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS)
2837
+ }
2387
2838
 
2388
2839
  // Get the extracted path reference.
2389
2840
  out = getpath(store, pathref, inj)
@@ -2393,14 +2844,19 @@ function _injectstr(
2393
2844
  // Check for injections within the string.
2394
2845
  const partial = (_m: string, ref: string) => {
2395
2846
  // Special escapes inside injection.
2396
- ref = 3 < ref.length ? ref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS) : ref
2847
+
2848
+ if (3 < size(ref)) {
2849
+ ref = ref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS)
2850
+ }
2851
+
2397
2852
  if (inj) {
2398
2853
  inj.full = false
2399
2854
  }
2855
+
2400
2856
  const found = getpath(store, ref, inj)
2401
2857
 
2402
2858
  // Ensure inject value is a string.
2403
- return UNDEF === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found)
2859
+ return NONE === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found)
2404
2860
  }
2405
2861
 
2406
2862
  out = val.replace(R_INJECTION_PARTIAL, partial)
@@ -2417,11 +2873,101 @@ function _injectstr(
2417
2873
  }
2418
2874
 
2419
2875
 
2876
+ // Handler Utilities
2877
+ // =================
2878
+
2879
+
2880
+ const MODENAME: any = {
2881
+ [M_VAL]: 'val',
2882
+ [M_KEYPRE]: 'key:pre',
2883
+ [M_KEYPOST]: 'key:post',
2884
+ }
2885
+
2886
+ const PLACEMENT: any = {
2887
+ [M_VAL]: 'value',
2888
+ [M_KEYPRE]: S_key,
2889
+ [M_KEYPOST]: S_key,
2890
+ }
2891
+
2892
+ function checkPlacement(
2893
+ modes: InjectMode,
2894
+ ijname: string,
2895
+ parentTypes: number,
2896
+ inj: Injection
2897
+ ): boolean {
2898
+ if (0 === (modes & inj.mode)) {
2899
+ inj.errs.push('$' + ijname + ': invalid placement as ' + PLACEMENT[inj.mode] +
2900
+ ', expected: ' + join(items(
2901
+ [M_KEYPRE, M_KEYPOST, M_VAL].filter(m => modes & m),
2902
+ (n: any) => PLACEMENT[n[1]]), ',') + '.')
2903
+ return false
2904
+ }
2905
+ if (!isempty(parentTypes)) {
2906
+ const ptype = typify(inj.parent)
2907
+ if (0 === (parentTypes & ptype)) {
2908
+ inj.errs.push('$' + ijname + ': invalid placement in parent ' + typename(ptype) +
2909
+ ', expected: ' + typename(parentTypes) + '.')
2910
+ return false
2911
+
2912
+ }
2913
+ }
2914
+ return true
2915
+ }
2916
+
2917
+
2918
+ // function injectorArgs(argTypes: number[], inj: Injection): any {
2919
+ function injectorArgs(argTypes: number[], args: any[]): any {
2920
+ const numargs = size(argTypes)
2921
+ const found = new Array(1 + numargs)
2922
+ found[0] = NONE
2923
+ for (let argI = 0; argI < numargs; argI++) {
2924
+ // const arg = inj.parent[1 + argI]
2925
+ const arg = args[argI]
2926
+ const argType = typify(arg)
2927
+ if (0 === (argTypes[argI] & argType)) {
2928
+ found[0] = 'invalid argument: ' + stringify(arg, 22) +
2929
+ ' (' + typename(argType) + ' at position ' + (1 + argI) +
2930
+ ') is not of type: ' + typename(argTypes[argI]) + '.'
2931
+ break
2932
+ }
2933
+ found[1 + argI] = arg
2934
+ }
2935
+ return found
2936
+ }
2937
+
2938
+
2939
+ function injectChild(child: any, store: any, inj: Injection): Injection {
2940
+ let cinj = inj
2941
+
2942
+ // Replace ['`$FORMAT`',...] with child
2943
+ if (null != inj.prior) {
2944
+ if (null != inj.prior.prior) {
2945
+ cinj = inj.prior.prior.child(inj.prior.keyI, inj.prior.keys)
2946
+ cinj.val = child
2947
+ setprop(cinj.parent, inj.prior.key, child)
2948
+ }
2949
+ else {
2950
+ cinj = inj.prior.child(inj.keyI, inj.keys)
2951
+ cinj.val = child
2952
+ setprop(cinj.parent, inj.key, child)
2953
+ }
2954
+ }
2955
+
2956
+ // console.log('FORMAT-INJECT-CHILD', child)
2957
+ inject(child, store, cinj)
2958
+
2959
+ return cinj
2960
+ }
2961
+
2962
+
2420
2963
  class StructUtility {
2421
2964
  clone = clone
2422
2965
  delprop = delprop
2423
2966
  escre = escre
2424
2967
  escurl = escurl
2968
+ filter = filter
2969
+ flatten = flatten
2970
+ getdef = getdef
2425
2971
  getelem = getelem
2426
2972
  getpath = getpath
2427
2973
  getprop = getprop
@@ -2434,13 +2980,14 @@ class StructUtility {
2434
2980
  ismap = ismap
2435
2981
  isnode = isnode
2436
2982
  items = items
2437
- joinurl = joinurl
2983
+ join = join
2438
2984
  jsonify = jsonify
2439
2985
  keysof = keysof
2440
2986
  merge = merge
2441
2987
  pad = pad
2442
2988
  pathify = pathify
2443
2989
  select = select
2990
+ setpath = setpath
2444
2991
  setprop = setprop
2445
2992
  size = size
2446
2993
  slice = slice
@@ -2448,11 +2995,36 @@ class StructUtility {
2448
2995
  stringify = stringify
2449
2996
  transform = transform
2450
2997
  typify = typify
2998
+ typename = typename
2451
2999
  validate = validate
2452
3000
  walk = walk
2453
3001
 
2454
- jo = jo
2455
- ja = ja
3002
+ SKIP = SKIP
3003
+ DELETE = DELETE
3004
+
3005
+ jm = jm
3006
+ jt = jt
3007
+ tn = typename
3008
+
3009
+ T_any = T_any
3010
+ T_noval = T_noval
3011
+ T_boolean = T_boolean
3012
+ T_decimal = T_decimal
3013
+ T_integer = T_integer
3014
+ T_number = T_number
3015
+ T_string = T_string
3016
+ T_function = T_function
3017
+ T_symbol = T_symbol
3018
+ T_null = T_null
3019
+ T_list = T_list
3020
+ T_map = T_map
3021
+ T_instance = T_instance
3022
+ T_scalar = T_scalar
3023
+ T_node = T_node
3024
+
3025
+ checkPlacement = checkPlacement
3026
+ injectorArgs = injectorArgs
3027
+ injectChild = injectChild
2456
3028
  }
2457
3029
 
2458
3030
  export {
@@ -2461,6 +3033,9 @@ export {
2461
3033
  delprop,
2462
3034
  escre,
2463
3035
  escurl,
3036
+ filter,
3037
+ flatten,
3038
+ getdef,
2464
3039
  getelem,
2465
3040
  getpath,
2466
3041
  getprop,
@@ -2473,13 +3048,14 @@ export {
2473
3048
  ismap,
2474
3049
  isnode,
2475
3050
  items,
2476
- joinurl,
3051
+ join,
2477
3052
  jsonify,
2478
3053
  keysof,
2479
3054
  merge,
2480
3055
  pad,
2481
3056
  pathify,
2482
3057
  select,
3058
+ setpath,
2483
3059
  setprop,
2484
3060
  size,
2485
3061
  slice,
@@ -2487,11 +3063,41 @@ export {
2487
3063
  stringify,
2488
3064
  transform,
2489
3065
  typify,
3066
+ typename,
2490
3067
  validate,
2491
3068
  walk,
2492
3069
 
2493
- jo,
2494
- ja,
3070
+ SKIP,
3071
+ DELETE,
3072
+
3073
+ jm,
3074
+ jt,
3075
+
3076
+ T_any,
3077
+ T_noval,
3078
+ T_boolean,
3079
+ T_decimal,
3080
+ T_integer,
3081
+ T_number,
3082
+ T_string,
3083
+ T_function,
3084
+ T_symbol,
3085
+ T_null,
3086
+ T_list,
3087
+ T_map,
3088
+ T_instance,
3089
+ T_scalar,
3090
+ T_node,
3091
+
3092
+ M_KEYPRE,
3093
+ M_KEYPOST,
3094
+ M_VAL,
3095
+
3096
+ MODENAME,
3097
+
3098
+ checkPlacement,
3099
+ injectorArgs,
3100
+ injectChild,
2495
3101
  }
2496
3102
 
2497
3103
  export type {