@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,11 +1,14 @@
1
1
  "use strict";
2
- /* Copyright (c) 2025 Voxgig Ltd. MIT LICENSE. */
2
+ /* Copyright (c) 2025-2026 Voxgig Ltd. MIT LICENSE. */
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.StructUtility = void 0;
4
+ exports.MODENAME = exports.M_VAL = exports.M_KEYPOST = exports.M_KEYPRE = exports.T_node = exports.T_scalar = exports.T_instance = exports.T_map = exports.T_list = exports.T_null = exports.T_symbol = exports.T_function = exports.T_string = exports.T_number = exports.T_integer = exports.T_decimal = exports.T_boolean = exports.T_noval = exports.T_any = exports.DELETE = exports.SKIP = exports.StructUtility = void 0;
5
5
  exports.clone = clone;
6
6
  exports.delprop = delprop;
7
7
  exports.escre = escre;
8
8
  exports.escurl = escurl;
9
+ exports.filter = filter;
10
+ exports.flatten = flatten;
11
+ exports.getdef = getdef;
9
12
  exports.getelem = getelem;
10
13
  exports.getpath = getpath;
11
14
  exports.getprop = getprop;
@@ -18,13 +21,14 @@ exports.islist = islist;
18
21
  exports.ismap = ismap;
19
22
  exports.isnode = isnode;
20
23
  exports.items = items;
21
- exports.joinurl = joinurl;
24
+ exports.join = join;
22
25
  exports.jsonify = jsonify;
23
26
  exports.keysof = keysof;
24
27
  exports.merge = merge;
25
28
  exports.pad = pad;
26
29
  exports.pathify = pathify;
27
30
  exports.select = select;
31
+ exports.setpath = setpath;
28
32
  exports.setprop = setprop;
29
33
  exports.size = size;
30
34
  exports.slice = slice;
@@ -32,11 +36,15 @@ exports.strkey = strkey;
32
36
  exports.stringify = stringify;
33
37
  exports.transform = transform;
34
38
  exports.typify = typify;
39
+ exports.typename = typename;
35
40
  exports.validate = validate;
36
41
  exports.walk = walk;
37
- exports.jo = jo;
38
- exports.ja = ja;
39
- // VERSION: @voxgig/struct 0.0.9
42
+ exports.jm = jm;
43
+ exports.jt = jt;
44
+ exports.checkPlacement = checkPlacement;
45
+ exports.injectorArgs = injectorArgs;
46
+ exports.injectChild = injectChild;
47
+ // VERSION: @voxgig/struct 0.0.10
40
48
  /* Voxgig Struct
41
49
  * =============
42
50
  *
@@ -68,13 +76,15 @@ exports.ja = ja;
68
76
  * - stringify: human-friendly string version of a value.
69
77
  * - escre: escape a regular expresion string.
70
78
  * - escurl: escape a url.
71
- * - joinurl: join parts of a url, merging forward slashes.
79
+ * - join: join parts of a url, merging forward slashes.
72
80
  *
73
81
  * This set of functions and supporting utilities is designed to work
74
82
  * uniformly across many languages, meaning that some code that may be
75
83
  * functionally redundant in specific languages is still retained to
76
84
  * keep the code human comparable.
77
85
  *
86
+ * NOTE: Lists are assumed to be mutable and reference stable.
87
+ *
78
88
  * NOTE: In this code JSON nulls are in general *not* considered the
79
89
  * same as the undefined value in the given language. However most
80
90
  * JSON parsers do use the undefined value to represent JSON
@@ -86,30 +96,42 @@ exports.ja = ja;
86
96
  *
87
97
  */
88
98
  // String constants are explicitly defined.
89
- // Mode value for inject step.
90
- const S_MKEYPRE = 'key:pre';
91
- const S_MKEYPOST = 'key:post';
92
- const S_MVAL = 'val';
93
- const S_MKEY = 'key';
94
- // Special keys.
99
+ // Mode value for inject step (bitfield).
100
+ const M_KEYPRE = 1;
101
+ exports.M_KEYPRE = M_KEYPRE;
102
+ const M_KEYPOST = 2;
103
+ exports.M_KEYPOST = M_KEYPOST;
104
+ const M_VAL = 4;
105
+ exports.M_VAL = M_VAL;
106
+ // Special strings.
95
107
  const S_BKEY = '`$KEY`';
96
108
  const S_BANNO = '`$ANNO`';
97
109
  const S_BEXACT = '`$EXACT`';
110
+ const S_BVAL = '`$VAL`';
98
111
  const S_DKEY = '$KEY';
99
112
  const S_DTOP = '$TOP';
100
113
  const S_DERRS = '$ERRS';
101
114
  const S_DSPEC = '$SPEC';
102
115
  // General strings.
103
- const S_array = 'array';
116
+ const S_list = 'list';
104
117
  const S_base = 'base';
105
118
  const S_boolean = 'boolean';
106
119
  const S_function = 'function';
120
+ const S_symbol = 'symbol';
107
121
  const S_instance = 'instance';
108
122
  const S_key = 'key';
123
+ const S_any = 'any';
124
+ const S_nil = 'nil';
109
125
  const S_null = 'null';
110
126
  const S_number = 'number';
111
127
  const S_object = 'object';
112
128
  const S_string = 'string';
129
+ const S_decimal = 'decimal';
130
+ const S_integer = 'integer';
131
+ const S_map = 'map';
132
+ const S_scalar = 'scalar';
133
+ const S_node = 'node';
134
+ // Character strings.
113
135
  const S_BT = '`';
114
136
  const S_CN = ':';
115
137
  const S_CS = ']';
@@ -120,11 +142,69 @@ const S_KEY = 'KEY';
120
142
  const S_MT = '';
121
143
  const S_OS = '[';
122
144
  const S_SP = ' ';
145
+ const S_CM = ',';
123
146
  const S_VIZ = ': ';
147
+ // Types
148
+ let t = 31;
149
+ const T_any = (1 << t--) - 1;
150
+ exports.T_any = T_any;
151
+ const T_noval = 1 << t--; // Means property absent, undefined. Also NOT a scalar!
152
+ exports.T_noval = T_noval;
153
+ const T_boolean = 1 << t--;
154
+ exports.T_boolean = T_boolean;
155
+ const T_decimal = 1 << t--;
156
+ exports.T_decimal = T_decimal;
157
+ const T_integer = 1 << t--;
158
+ exports.T_integer = T_integer;
159
+ const T_number = 1 << t--;
160
+ exports.T_number = T_number;
161
+ const T_string = 1 << t--;
162
+ exports.T_string = T_string;
163
+ const T_function = 1 << t--;
164
+ exports.T_function = T_function;
165
+ const T_symbol = 1 << t--;
166
+ exports.T_symbol = T_symbol;
167
+ const T_null = 1 << t--; // The actual JSON null value.
168
+ exports.T_null = T_null;
169
+ t -= 7;
170
+ const T_list = 1 << t--;
171
+ exports.T_list = T_list;
172
+ const T_map = 1 << t--;
173
+ exports.T_map = T_map;
174
+ const T_instance = 1 << t--;
175
+ exports.T_instance = T_instance;
176
+ t -= 4;
177
+ const T_scalar = 1 << t--;
178
+ exports.T_scalar = T_scalar;
179
+ const T_node = 1 << t--;
180
+ exports.T_node = T_node;
181
+ const TYPENAME = [
182
+ S_any,
183
+ S_nil,
184
+ S_boolean,
185
+ S_decimal,
186
+ S_integer,
187
+ S_number,
188
+ S_string,
189
+ S_function,
190
+ S_symbol,
191
+ S_null,
192
+ '', '', '',
193
+ '', '', '', '',
194
+ S_list,
195
+ S_map,
196
+ S_instance,
197
+ '', '', '', '',
198
+ S_scalar,
199
+ S_node,
200
+ ];
124
201
  // The standard undefined value for this language.
125
- const UNDEF = undefined;
126
- // Private marker to indicate a skippable value.
202
+ const NONE = undefined;
203
+ // Private markers
127
204
  const SKIP = { '`$SKIP`': true };
205
+ exports.SKIP = SKIP;
206
+ const DELETE = { '`$DELETE`': true };
207
+ exports.DELETE = DELETE;
128
208
  // Regular expression constants
129
209
  const R_INTEGER_KEY = /^[-0-9]+$/; // Match integer keys (including <0).
130
210
  const R_ESCAPE_REGEXP = /[.*+?^${}()|[\]\\]/g; // Chars that need escaping in regexp.
@@ -133,7 +213,7 @@ const R_LEADING_TRAILING_SLASH = /([^\/])\/+/; // Multiple slashes in URL middle
133
213
  const R_LEADING_SLASH = /^\/+/; // Leading slashes in URLs.
134
214
  const R_QUOTES = /"/g; // Double quotes for removal.
135
215
  const R_DOT = /\./g; // Dots in path strings.
136
- const R_FUNCTION_REF = /^`\$FUNCTION:([0-9]+)`$/; // Function reference in clone.
216
+ const R_CLONE_REF = /^`\$REF:([0-9]+)`$/; // Copy reference in cloning.
137
217
  const R_META_PATH = /^([^$]+)\$([=~])(.+)$/; // Meta path syntax.
138
218
  const R_DOUBLE_DOLLAR = /\$\$/g; // Double dollar escape sequence.
139
219
  const R_TRANSFORM_NAME = /`\$([A-Z]+)`/g; // Transform command names.
