@voxgig/struct 0.0.8 → 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.8
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;
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 {
@@ -586,23 +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
- // if (isnode(val)) {
595
790
  if (isnode(out)) {
596
- // for (let [ckey, child] of items(val)) {
597
791
  for (let [ckey, child] of items(out)) {
598
- // setprop(val, ckey, walk(
599
- setprop(out, ckey, walk(
600
- // child, before, after, maxdepth, ckey, val, [...(path || []), S_MT + ckey]))
601
- 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])));
602
793
  }
603
794
  }
604
- // out = null == after ? out : after(key, val, parent, path || [])
605
- out = null == after ? out : after(key, out, parent, path || []);
795
+ out = null == after ? out : after(key, out, parent, path);
606
796
  return out;
607
797
  }
608
798
  // Merge a list of values into each other. Later values have
@@ -610,7 +800,9 @@ key, parent, path) {
610
800
  // override each other, and do *not* merge. The first element is
611
801
  // modified.
612
802
  function merge(val, maxdepth) {
613
- 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;
614
806
  // Handle edge cases.
615
807
  if (!islist(val)) {
616
808
  return val;
@@ -618,7 +810,7 @@ function merge(val, maxdepth) {
618
810
  const list = val;
619
811
  const lenlist = list.length;
620
812
  if (0 === lenlist) {
621
- return UNDEF;
813
+ return NONE;
622
814
  }
623
815
  else if (1 === lenlist) {
624
816
  return list[0];
@@ -638,8 +830,11 @@ function merge(val, maxdepth) {
638
830
  let dst = [out];
639
831
  function before(key, val, _parent, path) {
640
832
  const pI = size(path);
833
+ if (md <= pI) {
834
+ setprop(cur[pI - 1], key, val);
835
+ }
641
836
  // Scalars just override directly.
642
- if (!isnode(val)) {
837
+ else if (!isnode(val)) {
643
838
  cur[pI] = val;
644
839
  }
645
840
  // Descend into override node - Set up correct target in `after` function.
@@ -647,8 +842,8 @@ function merge(val, maxdepth) {
647
842
  // Descend into destination node using same key.
648
843
  dst[pI] = 0 < pI ? getprop(dst[pI - 1], key) : dst[pI];
649
844
  const tval = dst[pI];
650
- // Destination empty, so create node.
651
- if (UNDEF === tval) {
845
+ // Destination empty, so create node (unless override is class instance).
846
+ if (NONE === tval && 0 === (T_instance & typify(val))) {
652
847
  cur[pI] = islist(val) ? [] : {};
653
848
  }
654
849
  // Matching override and destination so continue with their values.
@@ -659,7 +854,7 @@ function merge(val, maxdepth) {
659
854
  else {
660
855
  cur[pI] = val;
661
856
  // No need to descend when override wins (destination is discarded).
662
- val = UNDEF;
857
+ val = NONE;
663
858
  }
664
859
  }
665
860
  // console.log('BEFORE-END', pathify(path), '@', pI, key,
@@ -671,24 +866,59 @@ function merge(val, maxdepth) {
671
866
  const cI = size(path);
672
867
  const target = cur[cI - 1];
673
868
  const value = cur[cI];
674
- // console.log('AFTER-PREP', pathify(path), '@', cI,
869
+ // console.log('AFTER-PREP', pathify(path), '@', cI, cur, '|',
675
870
  // stringify(key, -1, 1), stringify(value, -1, 1), 'T=', stringify(target, -1, 1))
676
871
  setprop(target, key, value);
677
872
  return value;
678
873
  }
679
874
  // Walk overriding node, creating paths in output as needed.
680
875
  out = walk(obj, before, after, maxdepth);
876
+ // console.log('WALK-DONE', out, obj)
681
877
  }
682
878
  }
879
+ if (0 === md) {
880
+ out = getelem(list, -1);
881
+ out = islist(out) ? [] : ismap(out) ? {} : out;
882
+ }
683
883
  return out;
684
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
+ }
685
915
  function getpath(store, path, injdef) {
686
916
  // Operate on a string array.
687
917
  const parts = islist(path) ? path :
688
918
  'string' === typeof path ? path.split(S_DT) :
689
- 'number' === typeof path ? [strkey(path)] : UNDEF;
690
- if (UNDEF === parts) {
691
- return UNDEF;
919
+ 'number' === typeof path ? [strkey(path)] : NONE;
920
+ if (NONE === parts) {
921
+ return NONE;
692
922
  }
693
923
  // let root = store
694
924
  let val = store;
@@ -713,22 +943,22 @@ function getpath(store, path, injdef) {
713
943
  parts[0] = m[3];
714
944
  }
715
945
  const dpath = getprop(injdef, 'dpath');
716
- for (let pI = 0; UNDEF !== val && pI < parts.length; pI++) {
946
+ for (let pI = 0; NONE !== val && pI < numparts; pI++) {
717
947
  let part = parts[pI];
718
948
  if (injdef && S_DKEY === part) {
719
949
  part = getprop(injdef, S_key);
720
950
  }
721
951
  else if (injdef && part.startsWith('$GET:')) {
722
952
  // $GET:path$ -> get store value, use as path part (string)
723
- part = stringify(getpath(src, part.substring(5, part.length - 1)));
953
+ part = stringify(getpath(src, slice(part, 5, -1)));
724
954
  }
725
955
  else if (injdef && part.startsWith('$REF:')) {
726
956
  // $REF:refpath$ -> get spec value, use as path part (string)
727
- 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)));
728
958
  }
729
959
  else if (injdef && part.startsWith('$META:')) {
730
960
  // $META:metapath$ -> get meta value, use as path part (string)
731
- part = stringify(getpath(getprop(injdef, 'meta'), part.substring(6, part.length - 1)));
961
+ part = stringify(getpath(getprop(injdef, 'meta'), slice(part, 6, -1)));
732
962
  }
733
963
  // $$ escapes $
734
964
  part = part.replace(R_DOUBLE_DOLLAR, '$');
@@ -746,12 +976,13 @@ function getpath(store, path, injdef) {
746
976
  val = dparent;
747
977
  }
748
978
  else {
749
- 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)]);
750
981
  if (ascends <= size(dpath)) {
751
982
  val = getpath(store, fullpath);
752
983
  }
753
984
  else {
754
- val = UNDEF;
985
+ val = NONE;
755
986
  }
756
987
  break;
757
988
  }
@@ -772,10 +1003,11 @@ function getpath(store, path, injdef) {
772
1003
  const ref = pathify(path);
773
1004
  val = handler(injdef, val, ref, store);
774
1005
  }
1006
+ // console.log('GETPATH', path, val)
775
1007
  return val;
776
1008
  }
777
1009
  // Inject values from a data store into a node recursively, resolving
778
- // 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
779
1011
  // argument allows custom modification of the result. The inj
780
1012
  // (Injection) argument is used to maintain recursive state.
781
1013
  function inject(val, store, injdef) {
@@ -783,13 +1015,13 @@ function inject(val, store, injdef) {
783
1015
  let inj = injdef;
784
1016
  // Create state if at root of injection. The input value is placed
785
1017
  // inside a virtual parent holder to simplify edge cases.
786
- if (UNDEF === injdef || null == injdef.mode) {
1018
+ if (NONE === injdef || null == injdef.mode) {
787
1019
  // Set up state assuming we are starting in the virtual parent.
788
1020
  inj = new Injection(val, { [S_DTOP]: val });
789
1021
  inj.dparent = store;
790
1022
  inj.errs = getprop(store, S_DERRS, []);
791
1023
  inj.meta.__d = 0;
792
- if (UNDEF !== injdef) {
1024
+ if (NONE !== injdef) {
793
1025
  inj.modify = null == injdef.modify ? inj.modify : injdef.modify;
794
1026
  inj.extra = null == injdef.extra ? inj.extra : injdef.extra;
795
1027
  inj.meta = null == injdef.meta ? inj.meta : injdef.meta;
@@ -797,33 +1029,42 @@ function inject(val, store, injdef) {
797
1029
  }
798
1030
  }
799
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)
800
1034
  // Descend into node.
801
1035
  if (isnode(val)) {
802
1036
  // Keys are sorted alphanumerically to ensure determinism.
803
1037
  // Injection transforms ($FOO) are processed *after* other keys.
804
1038
  // NOTE: the optional digits suffix of the transform can thus be
805
1039
  // used to order the transforms.
806
- let nodekeys = ismap(val) ? [
807
- ...Object.keys(val).filter(k => !k.includes(S_DS)).sort(),
808
- ...Object.keys(val).filter(k => k.includes(S_DS)).sort(),
809
- ] : 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
+ }
810
1051
  // Each child key-value pair is processed in three injection phases:
811
- // 1. inj.mode='key:pre' - Key string is injected, returning a possibly altered key.
812
- // 2. inj.mode='val' - The child value is injected.
813
- // 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.
814
1055
  for (let nkI = 0; nkI < nodekeys.length; nkI++) {
815
1056
  const childinj = inj.child(nkI, nodekeys);
816
1057
  const nodekey = childinj.key;
817
- childinj.mode = S_MKEYPRE;
1058
+ childinj.mode = M_KEYPRE;
818
1059
  // Peform the key:pre mode injection on the child key.
819
1060
  const prekey = _injectstr(nodekey, store, childinj);
820
1061
  // The injection may modify child processing.
821
1062
  nkI = childinj.keyI;
822
1063
  nodekeys = childinj.keys;
823
1064
  // Prevent further processing by returning an undefined prekey
824
- if (UNDEF !== prekey) {
1065
+ if (NONE !== prekey) {
825
1066
  childinj.val = getprop(val, prekey);
826
- childinj.mode = S_MVAL;
1067
+ childinj.mode = M_VAL;
827
1068
  // Perform the val mode injection on the child value.
828
1069
  // NOTE: return value is not used.
829
1070
  inject(childinj.val, store, childinj);
@@ -831,7 +1072,7 @@ function inject(val, store, injdef) {
831
1072
  nkI = childinj.keyI;
832
1073
  nodekeys = childinj.keys;
833
1074
  // Peform the key:post mode injection on the child key.
834
- childinj.mode = S_MKEYPOST;
1075
+ childinj.mode = M_KEYPOST;
835
1076
  _injectstr(nodekey, store, childinj);
836
1077
  // The injection may modify child processing.
837
1078
  nkI = childinj.keyI;
@@ -841,7 +1082,7 @@ function inject(val, store, injdef) {
841
1082
  }
842
1083
  // Inject paths into string scalars.
843
1084
  else if (S_string === valtype) {
844
- inj.mode = S_MVAL;
1085
+ inj.mode = M_VAL;
845
1086
  val = _injectstr(val, store, inj);
846
1087
  if (SKIP !== val) {
847
1088
  inj.setval(val);
@@ -854,6 +1095,7 @@ function inject(val, store, injdef) {
854
1095
  let mval = getprop(mparent, mkey);
855
1096
  inj.modify(mval, mkey, mparent, inj, store);
856
1097
  }
1098
+ // console.log('INJ-VAL', val)
857
1099
  inj.val = val;
858
1100
  // Original val reference may no longer be correct.
859
1101
  // This return value is only used as the top level result.
@@ -862,42 +1104,43 @@ function inject(val, store, injdef) {
862
1104
  // The transform_* functions are special command inject handlers (see Injector).
863
1105
  // Delete a key from a map or list.
864
1106
  const transform_DELETE = (inj) => {
865
- inj.setval(UNDEF);
866
- return UNDEF;
1107
+ inj.setval(NONE);
1108
+ return NONE;
867
1109
  };
868
1110
  // Copy value from source data.
869
1111
  const transform_COPY = (inj, _val) => {
870
- const { mode, key } = inj;
871
- let out = key;
872
- if (!mode.startsWith(S_MKEY)) {
873
- out = getprop(inj.dparent, key);
874
- inj.setval(out);
1112
+ const ijname = 'COPY';
1113
+ if (!checkPlacement(M_VAL, ijname, T_any, inj)) {
1114
+ return NONE;
875
1115
  }
1116
+ let out = getprop(inj.dparent, inj.key);
1117
+ inj.setval(out);
876
1118
  return out;
877
1119
  };
878
1120
  // As a value, inject the key of the parent node.
879
1121
  // As a key, defined the name of the key property in the source object.
880
1122
  const transform_KEY = (inj) => {
881
1123
  const { mode, path, parent } = inj;
882
- // Do nothing in val mode.
883
- if (S_MVAL !== mode) {
884
- return UNDEF;
1124
+ // Do nothing in val mode - not an error.
1125
+ if (M_VAL !== mode) {
1126
+ return NONE;
885
1127
  }
886
1128
  // Key is defined by $KEY meta property.
887
1129
  const keyspec = getprop(parent, S_BKEY);
888
- if (UNDEF !== keyspec) {
1130
+ if (NONE !== keyspec) {
889
1131
  delprop(parent, S_BKEY);
890
1132
  return getprop(inj.dparent, keyspec);
891
1133
  }
892
1134
  // Key is defined within general purpose $META object.
893
- 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));
894
1137
  };
895
- // Annotatea node. Does nothing itself, just used by
1138
+ // Annotate node. Does nothing itself, just used by
896
1139
  // other injectors, and is removed when called.
897
1140
  const transform_ANNO = (inj) => {
898
1141
  const { parent } = inj;
899
1142
  delprop(parent, S_BANNO);
900
- return UNDEF;
1143
+ return NONE;
901
1144
  };
902
1145
  // Merge a list of objects into the current object.
903
1146
  // Must be a key in an object. The value is merged over the current object.
@@ -907,70 +1150,70 @@ const transform_ANNO = (inj) => {
907
1150
  const transform_MERGE = (inj) => {
908
1151
  const { mode, key, parent } = inj;
909
1152
  // Ensures $MERGE is removed from parent list (val mode).
910
- let out = UNDEF;
911
- if (S_MKEYPRE === mode) {
1153
+ let out = NONE;
1154
+ if (M_KEYPRE === mode) {
912
1155
  out = key;
913
1156
  }
914
1157
  // Operate after child values have been transformed.
915
- else if (S_MKEYPOST === mode) {
1158
+ else if (M_KEYPOST === mode) {
916
1159
  out = key;
917
1160
  let args = getprop(parent, key);
918
1161
  args = Array.isArray(args) ? args : [args];
919
1162
  // Remove the $MERGE command from a parent map.
920
- inj.setval(UNDEF);
1163
+ inj.setval(NONE);
921
1164
  // Literals in the parent have precedence, but we still merge onto
922
1165
  // the parent object, so that node tree references are not changed.
923
- const mergelist = [parent, ...args, clone(parent)];
1166
+ const mergelist = flatten([[parent], args, [clone(parent)]]);
924
1167
  merge(mergelist);
925
- // return key
926
1168
  }
927
1169
  return out;
928
1170
  };
929
1171
  // Convert a node to a list.
930
1172
  // Format: ['`$EACH`', '`source-path-of-node`', child-template]
931
1173
  const transform_EACH = (inj, _val, _ref, store) => {
932
- // Remove arguments to avoid spurious processing.
933
- if (null != inj.keys) {
934
- inj.keys.length = 1;
935
- }
936
- if (S_MVAL !== inj.mode) {
937
- return UNDEF;
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;
938
1185
  }
939
- // Get arguments: ['`$EACH`', 'source-path', child-template].
940
- const srcpath = getprop(inj.parent, 1);
941
- const child = clone(getprop(inj.parent, 2));
942
1186
  // Source data.
943
1187
  const srcstore = getprop(store, inj.base, store);
944
1188
  const src = getpath(srcstore, srcpath, inj);
1189
+ const srctype = typify(src);
945
1190
  // Create parallel data structures:
946
1191
  // source entries :: child templates
947
1192
  let tcur = [];
948
1193
  let tval = [];
949
- const tkey = inj.path[inj.path.length - 2];
950
- 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));
951
1196
  // Create clones of the child template for each value of the current soruce.
952
- if (islist(src)) {
953
- tval = src.map(() => clone(child));
1197
+ if (0 < (T_list & srctype)) {
1198
+ tval = items(src, () => clone(child));
954
1199
  }
955
- else if (ismap(src)) {
956
- tval = Object.entries(src).map(n => ({
957
- ...clone(child),
1200
+ else if (0 < (T_map & srctype)) {
1201
+ tval = items(src, (n => merge([
1202
+ clone(child),
958
1203
  // Make a note of the key for $KEY transforms.
959
- [S_BANNO]: { KEY: n[0] }
960
- }));
1204
+ { [S_BANNO]: { KEY: n[0] } }
1205
+ ], 1)));
961
1206
  }
962
1207
  let rval = [];
963
1208
  if (0 < size(tval)) {
964
- tcur = null == src ? UNDEF : Object.values(src);
1209
+ tcur = null == src ? NONE : Object.values(src);
965
1210
  const ckey = getelem(inj.path, -2);
966
1211
  const tpath = slice(inj.path, -1);
967
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey];
1212
+ const dpath = flatten([S_DTOP, srcpath.split(S_DT), '$:' + ckey]);
968
1213
  // Parent structure.
969
- // const ckey = getelem(cpath, -1)
970
1214
  tcur = { [ckey]: tcur };
971
- if (1 < tpath.length) {
1215
+ if (1 < size(tpath)) {
972
1216
  const pkey = getelem(inj.path, -3, S_DTOP);
973
- // const pkey = getelem(cpath, -2, S_DTOP)
974
1217
  tcur = { [pkey]: tcur };
975
1218
  dpath.push('$:' + pkey);
976
1219
  }
@@ -985,70 +1228,93 @@ const transform_EACH = (inj, _val, _ref, store) => {
985
1228
  inject(tval, store, tinj);
986
1229
  rval = tinj.val;
987
1230
  }
988
- _updateAncestors(inj, target, tkey, rval);
1231
+ // _updateAncestors(inj, target, tkey, rval)
1232
+ setprop(target, tkey, rval);
989
1233
  // Prevent callee from damaging first list entry (since we are in `val` mode).
990
1234
  return rval[0];
991
1235
  };
992
1236
  // Convert a node to a map.
993
- // Format: { '`$PACK`':['`source-path`', child-template]}
1237
+ // Format: { '`$PACK`':['source-path', child-template]}
994
1238
  const transform_PACK = (inj, _val, _ref, store) => {
995
1239
  const { mode, key, path, parent, nodes } = inj;
996
- // Defensive context checks.
997
- if (S_MKEYPRE !== mode || S_string !== typeof key || null == path || null == nodes) {
998
- return UNDEF;
1240
+ const ijname = 'EACH';
1241
+ if (!checkPlacement(M_KEYPRE, ijname, T_map, inj)) {
1242
+ return NONE;
999
1243
  }
1000
1244
  // Get arguments.
1001
- const args = parent[key];
1002
- const srcpath = args[0]; // Path to source data.
1003
- 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
+ }
1004
1251
  // Find key and target node.
1005
- const keyprop = child[S_BKEY];
1006
1252
  const tkey = getelem(path, -2);
1007
- 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));
1008
1255
  // Source data
1009
1256
  const srcstore = getprop(store, inj.base, store);
1010
1257
  let src = getpath(srcstore, srcpath, inj);
1011
1258
  // Prepare source as a list.
1012
- src = islist(src) ? src :
1013
- ismap(src) ? Object.entries(src)
1014
- .reduce((a, n) => (n[1][S_BANNO] = { KEY: n[0] }, a.push(n[1]), a), []) :
1015
- 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
+ }
1016
1270
  if (null == src) {
1017
- return UNDEF;
1271
+ return NONE;
1018
1272
  }
1019
- // Get key if specified.
1020
- let childkey = getprop(child, S_BKEY);
1021
- let keyname = UNDEF === childkey ? keyprop : childkey;
1022
- 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);
1023
1277
  // Build parallel target object.
1024
1278
  let tval = {};
1025
- tval = src.reduce((a, n) => {
1026
- let kn = getprop(n, keyname);
1027
- setprop(a, kn, clone(child));
1028
- const nchild = getprop(a, kn);
1029
- const mval = getprop(n, S_BANNO);
1030
- if (UNDEF === mval) {
1031
- 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);
1032
1296
  }
1033
1297
  else {
1034
- setprop(nchild, S_BANNO, mval);
1298
+ setprop(tchild, S_BANNO, anno);
1035
1299
  }
1036
- return a;
1037
- }, tval);
1300
+ });
1038
1301
  let rval = {};
1039
- if (0 < size(tval)) {
1302
+ if (!isempty(tval)) {
1040
1303
  // Build parallel source object.
1041
- let tcur = {};
1042
- src.reduce((a, n) => {
1043
- 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);
1044
1310
  setprop(a, kn, n);
1045
1311
  return a;
1046
- }, tcur);
1312
+ }, tsrc);
1047
1313
  const tpath = slice(inj.path, -1);
1048
1314
  const ckey = getelem(inj.path, -2);
1049
- const dpath = [S_DTOP, ...srcpath.split(S_DT), '$:' + ckey];
1050
- tcur = { [ckey]: tcur };
1051
- 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)) {
1052
1318
  const pkey = getelem(inj.path, -3, S_DTOP);
1053
1319
  tcur = { [pkey]: tcur };
1054
1320
  dpath.push('$:' + pkey);
@@ -1056,7 +1322,6 @@ const transform_PACK = (inj, _val, _ref, store) => {
1056
1322
  const tinj = inj.child(0, [ckey]);
1057
1323
  tinj.path = tpath;
1058
1324
  tinj.nodes = slice(inj.nodes, -1);
1059
- // tinj.parent = tcur
1060
1325
  tinj.parent = getelem(tinj.nodes, -1);
1061
1326
  tinj.val = tval;
1062
1327
  tinj.dpath = dpath;
@@ -1064,27 +1329,31 @@ const transform_PACK = (inj, _val, _ref, store) => {
1064
1329
  inject(tval, store, tinj);
1065
1330
  rval = tinj.val;
1066
1331
  }
1067
- _updateAncestors(inj, target, tkey, rval);
1332
+ // _updateAncestors(inj, target, tkey, rval)
1333
+ setprop(target, tkey, rval);
1068
1334
  // Drop transform key.
1069
- return UNDEF;
1335
+ return NONE;
1070
1336
  };
1071
- // TODO: not found ref should removed key (setprop UNDEF)
1337
+ // TODO: not found ref should removed key (setprop NONE)
1072
1338
  // Reference original spec (enables recursice transformations)
1073
1339
  // Format: ['`$REF`', '`spec-path`']
1074
1340
  const transform_REF = (inj, val, _ref, store) => {
1075
1341
  const { nodes } = inj;
1076
- if (S_MVAL !== inj.mode) {
1077
- return UNDEF;
1342
+ if (M_VAL !== inj.mode) {
1343
+ return NONE;
1078
1344
  }
1079
1345
  // Get arguments: ['`$REF`', 'ref-path'].
1080
1346
  const refpath = getprop(inj.parent, 1);
1081
- inj.keyI = inj.keys.length;
1347
+ inj.keyI = size(inj.keys);
1082
1348
  // Spec reference.
1083
1349
  const spec = getprop(store, S_DSPEC)();
1350
+ const dpath = slice(inj.path, 1);
1084
1351
  const ref = getpath(spec, refpath, {
1085
1352
  // TODO: test relative refs
1086
- dpath: inj.path.slice(1),
1087
- 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),
1088
1357
  });
1089
1358
  let hasSubRef = false;
1090
1359
  if (isnode(ref)) {
@@ -1100,20 +1369,20 @@ const transform_REF = (inj, val, _ref, store) => {
1100
1369
  const tpath = slice(inj.path, -1);
1101
1370
  let tcur = getpath(store, cpath);
1102
1371
  let tval = getpath(store, tpath);
1103
- let rval = UNDEF;
1104
- if (!hasSubRef || UNDEF !== tval) {
1372
+ let rval = NONE;
1373
+ if (!hasSubRef || NONE !== tval) {
1105
1374
  const tinj = inj.child(0, [getelem(tpath, -1)]);
1106
1375
  tinj.path = tpath;
1107
1376
  tinj.nodes = slice(inj.nodes, -1);
1108
1377
  tinj.parent = getelem(nodes, -2);
1109
1378
  tinj.val = tref;
1110
- tinj.dpath = [...cpath];
1379
+ tinj.dpath = flatten([cpath]);
1111
1380
  tinj.dparent = tcur;
1112
1381
  inject(tref, store, tinj);
1113
1382
  rval = tinj.val;
1114
1383
  }
1115
1384
  else {
1116
- rval = UNDEF;
1385
+ rval = NONE;
1117
1386
  }
1118
1387
  const grandparent = inj.setval(rval, 2);
1119
1388
  if (islist(grandparent) && inj.prior) {
@@ -1121,6 +1390,82 @@ const transform_REF = (inj, val, _ref, store) => {
1121
1390
  }
1122
1391
  return val;
1123
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
+ };
1124
1469
  // Transform data using spec.
1125
1470
  // Only operates on static JSON-like data.
1126
1471
  // Arrays are treated as if they are objects with indices as keys.
@@ -1131,64 +1476,78 @@ injdef) {
1131
1476
  const origspec = spec;
1132
1477
  spec = clone(origspec);
1133
1478
  const extra = injdef?.extra;
1134
- // const modify = injdef?.modify
1479
+ const collect = null != injdef?.errs;
1480
+ const errs = injdef?.errs || [];
1135
1481
  const extraTransforms = {};
1136
- const extraData = null == extra ? UNDEF : items(extra)
1482
+ const extraData = null == extra ? NONE : items(extra)
1137
1483
  .reduce((a, n) => (n[0].startsWith(S_DS) ? extraTransforms[n[0]] = n[1] : (a[n[0]] = n[1]), a), {});
1138
1484
  const dataClone = merge([
1139
- isempty(extraData) ? UNDEF : clone(extraData),
1485
+ isempty(extraData) ? NONE : clone(extraData),
1140
1486
  clone(data),
1141
1487
  ]);
1142
1488
  // Define a top level store that provides transform operations.
1143
- const store = {
1144
- // The inject function recognises this special location for the root of the source data.
1145
- // NOTE: to escape data that contains "`$FOO`" keys at the top level,
1146
- // place that data inside a holding map: { myholder: mydata }.
1147
- $TOP: dataClone,
1148
- $SPEC: () => origspec,
1149
- // Escape backtick (this also works inside backticks).
1150
- $BT: () => S_BT,
1151
- // Escape dollar sign (this also works inside backticks).
1152
- $DS: () => S_DS,
1153
- // Insert current date and time as an ISO string.
1154
- $WHEN: () => new Date().toISOString(),
1155
- $DELETE: transform_DELETE,
1156
- $COPY: transform_COPY,
1157
- $KEY: transform_KEY,
1158
- $ANNO: transform_ANNO,
1159
- $MERGE: transform_MERGE,
1160
- $EACH: transform_EACH,
1161
- $PACK: transform_PACK,
1162
- $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
+ },
1163
1513
  // Custom extra transforms, if any.
1164
- ...extraTransforms,
1165
- };
1514
+ extraTransforms,
1515
+ {
1516
+ $ERRS: errs,
1517
+ }
1518
+ ], 1);
1166
1519
  const out = inject(spec, store, injdef);
1520
+ const generr = (0 < size(errs) && !collect);
1521
+ if (generr) {
1522
+ throw new Error(join(errs, ' | '));
1523
+ }
1167
1524
  return out;
1168
1525
  }
1169
1526
  // A required string value. NOTE: Rejects empty strings.
1170
1527
  const validate_STRING = (inj) => {
1171
1528
  let out = getprop(inj.dparent, inj.key);
1172
1529
  const t = typify(out);
1173
- if (S_string !== t) {
1530
+ if (0 === (T_string & t)) {
1174
1531
  let msg = _invalidTypeMsg(inj.path, S_string, t, out, 'V1010');
1175
1532
  inj.errs.push(msg);
1176
- return UNDEF;
1533
+ return NONE;
1177
1534
  }
1178
1535
  if (S_MT === out) {
1179
1536
  let msg = 'Empty string at ' + pathify(inj.path, 1);
1180
1537
  inj.errs.push(msg);
1181
- return UNDEF;
1538
+ return NONE;
1182
1539
  }
1183
1540
  return out;
1184
1541
  };
1185
1542
  const validate_TYPE = (inj, _val, ref) => {
1186
- let tname = slice(ref, 1).toLowerCase();
1543
+ const tname = slice(ref, 1).toLowerCase();
1544
+ const typev = 1 << (31 - TYPENAME.indexOf(tname));
1187
1545
  let out = getprop(inj.dparent, inj.key);
1188
1546
  const t = typify(out);
1189
- if (t !== tname) {
1547
+ // console.log('TYPE', tname, typev, tn(typev), 'O=', t, tn(t), out, 'C=', t & typev)
1548
+ if (0 === (t & typev)) {
1190
1549
  inj.errs.push(_invalidTypeMsg(inj.path, tname, t, out, 'V1001'));
1191
- return UNDEF;
1550
+ return NONE;
1192
1551
  }
1193
1552
  return out;
1194
1553
  };
@@ -1204,17 +1563,17 @@ const validate_CHILD = (inj) => {
1204
1563
  const { mode, key, parent, keys, path } = inj;
1205
1564
  // Setup data structures for validation by cloning child template.
1206
1565
  // Map syntax.
1207
- if (S_MKEYPRE === mode) {
1566
+ if (M_KEYPRE === mode) {
1208
1567
  const childtm = getprop(parent, key);
1209
1568
  // Get corresponding current object.
1210
- const pkey = getprop(path, path.length - 2);
1569
+ const pkey = getelem(path, -2);
1211
1570
  let tval = getprop(inj.dparent, pkey);
1212
- if (UNDEF == tval) {
1571
+ if (NONE == tval) {
1213
1572
  tval = {};
1214
1573
  }
1215
1574
  else if (!ismap(tval)) {
1216
1575
  inj.errs.push(_invalidTypeMsg(slice(inj.path, -1), S_object, typify(tval), tval), 'V0220');
1217
- return UNDEF;
1576
+ return NONE;
1218
1577
  }
1219
1578
  const ckeys = keysof(tval);
1220
1579
  for (let ckey of ckeys) {
@@ -1223,58 +1582,62 @@ const validate_CHILD = (inj) => {
1223
1582
  keys.push(ckey);
1224
1583
  }
1225
1584
  // Remove $CHILD to cleanup ouput.
1226
- inj.setval(UNDEF);
1227
- return UNDEF;
1585
+ inj.setval(NONE);
1586
+ return NONE;
1228
1587
  }
1229
1588
  // List syntax.
1230
- if (S_MVAL === mode) {
1589
+ if (M_VAL === mode) {
1231
1590
  if (!islist(parent)) {
1232
1591
  // $CHILD was not inside a list.
1233
1592
  inj.errs.push('Invalid $CHILD as value');
1234
- return UNDEF;
1593
+ return NONE;
1235
1594
  }
1236
1595
  const childtm = getprop(parent, 1);
1237
- if (UNDEF === inj.dparent) {
1596
+ if (NONE === inj.dparent) {
1238
1597
  // Empty list as default.
1239
- parent.length = 0;
1240
- return UNDEF;
1598
+ // parent.length = 0
1599
+ slice(parent, 0, 0, true);
1600
+ return NONE;
1241
1601
  }
1242
1602
  if (!islist(inj.dparent)) {
1243
- 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');
1244
1604
  inj.errs.push(msg);
1245
- inj.keyI = parent.length;
1605
+ inj.keyI = size(parent);
1246
1606
  return inj.dparent;
1247
1607
  }
1248
1608
  // Clone children abd reset inj key index.
1249
1609
  // The inject child loop will now iterate over the cloned children,
1250
1610
  // validating them againt the current list values.
1251
- inj.dparent.map((_n, i) => parent[i] = clone(childtm));
1252
- parent.length = inj.dparent.length;
1611
+ items(inj.dparent, (n) => setprop(parent, n[0], clone(childtm)));
1612
+ slice(parent, 0, inj.dparent.length, true);
1253
1613
  inj.keyI = 0;
1254
1614
  const out = getprop(inj.dparent, 0);
1255
1615
  return out;
1256
1616
  }
1257
- return UNDEF;
1617
+ return NONE;
1258
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
1259
1622
  // Match at least one of the specified shapes.
1260
- // Syntax: ['`$ONE`', alt0, alt1, ...]okI
1623
+ // Syntax: ['`$ONE`', alt0, alt1, ...]
1261
1624
  const validate_ONE = (inj, _val, _ref, store) => {
1262
1625
  const { mode, parent, keyI } = inj;
1263
1626
  // Only operate in val mode, since parent is a list.
1264
- if (S_MVAL === mode) {
1627
+ if (M_VAL === mode) {
1265
1628
  if (!islist(parent) || 0 !== keyI) {
1266
1629
  inj.errs.push('The $ONE validator at field ' +
1267
1630
  pathify(inj.path, 1, 1) +
1268
1631
  ' must be the first element of an array.');
1269
1632
  return;
1270
1633
  }
1271
- inj.keyI = inj.keys.length;
1634
+ inj.keyI = size(inj.keys);
1272
1635
  // Clean up structure, replacing [$ONE, ...] with current
1273
1636
  inj.setval(inj.dparent, 2);
1274
1637
  inj.path = slice(inj.path, -1);
1275
1638
  inj.key = getelem(inj.path, -1);
1276
1639
  let tvals = slice(parent, 1);
1277
- if (0 === tvals.length) {
1640
+ if (0 === size(tvals)) {
1278
1641
  inj.errs.push('The $ONE validator at field ' +
1279
1642
  pathify(inj.path, 1, 1) +
1280
1643
  ' must have at least one argument.');
@@ -1284,7 +1647,7 @@ const validate_ONE = (inj, _val, _ref, store) => {
1284
1647
  for (let tval of tvals) {
1285
1648
  // If match, then errs.length = 0
1286
1649
  let terrs = [];
1287
- const vstore = { ...store };
1650
+ const vstore = merge([{}, store], 1);
1288
1651
  vstore.$TOP = inj.dparent;
1289
1652
  const vcurrent = validate(inj.dparent, tval, {
1290
1653
  extra: vstore,
@@ -1293,35 +1656,33 @@ const validate_ONE = (inj, _val, _ref, store) => {
1293
1656
  });
1294
1657
  inj.setval(vcurrent, -2);
1295
1658
  // Accept current value if there was a match
1296
- if (0 === terrs.length) {
1659
+ if (0 === size(terrs)) {
1297
1660
  return;
1298
1661
  }
1299
1662
  }
1300
1663
  // There was no match.
1301
- const valdesc = tvals
1302
- .map((v) => stringify(v))
1303
- .join(', ')
1304
- .replace(R_TRANSFORM_NAME, (_m, p1) => p1.toLowerCase());
1305
- 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'));
1306
1666
  }
1307
1667
  };
1308
1668
  const validate_EXACT = (inj) => {
1309
1669
  const { mode, parent, key, keyI } = inj;
1310
1670
  // Only operate in val mode, since parent is a list.
1311
- if (S_MVAL === mode) {
1671
+ if (M_VAL === mode) {
1312
1672
  if (!islist(parent) || 0 !== keyI) {
1313
1673
  inj.errs.push('The $EXACT validator at field ' +
1314
1674
  pathify(inj.path, 1, 1) +
1315
1675
  ' must be the first element of an array.');
1316
1676
  return;
1317
1677
  }
1318
- inj.keyI = inj.keys.length;
1678
+ inj.keyI = size(inj.keys);
1319
1679
  // Clean up structure, replacing [$EXACT, ...] with current data parent
1320
1680
  inj.setval(inj.dparent, 2);
1321
- 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);
1322
1683
  inj.key = getelem(inj.path, -1);
1323
1684
  let tvals = slice(parent, 1);
1324
- if (0 === tvals.length) {
1685
+ if (0 === size(tvals)) {
1325
1686
  inj.errs.push('The $EXACT validator at field ' +
1326
1687
  pathify(inj.path, 1, 1) +
1327
1688
  ' must have at least one argument.');
@@ -1340,12 +1701,10 @@ const validate_EXACT = (inj) => {
1340
1701
  return;
1341
1702
  }
1342
1703
  }
1343
- const valdesc = tvals
1344
- .map((v) => stringify(v))
1345
- .join(', ')
1346
- .replace(R_TRANSFORM_NAME, (_m, p1) => p1.toLowerCase());
1347
- inj.errs.push(_invalidTypeMsg(inj.path, (1 < inj.path.length ? '' : 'value ') +
1348
- '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'));
1349
1708
  }
1350
1709
  else {
1351
1710
  delprop(parent, key);
@@ -1354,7 +1713,7 @@ const validate_EXACT = (inj) => {
1354
1713
  // This is the "modify" argument to inject. Use this to perform
1355
1714
  // generic validation. Runs *after* any special commands.
1356
1715
  const _validation = (pval, key, parent, inj) => {
1357
- if (UNDEF === inj) {
1716
+ if (NONE === inj) {
1358
1717
  return;
1359
1718
  }
1360
1719
  if (SKIP === pval) {
@@ -1364,29 +1723,29 @@ const _validation = (pval, key, parent, inj) => {
1364
1723
  const exact = getprop(inj.meta, S_BEXACT, false);
1365
1724
  // Current val to verify.
1366
1725
  const cval = getprop(inj.dparent, key);
1367
- if (UNDEF === inj || (!exact && UNDEF === cval)) {
1726
+ if (NONE === inj || (!exact && NONE === cval)) {
1368
1727
  return;
1369
1728
  }
1370
1729
  const ptype = typify(pval);
1371
1730
  // Delete any special commands remaining.
1372
- if (S_string === ptype && pval.includes(S_DS)) {
1731
+ if (0 < (T_string & ptype) && pval.includes(S_DS)) {
1373
1732
  return;
1374
1733
  }
1375
1734
  const ctype = typify(cval);
1376
1735
  // Type mismatch.
1377
- if (ptype !== ctype && UNDEF !== pval) {
1378
- 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'));
1379
1738
  return;
1380
1739
  }
1381
1740
  if (ismap(cval)) {
1382
1741
  if (!ismap(pval)) {
1383
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0020'));
1742
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0020'));
1384
1743
  return;
1385
1744
  }
1386
1745
  const ckeys = keysof(cval);
1387
1746
  const pkeys = keysof(pval);
1388
1747
  // Empty spec object {} means object can be open (any keys).
1389
- if (0 < pkeys.length && true !== getprop(pval, '`$OPEN`')) {
1748
+ if (0 < size(pkeys) && true !== getprop(pval, '`$OPEN`')) {
1390
1749
  const badkeys = [];
1391
1750
  for (let ckey of ckeys) {
1392
1751
  if (!haskey(pval, ckey)) {
@@ -1394,8 +1753,8 @@ const _validation = (pval, key, parent, inj) => {
1394
1753
  }
1395
1754
  }
1396
1755
  // Closed object, so reject extra keys not in shape.
1397
- if (0 < badkeys.length) {
1398
- 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, ', ');
1399
1758
  inj.errs.push(msg);
1400
1759
  }
1401
1760
  }
@@ -1409,7 +1768,7 @@ const _validation = (pval, key, parent, inj) => {
1409
1768
  }
1410
1769
  else if (islist(cval)) {
1411
1770
  if (!islist(pval)) {
1412
- inj.errs.push(_invalidTypeMsg(inj.path, ptype, ctype, cval, 'V0030'));
1771
+ inj.errs.push(_invalidTypeMsg(inj.path, typename(ptype), ctype, cval, 'V0030'));
1413
1772
  }
1414
1773
  }
1415
1774
  else if (exact) {
@@ -1441,63 +1800,69 @@ injdef) {
1441
1800
  const extra = injdef?.extra;
1442
1801
  const collect = null != injdef?.errs;
1443
1802
  const errs = injdef?.errs || [];
1444
- const store = {
1445
- // Remove the transform commands.
1446
- $DELETE: null,
1447
- $COPY: null,
1448
- $KEY: null,
1449
- $META: null,
1450
- $MERGE: null,
1451
- $EACH: null,
1452
- $PACK: null,
1453
- $STRING: validate_STRING,
1454
- $NUMBER: validate_TYPE,
1455
- $BOOLEAN: validate_TYPE,
1456
- $OBJECT: validate_TYPE,
1457
- $ARRAY: validate_TYPE,
1458
- $FUNCTION: validate_TYPE,
1459
- $INSTANCE: validate_TYPE,
1460
- $ANY: validate_ANY,
1461
- $CHILD: validate_CHILD,
1462
- $ONE: validate_ONE,
1463
- $EXACT: validate_EXACT,
1464
- ...(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, {}),
1465
1830
  // A special top level value to collect errors.
1466
- // NOTE: collecterrs paramter always wins.
1467
- $ERRS: errs,
1468
- };
1469
- let meta = { [S_BEXACT]: false };
1470
- if (injdef?.meta) {
1471
- meta = merge([meta, injdef.meta]);
1472
- }
1831
+ // NOTE: collecterrs parameter always wins.
1832
+ {
1833
+ $ERRS: errs,
1834
+ }
1835
+ ], 1);
1836
+ let meta = getprop(injdef, 'meta', {});
1837
+ setprop(meta, S_BEXACT, getprop(meta, S_BEXACT, false));
1473
1838
  const out = transform(data, spec, {
1474
1839
  meta,
1475
1840
  extra: store,
1476
1841
  modify: _validation,
1477
- handler: _validatehandler
1842
+ handler: _validatehandler,
1843
+ errs,
1478
1844
  });
1479
- const generr = (0 < errs.length && !collect);
1845
+ const generr = (0 < size(errs) && !collect);
1480
1846
  if (generr) {
1481
- throw new Error('Invalid data: ' + errs.join(' | '));
1847
+ throw new Error(join(errs, ' | '));
1482
1848
  }
1483
1849
  return out;
1484
1850
  }
1485
1851
  const select_AND = (inj, _val, _ref, store) => {
1486
- if (S_MKEYPRE === inj.mode) {
1852
+ if (M_KEYPRE === inj.mode) {
1487
1853
  const terms = getprop(inj.parent, inj.key);
1488
1854
  const ppath = slice(inj.path, -1);
1489
1855
  const point = getpath(store, ppath);
1490
- const vstore = { ...store };
1856
+ const vstore = merge([{}, store], 1);
1491
1857
  vstore.$TOP = point;
1492
1858
  for (let term of terms) {
1493
- // setprop(term, '`$OPEN`', getprop(term, '`$OPEN`', true))
1494
1859
  let terrs = [];
1495
1860
  validate(point, term, {
1496
1861
  extra: vstore,
1497
1862
  errs: terrs,
1498
1863
  meta: inj.meta,
1499
1864
  });
1500
- if (0 != terrs.length) {
1865
+ if (0 != size(terrs)) {
1501
1866
  inj.errs.push('AND:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(terms));
1502
1867
  }
1503
1868
  }
@@ -1507,11 +1872,11 @@ const select_AND = (inj, _val, _ref, store) => {
1507
1872
  }
1508
1873
  };
1509
1874
  const select_OR = (inj, _val, _ref, store) => {
1510
- if (S_MKEYPRE === inj.mode) {
1875
+ if (M_KEYPRE === inj.mode) {
1511
1876
  const terms = getprop(inj.parent, inj.key);
1512
1877
  const ppath = slice(inj.path, -1);
1513
1878
  const point = getpath(store, ppath);
1514
- const vstore = { ...store };
1879
+ const vstore = merge([{}, store], 1);
1515
1880
  vstore.$TOP = point;
1516
1881
  for (let term of terms) {
1517
1882
  let terrs = [];
@@ -1520,7 +1885,7 @@ const select_OR = (inj, _val, _ref, store) => {
1520
1885
  errs: terrs,
1521
1886
  meta: inj.meta,
1522
1887
  });
1523
- if (0 === terrs.length) {
1888
+ if (0 === size(terrs)) {
1524
1889
  const gkey = getelem(inj.path, -2);
1525
1890
  const gp = getelem(inj.nodes, -2);
1526
1891
  setprop(gp, gkey, point);
@@ -1531,11 +1896,11 @@ const select_OR = (inj, _val, _ref, store) => {
1531
1896
  }
1532
1897
  };
1533
1898
  const select_NOT = (inj, _val, _ref, store) => {
1534
- if (S_MKEYPRE === inj.mode) {
1899
+ if (M_KEYPRE === inj.mode) {
1535
1900
  const term = getprop(inj.parent, inj.key);
1536
1901
  const ppath = slice(inj.path, -1);
1537
1902
  const point = getpath(store, ppath);
1538
- const vstore = { ...store };
1903
+ const vstore = merge([{}, store], 1);
1539
1904
  vstore.$TOP = point;
1540
1905
  let terrs = [];
1541
1906
  validate(point, term, {
@@ -1543,7 +1908,7 @@ const select_NOT = (inj, _val, _ref, store) => {
1543
1908
  errs: terrs,
1544
1909
  meta: inj.meta,
1545
1910
  });
1546
- if (0 == terrs.length) {
1911
+ if (0 == size(terrs)) {
1547
1912
  inj.errs.push('NOT:' + pathify(ppath) + S_VIZ + stringify(point) + ' fail:' + stringify(term));
1548
1913
  }
1549
1914
  const gkey = getelem(inj.path, -2);
@@ -1552,7 +1917,7 @@ const select_NOT = (inj, _val, _ref, store) => {
1552
1917
  }
1553
1918
  };
1554
1919
  const select_CMP = (inj, _val, ref, store) => {
1555
- if (S_MKEYPRE === inj.mode) {
1920
+ if (M_KEYPRE === inj.mode) {
1556
1921
  const term = getprop(inj.parent, inj.key);
1557
1922
  // const src = getprop(store, inj.base, store)
1558
1923
  const gkey = getelem(inj.path, -2);
@@ -1585,7 +1950,7 @@ const select_CMP = (inj, _val, ref, store) => {
1585
1950
  ' fail:' + ref + ' ' + stringify(term));
1586
1951
  }
1587
1952
  }
1588
- return UNDEF;
1953
+ return NONE;
1589
1954
  };
1590
1955
  // Select children from a top-level object that match a MongoDB-style query.
1591
1956
  // Supports $and, $or, and equality comparisons.
@@ -1596,10 +1961,13 @@ function select(children, query) {
1596
1961
  return [];
1597
1962
  }
1598
1963
  if (ismap(children)) {
1599
- 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
+ });
1600
1968
  }
1601
1969
  else {
1602
- 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]));
1603
1971
  }
1604
1972
  const results = [];
1605
1973
  const injdef = {
@@ -1638,9 +2006,9 @@ class Injection {
1638
2006
  this.val = val;
1639
2007
  this.parent = parent;
1640
2008
  this.errs = [];
1641
- this.dparent = UNDEF;
2009
+ this.dparent = NONE;
1642
2010
  this.dpath = [S_DTOP];
1643
- this.mode = S_MVAL;
2011
+ this.mode = M_VAL;
1644
2012
  this.full = false;
1645
2013
  this.keyI = 0;
1646
2014
  this.keys = [S_DTOP];
@@ -1654,7 +2022,7 @@ class Injection {
1654
2022
  toString(prefix) {
1655
2023
  return 'INJ' + (null == prefix ? '' : S_FS + prefix) + S_CN +
1656
2024
  pad(pathify(this.path, 1)) +
1657
- this.mode + (this.full ? '/full' : '') + S_CN +
2025
+ MODENAME[this.mode] + (this.full ? '/full' : '') + S_CN +
1658
2026
  'key=' + this.keyI + S_FS + this.key + S_FS + S_OS + this.keys + S_CS +
1659
2027
  ' p=' + stringify(this.parent, -1, 1) +
1660
2028
  ' m=' + stringify(this.meta, -1, 1) +
@@ -1665,11 +2033,11 @@ class Injection {
1665
2033
  this.meta.__d++;
1666
2034
  const parentkey = getelem(this.path, -2);
1667
2035
  // Resolve current node in store for local paths.
1668
- if (UNDEF === this.dparent) {
2036
+ if (NONE === this.dparent) {
1669
2037
  // Even if there's no data, dpath should continue to match path, so that
1670
2038
  // relative paths work properly.
1671
- if (1 < this.dpath.length) {
1672
- this.dpath = [...this.dpath, parentkey];
2039
+ if (1 < size(this.dpath)) {
2040
+ this.dpath = flatten([this.dpath, parentkey]);
1673
2041
  }
1674
2042
  }
1675
2043
  else {
@@ -1681,7 +2049,7 @@ class Injection {
1681
2049
  this.dpath = slice(this.dpath, -1);
1682
2050
  }
1683
2051
  else {
1684
- this.dpath = [...this.dpath, parentkey];
2052
+ this.dpath = flatten([this.dpath, parentkey]);
1685
2053
  }
1686
2054
  }
1687
2055
  }
@@ -1695,8 +2063,8 @@ class Injection {
1695
2063
  cinj.keyI = keyI;
1696
2064
  cinj.keys = keys;
1697
2065
  cinj.key = key;
1698
- cinj.path = [...(this.path || []), key];
1699
- cinj.nodes = [...(this.nodes || []), val];
2066
+ cinj.path = flatten([getdef(this.path, []), key]);
2067
+ cinj.nodes = flatten([getdef(this.nodes, []), [val]]);
1700
2068
  cinj.mode = this.mode;
1701
2069
  cinj.handler = this.handler;
1702
2070
  cinj.modify = this.modify;
@@ -1704,39 +2072,42 @@ class Injection {
1704
2072
  cinj.meta = this.meta;
1705
2073
  cinj.errs = this.errs;
1706
2074
  cinj.prior = this;
1707
- cinj.dpath = [...this.dpath];
2075
+ cinj.dpath = flatten([this.dpath]);
1708
2076
  cinj.dparent = this.dparent;
1709
2077
  return cinj;
1710
2078
  }
1711
2079
  setval(val, ancestor) {
2080
+ let parent = NONE;
1712
2081
  if (null == ancestor || ancestor < 2) {
1713
- return UNDEF === val ?
1714
- delprop(this.parent, this.key) :
2082
+ parent = NONE === val ?
2083
+ this.parent = delprop(this.parent, this.key) :
1715
2084
  setprop(this.parent, this.key, val);
1716
2085
  }
1717
2086
  else {
1718
2087
  const aval = getelem(this.nodes, 0 - ancestor);
1719
2088
  const akey = getelem(this.path, 0 - ancestor);
1720
- return UNDEF === val ?
2089
+ parent = NONE === val ?
1721
2090
  delprop(aval, akey) :
1722
2091
  setprop(aval, akey, val);
1723
2092
  }
2093
+ // console.log('SETVAL', val, this.key, this.parent)
2094
+ return parent;
1724
2095
  }
1725
2096
  }
1726
2097
  // Internal utilities
1727
2098
  // ==================
1728
- // Update all references to target in inj.nodes.
1729
- function _updateAncestors(_inj, target, tkey, tval) {
1730
- // SetProp is sufficient in TypeScript as target reference remains consistent even for lists.
1731
- setprop(target, tkey, tval);
1732
- }
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
+ // }
1733
2104
  // Build a type validation error message.
1734
2105
  function _invalidTypeMsg(path, needtype, vt, v, _whence) {
1735
2106
  let vs = null == v ? 'no value' : stringify(v);
1736
2107
  return 'Expected ' +
1737
- (1 < path.length ? ('field ' + pathify(path, 1) + ' to be ') : '') +
2108
+ (1 < size(path) ? ('field ' + pathify(path, 1) + ' to be ') : '') +
1738
2109
  needtype + ', but found ' +
1739
- (null != v ? vt + S_VIZ : '') + vs +
2110
+ (null != v ? typename(vt) + S_VIZ : '') + vs +
1740
2111
  // Uncomment to help debug validation errors.
1741
2112
  // ' [' + _whence + ']' +
1742
2113
  '.';
@@ -1745,14 +2116,14 @@ function _invalidTypeMsg(path, needtype, vt, v, _whence) {
1745
2116
  // call the function passing the injection inj. This is how transforms operate.
1746
2117
  const _injecthandler = (inj, val, ref, store) => {
1747
2118
  let out = val;
1748
- const iscmd = isfunc(val) && (UNDEF === ref || ref.startsWith(S_DS));
2119
+ const iscmd = isfunc(val) && (NONE === ref || ref.startsWith(S_DS));
1749
2120
  // Only call val function if it is a special command ($NAME format).
1750
2121
  // TODO: OR if meta.'$CALL'
1751
2122
  if (iscmd) {
1752
2123
  out = val(inj, val, ref, store);
1753
2124
  }
1754
2125
  // Update parent with value. Ensures references remain in node tree.
1755
- else if (S_MVAL === inj.mode && inj.full) {
2126
+ else if (M_VAL === inj.mode && inj.full) {
1756
2127
  inj.setval(val);
1757
2128
  }
1758
2129
  return out;
@@ -1800,9 +2171,9 @@ function _injectstr(val, store, inj) {
1800
2171
  }
1801
2172
  let pathref = m[1];
1802
2173
  // Special escapes inside injection.
1803
- pathref = 3 < pathref.length ?
1804
- pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS) :
1805
- pathref;
2174
+ if (3 < size(pathref)) {
2175
+ pathref = pathref.replace(R_BT_ESCAPE, S_BT).replace(R_DS_ESCAPE, S_DS);
2176
+ }
1806
2177
  // Get the extracted path reference.
1807
2178
  out = getpath(store, pathref, inj);
1808
2179
  }
@@ -1810,13 +2181,15 @@ function _injectstr(val, store, inj) {
1810
2181
  // Check for injections within the string.
1811
2182
  const partial = (_m, ref) => {
1812
2183
  // Special escapes inside injection.
1813
- 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
+ }
1814
2187
  if (inj) {
1815
2188
  inj.full = false;
1816
2189
  }
1817
2190
  const found = getpath(store, ref, inj);
1818
2191
  // Ensure inject value is a string.
1819
- 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);
1820
2193
  };
1821
2194
  out = val.replace(R_INJECTION_PARTIAL, partial);
1822
2195
  // Also call the inj handler on the entire string, providing the
@@ -1828,12 +2201,82 @@ function _injectstr(val, store, inj) {
1828
2201
  }
1829
2202
  return out;
1830
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
+ }
1831
2271
  class StructUtility {
1832
2272
  constructor() {
1833
2273
  this.clone = clone;
1834
2274
  this.delprop = delprop;
1835
2275
  this.escre = escre;
1836
2276
  this.escurl = escurl;
2277
+ this.filter = filter;
2278
+ this.flatten = flatten;
2279
+ this.getdef = getdef;
1837
2280
  this.getelem = getelem;
1838
2281
  this.getpath = getpath;
1839
2282
  this.getprop = getprop;
@@ -1846,13 +2289,14 @@ class StructUtility {
1846
2289
  this.ismap = ismap;
1847
2290
  this.isnode = isnode;
1848
2291
  this.items = items;
1849
- this.joinurl = joinurl;
2292
+ this.join = join;
1850
2293
  this.jsonify = jsonify;
1851
2294
  this.keysof = keysof;
1852
2295
  this.merge = merge;
1853
2296
  this.pad = pad;
1854
2297
  this.pathify = pathify;
1855
2298
  this.select = select;
2299
+ this.setpath = setpath;
1856
2300
  this.setprop = setprop;
1857
2301
  this.size = size;
1858
2302
  this.slice = slice;
@@ -1860,10 +2304,32 @@ class StructUtility {
1860
2304
  this.stringify = stringify;
1861
2305
  this.transform = transform;
1862
2306
  this.typify = typify;
2307
+ this.typename = typename;
1863
2308
  this.validate = validate;
1864
2309
  this.walk = walk;
1865
- this.jo = jo;
1866
- 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;
1867
2333
  }
1868
2334
  }
1869
2335
  exports.StructUtility = StructUtility;