-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2109 lines (1835 loc) · 77.3 KB
/
index.js
File metadata and controls
2109 lines (1835 loc) · 77.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// #region F I L E
// <copyright file="mcode-data/index.js" company="MicroCODE Incorporated">Copyright © 2022-2024 MicroCODE, Inc. Troy, MI</copyright><author>Timothy J. McGuire</author>
// #region M O D U L E
// #region D O C U M E N T A T I O N
/**
* Project: MicroCODE MERN Applications
* Customer: Internal + MIT xPRO Course
* @module 'mcode-data.js'
* @memberof mcode
* @created January 2022-2024
* @author Timothy McGuire, MicroCODE, Inc.
* @description >
* MicroCODE Common Data Utitlities
*
* LICENSE:
* --------
* MIT License: MicroCODE.mcode-data
*
* Copyright (c) 2022-2025 Timothy McGuire, MicroCODE, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* DESCRIPTION:
* ------------
* This module implements the MicroCODE's Common JavaScript functions for data handling.
*
*
* REFERENCES:
* -----------
* 1. MIT xPRO Course: Professional Certificate in Coding: Full Stack Development with MERN.
*
* 2. LADDERS® source code: MACRO-11, MACRO-32, C#, and JavaScript.
*
*
*
*
* MODIFICATIONS:
* --------------
* Date: By-Group: Rev: Description:
*
* 30-Jan-2024 TJM-MCODE {0001} New module for common reusable JavaScript data handling functions.
* 01-Feb-2024 TJM-MCODE {0002} Changed to the Universal Module Definition (UMD) pattern to support AMD,
* CommonJS/Node.js, and browser global in our exported module.
* 01-Feb-2024 TJM-MCODE {0003} Swap() and Call() now throw an error if the 'keys' and 'values' lists are not the same length,
* instead of logging the error and returning a default value.
* 22-Aug-2024 TJM-MCODE {0004} Corrected isJson() to rely on 1st character being '{' to determine JSON string
* it was returning true for any string that contained a '{' character,
* this was signaling 'true' for HTMX templates that contained '{{variable}}'.
* 05-Oct-2024 TJM-MCODE {0005} Added 'uuidDecode()' function to decode UUID strings into their component parts.
*
* 19-Feb-2025 TJM-MCODE {0006} v0.5.08 - updated 'httpStatus()' to use a STATIC copy of HTTP codes JSON for speed.
* - updated all UUID string lists to STATIC as well.
* 17-Apr-2025 TJM-MCODE {0007} v0.5.09 - added 'isHtml()' function to check if a string is HTML,
* updated 'isJson()' to use same check.
* 23-Oct-2025 TJM-MCODE {0008} v0.6.03 - added 'classExport()' to return the created class constructor to support SSR
* and ESM module loading, especially in HTMX applications.
* Also added: sleep(), ifNumber(), encodeJson(), generateRandomId().
*
*
*
* NOTE: This module follows MicroCODE's JavaScript Style Guide and Template JS file, see:
*
* o https://github.com/MicroCODEIncorporated/JavaScriptSG
* o https://github.com/MicroCODEIncorporated/TemplatesJS
*
*/
// #endregion
// #region I M P O R T S
// #endregion
// #region T Y P E S
// #endregion
// #region I N T E R F A C E S
// #endregion
// #region C O N S T A N T S, F U N C T I O N S – P U B L I C
// MicroCODE: define this module's name for our 'mcode-log' package
const MODULE_NAME = 'mcode-data.js';
// Static copy of HTTP codes for httpStatus() function for speed - {0006}
const HTTP_CODES =
{
//1xx: Informational responses (CYAN)
"100": "Continue",
"101": "Switching Protocols",
"102": "Processing",
"103": "Early Hints",
"104": "Checkpoint (WebDAV)",
"105": "Switch Proxy (WebDAV)",
"106": "Processing (WebDAV)",
"107": "Handoff (WebDAV)",
//2xx: Success responses (GREEN)
"200": "OK", // for READ
"201": "Created", //for CREATE
"202": "Accepted", // for PUT/PATCH/DELETE
"203": "Non-Authoritative Information",
"204": "No Content",
"205": "Reset Content",
"206": "Partial Content",
"207": "Multi-Status",
"208": "Already Reported",
"226": "IM Used",
//3xx: Redirection responses (YELLOW)
"300": "Multiple Choices",
"301": "Moved Permanently",
"302": "Found",
"303": "See Other",
"304": "Not Modified",
"305": "Use Proxy",
"307": "Temporary Redirect",
"308": "Permanent Redirect",
"309": "Resume Incomplete (WebDAV)",
"310": "Too Many Redirects",
//4xx: Client error responses (RED)
"400": "Bad Request", // missing Record Fields during CREATE or PUT
"401": "Unauthorized",
"402": "Payment Required",
"403": "Forbidden",
"404": "Not Found", // no record to update during PATCH or PUT
"405": "Method Not Allowed",
"406": "Not Acceptable",
"407": "Proxy Authentication Required",
"408": "Request Timeout",
"409": "Conflict",
"410": "Gone",
"411": "Length Required",
"412": "Precondition Failed",
"413": "Payload Too Large",
"414": "URI Too Long",
"415": "Unsupported Media Type",
"416": "Range Not Satisfiable",
"417": "Expectation Failed",
"418": "I'm a Teapot", // indicates that the server refuses to brew coffee because it is a teapot. (An April fool’s joke from 1998)
"419": "Page Expired (Laravel)",
"421": "Misdirected Request",
"422": "Unprocessable Entity",
"423": "Locked",
"424": "Failed Dependency",
"425": "Too Early",
"426": "Upgrade Required",
"428": "Precondition Required",
"429": "Too Many Requests",
"431": "Request Header Fields Too Large",
"440": "Login Timeout (Microsoft)",
"444": "Connection Closed Without Response (NGINX)",
"449": "Retry With (Microsoft - IIS specific)",
"450": "Blocked by Windows Parental Controls (Microsoft)",
"451": "Unavailable For Legal Reasons",
"499": "Client Closed Request (NGINX)",
//5xx: Server error responses (MAGENTA)
"500": "Internal Server Error", // unexpected Code Exceptions
"501": "Not Implemented", // hit stubs or calls to non-existent endpoints
"502": "Bad Gateway",
"503": "Service Unavailable",
"504": "Gateway Timeout",
"505": "HTTP Version Not Supported",
"506": "Variant Also Negotiates",
"507": "Insufficient Storage",
"508": "Loop Detected",
"509": "Bandwidth Limit Exceeded (Apache/cPanel)",
"510": "Not Extended",
"511": "Network Authentication Required",
"520": "Unknown Error (Cloudflare)",
"521": "Web Server Is Down (Cloudflare)",
"522": "Connection Timed Out (Cloudflare)",
"523": "Origin Is Unreachable (Cloudflare)",
"524": "A Timeout Occurred (Cloudflare)",
"525": "SSL Handshake Failed (Cloudflare)",
"526": "Invalid SSL Certificate (Cloudflare)",
"527": "Railgun Error (Cloudflare)",
"530": "Origin DNS Error (Cloudflare-FTP)",
"598": "Network Read Timeout Error (Unofficial)",
"599": "Network Connect Timeout Error (Azure/AWS)",
};
// U U I D - V A R I A N T S
const UUID_VARIANTS = [
"NCS compatibility",
"NCS compatibility",
"RFC 4122, RFC 9562",
"Microsoft GUIDs",
];
// U U I D - V E R S I O N S
// NCS compatibility (variant 0, 1)
const UUID_VAR1_VERSIONS = [
"Undefined / Reserved / NIL", // 0
" NCS Security Version", // 1
" NCS Security Version", // 2
" NCS Security Version", // 3
" NCS Security Version", // 4
" NCS Security Version", // 5
" NCS Security Version", // 6
" NCS Security Version", // 7
" NCS Security Version", // 8
" NCS Security Version", // 9
" NCS Security Version", // 10
" NCS Security Version", // 11
" NCS Security Version", // 12
" NCS Security Version", // 13
" NCS Security Version", // 14
"Undefined / Reserved / MAX", // 15
];
// RFC 4122 (Leach-Salz) (variant 2)
const UUID_VAR2_VERSIONS = [
"Undefined / Reserved / NIL", // 0
"Gregorian Unordered Timestamp", // 1
"DCE Security (POSIX)", // 2
"Name-Based (MD5 Hash)", // 3
"Random-Based Number", // 4
"Name Based (SHA-1 Hash)", // 5
"Gregorian Ordered Timestamp", // 6
"Unix Epoch Timestamp", // 7
"Custom Encoding Format", // 8
"Reserved for future defnition", // 9
"Reserved for future defnition", // 10
"Reserved for future defnition", // 11
"Reserved for future defnition", // 12
"Reserved for future defnition", // 13
"Reserved for future defnition", // 14
"Undefined / Reserved / MAX", // 15
];
// Microsoft GUIDs (variant 3)
const UUID_VAR3_VERSIONS = [
"Undefined / Reserved / NIL", // 0
"Microsoft GUID Version 1", // 1
"Microsoft GUID Version 2", // 2
"Microsoft GUID Version 3", // 3
"Microsoft GUID Version 4", // 4
"Microsoft GUID Version 5", // 5
"Microsoft GUID Version 6", // 6
"Microsoft GUID Version 7", // 7
"Microsoft GUID Version 8", // 8
"Microsoft GUID Version 9", // 9
"Microsoft GUID Version 10", // 10
"Microsoft GUID Version 11", // 11
"Microsoft GUID Version 12", // 12
"Microsoft GUID Version 13", // 13
"Microsoft GUID Version 14", // 14
"Undefined / Reserved / MAX", // 15
];
/**
* @namespace mcode
* @desc mcode namespace containing functions and constants.
*/
const mcode = {
/**
* @func property
* @memberof mcode
* @desc Creates a property with get, set methods, validator, and on change events.
* @api public
* @param {object} options optional params to define the property
* {initial: value, readonly: boolean, immutable: boolean, validator: function, onChange: function}.
* @returns {object} a property object with get, set, type, reset, isReadOnly, and isImmutable methods.
*/
property: function (options = {})
{
// internal variables
const _initial = options?.initial;
const _readonly = options.readonly || false;
const _immutable = options.immutable || false;
// optional functions
const _validator = options.validator || function () {return true;};
const _onChange = options.onChange || function () {};
// the actual value of the property
let _value = options.initial || undefined;
return {
get: function ()
{
return _value;
},
set: function (value)
{
if (_immutable && (_value !== undefined))
{
throw new Error('「mcode.property」 This property is immutable.');
}
if (_readonly)
{
throw new Error('「mcode.property」 This property is read-only.');
}
if (_validator(value))
{
const _last = _value;
_value = value;
_onChange(_last, _value);
}
else
{
throw new Error('「mcode.property」 Invalid property value.');
}
},
type: function ()
{
return typeof _value;
},
reset: function ()
{
const _last = _value;
_value = _initial;
_onChange(_last, _value);
},
isReadOnly: function ()
{
return _readonly;
},
isImmutable: function ()
{
return _immutable;
},
hasChanged: function ()
{
return _value !== _initial;
}
};
},
/**
* @func getProperty
* @memberof mcode
* @api private
* @desc Safely resolve a nested property using an array of keys.
* @param {object} source - Root object from which to read.
* @param {Array<string>} path - Ordered list of keys to traverse.
* @returns {any} Resolved value or undefined when not found.
*/
getProperty: function (source, path)
{
return path.reduce((keyPath, key) =>
{
if (keyPath && Object.prototype.hasOwnProperty.call(keyPath, key))
{
return keyPath[key];
}
return undefined;
}, source);
},
/**
* @func setProperty
* @memberof mcode
* @desc Assign a nested property on the target object, creating scopes as needed.
* @api private
* @param {object} target - Object receiving the assignment.
* @param {Array<string>} path - Ordered list of keys to reach the leaf property.
* @param {any} value - Value to assign at the terminal path segment.
* @returns {void}
*/
setProperty: function (target, path, value)
{
let current = target;
for (let index = 0; index < path.length - 1; index += 1)
{
const key = path[index];
if (!current[key] || typeof current[key] !== 'object')
{
current[key] = {};
}
current = current[key];
}
current[path[path.length - 1]] = value;
},
/**
* @func contextProperty
* @memberof mcode
* @desc Define a getter/setter proxy that syncs instance properties to context paths.
* @api public
* @param {Class} instance - Class instance being updated, must have a 'context' object and 'syncDomContext()' method.
* @param {string} property - Property name exposed on the instance.
* @param {Array<string>} path - Path segments within the context object.
* @param {object} [options] - Optional configuration flags.
* @param {boolean} [options.sync=true] - Whether to resync the DOM context when setting.
* @returns {void}
*/
contextProperty: function (instance, property, path, options = {})
{
const {sync = true} = options;
if (!instance || typeof instance !== 'object')
{
throw new Error('[mcode] Invalid instance provided to contextProperty.');
}
if (!instance.syncDomContext || typeof instance.syncDomContext !== 'function')
{
throw new Error('[mcode] Invalid syncDomContext() method provided to contextProperty.');
}
if (!instance.context || typeof instance.context !== 'object')
{
throw new Error('[mcode] Invalid context object provided to contextProperty.');
}
Object.defineProperty(instance, property, {
configurable: true,
enumerable: false,
get()
{
return mcode.getProperty(instance?.context, path);
},
set(value)
{
mcode.setProperty(instance?.context, path, value);
if (sync)
{
instance?.syncDomContext();
}
}
});
},
/**
* @func isString
* @memberof mcode
* @desc Checks whether or not a object is a JS String.
* @api public
* @param {object} jsObject JavaScript object to be tested
* @returns {boolean} a value indicating whether or not the object is a STRING.
*/
isString: function (jsObject)
{
return Object.prototype.toString.call(jsObject) === '[object String]';
},
/**
* @method isObject
* @memberof mcode
* @desc Checks whether or not a object is a JS Object.
* @api public
* @param {object} jsObject JavaScript object to be tested
* @returns {boolean} a value indicating whether or not the object is an OBJECT.
*/
isObject: function (jsObject)
{
if (mcode.isString(jsObject)) return false;
return typeof jsObject === 'object' && jsObject !== null && !Array.isArray(jsObject) && typeof jsObject !== 'function';
},
/**
* @method isArray
* @memberof mcode
* @desc Checks whether or not an object is a JS Array.
* @api public
* @param {object} jsObject JavaScript object to be tested
* @returns {boolean} a value indicating whether or not the object is an ARRAY.
*/
isArray: function (jsObject)
{
return Array.isArray(jsObject);
},
/**
* @method isFunction
* @memberof mcode
* @desc Checks whether or not an object is a JS Function.
* @api public
* @param {object} jsObject JavaScript object to be tested
* @returns {boolean} a value indicating whether or not the object is a FUNCTION.
*/
isFunction: function (jsObject)
{
if (mcode.isString(jsObject)) return false;
return typeof jsObject === 'function';
},
/**
* @func isNumber
* @memberof mcode
* @desc Checks whether or not an object is a JS Number and *not* NaN.
* @api public
* @param {any} numberToCheck as a number of some type
* @returns {boolean} a value indicating whether or not the object is valid Number.
*/
isNumber: function (numberToCheck)
{
// NOTE: this compare will fail for NaN
// eslint-disable-next-line no-self-compare
return (typeof numberToCheck === 'number') && (numberToCheck === numberToCheck);
},
/**
* @function ifNumber
* @memberof mcode
* @desc Checks if a value is a valid number; if not, returns a default value.
* @param {number} value The value to check.
* @param {number} defaultValue The default value to return if the check fails.
* @returns {number} The original value if valid, otherwise the default value.
*/
ifNumber: function (value, defaultValue = 0)
{
return Number.isFinite(value) ? value : defaultValue;
},
/**
* @func isNaN
* @memberof mcode
* @desc Checks whether or not an object is a double-precision 'Not-a-Number (Nan)'.
* @api public
* @param {any} numberToCheck as a number of some type
* @returns {boolean} a value indicating whether or not the object is NaN.
*/
isNaN: function (numberToCheck)
{
// NOTE: this compare will always be true for NaN, and only for NaN
// eslint-disable-next-line no-self-compare
return (numberToCheck !== numberToCheck);
},
/**
* @func isJson
* @memberof mcode
* @desc Quickly checks a string for embedded JSON data.
* @api public
* @param {object} object string to be tested
* @returns {boolean} a value indicating whether or not the object is a JSON string.
*/
isJson: function (object)
{
try
{
if (typeof object !== 'string') return false;
// if this string begins with '{' and ends with '}' its very likely legal JSON code
const trimmed = object.trim();
return trimmed.startsWith('{') && trimmed.endsWith('}');
}
catch
{
return false; // *not* JSON and not parsable
}
},
/**
* @func isHtml
* @memberof mcode
* @desc Quickly checks a string for HTML content.
* @api public
* @param {object} object string to be tested
* @returns {boolean} a value indicating whether or not the object is HTML string.
*/
isHtml: function (object)
{
try
{
if (typeof object !== 'string') return false;
// if this string begins with '<' and ends with '>' its very likely legal HTML code
const trimmed = object.trim();
return trimmed.startsWith('<') && trimmed.endsWith('>');
}
catch
{
return false; // *not* HTML and not parsable
}
},
/**
* @func isDomAvailable
* @memberof mcode
* @desc Determine whether DOM APIs are available in the current environment.
* @api public
* @returns {boolean} True when document access is supported.
*/
isDomAvailable: function ()
{
return typeof document !== 'undefined' && typeof document.getElementById === 'function';
},
/**
* @func isUndefined
* @memberof mcode
* @desc Checks whether or not an object is a 'undefined'.
* @api public
* @param {any} objectToCheck as a variable of some type
* @returns {boolean} a value indicating whether or not the object is UNDEFINED.
*/
isUndefined: function (objectToCheck)
{
// return true if 'objectToCheck' is UNDEFINED or NULL
return ((typeof objectToCheck === 'undefined') || (objectToCheck === null));
},
/**
* @func isDate
* @memberof mcode
* @desc Checks whether or not an object is a JS Date.
* @param {object} objectToCheck
* @returns {boolean} a value indicating whether or not the object is a DATE.
*/
isDate: function (objectToCheck)
{
// return true if 'objectToCheck' is DATE Value
return (objectToCheck instanceof Date);
},
/**
* @func isTimeStamp
* @memberof mcode
* @desc Checks whether or not an object is a Timestampe, i.e.: a JS Date.
* @param {object} objectToCheck
* @returns {boolean} a value indicating whether or not the object is a TIMESTAMP.
*/
isTimeStamp: function (objectToCheck)
{
// return true if 'objectToCheck' is DATE/TIMESTAMP Value
return (objectToCheck instanceof Date);
},
/**
* @func octify
* @memberof mcode
* @desc Converts a string to an octal string.
* @api public
* @param {string} text - The string to be converted to an octal string of bytes.
* @returns {string} The octal string.
* @example
* mcode.octify('Hello, World!'); // returns: "110 145 154 154 157 54 40 127 157 162 154 144 41"
*/
octify(text)
{
const buffer = Buffer.from(text, 'utf8');
// Convert each byte to its octal representation
const octArray = [...buffer].map((byte) => byte.toString(8).padStart(3, '0'));
// Join the octal values into a string separated by spaces
return octArray.join(' ');
},
/**
* @func hexify
* @memberof mcode
* @desc Converts a string to a hexadecinal string of bytes.
* @api public
* @param {string} text the string to be converted to a hex string.
* @returns {string} the hex string.
* @example
* mcode.hexify('Hello, World!'); // returns: "48 65 6c 6c 6f 2c 20 57 6f 72 6c 64 21"
*/
hexify(text)
{
const buffer = Buffer.from(text, 'utf8');
const hex = buffer.toString('hex');
// Format the hex string into groups of 2 characters (1 byte)
return hex.match(/.{1,2}/g).join(' ');
},
/**
* @func default
* @memberof mcode
* @desc Evaluates a param and returns a default if the param is null, undefined,
* or empty (strings, arrays, objects, or primitives).
* @api public
* @param {any} anyItem The JavaScript entity being tested.
* @param {any} defaultItem The item to be returned if 'anyItem' is null, undefined, or empty.
* @returns {any} The original item or the default if empty/null/undefined.
* @example
* err = mcode.default(err, 'Undefined error occurred'); // default to recognizable message
* data = mcode.default(data, []); // Default to empty array
* config = mcode.default(config, {}); // Default to empty object
* count = mcode.default(count, 1); // Default to 1 if count is 0
*
* log(mcode.default(undefined, 'Default')); // 'Default'
* log(mcode.default(null, 'Default')); // 'Default'
* log(mcode.default('', 'Default')); // 'Default'
* log(mcode.default(0, 1)); // 1 (0 is 'empty', returns default)
* log(mcode.default(42, 1)); // 42 (non-zero number, returns original)
* log(mcode.default([], [])); // []
* log(mcode.default(['item'], ['default'])); // ['item']
* log(mcode.default({}, {})); // {}
* log(mcode.default({ key: 'value' }, { def: 'default' }));
* // { key: 'value' }
* log(mcode.default(true, false)); // true
* log(mcode.default('Hello', 'Default')); // 'Hello'
*/
default(anyItem, defaultItem)
{
// handle null, undefined, or empty values
if (anyItem === null || anyItem === undefined)
{
return defaultItem;
}
// handle empty strings
if (typeof anyItem === 'string' && anyItem === '')
{
return defaultItem;
}
// handle unassigned values (0 is treated as 'unassigned')
if (typeof anyItem === 'number' && anyItem === 0)
{
return defaultItem;
}
// handle empty arrays
if (Array.isArray(anyItem) && anyItem.length === 0)
{
return defaultItem;
}
// Handle empty objects (excluding null prototypes or non-object types)
if (typeof anyItem === 'object' && anyItem !== null && Object.keys(anyItem).length === 0)
{
return defaultItem;
}
// return the original item for all other cases (primitives, non-empty arrays/objects, etc.)
return anyItem;
},
/**
* @func extractId
* @memberof mcode
* @desc Extracts an alpha-numberic ID Field from a string, intended to be a unique portion of a common string.
* @param {string} objectName typically a file name, but can be any string, to extract an ID Field from.
* @returns {string} the extracted ID Field.
*
* @example
*
* Rules for extracting the ID Field:
*
* 1. The ID Field is assumed to be the first alpha-numeric field in the string.
* 2. The ID Field is assumed to be Letters + Numbers, with no spaces or special characters.
* 3. The ID Field is assumed to be either at the beginning or end of the string, or separated by non-alpha-numeric characters.
* 4. The ID Field could have lowercase 'placeholders' for numbers, like 'PxCy' or 'PnCn' for 'P1C2'.
*
* const str1 = "CG_BRKE01_20231116.L5K";
* const str2 = "CG_BRKE03_20231116.L5K";
*
* log(extractIdField(str1)); // Expected output: "BRKE01"
* log(extractIdField(str2)); // Expected output: "BRKE03"
*
* const str1 = "EP_GPT13TZ1_20231115_0800.L5K";
* const str2 = "EP_GPT13TZ2_20231113_1600.L5K";
*
* log(extractIdField(str1)); // Expected output: "GPT13TZ1"
* log(extractIdField(str2)); // Expected output: "GPT13TZ2"
*
* const str1 = "SEP_P1C2_GMP_ARL.L5K";
* const str2 = "SEP_P3C0_GMP_ARL.L5K";
*
* log(extractIdField(str1)); // Expected output: "P1C2"
* log(extractIdField(str2)); // Expected output: "P3C0"
*
* const str1 = "SEP_P1C2_GMP_ARL.L5K";
* const str2 = "SEP_PxCy_GMP.L5K";
*
* log(extractIdField(str1)); // Expected output: "P1C2"
* log(extractIdField(str2)); // Expected output: "PxCy"
*
*/
extractId: function (objectName)
{
let idField = '';
let inAlphaNumeric = false;
let isLetter = false;
let isLowerL = false;
let isNumber = false;
let hasLetters = false;
let hasNumbers = false;
let si = 0;
// ƒ to check for upper case letter
const isUpper = (objectName, i) =>
{
// if 'i' is outside 'objectName' return false
if (i < 0 || i >= objectName.length)
{
return false;
}
return (objectName[i] >= 'A' && objectName[i] <= 'Z');
};
// scan the string for the first alpha-numeric field
for (let i = 0; i < objectName.length; i++)
{
isNumber = (objectName[i] >= '0' && objectName[i] <= '9');
isLetter = (objectName[i] >= 'A' && objectName[i] <= 'Z');
isLowerL = (objectName[i] >= 'a' && objectName[i] <= 'z');
if (isNumber || isLetter || isLowerL)
{
if (!inAlphaNumeric)
{
inAlphaNumeric = true;
si = i;
}
idField += objectName[i];
hasLetters = hasLetters || isLetter || isLowerL;
hasNumbers = hasNumbers || isNumber;
// Check for 'lower case numeric placeholder' like 'PxCy' or 'PnCn' for 'P1C2'
if (isUpper(objectName, i - 1) && isUpper(objectName, i + 1) && isLowerL)
{
hasNumbers = true; // treat the single lower case letter between upper case letters as a number placeholder
}
}
else
{
// hit non Alpha-Numeric character
if (inAlphaNumeric && hasLetters && hasNumbers)
{
idField = objectName.substring(si, i);
break; // we have the field we want, exit to return it
}
else
{
// current field does not meet criteria, reset and continue
si = 0;
idField = '';
inAlphaNumeric = false;
hasLetters = false;
hasNumbers = false;
}
}
}
return idField || '';
},
/**
* @func httpStatus
* @memberof mcode
* @desc Returns the text for a given HTTP status code.
* @param {var} httpCode the HTTP status code to translate.
* @returns {string} a value representing the English meaning of a HTTP status code, formatted for display.
*/
httpStatus: function (httpCode)
{
// return the translated HTTP status code
// example: `[HTTP] 404: Not Found`
return (`[HTTP] ${httpCode}: ` + HTTP_CODES[httpCode] || 'Unknown HTTP Status');
},
/**
* @func httpSeverity
* @memberof mcode
* @desc Returns the mcode.log() severity (as text) for a given HTTP status code.
* @param {var} httpCode the HTTP status code to translate.
* @returns {string} a value representing the text name for logging the proper severity.
*/
httpSeverity: function (httpCode)
{
if (httpCode >= 500)
{
return 'fatal'; // these severity must match mcode.log() definitions and app-banner.module.css
}
else if (httpCode >= 400)
{
return 'error';
}
else if (httpCode >= 300)
{
return 'warning';
}
else if (httpCode >= 200)
{
return 'success';
}
else if (httpCode >= 100)
{
return 'info';
}
return 'none';
},
/**
* @func uuidDecode
* @memberof mcode
* @desc Decodes a UUID string into its component parts, this supports RFC 4122 and RFC 9562 UUIDs.
* @param {string} uuid a UUID string in the format 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
* @param {boolean} localTime a flag to indicate if the timestamp should be converted to local time for display.
* @returns {string} a JSON object containing the decoded UUID parts.
*/
uuidDecode: function (uuid, localTime = false)
{
if (typeof uuid !== 'string' || !/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(uuid))
{
return { error: 'Invalid UUID format' };
}
// L I S T S - by UUID Variant and their Versions
// ƒ Table of UUID Variants
const uuidVariants = [
uuidvar1, // NCS compatibility
uuidvar1, // NCS compatibility
uuidvar2, // RFC 4122, RFC 9562
uuidvar3, // Microsoft GUIDs
];
// ƒ Table of UUID Layouts for Variant #0/1 (NCS compatibility)
const uuidvar1Layouts = [
uuidvarNIL,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvar1reserved,
uuidvarMAX,
];
// ƒ Table of UUID Layouts for Variant #2 (RFC 4122, RFC 9562)
const uuidvar2Layouts = [
uuidvarNIL,
uuidvar2v1,
uuidvar2v2,
uuidvar2v3,
uuidvar2v4,
uuidvar2v5,
uuidvar2v6,
uuidvar2v7,
uuidvar2v8,
uuidvar2reserved,
uuidvar2reserved,
uuidvar2reserved,
uuidvar2reserved,
uuidvar2reserved,
uuidvar2reserved,
uuidvarMAX
];
// ƒ Table of UUID Layouts for Variant #3 (GUID)
const uuidvar3Layouts = [
uuidvarNIL,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvar3reserved,
uuidvarMAX,
];
// L A Y O U T S - by UUID Variant and their Versions
// ƒ UUID Variant #0 and #1 - NCS compatibility