@voxgig/struct 0.0.9 → 0.1.0

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.1.0
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;
369
+ }
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
+ }
384
+ }
385
+ else if (S_string === typestr) {
386
+ return T_scalar | T_string;
387
+ }
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;
268
393
  }
269
- const type = typeof value;
270
- if (S_number === type && isNaN(value)) {
271
- return S_null;
394
+ // For languages that have symbolic atoms.
395
+ else if (S_symbol === typestr) {
396
+ return T_scalar | T_symbol;
272
397
  }
273
- if (Array.isArray(value)) {
274
- return S_array;
398
+ else if (Array.isArray(value)) {
399
+ return T_node | T_list;
275
400
  }
276
- if (type === 'object') {
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 {
@@ -575,6 +768,11 @@ function setprop(parent, key, val) {
575
768
  return parent;
576
769
  }
577
770
  // Walk a data structure depth first, applying a function to each value.
771
+ // The `path` argument passed to the before/after callbacks is a single
772
+ // mutable array per depth, shared across all callback invocations for the
773
+ // lifetime of this top-level walk call. Callbacks that need to store the
774
+ // path MUST clone it (e.g. `path.slice()`); the contents will otherwise
775
+ // be overwritten by subsequent visits.
578
776
  function walk(
579
777
  // These arguments are the public interface.
580
778
  val,
@@ -585,18 +783,38 @@ after,
585
783
  // Maximum recursive depth, default: 32. Use null for infinite depth.
586
784
  maxdepth,
587
785
  // These areguments are used for recursive state.
588
- key, parent, path) {
589
- let out = null == before ? val : before(key, val, parent, path || []);
590
- maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : 32;
591
- if (0 === maxdepth || (null != path && 0 < maxdepth && maxdepth <= path.length)) {
786
+ key, parent, path, pool) {
787
+ if (NONE === pool) {
788
+ pool = [[]];
789
+ }
790
+ if (NONE === path) {
791
+ path = pool[0];
792
+ }
793
+ const depth = path.length;
794
+ let out = null == before ? val : before(key, val, parent, path);
795
+ maxdepth = null != maxdepth && 0 <= maxdepth ? maxdepth : MAXDEPTH;
796
+ if (0 === maxdepth || (0 < maxdepth && maxdepth <= depth)) {
592
797
  return out;
593
798
  }
594
799
  if (isnode(out)) {
800
+ const childDepth = depth + 1;
801
+ let childPath = pool[childDepth];
802
+ if (NONE === childPath) {
803
+ childPath = new Array(childDepth);
804
+ pool[childDepth] = childPath;
805
+ }
806
+ // Sync prefix [0..depth-1] from the current path. Only needed once per
807
+ // parent: siblings share the same prefix and will each overwrite slot
808
+ // [depth] below.
809
+ for (let i = 0; i < depth; i++) {
810
+ childPath[i] = path[i];
811
+ }
595
812
  for (let [ckey, child] of items(out)) {
596
- setprop(out, ckey, walk(child, before, after, maxdepth, ckey, out, [...(path || []), S_MT + ckey]));
813
+ childPath[depth] = S_MT + ckey;
814
+ setprop(out, ckey, walk(child, before, after, maxdepth, ckey, out, childPath, pool));
597
815
  }
598
816
  }
599
- out = null == after ? out : after(key, out, parent, path || []);
817
+ out = null == after ? out : after(key, out, parent, path);
600
818
  return out;
601
819
  }
602
820
  // Merge a list of values into each other. Later values have
@@ -604,7 +822,9 @@ key, parent, path) {
604
822
  // override each other, and do *not* merge. The first element is
605
823
  // modified.
606
824
  function merge(val, maxdepth) {
607
- let out = UNDEF;
825
+ // const md: number = null == maxdepth ? MAXDEPTH : maxdepth < 0 ? 0 : maxdepth
826
+ const md = slice(maxdepth ?? MAXDEPTH, 0);
827
+ let out = NONE;
608
828
  // Handle edge cases.
609
829
  if (!islist(val)) {
610
830
  return val;
@@ -612,7 +832,7 @@ function merge(val, maxdepth) {
612
832
  const list = val;
613
833
  const lenlist = list.length;
614
834
  if (0 === lenlist) {
615
- return UNDEF;
835
+ return NONE;
616
836
  }
617
837
  else if (1 === lenlist) {
618
838
  return list[0];
@@ -632,8 +852,11 @@ function merge(val, maxdepth) {
632
852
  let dst = [out];
633
853
  function before(key, val, _parent, path) {
634
854
  const pI = size(path);
855
+ if (md <= pI) {
856
+ setprop(cur[pI - 1], key, val);
857
+ }
635
858
  // Scalars just override directly.
636
- if (!isnode(val)) {
859
+ else if (!isnode(val)) {
637
860
  cur[pI] = val;
638
861
  }
639
862
  // Descend into override node - Set up correct target in `after` function.
@@ -642,7 +865,7 @@ function merge(val, maxdepth) {
642
865
  dst[pI] = 0 < pI ? getprop(dst[pI - 1], key) : dst[pI];
643
866
  const tval = dst[pI];
644
867
  // Destination empty, so create node (unless override is class instance).
645
- if (UNDEF === tval && S_instance !== typify(val)) {
868
+ if (NONE === tval && 0 === (T_instance & typify(val))) {
646
869
  cur[pI] = islist(val) ? [] : {};
647
870
  }
648
871
  // Matching override and destination so continue with their values.
@@ -653,7 +876,7 @@ function merge(val, maxdepth) {
653
876
  else {
654
877
  cur[pI] = val;
655
878
  // No need to descend when override wins (destination is discarded).
656
- val = UNDEF;
879
+ val = NONE;
657
880
  }
658
881
  }
659
882
  // console.log('BEFORE-END', pathify(path), '@', pI, key,
@@ -665,24 +888,59 @@ function merge(val, maxdepth) {
665
888
  const cI = size(path);
666
889
  const target = cur[cI - 1];
667
890
  const value = cur[cI];
668
- // console.log('AFTER-PREP', pathify(path), '@', cI,
891
+ // console.log('AFTER-PREP', pathify(path), '@', cI, cur, '|',
669
892
  // stringify(key, -1, 1), stringify(value, -1, 1), 'T=', stringify(target, -1, 1))
670
893
  setprop(target, key, value);
671
894
  return value;
672
895
  }
673
896
  // Walk overriding node, creating paths in output as needed.
674
897
  out = walk(obj, before, after, maxdepth);
898
+ // console.log('WALK-DONE', out, obj)
675
899
  }
676
900
  }
901
+ if (0 === md) {
902
+ out = getelem(list, -1);
903
+ out = islist(out) ? [] : ismap(out) ? {} : out;
904
+ }
677
905
  return out;
678
906
  }
907
+ // Set a value using a path. Missing path parts are created.
908
+ // String paths create only maps. Use a string list to create list parts.
909
+ function setpath(store, path, val, injdef) {
910
+ const pathType = typify(path);
911
+ const parts = 0 < (T_list & pathType) ? path :
912
+ 0 < (T_string & pathType) ? path.split(S_DT) :
913
+ 0 < (T_number & pathType) ? [path] : NONE;
914
+ if (NONE === parts) {
915
+ return NONE;
916
+ }
917
+ const base = getprop(injdef, S_base);
918
+ const numparts = size(parts);
919
+ let parent = getprop(store, base, store);
920
+ for (let pI = 0; pI < numparts - 1; pI++) {
921
+ const partKey = getelem(parts, pI);
922
+ let nextParent = getprop(parent, partKey);
923
+ if (!isnode(nextParent)) {
924
+ nextParent = 0 < (T_number & typify(getelem(parts, pI + 1))) ? [] : {};
925
+ setprop(parent, partKey, nextParent);
926
+ }
927
+ parent = nextParent;
928
+ }
929
+ if (DELETE === val) {
930
+ delprop(parent, getelem(parts, -1));
931
+ }
932
+ else {
933
+ setprop(parent, getelem(parts, -1), val);
934
+ }
935
+ return parent;
936
+ }
679
937
  function getpath(store, path, injdef) {
680
938
  // Operate on a string array.
681
939
  const parts = islist(path) ? path :
682
940
  'string' === typeof path ? path.split(S_DT) :
683
- 'number' === typeof path ? [strkey(path)] : UNDEF;
684
- if (UNDEF === parts) {
685
- return UNDEF;
941
+ 'number' === typeof path ? [strkey(path)] : NONE;
942
+ if (NONE === parts) {
943
+ return NONE;
686
944
  }
687
945
  // let root = store
688
946
  let val = store;
@@ -707,22 +965,22 @@ function getpath(store, path, injdef) {
707
965
  parts[0] = m[3];
708
966
  }
709
967
  const dpath = getprop(injdef, 'dpath');
710
- for (let pI = 0; UNDEF !== val && pI < parts.length; pI++) {
968
+ for (let pI = 0; NONE !== val && pI < numparts; pI++) {
711
969
  let part = parts[pI];
712
970
  if (injdef && S_DKEY === part) {
713
971
  part = getprop(injdef, S_key);
714
972
  }
715
973
  else if (injdef && part.startsWith('$GET:')) {
716
974
  // $GET:path$ -> get store value, use as path part (string)
717
- part = stringify(getpath(src, part.substring(5, part.length - 1)));
975
+ part = stringify(getpath(src, slice(part, 5, -1)));
718
976
  }
719
977
  else if (injdef && part.startsWith('$REF:')) {
720
978
  // $REF:refpath$ -> get spec value, use as path part (string)
721
- part = stringify(getpath(getprop(store, S_DSPEC), part.substring(5, part.length - 1)));
979
+ part = stringify(getpath(getprop(store, S_DSPEC), slice(part, 5, -1)));
722
980
  }
723
981
  else if (injdef && part.startsWith('$META:')) {
724
982
  // $META:metapath$ -> get meta value, use as path part (string)
725
- part = stringify(getpath(getprop(injdef, 'meta'), part.substring(6, part.length - 1)));
983
+ part = stringify(getpath(getprop(injdef, 'meta'), slice(part, 6, -1)));
726
984
  }
727
985
  // $$ escapes $
728
986
  part = part.replace(R_DOUBLE_DOLLAR, '$');
@@ -740,12 +998,13 @@ function getpath(store, path, injdef) {
740
998
  val = dparent;
741
999
  }
742
1000
  else {
743
- const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1));
1001
+ // const fullpath = slice(dpath, 0 - ascends).concat(parts.slice(pI + 1))
1002
+ const fullpath = flatten([slice(dpath, 0 - ascends), parts.slice(pI + 1)]);
744
1003
  if (ascends <= size(dpath)) {
745
1004
  val = getpath(store, fullpath);
746
1005
  }
747
1006
  else {
748
- val = UNDEF;
1007
+ val = NONE;
749
1008
  }
750
1009
  break;
751
1010
  }
@@ -766,10 +1025,11 @@ function getpath(store, path, injdef) {
766
1025
  const ref = pathify(path);
767
1026
  val = handler(injdef, val, ref, store);
768
1027
  }
1028
+ // console.log('GETPATH', path, val)
769
1029
  return val;
770
1030
  }
771
1031
  // Inject values from a data store into a node recursively, resolving
772
- // paths against the store, or current if they are local. THe modify
1032
+ // paths against the store, or current if they are local. The modify
773
1033
  // argument allows custom modification of the result. The inj
774
1034
  // (Injection) argument is used to maintain recursive state.
775
1035
  function inject(val, store, injdef) {
@@ -777,13 +1037,13 @@ function inject(val, store, injdef) {
777
1037
  let inj = injdef;
778
1038
  // Create state if at root of injection. The input value is placed
779
1039
  // inside a virtual parent holder to simplify edge cases.
780
- if (UNDEF === injdef || null == injdef.mode) {
1040
+ if (NONE === injdef || null == injdef.mode) {
781
1041
  // Set up state assuming we are starting in the virtual parent.
782
1042
  inj = new Injection(val, { [S_DTOP]: val });
783
1043
  inj.dparent = store;
784
1044
  inj.errs = getprop(store, S_DERRS, []);
785
1045
  inj.meta.__d = 0;
786
- if (UNDEF !== injdef) {
1046
+ if (NONE !== injdef) {
787
1047
  inj.modify = null == injdef.modify ? inj.modify : injdef.modify;
788
1048
  inj.extra = null == injdef.extra ? inj.extra : injdef.extra;
789
1049
  inj.meta = null == injdef.meta ? inj.meta : injdef.meta;
@@ -791,33 +1051,42 @@ function inject(val, store, injdef) {
791
1051
  }
792
1052
  }
793
1053
  inj.descend();
1054
+ // console.log('INJ-START', val, inj.mode, inj.key, inj.val,
1055
+ // 't=', inj.path, 'P=', inj.parent, 'dp=', inj.dparent, 'ST=', store.$TOP)
794
1056
  // Descend into node.
795
1057
  if (isnode(val)) {
796
1058
  // Keys are sorted alphanumerically to ensure determinism.
797
1059
  // Injection transforms ($FOO) are processed *after* other keys.
798
1060
  // NOTE: the optional digits suffix of the transform can thus be
799
1061
  // 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);
1062
+ let nodekeys;
1063
+ nodekeys = keysof(val);
1064
+ if (ismap(val)) {
1065
+ nodekeys = flatten([
1066
+ filter(nodekeys, (n => !n[1].includes(S_DS))),
1067
+ filter(nodekeys, (n => n[1].includes(S_DS))),
1068
+ ]);
1069
+ }
1070
+ else {
1071
+ nodekeys = keysof(val);
1072
+ }
804
1073
  // 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.
1074
+ // 1. inj.mode=M_KEYPRE - Key string is injected, returning a possibly altered key.
1075
+ // 2. inj.mode=M_VAL - The child value is injected.
1076
+ // 3. inj.mode=M_KEYPOST - Key string is injected again, allowing child mutation.
808
1077
  for (let nkI = 0; nkI < nodekeys.length; nkI++) {
809
1078
  const childinj = inj.child(nkI, nodekeys);
810
1079
  const nodekey = childinj.key;
811
- childinj.mode = S_MKEYPRE;
1080
+ childinj.mode = M_KEYPRE;
812
1081
  // Peform the key:pre mode injection on the child key.
813
1082
  const prekey = _injectstr(nodekey, store, childinj);
814
1083
  // The injection may modify child processing.
815
1084
  nkI = childinj.keyI;
816
1085
  nodekeys = childinj.keys;
817
1086
  // Prevent further processing by returning an undefined prekey
818
- if (UNDEF !== prekey) {
1087
+ if (NONE !== prekey) {
819
1088
  childinj.val = getprop(val, prekey);
820
- childinj.mode = S_MVAL;
1089
+ childinj.mode = M_VAL;
821
1090
  // Perform the val mode injection on the child value.
822
1091
  // NOTE: return value is not used.
823
1092
  inject(childinj.val, store, childinj);
@@ -825,7 +1094,7 @@ function inject(val, store, injdef) {
825
1094
  nkI = childinj.keyI;
826
1095
  nodekeys = childinj.keys;
827
1096
  // Peform the key:post mode injection on the child key.
828
- childinj.mode = S_MKEYPOST;
1097
+ childinj.mode = M_KEYPOST;
829
1098
  _injectstr(nodekey, store, childinj);
830
1099
  // The injection may modify child processing.
831
1100
  nkI = childinj.keyI;
@@ -835,7 +1104,7 @@ function inject(val, store, injdef) {
835
1104
  }
836
1105
  // Inject paths into string scalars.
837
1106
  else if (S_string === valtype) {
838
- inj.mode = S_MVAL;
1107
+ inj.mode = M_VAL;
839
1108
  val = _injectstr(val, store, inj);
840
1109
  if (SKIP !== val) {
841
1110
  inj.setval(val);
@@ -848,6 +1117,7 @@ function inject(val, store, injdef) {
848
1117
  let mval = getprop(mparent, mkey);
849
1118
  inj.modify(mval, mkey, mparent, inj, store);
850
1119
  }
1120
+ // console.log('INJ-VAL', val)
851
1121
  inj.val = val;
852
1122
  // Original val reference may no longer be correct.
853
1123
  // This return value is only used as the top level result.
@@ -856,42 +1126,43 @@ function inject(val, store, injdef) {
856
1126
  // The transform_* functions are special command inject handlers (see Injector).
857
1127
  // Delete a key from a map or list.
858
1128
  const transform_DELETE = (inj) => {
859
- inj.setval(UNDEF);
860
- return UNDEF;
1129
+ inj.setval(NONE);
1130
+ return NONE;
861
1131
  };
862
1132
  // Copy value from source data.
863
1133
  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);
1134
+ const ijname = 'COPY';
1135
+ if (!checkPlacement(M_VAL, ijname, T_any, inj)) {
1136
+ return NONE;
869
1137
  }
1138
+ let out = getprop(inj.dparent, inj.key);
1139
+ inj.setval(out);
870
1140
  return out;
871
1141
  };
872
1142
  // As a value, inject the key of the parent node.
873
1143
  // As a key, defined the name of the key property in the source object.
874
1144
  const transform_KEY = (inj) => {
875
1145
  const { mode, path, parent } = inj;
876
- // Do nothing in val mode.
877
- if (S_MVAL !== mode) {
878
- return UNDEF;
1146
+ // Do nothing in val mode - not an error.
1147
+ if (M_VAL !== mode) {
1148
+ return NONE;
879
1149
  }
880
1150
  // Key is defined by $KEY meta property.
881
1151
  const keyspec = getprop(parent, S_BKEY);
882
- if (UNDEF !== keyspec) {
1152
+ if (NONE !== keyspec) {
883
1153
  delprop(parent, S_BKEY);
884
1154
  return getprop(inj.dparent, keyspec);
885
1155
  }
886
1156
  // Key is defined within general purpose $META object.
887
- return getprop(getprop(parent, S_BANNO), S_KEY, getprop(path, path.length - 2));
1157
+ // return getprop(getprop(parent, S_BANNO), S_KEY, getprop(path, path.length - 2))
1158
+ return getprop(getprop(parent, S_BANNO), S_KEY, getelem(path, -2));
888
1159
  };
889
- // Annotatea node. Does nothing itself, just used by
1160
+ // Annotate node. Does nothing itself, just used by
890
1161
  // other injectors, and is removed when called.
891
1162
  const transform_ANNO = (inj) => {
892
1163
  const { parent } = inj;
893
1164
  delprop(parent, S_BANNO);
894
- return UNDEF;
1165
+ return NONE;
895
1166
  };
896
1167
  // Merge a list of objects into the current object.
897
1168
  // Must be a key in an object. The value is merged over the current object.
@@ -901,70 +1172,70 @@ const transform_ANNO = (inj) => {
901
1172
  const transform_MERGE = (inj) => {
902
1173
  const { mode, key, parent } = inj;
903
1174
  // Ensures $MERGE is removed from parent list (val mode).
904
- let out = UNDEF;
905
- if (S_MKEYPRE === mode) {
1175
+ let out = NONE;
1176
+ if (M_KEYPRE === mode) {
906
1177
  out = key;
907
1178
  }
908
1179
  // Operate after child values have been transformed.
909
- else if (S_MKEYPOST === mode) {
1180
+ else if (M_KEYPOST === mode) {
910
1181
  out = key;
911
1182
  let args = getprop(parent, key);
912
1183
  args = Array.isArray(args) ? args : [args];
913
1184
  // Remove the $MERGE command from a parent map.
914
- inj.setval(UNDEF);
1185
+ inj.setval(NONE);
915
1186
  // Literals in the parent have precedence, but we still merge onto
916
1187
  // the parent object, so that node tree references are not changed.
917
- const mergelist = [parent, ...args, clone(parent)];
1188
+ const mergelist = flatten([[parent], args, [clone(parent)]]);
918
1189
  merge(mergelist);
919
- // return key
920
1190
  }
921
1191
  return out;
922
1192
  };
923
1193
  // Convert a node to a list.
924
1194
  // Format: ['`$EACH`', '`source-path-of-node`', child-template]
925
1195
  const transform_EACH = (inj, _val, _ref, store) => {
926
- // Remove arguments to avoid spurious processing.
927
- if (null != inj.keys) {
928
- inj.keys.length = 1;
929
- }
930
- if (S_MVAL !== inj.mode) {
931
- return UNDEF;
1196
+ const ijname = 'EACH';
1197
+ if (!checkPlacement(M_VAL, ijname, T_list, inj)) {
1198
+ return NONE;
1199
+ }
1200
+ // Remove remaining keys to avoid spurious processing.
1201
+ slice(inj.keys, 0, 1, true);
1202
+ // const [err, srcpath, child] = injectorArgs([T_string, T_any], inj)
1203
+ const [err, srcpath, child] = injectorArgs([T_string, T_any], slice(inj.parent, 1));
1204
+ if (NONE !== err) {
1205
+ inj.errs.push('$' + ijname + ': ' + err);
1206
+ return NONE;
932
1207
  }
933
- // Get arguments: ['`$EACH`', 'source-path', child-template].
934
- const srcpath = getprop(inj.parent, 1);
935
- const child = clone(getprop(inj.parent, 2));
936
1208
  // Source data.
937
1209
  const srcstore = getprop(store, inj.base, store);
938
1210
  const src = getpath(srcstore, srcpath, inj);
1211
+ const srctype = typify(src);
939
1212
  // Create parallel data structures:
940
1213
  // source entries :: child templates
941
1214
  let tcur = [];
942
1215
  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];
1216
+ const tkey = getelem(inj.path, -2);
1217
+ const target = getelem(inj.nodes, -2, () => getelem(inj.nodes, -1));
945
1218
  // Create clones of the child template for each value of the current soruce.
946
- if (islist(src)) {
947
- tval = src.map(() => clone(child));
1219
+ if (0 < (T_list & srctype)) {
1220
+ tval = items(src, () => clone(child));
948
1221
  }
949
- else if (ismap(src)) {
950
- tval = Object.entries(src).map(n => ({
951
- ...clone(child),
1222
+ else if (0 < (T_map & srctype)) {
1223
+ tval = items(src, (n => merge([
1224
+ clone(child),
952
1225
  // Make a note of the key for $KEY transforms.
953
- [S_BANNO]: { KEY: n[0] }
954
- }));
1226
+ { [S_BANNO]: { KEY: n[0] } }
1227
+ ], 1)));
955
1228
  }
956
1229
  let rval = [];
957
1230
  if (0 < size(tval)) {
958
- tcur = null == src ? UNDEF : Object.values(src);
1231
+ tcur = null == src ? NONE : items(src, (n) => n[1]);
959
1232
  const ckey = getelem(inj.path, -2);
960
1233
  const tpath = slice(inj.path, -1);
961
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey];
1234
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey]);
962
1235
  // Parent structure.
963
- // const ckey = getelem(cpath, -1)
964
1236
  tcur = { [ckey]: tcur };
965
- if (1 < tpath.length) {
1237
+ if (1 < size(tpath)) {
966
1238
  const pkey = getelem(inj.path, -3, S_DTOP);
967
- // const pkey = getelem(cpath, -2, S_DTOP)
968
1239
  tcur = { [pkey]: tcur };
969
1240
  dpath.push('$:' + pkey);
970
1241
  }
@@ -979,70 +1250,93 @@ const transform_EACH = (inj, _val, _ref, store) => {
979
1250
  inject(tval, store, tinj);
980
1251
  rval = tinj.val;
981
1252
  }
982
- _updateAncestors(inj, target, tkey, rval);
1253
+ // _updateAncestors(inj, target, tkey, rval)
1254
+ setprop(target, tkey, rval);
983
1255
  // Prevent callee from damaging first list entry (since we are in `val` mode).
984
1256
  return rval[0];
985
1257
  };
986
1258
  // Convert a node to a map.
987
- // Format: { '`$PACK`':['`source-path`', child-template]}
1259
+ // Format: { '`$PACK`':['source-path', child-template]}
988
1260
  const transform_PACK = (inj, _val, _ref, store) => {
989
1261
  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;
1262
+ const ijname = 'EACH';
1263
+ if (!checkPlacement(M_KEYPRE, ijname, T_map, inj)) {
1264
+ return NONE;
993
1265
  }
994
1266
  // Get arguments.
995
- const args = parent[key];
996
- const srcpath = args[0]; // Path to source data.
997
- const child = clone(args[1]); // Child template.
1267
+ const args = getprop(parent, key);
1268
+ const [err, srcpath, origchildspec] = injectorArgs([T_string, T_any], args);
1269
+ if (NONE !== err) {
1270
+ inj.errs.push('$' + ijname + ': ' + err);
1271
+ return NONE;
1272
+ }
998
1273
  // Find key and target node.
999
- const keyprop = child[S_BKEY];
1000
1274
  const tkey = getelem(path, -2);
1001
- const target = nodes[path.length - 2] || nodes[path.length - 1];
1275
+ const pathsize = size(path);
1276
+ const target = getelem(nodes, pathsize - 2, () => getelem(nodes, pathsize - 1));
1002
1277
  // Source data
1003
1278
  const srcstore = getprop(store, inj.base, store);
1004
1279
  let src = getpath(srcstore, srcpath, inj);
1005
1280
  // 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;
1281
+ if (!islist(src)) {
1282
+ if (ismap(src)) {
1283
+ src = items(src, (item) => {
1284
+ setprop(item[1], S_BANNO, { KEY: item[0] });
1285
+ return item[1];
1286
+ });
1287
+ }
1288
+ else {
1289
+ src = NONE;
1290
+ }
1291
+ }
1010
1292
  if (null == src) {
1011
- return UNDEF;
1293
+ return NONE;
1012
1294
  }
1013
- // Get key if specified.
1014
- let childkey = getprop(child, S_BKEY);
1015
- let keyname = UNDEF === childkey ? keyprop : childkey;
1016
- delprop(child, S_BKEY);
1295
+ // Get keypath.
1296
+ const keypath = getprop(origchildspec, S_BKEY);
1297
+ const childspec = delprop(origchildspec, S_BKEY);
1298
+ const child = getprop(childspec, S_BVAL, childspec);
1017
1299
  // Build parallel target object.
1018
1300
  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);
1301
+ items(src, (item) => {
1302
+ const srckey = item[0];
1303
+ const srcnode = item[1];
1304
+ let key = srckey;
1305
+ if (NONE !== keypath) {
1306
+ if (keypath.startsWith('`')) {
1307
+ key = inject(keypath, merge([{}, store, { $TOP: srcnode }], 1));
1308
+ }
1309
+ else {
1310
+ key = getpath(srcnode, keypath, inj);
1311
+ }
1312
+ }
1313
+ const tchild = clone(child);
1314
+ setprop(tval, key, tchild);
1315
+ const anno = getprop(srcnode, S_BANNO);
1316
+ if (NONE === anno) {
1317
+ delprop(tchild, S_BANNO);
1026
1318
  }
1027
1319
  else {
1028
- setprop(nchild, S_BANNO, mval);
1320
+ setprop(tchild, S_BANNO, anno);
1029
1321
  }
1030
- return a;
1031
- }, tval);
1322
+ });
1032
1323
  let rval = {};
1033
- if (0 < size(tval)) {
1324
+ if (!isempty(tval)) {
1034
1325
  // Build parallel source object.
1035
- let tcur = {};
1036
- src.reduce((a, n) => {
1037
- let kn = getprop(n, keyname);
1326
+ let tsrc = {};
1327
+ src.reduce((a, n, i) => {
1328
+ let kn = null == keypath ? i :
1329
+ keypath.startsWith('`') ?
1330
+ inject(keypath, merge([{}, store, { $TOP: n }], 1)) :
1331
+ getpath(n, keypath, inj);
1038
1332
  setprop(a, kn, n);
1039
1333
  return a;
1040
- }, tcur);
1334
+ }, tsrc);
1041
1335
  const tpath = slice(inj.path, -1);
1042
1336
  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) {
1337
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey]);
1338
+ let tcur = { [ckey]: tsrc };
1339
+ if (1 < size(tpath)) {
1046
1340
  const pkey = getelem(inj.path, -3, S_DTOP);
1047
1341
  tcur = { [pkey]: tcur };
1048
1342
  dpath.push('$:' + pkey);
@@ -1050,7 +1344,6 @@ const transform_PACK = (inj, _val, _ref, store) => {
1050
1344
  const tinj = inj.child(0, [ckey]);
1051
1345
  tinj.path = tpath;
1052
1346
  tinj.nodes = slice(inj.nodes, -1);
1053
- // tinj.parent = tcur
1054
1347
  tinj.parent = getelem(tinj.nodes, -1);
1055
1348
  tinj.val = tval;
1056
1349
  tinj.dpath = dpath;
@@ -1058,27 +1351,31 @@ const transform_PACK = (inj, _val, _ref, store) => {
1058
1351
  inject(tval, store, tinj);
1059
1352
  rval = tinj.val;
1060
1353
  }
1061
- _updateAncestors(inj, target, tkey, rval);
1354
+ // _updateAncestors(inj, target, tkey, rval)
1355
+ setprop(target, tkey, rval);
1062
1356
  // Drop transform key.
1063
- return UNDEF;
1357
+ return NONE;
1064
1358
  };
1065
- // TODO: not found ref should removed key (setprop UNDEF)
1359
+ // TODO: not found ref should removed key (setprop NONE)
1066
1360
  // Reference original spec (enables recursice transformations)
1067
1361
  // Format: ['`$REF`', '`spec-path`']
1068
1362
  const transform_REF = (inj, val, _ref, store) => {
1069
1363
  const { nodes } = inj;
1070
- if (S_MVAL !== inj.mode) {
1071
- return UNDEF;
1364
+ if (M_VAL !== inj.mode) {
1365
+ return NONE;
1072
1366
  }
1073
1367
  // Get arguments: ['`$REF`', 'ref-path'].
1074
1368
  const refpath = getprop(inj.parent, 1);
1075
- inj.keyI = inj.keys.length;
1369
+ inj.keyI = size(inj.keys);
1076
1370
  // Spec reference.
1077
1371
  const spec = getprop(store, S_DSPEC)();
1372
+ const dpath = slice(inj.path, 1);
1078
1373
  const ref = getpath(spec, refpath, {
1079
1374
  // TODO: test relative refs
1080
- dpath: inj.path.slice(1),
1081
- dparent: getpath(spec, inj.path.slice(1))
1375
+ // dpath: inj.path.slice(1),
1376
+ dpath,
1377
+ // dparent: getpath(spec, inj.path.slice(1))
1378
+ dparent: getpath(spec, dpath),
1082
1379
  });
1083
1380
  let hasSubRef = false;
1084
1381
  if (isnode(ref)) {
@@ -1094,20 +1391,20 @@ const transform_REF = (inj, val, _ref, store) => {
1094
1391
  const tpath = slice(inj.path, -1);
1095
1392
  let tcur = getpath(store, cpath);
1096
1393
  let tval = getpath(store, tpath);
1097
- let rval = UNDEF;
1098
- if (!hasSubRef || UNDEF !== tval) {
1394
+ let rval = NONE;
1395
+ if (!hasSubRef || NONE !== tval) {
1099
1396
  const tinj = inj.child(0, [getelem(tpath, -1)]);
1100
1397
  tinj.path = tpath;
1101
1398
  tinj.nodes = slice(inj.nodes, -1);
1102
1399
  tinj.parent = getelem(nodes, -2);
1103
1400
  tinj.val = tref;
1104
- tinj.dpath = [...cpath];
1401
+ tinj.dpath = flatten([cpath]);
1105
1402
  tinj.dparent = tcur;
1106
1403
  inject(tref, store, tinj);
1107
1404
  rval = tinj.val;
1108
1405
  }
1109
1406
  else {
1110
- rval = UNDEF;
1407
+ rval = NONE;
1111
1408
  }
1112
1409
  const grandparent = inj.setval(rval, 2);
1113
1410
  if (islist(grandparent) && inj.prior) {
@@ -1115,6 +1412,82 @@ const transform_REF = (inj, val, _ref, store) => {
1115
1412
  }
1116
1413
  return val;
1117
1414
  };
1415
+ const transform_FORMAT = (inj, _val, _ref, store) => {
1416
+ // console.log('FORMAT-START', inj, _val)
1417
+ // Remove remaining keys to avoid spurious processing.
1418
+ slice(inj.keys, 0, 1, true);
1419
+ if (M_VAL !== inj.mode) {
1420
+ return NONE;
1421
+ }
1422
+ // Get arguments: ['`$FORMAT`', 'name', child].
1423
+ // TODO: EACH and PACK should accept customm functions too
1424
+ const name = getprop(inj.parent, 1);
1425
+ const child = getprop(inj.parent, 2);
1426
+ // Source data.
1427
+ const tkey = getelem(inj.path, -2);
1428
+ const target = getelem(inj.nodes, -2, () => getelem(inj.nodes, -1));
1429
+ const cinj = injectChild(child, store, inj);
1430
+ const resolved = cinj.val;
1431
+ let formatter = 0 < (T_function & typify(name)) ? name : getprop(FORMATTER, name);
1432
+ if (NONE === formatter) {
1433
+ inj.errs.push('$FORMAT: unknown format: ' + name + '.');
1434
+ return NONE;
1435
+ }
1436
+ let out = walk(resolved, formatter);
1437
+ setprop(target, tkey, out);
1438
+ // _updateAncestors(inj, target, tkey, out)
1439
+ return out;
1440
+ };
1441
+ const FORMATTER = {
1442
+ identity: (_k, v) => v,
1443
+ upper: (_k, v) => isnode(v) ? v : ('' + v).toUpperCase(),
1444
+ lower: (_k, v) => isnode(v) ? v : ('' + v).toLowerCase(),
1445
+ string: (_k, v) => isnode(v) ? v : ('' + v),
1446
+ number: (_k, v) => {
1447
+ if (isnode(v)) {
1448
+ return v;
1449
+ }
1450
+ else {
1451
+ let n = Number(v);
1452
+ if (isNaN(n)) {
1453
+ n = 0;
1454
+ }
1455
+ return n;
1456
+ }
1457
+ },
1458
+ integer: (_k, v) => {
1459
+ if (isnode(v)) {
1460
+ return v;
1461
+ }
1462
+ else {
1463
+ let n = Number(v);
1464
+ if (isNaN(n)) {
1465
+ n = 0;
1466
+ }
1467
+ return n | 0;
1468
+ }
1469
+ },
1470
+ concat: (k, v) => null == k && islist(v) ? join(items(v, (n => isnode(n[1]) ? S_MT : (S_MT + n[1]))), S_MT) : v
1471
+ };
1472
+ const transform_APPLY = (inj, _val, _ref, store) => {
1473
+ const ijname = 'APPLY';
1474
+ if (!checkPlacement(M_VAL, ijname, T_list, inj)) {
1475
+ return NONE;
1476
+ }
1477
+ // const [err, apply, child] = injectorArgs([T_function, T_any], inj)
1478
+ const [err, apply, child] = injectorArgs([T_function, T_any], slice(inj.parent, 1));
1479
+ if (NONE !== err) {
1480
+ inj.errs.push('$' + ijname + ': ' + err);
1481
+ return NONE;
1482
+ }
1483
+ const tkey = getelem(inj.path, -2);
1484
+ const target = getelem(inj.nodes, -2, () => getelem(inj.nodes, -1));
1485
+ const cinj = injectChild(child, store, inj);
1486
+ const resolved = cinj.val;
1487
+ const out = apply(resolved, store, cinj);
1488
+ setprop(target, tkey, out);
1489
+ return out;
1490
+ };
1118
1491
  // Transform data using spec.
1119
1492
  // Only operates on static JSON-like data.
1120
1493
  // Arrays are treated as if they are objects with indices as keys.
@@ -1125,64 +1498,78 @@ injdef) {
1125
1498
  const origspec = spec;
1126
1499
  spec = clone(origspec);
1127
1500
  const extra = injdef?.extra;
1128
- // const modify = injdef?.modify
1501
+ const collect = null != injdef?.errs;
1502
+ const errs = injdef?.errs || [];
1129
1503
  const extraTransforms = {};
1130
- const extraData = null == extra ? UNDEF : items(extra)
1504
+ const extraData = null == extra ? NONE : items(extra)
1131
1505
  .reduce((a, n) => (n[0].startsWith(S_DS) ? extraTransforms[n[0]] = n[1] : (a[n[0]] = n[1]), a), {});
1132
1506
  const dataClone = merge([
1133
- isempty(extraData) ? UNDEF : clone(extraData),
1507
+ isempty(extraData) ? NONE : clone(extraData),
1134
1508
  clone(data),
1135
1509
  ]);
1136
1510
  // 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,
1511
+ const store = merge([
1512
+ {
1513
+ // The inject function recognises this special location for the root of the source data.
1514
+ // NOTE: to escape data that contains "`$FOO`" keys at the top level,
1515
+ // place that data inside a holding map: { myholder: mydata }.
1516
+ $TOP: dataClone,
1517
+ $SPEC: () => origspec,
1518
+ // Escape backtick (this also works inside backticks).
1519
+ $BT: () => S_BT,
1520
+ // Escape dollar sign (this also works inside backticks).
1521
+ $DS: () => S_DS,
1522
+ // Insert current date and time as an ISO string.
1523
+ $WHEN: () => new Date().toISOString(),
1524
+ $DELETE: transform_DELETE,
1525
+ $COPY: transform_COPY,
1526
+ $KEY: transform_KEY,
1527
+ $ANNO: transform_ANNO,
1528
+ $MERGE: transform_MERGE,
1529
+ $EACH: transform_EACH,
1530
+ $PACK: transform_PACK,
1531
+ $REF: transform_REF,
1532
+ $FORMAT: transform_FORMAT,
1533
+ $APPLY: transform_APPLY,
1534
+ },
1157
1535
  // Custom extra transforms, if any.
1158
- ...extraTransforms,
1159
- };
1536
+ extraTransforms,
1537
+ {
1538
+ $ERRS: errs,
1539
+ }
1540
+ ], 1);
1160
1541
  const out = inject(spec, store, injdef);
1542
+ const generr = (0 < size(errs) && !collect);
1543
+ if (generr) {
1544
+ throw new Error(join(errs, ' | '));
1545
+ }
1161
1546
  return out;
1162
1547
  }
1163
1548
  // A required string value. NOTE: Rejects empty strings.
1164
1549
  const validate_STRING = (inj) => {
1165
1550
  let out = getprop(inj.dparent, inj.key);
1166
1551
  const t = typify(out);
1167
- if (S_string !== t) {
1552
+ if (0 === (T_string & t)) {
1168
1553
  let msg = _invalidTypeMsg(inj.path, S_string, t, out, 'V1010');
1169
1554
  inj.errs.push(msg);
1170
- return UNDEF;
1555
+ return NONE;
1171
1556
  }
1172
1557
  if (S_MT === out) {
1173
1558
  let msg = 'Empty string at ' + pathify(inj.path, 1);
1174
1559
  inj.errs.push(msg);
1175
- return UNDEF;
1560
+ return NONE;
1176
1561
  }
1177
1562
  return out;
1178
1563
  };
1179
1564
  const validate_TYPE = (inj, _val, ref) => {
1180
- let tname = slice(ref, 1).toLowerCase();
1565
+ const tname = slice(ref, 1).toLowerCase();
1566
+ const typev = 1 << (31 - TYPENAME.indexOf(tname));
1181
1567
  let out = getprop(inj.dparent, inj.key);
1182
1568
  const t = typify(out);
1183
- if (t !== tname) {
1569
+ // console.log('TYPE', tname, typev, tn(typev), 'O=', t, tn(t), out, 'C=', t & typev)
1570
+ if (0 === (t & typev)) {
1184
1571
  inj.errs.push(_invalidTypeMsg(inj.path, tname, t, out, 'V1001'));
1185
- return UNDEF;
1572
+ return NONE;
1186
1573
  }
1187
1574
  return out;
1188
1575
  };
@@ -1198,17 +1585,17 @@ const validate_CHILD = (inj) => {
1198
1585
  const { mode, key, parent, keys, path } = inj;
1199
1586
  // Setup data structures for validation by cloning child template.
1200
1587
  // Map syntax.
1201
- if (S_MKEYPRE === mode) {
1588
+ if (M_KEYPRE === mode) {
1202
1589
  const childtm = getprop(parent, key);
1203
1590
  // Get corresponding current object.
1204
- const pkey = getprop(path, path.length - 2);
1591
+ const pkey = getelem(path, -2);
1205
1592
  let tval = getprop(inj.dparent, pkey);
1206
- if (UNDEF == tval) {
1593
+ if (NONE == tval) {
1207
1594
  tval = {};
1208
1595
  }
1209
1596
  else if (!ismap(tval)) {
1210
1597
  inj.errs.push(_invalidTypeMsg(slice(inj.path, -1), S_object, typify(tval), tval), 'V0220');
1211
- return UNDEF;
1598
+ return NONE;
1212
1599
  }
1213
1600
  const ckeys = keysof(tval);
1214
1601
  for (let ckey of ckeys) {
@@ -1217,58 +1604,62 @@ const validate_CHILD = (inj) => {
1217
1604
  keys.push(ckey);
1218
1605
  }
1219
1606
  // Remove $CHILD to cleanup ouput.
1220
- inj.setval(UNDEF);
1221
- return UNDEF;
1607
+ inj.setval(NONE);
1608
+ return NONE;
1222
1609
  }
1223
1610
  // List syntax.
1224
- if (S_MVAL === mode) {
1611
+ if (M_VAL === mode) {
1225
1612
  if (!islist(parent)) {
1226
1613
  // $CHILD was not inside a list.
1227
1614
  inj.errs.push('Invalid $CHILD as value');
1228
- return UNDEF;
1615
+ return NONE;
1229
1616
  }
1230
1617
  const childtm = getprop(parent, 1);
1231
- if (UNDEF === inj.dparent) {
1618
+ if (NONE === inj.dparent) {
1232
1619
  // Empty list as default.
1233
- parent.length = 0;
1234
- return UNDEF;
1620
+ // parent.length = 0
1621
+ slice(parent, 0, 0, true);
1622
+ return NONE;
1235
1623
  }
1236
1624
  if (!islist(inj.dparent)) {
1237
- const msg = _invalidTypeMsg(slice(inj.path, -1), S_array, typify(inj.dparent), inj.dparent, 'V0230');
1625
+ const msg = _invalidTypeMsg(slice(inj.path, -1), S_list, typify(inj.dparent), inj.dparent, 'V0230');
1238
1626
  inj.errs.push(msg);
1239
- inj.keyI = parent.length;
1627
+ inj.keyI = size(parent);
1240
1628
  return inj.dparent;
1241
1629
  }
1242
1630
  // Clone children abd reset inj key index.
1243
1631
  // The inject child loop will now iterate over the cloned children,
1244
1632
  // validating them againt the current list values.
1245
- inj.dparent.map((_n, i) => parent[i] = clone(childtm));
1246
- parent.length = inj.dparent.length;
1633
+ items(inj.dparent, (n) => setprop(parent, n[0], clone(childtm)));
1634
+ slice(parent, 0, inj.dparent.length, true);
1247
1635
  inj.keyI = 0;
1248
1636
  const out = getprop(inj.dparent, 0);
1249
1637
  return out;
1250
1638
  }
1251
- return UNDEF;
1639
+ return NONE;
1252
1640
  };
1641
+ // TODO: implement SOME, ALL
1642
+ // FIX: ONE should mean exactly one, not at least one (=SOME)
1643
+ // TODO: implement a generate validate_ALT to do all of these
1253
1644
  // Match at least one of the specified shapes.
1254
- // Syntax: ['`$ONE`', alt0, alt1, ...]okI
1645
+ // Syntax: ['`$ONE`', alt0, alt1, ...]
1255
1646
  const validate_ONE = (inj, _val, _ref, store) => {
1256
1647
  const { mode, parent, keyI } = inj;
1257
1648
  // Only operate in val mode, since parent is a list.
1258
- if (S_MVAL === mode) {
1649
+ if (M_VAL === mode) {
1259
1650
  if (!islist(parent) || 0 !== keyI) {
1260
1651
  inj.errs.push('The $ONE validator at field ' +
1261
1652
  pathify(inj.path, 1, 1) +
1262
1653
  ' must be the first element of an array.');
1263
1654
  return;
1264
1655
  }
1265
- inj.keyI = inj.keys.length;
1656
+ inj.keyI = size(inj.keys);
1266
1657
  // Clean up structure, replacing [$ONE, ...] with current
1267
1658
  inj.setval(inj.dparent, 2);
1268
1659
  inj.path = slice(inj.path, -1);
1269
1660
  inj.key = getelem(inj.path, -1);
1270
1661
  let tvals = slice(parent, 1);
1271
- if (0 === tvals.length) {
1662
+ if (0 === size(tvals)) {
1272
1663
  inj.errs.push('The $ONE validator at field ' +
1273
1664
  pathify(inj.path, 1, 1) +
1274
1665
  ' must have at least one argument.');
@@ -1278,7 +1669,7 @@ const validate_ONE = (inj, _val, _ref, store) => {
1278
1669
  for (let tval of tvals) {
1279
1670
  // If match, then errs.length = 0
1280
1671
  let terrs = [];
1281
- const vstore = { ...store };
1672
+ const vstore = merge([{}, store], 1);
1282
1673
  vstore.$TOP = inj.dparent;
1283
1674
  const vcurrent = validate(inj.dparent, tval, {
1284
1675
  extra: vstore,
@@ -1287,35 +1678,33 @@ const validate_ONE = (inj, _val, _ref, store) => {
1287
1678
  });
1288
1679
  inj.setval(vcurrent, -2);
1289
1680
  // Accept current value if there was a match
1290
- if (0 === terrs.length) {
1681
+ if (0 === size(terrs)) {
1291
1682
  return;
1292
1683
  }
1293
1684
  }
1294
1685
  // 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'));
1686
+ const valdesc = replace(join(items(tvals, (n) => stringify(n[1])), ', '), R_TRANSFORM_NAME, (_m, p1) => p1.toLowerCase());
1687
+ inj.errs.push(_invalidTypeMsg(inj.path, (1 < size(tvals) ? 'one of ' : '') + valdesc, typify(inj.dparent), inj.dparent, 'V0210'));
1300
1688
  }
1301
1689
  };
1302
1690
  const validate_EXACT = (inj) => {
1303
1691
  const { mode, parent, key, keyI } = inj;
1304
1692
  // Only operate in val mode, since parent is a list.
1305
- if (S_MVAL === mode) {
1693
+ if (M_VAL === mode) {
1306
1694
  if (!islist(parent) || 0 !== keyI) {
1307
1695
  inj.errs.push('The $EXACT validator at field ' +
1308
1696
  pathify(inj.path, 1, 1) +
1309
1697
  ' must be the first element of an array.');
1310
1698
  return;
1311
1699
  }
1312
- inj.keyI = inj.keys.length;
1700
+ inj.keyI = size(inj.keys);
1313
1701
  // Clean up structure, replacing [$EXACT, ...] with current data parent
1314
1702
  inj.setval(inj.dparent, 2);
1315
- inj.path = slice(inj.path, 0, inj.path.length - 1);
1703
+ // inj.path = slice(inj.path, 0, size(inj.path) - 1)
1704
+ inj.path = slice(inj.path, 0, -1);
1316
1705
  inj.key = getelem(inj.path, -1);
1317
1706
  let tvals = slice(parent, 1);
1318
- if (0 === tvals.length) {
1707
+ if (0 === size(tvals)) {
1319
1708
  inj.errs.push('The $EXACT validator at field ' +
1320
1709
  pathify(inj.path, 1, 1) +
1321
1710
  ' must have at least one argument.');
@@ -1334,12 +1723,10 @@ const validate_EXACT = (inj) => {
1334
1723
  return;
1335
1724
  }
1336
1725
  }
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'));
1726
+ // There was no match.
1727
+ const valdesc = replace(join(items(tvals, (n) => stringify(n[1])), ', '), R_TRANSFORM_NAME, (_m, p1) => p1.toLowerCase());
1728
+ inj.errs.push(_invalidTypeMsg(inj.path, (1 < size(inj.path) ? '' : 'value ') +
1729
+ 'exactly equal to ' + (1 === size(tvals) ? '' : 'one of ') + valdesc, typify(inj.dparent), inj.dparent, 'V0110'));
1343
1730
  }
1344
1731
  else {
1345
1732
  delprop(parent, key);
@@ -1348,7 +1735,7 @@ const validate_EXACT = (inj) => {
1348
1735
  // This is the "modify" argument to inject. Use this to perform
1349
1736
  // generic validation. Runs *after* any special commands.
1350
1737
  const _validation = (pval, key, parent, inj) => {
1351
- if (UNDEF === inj) {
1738
+ if (NONE === inj) {
1352
1739
  return;
1353
1740
  }
1354
1741
  if (SKIP === pval) {
@@ -1358,29 +1745,29 @@ const _validation = (pval, key, parent, inj) => {
1358
1745
  const exact = getprop(inj.meta, S_BEXACT, false);
1359
1746
  // Current val to verify.
1360
1747
  const cval = getprop(inj.dparent, key);
1361
- if (UNDEF === inj || (!exact && UNDEF === cval)) {
1748
+ if (NONE === inj || (!exact && NONE === cval)) {
1362
1749
  return;
1363
1750
  }
1364
1751
  const ptype = typify(pval);
1365
1752
  // Delete any special commands remaining.
1366
- if (S_string === ptype && pval.includes(S_DS)) {
1753
+ if (0 < (T_string & ptype) && pval.includes(S_DS)) {
1367
1754
  return;
1368
1755
  }
1369
1756
  const ctype = typify(cval);
1370
1757
  // Type mismatch.
1371
- if (ptype !== ctype && UNDEF !== pval) {
1372
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0010'));
1758
+ if (ptype !== ctype && NONE !== pval) {
1759
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0010'));
1373
1760
  return;
1374
1761
  }
1375
1762
  if (ismap(cval)) {
1376
1763
  if (!ismap(pval)) {
1377
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0020'));
1764
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0020'));
1378
1765
  return;
1379
1766
  }
1380
1767
  const ckeys = keysof(cval);
1381
1768
  const pkeys = keysof(pval);
1382
1769
  // Empty spec object {} means object can be open (any keys).
1383
- if (0 < pkeys.length && true !== getprop(pval, '`$OPEN`')) {
1770
+ if (0 < size(pkeys) && true !== getprop(pval, '`$OPEN`')) {
1384
1771
  const badkeys = [];
1385
1772
  for (let ckey of ckeys) {
1386
1773
  if (!haskey(pval, ckey)) {
@@ -1388,8 +1775,8 @@ const _validation = (pval, key, parent, inj) => {
1388
1775
  }
1389
1776
  }
1390
1777
  // 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(', ');
1778
+ if (0 < size(badkeys)) {
1779
+ const msg = 'Unexpected keys at field ' + pathify(inj.path, 1) + S_VIZ + join(badkeys, ', ');
1393
1780
  inj.errs.push(msg);
1394
1781
  }
1395
1782
  }
@@ -1403,7 +1790,7 @@ const _validation = (pval, key, parent, inj) => {
1403
1790
  }
1404
1791
  else if (islist(cval)) {
1405
1792
  if (!islist(pval)) {
1406
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0030'));
1793
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0030'));
1407
1794
  }
1408
1795
  }
1409
1796
  else if (exact) {
@@ -1435,61 +1822,69 @@ injdef) {
1435
1822
  const extra = injdef?.extra;
1436
1823
  const collect = null != injdef?.errs;
1437
1824
  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 || {}),
1825
+ const store = merge([
1826
+ {
1827
+ // Remove the transform commands.
1828
+ $DELETE: null,
1829
+ $COPY: null,
1830
+ $KEY: null,
1831
+ $META: null,
1832
+ $MERGE: null,
1833
+ $EACH: null,
1834
+ $PACK: null,
1835
+ $STRING: validate_STRING,
1836
+ $NUMBER: validate_TYPE,
1837
+ $INTEGER: validate_TYPE,
1838
+ $DECIMAL: validate_TYPE,
1839
+ $BOOLEAN: validate_TYPE,
1840
+ $NULL: validate_TYPE,
1841
+ $NIL: validate_TYPE,
1842
+ $MAP: validate_TYPE,
1843
+ $LIST: validate_TYPE,
1844
+ $FUNCTION: validate_TYPE,
1845
+ $INSTANCE: validate_TYPE,
1846
+ $ANY: validate_ANY,
1847
+ $CHILD: validate_CHILD,
1848
+ $ONE: validate_ONE,
1849
+ $EXACT: validate_EXACT,
1850
+ },
1851
+ getdef(extra, {}),
1459
1852
  // A special top level value to collect errors.
1460
- // NOTE: collecterrs paramter always wins.
1461
- $ERRS: errs,
1462
- };
1853
+ // NOTE: collecterrs parameter always wins.
1854
+ {
1855
+ $ERRS: errs,
1856
+ }
1857
+ ], 1);
1463
1858
  let meta = getprop(injdef, 'meta', {});
1464
1859
  setprop(meta, S_BEXACT, getprop(meta, S_BEXACT, false));
1465
1860
  const out = transform(data, spec, {
1466
1861
  meta,
1467
1862
  extra: store,
1468
1863
  modify: _validation,
1469
- handler: _validatehandler
1864
+ handler: _validatehandler,
1865
+ errs,
1470
1866
  });
1471
- const generr = (0 < errs.length && !collect);
1867
+ const generr = (0 < size(errs) && !collect);
1472
1868
  if (generr) {
1473
- throw new Error('Invalid data: ' + errs.join(' | '));
1869
+ throw new Error(join(errs, ' | '));
1474
1870
  }
1475
1871
  return out;
1476
1872
  }
1477
1873
  const select_AND = (inj, _val, _ref, store) => {
1478
- if (S_MKEYPRE === inj.mode) {
1874
+ if (M_KEYPRE === inj.mode) {
1479
1875
  const terms = getprop(inj.parent, inj.key);
1480
1876
  const ppath = slice(inj.path, -1);
1481
1877
  const point = getpath(store, ppath);
1482
- const vstore = { ...store };
1878
+ const vstore = merge([{}, store], 1);
1483
1879
  vstore.$TOP = point;
1484
1880
  for (let term of terms) {
1485
- // setprop(term, '`$OPEN`', getprop(term, '`$OPEN`', true))
1486
1881
  let terrs = [];
1487
1882
  validate(point, term, {
1488
1883
  extra: vstore,
1489
1884
  errs: terrs,
1490
1885
  meta: inj.meta,
1491
1886
  });
1492
- if (0 != terrs.length) {
1887
+ if (0 != size(terrs)) {
1493
1888
  inj.errs.push('AND:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(terms));
1494
1889
  }
1495
1890
  }
@@ -1499,11 +1894,11 @@ const select_AND = (inj, _val, _ref, store) => {
1499
1894
  }
1500
1895
  };
1501
1896
  const select_OR = (inj, _val, _ref, store) => {
1502
- if (S_MKEYPRE === inj.mode) {
1897
+ if (M_KEYPRE === inj.mode) {
1503
1898
  const terms = getprop(inj.parent, inj.key);
1504
1899
  const ppath = slice(inj.path, -1);
1505
1900
  const point = getpath(store, ppath);
1506
- const vstore = { ...store };
1901
+ const vstore = merge([{}, store], 1);
1507
1902
  vstore.$TOP = point;
1508
1903
  for (let term of terms) {
1509
1904
  let terrs = [];
@@ -1512,7 +1907,7 @@ const select_OR = (inj, _val, _ref, store) => {
1512
1907
  errs: terrs,
1513
1908
  meta: inj.meta,
1514
1909
  });
1515
- if (0 === terrs.length) {
1910
+ if (0 === size(terrs)) {
1516
1911
  const gkey = getelem(inj.path, -2);
1517
1912
  const gp = getelem(inj.nodes, -2);
1518
1913
  setprop(gp, gkey, point);
@@ -1523,11 +1918,11 @@ const select_OR = (inj, _val, _ref, store) => {
1523
1918
  }
1524
1919
  };
1525
1920
  const select_NOT = (inj, _val, _ref, store) => {
1526
- if (S_MKEYPRE === inj.mode) {
1921
+ if (M_KEYPRE === inj.mode) {
1527
1922
  const term = getprop(inj.parent, inj.key);
1528
1923
  const ppath = slice(inj.path, -1);
1529
1924
  const point = getpath(store, ppath);
1530
- const vstore = { ...store };
1925
+ const vstore = merge([{}, store], 1);
1531
1926
  vstore.$TOP = point;
1532
1927
  let terrs = [];
1533
1928
  validate(point, term, {
@@ -1535,7 +1930,7 @@ const select_NOT = (inj, _val, _ref, store) => {
1535
1930
  errs: terrs,
1536
1931
  meta: inj.meta,
1537
1932
  });
1538
- if (0 == terrs.length) {
1933
+ if (0 == size(terrs)) {
1539
1934
  inj.errs.push('NOT:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(term));
1540
1935
  }
1541
1936
  const gkey = getelem(inj.path, -2);
@@ -1544,7 +1939,7 @@ const select_NOT = (inj, _val, _ref, store) => {
1544
1939
  }
1545
1940
  };
1546
1941
  const select_CMP = (inj, _val, ref, store) => {
1547
- if (S_MKEYPRE === inj.mode) {
1942
+ if (M_KEYPRE === inj.mode) {
1548
1943
  const term = getprop(inj.parent, inj.key);
1549
1944
  // const src = getprop(store, inj.base, store)
1550
1945
  const gkey = getelem(inj.path, -2);
@@ -1577,7 +1972,7 @@ const select_CMP = (inj, _val, ref, store) => {
1577
1972
  ' fail:' + ref + ' ' + stringify(term));
1578
1973
  }
1579
1974
  }
1580
- return UNDEF;
1975
+ return NONE;
1581
1976
  };
1582
1977
  // Select children from a top-level object that match a MongoDB-style query.
1583
1978
  // Supports $and, $or, and equality comparisons.
@@ -1588,10 +1983,13 @@ function select(children, query) {
1588
1983
  return [];
1589
1984
  }
1590
1985
  if (ismap(children)) {
1591
- children = items(children).map(n => (n[1][S_DKEY] = n[0], n[1]));
1986
+ children = items(children, n => {
1987
+ setprop(n[1], S_DKEY, n[0]);
1988
+ return n[1];
1989
+ });
1592
1990
  }
1593
1991
  else {
1594
- children = children.map((n, i) => ((ismap(n) ? n[S_DKEY] = i : null), n));
1992
+ children = items(children, (n) => (setprop(n[1], S_DKEY, +n[0]), n[1]));
1595
1993
  }
1596
1994
  const results = [];
1597
1995
  const injdef = {
@@ -1630,9 +2028,9 @@ class Injection {
1630
2028
  this.val = val;
1631
2029
  this.parent = parent;
1632
2030
  this.errs = [];
1633
- this.dparent = UNDEF;
2031
+ this.dparent = NONE;
1634
2032
  this.dpath = [S_DTOP];
1635
- this.mode = S_MVAL;
2033
+ this.mode = M_VAL;
1636
2034
  this.full = false;
1637
2035
  this.keyI = 0;
1638
2036
  this.keys = [S_DTOP];
@@ -1646,7 +2044,7 @@ class Injection {
1646
2044
  toString(prefix) {
1647
2045
  return 'INJ' + (null == prefix ? '' : S_FS + prefix) + S_CN +
1648
2046
  pad(pathify(this.path, 1)) +
1649
- this.mode + (this.full ? '/full' : '') + S_CN +
2047
+ MODENAME[this.mode] + (this.full ? '/full' : '') + S_CN +
1650
2048
  'key=' + this.keyI + S_FS + this.key + S_FS + S_OS + this.keys + S_CS +
1651
2049
  ' p=' + stringify(this.parent, -1, 1) +
1652
2050
  ' m=' + stringify(this.meta, -1, 1) +
@@ -1657,11 +2055,11 @@ class Injection {
1657
2055
  this.meta.__d++;
1658
2056
  const parentkey = getelem(this.path, -2);
1659
2057
  // Resolve current node in store for local paths.
1660
- if (UNDEF === this.dparent) {
2058
+ if (NONE === this.dparent) {
1661
2059
  // Even if there's no data, dpath should continue to match path, so that
1662
2060
  // relative paths work properly.
1663
- if (1 < this.dpath.length) {
1664
- this.dpath = [...this.dpath, parentkey];
2061
+ if (1 < size(this.dpath)) {
2062
+ this.dpath = flatten([this.dpath, parentkey]);
1665
2063
  }
1666
2064
  }
1667
2065
  else {
@@ -1673,7 +2071,7 @@ class Injection {
1673
2071
  this.dpath = slice(this.dpath, -1);
1674
2072
  }
1675
2073
  else {
1676
- this.dpath = [...this.dpath, parentkey];
2074
+ this.dpath = flatten([this.dpath, parentkey]);
1677
2075
  }
1678
2076
  }
1679
2077
  }
@@ -1687,8 +2085,8 @@ class Injection {
1687
2085
  cinj.keyI = keyI;
1688
2086
  cinj.keys = keys;
1689
2087
  cinj.key = key;
1690
- cinj.path = [...(this.path || []), key];
1691
- cinj.nodes = [...(this.nodes || []), val];
2088
+ cinj.path = flatten([getdef(this.path, []), key]);
2089
+ cinj.nodes = flatten([getdef(this.nodes, []), [val]]);
1692
2090
  cinj.mode = this.mode;
1693
2091
  cinj.handler = this.handler;
1694
2092
  cinj.modify = this.modify;
@@ -1696,39 +2094,42 @@ class Injection {
1696
2094
  cinj.meta = this.meta;
1697
2095
  cinj.errs = this.errs;
1698
2096
  cinj.prior = this;
1699
- cinj.dpath = [...this.dpath];
2097
+ cinj.dpath = flatten([this.dpath]);
1700
2098
  cinj.dparent = this.dparent;
1701
2099
  return cinj;
1702
2100
  }
1703
2101
  setval(val, ancestor) {
2102
+ let parent = NONE;
1704
2103
  if (null == ancestor || ancestor < 2) {
1705
- return UNDEF === val ?
1706
- delprop(this.parent, this.key) :
2104
+ parent = NONE === val ?
2105
+ this.parent = delprop(this.parent, this.key) :
1707
2106
  setprop(this.parent, this.key, val);
1708
2107
  }
1709
2108
  else {
1710
2109
  const aval = getelem(this.nodes, 0 - ancestor);
1711
2110
  const akey = getelem(this.path, 0 - ancestor);
1712
- return UNDEF === val ?
2111
+ parent = NONE === val ?
1713
2112
  delprop(aval, akey) :
1714
2113
  setprop(aval, akey, val);
1715
2114
  }
2115
+ // console.log('SETVAL', val, this.key, this.parent)
2116
+ return parent;
1716
2117
  }
1717
2118
  }
1718
2119
  // Internal utilities
1719
2120
  // ==================
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
- }
2121
+ // // Update all references to target in inj.nodes.
2122
+ // function _updateAncestors(_inj: Injection, target: any, tkey: any, tval: any) {
2123
+ // // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
2124
+ // setprop(target, tkey, tval)
2125
+ // }
1725
2126
  // Build a type validation error message.
1726
2127
  function _invalidTypeMsg(path, needtype, vt, v, _whence) {
1727
2128
  let vs = null == v ? 'no value' : stringify(v);
1728
2129
  return 'Expected ' +
1729
- (1 < path.length ? ('field ' + pathify(path, 1) + ' to be ') : '') +
2130
+ (1 < size(path) ? ('field ' + pathify(path, 1) + ' to be ') : '') +
1730
2131
  needtype + ', but found ' +
1731
- (null != v ? vt + S_VIZ : '') + vs +
2132
+ (null != v ? typename(vt) + S_VIZ : '') + vs +
1732
2133
  // Uncomment to help debug validation errors.
1733
2134
  // ' [' + _whence + ']' +
1734
2135
  '.';
@@ -1737,14 +2138,14 @@ function _invalidTypeMsg(path, needtype, vt, v, _whence) {
1737
2138
  // call the function passing the injection inj. This is how transforms operate.
1738
2139
  const _injecthandler = (inj, val, ref, store) => {
1739
2140
  let out = val;
1740
- const iscmd = isfunc(val) && (UNDEF === ref || ref.startsWith(S_DS));
2141
+ const iscmd = isfunc(val) && (NONE === ref || ref.startsWith(S_DS));
1741
2142
  // Only call val function if it is a special command ($NAME format).
1742
2143
  // TODO: OR if meta.'$CALL'
1743
2144
  if (iscmd) {
1744
2145
  out = val(inj, val, ref, store);
1745
2146
  }
1746
2147
  // Update parent with value. Ensures references remain in node tree.
1747
- else if (S_MVAL === inj.mode && inj.full) {
2148
+ else if (M_VAL === inj.mode && inj.full) {
1748
2149
  inj.setval(val);
1749
2150
  }
1750
2151
  return out;
@@ -1792,9 +2193,9 @@ function _injectstr(val, store, inj) {
1792
2193
  }
1793
2194
  let pathref = m[1];
1794
2195
  // 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;
2196
+ if (3 < size(pathref)) {
2197
+ pathref = pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS);
2198
+ }
1798
2199
  // Get the extracted path reference.
1799
2200
  out = getpath(store, pathref, inj);
1800
2201
  }
@@ -1802,13 +2203,15 @@ function _injectstr(val, store, inj) {
1802
2203
  // Check for injections within the string.
1803
2204
  const partial = (_m, ref) => {
1804
2205
  // Special escapes inside injection.
1805
- ref = 3 < ref.length ? ref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS) : ref;
2206
+ if (3 < size(ref)) {
2207
+ ref = ref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS);
2208
+ }
1806
2209
  if (inj) {
1807
2210
  inj.full = false;
1808
2211
  }
1809
2212
  const found = getpath(store, ref, inj);
1810
2213
  // Ensure inject value is a string.
1811
- return UNDEF === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found);
2214
+ return NONE === found ? S_MT : S_string === typeof found ? found : JSON.stringify(found);
1812
2215
  };
1813
2216
  out = val.replace(R_INJECTION_PARTIAL, partial);
1814
2217
  // Also call the inj handler on the entire string, providing the
@@ -1820,12 +2223,82 @@ function _injectstr(val, store, inj) {
1820
2223
  }
1821
2224
  return out;
1822
2225
  }
2226
+ // Handler Utilities
2227
+ // =================
2228
+ const MODENAME = {
2229
+ [M_VAL]: 'val',
2230
+ [M_KEYPRE]: 'key:pre',
2231
+ [M_KEYPOST]: 'key:post',
2232
+ };
2233
+ exports.MODENAME = MODENAME;
2234
+ const PLACEMENT = {
2235
+ [M_VAL]: 'value',
2236
+ [M_KEYPRE]: S_key,
2237
+ [M_KEYPOST]: S_key,
2238
+ };
2239
+ function checkPlacement(modes, ijname, parentTypes, inj) {
2240
+ if (0 === (modes & inj.mode)) {
2241
+ inj.errs.push('$' + ijname + ': invalid placement as ' + PLACEMENT[inj.mode] +
2242
+ ', expected: ' + join(items([M_KEYPRE, M_KEYPOST, M_VAL].filter(m => modes & m), (n) => PLACEMENT[n[1]]), ',') + '.');
2243
+ return false;
2244
+ }
2245
+ if (!isempty(parentTypes)) {
2246
+ const ptype = typify(inj.parent);
2247
+ if (0 === (parentTypes & ptype)) {
2248
+ inj.errs.push('$' + ijname + ': invalid placement in parent ' + typename(ptype) +
2249
+ ', expected: ' + typename(parentTypes) + '.');
2250
+ return false;
2251
+ }
2252
+ }
2253
+ return true;
2254
+ }
2255
+ // function injectorArgs(argTypes: number[], inj: Injection): any {
2256
+ function injectorArgs(argTypes, args) {
2257
+ const numargs = size(argTypes);
2258
+ const found = new Array(1 + numargs);
2259
+ found[0] = NONE;
2260
+ for (let argI = 0; argI < numargs; argI++) {
2261
+ // const arg = inj.parent[1 + argI]
2262
+ const arg = args[argI];
2263
+ const argType = typify(arg);
2264
+ if (0 === (argTypes[argI] & argType)) {
2265
+ found[0] = 'invalid argument: ' + stringify(arg, 22) +
2266
+ ' (' + typename(argType) + ' at position ' + (1 + argI) +
2267
+ ') is not of type: ' + typename(argTypes[argI]) + '.';
2268
+ break;
2269
+ }
2270
+ found[1 + argI] = arg;
2271
+ }
2272
+ return found;
2273
+ }
2274
+ function injectChild(child, store, inj) {
2275
+ let cinj = inj;
2276
+ // Replace ['`$FORMAT`',...] with child
2277
+ if (null != inj.prior) {
2278
+ if (null != inj.prior.prior) {
2279
+ cinj = inj.prior.prior.child(inj.prior.keyI, inj.prior.keys);
2280
+ cinj.val = child;
2281
+ setprop(cinj.parent, inj.prior.key, child);
2282
+ }
2283
+ else {
2284
+ cinj = inj.prior.child(inj.keyI, inj.keys);
2285
+ cinj.val = child;
2286
+ setprop(cinj.parent, inj.key, child);
2287
+ }
2288
+ }
2289
+ // console.log('FORMAT-INJECT-CHILD', child)
2290
+ inject(child, store, cinj);
2291
+ return cinj;
2292
+ }
1823
2293
  class StructUtility {
1824
2294
  constructor() {
1825
2295
  this.clone = clone;
1826
2296
  this.delprop = delprop;
1827
2297
  this.escre = escre;
1828
2298
  this.escurl = escurl;
2299
+ this.filter = filter;
2300
+ this.flatten = flatten;
2301
+ this.getdef = getdef;
1829
2302
  this.getelem = getelem;
1830
2303
  this.getpath = getpath;
1831
2304
  this.getprop = getprop;
@@ -1838,13 +2311,14 @@ class StructUtility {
1838
2311
  this.ismap = ismap;
1839
2312
  this.isnode = isnode;
1840
2313
  this.items = items;
1841
- this.joinurl = joinurl;
2314
+ this.join = join;
1842
2315
  this.jsonify = jsonify;
1843
2316
  this.keysof = keysof;
1844
2317
  this.merge = merge;
1845
2318
  this.pad = pad;
1846
2319
  this.pathify = pathify;
1847
2320
  this.select = select;
2321
+ this.setpath = setpath;
1848
2322
  this.setprop = setprop;
1849
2323
  this.size = size;
1850
2324
  this.slice = slice;
@@ -1852,10 +2326,32 @@ class StructUtility {
1852
2326
  this.stringify = stringify;
1853
2327
  this.transform = transform;
1854
2328
  this.typify = typify;
2329
+ this.typename = typename;
1855
2330
  this.validate = validate;
1856
2331
  this.walk = walk;
1857
- this.jo = jo;
1858
- this.ja = ja;
2332
+ this.SKIP = SKIP;
2333
+ this.DELETE = DELETE;
2334
+ this.jm = jm;
2335
+ this.jt = jt;
2336
+ this.tn = typename;
2337
+ this.T_any = T_any;
2338
+ this.T_noval = T_noval;
2339
+ this.T_boolean = T_boolean;
2340
+ this.T_decimal = T_decimal;
2341
+ this.T_integer = T_integer;
2342
+ this.T_number = T_number;
2343
+ this.T_string = T_string;
2344
+ this.T_function = T_function;
2345
+ this.T_symbol = T_symbol;
2346
+ this.T_null = T_null;
2347
+ this.T_list = T_list;
2348
+ this.T_map = T_map;
2349
+ this.T_instance = T_instance;
2350
+ this.T_scalar = T_scalar;
2351
+ this.T_node = T_node;
2352
+ this.checkPlacement = checkPlacement;
2353
+ this.injectorArgs = injectorArgs;
2354
+ this.injectChild = injectChild;
1859
2355
  }
1860
2356
  }
1861
2357
  exports.StructUtility = StructUtility;