@@ -141,6 +221,19 @@ const R_INJECTION_FULL = /^`(\$[A-Z]+|[^`]*)[0-9]*`$/; // Full string injection
141
221
  const R_BT_ESCAPE = /\$BT/g; // Backtick escape sequence.
142
222
  const R_DS_ESCAPE = /\$DS/g; // Dollar sign escape sequence.
143
223
  const R_INJECTION_PARTIAL = /`([^`]+)`/g; // Partial string injection pattern.
224
+ // Default max depth (for walk etc).
225
+ const MAXDEPTH = 32;
226
+ // Return type string for narrowest type.
227
+ function typename(t) {
228
+ return getelem(TYPENAME, Math.clz32(t), TYPENAME[0]);
229
+ }
230
+ // Get a defined value. Returns alt if val is undefined.
231
+ function getdef(val, alt) {
232
+ if (NONE === val) {
233
+ return alt;
234
+ }
235
+ return val;
236
+ }
144
237
  // Value is a node - defined, and a map (hash) or list (array).
145
238
  // NOTE: typescript
146
239
  // things
@@ -193,11 +286,14 @@ function size(val) {
193
286
  return 0;
194
287
  }
195
288
  }
196
- // Extract part of an array or string into a new value, from the start point to the end point.
197
- // If no end is specified, extract to the full length of the value. Negative arguments count
198
- // from the end of the value. For numbers, perform min and max bounding, where start is
199
- // inclusive, and end is *exclusive*.
200
- function slice(val, start, end) {
289
+ // Extract part of an array or string into a new value, from the start
290
+ // point to the end point. If no end is specified, extract to the
291
+ // full length of the value. Negative arguments count from the end of
292
+ // the value. For numbers, perform min and max bounding, where start
293
+ // is inclusive, and end is *exclusive*.
294
+ // NOTE: input lists are not mutated by default. Use the mutate
295
+ // argument to mutate lists in place.
296
+ function slice(val, start, end, mutate) {
201
297
  if (S_number === typeof val) {
202
298
  start = null == start || S_number !== typeof start ? Number.MIN_SAFE_INTEGER : start;
203
299
  end = (null == end || S_number !== typeof end ? Number.MAX_SAFE_INTEGER : end) - 1;
@@ -234,7 +330,15 @@ function slice(val, start, end) {
234
330
  }
235
331
  if (-1 < start && start <= end && end <= vlen) {
236
332
  if (islist(val)) {
237
- val = val.slice(start, end);
333
+ if (mutate) {
334
+ for (let i = 0, j = start; j < end; i++, j++) {
335
+ val[i] = val[j];
336
+ }
337
+ val.length = (end - start);
338
+ }
339
+ else {
340
+ val = val.slice(start, end);
341
+ }
238
342
  }
239
343
  else if (S_string === typeof val) {
240
344
  val = val.substring(start, end);
@@ -251,44 +355,66 @@ function slice(val, start, end) {
251
355
  }
252
356
  return val;
253
357
  }
358
+ // String padding.
254
359
  function pad(str, padding, padchar) {
255
360
  str = S_string === typeof str ? str : stringify(str);
256
361
  padding = null == padding ? 44 : padding;
257
362
  padchar = null == padchar ? S_SP : ((padchar + S_SP)[0]);
258
363
  return -1 < padding ? str.padEnd(padding, padchar) : str.padStart(0 - padding, padchar);
259
364
  }
260
- // Determine the type of a value as a string.
261
- // Returns one of:
262
- // 'null', 'string', 'number', 'boolean', 'function', 'array', 'object', 'instance'
263
- // where 'instance' is an instance of a class, and 'null' is undefined, null, or NaN.
264
- // Normalizes and simplifies JavaScript's type system for consistency.
365
+ // Determine the type of a value as a bit code.
265
366
  function typify(value) {
266
- if (value === null || value === undefined) {
267
- return S_null;
367
+ if (undefined === value) {
368
+ return T_noval;
268
369
  }
269
- const type = typeof value;
270
- if (S_number === type && isNaN(value)) {
271
- return S_null;
370
+ const typestr = typeof value;
371
+ if (null === value) {
372
+ return T_scalar | T_null;
373
+ }
374
+ else if (S_number === typestr) {
375
+ if (Number.isInteger(value)) {
376
+ return T_scalar | T_number | T_integer;
377
+ }
378
+ else if (isNaN(value)) {
379
+ return T_noval;
380
+ }
381
+ else {
382
+ return T_scalar | T_number | T_decimal;
383
+ }
272
384
  }
273
- if (Array.isArray(value)) {
274
- return S_array;
385
+ else if (S_string === typestr) {
386
+ return T_scalar | T_string;
275
387
  }
276
- if (type === 'object') {
388
+ else if (S_boolean === typestr) {
389
+ return T_scalar | T_boolean;
390
+ }
391
+ else if (S_function === typestr) {
392
+ return T_scalar | T_function;
393
+ }
394
+ // For languages that have symbolic atoms.
395
+ else if (S_symbol === typestr) {
396
+ return T_scalar | T_symbol;
397
+ }
398
+ else if (Array.isArray(value)) {
399
+ return T_node | T_list;
400
+ }
401
+ else if (S_object === typestr) {
277
402
  if (value.constructor instanceof Function) {
278
403
  let cname = value.constructor.name;
279
404
  if ('Object' !== cname && 'Array' !== cname) {
280
- return S_instance;
405
+ return T_node | T_instance;
281
406
  }
282
407
  }
283
- return S_object;
408
+ return T_node | T_map;
284
409
  }
285
- return type;
410
+ // Anything else (e.g. bigint) is considered T_any
411
+ return T_any;
286
412
  }
287
413
  // Get a list element. The key should be an integer, or a string
288
414
  // that can parse to an integer only. Negative integers count from the end of the list.
289
415
  function getelem(val, key, alt) {
290
- let out = UNDEF;
291
- if (UNDEF === val || UNDEF === key) {
416
+ let out = NONE;
417
+ if (NONE === val || NONE === key) {
292
418
  return alt;
293
419
  }
294
420
  if (islist(val)) {
@@ -300,8 +426,8 @@ function getelem(val, key, alt) {
300
426
  out = val[key];
301
427
  }
302
428
  }
303
- if (UNDEF === out) {
304
- return alt;
429
+ if (NONE === out) {
430
+ return 0 < (T_function & typify(alt)) ? alt() : alt;
305
431
  }
306
432
  return out;
307
433
  }
@@ -309,13 +435,13 @@ function getelem(val, key, alt) {
309
435
  // If the key is not found, return the alternative value, if any.
310
436
  function getprop(val, key, alt) {
311
437
  let out = alt;
312
- if (UNDEF === val || UNDEF === key) {
438
+ if (NONE === val || NONE === key) {
313
439
  return alt;
314
440
  }
315
441
  if (isnode(val)) {
316
442
  out = val[key];
317
443
  }
318
- if (UNDEF === out) {
444
+ if (NONE === out) {
319
445
  return alt;
320
446
  }
321
447
  return out;
@@ -325,55 +451,115 @@ function getprop(val, key, alt) {
325
451
  // Number keys are converted to strings.
326
452
  // Floats are truncated to integers.
327
453
  // Booleans, objects, arrays, null, undefined all return empty string.
328
- function strkey(key = UNDEF) {
329
- if (UNDEF === key) {
454
+ function strkey(key = NONE) {
455
+ if (NONE === key) {
330
456
  return S_MT;
331
457
  }
332
- if (typeof key === S_string) {
458
+ const t = typify(key);
459
+ if (0 < (T_string & t)) {
333
460
  return key;
334
461
  }
335
- if (typeof key === S_boolean) {
462
+ else if (0 < (T_boolean & t)) {
336
463
  return S_MT;
337
464
  }
338
- if (typeof key === S_number) {
465
+ else if (0 < (T_number & t)) {
339
466
  return key % 1 === 0 ? String(key) : String(Math.floor(key));
340
467
  }
341
468
  return S_MT;
342
469
  }
343
470
  // Sorted keys of a map, or indexes (as strings) of a list.
471
+ // Root utility - only uses language facilities.
344
472
  function keysof(val) {
345
473
  return !isnode(val) ? [] :
346
474
  ismap(val) ? Object.keys(val).sort() : val.map((_n, i) => S_MT + i);
347
475
  }
348
476
  // Value of property with name key in node val is defined.
477
+ // Root utility - only uses language facilities.
349
478
  function haskey(val, key) {
350
- return UNDEF !== getprop(val, key);
479
+ return NONE !== getprop(val, key);
480
+ }
481
+ function items(val, apply) {
482
+ let out = keysof(val).map((k) => [k, val[k]]);
483
+ if (null != apply) {
484
+ out = out.map(apply);
485
+ }
486
+ return out;
351
487
  }
352
- // List the sorted keys of a map or list as an array of tuples of the form [key, value].
353
- // As with keysof, list indexes are converted to strings.
354
- function items(val) {
355
- return keysof(val).map((k) => [k, val[k]]);
488
+ // To replicate the array spread operator:
489
+ // a=1, b=[2,3], c=[4,5]
490
+ // [a,...b,c] -> [1,2,3,[4,5]]
491
+ // flatten([a,b,[c]]) -> [1,2,3,[4,5]]
492
+ // NOTE: [c] ensures c is not expanded
493
+ function flatten(list, depth) {
494
+ if (!islist(list)) {
495
+ return list;
496
+ }
497
+ return list.flat(getdef(depth, 1));
498
+ }
499
+ // Filter item values using check function.
500
+ function filter(val, check) {
501
+ let all = items(val);
502
+ let numall = size(all);
503
+ let out = [];
504
+ for (let i = 0; i < numall; i++) {
505
+ if (check(all[i])) {
506
+ out.push(all[i][1]);
507
+ }
508
+ }
509
+ return out;
356
510
  }
357
511
  // Escape regular expression.
358
512
  function escre(s) {
359
- s = null == s ? S_MT : s;
360
- return s.replace(R_ESCAPE_REGEXP, '\\$&');
513
+ // s = null == s ? S_MT : s
514
+ return replace(s, R_ESCAPE_REGEXP, '\\$&');
361
515
  }
362
516
  // Escape URLs.
363
517
  function escurl(s) {
364
518
  s = null == s ? S_MT : s;
365
519
  return encodeURIComponent(s);
366
520
  }
367
- // Concatenate url part strings, merging forward slashes as needed.
368
- function joinurl(sarr) {
369
- return sarr
370
- .filter(s => null != s && S_MT !== s)
371
- .map((s, i) => 0 === i ? s.replace(R_TRAILING_SLASH, S_MT) :
372
- s.replace(R_LEADING_TRAILING_SLASH, '$1/')
373
- .replace(R_LEADING_SLASH, S_MT)
374
- .replace(R_TRAILING_SLASH, S_MT))
375
- .filter(s => S_MT !== s)
376
- .join(S_FS);
521
+ // Replace a search string (all), or a regexp, in a source string.
522
+ function replace(s, from, to) {
523
+ let rs = s;
524
+ let ts = typify(s);
525
+ if (0 === (T_string & ts)) {
526
+ rs = stringify(s);
527
+ }
528
+ else if (0 < ((T_noval | T_null) & ts)) {
529
+ rs = S_MT;
530
+ }
531
+ else {
532
+ rs = stringify(s);
533
+ }
534
+ return rs.replace(from, to);
535
+ }
536
+ // Concatenate url part strings, merging sep char as needed.
537
+ function join(arr, sep, url) {
538
+ const sarr = size(arr);
539
+ const sepdef = getdef(sep, S_CM);
540
+ const sepre = 1 === size(sepdef) ? escre(sepdef) : NONE;
541
+ const out = filter(items(
542
+ // filter(arr, (n) => null != n[1] && S_MT !== n[1]),
543
+ filter(arr, (n) => (0 < (T_string & typify(n[1]))) && S_MT !== n[1]), (n) => {
544
+ let i = +n[0];
545
+ let s = n[1];
546
+ if (NONE !== sepre && S_MT !== sepre) {
547
+ if (url && 0 === i) {
548
+ s = replace(s, RegExp(sepre + '+$'), S_MT);
549
+ return s;
550
+ }
551
+ if (0 < i) {
552
+ s = replace(s, RegExp('^' + sepre + '+'), S_MT);
553
+ }
554
+ if (i < sarr - 1 || !url) {
555
+ s = replace(s, RegExp(sepre + '+$'), S_MT);
556
+ }
557
+ s = replace(s, RegExp('([^' + sepre + '])' + sepre + '+([^' + sepre + '])'), '$1' + sepdef + '$2');
558
+ }
559
+ return s;
560
+ }), (n) => S_MT !== n[1])
561
+ .join(sepdef);
562
+ return out;
377
563
  }
378
564
  // Output JSON in a "standard" format, with 2 space indents, each property on a new line,
379
565
  // and spaces after {[: and before ]}. Any "wierd" values (NaN, etc) are output as null.
@@ -381,18 +567,22 @@ function joinurl(sarr) {
381
567
  function jsonify(val, flags) {
382
568
  let str = S_null;
383
569
  if (null != val) {
384
- const indent = getprop(flags, 'indent', 2);
385
- str = JSON.stringify(val, null, indent);
386
- if (UNDEF === str) {
387
- str = S_null;
570
+ try {
571
+ const indent = getprop(flags, 'indent', 2);
572
+ str = JSON.stringify(val, null, indent);
573
+ if (NONE === str) {
574
+ str = S_null;
575
+ }
576
+ const offset = getprop(flags, 'offset', 0);
577
+ if (0 < offset) {
578
+ // Left offset entire indented JSON so that it aligns with surrounding code
579
+ // indented by offset. Assume first brace is on line with asignment, so not offset.
580
+ str = '{\n' +
581
+ join(items(slice(str.split('\n'), 1), (n) => pad(n[1], 0 - offset - size(n[1]))), '\n');
582
+ }
388
583
  }
389
- const offset = getprop(flags, 'offset', 0);
390
- if (0 < offset) {
391
- // Left offset entire indented JSON so that it aligns with surrounding code
392
- // indented by offset.
393
- str = '{\n' + str.split('\n').slice(1)
394
- .map(n => pad(n, 0 - offset - size(n)))
395
- .join('\n');
584
+ catch (e) {
585
+ str = '__JSONIFY_FAILED__';
396
586
  }
397
587
  }
398
588
  return str;
@@ -401,7 +591,7 @@ function jsonify(val, flags) {
401
591
  function stringify(val, maxlen, pretty) {
402
592
  let valstr = S_MT;
403
593
  pretty = !!pretty;
404
- if (UNDEF === val) {
594
+ if (NONE === val) {
405
595
  return pretty ? '<>' : valstr;
406
596
  }
407
597
  if (S_string === typeof val) {
@@ -414,9 +604,9 @@ function stringify(val, maxlen, pretty) {
414
604
  typeof val === "object" &&
415
605
  !Array.isArray(val)) {
416
606
  const sortedObj = {};
417
- for (const k of Object.keys(val).sort()) {
418
- sortedObj[k] = val[k];
419
- }
607
+ items(val, (n) => {
608
+ sortedObj[n[0]] = val[n[0]];
609
+ });
420
610
  return sortedObj;
421
611
  }
422
612
  return val;
@@ -424,7 +614,7 @@ function stringify(val, maxlen, pretty) {
424
614
  valstr = valstr.replace(R_QUOTES, S_MT);
425
615
  }
426
616
  catch (err) {
427
- valstr = S_MT + val;
617
+ valstr = '__STRINGIFY_FAILED__';
428
618
  }
429
619
  }
430
620
  if (null != maxlen && -1 < maxlen) {
@@ -433,8 +623,7 @@ function stringify(val, maxlen, pretty) {
433
623
  }
434
624
  if (pretty) {
435
625
  // Indicate deeper JSON levels with different terminal colors (simplistic wrt strings).
436
- let c = [81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69]
437
- .map(n => `\x1b[38;5;${n}m`), r = '\x1b[0m', d = 0, o = c[0], t = o;
626
+ let c = items([81, 118, 213, 39, 208, 201, 45, 190, 129, 51, 160, 121, 226, 33, 207, 69], (n) => '\x1b[38;5;' + n[1] + 'm'), r = '\x1b[0m', d = 0, o = c[0], t = o;
438
627
  for (const ch of valstr) {
439
628
  if (ch === '{' || ch === '[') {
440
629
  d++;
@@ -456,44 +645,45 @@ function stringify(val, maxlen, pretty) {
456
645
  }
457
646
  // Build a human friendly path string.
458
647
  function pathify(val, startin, endin) {
459
- let pathstr = UNDEF;
648
+ let pathstr = NONE;
460
649
  let path = islist(val) ? val :
461
650
  S_string == typeof val ? [val] :
462
651
  S_number == typeof val ? [val] :
463
- UNDEF;
652
+ NONE;
464
653
  const start = null == startin ? 0 : -1 < startin ? startin : 0;
465
654
  const end = null == endin ? 0 : -1 < endin ? endin : 0;
466
- if (UNDEF != path && 0 <= start) {
655
+ if (NONE != path && 0 <= start) {
467
656
  path = slice(path, start, path.length - end);
468
657
  if (0 === path.length) {
469
658
  pathstr = '<root>';
470
659
  }
471
660
  else {
472
- pathstr = path
473
- // .filter((p: any, t: any) => (t = typeof p, S_string === t || S_number === t))
474
- .filter((p) => iskey(p))
475
- .map((p) => S_number === typeof p ? S_MT + Math.floor(p) :
476
- p.replace(R_DOT, S_MT))
477
- .join(S_DT);
661
+ pathstr = join(items(filter(path, (n) => iskey(n[1])), (n) => {
662
+ let p = n[1];
663
+ return S_number === typeof p ? S_MT + Math.floor(p) :
664
+ p.replace(R_DOT, S_MT);
665
+ }), S_DT);
478
666
  }
479
667
  }
480
- if (UNDEF === pathstr) {
481
- pathstr = '<unknown-path' + (UNDEF === val ? S_MT : S_CN + stringify(val, 47)) + '>';
668
+ if (NONE === pathstr) {
669
+ pathstr = '<unknown-path' + (NONE === val ? S_MT : S_CN + stringify(val, 47)) + '>';
482
670
  }
483
671
  return pathstr;
484
672
  }
485
673
  // Clone a JSON-like data structure.
486
- // NOTE: function value references are copied, *not* cloned.
674
+ // NOTE: function and instance values are copied, *not* cloned.
487
675
  function clone(val) {
488
676
  const refs = [];
489
- const replacer = (_k, v) => S_function === typeof v ?
490
- (refs.push(v), '`$FUNCTION:' + (refs.length - 1) + '`') : v;
677
+ const reftype = T_function | T_instance;
678
+ const replacer = (_k, v) => 0 < (reftype & typify(v)) ?
679
+ (refs.push(v), '`$REF:' + (refs.length - 1) + '`') : v;
491
680
  const reviver = (_k, v, m) => S_string === typeof v ?
492
- (m = v.match(R_FUNCTION_REF), m ? refs[m[1]] : v) : v;
493
- return UNDEF === val ? UNDEF : JSON.parse(JSON.stringify(val, replacer), reviver);
681
+ (m = v.match(R_CLONE_REF), m ? refs[m[1]] : v) : v;
682
+ const out = NONE === val ? NONE : JSON.parse(JSON.stringify(val, replacer), reviver);
683
+ return out;
494
684
  }
495
685
  // Define a JSON Object using function arguments.
496
- function jo(...kv) {
686
+ function jm(...kv) {
497
687
  const kvsize = size(kv);
498
688
  const o = {};
499
689
  for (let i = 0; i < kvsize; i += 2) {
@@ -504,7 +694,7 @@ function jo(...kv) {
504
694
  return o;
505
695
  }
506
696
  // Define a JSON Array using function arguments.
507
- function ja(...v) {
697
+ function jt(...v) {
508
698
  const vsize = size(v);
509
699
  const a = new Array(vsize);
510
700
  for (let i = 0; i < vsize; i++) {
@@ -517,12 +707,12 @@ function ja(...v) {
517
707
  // Returns the (possibly modified) parent.
518
708
  // For objects, the property is deleted using the delete operator.
519
709
  // For arrays, the element at the index is removed and remaining elements are shifted down.
710
+ // NOTE: parent list may be new list, thus update references.
520
711
  function delprop(parent, key) {
521
712
  if (!iskey(key)) {
522
713
  return parent;
523
714
  }
524
715
  if (ismap(parent)) {
525
- // key = S_MT + key
526
716
  key = strkey(key);
527
717
  delete parent[key];
528
718
  }
@@ -534,8 +724,9 @@ function delprop(parent, key) {
534
724
  }
535
725
  keyI = Math.floor(keyI);
536
726
  // Delete list element at position keyI, shifting later elements down.
537
- if (0 <= keyI && keyI < parent.length) {
538
- for (let pI = keyI; pI < parent.length - 1; pI++) {
727
+ const psize = size(parent);
728
+ if (0 <= keyI && keyI < psize) {
729
+ for (let pI = keyI; pI < psize - 1; pI++) {
539
730
  parent[pI] = parent[pI + 1];
540
731
  }
541
732
  parent.length = parent.length - 1;
@@ -547,6 +738,7 @@ function delprop(parent, key) {
547
738
  // Returns the (possibly modified) parent.
548
739
  // If the parent is a list, and the key is negative, prepend the value.
549
740
  // NOTE: If the key is above the list size, append the value; below, prepend.
741
+ // NOTE: parent list may be new list, thus update references.
550
742
  function setprop(parent, key, val) {
551
743
  if (!iskey(key)) {
552
744
  return parent;
@@ -563,9 +755,10 @@ function setprop(parent, key, val) {
563
755
  return parent;
564
756
  }
565
757
  keyI = Math.floor(keyI);
758
+ // TODO: DELETE list element
566
759
  // Set or append value at position keyI, or append if keyI out of bounds.
567
760
  if (0 <= keyI) {
568
- parent[parent.length < keyI ? parent.length : keyI] = val;
761
+ parent[slice(keyI, 0, size(parent) + 1)] = val;
569
762
  }
570
763
  // Prepend value if keyI is negative
571
764
  else {
@@ -586,17 +779,20 @@ after,
586
779
  maxdepth,
587
780
  // These areguments are used for recursive state.
588
781
  key, parent, path) {
589
- let out = null == before ? val : before(key, val, parent, path || []);
590
- maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : 32;
782
+ if (NONE === path) {
783
+ path = [];
784
+ }
785
+ let out = null == before ? val : before(key, val, parent, path);
786
+ maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : MAXDEPTH;
591
787
  if (0 === maxdepth || (null != path && 0 < maxdepth && maxdepth <= path.length)) {
592
788
  return out;
593
789
  }
594
790
  if (isnode(out)) {
595
791
  for (let [ckey, child] of items(out)) {
596
- setprop(out, ckey, walk(child, before, after, maxdepth, ckey, out, [...(path || []), S_MT + ckey]));
792
+ setprop(out, ckey, walk(child, before, after, maxdepth, ckey, out, flatten([getdef(path, []), S_MT + ckey])));
597
793
  }
598
794
  }
599
- out = null == after ? out : after(key, out, parent, path || []);
795
+ out = null == after ? out : after(key, out, parent, path);
600
796
  return out;
601
797
  }
602
798
  // Merge a list of values into each other. Later values have
@@ -604,7 +800,9 @@ key, parent, path) {
604
800
  // override each other, and do *not* merge. The first element is
605
801
  // modified.
606
802
  function merge(val, maxdepth) {
607
- let out = UNDEF;
803
+ // const md: number = null == maxdepth ? MAXDEPTH : maxdepth < 0 ? 0 : maxdepth
804
+ const md = slice(maxdepth ?? MAXDEPTH, 0);
805
+ let out = NONE;
608
806
  // Handle edge cases.
609
807
  if (!islist(val)) {
610
808
  return val;
@@ -612,7 +810,7 @@ function merge(val, maxdepth) {
612
810
  const list = val;
613
811
  const lenlist = list.length;
614
812
  if (0 === lenlist) {
615
- return UNDEF;
813
+ return NONE;
616
814
  }
617
815
  else if (1 === lenlist) {
618
816
  return list[0];
@@ -632,8 +830,11 @@ function merge(val, maxdepth) {
632
830
  let dst = [out];
633
831
  function before(key, val, _parent, path) {
634
832
  const pI = size(path);
833
+ if (md <= pI) {
834
+ setprop(cur[pI - 1], key, val);
835
+ }
635
836
  // Scalars just override directly.
636
- if (!isnode(val)) {
837
+ else if (!isnode(val)) {
637
838
  cur[pI] = val;
638
839
  }
639
840
  // Descend into override node - Set up correct target in `after` function.
@@ -642,7 +843,7 @@ function merge(val, maxdepth) {
642
843
  dst[pI] = 0 < pI ? getprop(dst[pI - 1], key) : dst[pI];
643
844
  const tval = dst[pI];
644
845
  // Destination empty, so create node (unless override is class instance).
645
- if (UNDEF === tval && S_instance !== typify(val)) {
846
+ if (NONE === tval && 0 === (T_instance & typify(val))) {
646
847
  cur[pI] = islist(val) ? [] : {};
647
848
  }
648
849
  // Matching override and destination so continue with their values.
@@ -653,7 +854,7 @@ function merge(val, maxdepth) {
653
854
  else {
654
855
  cur[pI] = val;
655
856
  // No need to descend when override wins (destination is discarded).
656
- val = UNDEF;
857
+ val = NONE;
657
858
  }
658
859
  }
659
860
  // console.log('BEFORE-END', pathify(path), '@', pI, key,
@@ -665,24 +866,59 @@ function merge(val, maxdepth) {
665
866
  const cI = size(path);
666
867
  const target = cur[cI - 1];
667
868
  const value = cur[cI];
668
- // console.log('AFTER-PREP', pathify(path), '@', cI,
869
+ // console.log('AFTER-PREP', pathify(path), '@', cI, cur, '|',
669
870
  // stringify(key, -1, 1), stringify(value, -1, 1), 'T=', stringify(target, -1, 1))
670
871
  setprop(target, key, value);
671
872
  return value;
672
873
  }
673
874
  // Walk overriding node, creating paths in output as needed.
674
875
  out = walk(obj, before, after, maxdepth);
876
+ // console.log('WALK-DONE', out, obj)
675
877
  }
676
878
  }
879
+ if (0 === md) {
880
+ out = getelem(list, -1);
881
+ out = islist(out) ? [] : ismap(out) ? {} : out;
882
+ }
677
883
  return out;
678
884
  }
885
+ // Set a value using a path. Missing path parts are created.
886
+ // String paths create only maps. Use a string list to create list parts.
887
+ function setpath(store, path, val, injdef) {
888
+ const pathType = typify(path);
889
+ const parts = 0 < (T_list & pathType) ? path :
890
+ 0 < (T_string & pathType) ? path.split(S_DT) :
891
+ 0 < (T_number & pathType) ? [path] : NONE;
892
+ if (NONE === parts) {
893
+ return NONE;
894
+ }
895
+ const base = getprop(injdef, S_base);
896
+ const numparts = size(parts);
897
+ let parent = getprop(store, base, store);
898
+ for (let pI = 0; pI < numparts - 1; pI++) {
899
+ const partKey = getelem(parts, pI);
900
+ let nextParent = getprop(parent, partKey);
901
+ if (!isnode(nextParent)) {
902
+ nextParent = 0 < (T_number & typify(getelem(parts, pI + 1))) ? [] : {};
903
+ setprop(parent, partKey, nextParent);
904
+ }
905
+ parent = nextParent;
906
+ }
907
+ if (DELETE === val) {
908
+ delprop(parent, getelem(parts, -1));
909
+ }
910
+ else {
911
+ setprop(parent, getelem(parts, -1), val);
912
+ }
913
+ return parent;
914
+ }
679
915
  function getpath(store, path, injdef) {
680
916
  // Operate on a string array.
681
917
  const parts = islist(path) ? path :
682
918
  'string' === typeof path ? path.split(S_DT) :
683
- 'number' === typeof path ? [strkey(path)] : UNDEF;
684
- if (UNDEF === parts) {
685
- return UNDEF;
919
+ 'number' === typeof path ? [strkey(path)] : NONE;
920
+ if (NONE === parts) {
921
+ return NONE;
686
922
  }
687
923
  // let root = store
688
924
  let val = store;
@@ -707,22 +943,22 @@ function getpath(store, path, injdef) {
707
943
  parts[0] = m[3];
708
944
  }
709
945
  const dpath = getprop(injdef, 'dpath');
710
- for (let pI = 0; UNDEF !== val && pI < parts.length; pI++) {
946
+ for (let pI = 0; NONE !== val && pI < numparts; pI++) {
711
947
  let part = parts[pI];
712
948
  if (injdef && S_DKEY === part) {
713
949
  part = getprop(injdef, S_key);
714
950
  }
715
951
  else if (injdef && part.startsWith('$GET:')) {
716
952
  // $GET:path$ -> get store value, use as path part (string)
717
- part = stringify(getpath(src, part.substring(5, part.length - 1)));
953
+ part = stringify(getpath(src, slice(part, 5, -1)));
718
954
  }
719
955
  else if (injdef && part.startsWith('$REF:')) {
720
956
  // $REF:refpath$ -> get spec value, use as path part (string)
721
- part = stringify(getpath(getprop(store, S_DSPEC), part.substring(5, part.length - 1)));
957
+ part = stringify(getpath(getprop(store, S_DSPEC), slice(part, 5, -1)));
722
958
  }
723
959
  else if (injdef && part.startsWith('$META:')) {
724
960
  // $META:metapath$ -> get meta value, use as path part (string)
725
- part = stringify(getpath(getprop(injdef, 'meta'), part.substring(6, part.length - 1)));
961
+ part = stringify(getpath(getprop(injdef, 'meta'), slice(part, 6, -1)));
726
962
  }
727
963
  // $$ escapes $
728
964
  part = part.replace(R_DOUBLE_DOLLAR, '$');
@@ -740,12 +976,13 @@ function getpath(store, path, injdef) {
740
976
  val = dparent;
741
977
  }
742
978
  else {
743
- const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1));
979
+ // const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1))
980
+ const fullpath = flatten([slice(dpath, 0 - ascends), parts.slice(pI + 1)]);
744
981
  if (ascends <= size(dpath)) {
745
982
  val = getpath(store, fullpath);
746
983
  }
747
984
  else {
748
- val = UNDEF;
985
+ val = NONE;
749
986
  }
750
987
  break;
751
988
  }
@@ -766,10 +1003,11 @@ function getpath(store, path, injdef) {
766
1003
  const ref = pathify(path);
767
1004
  val = handler(injdef, val, ref, store);
768
1005
  }
1006
+ // console.log('GETPATH', path, val)
769
1007
  return val;
770
1008
  }
771
1009
  // Inject values from a data store into a node recursively, resolving
772
- // paths against the store, or current if they are local. THe modify
1010
+ // paths against the store, or current if they are local. The modify
773
1011
  // argument allows custom modification of the result. The inj
774
1012
  // (Injection) argument is used to maintain recursive state.
775
1013
  function inject(val, store, injdef) {
@@ -777,13 +1015,13 @@ function inject(val, store, injdef) {
777
1015
  let inj = injdef;
778
1016
  // Create state if at root of injection. The input value is placed
779
1017
  // inside a virtual parent holder to simplify edge cases.
780
- if (UNDEF === injdef || null == injdef.mode) {
1018
+ if (NONE === injdef || null == injdef.mode) {
781
1019
  // Set up state assuming we are starting in the virtual parent.
782
1020
  inj = new Injection(val, { [S_DTOP]: val });
783
1021
  inj.dparent = store;
784
1022
  inj.errs = getprop(store, S_DERRS, []);
785
1023
  inj.meta.__d = 0;
786
- if (UNDEF !== injdef) {
1024
+ if (NONE !== injdef) {
787
1025
  inj.modify = null == injdef.modify ? inj.modify : injdef.modify;
788
1026
  inj.extra = null == injdef.extra ? inj.extra : injdef.extra;
789
1027
  inj.meta = null == injdef.meta ? inj.meta : injdef.meta;
@@ -791,33 +1029,42 @@ function inject(val, store, injdef) {
791
1029
  }
792
1030
  }
793
1031
  inj.descend();
1032
+ // console.log('INJ-START', val, inj.mode, inj.key, inj.val,
1033
+ // 't=', inj.path, 'P=', inj.parent, 'dp=', inj.dparent, 'ST=', store.$TOP)
794
1034
  // Descend into node.
795
1035
  if (isnode(val)) {
796
1036
  // Keys are sorted alphanumerically to ensure determinism.
797
1037
  // Injection transforms ($FOO) are processed *after* other keys.
798
1038
  // NOTE: the optional digits suffix of the transform can thus be
799
1039
  // used to order the transforms.
800
- let nodekeys = ismap(val) ? [
801
- ...Object.keys(val).filter(k => !k.includes(S_DS)).sort(),
802
- ...Object.keys(val).filter(k => k.includes(S_DS)).sort(),
803
- ] : val.map((_n, i) => i);
1040
+ let nodekeys;
1041
+ nodekeys = keysof(val);
1042
+ if (ismap(val)) {
1043
+ nodekeys = flatten([
1044
+ filter(nodekeys, (n => !n[1].includes(S_DS))),
1045
+ filter(nodekeys, (n => n[1].includes(S_DS))),
1046
+ ]);
1047
+ }
1048
+ else {
1049
+ nodekeys = keysof(val);
1050
+ }
804
1051
  // Each child key-value pair is processed in three injection phases:
805
- // 1. inj.mode='key:pre' - Key string is injected, returning a possibly altered key.
806
- // 2. inj.mode='val' - The child value is injected.
807
- // 3. inj.mode='key:post' - Key string is injected again, allowing child mutation.
1052
+ // 1. inj.mode=M_KEYPRE - Key string is injected, returning a possibly altered key.
1053
+ // 2. inj.mode=M_VAL - The child value is injected.
1054
+ // 3. inj.mode=M_KEYPOST - Key string is injected again, allowing child mutation.
808
1055
  for (let nkI = 0; nkI < nodekeys.length; nkI++) {
809
1056
  const childinj = inj.child(nkI, nodekeys);
810
1057
  const nodekey = childinj.key;
811
- childinj.mode = S_MKEYPRE;
1058
+ childinj.mode = M_KEYPRE;
812
1059
  // Peform the key:pre mode injection on the child key.
813
1060
  const prekey = _injectstr(nodekey, store, childinj);
814
1061
  // The injection may modify child processing.
815
1062
  nkI = childinj.keyI;
816
1063
  nodekeys = childinj.keys;
817
1064
  // Prevent further processing by returning an undefined prekey
818
- if (UNDEF !== prekey) {
1065
+ if (NONE !== prekey) {
819
1066
  childinj.val = getprop(val, prekey);
820
- childinj.mode = S_MVAL;
1067
+ childinj.mode = M_VAL;
821
1068
  // Perform the val mode injection on the child value.
822
1069
  // NOTE: return value is not used.
823
1070
  inject(childinj.val, store, childinj);
@@ -825,7 +1072,7 @@ function inject(val, store, injdef) {
825
1072
  nkI = childinj.keyI;
826
1073
  nodekeys = childinj.keys;
827
1074
  // Peform the key:post mode injection on the child key.
828
- childinj.mode = S_MKEYPOST;
1075
+ childinj.mode = M_KEYPOST;
829
1076
  _injectstr(nodekey, store, childinj);
830
1077
  // The injection may modify child processing.
831
1078
  nkI = childinj.keyI;
@@ -835,7 +1082,7 @@ function inject(val, store, injdef) {
835
1082
  }
836
1083
  // Inject paths into string scalars.
837
1084
  else if (S_string === valtype) {
838
- inj.mode = S_MVAL;
1085
+ inj.mode = M_VAL;
839
1086
  val = _injectstr(val, store, inj);
840
1087
  if (SKIP !== val) {
841
1088
  inj.setval(val);
@@ -848,6 +1095,7 @@ function inject(val, store, injdef) {
848
1095
  let mval = getprop(mparent, mkey);
849
1096
  inj.modify(mval, mkey, mparent, inj, store);
850
1097
  }
1098
+ // console.log('INJ-VAL', val)
851
1099
  inj.val = val;
852
1100
  // Original val reference may no longer be correct.
853
1101
  // This return value is only used as the top level result.
@@ -856,42 +1104,43 @@ function inject(val, store, injdef) {
856
1104
  // The transform_* functions are special command inject handlers (see Injector).
857
1105
  // Delete a key from a map or list.
858
1106
  const transform_DELETE = (inj) => {
859
- inj.setval(UNDEF);
860
- return UNDEF;
1107
+ inj.setval(NONE);
1108
+ return NONE;
861
1109
  };
862
1110
  // Copy value from source data.
863
1111
  const transform_COPY = (inj, _val) => {
864
- const { mode, key } = inj;
865
- let out = key;
866
- if (!mode.startsWith(S_MKEY)) {
867
- out = getprop(inj.dparent, key);
868
- inj.setval(out);
1112
+ const ijname = 'COPY';
1113
+ if (!checkPlacement(M_VAL, ijname, T_any, inj)) {
1114
+ return NONE;
869
1115
  }
1116
+ let out = getprop(inj.dparent, inj.key);
1117
+ inj.setval(out);
870
1118
  return out;
871
1119
  };
872
1120
  // As a value, inject the key of the parent node.
873
1121
  // As a key, defined the name of the key property in the source object.
874
1122
  const transform_KEY = (inj) => {
875
1123
  const { mode, path, parent } = inj;
876
- // Do nothing in val mode.
877
- if (S_MVAL !== mode) {
878
- return UNDEF;
1124
+ // Do nothing in val mode - not an error.
1125
+ if (M_VAL !== mode) {
1126
+ return NONE;
879
1127
  }
880
1128
  // Key is defined by $KEY meta property.
881
1129
  const keyspec = getprop(parent, S_BKEY);
882
- if (UNDEF !== keyspec) {
1130
+ if (NONE !== keyspec) {
883
1131
  delprop(parent, S_BKEY);
884
1132
  return getprop(inj.dparent, keyspec);
885
1133
  }
886
1134
  // Key is defined within general purpose $META object.
887
- return getprop(getprop(parent, S_BANNO), S_KEY, getprop(path, path.length - 2));
1135
+ // return getprop(getprop(parent, S_BANNO), S_KEY, getprop(path, path.length - 2))
1136
+ return getprop(getprop(parent, S_BANNO), S_KEY, getelem(path, -2));
888
1137
  };
889
- // Annotatea node. Does nothing itself, just used by
1138
+ // Annotate node. Does nothing itself, just used by
890
1139
  // other injectors, and is removed when called.
891
1140
  const transform_ANNO = (inj) => {
892
1141
  const { parent } = inj;
893
1142
  delprop(parent, S_BANNO);
894
- return UNDEF;
1143
+ return NONE;
895
1144
  };
896
1145
  // Merge a list of objects into the current object.
897
1146
  // Must be a key in an object. The value is merged over the current object.
@@ -901,70 +1150,70 @@ const transform_ANNO = (inj) => {
901
1150
  const transform_MERGE = (inj) => {
902
1151
  const { mode, key, parent } = inj;
903
1152
  // Ensures $MERGE is removed from parent list (val mode).
904
- let out = UNDEF;
905
- if (S_MKEYPRE === mode) {
1153
+ let out = NONE;
1154
+ if (M_KEYPRE === mode) {
906
1155
  out = key;
907
1156
  }
908
1157
  // Operate after child values have been transformed.
909
- else if (S_MKEYPOST === mode) {
1158
+ else if (M_KEYPOST === mode) {
910
1159
  out = key;
911
1160
  let args = getprop(parent, key);
912
1161
  args = Array.isArray(args) ? args : [args];
913
1162
  // Remove the $MERGE command from a parent map.
914
- inj.setval(UNDEF);
1163
+ inj.setval(NONE);
915
1164
  // Literals in the parent have precedence, but we still merge onto
916
1165
  // the parent object, so that node tree references are not changed.
917
- const mergelist = [parent, ...args, clone(parent)];
1166
+ const mergelist = flatten([[parent], args, [clone(parent)]]);
918
1167
  merge(mergelist);
919
- // return key
920
1168
  }
921
1169
  return out;
922
1170
  };
923
1171
  // Convert a node to a list.
924
1172
  // Format: ['`$EACH`', '`source-path-of-node`', child-template]
925
1173
  const transform_EACH = (inj, _val, _ref, store) => {
926
- // Remove arguments to avoid spurious processing.
927
- if (null != inj.keys) {
928
- inj.keys.length = 1;
1174
+ const ijname = 'EACH';
1175
+ if (!checkPlacement(M_VAL, ijname, T_list, inj)) {
1176
+ return NONE;
1177
+ }
1178
+ // Remove remaining keys to avoid spurious processing.
1179
+ slice(inj.keys, 0, 1, true);
1180
+ // const [err, srcpath, child] = injectorArgs([T_string, T_any], inj)
1181
+ const [err, srcpath, child] = injectorArgs([T_string, T_any], slice(inj.parent, 1));
1182
+ if (NONE !== err) {
1183
+ inj.errs.push('$' + ijname + ': ' + err);
1184
+ return NONE;
929
1185
  }
930
- if (S_MVAL !== inj.mode) {
931
- return UNDEF;
932
- }
933
- // Get arguments: ['`$EACH`', 'source-path', child-template].
934
- const srcpath = getprop(inj.parent, 1);
935
- const child = clone(getprop(inj.parent, 2));
936
1186
  // Source data.
937
1187
  const srcstore = getprop(store, inj.base, store);
938
1188
  const src = getpath(srcstore, srcpath, inj);
1189
+ const srctype = typify(src);
939
1190
  // Create parallel data structures:
940
1191
  // source entries :: child templates
941
1192
  let tcur = [];
942
1193
  let tval = [];
943
- const tkey = inj.path[inj.path.length - 2];
944
- const target = inj.nodes[inj.nodes.length - 2] || inj.nodes[inj.nodes.length - 1];
1194
+ const tkey = getelem(inj.path, -2);
1195
+ const target = getelem(inj.nodes, -2, () => getelem(inj.nodes, -1));
945
1196
  // Create clones of the child template for each value of the current soruce.
946
- if (islist(src)) {
947
- tval = src.map(() => clone(child));
1197
+ if (0 < (T_list & srctype)) {
1198
+ tval = items(src, () => clone(child));
948
1199
  }
949
- else if (ismap(src)) {
950
- tval = Object.entries(src).map(n => ({
951
- ...clone(child),
1200
+ else if (0 < (T_map & srctype)) {
1201
+ tval = items(src, (n => merge([
1202
+ clone(child),
952
1203
  // Make a note of the key for $KEY transforms.
953
- [S_BANNO]: { KEY: n[0] }
954
- }));
1204
+ { [S_BANNO]: { KEY: n[0] } }
1205
+ ], 1)));
955
1206
  }
956
1207
  let rval = [];
957
1208
  if (0 < size(tval)) {
958
- tcur = null == src ? UNDEF : Object.values(src);
1209
+ tcur = null == src ? NONE : Object.values(src);
959
1210
  const ckey = getelem(inj.path, -2);
960
1211
  const tpath = slice(inj.path, -1);
961
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey];
1212
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey]);
962
1213
  // Parent structure.
963
- // const ckey = getelem(cpath, -1)
964
1214
  tcur = { [ckey]: tcur };
965
- if (1 < tpath.length) {
1215
+ if (1 < size(tpath)) {
966
1216
  const pkey = getelem(inj.path, -3, S_DTOP);
967
- // const pkey = getelem(cpath, -2, S_DTOP)
968
1217
  tcur = { [pkey]: tcur };
969
1218
  dpath.push('$:' + pkey);
970
1219
  }
@@ -979,70 +1228,93 @@ const transform_EACH = (inj, _val, _ref, store) => {
979
1228
  inject(tval, store, tinj);
980
1229
  rval = tinj.val;
981
1230
  }
982
- _updateAncestors(inj, target, tkey, rval);
1231
+ // _updateAncestors(inj, target, tkey, rval)
1232
+ setprop(target, tkey, rval);
983
1233
  // Prevent callee from damaging first list entry (since we are in `val` mode).
984
1234
  return rval[0];
985
1235
  };
986
1236
  // Convert a node to a map.
987
- // Format: { '`$PACK`':['`source-path`', child-template]}
1237
+ // Format: { '`$PACK`':['source-path', child-template]}
988
1238
  const transform_PACK = (inj, _val, _ref, store) => {
989
1239
  const { mode, key, path, parent, nodes } = inj;
990
- // Defensive context checks.
991
- if (S_MKEYPRE !== mode || S_string !== typeof key || null == path || null == nodes) {
992
- return UNDEF;
1240
+ const ijname = 'EACH';
1241
+ if (!checkPlacement(M_KEYPRE, ijname, T_map, inj)) {
1242
+ return NONE;
993
1243
  }
994
1244
  // Get arguments.
995
- const args = parent[key];
996
- const srcpath = args[0]; // Path to source data.
997
- const child = clone(args[1]); // Child template.
1245
+ const args = getprop(parent, key);
1246
+ const [err, srcpath, origchildspec] = injectorArgs([T_string, T_any], args);
1247
+ if (NONE !== err) {
1248
+ inj.errs.push('$' + ijname + ': ' + err);
1249
+ return NONE;
1250
+ }
998
1251
  // Find key and target node.
999
- const keyprop = child[S_BKEY];
1000
1252
  const tkey = getelem(path, -2);
1001
- const target = nodes[path.length - 2] || nodes[path.length - 1];
1253
+ const pathsize = size(path);
1254
+ const target = getelem(nodes, pathsize - 2, () => getelem(nodes, pathsize - 1));
1002
1255
  // Source data
1003
1256
  const srcstore = getprop(store, inj.base, store);
1004
1257
  let src = getpath(srcstore, srcpath, inj);
1005
1258
  // Prepare source as a list.
1006
- src = islist(src) ? src :
1007
- ismap(src) ? Object.entries(src)
1008
- .reduce((a, n) => (n[1][S_BANNO] = { KEY: n[0] }, a.push(n[1]), a), []) :
1009
- UNDEF;
1259
+ if (!islist(src)) {
1260
+ if (ismap(src)) {
1261
+ src = items(src, (item) => {
1262
+ setprop(item[1], S_BANNO, { KEY: item[0] });
1263
+ return item[1];
1264
+ });
1265
+ }
1266
+ else {
1267
+ src = NONE;
1268
+ }
1269
+ }
1010
1270
  if (null == src) {
1011
- return UNDEF;
1271
+ return NONE;
1012
1272
  }
1013
- // Get key if specified.
1014
- let childkey = getprop(child, S_BKEY);
1015
- let keyname = UNDEF === childkey ? keyprop : childkey;
1016
- delprop(child, S_BKEY);
1273
+ // Get keypath.
1274
+ const keypath = getprop(origchildspec, S_BKEY);
1275
+ const childspec = delprop(origchildspec, S_BKEY);
1276
+ const child = getprop(childspec, S_BVAL, childspec);
1017
1277
  // Build parallel target object.
1018
1278
  let tval = {};
1019
- tval = src.reduce((a, n) => {
1020
- let kn = getprop(n, keyname);
1021
- setprop(a, kn, clone(child));
1022
- const nchild = getprop(a, kn);
1023
- const mval = getprop(n, S_BANNO);
1024
- if (UNDEF === mval) {
1025
- delprop(nchild, S_BANNO);
1279
+ items(src, (item) => {
1280
+ const srckey = item[0];
1281
+ const srcnode = item[1];
1282
+ let key = srckey;
1283
+ if (NONE !== keypath) {
1284
+ if (keypath.startsWith('`')) {
1285
+ key = inject(keypath, merge([{}, store, { $TOP: srcnode }], 1));
1286
+ }
1287
+ else {
1288
+ key = getpath(srcnode, keypath, inj);
1289
+ }
1290
+ }
1291
+ const tchild = clone(child);
1292
+ setprop(tval, key, tchild);
1293
+ const anno = getprop(srcnode, S_BANNO);
1294
+ if (NONE === anno) {
1295
+ delprop(tchild, S_BANNO);
1026
1296
  }
1027
1297
  else {
1028
- setprop(nchild, S_BANNO, mval);
1298
+ setprop(tchild, S_BANNO, anno);
1029
1299
  }
1030
- return a;
1031
- }, tval);
1300
+ });
1032
1301
  let rval = {};
1033
- if (0 < size(tval)) {
1302
+ if (!isempty(tval)) {
1034
1303
  // Build parallel source object.
1035
- let tcur = {};
1036
- src.reduce((a, n) => {
1037
- let kn = getprop(n, keyname);
1304
+ let tsrc = {};
1305
+ src.reduce((a, n, i) => {
1306
+ let kn = null == keypath ? i :
1307
+ keypath.startsWith('`') ?
1308
+ inject(keypath, merge([{}, store, { $TOP: n }], 1)) :
1309
+ getpath(n, keypath, inj);
1038
1310
  setprop(a, kn, n);
1039
1311
  return a;
1040
- }, tcur);
1312
+ }, tsrc);
1041
1313
  const tpath = slice(inj.path, -1);
1042
1314
  const ckey = getelem(inj.path, -2);
1043
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey];
1044
- tcur = { [ckey]: tcur };
1045
- if (1 < tpath.length) {
1315
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey]);
1316
+ let tcur = { [ckey]: tsrc };
1317
+ if (1 < size(tpath)) {
1046
1318
  const pkey = getelem(inj.path, -3, S_DTOP);
1047
1319
  tcur = { [pkey]: tcur };
1048
1320
  dpath.push('$:' + pkey);
@@ -1050,7 +1322,6 @@ const transform_PACK = (inj, _val, _ref, store) => {
1050
1322
  const tinj = inj.child(0, [ckey]);
1051
1323
  tinj.path = tpath;
1052
1324
  tinj.nodes = slice(inj.nodes, -1);
1053
- // tinj.parent = tcur
1054
1325
  tinj.parent = getelem(tinj.nodes, -1);
1055
1326
  tinj.val = tval;
1056
1327
  tinj.dpath = dpath;
@@ -1058,27 +1329,31 @@ const transform_PACK = (inj, _val, _ref, store) => {
1058
1329
  inject(tval, store, tinj);
1059
1330
  rval = tinj.val;
1060
1331
  }
1061
- _updateAncestors(inj, target, tkey, rval);
1332
+ // _updateAncestors(inj, target, tkey, rval)
1333
+ setprop(target, tkey, rval);
1062
1334
  // Drop transform key.
1063
- return UNDEF;
1335
+ return NONE;
1064
1336
  };
1065
- // TODO: not found ref should removed key (setprop UNDEF)
1337
+ // TODO: not found ref should removed key (setprop NONE)
1066
1338
  // Reference original spec (enables recursice transformations)
1067
1339
  // Format: ['`$REF`', '`spec-path`']
1068
1340
  const transform_REF = (inj, val, _ref, store) => {
1069
1341
  const { nodes } = inj;
1070
- if (S_MVAL !== inj.mode) {
1071
- return UNDEF;
1342
+ if (M_VAL !== inj.mode) {
1343
+ return NONE;
1072
1344
  }
1073
1345
  // Get arguments: ['`$REF`', 'ref-path'].
1074
1346
  const refpath = getprop(inj.parent, 1);
1075
- inj.keyI = inj.keys.length;
1347
+ inj.keyI = size(inj.keys);
1076
1348
  // Spec reference.
1077
1349
  const spec = getprop(store, S_DSPEC)();
1350
+ const dpath = slice(inj.path, 1);
1078
1351
  const ref = getpath(spec, refpath, {
1079
1352
  // TODO: test relative refs
1080
- dpath: inj.path.slice(1),
1081
- dparent: getpath(spec, inj.path.slice(1))
1353
+ // dpath: inj.path.slice(1),
1354
+ dpath,
1355
+ // dparent: getpath(spec, inj.path.slice(1))
1356
+ dparent: getpath(spec, dpath),
1082
1357
  });
1083
1358
  let hasSubRef = false;
1084
1359
  if (isnode(ref)) {
@@ -1094,20 +1369,20 @@ const transform_REF = (inj, val, _ref, store) => {
1094
1369
  const tpath = slice(inj.path, -1);
1095
1370
  let tcur = getpath(store, cpath);
1096
1371
  let tval = getpath(store, tpath);
1097
- let rval = UNDEF;
1098
- if (!hasSubRef || UNDEF !== tval) {
1372
+ let rval = NONE;
1373
+ if (!hasSubRef || NONE !== tval) {
1099
1374
  const tinj = inj.child(0, [getelem(tpath, -1)]);
1100
1375
  tinj.path = tpath;
1101
1376
  tinj.nodes = slice(inj.nodes, -1);
1102
1377
  tinj.parent = getelem(nodes, -2);
1103
1378
  tinj.val = tref;
1104
- tinj.dpath = [...cpath];
1379
+ tinj.dpath = flatten([cpath]);
1105
1380
  tinj.dparent = tcur;
1106
1381
  inject(tref, store, tinj);
1107
1382
  rval = tinj.val;
1108
1383
  }
1109
1384
  else {
1110
- rval = UNDEF;
1385
+ rval = NONE;
1111
1386
  }
1112
1387
  const grandparent = inj.setval(rval, 2);
1113
1388
  if (islist(grandparent) && inj.prior) {
@@ -1115,6 +1390,82 @@ const transform_REF = (inj, val, _ref, store) => {
1115
1390
  }
1116
1391
  return val;
1117
1392
  };
1393
+ const transform_FORMAT = (inj, _val, _ref, store) => {
1394
+ // console.log('FORMAT-START', inj, _val)
1395
+ // Remove remaining keys to avoid spurious processing.
1396
+ slice(inj.keys, 0, 1, true);
1397
+ if (M_VAL !== inj.mode) {
1398
+ return NONE;
1399
+ }
1400
+ // Get arguments: ['`$FORMAT`', 'name', child].
1401
+ // TODO: EACH and PACK should accept customm functions too
1402
+ const name = getprop(inj.parent, 1);
1403
+ const child = getprop(inj.parent, 2);
1404
+ // Source data.
1405
+ const tkey = getelem(inj.path, -2);
1406
+ const target = getelem(inj.nodes, -2, () => getelem(inj.nodes, -1));
1407
+ const cinj = injectChild(child, store, inj);
1408
+ const resolved = cinj.val;
1409
+ let formatter = 0 < (T_function & typify(name)) ? name : getprop(FORMATTER, name);
1410
+ if (NONE === formatter) {
1411
+ inj.errs.push('$FORMAT: unknown format: ' + name + '.');
1412
+ return NONE;
1413
+ }
1414
+ let out = walk(resolved, formatter);
1415
+ setprop(target, tkey, out);
1416
+ // _updateAncestors(inj, target, tkey, out)
1417
+ return out;
1418
+ };
1419
+ const FORMATTER = {
1420
+ identity: (_k, v) => v,
1421
+ upper: (_k, v) => isnode(v) ? v : ('' + v).toUpperCase(),
1422
+ lower: (_k, v) => isnode(v) ? v : ('' + v).toLowerCase(),
1423
+ string: (_k, v) => isnode(v) ? v : ('' + v),
1424
+ number: (_k, v) => {
1425
+ if (isnode(v)) {
1426
+ return v;
1427
+ }
1428
+ else {
1429
+ let n = Number(v);
1430
+ if (isNaN(n)) {
1431
+ n = 0;
1432
+ }
1433
+ return n;
1434
+ }
1435
+ },
1436
+ integer: (_k, v) => {
1437
+ if (isnode(v)) {
1438
+ return v;
1439
+ }
1440
+ else {
1441
+ let n = Number(v);
1442
+ if (isNaN(n)) {
1443
+ n = 0;
1444
+ }
1445
+ return n | 0;
1446
+ }
1447
+ },
1448
+ concat: (k, v) => null == k && islist(v) ? join(items(v, (n => isnode(n[1]) ? S_MT : (S_MT + n[1]))), S_MT) : v
1449
+ };
1450
+ const transform_APPLY = (inj, _val, _ref, store) => {
1451
+ const ijname = 'APPLY';
1452
+ if (!checkPlacement(M_VAL, ijname, T_list, inj)) {
1453
+ return NONE;
1454
+ }
1455
+ // const [err, apply, child] = injectorArgs([T_function, T_any], inj)
1456
+ const [err, apply, child] = injectorArgs([T_function, T_any], slice(inj.parent, 1));
1457
+ if (NONE !== err) {
1458
+ inj.errs.push('$' + ijname + ': ' + err);
1459
+ return NONE;
1460
+ }
1461
+ const tkey = getelem(inj.path, -2);
1462
+ const target = getelem(inj.nodes, -2, () => getelem(inj.nodes, -1));
1463
+ const cinj = injectChild(child, store, inj);
1464
+ const resolved = cinj.val;
1465
+ const out = apply(resolved, store, cinj);
1466
+ setprop(target, tkey, out);
1467
+ return out;
1468
+ };
1118
1469
  // Transform data using spec.
1119
1470
  // Only operates on static JSON-like data.
1120
1471
  // Arrays are treated as if they are objects with indices as keys.
@@ -1125,64 +1476,78 @@ injdef) {
1125
1476
  const origspec = spec;
1126
1477
  spec = clone(origspec);
1127
1478
  const extra = injdef?.extra;
1128
- // const modify = injdef?.modify
1479
+ const collect = null != injdef?.errs;
1480
+ const errs = injdef?.errs || [];
1129
1481
  const extraTransforms = {};
1130
- const extraData = null == extra ? UNDEF : items(extra)
1482
+ const extraData = null == extra ? NONE : items(extra)
1131
1483
  .reduce((a, n) => (n[0].startsWith(S_DS) ? extraTransforms[n[0]] = n[1] : (a[n[0]] = n[1]), a), {});
1132
1484
  const dataClone = merge([
1133
- isempty(extraData) ? UNDEF : clone(extraData),
1485
+ isempty(extraData) ? NONE : clone(extraData),
1134
1486
  clone(data),
1135
1487
  ]);
1136
1488
  // Define a top level store that provides transform operations.
1137
- const store = {
1138
- // The inject function recognises this special location for the root of the source data.
1139
- // NOTE: to escape data that contains "`$FOO`" keys at the top level,
1140
- // place that data inside a holding map: { myholder: mydata }.
1141
- $TOP: dataClone,
1142
- $SPEC: () => origspec,
1143
- // Escape backtick (this also works inside backticks).
1144
- $BT: () => S_BT,
1145
- // Escape dollar sign (this also works inside backticks).
1146
- $DS: () => S_DS,
1147
- // Insert current date and time as an ISO string.
1148
- $WHEN: () => new Date().toISOString(),
1149
- $DELETE: transform_DELETE,
1150
- $COPY: transform_COPY,
1151
- $KEY: transform_KEY,
1152
- $ANNO: transform_ANNO,
1153
- $MERGE: transform_MERGE,
1154
- $EACH: transform_EACH,
1155
- $PACK: transform_PACK,
1156
- $REF: transform_REF,
1489
+ const store = merge([
1490
+ {
1491
+ // The inject function recognises this special location for the root of the source data.
1492
+ // NOTE: to escape data that contains "`$FOO`" keys at the top level,
1493
+ // place that data inside a holding map: { myholder: mydata }.
1494
+ $TOP: dataClone,
1495
+ $SPEC: () => origspec,
1496
+ // Escape backtick (this also works inside backticks).
1497
+ $BT: () => S_BT,
1498
+ // Escape dollar sign (this also works inside backticks).
1499
+ $DS: () => S_DS,
1500
+ // Insert current date and time as an ISO string.
1501
+ $WHEN: () => new Date().toISOString(),
1502
+ $DELETE: transform_DELETE,
1503
+ $COPY: transform_COPY,
1504
+ $KEY: transform_KEY,
1505
+ $ANNO: transform_ANNO,
1506
+ $MERGE: transform_MERGE,
1507
+ $EACH: transform_EACH,
1508
+ $PACK: transform_PACK,
1509
+ $REF: transform_REF,
1510
+ $FORMAT: transform_FORMAT,
1511
+ $APPLY: transform_APPLY,
1512
+ },
1157
1513
  // Custom extra transforms, if any.
1158
- ...extraTransforms,
1159
- };
1514
+ extraTransforms,
1515
+ {
1516
+ $ERRS: errs,
1517
+ }
1518
+ ], 1);
1160
1519
  const out = inject(spec, store, injdef);
1520
+ const generr = (0 < size(errs) && !collect);
1521
+ if (generr) {
1522
+ throw new Error(join(errs, ' | '));
1523
+ }
1161
1524
  return out;
1162
1525
  }
1163
1526
  // A required string value. NOTE: Rejects empty strings.
1164
1527
  const validate_STRING = (inj) => {
1165
1528
  let out = getprop(inj.dparent, inj.key);
1166
1529
  const t = typify(out);
1167
- if (S_string !== t) {
1530
+ if (0 === (T_string & t)) {
1168
1531
  let msg = _invalidTypeMsg(inj.path, S_string, t, out, 'V1010');
1169
1532
  inj.errs.push(msg);
1170
- return UNDEF;
1533
+ return NONE;
1171
1534
  }
1172
1535
  if (S_MT === out) {
1173
1536
  let msg = 'Empty string at ' + pathify(inj.path, 1);
1174
1537
  inj.errs.push(msg);
1175
- return UNDEF;
1538
+ return NONE;
1176
1539
  }
1177
1540
  return out;
1178
1541
  };
1179
1542
  const validate_TYPE = (inj, _val, ref) => {
1180
- let tname = slice(ref, 1).toLowerCase();
1543
+ const tname = slice(ref, 1).toLowerCase();
1544
+ const typev = 1 << (31 - TYPENAME.indexOf(tname));
1181
1545
  let out = getprop(inj.dparent, inj.key);
1182
1546
  const t = typify(out);
1183
- if (t !== tname) {
1547
+ // console.log('TYPE', tname, typev, tn(typev), 'O=', t, tn(t), out, 'C=', t & typev)
1548
+ if (0 === (t & typev)) {
1184
1549
  inj.errs.push(_invalidTypeMsg(inj.path, tname, t, out, 'V1001'));
1185
- return UNDEF;
1550
+ return NONE;
1186
1551
  }
1187
1552
  return out;
1188
1553
  };
@@ -1198,17 +1563,17 @@ const validate_CHILD = (inj) => {
1198
1563
  const { mode, key, parent, keys, path } = inj;
1199
1564
  // Setup data structures for validation by cloning child template.
1200
1565
  // Map syntax.
1201
- if (S_MKEYPRE === mode) {
1566
+ if (M_KEYPRE === mode) {
1202
1567
  const childtm = getprop(parent, key);
1203
1568
  // Get corresponding current object.
1204
- const pkey = getprop(path, path.length - 2);
1569
+ const pkey = getelem(path, -2);
1205
1570
  let tval = getprop(inj.dparent, pkey);
1206
- if (UNDEF == tval) {
1571
+ if (NONE == tval) {
1207
1572
  tval = {};
1208
1573
  }
1209
1574
  else if (!ismap(tval)) {
1210
1575
  inj.errs.push(_invalidTypeMsg(slice(inj.path, -1), S_object, typify(tval), tval), 'V0220');
1211
- return UNDEF;
1576
+ return NONE;
1212
1577
  }
1213
1578
  const ckeys = keysof(tval);
1214
1579
  for (let ckey of ckeys) {
@@ -1217,58 +1582,62 @@ const validate_CHILD = (inj) => {
1217
1582
  keys.push(ckey);
1218
1583
  }
1219
1584
  // Remove $CHILD to cleanup ouput.
1220
- inj.setval(UNDEF);
1221
- return UNDEF;
1585
+ inj.setval(NONE);
1586
+ return NONE;
1222
1587
  }
1223
1588
  // List syntax.
1224
- if (S_MVAL === mode) {
1589
+ if (M_VAL === mode) {
1225
1590
  if (!islist(parent)) {
1226
1591
  // $CHILD was not inside a list.
1227
1592
  inj.errs.push('Invalid $CHILD as value');
1228
- return UNDEF;
1593
+ return NONE;
1229
1594
  }
1230
1595
  const childtm = getprop(parent, 1);
1231
- if (UNDEF === inj.dparent) {
1596
+ if (NONE === inj.dparent) {
1232
1597
  // Empty list as default.
1233
- parent.length = 0;
1234
- return UNDEF;
1598
+ // parent.length = 0
1599
+ slice(parent, 0, 0, true);
1600
+ return NONE;
1235
1601
  }
1236
1602
  if (!islist(inj.dparent)) {
1237
- const msg = _invalidTypeMsg(slice(inj.path, -1), S_array, typify(inj.dparent), inj.dparent, 'V0230');
1603
+ const msg = _invalidTypeMsg(slice(inj.path, -1), S_list, typify(inj.dparent), inj.dparent, 'V0230');
1238
1604
  inj.errs.push(msg);
1239
- inj.keyI = parent.length;
1605
+ inj.keyI = size(parent);
1240
1606
  return inj.dparent;
1241
1607
  }
1242
1608
  // Clone children abd reset inj key index.
1243
1609
  // The inject child loop will now iterate over the cloned children,
1244
1610
  // validating them againt the current list values.
1245
- inj.dparent.map((_n, i) => parent[i] = clone(childtm));
1246
- parent.length = inj.dparent.length;
1611
+ items(inj.dparent, (n) => setprop(parent, n[0], clone(childtm)));
1612
+ slice(parent, 0, inj.dparent.length, true);
1247
1613
  inj.keyI = 0;
1248
1614
  const out = getprop(inj.dparent, 0);
1249
1615
  return out;
1250
1616
  }
1251
- return UNDEF;
1617
+ return NONE;
1252
1618
  };
1619
+ // TODO: implement SOME, ALL
1620
+ // FIX: ONE should mean exactly one, not at least one (=SOME)
1621
+ // TODO: implement a generate validate_ALT to do all of these
1253
1622
  // Match at least one of the specified shapes.
1254
- // Syntax: ['`$ONE`', alt0, alt1, ...]okI
1623
+ // Syntax: ['`$ONE`', alt0, alt1, ...]
1255
1624
  const validate_ONE = (inj, _val, _ref, store) => {
1256
1625
  const { mode, parent, keyI } = inj;
1257
1626
  // Only operate in val mode, since parent is a list.
1258
- if (S_MVAL === mode) {
1627
+ if (M_VAL === mode) {
1259
1628
  if (!islist(parent) || 0 !== keyI) {
1260
1629
  inj.errs.push('The $ONE validator at field ' +
1261
1630
  pathify(inj.path, 1, 1) +
1262
1631
  ' must be the first element of an array.');
1263
1632
  return;
1264
1633
  }
1265
- inj.keyI = inj.keys.length;
1634
+ inj.keyI = size(inj.keys);
1266
1635
  // Clean up structure, replacing [$ONE, ...] with current
1267
1636
  inj.setval(inj.dparent, 2);
1268
1637
  inj.path = slice(inj.path, -1);
1269
1638
  inj.key = getelem(inj.path, -1);
1270
1639
  let tvals = slice(parent, 1);
1271
- if (0 === tvals.length) {
1640
+ if (0 === size(tvals)) {
1272
1641
  inj.errs.push('The $ONE validator at field ' +
1273
1642
  pathify(inj.path, 1, 1) +
1274
1643
  ' must have at least one argument.');
@@ -1278,7 +1647,7 @@ const validate_ONE = (inj, _val, _ref, store) => {
1278
1647
  for (let tval of tvals) {
1279
1648
  // If match, then errs.length = 0
1280
1649
  let terrs = [];
1281
- const vstore = { ...store };
1650
+ const vstore = merge([{}, store], 1);
1282
1651
  vstore.$TOP = inj.dparent;
1283
1652
  const vcurrent = validate(inj.dparent, tval, {
1284
1653
  extra: vstore,
@@ -1287,35 +1656,33 @@ const validate_ONE = (inj, _val, _ref, store) => {
1287
1656
  });
1288
1657
  inj.setval(vcurrent, -2);
1289
1658
  // Accept current value if there was a match
1290
- if (0 === terrs.length) {
1659
+ if (0 === size(terrs)) {
1291
1660
  return;
1292
1661
  }
1293
1662
  }
1294
1663
  // There was no match.
1295
- const valdesc = tvals
1296
- .map((v) => stringify(v))
1297
- .join(', ')
1298
- .replace(R_TRANSFORM_NAME, (_m, p1) => p1.toLowerCase());
1299
- inj.errs.push(_invalidTypeMsg(inj.path, (1 < tvals.length ? 'one of ' : '') + valdesc, typify(inj.dparent), inj.dparent, 'V0210'));
1664
+ const valdesc = replace(join(items(tvals, (n) => stringify(n[1])), ', '), R_TRANSFORM_NAME, (_m, p1) => p1.toLowerCase());
1665
+ inj.errs.push(_invalidTypeMsg(inj.path, (1 < size(tvals) ? 'one of ' : '') + valdesc, typify(inj.dparent), inj.dparent, 'V0210'));
1300
1666
  }
1301
1667
  };
1302
1668
  const validate_EXACT = (inj) => {
1303
1669
  const { mode, parent, key, keyI } = inj;
1304
1670
  // Only operate in val mode, since parent is a list.
1305
- if (S_MVAL === mode) {
1671
+ if (M_VAL === mode) {
1306
1672
  if (!islist(parent) || 0 !== keyI) {
1307
1673
  inj.errs.push('The $EXACT validator at field ' +
1308
1674
  pathify(inj.path, 1, 1) +
1309
1675
  ' must be the first element of an array.');
1310
1676
  return;
1311
1677
  }
1312
- inj.keyI = inj.keys.length;
1678
+ inj.keyI = size(inj.keys);
1313
1679
  // Clean up structure, replacing [$EXACT, ...] with current data parent
1314
1680
  inj.setval(inj.dparent, 2);
1315
- inj.path = slice(inj.path, 0, inj.path.length - 1);
1681
+ // inj.path = slice(inj.path, 0, size(inj.path) - 1)
1682
+ inj.path = slice(inj.path, 0, -1);
1316
1683
  inj.key = getelem(inj.path, -1);
1317
1684
  let tvals = slice(parent, 1);
1318
- if (0 === tvals.length) {
1685
+ if (0 === size(tvals)) {
1319
1686
  inj.errs.push('The $EXACT validator at field ' +
1320
1687
  pathify(inj.path, 1, 1) +
1321
1688
  ' must have at least one argument.');
@@ -1334,12 +1701,10 @@ const validate_EXACT = (inj) => {
1334
1701
  return;
1335
1702
  }
1336
1703
  }
1337
- const valdesc = tvals
1338
- .map((v) => stringify(v))
1339
- .join(', ')
1340
- .replace(R_TRANSFORM_NAME, (_m, p1) => p1.toLowerCase());
1341
- inj.errs.push(_invalidTypeMsg(inj.path, (1 < inj.path.length ? '' : 'value ') +
1342
- 'exactly equal to ' + (1 === tvals.length ? '' : 'one of ') + valdesc, typify(inj.dparent), inj.dparent, 'V0110'));
1704
+ // There was no match.
1705
+ const valdesc = replace(join(items(tvals, (n) => stringify(n[1])), ', '), R_TRANSFORM_NAME, (_m, p1) => p1.toLowerCase());
1706
+ inj.errs.push(_invalidTypeMsg(inj.path, (1 < size(inj.path) ? '' : 'value ') +
1707
+ 'exactly equal to ' + (1 === size(tvals) ? '' : 'one of ') + valdesc, typify(inj.dparent), inj.dparent, 'V0110'));
1343
1708
  }
1344
1709
  else {
1345
1710
  delprop(parent, key);
@@ -1348,7 +1713,7 @@ const validate_EXACT = (inj) => {
1348
1713
  // This is the "modify" argument to inject. Use this to perform
1349
1714
  // generic validation. Runs *after* any special commands.
1350
1715
  const _validation = (pval, key, parent, inj) => {
1351
- if (UNDEF === inj) {
1716
+ if (NONE === inj) {
1352
1717
  return;
1353
1718
  }
1354
1719
  if (SKIP === pval) {
@@ -1358,29 +1723,29 @@ const _validation = (pval, key, parent, inj) => {
1358
1723
  const exact = getprop(inj.meta, S_BEXACT, false);
1359
1724
  // Current val to verify.
1360
1725
  const cval = getprop(inj.dparent, key);
1361
- if (UNDEF === inj || (!exact && UNDEF === cval)) {
1726
+ if (NONE === inj || (!exact && NONE === cval)) {
1362
1727
  return;
1363
1728
  }
1364
1729
  const ptype = typify(pval);
1365
1730
  // Delete any special commands remaining.
1366
- if (S_string === ptype && pval.includes(S_DS)) {
1731
+ if (0 < (T_string & ptype) && pval.includes(S_DS)) {
1367
1732
  return;
1368
1733
  }
1369
1734
  const ctype = typify(cval);
1370
1735
  // Type mismatch.
1371
- if (ptype !== ctype && UNDEF !== pval) {
1372
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0010'));
1736
+ if (ptype !== ctype && NONE !== pval) {
1737
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0010'));
1373
1738
  return;
1374
1739
  }
1375
1740
  if (ismap(cval)) {
1376
1741
  if (!ismap(pval)) {
1377
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0020'));
1742
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0020'));
1378
1743
  return;
1379
1744
  }
1380
1745
  const ckeys = keysof(cval);
1381
1746
  const pkeys = keysof(pval);
1382
1747
  // Empty spec object {} means object can be open (any keys).
1383
- if (0 < pkeys.length && true !== getprop(pval, '`$OPEN`')) {
1748
+ if (0 < size(pkeys) && true !== getprop(pval, '`$OPEN`')) {
1384
1749
  const badkeys = [];
1385
1750
  for (let ckey of ckeys) {
1386
1751
  if (!haskey(pval, ckey)) {
@@ -1388,8 +1753,8 @@ const _validation = (pval, key, parent, inj) => {
1388
1753
  }
1389
1754
  }
1390
1755
  // Closed object, so reject extra keys not in shape.
1391
- if (0 < badkeys.length) {
1392
- const msg = 'Unexpected keys at field ' + pathify(inj.path, 1) + S_VIZ + badkeys.join(', ');
1756
+ if (0 < size(badkeys)) {
1757
+ const msg = 'Unexpected keys at field ' + pathify(inj.path, 1) + S_VIZ + join(badkeys, ', ');
1393
1758
  inj.errs.push(msg);
1394
1759
  }
1395
1760
  }
@@ -1403,7 +1768,7 @@ const _validation = (pval, key, parent, inj) => {
1403
1768
  }
1404
1769
  else if (islist(cval)) {
1405
1770
  if (!islist(pval)) {
1406
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0030'));
1771
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0030'));
1407
1772
  }
1408
1773
  }
1409
1774
  else if (exact) {
@@ -1435,61 +1800,69 @@ injdef) {
1435
1800
  const extra = injdef?.extra;
1436
1801
  const collect = null != injdef?.errs;
1437
1802
  const errs = injdef?.errs || [];
1438
- const store = {
1439
- // Remove the transform commands.
1440
- $DELETE: null,
1441
- $COPY: null,
1442
- $KEY: null,
1443
- $META: null,
1444
- $MERGE: null,
1445
- $EACH: null,
1446
- $PACK: null,
1447
- $STRING: validate_STRING,
1448
- $NUMBER: validate_TYPE,
1449
- $BOOLEAN: validate_TYPE,
1450
- $OBJECT: validate_TYPE,
1451
- $ARRAY: validate_TYPE,
1452
- $FUNCTION: validate_TYPE,
1453
- $INSTANCE: validate_TYPE,
1454
- $ANY: validate_ANY,
1455
- $CHILD: validate_CHILD,
1456
- $ONE: validate_ONE,
1457
- $EXACT: validate_EXACT,
1458
- ...(extra || {}),
1803
+ const store = merge([
1804
+ {
1805
+ // Remove the transform commands.
1806
+ $DELETE: null,
1807
+ $COPY: null,
1808
+ $KEY: null,
1809
+ $META: null,
1810
+ $MERGE: null,
1811
+ $EACH: null,
1812
+ $PACK: null,
1813
+ $STRING: validate_STRING,
1814
+ $NUMBER: validate_TYPE,
1815
+ $INTEGER: validate_TYPE,
1816
+ $DECIMAL: validate_TYPE,
1817
+ $BOOLEAN: validate_TYPE,
1818
+ $NULL: validate_TYPE,
1819
+ $NIL: validate_TYPE,
1820
+ $MAP: validate_TYPE,
1821
+ $LIST: validate_TYPE,
1822
+ $FUNCTION: validate_TYPE,
1823
+ $INSTANCE: validate_TYPE,
1824
+ $ANY: validate_ANY,
1825
+ $CHILD: validate_CHILD,
1826
+ $ONE: validate_ONE,
1827
+ $EXACT: validate_EXACT,
1828
+ },
1829
+ getdef(extra, {}),
1459
1830
  // A special top level value to collect errors.
1460
- // NOTE: collecterrs paramter always wins.
1461
- $ERRS: errs,
1462
- };
1831
+ // NOTE: collecterrs parameter always wins.
1832
+ {
1833
+ $ERRS: errs,
1834
+ }
1835
+ ], 1);
1463
1836
  let meta = getprop(injdef, 'meta', {});
1464
1837
  setprop(meta, S_BEXACT, getprop(meta, S_BEXACT, false));
1465
1838
  const out = transform(data, spec, {
1466
1839
  meta,
1467
1840
  extra: store,
1468
1841
  modify: _validation,
1469
- handler: _validatehandler
1842
+ handler: _validatehandler,
1843
+ errs,
1470
1844
  });
1471
- const generr = (0 < errs.length && !collect);
1845
+ const generr = (0 < size(errs) && !collect);
1472
1846
  if (generr) {
1473
- throw new Error('Invalid data: ' + errs.join(' | '));
1847
+ throw new Error(join(errs, ' | '));
1474
1848
  }
1475
1849
  return out;
1476
1850
  }
1477
1851
  const select_AND = (inj, _val, _ref, store) => {
1478
- if (S_MKEYPRE === inj.mode) {
1852
+ if (M_KEYPRE === inj.mode) {
1479
1853
  const terms = getprop(inj.parent, inj.key);
1480
1854
  const ppath = slice(inj.path, -1);
1481
1855
  const point = getpath(store, ppath);
1482
- const vstore = { ...store };
1856
+ const vstore = merge([{}, store], 1);
1483
1857
  vstore.$TOP = point;
1484
1858
  for (let term of terms) {
1485
- // setprop(term, '`$OPEN`', getprop(term, '`$OPEN`', true))
1486
1859
  let terrs = [];
1487
1860
  validate(point, term, {
1488
1861
  extra: vstore,
1489
1862
  errs: terrs,
1490
1863
  meta: inj.meta,
1491
1864
  });
1492
- if (0 != terrs.length) {
1865
+ if (0 != size(terrs)) {
1493
1866
  inj.errs.push('AND:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(terms));
1494
1867
  }
1495
1868
  }
@@ -1499,11 +1872,11 @@ const select_AND = (inj, _val, _ref, store) => {
1499
1872
  }
1500
1873
  };
1501
1874
  const select_OR = (inj, _val, _ref, store) => {
1502
- if (S_MKEYPRE === inj.mode) {
1875
+ if (M_KEYPRE === inj.mode) {
1503
1876
  const terms = getprop(inj.parent, inj.key);
1504
1877
  const ppath = slice(inj.path, -1);
1505
1878
  const point = getpath(store, ppath);
1506
- const vstore = { ...store };
1879
+ const vstore = merge([{}, store], 1);
1507
1880
  vstore.$TOP = point;
1508
1881
  for (let term of terms) {
1509
1882
  let terrs = [];
@@ -1512,7 +1885,7 @@ const select_OR = (inj, _val, _ref, store) => {
1512
1885
  errs: terrs,
1513
1886
  meta: inj.meta,
1514
1887
  });
1515
- if (0 === terrs.length) {
1888
+ if (0 === size(terrs)) {
1516
1889
  const gkey = getelem(inj.path, -2);
1517
1890
  const gp = getelem(inj.nodes, -2);
1518
1891
  setprop(gp, gkey, point);
@@ -1523,11 +1896,11 @@ const select_OR = (inj, _val, _ref, store) => {
1523
1896
  }
1524
1897
  };
1525
1898
  const select_NOT = (inj, _val, _ref, store) => {
1526
- if (S_MKEYPRE === inj.mode) {
1899
+ if (M_KEYPRE === inj.mode) {
1527
1900
  const term = getprop(inj.parent, inj.key);
1528
1901
  const ppath = slice(inj.path, -1);
1529
1902
  const point = getpath(store, ppath);
1530
- const vstore = { ...store };
1903
+ const vstore = merge([{}, store], 1);
1531
1904
  vstore.$TOP = point;
1532
1905
  let terrs = [];
1533
1906
  validate(point, term, {
@@ -1535,7 +1908,7 @@ const select_NOT = (inj, _val, _ref, store) => {
1535
1908
  errs: terrs,
1536
1909
  meta: inj.meta,
1537
1910
  });
1538
- if (0 == terrs.length) {
1911
+ if (0 == size(terrs)) {
1539
1912
  inj.errs.push('NOT:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(term));
1540
1913
  }
1541
1914
  const gkey = getelem(inj.path, -2);
@@ -1544,7 +1917,7 @@ const select_NOT = (inj, _val, _ref, store) => {
1544
1917
  }
1545
1918
  };
1546
1919
  const select_CMP = (inj, _val, ref, store) => {
1547
- if (S_MKEYPRE === inj.mode) {
1920
+ if (M_KEYPRE === inj.mode) {
1548
1921
  const term = getprop(inj.parent, inj.key);
1549
1922
  // const src = getprop(store, inj.base, store)
1550
1923
  const gkey = getelem(inj.path, -2);
@@ -1577,7 +1950,7 @@ const select_CMP = (inj, _val, ref, store) => {
1577
1950
  ' fail:' + ref + ' ' + stringify(term));
1578
1951
  }
1579
1952
  }
1580
- return UNDEF;
1953
+ return NONE;
1581
1954
  };
1582
1955
  // Select children from a top-level object that match a MongoDB-style query.
1583
1956
  // Supports $and, $or, and equality comparisons.
@@ -1588,10 +1961,13 @@ function select(children, query) {
1588
1961
  return [];
1589
1962
  }
1590
1963
  if (ismap(children)) {
1591
- children = items(children).map(n => (n[1][S_DKEY] = n[0], n[1]));
1964
+ children = items(children, n => {
1965
+ setprop(n[1], S_DKEY, n[0]);
1966
+ return n[1];
1967
+ });
1592
1968
  }
1593
1969
  else {
1594
- children = children.map((n, i) => ((ismap(n) ? n[S_DKEY] = i : null), n));
1970
+ children = items(children, (n) => (setprop(n[1], S_DKEY, +n[0]), n[1]));
1595
1971
  }
1596
1972
  const results = [];
1597
1973
  const injdef = {
@@ -1630,9 +2006,9 @@ class Injection {
1630
2006
  this.val = val;
1631
2007
  this.parent = parent;
1632
2008
  this.errs = [];
1633
- this.dparent = UNDEF;
2009
+ this.dparent = NONE;
1634
2010
  this.dpath = [S_DTOP];
1635
- this.mode = S_MVAL;
2011
+ this.mode = M_VAL;
1636
2012
  this.full = false;
1637
2013
  this.keyI = 0;
1638
2014
  this.keys = [S_DTOP];
@@ -1646,7 +2022,7 @@ class Injection {
1646
2022
  toString(prefix) {
1647
2023
  return 'INJ' + (null == prefix ? '' : S_FS + prefix) + S_CN +
1648
2024
  pad(pathify(this.path, 1)) +
1649
- this.mode + (this.full ? '/full' : '') + S_CN +
2025
+ MODENAME[this.mode] + (this.full ? '/full' : '') + S_CN +
1650
2026
  'key=' + this.keyI + S_FS + this.key + S_FS + S_OS + this.keys + S_CS +
1651
2027
  ' p=' + stringify(this.parent, -1, 1) +
1652
2028
  ' m=' + stringify(this.meta, -1, 1) +
@@ -1657,11 +2033,11 @@ class Injection {
1657
2033
  this.meta.__d++;
1658
2034
  const parentkey = getelem(this.path, -2);
1659
2035
  // Resolve current node in store for local paths.
1660
- if (UNDEF === this.dparent) {
2036
+ if (NONE === this.dparent) {
1661
2037
  // Even if there's no data, dpath should continue to match path, so that
1662
2038
  // relative paths work properly.
1663
- if (1 < this.dpath.length) {
1664
- this.dpath = [...this.dpath, parentkey];
2039
+ if (1 < size(this.dpath)) {
2040
+ this.dpath = flatten([this.dpath, parentkey]);
1665
2041
  }
1666
2042
  }
1667
2043
  else {
@@ -1673,7 +2049,7 @@ class Injection {
1673
2049
  this.dpath = slice(this.dpath, -1);
1674
2050
  }
1675
2051
  else {
1676
- this.dpath = [...this.dpath, parentkey];
2052
+ this.dpath = flatten([this.dpath, parentkey]);
1677
2053
  }
1678
2054
  }
1679
2055
  }
@@ -1687,8 +2063,8 @@ class Injection {
1687
2063
  cinj.keyI = keyI;
1688
2064
  cinj.keys = keys;
1689
2065
  cinj.key = key;
1690
- cinj.path = [...(this.path || []), key];
1691
- cinj.nodes = [...(this.nodes || []), val];
2066
+ cinj.path = flatten([getdef(this.path, []), key]);
2067
+ cinj.nodes = flatten([getdef(this.nodes, []), [val]]);
1692
2068
  cinj.mode = this.mode;
1693
2069
  cinj.handler = this.handler;
1694
2070
  cinj.modify = this.modify;
@@ -1696,39 +2072,42 @@ class Injection {
1696
2072
  cinj.meta = this.meta;
1697
2073
  cinj.errs = this.errs;
1698
2074
  cinj.prior = this;
1699
- cinj.dpath = [...this.dpath];
2075
+ cinj.dpath = flatten([this.dpath]);
1700
2076
  cinj.dparent = this.dparent;
1701
2077
  return cinj;
1702
2078
  }
1703
2079
  setval(val, ancestor) {
2080
+ let parent = NONE;
1704
2081
  if (null == ancestor || ancestor < 2) {
1705
- return UNDEF === val ?
1706
- delprop(this.parent, this.key) :
2082
+ parent = NONE === val ?
2083
+ this.parent = delprop(this.parent, this.key) :
1707
2084
  setprop(this.parent, this.key, val);
1708
2085
  }
1709
2086
  else {
1710
2087
  const aval = getelem(this.nodes, 0 - ancestor);
1711
2088
  const akey = getelem(this.path, 0 - ancestor);
1712
- return UNDEF === val ?
2089
+ parent = NONE === val ?
1713
2090
  delprop(aval, akey) :
1714
2091
  setprop(aval, akey, val);
1715
2092
  }
2093
+ // console.log('SETVAL', val, this.key, this.parent)
2094
+ return parent;
1716
2095
  }
1717
2096
  }
1718
2097
  // Internal utilities
1719
2098
  // ==================
1720
- // Update all references to target in inj.nodes.
1721
- function _updateAncestors(_inj, target, tkey, tval) {
1722
- // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
1723
- setprop(target, tkey, tval);
1724
- }
2099
+ // // Update all references to target in inj.nodes.
2100
+ // function _updateAncestors(_inj: Injection, target: any, tkey: any, tval: any) {
2101
+ // // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
2102
+ // setprop(target, tkey, tval)
2103
+ // }
1725
2104
  // Build a type validation error message.
1726
2105
  function _invalidTypeMsg(path, needtype, vt, v, _whence) {
1727
2106
  let vs = null == v ? 'no value' : stringify(v);
1728
2107
  return 'Expected ' +
1729
- (1 < path.length ? ('field ' + pathify(path, 1) + ' to be ') : '') +
2108
+ (1 < size(path) ? ('field ' + pathify(path, 1) + ' to be ') : '') +
1730
2109
  needtype + ', but found ' +
1731
- (null != v ? vt + S_VIZ : '') + vs +
2110
+ (null != v ? typename(vt) + S_VIZ : '') + vs +
1732
2111
  // Uncomment to help debug validation errors.
1733
2112
  // ' [' + _whence + ']' +
1734
2113
  '.';
@@ -1737,14 +2116,14 @@ function _invalidTypeMsg(path, needtype, vt, v, _whence) {
1737
2116
  // call the function passing the injection inj. This is how transforms operate.
1738
2117
  const _injecthandler = (inj, val, ref, store) => {
1739
2118
  let out = val;
1740
- const iscmd = isfunc(val) && (UNDEF === ref || ref.startsWith(S_DS));
2119
+ const iscmd = isfunc(val) && (NONE === ref || ref.startsWith(S_DS));
1741
2120
  // Only call val function if it is a special command ($NAME format).
1742
2121
  // TODO: OR if meta.'$CALL'
1743
2122
  if (iscmd) {
1744
2123
  out = val(inj, val, ref, store);
1745
2124
  }
1746
2125
  // Update parent with value. Ensures references remain in node tree.
1747
- else if (S_MVAL === inj.mode && inj.full) {
2126
+ else if (M_VAL === inj.mode && inj.full) {
1748
2127
  inj.setval(val);
1749
2128
  }
1750
2129
  return out;
@@ -1792,9 +2171,9 @@ function _injectstr(val, store, inj) {
1792
2171
  }
1793
2172
  let pathref = m[1];
1794
2173
  // Special escapes inside injection.
1795
- pathref = 3 < pathref.length ?
1796
- pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS) :
1797
- pathref;
2174
+ if (3 < size(pathref)) {
2175
+ pathref = pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS);
2176
+ }
1798
2177
  // Get the extracted path reference.
1799
2178
  out = getpath(store, pathref, inj);
1800
2179
  }
@@ -1802,13 +2181,15 @@ function _injectstr(val, store, inj) {
1802
2181
  // Check for injections within the string.
1803
2182
  const partial = (_m, ref) => {
1804
2183
  // Special escapes inside injection.
1805
- ref = 3 < ref.length ? ref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS) : ref;
2184
+ if (3 < size(ref)) {
2185
+ ref = ref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS);
2186
+ }
1806
2187
  if (inj) {
1807
2188
  inj.full = false;
1808
2189
  }
1809
2190
  const found = getpath(store, ref, inj);
1810
2191
  // Ensure inject value is a string.
1811
- return UNDEF === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found);
2192
+ return NONE === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found);
1812
2193
  };
1813
2194
  out = val.replace(R_INJECTION_PARTIAL, partial);
1814
2195
  // Also call the inj handler on the entire string, providing the
@@ -1820,12 +2201,82 @@ function _injectstr(val, store, inj) {
1820
2201
  }
1821
2202
  return out;
1822
2203
  }
2204
+ // Handler Utilities
2205
+ // =================
2206
+ const MODENAME = {
2207
+ [M_VAL]: 'val',
2208
+ [M_KEYPRE]: 'key:pre',
2209
+ [M_KEYPOST]: 'key:post',
2210
+ };
2211
+ exports.MODENAME = MODENAME;
2212
+ const PLACEMENT = {
2213
+ [M_VAL]: 'value',
2214
+ [M_KEYPRE]: S_key,
2215
+ [M_KEYPOST]: S_key,
2216
+ };
2217
+ function checkPlacement(modes, ijname, parentTypes, inj) {
2218
+ if (0 === (modes & inj.mode)) {
2219
+ inj.errs.push('$' + ijname + ': invalid placement as ' + PLACEMENT[inj.mode] +
2220
+ ', expected: ' + join(items([M_KEYPRE, M_KEYPOST, M_VAL].filter(m => modes & m), (n) => PLACEMENT[n[1]]), ',') + '.');
2221
+ return false;
2222
+ }
2223
+ if (!isempty(parentTypes)) {
2224
+ const ptype = typify(inj.parent);
2225
+ if (0 === (parentTypes & ptype)) {
2226
+ inj.errs.push('$' + ijname + ': invalid placement in parent ' + typename(ptype) +
2227
+ ', expected: ' + typename(parentTypes) + '.');
2228
+ return false;
2229
+ }
2230
+ }
2231
+ return true;
2232
+ }
2233
+ // function injectorArgs(argTypes: number[], inj: Injection): any {
2234
+ function injectorArgs(argTypes, args) {
2235
+ const numargs = size(argTypes);
2236
+ const found = new Array(1 + numargs);
2237
+ found[0] = NONE;
2238
+ for (let argI = 0; argI < numargs; argI++) {
2239
+ // const arg = inj.parent[1 + argI]
2240
+ const arg = args[argI];
2241
+ const argType = typify(arg);
2242
+ if (0 === (argTypes[argI] & argType)) {
2243
+ found[0] = 'invalid argument: ' + stringify(arg, 22) +
2244
+ ' (' + typename(argType) + ' at position ' + (1 + argI) +
2245
+ ') is not of type: ' + typename(argTypes[argI]) + '.';
2246
+ break;
2247
+ }
2248
+ found[1 + argI] = arg;
2249
+ }
2250
+ return found;
2251
+ }
2252
+ function injectChild(child, store, inj) {
2253
+ let cinj = inj;
2254
+ // Replace ['`$FORMAT`',...] with child
2255
+ if (null != inj.prior) {
2256
+ if (null != inj.prior.prior) {
2257
+ cinj = inj.prior.prior.child(inj.prior.keyI, inj.prior.keys);
2258
+ cinj.val = child;
2259
+ setprop(cinj.parent, inj.prior.key, child);
2260
+ }
2261
+ else {
2262
+ cinj = inj.prior.child(inj.keyI, inj.keys);
2263
+ cinj.val = child;
2264
+ setprop(cinj.parent, inj.key, child);
2265
+ }
2266
+ }
2267
+ // console.log('FORMAT-INJECT-CHILD', child)
2268
+ inject(child, store, cinj);
2269
+ return cinj;
2270
+ }
1823
2271
  class StructUtility {
1824
2272
  constructor() {
1825
2273
  this.clone = clone;
1826
2274
  this.delprop = delprop;
1827
2275
  this.escre = escre;
1828
2276
  this.escurl = escurl;
2277
+ this.filter = filter;
2278
+ this.flatten = flatten;
2279
+ this.getdef = getdef;
1829
2280
  this.getelem = getelem;
1830
2281
  this.getpath = getpath;
1831
2282
  this.getprop = getprop;
@@ -1838,13 +2289,14 @@ class StructUtility {
1838
2289
  this.ismap = ismap;
1839
2290
  this.isnode = isnode;
1840
2291
  this.items = items;
1841
- this.joinurl = joinurl;
2292
+ this.join = join;
1842
2293
  this.jsonify = jsonify;
1843
2294
  this.keysof = keysof;
1844
2295
  this.merge = merge;
1845
2296
  this.pad = pad;
1846
2297
  this.pathify = pathify;
1847
2298
  this.select = select;
2299
+ this.setpath = setpath;
1848
2300
  this.setprop = setprop;
1849
2301
  this.size = size;
1850
2302
  this.slice = slice;
@@ -1852,10 +2304,32 @@ class StructUtility {
1852
2304
  this.stringify = stringify;
1853
2305
  this.transform = transform;
1854
2306
  this.typify = typify;
2307
+ this.typename = typename;
1855
2308
  this.validate = validate;
1856
2309
  this.walk = walk;
1857
- this.jo = jo;
1858
- this.ja = ja;
2310
+ this.SKIP = SKIP;
2311
+ this.DELETE = DELETE;
2312
+ this.jm = jm;
2313
+ this.jt = jt;
2314
+ this.tn = typename;
2315
+ this.T_any = T_any;
2316
+ this.T_noval = T_noval;
2317
+ this.T_boolean = T_boolean;
2318
+ this.T_decimal = T_decimal;
2319
+ this.T_integer = T_integer;
2320
+ this.T_number = T_number;
2321
+ this.T_string = T_string;
2322
+ this.T_function = T_function;
2323
+ this.T_symbol = T_symbol;
2324
+ this.T_null = T_null;
2325
+ this.T_list = T_list;
2326
+ this.T_map = T_map;
2327
+ this.T_instance = T_instance;
2328
+ this.T_scalar = T_scalar;
2329
+ this.T_node = T_node;
2330
+ this.checkPlacement = checkPlacement;
2331
+ this.injectorArgs = injectorArgs;
2332
+ this.injectChild = injectChild;
1859
2333
  }
1860
2334
  }
1861
2335
  exports.StructUtility = StructUtility;