@questwork/q-utilities 0.1.17 → 0.1.18

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,3629 +0,0 @@
1
- (function webpackUniversalModuleDefinition(root, factory) {
2
- if(typeof exports === 'object' && typeof module === 'object')
3
- module.exports = factory();
4
- else if(typeof define === 'function' && define.amd)
5
- define([], factory);
6
- else {
7
- var a = factory();
8
- for(var i in a) (typeof exports === 'object' ? exports : root)[i] = a[i];
9
- }
10
- })(this, () => {
11
- return /******/ (() => { // webpackBootstrap
12
- /******/ "use strict";
13
- /******/ // The require scope
14
- /******/ var __webpack_require__ = {};
15
- /******/
16
- /************************************************************************/
17
- /******/ /* webpack/runtime/define property getters */
18
- /******/ (() => {
19
- /******/ // define getter functions for harmony exports
20
- /******/ __webpack_require__.d = (exports, definition) => {
21
- /******/ for(var key in definition) {
22
- /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
23
- /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
24
- /******/ }
25
- /******/ }
26
- /******/ };
27
- /******/ })();
28
- /******/
29
- /******/ /* webpack/runtime/hasOwnProperty shorthand */
30
- /******/ (() => {
31
- /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
32
- /******/ })();
33
- /******/
34
- /******/ /* webpack/runtime/make namespace object */
35
- /******/ (() => {
36
- /******/ // define __esModule on exports
37
- /******/ __webpack_require__.r = (exports) => {
38
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
39
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
40
- /******/ }
41
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
42
- /******/ };
43
- /******/ })();
44
- /******/
45
- /************************************************************************/
46
- var __webpack_exports__ = {};
47
- // ESM COMPAT FLAG
48
- __webpack_require__.r(__webpack_exports__);
49
-
50
- // EXPORTS
51
- __webpack_require__.d(__webpack_exports__, {
52
- ApiResponse: () => (/* reexport */ ApiResponse),
53
- AwsStsS3Client: () => (/* reexport */ AwsStsS3Client),
54
- KeyValueObject: () => (/* reexport */ KeyValueObject),
55
- Metadata: () => (/* reexport */ Metadata),
56
- QMeta: () => (/* reexport */ QMeta),
57
- Repo: () => (/* reexport */ Repo),
58
- Service: () => (/* reexport */ Service),
59
- TemplateCompiler: () => (/* reexport */ TemplateCompiler),
60
- TenantAwareEntity: () => (/* reexport */ TenantAwareEntity),
61
- TrackedEntity: () => (/* reexport */ TrackedEntity),
62
- UniqueKeyGenerator: () => (/* reexport */ UniqueKeyGenerator),
63
- authorize: () => (/* reexport */ authorize),
64
- changeCreatorOwner: () => (/* reexport */ changeCreatorOwner),
65
- concatStringByArray: () => (/* reexport */ concatStringByArray),
66
- convertString: () => (/* reexport */ convertString),
67
- escapeRegex: () => (/* reexport */ escapeRegex),
68
- expressHelper: () => (/* reexport */ expressHelper),
69
- extractEmails: () => (/* reexport */ extractEmails),
70
- formatDate: () => (/* reexport */ formatDate),
71
- generalPost: () => (/* reexport */ generalPost),
72
- getValidation: () => (/* reexport */ getValidation),
73
- getValueByKeys: () => (/* reexport */ getValueByKeys_getValueByKeys),
74
- init: () => (/* reexport */ init),
75
- initFromArray: () => (/* reexport */ initFromArray),
76
- initOnlyValidFromArray: () => (/* reexport */ initOnlyValidFromArray),
77
- makeApiResponse: () => (/* reexport */ makeApiResponse),
78
- makeService: () => (/* reexport */ makeService),
79
- mergeArraysByKey: () => (/* reexport */ mergeArraysByKey),
80
- objectHelper: () => (/* reexport */ objectHelper),
81
- pReduce: () => (/* reexport */ pReduce),
82
- padZeros: () => (/* reexport */ padZeros),
83
- replacePlaceholders: () => (/* reexport */ replacePlaceholders),
84
- sanitizeText: () => (/* reexport */ sanitizeText),
85
- stringFormatter: () => (/* reexport */ stringFormatter),
86
- stringHelper: () => (/* reexport */ stringHelper),
87
- tenantPlugin: () => (/* reexport */ tenantPlugin),
88
- trackingPlugin: () => (/* reexport */ trackingPlugin)
89
- });
90
-
91
- ;// ./lib/helpers/authorize/authorize.js
92
- function authorize({ allowCoordinator, allowOwner, query = {}, required, user }) {
93
- if (!user) {
94
- throw new Error('Require login.')
95
- }
96
- if (!user.permission) {
97
- // throw new Error('You do not have any permission.')
98
- }
99
- const scopes = user.permission.getScopes(required || {}) || []
100
- if (!scopes || scopes.length === 0) {
101
- // throw new Error('You are not allowed in this scope.')
102
- }
103
- if (!scopes.includes('*')) {
104
- query.tenantCode = user.tenantCode
105
- }
106
- if (!scopes.includes('TENANT')) {
107
- query.eventShortCode = user.eventShortCode
108
- }
109
- // if (!scopes.includes('EVENT')) {
110
- // query.eventRegistrationCode = user.eventRegistrationCode
111
- // }
112
- if (allowCoordinator) {
113
- if (query.registrationGroupCode && user.myManagedRegistrationGroupCodes.includes(query.registrationGroupCode)) {
114
- query.__ALLOW_COORDINATOR = true
115
- } else {
116
- if (!scopes.includes('EVENT')) {
117
- query.eventRegistrationCode = user.eventRegistrationCode
118
- }
119
- }
120
- } else {
121
- if (!scopes.includes('EVENT')) {
122
- query.eventRegistrationCode = user.eventRegistrationCode
123
- }
124
- }
125
- if (allowOwner) {
126
- query.__ALLOW_OWNER = true
127
- }
128
- // not good, just use it as example
129
- if (user.hasExcludedFields) {
130
- query.__EXCLUDED_FIELDS = user.getExcludedFields(required)
131
- }
132
- query.__LOGIN_SUBJECT_CODE = user.loginSubjectCode
133
- return query
134
- }
135
-
136
- ;// ./lib/helpers/authorize/index.js
137
-
138
-
139
- ;// ./lib/helpers/changeCreatorOwner/changeCreatorOwner.js
140
- function changeCreatorOwner(that, { source, target }) {
141
- if (that.meta) {
142
- if (!that.meta.creator || that.meta.creator === source.getId()) {
143
- that.meta.creator = target.getId()
144
- }
145
- if (!that.meta.owner || that.meta.owner === source.getId()) {
146
- that.meta.owner = target.getId()
147
- }
148
- } else {
149
- if (!that.creator || that.creator === source.getId()) {
150
- that.creator = target.getId()
151
- }
152
- if (!that.owner || that.owner === source.getId()) {
153
- that.owner = target.getId()
154
- }
155
- }
156
- return that
157
- }
158
-
159
- ;// ./lib/helpers/changeCreatorOwner/index.js
160
-
161
-
162
- ;// ./lib/helpers/getValidation/getValidation.js
163
- function getValidation(rule, data, getDataByKey, KeyValueObject) {
164
- if (!rule) {
165
- return true
166
- }
167
- if (typeof getDataByKey !== 'function' || (KeyValueObject && typeof KeyValueObject !== 'function')) {
168
- return false
169
- }
170
- const { key = '', value, placeholder, keyValuePath = '' } = rule
171
- const [valueAttribute] = Object.keys(value)
172
-
173
- if (!key && typeof placeholder === 'undefined') {
174
- switch (valueAttribute) {
175
- case '$and': {
176
- return value['$and'].reduce((acc, item) => (acc && getValidation(item, data, getDataByKey, KeyValueObject)), true)
177
- }
178
- case '$or': {
179
- return value['$or'].reduce((acc, item) => (acc || getValidation(item, data, getDataByKey, KeyValueObject)), false)
180
- }
181
- default:
182
- return false
183
- }
184
- }
185
- let rowValue = typeof placeholder === 'undefined' ? getDataByKey(key, data) : placeholder
186
-
187
- // if KeyValue object
188
- if (keyValuePath) {
189
- const rowValueData = KeyValueObject.toObject(rowValue)
190
- rowValue = getDataByKey(keyValuePath, rowValueData)
191
- }
192
-
193
- switch (valueAttribute) {
194
- case '$empty': {
195
- const isEmpty = rowValue === null || rowValue === undefined
196
- return isEmpty === value['$empty']
197
- }
198
- case '$eq': {
199
- return rowValue === value['$eq']
200
- }
201
- case '$gt': {
202
- return rowValue > value['$gt']
203
- }
204
- case '$gte': {
205
- return rowValue >= value['$gte']
206
- }
207
- case '$hasOverlap': {
208
- return _hasOverlap(rowValue, value['$hasOverlap'])
209
- }
210
- case '$lt': {
211
- return rowValue < value['$lt']
212
- }
213
- case '$lte': {
214
- return rowValue <= value['$lte']
215
- }
216
- case '$in': {
217
- if (Array.isArray(rowValue)) {
218
- return !!rowValue.find((e) => (value['$in'].includes(e)))
219
- }
220
- if (typeof rowValue !== 'object') {
221
- return !!value['$in'].includes(rowValue)
222
- }
223
- return false
224
- }
225
- case '$inValue': {
226
- const result = getDataByKey(value['$inValue'], data)
227
- const _value = Array.isArray(result) ? result : []
228
- if (Array.isArray(rowValue)) {
229
- return !!rowValue.find((e) => (_value.includes(e)))
230
- }
231
- if (typeof rowValue === 'string') {
232
- return !!_value.includes(rowValue)
233
- }
234
- return false
235
- }
236
- case '$ne': {
237
- return rowValue !== value['$ne']
238
- }
239
- case '$notIn': {
240
- if (Array.isArray(rowValue)) {
241
- return !rowValue.find((e) => (value['$notIn'].includes(e)))
242
- }
243
- if (typeof rowValue !== 'object') {
244
- return !value['$notIn'].includes(rowValue)
245
- }
246
- return false
247
- }
248
- case '$intervalTimeGt': {
249
- const now = new Date().getTime()
250
- const timestamp = new Date(rowValue).getTime()
251
- return (now - timestamp) > value['$intervalTimeGt']
252
- }
253
- case '$intervalTimeLt': {
254
- const now = new Date().getTime()
255
- const timestamp = new Date(rowValue).getTime()
256
- return (now - timestamp) < value['$intervalTimeLt']
257
- }
258
- case '$isToday': {
259
- const currentDate = new Date()
260
- const start = currentDate.setHours(0,0,0,0)
261
- const end = currentDate.setHours(23,59,59,59)
262
- const dateValue = new Date(rowValue).getTime()
263
- return (start <= dateValue && end >= dateValue) === value['$isToday']
264
- }
265
- case '$notInValue': {
266
- const result = getDataByKey(value['$notInValue'], data)
267
- const _value = Array.isArray(result) ? result : []
268
- if (Array.isArray(rowValue)) {
269
- return !rowValue.find((e) => (_value.includes(e)))
270
- }
271
- if (typeof rowValue !== 'object') {
272
- return !_value.includes(rowValue)
273
- }
274
- return false
275
- }
276
- case '$range': {
277
- const [min, max] = value['$range']
278
- if (typeof min === 'number' && typeof max === 'number' && rowValue >= min && rowValue <= max) {
279
- return true
280
- }
281
- return false
282
- }
283
- default:
284
- return false
285
- }
286
-
287
- }
288
-
289
- function _hasOverlap(item1, item2) {
290
- let arr1 = item1
291
- let arr2 = item2
292
- if (typeof arr1 === 'string') {
293
- arr1 = arr1.split(',')
294
- }
295
- if (typeof arr2 === 'string') {
296
- arr2 = arr2.split(',')
297
- }
298
- const set1 = new Set(arr1)
299
- return arr2.find((i) => (set1.has(i)))
300
- }
301
-
302
- /* harmony default export */ const getValidation_getValidation = ({
303
- getValidation
304
- });
305
-
306
-
307
- ;// ./lib/helpers/getValidation/index.js
308
-
309
-
310
- ;// ./lib/helpers/formatDate/formatDate.js
311
-
312
- function formatDate(date, format) {
313
- const _date = date && date instanceof Date ? date : new Date(date)
314
- const dayMapChi = ['日','一','二','三','四','五','六']
315
- const dayMapEng = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
316
- const dayMapEngShort = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
317
- const _format = format || 'YYYY/MM/DD hh:mm'
318
- const e = _date.getDay()
319
- const ee = dayMapEngShort[e]
320
- const eee = dayMapChi[e]
321
- const eeee = dayMapEng[e]
322
- const y = _date.getFullYear()
323
- const m = _date.getMonth() + 1
324
- const d = _date.getDate()
325
- const h = _date.getHours()
326
- const mm = _date.getMinutes()
327
- const s = _date.getSeconds()
328
-
329
- return _format.replace('YYYY', y)
330
- .replace('MM', padding(m))
331
- .replace('MM', padding(m))
332
- .replace('DD', padding(d))
333
- .replace('hh', padding(h))
334
- .replace('mm', padding(mm))
335
- .replace('ss', padding(s))
336
- .replace('M', m)
337
- .replace('D', d)
338
- .replace('h', h)
339
- .replace('m', mm)
340
- .replace('s', s)
341
- .replace('EEEE', padding(eeee))
342
- .replace('EEE', padding(eee))
343
- .replace('EE', padding(ee))
344
- .replace('E', padding(e))
345
- }
346
-
347
- function padding(m) {
348
- return m < 10 ? `0${m}` : m
349
- }
350
-
351
-
352
- /* harmony default export */ const formatDate_formatDate = ({
353
- formatDate
354
- });
355
-
356
-
357
-
358
- ;// ./lib/helpers/formatDate/index.js
359
-
360
-
361
- ;// ./lib/helpers/getValueByKeys/getValueByKeys.js
362
- // keys can be array or object or string
363
- function getValueByKeys_getValueByKeys(keys, data) {
364
- let _keys = keys
365
- let _data = data
366
- if (typeof keys === 'string') {
367
- _keys = _keys.split('.')
368
- }
369
- if (!Array.isArray(keys) && typeof keys === 'object') {
370
- const { keys: keyArr, obj } = keys
371
- _keys = keyArr
372
- _data = obj
373
- }
374
- if (_keys.length === 0) {
375
- return _data
376
- }
377
- const firstKey = _keys.shift()
378
- if (_data && Object.prototype.hasOwnProperty.call(_data, firstKey)) {
379
- return getValueByKeys_getValueByKeys(_keys, _data[firstKey])
380
- }
381
- if (_data && firstKey) {
382
- if (_keys.length > 0) {
383
- return getValueByKeys_getValueByKeys(_keys, _data[firstKey])
384
- }
385
- return _data[firstKey]
386
- }
387
- return _data
388
-
389
- }
390
- /* harmony default export */ const getValueByKeys = ({
391
- getValueByKeys: getValueByKeys_getValueByKeys
392
- });
393
-
394
-
395
- ;// ./lib/helpers/getValueByKeys/index.js
396
-
397
-
398
- ;// ./lib/models/templateCompiler/templateCompilerException.js
399
- const TEMPLATE_COMPILER_EXCEPTION_TYPE = {
400
- argumentEmptyException: 'Argument is empty',
401
- argumentFormatException: 'Incorrect number or format of argument',
402
- invalidFuntionException: 'Function Name is invalid',
403
- invalidRegExpException: 'Invalid regular expression',
404
- isNotAFunctionException: 'Is not a function',
405
- notExistException: 'Key does not exist',
406
- resultEmptyException: 'Result is empty',
407
- resultMoreThanOneException: 'More than one result'
408
- }
409
-
410
- class TemplateCompilerException extends Error {
411
- constructor(message) {
412
- super(message)
413
- this.message = message
414
- }
415
- }
416
-
417
-
418
-
419
- ;// ./lib/models/templateCompiler/constants.js
420
- const _EMPTY = '_EMPTY'
421
- const _FN_NAMES = [
422
- 'concatIf',
423
- 'divide',
424
- 'eq',
425
- 'exec',
426
- 'filterAll',
427
- 'filterOne',
428
- 'formatDate',
429
- 'get',
430
- 'gt',
431
- 'gte',
432
- 'isEmpty',
433
- 'isNotEmpty',
434
- 'join',
435
- 'lt',
436
- 'lte',
437
- 'map',
438
- 'neq',
439
- 'removeHtml',
440
- 'toLowerCase',
441
- 'toUpperCase',
442
- ]
443
- const _HIDE = '_HIDE'
444
- const _NOT_EMPTY = '_NOT_EMPTY'
445
- const _SELF = '_SELF'
446
- const TAGS_EJS = ['<%=', '%>']
447
- const TAGS_HANDLEBAR = ['{{', '}}']
448
-
449
-
450
-
451
- ;// ./lib/models/templateCompiler/helpers/_concatIf.js
452
-
453
-
454
-
455
-
456
- function _concatIf(data, args) {
457
- if (typeof data !== 'string') {
458
- throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string :${data.join(', ')}`)
459
- }
460
- if (args.length !== 3) {
461
- throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
462
- }
463
- if (data === null || (typeof data === 'undefined')) {
464
- return null
465
- }
466
- const [condition, success, failover] = args
467
- const validConditions = [_EMPTY, _NOT_EMPTY]
468
- if (validConditions.includes(condition) || success.length !== 2) {
469
- throw new TemplateCompilerException(`concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException}: ${condition}, ${success}`)
470
- }
471
- if (data === '' && failover.includes(_HIDE)) {
472
- return ''
473
- }
474
- if (data !== '' && (data !== null || data !== undefined) && failover.includes(_HIDE)) {
475
- return `${success[0]}${data}${success[success.length - 1]}`
476
- }
477
- return failover
478
- }
479
-
480
-
481
-
482
- ;// ./lib/models/templateCompiler/helpers/_divide.js
483
- function _divide(value, divisor) {
484
- try {
485
- if (Number.isNaN(value)) {
486
- return value
487
- }
488
- return (value / divisor)
489
- } catch (e) {
490
- throw e
491
- }
492
- }
493
-
494
-
495
-
496
- ;// ./lib/models/templateCompiler/helpers/_eq.js
497
-
498
-
499
-
500
-
501
- function _eq(data, args) {
502
- if (args.length !== 3) {
503
- throw new TemplateCompilerException(`eq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
504
- }
505
- if (data === null || (typeof data === 'undefined')) {
506
- return null
507
- }
508
- if (args.includes(_SELF)) {
509
- args = args.map((arg) => {
510
- return (arg === _SELF) ? data : arg
511
- })
512
- }
513
- const expected = args[0]
514
- return data === expected ? args[1] : args[2]
515
- }
516
-
517
-
518
-
519
- ;// ./lib/models/templateCompiler/helpers/_exec.js
520
- function _exec(data, args) {
521
- try {
522
- const [methodName, ..._args] = args
523
- return data[methodName](..._args)
524
- } catch (e) {
525
- throw e
526
- }
527
- }
528
-
529
-
530
-
531
- ;// ./lib/models/templateCompiler/helpers/_filterAll.js
532
-
533
-
534
-
535
- // const DELIMITER = '~~~'
536
-
537
- function _filterAll(data, args) {
538
- try {
539
- if (!Array.isArray(args) || args.length === 0) {
540
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
541
- }
542
- if (!Array.isArray(data) || data.length === 0) {
543
- return []
544
- }
545
- if (typeof data[0] === 'object') {
546
- return _existObject(data, args)
547
- }
548
- if (typeof data[0] === 'string' || typeof data[0] === 'number') {
549
- return _exist(data, args)
550
- }
551
- return []
552
- } catch (e) {
553
- throw e
554
- }
555
- }
556
-
557
- function _exist(data, args) {
558
- const _args = args.flat()
559
- return data.filter((e) => _args.some((arg) => _performOperation(arg, e)))
560
- }
561
-
562
- function _existObject(data, args) {
563
- if (args.length === 1) {
564
- const arg = args[0]
565
- return data.filter((e) => {
566
- if (arg.includes('.')) {
567
- return getValueByKeys_getValueByKeys(arg.split('.'), e)
568
- }
569
- return Object.prototype.hasOwnProperty.call(e, arg)
570
- })
571
- }
572
-
573
- if (args.length > 2) {
574
- let res = data
575
- for (let i = 0; i < args.length; i += 2) {
576
- const group = [args[i], args[i + 1]]
577
- res = _existObject(res, group)
578
- }
579
- return res
580
- }
581
-
582
- const [key, ..._argsArr] = args
583
- const _args = _argsArr.flat()
584
- return data.filter((e) => {
585
- const value = key.includes('.') ? getValueByKeys_getValueByKeys(key.split('.'), e) : e[key]
586
- return _args.some((arg) => _performOperation(arg, value))
587
- })
588
- }
589
-
590
- function _performOperation(arg, value) {
591
- // the arg is undefined
592
- if (arg === undefined && value === undefined) return true
593
-
594
- // the arg is null
595
- if (arg === null && value === null) return true
596
-
597
- // the arg is boolean
598
- if (typeof arg === 'boolean') {
599
- return arg === value
600
- }
601
-
602
- // the arg is blank or *: Blank => Empty, * => Not Empty
603
- if (arg === '' || arg === '*') {
604
- // null and undefined are not included in either case
605
- if (value === null || value === undefined) {
606
- return false
607
- }
608
- if (typeof value === 'string') {
609
- return arg === '' ? value === '' : value !== ''
610
- }
611
- if (Array.isArray(value)) {
612
- return arg === '' ? value.length === 0 : value.length !== 0
613
- }
614
- return arg !== ''
615
- }
616
-
617
- // the arg is alphabetic or number
618
- if (_isPureStringOrNumber(arg)) {
619
- return arg === value
620
- }
621
-
622
- // the arg is array of [] or [*]: [] => Empty, [*] => Not Empty
623
- if (arg.startsWith('[') && arg.endsWith(']')) {
624
- if (arg === '[]') {
625
- return Array.isArray(value) && value.length === 0
626
- }
627
- if (arg === '[*]') {
628
- return Array.isArray(value) && value.length !== 0
629
- }
630
- return false
631
- }
632
-
633
- // the arg is 'operator + string | number'
634
- const { operator, value: argValue } = _splitOperator(arg)
635
- if (!operator || (argValue !== 0 && !argValue)) {
636
- return false
637
- }
638
- switch (operator) {
639
- case '>':
640
- return value > argValue
641
- case '<':
642
- return value < argValue
643
- case '!=':
644
- return value !== argValue
645
- case '>=':
646
- return value >= argValue
647
- case '<=':
648
- return value <= argValue
649
- default:
650
- return false
651
- }
652
- }
653
-
654
- function _isPureStringOrNumber(input) {
655
- if (typeof input === 'string') {
656
- if (input.startsWith('[') && input.endsWith(']')) {
657
- return false
658
- }
659
- if (/!=|>=|<=|>|</.test(input)) {
660
- return false
661
- }
662
- return true
663
- }
664
- return !Number.isNaN(input)
665
- }
666
-
667
- function _splitOperator(str) {
668
- const operators = ['!=', '>=', '<=', '>', '<']
669
-
670
- const matchedOp = operators.find((op) => str.startsWith(op))
671
- if (!matchedOp) return { operator: null, value: null }
672
-
673
- const remaining = str.slice(matchedOp.length)
674
-
675
- // '>Primary' or '<Primary' is invalid
676
- if (/^[a-zA-Z]*$/.test(remaining) && matchedOp !== '!=') {
677
- return { operator: null, value: null }
678
- }
679
-
680
- // if it is a number it is converted to a number
681
- const value = (!Number.isNaN(parseFloat(remaining)) && !Number.isNaN(remaining)) ? Number(remaining) : remaining
682
-
683
- return {
684
- operator: matchedOp,
685
- value
686
- }
687
- }
688
-
689
-
690
-
691
- ;// ./lib/models/templateCompiler/helpers/_filterOne.js
692
-
693
-
694
-
695
- function _filterOne(data, args) {
696
- try {
697
- const list = _filterAll(data, args)
698
- if (list.length === 1) {
699
- return list[0]
700
- }
701
- if (list.length === 0) {
702
- return null
703
- }
704
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.resultMoreThanOneException)
705
- } catch (e) {
706
- throw e
707
- }
708
- }
709
-
710
-
711
-
712
- ;// ./lib/models/templateCompiler/helpers/_formatDate.js
713
-
714
-
715
- function _formatDate(timestamp, format) {
716
- if (format.length === 0) {
717
- throw new TemplateCompilerException(`_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: format parts must be not empty array`)
718
- }
719
-
720
- if (timestamp === null || timestamp === undefined) {
721
- return null
722
- }
723
-
724
- const date = new Date(timestamp)
725
-
726
- const partsMap = {
727
- yyyy: String(date.getFullYear()),
728
- mm: String(date.getMonth() + 1).padStart(2, '0'),
729
- dd: String(date.getDate()).padStart(2, '0')
730
- }
731
-
732
- // Check for invalid format tokens
733
- const validTokens = ['yyyy', 'mm', 'dd']
734
- const invalidTokens = format.filter((part) => part.length > 1 && !validTokens.includes(part))
735
-
736
- if (invalidTokens.length > 0) {
737
- throw new TemplateCompilerException(
738
- `_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the format type is not valid: ${format.join(', ')}`
739
- )
740
- }
741
-
742
- // Build the formatted string using reduce
743
- return format.reduce((result, part) => result + (partsMap[part] || part), '')
744
- }
745
-
746
-
747
-
748
- ;// ./lib/models/templateCompiler/helpers/_get.js
749
-
750
-
751
- function _get(data, key, failover = null) {
752
- try {
753
- if (key === null || (typeof key === 'undefined') || key === '') {
754
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
755
- }
756
- if (data === null) {
757
- return null
758
- }
759
- if (key.includes('.')) {
760
- const parts = key.split('.')
761
- if (parts.length > 1) {
762
- const first = parts.shift()
763
- const remainingKey = parts.join('.')
764
- if (typeof data[first] !== 'undefined') {
765
- return _get(data[first], remainingKey, failover)
766
- }
767
- return _handleFailover(key, failover)
768
- }
769
- }
770
- if (typeof data[key] !== 'undefined') {
771
- return data[key]
772
- }
773
- return _handleFailover(key, failover)
774
- } catch (e) {
775
- throw e
776
- }
777
- }
778
-
779
- function _handleFailover(key, failover) {
780
- if (failover !== null) {
781
- return failover
782
- }
783
- return null
784
- // throw new TemplateCompilerException(`Key "${key}" does not exist and no failover`)
785
- }
786
-
787
-
788
-
789
- ;// ./lib/models/templateCompiler/helpers/_gt.js
790
-
791
-
792
-
793
-
794
- function _gt(data, args) {
795
- if (args.length !== 3) {
796
- throw new TemplateCompilerException(`_gt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
797
- }
798
- if (data === null || (typeof data === 'undefined')) {
799
- return null
800
- }
801
- if (args.includes(_SELF)) {
802
- args = args.map((arg) => {
803
- return (arg === _SELF) ? data : arg
804
- })
805
- }
806
- const expected = args[0]
807
- return data > expected ? args[1] : args[2]
808
- }
809
-
810
-
811
-
812
- ;// ./lib/models/templateCompiler/helpers/_gte.js
813
-
814
-
815
-
816
-
817
- function _gte(data, args) {
818
- if (args.length !== 3) {
819
- throw new TemplateCompilerException(`_gte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
820
- }
821
- if (data === null || (typeof data === 'undefined')) {
822
- return null
823
- }
824
- if (args.includes(_SELF)) {
825
- args = args.map((arg) => {
826
- return (arg === _SELF) ? data : arg
827
- })
828
- }
829
- const expected = args[0]
830
- return data >= expected ? args[1] : args[2]
831
- }
832
-
833
-
834
-
835
- ;// ./lib/models/templateCompiler/helpers/_isEmpty.js
836
-
837
-
838
-
839
-
840
- function _isEmpty(data, args) {
841
- if (args.length !== 2) {
842
- throw new TemplateCompilerException(`_isEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
843
- }
844
- // if (data === null || (typeof data === 'undefined')) {
845
- // return null
846
- // }
847
- if (args.includes(_SELF)) {
848
- args = args.map((arg) => {
849
- return (arg === _SELF) ? data : arg
850
- })
851
- }
852
- if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
853
- return args[0]
854
- }
855
- return (data === '' || data === null || data === undefined || data.length === 0) ? args[0] : args[1]
856
- }
857
-
858
-
859
-
860
- ;// ./lib/models/templateCompiler/helpers/_isNotEmpty.js
861
-
862
-
863
-
864
-
865
- function _isNotEmpty(data, args) {
866
- if (args.length !== 2) {
867
- throw new TemplateCompilerException(`_isNotEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
868
- }
869
- // if (data === null || (typeof data === 'undefined')) {
870
- // return null
871
- // }
872
- if (args.includes(_SELF)) {
873
- args = args.map((arg) => {
874
- return (arg === _SELF) ? data : arg
875
- })
876
- }
877
- if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
878
- return args[1]
879
- }
880
- if (Array.isArray(data) && data.length === 0) {
881
- return args[1]
882
- }
883
- if (typeof data === 'string' && data === '') {
884
- return args[1]
885
- }
886
- if (data === null || data === undefined) {
887
- return args[1]
888
- }
889
- return args[0]
890
- }
891
-
892
-
893
- ;// ./lib/models/templateCompiler/helpers/_join.js
894
- function _join(data, delimiter) {
895
- try {
896
- if (data.length === 0) return ''
897
- if (data.length === 1) return _stringifyObject(data[0])
898
- return data.map((item) => _stringifyObject(item)).join(delimiter)
899
- } catch (e) {
900
- throw e
901
- }
902
- }
903
-
904
- function _stringifyObject(obj) {
905
- return JSON.stringify(obj).replace(/"([^"]+)":/g, '$1: ').replace(/"([^"]+)"/g, '$1').replace(/,/g, ', ')
906
- }
907
-
908
-
909
-
910
- ;// ./lib/models/templateCompiler/helpers/_lt.js
911
-
912
-
913
-
914
-
915
- function _lt(data, args) {
916
- if (args.length !== 3) {
917
- throw new TemplateCompilerException(`_lt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
918
- }
919
- if (data === null || (typeof data === 'undefined')) {
920
- return null
921
- }
922
- if (args.includes(_SELF)) {
923
- args = args.map((arg) => {
924
- return (arg === _SELF) ? data : arg
925
- })
926
- }
927
- const expected = args[0]
928
- return data < expected ? args[1] : args[2]
929
- }
930
-
931
-
932
-
933
- ;// ./lib/models/templateCompiler/helpers/_lte.js
934
-
935
-
936
-
937
-
938
- function _lte(data, args) {
939
- if (args.length !== 3) {
940
- throw new TemplateCompilerException(`_lte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
941
- }
942
- if (data === null || (typeof data === 'undefined')) {
943
- return null
944
- }
945
- if (args.includes(_SELF)) {
946
- args = args.map((arg) => {
947
- return (arg === _SELF) ? data : arg
948
- })
949
- }
950
- const expected = args[0]
951
- return data <= expected ? args[1] : args[2]
952
- }
953
-
954
-
955
-
956
- ;// ./lib/models/templateCompiler/helpers/_map.js
957
-
958
-
959
-
960
- function _map(data, args) {
961
- try {
962
- if (args.length === 0) {
963
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
964
- }
965
- if (data === null || (typeof data === 'undefined')) {
966
- return null
967
- }
968
-
969
- const result = data.reduce((acc, item) => {
970
- if (args.length === 1 && Array.isArray(args[0])) {
971
- args = args[0]
972
- acc.hasFormat = true
973
- }
974
- const list = args.map((key) => {
975
- if (key.includes('.')) {
976
- const parts = key.split('.')
977
- const first = parts[0]
978
- parts.shift()
979
- const remainingKey = parts.join('.')
980
- return _get(item[first], remainingKey)
981
- }
982
- if (typeof item[key] !== 'undefined') {
983
- return item[key]
984
- }
985
- return null
986
- })
987
- if (acc.hasFormat) {
988
- acc.content.push(list)
989
- } else {
990
- acc.content = acc.content.concat(list)
991
- }
992
- return acc
993
- }, {
994
- content: [],
995
- hasFormat: false
996
- })
997
- return result.content
998
- } catch (e) {
999
- throw e
1000
- }
1001
- }
1002
-
1003
-
1004
-
1005
- ;// ./lib/models/templateCompiler/helpers/_neq.js
1006
-
1007
-
1008
-
1009
-
1010
- function _neq(data, args) {
1011
- if (args.length !== 3) {
1012
- throw new TemplateCompilerException(`_neq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1013
- }
1014
- if (data === null || (typeof data === 'undefined')) {
1015
- return null
1016
- }
1017
- if (args.includes(_SELF)) {
1018
- args = args.map((arg) => {
1019
- return (arg === _SELF) ? data : arg
1020
- })
1021
- }
1022
- const expected = args[0]
1023
- return data !== expected ? args[1] : args[2]
1024
- }
1025
-
1026
-
1027
-
1028
- ;// ./lib/models/templateCompiler/helpers/_removeHtml.js
1029
-
1030
-
1031
- function _removeHtml(html, args) {
1032
- if (html === null || html === undefined) {
1033
- return null
1034
- }
1035
- if (!Array.isArray(args)) {
1036
- throw new TemplateCompilerException(`_removeHtml: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: args parts must be array`)
1037
- }
1038
-
1039
- return _htmlToPlainText(html, args[0])
1040
- }
1041
-
1042
- function _htmlToPlainText(html, delimiter = '\n') {
1043
- if (typeof delimiter !== 'string') {
1044
- delimiter = '\n'; // Fallback to default if not a string
1045
- }
1046
-
1047
- // First decode HTML entities and normalize whitespace
1048
- const decodedHtml = html
1049
- .replace(/&nbsp;/g, ' ')
1050
- .replace(/\s+/g, ' '); // Collapse all whitespace to single spaces
1051
-
1052
- // Process HTML tags
1053
- let text = decodedHtml
1054
- // Replace block tags with temporary marker (~~~)
1055
- .replace(/<\/?(p|div|h[1-6]|ul|ol|li|pre|section|article|table|tr|td|th)(\s[^>]*)?>/gi, '~~~')
1056
- // Replace <br> tags with temporary marker (~~~)
1057
- .replace(/<br\s*\/?>/gi, '~~~')
1058
- // Remove all other tags
1059
- .replace(/<[^>]+>/g, '')
1060
- // Convert markers to specified delimiter
1061
- .replace(/~~~+/g, delimiter)
1062
- // Trim and clean whitespace
1063
- .trim();
1064
-
1065
- // Special handling for empty delimiter
1066
- if (delimiter === '') {
1067
- // Collapse all whitespace to single space
1068
- text = text.replace(/\s+/g, ' ');
1069
- } else {
1070
-
1071
-
1072
- // Collapse multiple delimiters to single
1073
- text = text.replace(new RegExp(`${escapeRegExp(delimiter)}+`, 'g'), delimiter);
1074
- // Remove leading/trailing delimiters
1075
- text = text.replace(new RegExp(`^${escapeRegExp(delimiter)}|${escapeRegExp(delimiter)}$`, 'g'), '');
1076
- }
1077
-
1078
- return text;
1079
- }
1080
-
1081
-
1082
- function escapeRegExp(string) {
1083
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1084
- }
1085
-
1086
-
1087
-
1088
- ;// ./lib/models/templateCompiler/helpers/_toLowerCase.js
1089
-
1090
-
1091
- function _toLowerCase(data, args) {
1092
- if (args !== undefined) {
1093
- throw new TemplateCompilerException(`_toLowerCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1094
- }
1095
- if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
1096
- return null
1097
- }
1098
- return String(data).toLowerCase()
1099
- }
1100
-
1101
-
1102
-
1103
- ;// ./lib/models/templateCompiler/helpers/_toUpperCase.js
1104
-
1105
-
1106
- function _toUpperCase(data, args) {
1107
- if (typeof data !== 'string') {
1108
- throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string: ${data}`)
1109
- }
1110
- if (args !== undefined) {
1111
- throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the argument must be empty: ${args.join(', ')}`)
1112
- }
1113
- if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
1114
- return null
1115
- }
1116
- return String(data).toUpperCase()
1117
- }
1118
-
1119
-
1120
-
1121
- ;// ./lib/models/templateCompiler/helpers/index.js
1122
-
1123
-
1124
-
1125
-
1126
-
1127
-
1128
-
1129
-
1130
-
1131
-
1132
-
1133
-
1134
-
1135
-
1136
-
1137
-
1138
-
1139
-
1140
-
1141
-
1142
-
1143
-
1144
-
1145
- ;// ./lib/models/templateCompiler/templateCompiler.js
1146
-
1147
-
1148
-
1149
-
1150
- class TemplateCompiler {
1151
- constructor(data) {
1152
- this.data = data
1153
- }
1154
- static init(options) {
1155
- return new this(options)
1156
- }
1157
- static initFromArray(arr = []) {
1158
- if (Array.isArray(arr)) {
1159
- return arr.map((a) => this.init(a))
1160
- }
1161
- return []
1162
- }
1163
- static initOnlyValidFromArray(arr = []) {
1164
- return this.initFromArray(arr).filter((i) => i)
1165
- }
1166
- static concatIf(data, args) {
1167
- return _concatIf(data, args)
1168
- }
1169
- static divide(data, args) {
1170
- return _divide(data, args)
1171
- }
1172
- static eq(data, args) {
1173
- return _eq(data, args)
1174
- }
1175
-
1176
- static filterAll(data, args) {
1177
- return _filterAll(data, args)
1178
- }
1179
-
1180
- static formatDate(data, args) {
1181
- return _formatDate(data, args)
1182
- }
1183
- static get(data, key, failover = null) {
1184
- return _get(data, key, failover)
1185
- }
1186
- static gt(data, args) {
1187
- return _gt(data, args)
1188
- }
1189
- static gte(data, args) {
1190
- return _gte(data, args)
1191
- }
1192
- static isEmpty(data, args) {
1193
- return _isEmpty(data, args)
1194
- }
1195
- static isNotEmpty(data, args) {
1196
- return _isNotEmpty(data, args)
1197
- }
1198
- static join(data, separator = '') {
1199
- return _join(data, separator)
1200
- }
1201
- static lt(data, args) {
1202
- return _lt(data, args)
1203
- }
1204
- static lte(data, args) {
1205
- return _lte(data, args)
1206
- }
1207
- static map(data, args = []) {
1208
- return _map(data, args)
1209
- }
1210
- static neq(data, args) {
1211
- return _neq(data, args)
1212
- }
1213
- static removeHtml(data, args) {
1214
- return _removeHtml(data, args)
1215
- }
1216
- static toLowerCase(data, args) {
1217
- return _toLowerCase(data, args)
1218
- }
1219
- static toUpperCase(data, args) {
1220
- return _toUpperCase(data, args)
1221
- }
1222
- static parseFunction(expression) {
1223
- return _parseFunction(expression, _FN_NAMES)
1224
- }
1225
- static parseParams(parameters) {
1226
- return _parseParams(parameters)
1227
- }
1228
-
1229
- pipe(expression = '') {
1230
- this.delimiters = expression.substring(0, 2) === '{{' ? TAGS_HANDLEBAR : TAGS_EJS
1231
- const regex = new RegExp(`${this.delimiters[0]}\\s(.*?)\\s${this.delimiters[1]}`)
1232
- const match = expression.match(regex)
1233
- if (match !== null) {
1234
- try {
1235
- const functionList = _parseFunction(match[1], _FN_NAMES)
1236
- return functionList.reduce((acc, fn) => {
1237
- return _callFunction(acc, fn.name, fn.args)
1238
- }, this.data)
1239
- } catch (e) {
1240
- throw new TemplateCompilerException(`TemplateCompiler engine error: ${e.message}`)
1241
- }
1242
- }
1243
- throw new TemplateCompilerException(`TemplateCompiler engine error: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.invalidRegExpException}`)
1244
- }
1245
- }
1246
-
1247
- function _parseFunction(expression, existFunctionNames) {
1248
- const regExp = new RegExp(/(\w+)\(([^)]*)\)/)
1249
- let parts
1250
- if (expression.includes('|')) {
1251
- parts = expression.split('|')
1252
- } else {
1253
- parts = [expression]
1254
- }
1255
- return parts.reduce((acc, part) => {
1256
- const match = part.match(regExp)
1257
- if (match !== null) {
1258
- const functionName = match[1]
1259
- const parameters = match[2]
1260
- const paramList = _parseParams(parameters)
1261
- if (existFunctionNames.includes(functionName)) {
1262
- acc.push({
1263
- name: functionName,
1264
- args: paramList
1265
- })
1266
- } else {
1267
- throw new TemplateCompilerException(`${functionName} is not a valid function`)
1268
- }
1269
- }
1270
- return acc
1271
- }, [])
1272
- }
1273
-
1274
- function _parseParams(parameters) {
1275
- const _parameters = parameters.trim()
1276
- const regExp = new RegExp(/^[^\w\d\s]+$/)
1277
- const match = _parameters.match(regExp)
1278
- if (match !== null) {
1279
- return [_parameters.substring(1, _parameters.length - 1)]
1280
- }
1281
- if (_parameters.includes(',')) {
1282
- // 用正则表达式匹配逗号,但忽略方括号中的逗号
1283
- const parts = _splitIgnoringBrackets(_parameters)
1284
- return parts.map((part) => _parseSinglePart(part))
1285
- }
1286
- return [_parseSinglePart(_parameters)]
1287
- }
1288
-
1289
- function _splitIgnoringBrackets(input) {
1290
- const regExp2 = new RegExp(/^\d+(\.\d+)?$/)
1291
- const regExp = new RegExp(/(?![^\[]*\])\s*,\s*/)
1292
- const parts = input.split(regExp)
1293
- return parts.map((part) => {
1294
- const _part = part.trim()
1295
- if (_part !== '' && !!_part.match(regExp2)) {
1296
- // 如果是数字,转换为 num 类型
1297
- return Number.isNaN(_part) ? _part : parseInt(_part, 10)
1298
- }
1299
- // 否则当作字符串处理
1300
- return _part
1301
- })
1302
- }
1303
-
1304
- function _parseSinglePart(input) {
1305
- if (typeof input === 'string') {
1306
- if (input.startsWith('"') && input.endsWith('"')) {
1307
- // 去掉双引号,返回
1308
- return input.substring(1, input.length - 1)
1309
- }
1310
- if (input.startsWith("'") && input.endsWith("'")) {
1311
- // 去掉双引号,返回
1312
- return input.substring(1, input.length - 1)
1313
- }
1314
-
1315
- const _input = _toBasicType(input)
1316
-
1317
- if (typeof _input !== 'string') {
1318
- return _input
1319
- }
1320
-
1321
- // 如果是一个列表形式(例如 ["p", "d"] 或 [p, d])
1322
- if (_input.startsWith('[') && _input.endsWith(']')) {
1323
- const listContent = _input.substring(1, _input.length - 1).trim()
1324
- if (listContent !== '') {
1325
- return listContent.split(',').map((item) => {
1326
- return _toBasicType(item.trim())
1327
- })
1328
- }
1329
- return []
1330
- }
1331
- return input
1332
- }
1333
- return input
1334
- }
1335
-
1336
- function _toBasicType(input) {
1337
- if (input.startsWith('"') && input.endsWith('"')) {
1338
- // 去掉双引号,返回
1339
- return input.substring(1, input.length - 1)
1340
- }
1341
- if (input.startsWith("'") && input.endsWith("'")) {
1342
- // 去掉双引号,返回
1343
- return input.substring(1, input.length - 1)
1344
- }
1345
- if (input === 'true') {
1346
- return true
1347
- }
1348
- if (input === 'false') {
1349
- return false
1350
- }
1351
- if (input === 'undefined') {
1352
- return undefined
1353
- }
1354
- if (input === 'null') {
1355
- return null
1356
- }
1357
- if (!Number.isNaN(input) && !Number.isNaN(Number.parseFloat(input))) {
1358
- return Number(input)
1359
- }
1360
- return input
1361
- }
1362
-
1363
- function _callFunction(data, functionName, parameters) {
1364
- try {
1365
- let failover
1366
- switch (functionName) {
1367
- case 'concatIf':
1368
- return _concatIf(data, parameters)
1369
- case 'divide':
1370
- return _divide(data, parameters)
1371
- case 'eq':
1372
- return _eq(data, parameters)
1373
- case 'exec':
1374
- return _exec(data, parameters)
1375
- case 'filterAll':
1376
- return _filterAll(data, parameters)
1377
- case 'filterOne':
1378
- return _filterOne(data, parameters)
1379
- case 'formatDate':
1380
- return _formatDate(data, parameters)
1381
- case 'get':
1382
- if (parameters.length > 2) {
1383
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException)
1384
- }
1385
- if (parameters.length === 2) {
1386
- failover = parameters[parameters.length - 1]
1387
- }
1388
- return _get(data, parameters[0], failover)
1389
- case 'gt':
1390
- return _gt(data, parameters)
1391
- case 'gte':
1392
- return _gte(data, parameters)
1393
- case 'isEmpty':
1394
- return _isEmpty(data, parameters)
1395
- case 'isNotEmpty':
1396
- return _isNotEmpty(data, parameters)
1397
- case 'join':
1398
- return _join(data, parameters[0])
1399
- case 'lt':
1400
- return _lt(data, parameters)
1401
- case 'lte':
1402
- return _lte(data, parameters)
1403
- case 'map':
1404
- return _map(data, parameters)
1405
- case 'neq':
1406
- return _neq(data, parameters)
1407
- case 'removeHtml':
1408
- return _removeHtml(data, parameters)
1409
- case 'toLowerCase':
1410
- return _toLowerCase(data)
1411
- case 'toUpperCase':
1412
- return _toUpperCase(data)
1413
- default:
1414
- throw new Error(`${functionName} is not a valid function`)
1415
- }
1416
- } catch (e) {
1417
- throw e
1418
- }
1419
- }
1420
-
1421
-
1422
-
1423
- ;// ./lib/models/templateCompiler/index.js
1424
-
1425
-
1426
-
1427
-
1428
- ;// ./lib/helpers/concatStringByArray/concatStringByArray.js
1429
-
1430
-
1431
-
1432
-
1433
-
1434
- function concatStringByArray(arrTemplate, data) {
1435
- return arrTemplate.reduce((acc, item) => {
1436
- const { type, value = '', restriction, template, format, showMinutes } = item
1437
- switch (type) {
1438
- case('array'): {
1439
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1440
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || []
1441
- acc += _value.reduce((_acc, item) => {
1442
- return _acc += concatStringByArray(template, item)
1443
- }, '')
1444
- }
1445
- break
1446
- }
1447
- case ('date'): {
1448
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1449
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1450
- acc += (formatDate(_value, format).toString())
1451
- }
1452
- break
1453
- }
1454
- case('ellipsis'): {
1455
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1456
- const { maxLength } = item
1457
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1458
- if (_value.length <= maxLength) {
1459
- acc += (_value.toString())
1460
- } else {
1461
- acc += `${_value.substr(0, maxLength)}...`
1462
- }
1463
- }
1464
- break
1465
- }
1466
- case('group'): {
1467
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1468
- return concatStringByArray(value, data)
1469
- }
1470
- break
1471
- }
1472
- case('label'): {
1473
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1474
- acc += (value.toString())
1475
- }
1476
- break
1477
- }
1478
- case ('templateCompiler'): {
1479
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1480
- const templateCompiler = new TemplateCompiler({ data })
1481
- acc += templateCompiler.pipe(value)
1482
- }
1483
- break
1484
- }
1485
- case('value'): {
1486
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1487
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1488
- acc += (_value.toString())
1489
- }
1490
- break
1491
- }
1492
- }
1493
- return acc
1494
- }, '')
1495
- }
1496
- /* harmony default export */ const concatStringByArray_concatStringByArray = ({
1497
- concatStringByArray
1498
- });
1499
-
1500
-
1501
-
1502
- ;// ./lib/helpers/concatStringByArray/index.js
1503
-
1504
-
1505
- ;// ./lib/helpers/convertString/convertString.js
1506
-
1507
-
1508
- function convertString(string, patternMatch = /\$\{(.+?)\}/g, value, getValueByKeys) {
1509
- if (!string) {
1510
- return ''
1511
- }
1512
- let _getValueByKeys = typeof getValueByKeys === 'function' ? getValueByKeys : getValueByKeys_getValueByKeys
1513
- const reg = new RegExp(patternMatch, 'g')
1514
- return string.replace(reg, (match, key) => {
1515
- const result = _getValueByKeys({ keys: key.split('.'), obj: value })
1516
- if (result === null || result === undefined) {
1517
- return ''
1518
- }
1519
- return typeof result === 'object' ? JSON.stringify(result) : result
1520
- })
1521
- }
1522
-
1523
- /* harmony default export */ const convertString_convertString = ({
1524
- convertString
1525
- });
1526
-
1527
-
1528
- ;// ./lib/helpers/convertString/index.js
1529
-
1530
-
1531
- ;// ./lib/helpers/escapeRegex/escapeRegex.js
1532
- function escapeRegex(string) {
1533
- return String(string).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
1534
- }
1535
-
1536
- ;// ./lib/helpers/escapeRegex/index.js
1537
-
1538
-
1539
- ;// ./lib/helpers/expressHelper/customHandler.js
1540
- function customHandler({ responseHelper, handler, ignoreError = false }) {
1541
- return async (req, res, next) => {
1542
- try {
1543
- await handler({ req, res })
1544
- await next()
1545
- } catch (err) {
1546
- if (ignoreError) {
1547
- await next()
1548
- } else {
1549
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1550
- }
1551
- }
1552
- }
1553
- }
1554
-
1555
- ;// ./lib/helpers/expressHelper/findAllResult.js
1556
- function findAllResult({ responseHelper, service }) {
1557
- return async (req, res, next) => {
1558
- try {
1559
- const { query } = req
1560
- const result = await service.findAll({ query })
1561
- res.locals.findAllResult = result
1562
- await next()
1563
- } catch (err) {
1564
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1565
- }
1566
- }
1567
- }
1568
-
1569
- ;// ./lib/helpers/expressHelper/findOneResult.js
1570
- function findOneResult({ responseHelper, service }) {
1571
- return async (req, res, next) => {
1572
- try {
1573
- const { params, query } = req
1574
- const { id } = params
1575
- const result = await service.findOne({
1576
- query: {
1577
- ...query,
1578
- id
1579
- }
1580
- })
1581
- res.locals.findOneResult = result
1582
- await next()
1583
- } catch (err) {
1584
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1585
- }
1586
- }
1587
- }
1588
-
1589
- ;// ./lib/helpers/expressHelper/postResult.js
1590
- function postResult({ responseHelper, service }) {
1591
- return async (req, res, next) => {
1592
- try {
1593
- const { body } = req
1594
- let result
1595
- if (Array.isArray(body)) {
1596
- result = await service.saveAll({ docs: body })
1597
- } else {
1598
- result = await service.saveOne({ doc: body })
1599
- }
1600
- res.locals.postResult = result
1601
- await next()
1602
- } catch (err) {
1603
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1604
- }
1605
- }
1606
- }
1607
-
1608
- ;// ./lib/helpers/expressHelper/updateOneResult.js
1609
- function updateOneResult({ responseHelper, service }) {
1610
- return async (req, res, next) => {
1611
- try {
1612
- const { body, params } = req
1613
- const { id } = params
1614
- if (id !== body.id) {
1615
- throw new Error('id in params and body must be same')
1616
- }
1617
- const { data } = await service.findOne({ query: { id } })
1618
- const doc = data[0]
1619
- doc.update(body)
1620
- const result = await service.saveOne({ doc })
1621
- res.locals.updateOneResult = result
1622
- await next()
1623
- } catch (err) {
1624
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1625
- }
1626
- }
1627
- }
1628
-
1629
- ;// ./lib/helpers/expressHelper/index.js
1630
-
1631
-
1632
-
1633
-
1634
-
1635
-
1636
-
1637
- const expressHelper = {
1638
- customHandler: customHandler,
1639
- findAllResult: findAllResult,
1640
- findOneResult: findOneResult,
1641
- postResult: postResult,
1642
- updateOneResult: updateOneResult,
1643
- }
1644
-
1645
- ;// ./lib/helpers/extractEmails/extractEmails.js
1646
- /**
1647
- * Extracts and normalizes unique email addresses from an array containing messy entries
1648
- * @param {Array} dirtyArray - Array that may contain emails in various formats (may include null/empty entries)
1649
- * @returns {Array} Sorted array of unique, lowercase email addresses
1650
- */
1651
- function extractEmails(dirtyArray) {
1652
- const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
1653
- const emails = new Set()
1654
-
1655
- // Handle null/undefined input array
1656
- if (!dirtyArray) return []
1657
-
1658
- dirtyArray.forEach(entry => {
1659
- // Skip null, undefined, empty, or whitespace-only entries
1660
- if (!entry || typeof entry !== 'string' || !entry.trim()) return
1661
-
1662
- try {
1663
- const cleanEntry = entry
1664
- .replace(/[\u200B-\u200D\uFEFF\u202A-\u202E]/g, '') // Remove hidden chars
1665
- .replace(/[<>]/g, ' ') // Convert email delimiters to spaces
1666
- .replace(/\s+/g, ' ') // Collapse multiple whitespace
1667
- .trim()
1668
-
1669
- // Extract all email matches
1670
- const matches = cleanEntry.match(emailRegex)
1671
- if (matches) {
1672
- matches.forEach(email => emails.add(email.toLowerCase())) // Normalize to lowercase
1673
- }
1674
- } catch (e) {
1675
- console.warn('Failed to process entry:', entry, e)
1676
- }
1677
- })
1678
-
1679
- // Convert Set to array and sort alphabetically
1680
- return Array.from(emails).sort((a, b) => a.localeCompare(b))
1681
- }
1682
-
1683
- ;// ./lib/helpers/extractEmails/index.js
1684
-
1685
-
1686
- ;// ./lib/helpers/objectHelper/objectHelper.js
1687
- const objectHelper = {
1688
- get(obj, path) {
1689
- const parts = path.split('.')
1690
- return parts.reduce((acc, part) => {
1691
- if (part.endsWith('[]')) {
1692
- // 处理数组遍历
1693
- const key = part.slice(0, -2) // 去掉 '[]' 得到属性名
1694
- if (Array.isArray(acc[key])) {
1695
- return acc[key] // 返回整个数组
1696
- }
1697
- return [] // 如果不是数组,返回空数组
1698
- }
1699
- if (part.includes('[') && part.includes(']')) {
1700
- // 处理数组索引
1701
- const arrayMatch = part.match(/(\w+)\[(\d+)\]/)
1702
- if (arrayMatch) {
1703
- const key = arrayMatch[1]
1704
- const index = arrayMatch[2]
1705
- return acc && acc[key] && acc[key][index]
1706
- }
1707
- } else if (acc && Array.isArray(acc)) {
1708
- // 如果当前值是数组,提取每个对象的指定属性
1709
- return acc.map((item) => item[part])
1710
- } else {
1711
- // 处理普通属性
1712
- return acc && acc[part]
1713
- }
1714
- }, obj)
1715
- },
1716
- merge,
1717
- set(obj, path, value) {
1718
- const parts = path.split('.');
1719
- let current = obj;
1720
-
1721
- // 处理所有中间部分
1722
- for (let i = 0; i < parts.length - 1; i++) {
1723
- const part = parts[i];
1724
- let key, index;
1725
-
1726
- // 检查是否是数组索引格式,如key[0]
1727
- const arrayMatch = part.match(/^(\w+)\[(\d+)\]$/);
1728
- if (arrayMatch) {
1729
- key = arrayMatch[1];
1730
- index = parseInt(arrayMatch[2], 10);
1731
- // 确保当前层级的数组存在
1732
- if (!current[key] || !Array.isArray(current[key])) {
1733
- current[key] = [];
1734
- }
1735
- // 扩展数组到足够大
1736
- while (current[key].length <= index) {
1737
- current[key].push(undefined);
1738
- }
1739
- // 如果当前位置未定义或为null,初始化为对象
1740
- if (current[key][index] == null) {
1741
- current[key][index] = {};
1742
- }
1743
- current = current[key][index];
1744
- } else {
1745
- // 处理普通属性
1746
- if (!current[part]) {
1747
- current[part] = {};
1748
- }
1749
- current = current[part];
1750
- }
1751
- }
1752
-
1753
- // 处理最后一部分
1754
- const lastPart = parts[parts.length - 1];
1755
- const arrayMatch = lastPart.match(/^(\w+)\[(\d+)\]$/);
1756
- if (arrayMatch) {
1757
- const key = arrayMatch[1];
1758
- const index = parseInt(arrayMatch[2], 10);
1759
- // 确保数组存在
1760
- if (!current[key] || !Array.isArray(current[key])) {
1761
- current[key] = [];
1762
- }
1763
- // 扩展数组到所需索引
1764
- while (current[key].length <= index) {
1765
- current[key].push(undefined);
1766
- }
1767
- current[key][index] = value;
1768
- } else {
1769
- current[lastPart] = value;
1770
- }
1771
- }
1772
- }
1773
-
1774
- function merge(target, ...sources) {
1775
- if (!sources.length) return target
1776
-
1777
- const source = sources.shift() // 取出第一个源对象
1778
-
1779
- if (_isObject(target) && _isObject(source)) {
1780
- for (const key in source) {
1781
- if (_isObject(source[key])) {
1782
- if (!target[key]) {
1783
- // 如果目标对象没有该属性,创建一个空对象
1784
- target[key] = {}
1785
- }
1786
- // 递归合并
1787
- merge(target[key], source[key])
1788
- } else {
1789
- // 直接覆盖
1790
- target[key] = source[key]
1791
- }
1792
- }
1793
- }
1794
-
1795
- // 继续合并剩余的源对象
1796
- return merge(target, ...sources)
1797
- }
1798
-
1799
- function _isObject(obj) {
1800
- return obj && typeof obj === 'object' && !Array.isArray(obj)
1801
- }
1802
-
1803
-
1804
-
1805
- ;// ./lib/helpers/objectHelper/index.js
1806
-
1807
-
1808
-
1809
-
1810
- ;// ./lib/helpers/pReduce/pReduce.js
1811
- async function pReduce(iterable, reducer, initialValue) {
1812
- return new Promise((resolve, reject) => {
1813
- const iterator = iterable[Symbol.iterator]()
1814
- let index = 0
1815
-
1816
- const next = async total => {
1817
- const element = iterator.next()
1818
-
1819
- if (element.done) {
1820
- resolve(total)
1821
- return
1822
- }
1823
-
1824
- try {
1825
- const [resolvedTotal, resolvedValue] = await Promise.all([total, element.value])
1826
- next(reducer(resolvedTotal, resolvedValue, index++))
1827
- } catch (error) {
1828
- reject(error)
1829
- }
1830
- }
1831
-
1832
- next(initialValue)
1833
- })
1834
- }
1835
-
1836
-
1837
-
1838
- ;// ./lib/models/repo/repo.js
1839
-
1840
-
1841
- class Repo {
1842
- constructor(options) {
1843
- options = options || {}
1844
- this.model = options.model
1845
- this._sharedOptions = options._sharedOptions // { session: this.dbTransaction }
1846
- this._queryOptions = options._queryOptions
1847
- this._saveOptions = options._saveOptions
1848
- this._Class = options._constructor && options._constructor._Class
1849
- ? options._constructor._Class
1850
- : null
1851
- }
1852
- static init(options = {}) {
1853
- return init(this, options)
1854
- }
1855
- static get _classname() {
1856
- return 'Repo'
1857
- }
1858
- static get _superclass() {
1859
- return 'Repo'
1860
- }
1861
-
1862
- get _classname() {
1863
- return 'Repo'
1864
- }
1865
-
1866
- get _superclass() {
1867
- return 'Repo'
1868
- }
1869
-
1870
- get isValid() {
1871
- return this.model
1872
- && (typeof this.model.deleteOne === 'function')
1873
- && (typeof this.model.findAll === 'function')
1874
- && (typeof this.model.saveOne === 'function')
1875
- }
1876
-
1877
- get queryOptions() {
1878
- return {
1879
- ...this._sharedOptions,
1880
- ...this._queryOptions,
1881
- }
1882
- }
1883
-
1884
- get saveOptions() {
1885
- return {
1886
- ...this._sharedOptions,
1887
- ...this._saveOptions,
1888
- }
1889
- }
1890
-
1891
- init(options) {
1892
- if (this._Class && typeof this._Class.init === 'function') {
1893
- return this._Class.init(options)
1894
- }
1895
- return options
1896
- }
1897
-
1898
- async deleteOne({ id }) {
1899
- try {
1900
- const result = await this.model.deleteOne({ _id: id })
1901
- return {
1902
- ...result, // { message: 'ok', total }
1903
- isNew: false,
1904
- data: []
1905
- }
1906
- } catch (err) {
1907
- throw err
1908
- }
1909
- }
1910
-
1911
- // systemLog is optional
1912
- findAll({ query, systemLog }) {
1913
- const log = _makeLog({
1914
- systemLog,
1915
- label: 'REPO_READ',
1916
- message: `fn ${this._classname}.prototype.findAll`,
1917
- input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1918
- })
1919
- return new Promise((resolve, reject) => {
1920
- this.model.findAll(query, this.queryOptions, (err, data, total) => {
1921
- if (err) {
1922
- log({ level: 'warn', output: err.toString() })
1923
- reject(err)
1924
- } else {
1925
- const result = {
1926
- isNew: false,
1927
- data,
1928
- total: total || data.length
1929
- }
1930
- log({ level: 'info', output: { ...result } })
1931
- resolve(result)
1932
- }
1933
- })
1934
- })
1935
- }
1936
-
1937
- findOne({ query, systemLog }) {
1938
- const log = _makeLog({
1939
- systemLog,
1940
- label: 'REPO_READ',
1941
- message: `fn ${this._classname}.prototype.findOne`,
1942
- input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1943
- })
1944
- return new Promise((resolve, reject) => {
1945
- this.model.findAll(query, this.queryOptions, (err, data) => {
1946
- if (err) {
1947
- reject(err)
1948
- } else if (data.length === 1) {
1949
- const result = {
1950
- isNew: false,
1951
- data,
1952
- total: 1
1953
- }
1954
- log({ level: 'info', output: { ...result } })
1955
- resolve(result)
1956
- } else if (data.length === 0) {
1957
- reject(new Error('record not found'))
1958
- } else {
1959
- reject(new Error('more than one is found'))
1960
- }
1961
- })
1962
- })
1963
- .catch((err) => {
1964
- log({ level: 'warn', output: err.toString() })
1965
- throw err
1966
- })
1967
- }
1968
-
1969
- saveAll({ config = {}, docs, systemLog }) {
1970
- let isNew
1971
- const log = _makeLog({
1972
- systemLog,
1973
- label: 'REPO_WRITE',
1974
- message: `fn ${this._classname}.prototype.saveAll`,
1975
- input: [{ config, docs: [...docs], systemLog: { ...systemLog } }]
1976
- })
1977
- const promise = typeof this.model.saveAll === 'function'
1978
- ? this.model.saveAll({ config, docs })
1979
- : Promise.all(docs.map(async (doc) => {
1980
- if (doc) {
1981
- const result = await this.saveOne({ config, doc })
1982
- isNew = result.isNew
1983
- const _data = result._data || result.data
1984
- return _data[0]
1985
- }
1986
- return null
1987
- }))
1988
- return promise.then((savedData) => {
1989
- if (savedData.length !== 1) isNew = null
1990
- const result = {
1991
- data: savedData,
1992
- isNew,
1993
- total: savedData.length
1994
- }
1995
- log({ level: 'info', output: { ...result } })
1996
- return result
1997
- }).catch((err) => {
1998
- log({ level: 'warn', output: err.toString() })
1999
- throw err
2000
- })
2001
- }
2002
-
2003
- saveOne({ config = {}, doc, systemLog }) {
2004
- const log = _makeLog({
2005
- systemLog,
2006
- label: 'REPO_WRITE',
2007
- message: `fn ${this._classname}.prototype.saveOne`,
2008
- input: [{ config, doc: { ...doc }, systemLog: { ...systemLog } }]
2009
- })
2010
- const saveOptions = {
2011
- ...this.saveOptions,
2012
- ...config,
2013
- }
2014
- return new Promise((resolve, reject) => {
2015
- this.model.saveOne(doc, saveOptions, (err, result) => {
2016
- if (err) {
2017
- log({ level: 'warn', output: err.toString() })
2018
- reject(err)
2019
- } else {
2020
- log({ level: 'info', output: { ...result } })
2021
- resolve(result)
2022
- }
2023
- })
2024
- })
2025
- }
2026
- }
2027
-
2028
- function _makeLog({ systemLog, label, message: message1, input } = {}) {
2029
- return ({ level, messgae: massage2, output } = {}) => {
2030
- if (systemLog && systemLog.systemLogHelper) {
2031
- systemLog.systemLogHelper.log({
2032
- batchId: systemLog.batchId,
2033
- label,
2034
- level,
2035
- message: massage2 || message1,
2036
- data: {
2037
- payload: {
2038
- input,
2039
- output
2040
- }
2041
- }
2042
- })
2043
- }
2044
- }
2045
- }
2046
-
2047
-
2048
-
2049
- ;// ./lib/models/repo/index.js
2050
-
2051
-
2052
-
2053
-
2054
- ;// ./lib/models/apiResponse/apiResponse.js
2055
- class ApiResponse {
2056
- constructor(options = {}) {
2057
- options = options || {}
2058
- this._data = options.data || options._data || []
2059
- this.err = options.err
2060
- this.isNew = options.isNew || false
2061
- this.message = options.message
2062
- this.total = options.total || 0
2063
- this._instanceBuilder = options._instanceBuilder
2064
- }
2065
-
2066
- static init(options = {}) {
2067
- if (options instanceof this) {
2068
- return options
2069
- }
2070
- const instance = new this(options)
2071
- return instance
2072
- }
2073
- static get _classname() {
2074
- return 'ApiResponse'
2075
- }
2076
- static get _superclass() {
2077
- return 'ApiResponse'
2078
- }
2079
-
2080
- // getters
2081
- get data() {
2082
- if (this._instanceBuilder && (typeof this._instanceBuilder === 'function')) {
2083
- return this._data.map(this._instanceBuilder)
2084
- }
2085
- return this._data
2086
- }
2087
- }
2088
-
2089
-
2090
-
2091
- ;// ./lib/models/apiResponse/makeApiResponse.js
2092
-
2093
-
2094
- function makeApiResponse({ repo, result }) {
2095
- return ApiResponse.init({
2096
- ...result,
2097
- _instanceBuilder: (i) => {
2098
- return repo.init(i)
2099
- }
2100
- })
2101
- }
2102
-
2103
-
2104
-
2105
- ;// ./lib/models/service/service.js
2106
-
2107
-
2108
-
2109
- class Service {
2110
- constructor({ repo }) {
2111
- this.repo = repo
2112
- }
2113
-
2114
- static get _classname() {
2115
- return 'Service'
2116
- }
2117
- static get _superclass() {
2118
- return 'Service'
2119
- }
2120
-
2121
- deleteOne({ id }) {
2122
- return this.repo.deleteOne({ id })
2123
- .catch(() => {
2124
- throw new Error(`Not found for query: ${id}`)
2125
- })
2126
- }
2127
-
2128
- async findAll({ query = {}, systemLog } = {}) {
2129
- const result = await this.repo.findAll({ query, systemLog })
2130
- return makeApiResponse({
2131
- repo: this.repo,
2132
- result
2133
- })
2134
- }
2135
-
2136
- async findOne({ query = {}, systemLog } = {}) {
2137
- const result = await this.repo.findOne({ query, systemLog })
2138
- return makeApiResponse({
2139
- repo: this.repo,
2140
- result
2141
- })
2142
- }
2143
-
2144
- init(options) {
2145
- return this.repo.init(options)
2146
- }
2147
- initFromArray(arr = []) {
2148
- if (Array.isArray(arr)) {
2149
- return arr.map((a) => this.init(a))
2150
- }
2151
- return []
2152
- }
2153
- initOnlyValidFromArray(arr = []) {
2154
- return this.initFromArray(arr).filter((i) => i)
2155
- }
2156
-
2157
- async saveAll({ config = {}, docs = [], systemLog } = {}) {
2158
- const copies = docs.map((doc) => {
2159
- return config.skipInit ? doc : this.init(doc)
2160
- })
2161
- const result = await this.repo.saveAll({ config, docs: copies, systemLog })
2162
- return makeApiResponse({
2163
- repo: this.repo,
2164
- result
2165
- })
2166
- }
2167
-
2168
- // set skipInit to true if we want to use POST for query
2169
- async saveOne({ config = {}, doc = {}, systemLog } = {}) {
2170
- const copy = config.skipInit ? doc : this.init(doc)
2171
- if (copy) {
2172
- const result = await this.repo.saveOne({ config, doc: copy, systemLog })
2173
- return makeApiResponse({
2174
- repo: this.repo,
2175
- result
2176
- })
2177
- }
2178
- return {
2179
- isNew: null,
2180
- data: [],
2181
- err: new Error('doc is not a valid instance')
2182
- }
2183
- }
2184
- }
2185
-
2186
- function makeService({ repo }) {
2187
- if (repo === undefined) {
2188
- throw new Error('repo is required.')
2189
- }
2190
- if (repo._superclass !== Repo._superclass) {
2191
- throw new Error('repo is not an instance of Repo.')
2192
- }
2193
- return new Service({ repo })
2194
- }
2195
-
2196
-
2197
-
2198
- ;// ./lib/models/service/index.js
2199
-
2200
-
2201
-
2202
-
2203
- ;// ./lib/helpers/generalPost/generalPost.js
2204
-
2205
-
2206
-
2207
-
2208
-
2209
- async function generalPost({ body = {}, GeneralModel, UniqueKeyGenerator, resourceInfo }) {
2210
- const { resources, data, globalShared = {}, shared = {}, relationship = {} } = body
2211
- const _resourceInfo = resourceInfo || body.resourceInfo
2212
- _attachShared(data, globalShared, shared)
2213
- const obj = await pReduce(resources, async (acc, resource) => {
2214
- const service = _makeService(resource, _resourceInfo, UniqueKeyGenerator, GeneralModel)
2215
- _createRelationship(data, relationship[resource], acc)
2216
- const _data = data[resource]
2217
- const result = await service.saveAll({ docs: [].concat(_data) })
2218
- acc[resource] = Array.isArray(_data) ? result._data : result._data[0]
2219
- return acc
2220
- }, {})
2221
- return obj
2222
- }
2223
-
2224
- function _attachShared(data, globalShared = {}, shared = {}) {
2225
- Object.keys(shared).forEach((key) => {
2226
- const _data = data[key]
2227
- if (Array.isArray(_data)) {
2228
- data[key] = _data.map((_dataItem) => {
2229
- return objectHelper.merge({}, _dataItem, globalShared, shared[key] || {})
2230
- })
2231
- } else {
2232
- data[key] = objectHelper.merge({}, _data, globalShared, shared[key] || {})
2233
- }
2234
- })
2235
- }
2236
-
2237
- function _createRelationship(data, relationship = {}, object) {
2238
- Object.keys(relationship).forEach((key) => {
2239
- const path = relationship[key]
2240
- const val = objectHelper.get(object, path)
2241
- objectHelper.set(data, key, val)
2242
- })
2243
- }
2244
-
2245
- function _makeService(resource, resourceInfo, UniqueKeyGenerator, GeneralModel) {
2246
- const { collectionName, fields } = resourceInfo[resource]
2247
- const uniqueKeyGenerator = UniqueKeyGenerator.makeGenerator(fields)
2248
- const model = new GeneralModel({ collectionName, uniqueKeyGenerator })
2249
- return makeService({
2250
- repo: new Repo({ model })
2251
- })
2252
- }
2253
-
2254
-
2255
-
2256
- ;// ./lib/helpers/generalPost/index.js
2257
-
2258
-
2259
-
2260
-
2261
- ;// ./lib/helpers/init/init.js
2262
- function init(_class, options) {
2263
- if (options instanceof _class) {
2264
- return options
2265
- }
2266
- try {
2267
- const instance = new _class(options)
2268
- return instance.isValid !== false ? instance : null
2269
- } catch (e) {
2270
- console.log(`init failed for class: ${_class._classname || 'no _classname'}`, e)
2271
- return null
2272
- }
2273
- }
2274
-
2275
- ;// ./lib/helpers/init/index.js
2276
-
2277
-
2278
- ;// ./lib/helpers/initFromArray/initFromArray.js
2279
-
2280
-
2281
- function initFromArray(_class, arr) {
2282
- if (Array.isArray(arr)) {
2283
- return arr.map((a) => init(_class, a))
2284
- }
2285
- return []
2286
- }
2287
-
2288
- ;// ./lib/helpers/initFromArray/index.js
2289
-
2290
-
2291
- ;// ./lib/helpers/initOnlyValidFromArray/initOnlyValidFromArray.js
2292
-
2293
-
2294
- function initOnlyValidFromArray(_class, arr) {
2295
- return initFromArray(_class, arr).filter((i) => i)
2296
- }
2297
-
2298
- ;// ./lib/helpers/initOnlyValidFromArray/index.js
2299
-
2300
-
2301
- ;// ./lib/helpers/mergeArraysByKey/mergeArraysByKey.js
2302
- function mergeArraysByKey(arr1, arr2) {
2303
- // Handle undefined/null inputs by defaulting to empty arrays
2304
- const safeArr1 = Array.isArray(arr1) ? arr1 : []
2305
- const safeArr2 = Array.isArray(arr2) ? arr2 : []
2306
-
2307
- const mergedMap = new Map()
2308
-
2309
- // Helper function to merge values based on their type
2310
- const mergeValues = (existingValue, newValue) => {
2311
- if (existingValue === undefined) return newValue
2312
-
2313
- // Handle arrays by concatenating
2314
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
2315
- return [...new Set([...existingValue, ...newValue])]
2316
- }
2317
-
2318
- // Handle objects by merging
2319
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
2320
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
2321
- return { ...existingValue, ...newValue }
2322
- }
2323
-
2324
- // // Handle numbers by adding
2325
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
2326
- // return existingValue
2327
- // }
2328
-
2329
- // // Handle strings by concatenating
2330
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
2331
- // return existingValue
2332
- // }
2333
-
2334
- // Default: use the new value
2335
- return newValue
2336
- }
2337
-
2338
- // Process first array
2339
- safeArr1.forEach(item => {
2340
- mergedMap.set(item.key, item.value)
2341
- })
2342
-
2343
- // Process second array and merge values
2344
- safeArr2.forEach(item => {
2345
- const existingValue = mergedMap.get(item.key)
2346
- mergedMap.set(item.key, mergeValues(existingValue, item.value))
2347
- })
2348
-
2349
- // Convert back to array format
2350
- return Array.from(mergedMap.entries()).map(([key, value]) => ({
2351
- key,
2352
- value
2353
- }))
2354
- }
2355
-
2356
- ;// ./lib/helpers/mergeArraysByKey/index.js
2357
-
2358
-
2359
- ;// ./lib/helpers/padZeros/padZeros.js
2360
- function padZeros(num, minLength = 6) {
2361
- num = num.toString()
2362
- if (num.length < minLength) {
2363
- return padZeros('0' + num, minLength)
2364
- }
2365
- return num
2366
- }
2367
-
2368
-
2369
-
2370
- ;// ./lib/helpers/padZeros/index.js
2371
-
2372
-
2373
-
2374
-
2375
- ;// ./lib/helpers/pReduce/index.js
2376
-
2377
-
2378
-
2379
-
2380
- ;// ./lib/helpers/replacePlaceholders/replacePlaceholders.js
2381
- function replacePlaceholders({ content, mapping }) {
2382
- let isObjectMode = false
2383
-
2384
- if (typeof content === 'object' && content !== null) {
2385
- content = JSON.stringify(content)
2386
- isObjectMode = true
2387
- }
2388
-
2389
- // [[ eventRegistration.eventRegistrationCode | 0 ]]
2390
- const regex = /(\[*)\[\[\s*([\w.\-_]+)(?:\s*\|\s*([^:\]\s]+))?(?:\s*:\s*([^\]\s]+))?\s*\]\](\]*)/g;
2391
-
2392
- const result = content.replace(regex, (match, leadingBrackets, path, defaultValue, type, trailingBrackets) => {
2393
-
2394
- // Split the path into parts
2395
- const keys = path.trim().split('.')
2396
-
2397
- // Traverse the nested object structure
2398
- let value = mapping
2399
- for (const key of keys) {
2400
- // Handle empty keys (in case of double dots or leading/trailing dots)
2401
- if (!key) continue
2402
-
2403
- value = value?.[key]
2404
- if (value === undefined) {
2405
- break
2406
- }
2407
- }
2408
-
2409
- // Apply default if missing
2410
- if (value === undefined) value = defaultValue?.trim();
2411
- if (value === undefined) return isObjectMode ? undefined : match;
2412
-
2413
- value = value !== undefined
2414
- ? leadingBrackets + value + trailingBrackets
2415
- : match
2416
-
2417
- // Return replacement or original if not found
2418
- return value
2419
- })
2420
-
2421
- if (isObjectMode) {
2422
- return JSON.parse(result)
2423
- }
2424
- return result
2425
- }
2426
-
2427
- ;// ./lib/helpers/replacePlaceholders/index.js
2428
-
2429
-
2430
- ;// ./lib/helpers/sanitizeText/sanitizeText.js
2431
- /**
2432
- * Sanitizes input by removing hidden/control characters with customizable whitespace handling.
2433
- * @param {string} input - The string to sanitize.
2434
- * @param {Object} [options] - Configuration options.
2435
- * @param {boolean} [options.normalizeWhitespace=true] - Collapse multiple spaces/tabs into one space.
2436
- * @param {boolean} [options.removeNewlines=false] - If true, replaces newlines with spaces.
2437
- * @param {boolean} [options.trim=true] - If true, trims leading/trailing whitespace.
2438
- * @returns {string} The sanitized string.
2439
- */
2440
- function sanitizeText(input, options = {}) {
2441
- const {
2442
- normalizeWhitespace = true,
2443
- removeNewlines = false,
2444
- trim = true,
2445
- preserveBasicWhitespace = true, // new option to keep tabs, newlines if removeNewlines=false
2446
- } = options
2447
-
2448
- if (typeof input !== 'string') {
2449
- return input
2450
- }
2451
-
2452
- let result = input
2453
-
2454
- // Phase 1: Remove all control characters except basic whitespace if requested
2455
- if (preserveBasicWhitespace && !removeNewlines) {
2456
- // Keep tab (\t), newline (\n), carriage return (\r)
2457
- result = result.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g, '')
2458
- } else {
2459
- // Remove all control characters including basic whitespace
2460
- result = result.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g, '')
2461
- }
2462
-
2463
- // Phase 2: Handle whitespace transformations
2464
- if (removeNewlines) {
2465
- result = result.replace(/[\r\n]+/g, ' ') // Convert newlines to spaces
2466
- }
2467
-
2468
- if (normalizeWhitespace) {
2469
- result = result.replace(/[ \t]+/g, ' ') // Collapse spaces/tabs to single space
2470
- }
2471
-
2472
- // Phase 3: Final trimming
2473
- if (trim) {
2474
- result = result.trim()
2475
- }
2476
-
2477
- return result
2478
- }
2479
-
2480
- ;// ./lib/helpers/sanitizeText/index.js
2481
-
2482
-
2483
- ;// ./lib/helpers/stringFormatter/stringFormatter.js
2484
- function stringFormatter(str, delimiter = '_') {
2485
- if (str === null || typeof str === 'undefined' || typeof str.toString === 'undefined') {
2486
- return null
2487
- }
2488
- return str.toString()
2489
- .trim()
2490
- .toUpperCase()
2491
- .replace('-', delimiter)
2492
- .replace(' ', delimiter)
2493
- }
2494
-
2495
-
2496
-
2497
- ;// ./lib/helpers/stringFormatter/index.js
2498
-
2499
-
2500
-
2501
-
2502
- ;// ./lib/helpers/stringHelper/stringHelper.js
2503
- function baseXEncode(num, base = 34) {
2504
- const charset = getBaseCharset(base)
2505
- return encode(num, charset)
2506
- }
2507
-
2508
- function encode(int, charset) {
2509
- const { byCode } = charset
2510
- if (int === 0) {
2511
- return byCode[0]
2512
- }
2513
-
2514
- let res = ''
2515
- const max = charset.length
2516
- while (int > 0) {
2517
- res = byCode[int % max] + res
2518
- int = Math.floor(int / max)
2519
- }
2520
- return res
2521
- }
2522
-
2523
- function getBaseCharset(base) {
2524
- let charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZ'
2525
- if (base === 58) {
2526
- charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
2527
- }
2528
- return indexCharset(charset)
2529
- }
2530
-
2531
- function indexCharset(str) {
2532
- const byCode = {}
2533
- const byChar = {}
2534
- const { length } = str
2535
- let char
2536
- for (let i = 0; i < length; i++) {
2537
- char = str[i]
2538
- byCode[i] = char
2539
- byChar[char] = i;
2540
- }
2541
- return { byCode, byChar, length }
2542
- }
2543
-
2544
- function isSame(str1, str2) {
2545
- if (typeof str1 !== 'string' || typeof str2 !== 'string') {
2546
- return false
2547
- }
2548
- return str1.trim().toUpperCase() === str2.trim().toUpperCase()
2549
- }
2550
-
2551
- function randomString({ len = 16, pattern = 'a1' } = {}) {
2552
- const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2553
- const a = 'abcdefghijklmnopqrstuvwxyz'
2554
- const num = '1234567890'
2555
- const mark = '~!@#$%^&*_+-='
2556
- let str = ''
2557
- if (pattern.includes('A')) {
2558
- str += A
2559
- }
2560
- if (pattern.includes('a')) {
2561
- str += a
2562
- }
2563
- if (pattern.includes('1')) {
2564
- str += num
2565
- }
2566
- if (pattern.includes('#')) {
2567
- str += mark
2568
- }
2569
- const chars = [...str]
2570
- return [...Array(len)].map(i => {
2571
- return chars[(Math.random() * chars.length) | 0]
2572
- }).join``
2573
- }
2574
-
2575
- function reverse(str) {
2576
- const _str = (typeof str !== 'string') ? str.toString() : str
2577
- const splitString = _str.split('')
2578
- const reverseArray = splitString.reverse()
2579
- return reverseArray.join('')
2580
- }
2581
-
2582
- function setCode(base = 34) {
2583
- const now = (new Date()).valueOf()
2584
- const random = randomString({
2585
- len: 8,
2586
- pattern: '1'
2587
- })
2588
- const str = reverse(`${now}${random}`)
2589
- // const str = `${now}${random}`
2590
- return baseXEncode(str, base)
2591
- }
2592
-
2593
- function toCamelCase(str) {
2594
- if (!str) return ''
2595
- return str
2596
- .trim()
2597
- .split(/\s+/)
2598
- .map((word, index) => {
2599
- if (!word) return ''
2600
- if (index === 0) {
2601
- return word.toLowerCase()
2602
- }
2603
- return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
2604
- })
2605
- .join('')
2606
- }
2607
-
2608
- function toLowerCase(str) {
2609
- if (!str) return ''
2610
- return str
2611
- .trim()
2612
- .toLowerCase()
2613
- }
2614
-
2615
- const stringHelper = {
2616
- isSame,
2617
- setCode,
2618
- toCamelCase,
2619
- toLowerCase,
2620
- }
2621
-
2622
-
2623
-
2624
- ;// ./lib/helpers/stringHelper/index.js
2625
-
2626
-
2627
-
2628
-
2629
- ;// ./lib/helpers/trackingPlugin/trackingPlugin.js
2630
- function trackingPlugin(schema, options) {
2631
- // Add meta fields
2632
- schema.add({
2633
- meta: {
2634
- active: { type: Boolean, default: true },
2635
- created: { type: Number },
2636
- creator: { type: String },
2637
- deleted: { type: Boolean, default: false },
2638
- modified: { type: Number },
2639
- owner: { type: String },
2640
- }
2641
- })
2642
-
2643
- // Auto-update hook
2644
- schema.pre('save', function(next) {
2645
- this.meta.modified = Date.now()
2646
- next()
2647
- })
2648
-
2649
- // Add core indexes
2650
- schema.index({
2651
- 'meta.active': 1,
2652
- 'meta.deleted': 1
2653
- }, {
2654
- name: 'tracking_status_index',
2655
- background: true,
2656
- partialFilterExpression: {
2657
- 'meta.active': true,
2658
- 'meta.deleted': false
2659
- }
2660
- })
2661
-
2662
- // Optional: Add helper methods
2663
- // schema.methods.touch = function(userId) {
2664
- // this.meta.updatedAt = new Date()
2665
- // this.meta.updatedBy = userId
2666
- // }
2667
- }
2668
-
2669
- ;// ./lib/helpers/tenantPlugin/tenantPlugin.js
2670
-
2671
-
2672
- function tenantPlugin(schema, options) {
2673
- // Apply tracking plugin first if not already present
2674
- if (!schema.path('meta')) {
2675
- trackingPlugin(schema, options)
2676
- }
2677
-
2678
- // Add tenant-specific fields
2679
- schema.add({
2680
- metadata: [{ type: Object }], // Instead of Schema.Types.Mixed
2681
- remarks: [{ type: Object }],
2682
- tenantCode: { type: String, required: true }
2683
- })
2684
-
2685
- // Add core indexes
2686
- schema.index({
2687
- 'tenantCode': 1
2688
- }, {
2689
- name: 'tenant_core_index',
2690
- background: true
2691
- })
2692
-
2693
- // 1. ENHANCE EXISTING TRACKING INDEXES
2694
- const existingIndexes = schema.indexes()
2695
-
2696
- // Check if tracking_status_index exists
2697
- const hasTenantStatusIndex = existingIndexes.some(idx =>
2698
- idx.name === 'tenant_status_index' // Check by name for reliability
2699
- )
2700
-
2701
- if (!hasTenantStatusIndex) {
2702
- schema.index({
2703
- 'tenantCode': 1, // Unique field first
2704
- _type: 1, // Low-cardinality field last
2705
- }, {
2706
- name: 'tenant_status_index',
2707
- background: true,
2708
- partialFilterExpression: {
2709
- '_type': 'Tenant',
2710
- 'meta.active': true,
2711
- 'meta.deleted': false
2712
- }
2713
- })
2714
- }
2715
- }
2716
-
2717
- ;// ./lib/helpers/tenantPlugin/index.js
2718
-
2719
-
2720
- ;// ./lib/helpers/trackingPlugin/index.js
2721
-
2722
-
2723
- ;// ./lib/helpers/index.js
2724
-
2725
-
2726
-
2727
-
2728
-
2729
-
2730
-
2731
-
2732
-
2733
-
2734
-
2735
-
2736
-
2737
-
2738
-
2739
-
2740
-
2741
-
2742
-
2743
-
2744
-
2745
-
2746
-
2747
-
2748
-
2749
- ;// ./lib/models/apiResponse/index.js
2750
-
2751
-
2752
-
2753
-
2754
-
2755
- ;// ./lib/models/awsStsS3Client/awsStsS3Client.js
2756
- class AwsStsS3Client {
2757
- constructor(options) {
2758
- options = options || {}
2759
-
2760
- this.expiration = options.expiration || null
2761
- this.s3Client = options.s3Client || null
2762
- this.getIdToken = options.getIdToken
2763
- this.region = options.region || 'ap-east-1'
2764
- this.roleArn = options.roleArn
2765
- this.roleSessionName = options.roleSessionName || 'web-identity-session'
2766
- this.durationSession = options.durationSession || 3600
2767
- this.awsClientSts = options.awsClientSts
2768
- this.awsClientS3 = options.awsClientS3
2769
- }
2770
-
2771
- static dummyData() {
2772
- return {
2773
- getIdToken: () => 'mock-web-identity-token',
2774
- roleArn: 'arn:aws:iam::846252828949:role/oidcS3Jccpa',
2775
- awsClientSts: {
2776
- STSClient: class {},
2777
- AssumeRoleWithWebIdentityCommand: class {}
2778
- },
2779
- awsClientS3: {
2780
- S3Client: class {},
2781
- PutObjectCommand: class {},
2782
- GetObjectCommand: class {},
2783
- DeleteObjectCommand: class {}
2784
- }
2785
- }
2786
- }
2787
-
2788
- static init(options = {}) {
2789
- if (options instanceof this) {
2790
- return options
2791
- }
2792
- try {
2793
- const instance = new this(options)
2794
- if (!instance.isValid) {
2795
- return null
2796
- }
2797
- return instance
2798
- } catch (error) {
2799
- return null
2800
- }
2801
- }
2802
-
2803
- get isExpired() {
2804
- if (!this.expiration) return true;
2805
- const now = new Date();
2806
- const bufferMs = 1 * 60 * 1000; // 一分钟缓冲
2807
- return now >= new Date(this.expiration.getTime() - bufferMs);
2808
- }
2809
-
2810
- get isValid() {
2811
- if (!this.getIdToken) {
2812
- throw new Error('Missing required configuration: getIdToken function')
2813
- }
2814
- if (!this.roleArn) {
2815
- throw new Error('Missing required configuration: roleArn')
2816
- }
2817
- if (!this.awsClientSts) {
2818
- throw new Error('Missing required AWS awsClientSts client configuration')
2819
- }
2820
- if (!this.awsClientSts.STSClient) {
2821
- throw new Error('Missing STSClient in AWS awsClientSts client configuration')
2822
- }
2823
- if (!this.awsClientSts.AssumeRoleWithWebIdentityCommand) {
2824
- throw new Error('Missing AssumeRoleWithWebIdentityCommand in AWS awsClientSts client configuration')
2825
- }
2826
- if (!this.awsClientS3) {
2827
- throw new Error('Missing required AWS awsClientS3 client configuration')
2828
- }
2829
-
2830
- const requiredS3Components = [
2831
- 'S3Client',
2832
- 'PutObjectCommand',
2833
- 'GetObjectCommand',
2834
- 'DeleteObjectCommand'
2835
- ]
2836
-
2837
- for (const component of requiredS3Components) {
2838
- if (!this.awsClientS3[component]) {
2839
- throw new Error(`Missing ${component} in AWS awsClientS3 client configuration`)
2840
- }
2841
- }
2842
-
2843
- return true
2844
- }
2845
-
2846
- async refreshCredentials() {
2847
- try {
2848
- const webIdentityToken = await this.getIdToken()
2849
- if (!webIdentityToken) {
2850
- throw new Error('getIdToken function returned empty or invalid token')
2851
- }
2852
-
2853
- const stsClient = new this.awsClientSts.STSClient({ region: this.region })
2854
-
2855
- const stsResponse = await stsClient.send(
2856
- new this.awsClientSts.AssumeRoleWithWebIdentityCommand({
2857
- RoleArn: this.roleArn,
2858
- RoleSessionName: this.roleSessionName,
2859
- WebIdentityToken: await this.getIdToken(),
2860
- DurationSeconds: this.durationSession,
2861
- })
2862
- )
2863
-
2864
- const credentials = stsResponse.Credentials
2865
- if (!credentials) {
2866
- throw new Error('No credentials returned from awsClientSts')
2867
- }
2868
-
2869
- this.expiration = credentials.Expiration
2870
-
2871
- this.s3Client = new this.awsClientS3.S3Client({
2872
- region: this.region,
2873
- credentials: {
2874
- accessKeyId: credentials.AccessKeyId,
2875
- secretAccessKey: credentials.SecretAccessKey,
2876
- sessionToken: credentials.SessionToken,
2877
- }
2878
- })
2879
-
2880
- return this
2881
- } catch (error) {
2882
- throw new Error(`Failed to refresh credentials: ${error.message}`)
2883
- }
2884
- }
2885
-
2886
- async getS3Client() {
2887
- if (this.isExpired || !this.s3Client) {
2888
- await this.refreshCredentials()
2889
- }
2890
- return this.s3Client
2891
- }
2892
-
2893
- async putObject(params) {
2894
- try {
2895
- const client = await this.getS3Client()
2896
- const command = new this.awsClientS3.PutObjectCommand(params)
2897
- await client.send(command)
2898
- const fileArr = params.Key.split('/')
2899
- return {
2900
- url: `https://s3.${this.region}.amazonaws.com/${params.Bucket}/${params.Key}`,
2901
- filename: fileArr.pop(),
2902
- folder: params.Bucket,
2903
- subFolders: fileArr
2904
- }
2905
- } catch (error) {
2906
- throw new Error(`Failed to put object: ${error.message}`)
2907
- }
2908
- }
2909
-
2910
- async getObject(params) {
2911
- try {
2912
- const client = await this.getS3Client()
2913
- const command = new this.awsClientS3.GetObjectCommand(params)
2914
- const response = await client.send(command)
2915
- return {
2916
- body: response.Body,
2917
- contentType: response.ContentType,
2918
- lastModified: response.LastModified,
2919
- contentLength: response.ContentLength,
2920
- }
2921
- } catch (error) {
2922
- throw new Error(`Failed to get object: ${error.message}`)
2923
- }
2924
- }
2925
-
2926
- async deleteObject(params) {
2927
- try {
2928
- const client = await this.getS3Client()
2929
- const command = new this.awsClientS3.DeleteObjectCommand(params)
2930
- await client.send(command)
2931
- return true
2932
- } catch (error) {
2933
- throw new Error(`Failed to delete object: ${error.message}`)
2934
- }
2935
- }
2936
- }
2937
-
2938
-
2939
-
2940
- ;// ./lib/models/awsStsS3Client/index.js
2941
-
2942
-
2943
-
2944
-
2945
- ;// ./lib/models/keyValueObject/keyValueObject.js
2946
- class KeyValueObject {
2947
- constructor(options = {}) {
2948
- options = options || {}
2949
- this.key = options.key || null
2950
- this.value = (typeof options.value !== 'undefined') ? options.value : ''
2951
- }
2952
-
2953
- // Class methods
2954
- static init(options = {}) {
2955
- if (options instanceof this) {
2956
- return options
2957
- }
2958
- const instance = new this(options)
2959
- return instance.isValid ? instance : null
2960
- }
2961
- static initFromArray(arr = []) {
2962
- if (Array.isArray(arr)) {
2963
- return arr.map((a) => this.init(a))
2964
- }
2965
- return []
2966
- }
2967
- static initOnlyValidFromArray(arr = []) {
2968
- return this.initFromArray(arr).filter((i) => i)
2969
- }
2970
- static get _classname() {
2971
- return 'KeyValueObject'
2972
- }
2973
- static get _superclass() {
2974
- return 'KeyValueObject'
2975
- }
2976
-
2977
- static addItem(arr, key, value) {
2978
- arr.push(this.init({ key, value }))
2979
- }
2980
- static addRecord(arr = [], key, value) {
2981
- if (!this.hasKeyValue(arr, key, value)) {
2982
- arr.push(this.init({ key, value }))
2983
- }
2984
- return arr
2985
- }
2986
- static appendRecord(arr = [], key, value) {
2987
- return arr.map((item) => {
2988
- if (this.sameKey(item, key)) {
2989
- item.value = [...item.value, ...value]
2990
- }
2991
- return item
2992
- })
2993
- }
2994
- static appendValueArray(arr = [], key, value) {
2995
- return arr.map((item) => {
2996
- if (this.sameKey(item, key)) {
2997
- item.value = [...item.value, ...value]
2998
- }
2999
- return item
3000
- })
3001
- }
3002
- static foundByKey(arr = [], key) {
3003
- const found = arr.find((m) => {
3004
- return this.sameKey(m, key)
3005
- })
3006
- return found || null
3007
- }
3008
- static foundValueByKey(arr = [], key) {
3009
- const found = this.foundByKey(arr, key)
3010
- return found ? found.value : null
3011
- }
3012
- static fromObject(options = {}) {
3013
- return Object.keys(options).reduce((acc, key) => {
3014
- acc.push(this.init({ key, value: options[key] }))
3015
- return acc
3016
- }, [])
3017
- }
3018
- static getValueByKey(arr = [], key) {
3019
- return this.foundValueByKey(arr, key)
3020
- }
3021
- static getValueByKeyFromArray(arr = [], key) {
3022
- if (arr.length === 0) {
3023
- return null
3024
- }
3025
- const firstArr = arr.shift()
3026
- const found = firstArr.find((i) => {
3027
- return this.sameKey(i, key)
3028
- })
3029
- if (found && found.value) {
3030
- return found.value
3031
- }
3032
- return this.getValueByKeyFromArray(arr, key)
3033
- }
3034
- static getValuesByKey(arr = [], key) {
3035
- return arr.reduce((acc, item) => {
3036
- if (this.sameKey(item, key)) {
3037
- acc.push(item.value)
3038
- }
3039
- return acc
3040
- }, [])
3041
- }
3042
- static hasKeyValue(arr = [], key, value) {
3043
- if (typeof value === 'undefined') {
3044
- return arr.filter((item) => this.sameKey(item, key)).length > 0
3045
- }
3046
- return arr.filter((item) => (this.sameKey(item, key) && _isSame(item.value, value))).length > 0
3047
- }
3048
- static insertOrUpdateRecord(arr = [], key, value) {
3049
- let copy = [...arr]
3050
- if (!this.hasKeyValue(arr, key)) {
3051
- copy.push(this.init({ key, value }))
3052
- } else {
3053
- copy = this.updateRecord(arr, key, value)
3054
- }
3055
- return copy
3056
- }
3057
- static keys(arr = []) {
3058
- if (Array.isArray(arr)) {
3059
- return arr.reduce((acc, item) => {
3060
- acc.push(item.key)
3061
- return acc
3062
- }, [])
3063
- }
3064
- return []
3065
- }
3066
- static merge(toArr, fromArr) {
3067
- (fromArr || []).map((from) => {
3068
- const found = toArr.find((to) => {
3069
- return to.key === from.key
3070
- })
3071
- if (found) {
3072
- found.value = _mergeValues(from.value, found.value)
3073
- } else {
3074
- toArr.push(from)
3075
- }
3076
- })
3077
- return toArr
3078
- }
3079
- static removeByKey(arr, key) {
3080
- return arr.reduce((acc, item) => {
3081
- if (!this.sameKey(item, key)) {
3082
- acc.push(item)
3083
- }
3084
- return acc
3085
- }, [])
3086
- }
3087
- static sameKey(item, key) {
3088
- if (item) {
3089
- return _isSame(item.key, key)
3090
- }
3091
- return false
3092
- }
3093
- static toObject(arr = []) {
3094
- if (Array.isArray(arr)) {
3095
- return arr.reduce((acc, item) => {
3096
- acc[item.key] = item.value
3097
- return acc
3098
- }, {})
3099
- }
3100
- return {}
3101
- }
3102
- static toString(arr = [], delimiter = '; ') {
3103
- if (Array.isArray(arr)) {
3104
- return arr.reduce((acc, item) => {
3105
- acc.push(`${item.key}: ${item.value}`)
3106
- return acc
3107
- }, []).join(delimiter)
3108
- }
3109
- return ''
3110
- }
3111
- static updateRecord(arr = [], key, value) {
3112
- return arr.map((item) => {
3113
- if (this.sameKey(item, key)) {
3114
- return {
3115
- ...item,
3116
- value
3117
- }
3118
- }
3119
- return item
3120
- })
3121
- }
3122
- static updateOrInsertRecord(arr = [], key, value) {
3123
- return this.insertOrUpdateRecord(arr, key, value)
3124
- }
3125
- static updateRecordsFromArray(arr = [], updateArr = []) {
3126
- if (Array.isArray(arr) && Array.isArray(updateArr)) {
3127
- const obj1 = this.toObject(arr)
3128
- const obj2 = this.toObject(updateArr)
3129
- return this.fromObject({
3130
- ...obj1,
3131
- ...obj2
3132
- })
3133
- }
3134
- return []
3135
- }
3136
- static values(arr = []) {
3137
- if (Array.isArray(arr)) {
3138
- return arr.reduce((acc, item) => {
3139
- acc.push(item.value)
3140
- return acc
3141
- }, [])
3142
- }
3143
- return []
3144
- }
3145
-
3146
- // getters
3147
- get isValid() {
3148
- return !!this.key
3149
- }
3150
-
3151
- get toObject() {
3152
- const obj = {}
3153
- if (this.isValid) {
3154
- obj[this.key] = this.value
3155
- }
3156
- return obj
3157
- }
3158
- }
3159
-
3160
- function _mergeValues(existingValue, newValue) {
3161
- if (existingValue === undefined) return newValue
3162
-
3163
- // Handle arrays by concatenating
3164
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
3165
- return [...new Set([...existingValue, ...newValue])]
3166
- }
3167
-
3168
- // Handle objects by merging
3169
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
3170
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
3171
- return { ...existingValue, ...newValue }
3172
- }
3173
-
3174
- // // Handle numbers by adding
3175
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
3176
- // return existingValue
3177
- // }
3178
-
3179
- // // Handle strings by concatenating
3180
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
3181
- // return existingValue
3182
- // }
3183
-
3184
- // Default: use the new value
3185
- return newValue
3186
- }
3187
-
3188
- function _isSame(key1, key2) {
3189
- return key1 === key2
3190
- }
3191
-
3192
-
3193
-
3194
- ;// ./lib/models/keyValueObject/index.js
3195
-
3196
-
3197
-
3198
-
3199
- ;// ./lib/models/metadata/metadata.js
3200
-
3201
-
3202
-
3203
- const DELIMITER = '_'
3204
-
3205
- class Metadata extends KeyValueObject {
3206
- static init(options = {}) {
3207
- if (options instanceof this) {
3208
- return options
3209
- }
3210
- const instance = new this({
3211
- ...options,
3212
- key: stringFormatter(options.key, DELIMITER),
3213
- })
3214
- return instance.isValid ? instance : null
3215
- }
3216
- static get _classname() {
3217
- return 'Metadata'
3218
- }
3219
-
3220
- static merge(toArr, fromArr) {
3221
- (fromArr || []).map((from) => {
3222
- const found = toArr.find((to) => {
3223
- return metadata_isSame(to.key, from.key)
3224
- })
3225
- if (found) {
3226
- found.value = metadata_mergeValues(from.value, found.value)
3227
- } else {
3228
- toArr.push(from)
3229
- }
3230
- })
3231
- return toArr
3232
- }
3233
- static sameKey(item, key) {
3234
- return metadata_isSame(item.key, key)
3235
- }
3236
- }
3237
-
3238
- function metadata_isSame(key1, key2) {
3239
- return stringFormatter(key1, DELIMITER) === stringFormatter(key2, DELIMITER)
3240
- }
3241
-
3242
- function metadata_mergeValues(existingValue, newValue) {
3243
- if (existingValue === undefined) return newValue
3244
-
3245
- // Handle arrays by concatenating
3246
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
3247
- return [...new Set([...existingValue, ...newValue])]
3248
- }
3249
-
3250
- // Handle objects by merging
3251
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
3252
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
3253
- return { ...existingValue, ...newValue }
3254
- }
3255
-
3256
- // // Handle numbers by adding
3257
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
3258
- // return existingValue
3259
- // }
3260
-
3261
- // // Handle strings by concatenating
3262
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
3263
- // return existingValue
3264
- // }
3265
-
3266
- // Default: use the new value
3267
- return newValue
3268
- }
3269
-
3270
-
3271
-
3272
- ;// ./lib/models/metadata/index.js
3273
-
3274
-
3275
-
3276
-
3277
- ;// ./lib/models/qMeta/qMeta.js
3278
-
3279
-
3280
- const updateAllowedProps = [
3281
- 'attributes',
3282
- 'ref'
3283
- ]
3284
-
3285
- class QMeta {
3286
- constructor(options = {}) {
3287
- options = options || {}
3288
- this.attributes = KeyValueObject.initOnlyValidFromArray(options.attributes)
3289
- this.ref = options.ref || {}
3290
- }
3291
-
3292
- static get _classname() {
3293
- return 'QMeta'
3294
- }
3295
- static get _superclass() {
3296
- return 'QMeta'
3297
- }
3298
-
3299
- // Class methods
3300
- static init(options = {}) {
3301
- if (options instanceof QMeta) {
3302
- return options
3303
- }
3304
- return new QMeta(options)
3305
- }
3306
-
3307
- // instance methods
3308
- addAttribute(obj) {
3309
- const kvObject = KeyValueObject.init(obj)
3310
- if (!kvObject) {
3311
- throw new Error('invalid meta attribute')
3312
- }
3313
- this.attributes.push(kvObject)
3314
- return this
3315
- }
3316
-
3317
- update(obj) {
3318
- Object.keys(obj).forEach((key) => {
3319
- if (updateAllowedProps.includes(key)) {
3320
- if (key === 'attributes') {
3321
- this[key] = KeyValueObject.initOnlyValidFromArray(obj[key])
3322
- } else {
3323
- this[key] = obj[key]
3324
- }
3325
- }
3326
- })
3327
- return this
3328
- }
3329
- }
3330
-
3331
-
3332
-
3333
- ;// ./lib/models/qMeta/index.js
3334
-
3335
-
3336
-
3337
-
3338
- ;// ./lib/models/trackedEntity/trackedEntity.js
3339
-
3340
-
3341
- class TrackedEntity {
3342
- constructor(options = {}) {
3343
- options = options || {}
3344
- const timestamp = Date.now()
3345
- this.meta = {
3346
- active: options.meta?.active ?? options.active ?? true,
3347
- created: options.meta?.created ?? (options.created
3348
- ? new Date(options.created).getTime()
3349
- : timestamp),
3350
- creator: options.meta?.creator ?? options.creator ?? '',
3351
- deleted: options.meta?.deleted ?? options.deleted ?? false,
3352
- modified: options.meta?.modified ?? (options.modified
3353
- ? new Date(options.modified).getTime()
3354
- : timestamp),
3355
- owner: options.meta?.owner ?? options.owner ?? '',
3356
- }
3357
-
3358
- // if (trackFlat) {
3359
- // Object.assign(this, _tracking)
3360
- // } else {
3361
- // this.meta = { ..._tracking, ...options.meta }
3362
- // }
3363
- }
3364
-
3365
- // Class methods
3366
- static get _classname() {
3367
- return 'TrackedEntity'
3368
- }
3369
- static get _superclass() {
3370
- return 'TrackedEntity'
3371
- }
3372
-
3373
- static init(options = {}) {
3374
- return init(this, options)
3375
- }
3376
- static initFromArray(arr = []) {
3377
- return initFromArray(this, arr)
3378
- }
3379
- static initOnlyValidFromArray(arr = []) {
3380
- return initOnlyValidFromArray(this, arr)
3381
- }
3382
- // static nest(entity) {
3383
- // const { active, created, creator, deleted, modified, owner, ...rest } = entity
3384
- // return { ...rest, meta: { active, created, creator, deleted, modified, owner } }
3385
- // }
3386
-
3387
- // getters
3388
- get isValid() {
3389
- return !!this
3390
- }
3391
- get active() {
3392
- return this.meta?.active ?? this.active
3393
- }
3394
- get created() {
3395
- return this.meta?.created ?? this.created
3396
- }
3397
- get creator() {
3398
- return this.meta?.creator ?? this.creator
3399
- }
3400
- get deleted() {
3401
- return this.meta?.deleted ?? this.deleted
3402
- }
3403
- get modified() {
3404
- return this.meta?.modified ?? this.modified
3405
- }
3406
- get owner() {
3407
- return this.meta?.owner ?? this.owner
3408
- }
3409
- changeCreatorOwner({ source, target }) {
3410
- return changeCreatorOwner(this, { source, target }).setModified()
3411
- }
3412
- delete() {
3413
- return this.setDeleted()
3414
- }
3415
- setActive() {
3416
- if (this.meta) {
3417
- this.meta.active = true
3418
- } else {
3419
- this.active = true
3420
- }
3421
- return this
3422
- }
3423
- setDeleted() {
3424
- if (this.meta) {
3425
- this.meta.deleted = true
3426
- } else {
3427
- this.deleted = true
3428
- }
3429
- return this
3430
- }
3431
- setModified() {
3432
- const timestamp = Date.now()
3433
- if (this.meta) {
3434
- this.meta.modified = timestamp
3435
- } else {
3436
- this.modified = timestamp
3437
- }
3438
- return this
3439
- }
3440
- setOwner(owner) {
3441
- if (!owner) {
3442
- return this
3443
- }
3444
- if (this.meta) {
3445
- this.meta.owner = owner
3446
- } else {
3447
- this.owner = owner
3448
- }
3449
- return this
3450
- }
3451
- unsetActive() {
3452
- if (this.meta) {
3453
- this.meta.active = false
3454
- } else {
3455
- this.active = false
3456
- }
3457
- return this
3458
- }
3459
- unsetDeleted() {
3460
- if (this.meta) {
3461
- this.meta.deleted = false
3462
- } else {
3463
- this.deleted = false
3464
- }
3465
- return this
3466
- }
3467
-
3468
- update(update) {
3469
- if (update.meta) {
3470
- this.meta = { ...this.meta, ...update.meta }
3471
- }
3472
- return this.setModified()
3473
- }
3474
- }
3475
-
3476
- ;// ./lib/models/trackedEntity/index.js
3477
-
3478
- // Explicit named export (optional)
3479
-
3480
- ;// ./lib/models/tenantAwareEntity/tenantAwareEntity.js
3481
-
3482
-
3483
-
3484
-
3485
- class TenantAwareEntity extends TrackedEntity {
3486
- constructor(options = {}) {
3487
- options = options || {}
3488
-
3489
- /**
3490
- * instead of throw error, we choose to implement the isValid checking
3491
- */
3492
- // if (!options.tenantCode) {
3493
- // throw new Error('tenantCode required')
3494
- // }
3495
-
3496
- super(options)
3497
-
3498
- this._tenant = options._tenant
3499
-
3500
- this.metadata = Metadata.initOnlyValidFromArray(options.metadata)
3501
- this.remarks = KeyValueObject.initOnlyValidFromArray(options.remarks)
3502
- this.tenantCode = options.tenantCode // Required for multi-tenancy
3503
- }
3504
-
3505
- // Class methods
3506
- static get _classname() {
3507
- return 'TenantAwareEntity'
3508
- }
3509
- static get _superclass() {
3510
- return 'TenantAwareEntity'
3511
- }
3512
-
3513
- // getters
3514
- get isValid() {
3515
- return super.isValid && !!this.tenantCode // Required for multi-tenancy
3516
- }
3517
-
3518
- // instance methods
3519
- getMetadata() {
3520
- return this.metadata
3521
- }
3522
- getMetadataByKey(key) {
3523
- return Metadata.foundByKey(this.metadata, key)
3524
- }
3525
- getMetadataValueByKey(key) {
3526
- const found = this.getMetadataByKey(key)
3527
- return found ? found.value : null
3528
- }
3529
- getRemarks() {
3530
- return this.remarks
3531
- }
3532
- getRemarkByKey(key) {
3533
- return KeyValueObject.foundByKey(this.remarks, key)
3534
- }
3535
- getRemarksValueByKey(key) {
3536
- const found = this.getRemarkByKey(key)
3537
- return found ? found.value : null
3538
- }
3539
- getTenantCode() {
3540
- return this.tenantCode
3541
- }
3542
-
3543
- update(update) {
3544
- if (update.metadata && Array.isArray(update.metadata)) {
3545
- this.metadata = Metadata.initOnlyValidFromArray(update.metadata)
3546
- }
3547
- if (update.remarks && Array.isArray(update.remarks)) {
3548
- this.remarks = KeyValueObject.initOnlyValidFromArray(update.remarks)
3549
- }
3550
- return super.update(update)
3551
- }
3552
- }
3553
-
3554
- ;// ./lib/models/tenantAwareEntity/index.js
3555
-
3556
-
3557
-
3558
- ;// ./lib/models/uniqueKeyGenerator/uniqueKeyGenerator.js
3559
-
3560
-
3561
- class UniqueKeyGenerator {
3562
- static get _classname() {
3563
- return 'UniqueKeyGenerator'
3564
- }
3565
- static get _superclass() {
3566
- return 'UniqueKeyGenerator'
3567
- }
3568
- static makeFormatter({ fieldName, format, options }) {
3569
- switch (format) {
3570
- case 'set_code':
3571
- return _makeSetCode(fieldName, options)
3572
- default:
3573
- return _makeSetCode(fieldName, options)
3574
- }
3575
- }
3576
- static makeGenerator(arr) {
3577
- const fns = arr.map((item) => this.makeFormatter(item))
3578
- return async (obj) => {
3579
- const output = await pReduce(fns, async (acc, fn) => {
3580
- const _obj = await fn(obj)
3581
- return Object.assign(acc, _obj)
3582
- }, obj)
3583
- return output
3584
- }
3585
- }
3586
- }
3587
-
3588
- function _makeSetCode(fieldName, options) {
3589
- return async (obj = {}) => {
3590
- if (obj[fieldName]) {
3591
- return {}
3592
- }
3593
- return {
3594
- [fieldName]: stringHelper.setCode()
3595
- }
3596
- }
3597
- }
3598
-
3599
-
3600
-
3601
- ;// ./lib/models/uniqueKeyGenerator/index.js
3602
-
3603
-
3604
-
3605
-
3606
- ;// ./lib/models/index.js
3607
-
3608
-
3609
-
3610
-
3611
-
3612
-
3613
-
3614
-
3615
-
3616
-
3617
-
3618
-
3619
- ;// ./lib/index.js
3620
-
3621
-
3622
-
3623
- ;// ./index.js
3624
-
3625
-
3626
- /******/ return __webpack_exports__;
3627
- /******/ })()
3628
- ;
3629
- });