@kivacore/app-utils 0.0.0 → 0.22.1

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.
Files changed (41) hide show
  1. package/README.md +1515 -1
  2. package/dist/index.d.ts +82 -0
  3. package/dist/index.js +2304 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.native.js +4695 -0
  6. package/dist/index.native.js.map +1 -0
  7. package/dist/query.d.ts +54 -0
  8. package/dist/query.js +269 -0
  9. package/dist/query.js.map +1 -0
  10. package/dist/types-GNkXRpu4.d.ts +754 -0
  11. package/package.json +57 -3
  12. package/src/app-config-client.ts +48 -0
  13. package/src/async-each-helper.ts +98 -0
  14. package/src/brand-client.ts +80 -0
  15. package/src/data-form-client.ts +85 -0
  16. package/src/data-source-client.ts +298 -0
  17. package/src/data-source-queries.ts +149 -0
  18. package/src/data-view-client.ts +92 -0
  19. package/src/date-utils.test.ts +48 -0
  20. package/src/date-utils.ts +146 -0
  21. package/src/envelope-interceptor.ts +65 -0
  22. package/src/get-tenant-preferences.test.ts +42 -0
  23. package/src/get-tenant-preferences.ts +30 -0
  24. package/src/handlebars-async-helpers.d.ts +12 -0
  25. package/src/index.native.ts +9 -0
  26. package/src/index.ts +88 -0
  27. package/src/inventory-client.ts +725 -0
  28. package/src/jsonata-helpers.ts +545 -0
  29. package/src/number-utils.ts +305 -0
  30. package/src/php-date-formatter.d.ts +8 -0
  31. package/src/query.ts +5 -0
  32. package/src/shims/stream.ts +11 -0
  33. package/src/template-engine.test.ts +47 -0
  34. package/src/template-engine.ts +298 -0
  35. package/src/types.ts +871 -0
  36. package/src/unwrap-envelope.ts +51 -0
  37. package/src/user-app-config-client.ts +44 -0
  38. package/src/user-identity-client.ts +21 -0
  39. package/tsconfig.json +9 -0
  40. package/tsup.config.ts +71 -0
  41. package/vitest.config.mts +13 -0
@@ -0,0 +1,4695 @@
1
+ import Handlebars from 'handlebars';
2
+ import jsonata from 'jsonata';
3
+ import { endOfQuarter, endOfToday, endOfWeek, endOfMonth, endOfDay, startOfQuarter, startOfToday, startOfWeek, startOfMonth, startOfDay, differenceInBusinessDays, differenceInSeconds, differenceInMinutes, differenceInHours, differenceInDays, differenceInWeeks, differenceInMonths, differenceInYears, isPast, isEqual as isEqual$1, isBefore, isAfter, subMilliseconds, subSeconds, subMinutes, subHours, subDays, subWeeks, subMonths, subYears, addMilliseconds, addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears, formatRelative, formatISO, formatDuration, formatDistanceToNowStrict, formatDistanceToNow, formatDistanceStrict, formatDistance, format } from 'date-fns';
4
+
5
+ var __create = Object.create;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __esm = (fn, res, err) => function __init() {
12
+ if (err) throw err[0];
13
+ try {
14
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
+ } catch (e) {
16
+ throw err = [e], e;
17
+ }
18
+ };
19
+ var __commonJS = (cb, mod) => function __require() {
20
+ try {
21
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
22
+ } catch (e) {
23
+ throw mod = 0, e;
24
+ }
25
+ };
26
+ var __export = (target, all) => {
27
+ for (var name in all)
28
+ __defProp(target, name, { get: all[name], enumerable: true });
29
+ };
30
+ var __copyProps = (to, from, except, desc) => {
31
+ if (from && typeof from === "object" || typeof from === "function") {
32
+ for (let key of __getOwnPropNames(from))
33
+ if (!__hasOwnProp.call(to, key) && key !== except)
34
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
35
+ }
36
+ return to;
37
+ };
38
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
39
+ // If the importer is in node compatibility mode or this is not an ESM
40
+ // file that has been converted to a CommonJS file using a Babel-
41
+ // compatible transform (i.e. "__esModule" has not been set), then set
42
+ // "default" to the CommonJS "module.exports" for node compatibility.
43
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
44
+ mod
45
+ ));
46
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
47
+
48
+ // ../../node_modules/.pnpm/php-date-formatter@1.3.7/node_modules/php-date-formatter/js/php-date-formatter.js
49
+ var require_php_date_formatter = __commonJS({
50
+ "../../node_modules/.pnpm/php-date-formatter@1.3.7/node_modules/php-date-formatter/js/php-date-formatter.js"(exports, module) {
51
+ (function(root, factory) {
52
+ if (typeof define === "function" && define.amd) {
53
+ define([], factory);
54
+ } else {
55
+ if (typeof module === "object" && module.exports) {
56
+ module.exports = factory();
57
+ } else {
58
+ root.DateFormatter = factory();
59
+ }
60
+ }
61
+ })(typeof self !== "undefined" ? self : exports, function() {
62
+ var DateFormatter2, $h;
63
+ $h = {
64
+ DAY: 1e3 * 60 * 60 * 24,
65
+ HOUR: 3600,
66
+ defaults: {
67
+ dateSettings: {
68
+ days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
69
+ daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
70
+ months: [
71
+ "January",
72
+ "February",
73
+ "March",
74
+ "April",
75
+ "May",
76
+ "June",
77
+ "July",
78
+ "August",
79
+ "September",
80
+ "October",
81
+ "November",
82
+ "December"
83
+ ],
84
+ monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
85
+ meridiem: ["AM", "PM"],
86
+ ordinal: function(number) {
87
+ var n = number % 10, suffixes = { 1: "st", 2: "nd", 3: "rd" };
88
+ return Math.floor(number % 100 / 10) === 1 || !suffixes[n] ? "th" : suffixes[n];
89
+ }
90
+ },
91
+ separators: /[ \-+\/.:@]/g,
92
+ validParts: /[dDjlNSwzWFmMntLoYyaABgGhHisueTIOPZcrU]/g,
93
+ intParts: /[djwNzmnyYhHgGis]/g,
94
+ tzParts: /\b(?:[PMCEA][SDP]T|(?:Australian|Pacific|Mountain|Central|Eastern|Atlantic) (?:Eastern) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
95
+ tzClip: /[^-+\dA-Z]/g
96
+ },
97
+ getInt: function(str, radix) {
98
+ return parseInt(str, radix ? radix : 10);
99
+ },
100
+ compare: function(str1, str2) {
101
+ return typeof str1 === "string" && typeof str2 === "string" && str1.toLowerCase() === str2.toLowerCase();
102
+ },
103
+ lpad: function(value, length, chr) {
104
+ var val = value.toString();
105
+ chr = chr || "0";
106
+ return val.length < length ? $h.lpad(chr + val, length) : val;
107
+ },
108
+ merge: function(out) {
109
+ var i, obj;
110
+ out = out || {};
111
+ for (i = 1; i < arguments.length; i++) {
112
+ obj = arguments[i];
113
+ if (!obj) {
114
+ continue;
115
+ }
116
+ for (var key in obj) {
117
+ if (obj.hasOwnProperty(key)) {
118
+ if (typeof obj[key] === "object") {
119
+ $h.merge(out[key], obj[key]);
120
+ } else {
121
+ out[key] = obj[key];
122
+ }
123
+ }
124
+ }
125
+ }
126
+ return out;
127
+ },
128
+ getIndex: function(val, arr) {
129
+ for (var i = 0; i < arr.length; i++) {
130
+ if (arr[i].toLowerCase() === val.toLowerCase()) {
131
+ return i;
132
+ }
133
+ }
134
+ return -1;
135
+ }
136
+ };
137
+ DateFormatter2 = function(options) {
138
+ var self2 = this, config = $h.merge($h.defaults, options);
139
+ self2.dateSettings = config.dateSettings;
140
+ self2.separators = config.separators;
141
+ self2.validParts = config.validParts;
142
+ self2.intParts = config.intParts;
143
+ self2.tzParts = config.tzParts;
144
+ self2.tzClip = config.tzClip;
145
+ };
146
+ DateFormatter2.prototype = {
147
+ constructor: DateFormatter2,
148
+ getMonth: function(val) {
149
+ var self2 = this, i;
150
+ i = $h.getIndex(val, self2.dateSettings.monthsShort) + 1;
151
+ if (i === 0) {
152
+ i = $h.getIndex(val, self2.dateSettings.months) + 1;
153
+ }
154
+ return i;
155
+ },
156
+ parseDate: function(vDate, vFormat) {
157
+ var self2 = this, vFormatParts, vDateParts, i, vDateFlag = false, vTimeFlag = false, vDatePart, iDatePart, vSettings = self2.dateSettings, vMonth, vMeriIndex, vMeriOffset, len, mer, out = { date: null, year: null, month: null, day: null, hour: 0, min: 0, sec: 0 };
158
+ if (!vDate) {
159
+ return null;
160
+ }
161
+ if (vDate instanceof Date) {
162
+ return vDate;
163
+ }
164
+ if (vFormat === "U") {
165
+ i = $h.getInt(vDate);
166
+ return i ? new Date(i * 1e3) : vDate;
167
+ }
168
+ switch (typeof vDate) {
169
+ case "number":
170
+ return new Date(vDate);
171
+ case "string":
172
+ break;
173
+ default:
174
+ return null;
175
+ }
176
+ vFormatParts = vFormat.match(self2.validParts);
177
+ if (!vFormatParts || vFormatParts.length === 0) {
178
+ throw new Error("Invalid date format definition.");
179
+ }
180
+ for (i = vFormatParts.length - 1; i >= 0; i--) {
181
+ if (vFormatParts[i] === "S") {
182
+ vFormatParts.splice(i, 1);
183
+ }
184
+ }
185
+ vDateParts = vDate.replace(self2.separators, "\0").split("\0");
186
+ for (i = 0; i < vDateParts.length; i++) {
187
+ vDatePart = vDateParts[i];
188
+ iDatePart = $h.getInt(vDatePart);
189
+ switch (vFormatParts[i]) {
190
+ case "y":
191
+ case "Y":
192
+ if (iDatePart) {
193
+ len = vDatePart.length;
194
+ out.year = len === 2 ? $h.getInt((iDatePart < 70 ? "20" : "19") + vDatePart) : iDatePart;
195
+ } else {
196
+ return null;
197
+ }
198
+ vDateFlag = true;
199
+ break;
200
+ case "m":
201
+ case "n":
202
+ case "M":
203
+ case "F":
204
+ if (isNaN(iDatePart)) {
205
+ vMonth = self2.getMonth(vDatePart);
206
+ if (vMonth > 0) {
207
+ out.month = vMonth;
208
+ } else {
209
+ return null;
210
+ }
211
+ } else {
212
+ if (iDatePart >= 1 && iDatePart <= 12) {
213
+ out.month = iDatePart;
214
+ } else {
215
+ return null;
216
+ }
217
+ }
218
+ vDateFlag = true;
219
+ break;
220
+ case "d":
221
+ case "j":
222
+ if (iDatePart >= 1 && iDatePart <= 31) {
223
+ out.day = iDatePart;
224
+ } else {
225
+ return null;
226
+ }
227
+ vDateFlag = true;
228
+ break;
229
+ case "g":
230
+ case "h":
231
+ vMeriIndex = vFormatParts.indexOf("a") > -1 ? vFormatParts.indexOf("a") : vFormatParts.indexOf("A") > -1 ? vFormatParts.indexOf("A") : -1;
232
+ mer = vDateParts[vMeriIndex];
233
+ if (vMeriIndex !== -1) {
234
+ vMeriOffset = $h.compare(mer, vSettings.meridiem[0]) ? 0 : $h.compare(mer, vSettings.meridiem[1]) ? 12 : -1;
235
+ if (iDatePart >= 1 && iDatePart <= 12 && vMeriOffset !== -1) {
236
+ out.hour = iDatePart % 12 === 0 ? vMeriOffset : iDatePart + vMeriOffset;
237
+ } else {
238
+ if (iDatePart >= 0 && iDatePart <= 23) {
239
+ out.hour = iDatePart;
240
+ }
241
+ }
242
+ } else {
243
+ if (iDatePart >= 0 && iDatePart <= 23) {
244
+ out.hour = iDatePart;
245
+ } else {
246
+ return null;
247
+ }
248
+ }
249
+ vTimeFlag = true;
250
+ break;
251
+ case "G":
252
+ case "H":
253
+ if (iDatePart >= 0 && iDatePart <= 23) {
254
+ out.hour = iDatePart;
255
+ } else {
256
+ return null;
257
+ }
258
+ vTimeFlag = true;
259
+ break;
260
+ case "i":
261
+ if (iDatePart >= 0 && iDatePart <= 59) {
262
+ out.min = iDatePart;
263
+ } else {
264
+ return null;
265
+ }
266
+ vTimeFlag = true;
267
+ break;
268
+ case "s":
269
+ if (iDatePart >= 0 && iDatePart <= 59) {
270
+ out.sec = iDatePart;
271
+ } else {
272
+ return null;
273
+ }
274
+ vTimeFlag = true;
275
+ break;
276
+ }
277
+ }
278
+ if (vDateFlag === true) {
279
+ var varY = out.year || 0, varM = out.month ? out.month - 1 : 0, varD = out.day || 1;
280
+ out.date = new Date(varY, varM, varD, out.hour, out.min, out.sec, 0);
281
+ } else {
282
+ if (vTimeFlag !== true) {
283
+ return null;
284
+ }
285
+ out.date = new Date(0, 0, 0, out.hour, out.min, out.sec, 0);
286
+ }
287
+ return out.date;
288
+ },
289
+ guessDate: function(vDateStr, vFormat) {
290
+ if (typeof vDateStr !== "string") {
291
+ return vDateStr;
292
+ }
293
+ var self2 = this, vParts = vDateStr.replace(self2.separators, "\0").split("\0"), vPattern = /^[djmn]/g, len, vFormatParts = vFormat.match(self2.validParts), vDate = /* @__PURE__ */ new Date(), vDigit = 0, vYear, i, n, iPart, iSec;
294
+ if (!vPattern.test(vFormatParts[0])) {
295
+ return vDateStr;
296
+ }
297
+ for (i = 0; i < vParts.length; i++) {
298
+ vDigit = 2;
299
+ iPart = vParts[i];
300
+ iSec = $h.getInt(iPart.substr(0, 2));
301
+ if (isNaN(iSec)) {
302
+ return null;
303
+ }
304
+ switch (i) {
305
+ case 0:
306
+ if (vFormatParts[0] === "m" || vFormatParts[0] === "n") {
307
+ vDate.setMonth(iSec - 1);
308
+ } else {
309
+ vDate.setDate(iSec);
310
+ }
311
+ break;
312
+ case 1:
313
+ if (vFormatParts[0] === "m" || vFormatParts[0] === "n") {
314
+ vDate.setDate(iSec);
315
+ } else {
316
+ vDate.setMonth(iSec - 1);
317
+ }
318
+ break;
319
+ case 2:
320
+ vYear = vDate.getFullYear();
321
+ len = iPart.length;
322
+ vDigit = len < 4 ? len : 4;
323
+ vYear = $h.getInt(len < 4 ? vYear.toString().substr(0, 4 - len) + iPart : iPart.substr(0, 4));
324
+ if (!vYear) {
325
+ return null;
326
+ }
327
+ vDate.setFullYear(vYear);
328
+ break;
329
+ case 3:
330
+ vDate.setHours(iSec);
331
+ break;
332
+ case 4:
333
+ vDate.setMinutes(iSec);
334
+ break;
335
+ case 5:
336
+ vDate.setSeconds(iSec);
337
+ break;
338
+ }
339
+ n = iPart.substr(vDigit);
340
+ if (n.length > 0) {
341
+ vParts.splice(i + 1, 0, n);
342
+ }
343
+ }
344
+ return vDate;
345
+ },
346
+ parseFormat: function(vChar, vDate) {
347
+ var self2 = this, vSettings = self2.dateSettings, fmt, backslash = /\\?(.?)/gi, doFormat = function(t, s) {
348
+ return fmt[t] ? fmt[t]() : s;
349
+ };
350
+ fmt = {
351
+ /////////
352
+ // DAY //
353
+ /////////
354
+ /**
355
+ * Day of month with leading 0: `01..31`
356
+ * @return {string}
357
+ */
358
+ d: function() {
359
+ return $h.lpad(fmt.j(), 2);
360
+ },
361
+ /**
362
+ * Shorthand day name: `Mon...Sun`
363
+ * @return {string}
364
+ */
365
+ D: function() {
366
+ return vSettings.daysShort[fmt.w()];
367
+ },
368
+ /**
369
+ * Day of month: `1..31`
370
+ * @return {number}
371
+ */
372
+ j: function() {
373
+ return vDate.getDate();
374
+ },
375
+ /**
376
+ * Full day name: `Monday...Sunday`
377
+ * @return {string}
378
+ */
379
+ l: function() {
380
+ return vSettings.days[fmt.w()];
381
+ },
382
+ /**
383
+ * ISO-8601 day of week: `1[Mon]..7[Sun]`
384
+ * @return {number}
385
+ */
386
+ N: function() {
387
+ return fmt.w() || 7;
388
+ },
389
+ /**
390
+ * Day of week: `0[Sun]..6[Sat]`
391
+ * @return {number}
392
+ */
393
+ w: function() {
394
+ return vDate.getDay();
395
+ },
396
+ /**
397
+ * Day of year: `0..365`
398
+ * @return {number}
399
+ */
400
+ z: function() {
401
+ var a = new Date(fmt.Y(), fmt.n() - 1, fmt.j()), b = new Date(fmt.Y(), 0, 1);
402
+ return Math.round((a - b) / $h.DAY);
403
+ },
404
+ //////////
405
+ // WEEK //
406
+ //////////
407
+ /**
408
+ * ISO-8601 week number
409
+ * @return {number}
410
+ */
411
+ W: function() {
412
+ var a = new Date(fmt.Y(), fmt.n() - 1, fmt.j() - fmt.N() + 3), b = new Date(a.getFullYear(), 0, 4);
413
+ return $h.lpad(1 + Math.round((a - b) / $h.DAY / 7), 2);
414
+ },
415
+ ///////////
416
+ // MONTH //
417
+ ///////////
418
+ /**
419
+ * Full month name: `January...December`
420
+ * @return {string}
421
+ */
422
+ F: function() {
423
+ return vSettings.months[vDate.getMonth()];
424
+ },
425
+ /**
426
+ * Month w/leading 0: `01..12`
427
+ * @return {string}
428
+ */
429
+ m: function() {
430
+ return $h.lpad(fmt.n(), 2);
431
+ },
432
+ /**
433
+ * Shorthand month name; `Jan...Dec`
434
+ * @return {string}
435
+ */
436
+ M: function() {
437
+ return vSettings.monthsShort[vDate.getMonth()];
438
+ },
439
+ /**
440
+ * Month: `1...12`
441
+ * @return {number}
442
+ */
443
+ n: function() {
444
+ return vDate.getMonth() + 1;
445
+ },
446
+ /**
447
+ * Days in month: `28...31`
448
+ * @return {number}
449
+ */
450
+ t: function() {
451
+ return new Date(fmt.Y(), fmt.n(), 0).getDate();
452
+ },
453
+ //////////
454
+ // YEAR //
455
+ //////////
456
+ /**
457
+ * Is leap year? `0 or 1`
458
+ * @return {number}
459
+ */
460
+ L: function() {
461
+ var Y = fmt.Y();
462
+ return Y % 4 === 0 && Y % 100 !== 0 || Y % 400 === 0 ? 1 : 0;
463
+ },
464
+ /**
465
+ * ISO-8601 year
466
+ * @return {number}
467
+ */
468
+ o: function() {
469
+ var n = fmt.n(), W = fmt.W(), Y = fmt.Y();
470
+ return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0);
471
+ },
472
+ /**
473
+ * Full year: `e.g. 1980...2010`
474
+ * @return {number}
475
+ */
476
+ Y: function() {
477
+ return vDate.getFullYear();
478
+ },
479
+ /**
480
+ * Last two digits of year: `00...99`
481
+ * @return {string}
482
+ */
483
+ y: function() {
484
+ return fmt.Y().toString().slice(-2);
485
+ },
486
+ //////////
487
+ // TIME //
488
+ //////////
489
+ /**
490
+ * Meridian lower: `am or pm`
491
+ * @return {string}
492
+ */
493
+ a: function() {
494
+ return fmt.A().toLowerCase();
495
+ },
496
+ /**
497
+ * Meridian upper: `AM or PM`
498
+ * @return {string}
499
+ */
500
+ A: function() {
501
+ var n = fmt.G() < 12 ? 0 : 1;
502
+ return vSettings.meridiem[n];
503
+ },
504
+ /**
505
+ * Swatch Internet time: `000..999`
506
+ * @return {string}
507
+ */
508
+ B: function() {
509
+ var H = vDate.getUTCHours() * $h.HOUR, i = vDate.getUTCMinutes() * 60, s = vDate.getUTCSeconds();
510
+ return $h.lpad(Math.floor((H + i + s + $h.HOUR) / 86.4) % 1e3, 3);
511
+ },
512
+ /**
513
+ * 12-Hours: `1..12`
514
+ * @return {number}
515
+ */
516
+ g: function() {
517
+ return fmt.G() % 12 || 12;
518
+ },
519
+ /**
520
+ * 24-Hours: `0..23`
521
+ * @return {number}
522
+ */
523
+ G: function() {
524
+ return vDate.getHours();
525
+ },
526
+ /**
527
+ * 12-Hours with leading 0: `01..12`
528
+ * @return {string}
529
+ */
530
+ h: function() {
531
+ return $h.lpad(fmt.g(), 2);
532
+ },
533
+ /**
534
+ * 24-Hours w/leading 0: `00..23`
535
+ * @return {string}
536
+ */
537
+ H: function() {
538
+ return $h.lpad(fmt.G(), 2);
539
+ },
540
+ /**
541
+ * Minutes w/leading 0: `00..59`
542
+ * @return {string}
543
+ */
544
+ i: function() {
545
+ return $h.lpad(vDate.getMinutes(), 2);
546
+ },
547
+ /**
548
+ * Seconds w/leading 0: `00..59`
549
+ * @return {string}
550
+ */
551
+ s: function() {
552
+ return $h.lpad(vDate.getSeconds(), 2);
553
+ },
554
+ /**
555
+ * Microseconds: `000000-999000`
556
+ * @return {string}
557
+ */
558
+ u: function() {
559
+ return $h.lpad(vDate.getMilliseconds() * 1e3, 6);
560
+ },
561
+ //////////////
562
+ // TIMEZONE //
563
+ //////////////
564
+ /**
565
+ * Timezone identifier: `e.g. Atlantic/Azores, ...`
566
+ * @return {string}
567
+ */
568
+ e: function() {
569
+ var str = /\((.*)\)/.exec(String(vDate))[1];
570
+ return str || "Coordinated Universal Time";
571
+ },
572
+ /**
573
+ * DST observed? `0 or 1`
574
+ * @return {number}
575
+ */
576
+ I: function() {
577
+ var a = new Date(fmt.Y(), 0), c = Date.UTC(fmt.Y(), 0), b = new Date(fmt.Y(), 6), d = Date.UTC(fmt.Y(), 6);
578
+ return a - c !== b - d ? 1 : 0;
579
+ },
580
+ /**
581
+ * Difference to GMT in hour format: `e.g. +0200`
582
+ * @return {string}
583
+ */
584
+ O: function() {
585
+ var tzo = vDate.getTimezoneOffset(), a = Math.abs(tzo);
586
+ return (tzo > 0 ? "-" : "+") + $h.lpad(Math.floor(a / 60) * 100 + a % 60, 4);
587
+ },
588
+ /**
589
+ * Difference to GMT with colon: `e.g. +02:00`
590
+ * @return {string}
591
+ */
592
+ P: function() {
593
+ var O = fmt.O();
594
+ return O.substr(0, 3) + ":" + O.substr(3, 2);
595
+ },
596
+ /**
597
+ * Timezone abbreviation: `e.g. EST, MDT, ...`
598
+ * @return {string}
599
+ */
600
+ T: function() {
601
+ var str = (String(vDate).match(self2.tzParts) || [""]).pop().replace(self2.tzClip, "");
602
+ return str || "UTC";
603
+ },
604
+ /**
605
+ * Timezone offset in seconds: `-43200...50400`
606
+ * @return {number}
607
+ */
608
+ Z: function() {
609
+ return -vDate.getTimezoneOffset() * 60;
610
+ },
611
+ ////////////////////
612
+ // FULL DATE TIME //
613
+ ////////////////////
614
+ /**
615
+ * ISO-8601 date
616
+ * @return {string}
617
+ */
618
+ c: function() {
619
+ return "Y-m-d\\TH:i:sP".replace(backslash, doFormat);
620
+ },
621
+ /**
622
+ * RFC 2822 date
623
+ * @return {string}
624
+ */
625
+ r: function() {
626
+ return "D, d M Y H:i:s O".replace(backslash, doFormat);
627
+ },
628
+ /**
629
+ * Seconds since UNIX epoch
630
+ * @return {number}
631
+ */
632
+ U: function() {
633
+ return vDate.getTime() / 1e3 || 0;
634
+ }
635
+ };
636
+ return doFormat(vChar, vChar);
637
+ },
638
+ formatDate: function(vDate, vFormat) {
639
+ var self2 = this, i, n, len, str, vChar, vDateStr = "", BACKSLASH = "\\";
640
+ if (typeof vDate === "string") {
641
+ vDate = self2.parseDate(vDate, vFormat);
642
+ if (!vDate) {
643
+ return null;
644
+ }
645
+ }
646
+ if (vDate instanceof Date) {
647
+ len = vFormat.length;
648
+ for (i = 0; i < len; i++) {
649
+ vChar = vFormat.charAt(i);
650
+ if (vChar === "S" || vChar === BACKSLASH) {
651
+ continue;
652
+ }
653
+ if (i > 0 && vFormat.charAt(i - 1) === BACKSLASH) {
654
+ vDateStr += vChar;
655
+ continue;
656
+ }
657
+ str = self2.parseFormat(vChar, vDate);
658
+ if (i !== len - 1 && self2.intParts.test(vChar) && vFormat.charAt(i + 1) === "S") {
659
+ n = $h.getInt(str) || 0;
660
+ str += self2.dateSettings.ordinal(n);
661
+ }
662
+ vDateStr += str;
663
+ }
664
+ return vDateStr;
665
+ }
666
+ return "";
667
+ }
668
+ };
669
+ Object.freeze(DateFormatter2);
670
+ return DateFormatter2;
671
+ });
672
+ }
673
+ });
674
+
675
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/package.json
676
+ var require_package = __commonJS({
677
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/package.json"(exports, module) {
678
+ module.exports = {
679
+ name: "handlebars-async-helpers",
680
+ version: "1.0.6",
681
+ description: "Adding async function support to handlebars helpers",
682
+ main: "index.js",
683
+ scripts: {
684
+ test: "mocha --ui bdd --recursive --timeout 15000"
685
+ },
686
+ repository: "https://github.com/gastonrobledo/handlebars-async-helpers",
687
+ author: "Gaston Robledo",
688
+ license: "MIT",
689
+ peerDependencies: {
690
+ handlebars: "4.7.6"
691
+ },
692
+ devDependencies: {
693
+ handlebars: "^4.7.6",
694
+ eslint: "^8.9.0",
695
+ "eslint-config-airbnb": "^19.0.4",
696
+ "eslint-config-standard": "^12.0.0",
697
+ "eslint-plugin-import": "^2.14.0",
698
+ "eslint-plugin-node": "^8.0.0",
699
+ "eslint-plugin-promise": "^4.0.1",
700
+ "eslint-plugin-standard": "^4.0.0",
701
+ mocha: "^9.2.0",
702
+ should: "^13.2.3"
703
+ }
704
+ };
705
+ }
706
+ });
707
+
708
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/utils.js
709
+ var require_utils = __commonJS({
710
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/utils.js"(exports, module) {
711
+ function blockParams(params, ids) {
712
+ params.path = ids;
713
+ return params;
714
+ }
715
+ function extend(obj) {
716
+ for (let i = 1; i < arguments.length; i++) {
717
+ for (const key in arguments[i]) {
718
+ if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
719
+ obj[key] = arguments[i][key];
720
+ }
721
+ }
722
+ }
723
+ return obj;
724
+ }
725
+ function appendContextPath(contextPath, id) {
726
+ return (contextPath ? `${contextPath}.` : "") + id;
727
+ }
728
+ function createFrame(object) {
729
+ const frame = extend({}, object);
730
+ frame._parent = object;
731
+ return frame;
732
+ }
733
+ function isEmpty(value) {
734
+ if (!value && value !== 0) {
735
+ return true;
736
+ }
737
+ if (Array.isArray(value) && value.length === 0) {
738
+ return true;
739
+ }
740
+ return false;
741
+ }
742
+ function isPromise(value) {
743
+ return typeof value === "object" && value !== null && typeof value.then === "function";
744
+ }
745
+ module.exports = {
746
+ blockParams,
747
+ extend,
748
+ appendContextPath,
749
+ createFrame,
750
+ isEmpty,
751
+ isPromise
752
+ };
753
+ }
754
+ });
755
+
756
+ // src/shims/stream.ts
757
+ var stream_exports = {};
758
+ __export(stream_exports, {
759
+ Readable: () => Readable,
760
+ default: () => stream_default
761
+ });
762
+ var Readable, stream_default;
763
+ var init_stream = __esm({
764
+ "src/shims/stream.ts"() {
765
+ Readable = class {
766
+ };
767
+ stream_default = { Readable };
768
+ }
769
+ });
770
+
771
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/each.js
772
+ var require_each = __commonJS({
773
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/each.js"(exports, module) {
774
+ var {
775
+ appendContextPath,
776
+ createFrame,
777
+ blockParams,
778
+ isPromise
779
+ } = require_utils();
780
+ var { Readable: Readable2 } = (init_stream(), __toCommonJS(stream_exports));
781
+ module.exports = (handlebars) => {
782
+ handlebars.registerHelper("each", async function(context, options) {
783
+ if (!options) {
784
+ throw new Error("Must pass iterator to #each");
785
+ }
786
+ let { fn } = options, { inverse } = options, i = 0, ret = [], data, contextPath;
787
+ if (options.data && options.ids) {
788
+ contextPath = `${appendContextPath(options.data.contextPath, options.ids[0])}.`;
789
+ }
790
+ if (typeof context === "function") {
791
+ context = context.call(this);
792
+ }
793
+ if (options.data) {
794
+ data = createFrame(options.data);
795
+ }
796
+ async function execIteration(field, index2, last) {
797
+ if (data) {
798
+ data.key = field;
799
+ data.index = index2;
800
+ data.first = index2 === 0;
801
+ data.last = !!last;
802
+ if (contextPath) {
803
+ data.contextPath = contextPath + field;
804
+ }
805
+ }
806
+ ret.push(await fn(context[field], {
807
+ data,
808
+ blockParams: blockParams(
809
+ [context[field], field],
810
+ [contextPath + field, null]
811
+ )
812
+ }));
813
+ }
814
+ if (context && typeof context === "object") {
815
+ if (isPromise(context)) {
816
+ context = await context;
817
+ }
818
+ if (Array.isArray(context)) {
819
+ for (let j = context.length; i < j; i++) {
820
+ if (i in context) {
821
+ await execIteration(i, i, i === context.length - 1);
822
+ }
823
+ }
824
+ } else if (global.Symbol && context[global.Symbol.iterator]) {
825
+ const newContext = [], iterator = context[global.Symbol.iterator]();
826
+ for (let it = iterator.next(); !it.done; it = iterator.next()) {
827
+ newContext.push(it.value);
828
+ }
829
+ context = newContext;
830
+ for (let j = context.length; i < j; i++) {
831
+ await execIteration(i, i, i === context.length - 1);
832
+ }
833
+ } else if (context instanceof Readable2) {
834
+ const newContext = [];
835
+ await new Promise((resolve, reject) => {
836
+ context.on("data", (item) => {
837
+ newContext.push(item);
838
+ }).on("end", async () => {
839
+ context = newContext;
840
+ for (let j = context.length; i < j; i++) {
841
+ await execIteration(i, i, i === context.length - 1);
842
+ }
843
+ resolve();
844
+ }).once("error", (e) => reject(e));
845
+ });
846
+ } else {
847
+ let priorKey;
848
+ for (const key of Object.keys(context)) {
849
+ if (priorKey !== void 0) {
850
+ await execIteration(priorKey, i - 1);
851
+ }
852
+ priorKey = key;
853
+ i++;
854
+ }
855
+ if (priorKey !== void 0) {
856
+ await execIteration(priorKey, i - 1, true);
857
+ }
858
+ }
859
+ }
860
+ if (i === 0) {
861
+ ret = inverse(this);
862
+ }
863
+ return ret.join("");
864
+ });
865
+ };
866
+ }
867
+ });
868
+
869
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/if.js
870
+ var require_if = __commonJS({
871
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/if.js"(exports, module) {
872
+ var { isPromise, isEmpty } = require_utils();
873
+ module.exports = (handlebars) => {
874
+ handlebars.registerHelper("if", async function(conditional, options) {
875
+ if (arguments.length !== 2) {
876
+ throw new Error("#if requires exactly one argument");
877
+ }
878
+ if (typeof conditional === "function") {
879
+ conditional = conditional.call(this);
880
+ } else if (isPromise(conditional)) {
881
+ conditional = await conditional;
882
+ }
883
+ if (!options.hash.includeZero && !conditional || isEmpty(conditional)) {
884
+ return options.inverse(this);
885
+ } else {
886
+ return options.fn(this);
887
+ }
888
+ });
889
+ handlebars.registerHelper("unless", function(conditional, options) {
890
+ if (arguments.length !== 2) {
891
+ throw new Error("#unless requires exactly one argument");
892
+ }
893
+ return handlebars.helpers["if"].call(this, conditional, {
894
+ fn: options.inverse,
895
+ inverse: options.fn,
896
+ hash: options.hash
897
+ });
898
+ });
899
+ };
900
+ }
901
+ });
902
+
903
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/with.js
904
+ var require_with = __commonJS({
905
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/with.js"(exports, module) {
906
+ var { isPromise, isEmpty, createFrame, appendContextPath, blockParams } = require_utils();
907
+ module.exports = (handlebars) => {
908
+ handlebars.registerHelper("with", async function(context, options) {
909
+ if (arguments.length !== 2) {
910
+ throw new Error("#with requires exactly one argument");
911
+ }
912
+ if (typeof context === "function") {
913
+ context = context.call(this);
914
+ } else if (isPromise(context)) {
915
+ context = await context;
916
+ }
917
+ const { fn } = options;
918
+ if (!isEmpty(context)) {
919
+ let { data } = options;
920
+ if (options.data && options.ids) {
921
+ data = createFrame(options.data);
922
+ data.contextPath = appendContextPath(
923
+ options.data.contextPath,
924
+ options.ids[0]
925
+ );
926
+ }
927
+ return fn(context, {
928
+ data,
929
+ blockParams: blockParams([context], [data && data.contextPath])
930
+ });
931
+ }
932
+ return options.inverse(this);
933
+ });
934
+ };
935
+ }
936
+ });
937
+
938
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/index.js
939
+ var require_helpers = __commonJS({
940
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/helpers/index.js"(exports, module) {
941
+ module.exports = {
942
+ registerCoreHelpers: (handlebars) => {
943
+ require_each()(handlebars);
944
+ require_if()(handlebars);
945
+ require_with()(handlebars);
946
+ }
947
+ };
948
+ }
949
+ });
950
+
951
+ // ../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/index.js
952
+ var require_handlebars_async_helpers = __commonJS({
953
+ "../../node_modules/.pnpm/handlebars-async-helpers@1.0.6_handlebars@4.7.10/node_modules/handlebars-async-helpers/index.js"(exports, module) {
954
+ var app = require_package();
955
+ var { registerCoreHelpers } = require_helpers();
956
+ var isPromise = (obj) => !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function";
957
+ function asyncHelpers2(hbs) {
958
+ const handlebars = hbs.create(), asyncCompiler = class extends hbs.JavaScriptCompiler {
959
+ constructor() {
960
+ super();
961
+ this.compiler = asyncCompiler;
962
+ }
963
+ mergeSource(varDeclarations) {
964
+ const sources = super.mergeSource(varDeclarations);
965
+ sources.prepend("return (async () => {");
966
+ sources.add(" })()");
967
+ return sources;
968
+ }
969
+ appendToBuffer(source, location, explicit) {
970
+ if (!Array.isArray(source)) {
971
+ source = [source];
972
+ }
973
+ source = this.source.wrap(source, location);
974
+ if (this.environment.isSimple) {
975
+ return ["return await ", source, ";"];
976
+ }
977
+ if (explicit) {
978
+ return ["buffer += await ", source, ";"];
979
+ }
980
+ source.appendToBuffer = true;
981
+ source.prepend("await ");
982
+ return source;
983
+ }
984
+ };
985
+ handlebars.JavaScriptCompiler = asyncCompiler;
986
+ const _compile = handlebars.compile, _template = handlebars.VM.template, _escapeExpression = handlebars.escapeExpression, escapeExpression = function(value) {
987
+ if (isPromise(value)) {
988
+ return value.then((v) => _escapeExpression(v));
989
+ }
990
+ return _escapeExpression(value);
991
+ };
992
+ function lookupProperty(containerLookupProperty) {
993
+ return function(parent, propertyName) {
994
+ if (isPromise(parent)) {
995
+ return parent.then((p) => containerLookupProperty(p, propertyName));
996
+ }
997
+ return containerLookupProperty(parent, propertyName);
998
+ };
999
+ }
1000
+ handlebars.template = function(spec) {
1001
+ spec.main_d = (prog, props, container, depth, data, blockParams, depths) => async (context) => {
1002
+ container.escapeExpression = escapeExpression;
1003
+ container.lookupProperty = lookupProperty(container.lookupProperty);
1004
+ const v = spec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
1005
+ return v;
1006
+ };
1007
+ return _template(spec, handlebars);
1008
+ };
1009
+ handlebars.compile = function(template, options) {
1010
+ const compiled = _compile.apply(handlebars, [template, { ...options }]);
1011
+ return function(context, execOptions) {
1012
+ context = context || {};
1013
+ return compiled.call(handlebars, context, execOptions);
1014
+ };
1015
+ };
1016
+ handlebars.ASYNC_VERSION = app.version;
1017
+ registerCoreHelpers(handlebars);
1018
+ return handlebars;
1019
+ }
1020
+ module.exports = asyncHelpers2;
1021
+ }
1022
+ });
1023
+
1024
+ // src/unwrap-envelope.ts
1025
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set([
1026
+ "data",
1027
+ "success",
1028
+ "meta",
1029
+ "error",
1030
+ "message"
1031
+ ]);
1032
+ function unwrapEnvelope(response) {
1033
+ if (response !== null && typeof response === "object" && !Array.isArray(response)) {
1034
+ const keys = Object.keys(response);
1035
+ const looksLikeEnvelope2 = "data" in response && keys.every((key) => ENVELOPE_KEYS.has(key));
1036
+ if (looksLikeEnvelope2) {
1037
+ return response.data;
1038
+ }
1039
+ }
1040
+ return response;
1041
+ }
1042
+
1043
+ // src/get-tenant-preferences.ts
1044
+ async function getTenantPreferences(client) {
1045
+ return client.get("/v1/tenant/preferences");
1046
+ }
1047
+ async function getTenantPreferenceSummary(client) {
1048
+ const { preferences, tenant, product } = unwrapEnvelope(
1049
+ await client.get("/v1/tenant/preferences", { includeEnums: false })
1050
+ );
1051
+ return {
1052
+ preferences: preferences ? {
1053
+ ...preferences,
1054
+ date_format: preferences.date_format ?? preferences.dateFormat,
1055
+ date_time_format: preferences.date_time_format ?? preferences.dateTimeFormat,
1056
+ long_date_format: preferences.long_date_format ?? preferences.longDateFormat,
1057
+ time_format: preferences.time_format ?? preferences.timeFormat,
1058
+ time_zone: preferences.time_zone ?? preferences.timeZone,
1059
+ thousand_separator: preferences.thousand_separator ?? preferences.thousandSeparator,
1060
+ decimal_separator: preferences.decimal_separator ?? preferences.decimalSeparator,
1061
+ decimal_precision: preferences.decimal_precision ?? preferences.decimalPrecision
1062
+ } : null,
1063
+ tenant,
1064
+ product
1065
+ };
1066
+ }
1067
+
1068
+ // src/date-utils.ts
1069
+ var import_php_date_formatter = __toESM(require_php_date_formatter());
1070
+ var TIMEZONE_SUFFIX_RE = /([+-]\d{2}:\d{2}|Z)\s*$/;
1071
+ function applyTimezone(date, timezone) {
1072
+ return new Date(date.toLocaleString("en-US", { timeZone: timezone }));
1073
+ }
1074
+ function parseDate(value) {
1075
+ return new Date(value);
1076
+ }
1077
+ function parseDatetime(value) {
1078
+ const hasTimezone = TIMEZONE_SUFFIX_RE.test(value);
1079
+ return hasTimezone ? new Date(value) : /* @__PURE__ */ new Date(`${value}Z`);
1080
+ }
1081
+ var dateNameCache = /* @__PURE__ */ new Map();
1082
+ function partOf(formatter, date, type) {
1083
+ return formatter.formatToParts(date).find((part) => part.type === type)?.value ?? "";
1084
+ }
1085
+ function getDateNames(locale) {
1086
+ const tag = locale?.trim().replace(/_/g, "-");
1087
+ if (!tag || /^en(-|$)/i.test(tag)) return null;
1088
+ const cached = dateNameCache.get(tag);
1089
+ if (cached !== void 0) return cached;
1090
+ let names = null;
1091
+ try {
1092
+ const weekdayLong = new Intl.DateTimeFormat(tag, { weekday: "long", timeZone: "UTC" });
1093
+ const weekdayShort = new Intl.DateTimeFormat(tag, { weekday: "short", timeZone: "UTC" });
1094
+ const monthLong = new Intl.DateTimeFormat(tag, { day: "numeric", month: "long", timeZone: "UTC" });
1095
+ const monthShort = new Intl.DateTimeFormat(tag, { day: "numeric", month: "short", timeZone: "UTC" });
1096
+ const weekdays = Array.from({ length: 7 }, (_, i) => new Date(Date.UTC(2023, 0, 1 + i)));
1097
+ const months = Array.from({ length: 12 }, (_, i) => new Date(Date.UTC(2023, i, 15)));
1098
+ names = {
1099
+ days: weekdays.map((date) => partOf(weekdayLong, date, "weekday")),
1100
+ daysShort: weekdays.map((date) => partOf(weekdayShort, date, "weekday")),
1101
+ months: months.map((date) => partOf(monthLong, date, "month")),
1102
+ monthsShort: months.map((date) => partOf(monthShort, date, "month"))
1103
+ };
1104
+ } catch {
1105
+ names = null;
1106
+ }
1107
+ dateNameCache.set(tag, names);
1108
+ return names;
1109
+ }
1110
+ function createFormatter(locale) {
1111
+ const formatter = new import_php_date_formatter.default();
1112
+ const names = getDateNames(locale);
1113
+ if (names) {
1114
+ const instance = formatter;
1115
+ instance.dateSettings = { ...instance.dateSettings, ...names };
1116
+ }
1117
+ return formatter;
1118
+ }
1119
+ function createDateUtils(config) {
1120
+ const { preferences, userTimezone = "UTC", locale } = config;
1121
+ const formatter = createFormatter(locale);
1122
+ function formatDate(date, options) {
1123
+ if (!date) return null;
1124
+ const format = options?.format ?? preferences.date_format ?? "Y-m-d";
1125
+ const timezone = options?.timezone ?? userTimezone;
1126
+ const parsed = applyTimezone(
1127
+ typeof date === "string" ? parseDate(date) : date,
1128
+ timezone
1129
+ );
1130
+ return formatter.formatDate(parsed, format);
1131
+ }
1132
+ function formatDateTime(date, options) {
1133
+ if (!date) return null;
1134
+ const format = options?.format ?? preferences.date_time_format ?? "Y-m-d H:i:s";
1135
+ const timezone = options?.timezone ?? userTimezone;
1136
+ const parsed = applyTimezone(
1137
+ typeof date === "string" ? parseDatetime(date) : date,
1138
+ timezone
1139
+ );
1140
+ return formatter.formatDate(parsed, format);
1141
+ }
1142
+ function formatDateLong(date, options) {
1143
+ if (!date) return null;
1144
+ const format = options?.format ?? preferences.long_date_format ?? "Y-m-d H:i:s";
1145
+ const timezone = options?.timezone ?? userTimezone;
1146
+ const parsed = applyTimezone(
1147
+ typeof date === "string" ? parseDate(date) : date,
1148
+ timezone
1149
+ );
1150
+ return formatter.formatDate(parsed, format);
1151
+ }
1152
+ function toUserTimezone(date) {
1153
+ const parsed = typeof date === "string" ? parseDatetime(date) : date;
1154
+ return applyTimezone(parsed, userTimezone);
1155
+ }
1156
+ return {
1157
+ formatDate,
1158
+ formatDateTime,
1159
+ formatDateLong,
1160
+ toUserTimezone
1161
+ };
1162
+ }
1163
+
1164
+ // src/number-utils.ts
1165
+ function createNumberUtils(config) {
1166
+ const { preferences } = config;
1167
+ function formatNumber(value, options) {
1168
+ if (value == null) return null;
1169
+ const precision = options?.decimalPrecision ?? preferences.decimal_precision ?? 2;
1170
+ const thousandSep = options?.thousandSeparator !== void 0 ? options.thousandSeparator : preferences.thousand_separator;
1171
+ const decimalSep = options?.decimalSeparator || preferences.decimal_separator;
1172
+ if (thousandSep && decimalSep) {
1173
+ const formatted = parseFloat(String(value)).toFixed(precision);
1174
+ const parts = formatted.split(".");
1175
+ parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep);
1176
+ return parts.join(decimalSep);
1177
+ }
1178
+ const resolvedLocale = preferences.locale?.replace("_", "-") || "en-US";
1179
+ return value.toLocaleString(resolvedLocale, {
1180
+ minimumFractionDigits: precision,
1181
+ maximumFractionDigits: precision,
1182
+ useGrouping: !!thousandSep
1183
+ });
1184
+ }
1185
+ return { formatNumber };
1186
+ }
1187
+ var THOUSAND_SEP = ".";
1188
+ var DECIMAL_SEP = ",";
1189
+ function phpNumberFormat(value, decimals = 2) {
1190
+ const num = Number(value);
1191
+ if (isNaN(num)) return `0${DECIMAL_SEP}${"0".repeat(decimals)}`;
1192
+ const [intPart, decPart] = num.toFixed(decimals).split(".");
1193
+ return `${intPart.replace(/\B(?=(\d{3})+(?!\d))/g, THOUSAND_SEP)}${DECIMAL_SEP}${decPart}`;
1194
+ }
1195
+ var DIGITS_1_TR = [
1196
+ "",
1197
+ "B\u0130R",
1198
+ "\u0130K\u0130",
1199
+ "\xDC\xC7",
1200
+ "D\xD6RT",
1201
+ "BE\u015E",
1202
+ "ALTI",
1203
+ "YED\u0130",
1204
+ "SEK\u0130Z",
1205
+ "DOKUZ"
1206
+ ];
1207
+ var DIGITS_10_TR = [
1208
+ "",
1209
+ "ON",
1210
+ "Y\u0130RM\u0130",
1211
+ "OTUZ",
1212
+ "KIRK",
1213
+ "ELL\u0130",
1214
+ "ALTMI\u015E",
1215
+ "YETM\u0130\u015E",
1216
+ "SEKSEN",
1217
+ "DOKSAN"
1218
+ ];
1219
+ var DIGITS_100_TR = [
1220
+ "",
1221
+ "Y\xDCZ",
1222
+ "\u0130K\u0130Y\xDCZ",
1223
+ "\xDC\xC7Y\xDCZ",
1224
+ "D\xD6RTY\xDCZ",
1225
+ "BE\u015EY\xDCZ",
1226
+ "ALTIY\xDCZ",
1227
+ "YED\u0130Y\xDCZ",
1228
+ "SEK\u0130ZY\xDCZ",
1229
+ "DOKUZY\xDCZ"
1230
+ ];
1231
+ var SCALE_TR = [
1232
+ "",
1233
+ "",
1234
+ "B\u0130N",
1235
+ "M\u0130LYON",
1236
+ "M\u0130LYAR",
1237
+ "TR\u0130LYON",
1238
+ "KAT\u0130R\u0130LYON",
1239
+ "KENT\u0130LYON",
1240
+ "SEKS\u0130LYON",
1241
+ "SEPT\u0130LYON",
1242
+ "OKT\u0130LYON"
1243
+ ];
1244
+ function toWordTR(value, useSpaces) {
1245
+ const formatted = phpNumberFormat(value);
1246
+ const [intPart, decPart] = formatted.split(DECIMAL_SEP);
1247
+ const groups = intPart.split(THOUSAND_SEP).reverse();
1248
+ let integerStr = "";
1249
+ groups.forEach((group, idx) => {
1250
+ const padded = group.padStart(3, "0");
1251
+ const d1 = parseInt(padded[0], 10);
1252
+ const d2 = parseInt(padded[1], 10);
1253
+ const d3 = parseInt(padded[2], 10);
1254
+ const groupIndex = groups.length - idx;
1255
+ if (groupIndex === groups.length && d1 === 0 && d2 === 0 && d3 === 1 && groups.length > 1) {
1256
+ integerStr += " ";
1257
+ } else {
1258
+ integerStr += ` ${DIGITS_100_TR[d1]} ${DIGITS_10_TR[d2]} ${DIGITS_1_TR[d3]} `;
1259
+ }
1260
+ integerStr += SCALE_TR[groupIndex] || "";
1261
+ });
1262
+ const paddedDec = decPart.padEnd(2, "0");
1263
+ const decStr = `${DIGITS_10_TR[parseInt(paddedDec[0], 10)]} ${DIGITS_1_TR[parseInt(paddedDec[1], 10)]}`;
1264
+ if (!useSpaces) {
1265
+ integerStr = integerStr.replace(/ /g, "");
1266
+ }
1267
+ return [integerStr.replace(/ {2,}/g, " ").trim(), decStr.replace(/ {2,}/g, " ").trim()];
1268
+ }
1269
+ var DIGITS_1_EN = [
1270
+ "",
1271
+ "ONE",
1272
+ "TWO",
1273
+ "THREE",
1274
+ "FOUR",
1275
+ "FIVE",
1276
+ "SIX",
1277
+ "SEVEN",
1278
+ "EIGHT",
1279
+ "NINE"
1280
+ ];
1281
+ var DIGITS_TEEN_EN = [
1282
+ "",
1283
+ "ELEVEN",
1284
+ "TWELVE",
1285
+ "THIRTEEN",
1286
+ "FOURTEEN",
1287
+ "FIFTEEN",
1288
+ "SIXTEEN",
1289
+ "SEVENTEEN",
1290
+ "EIGHTEEN",
1291
+ "NINETEEN"
1292
+ ];
1293
+ var DIGITS_10_EN = [
1294
+ "",
1295
+ "TEN",
1296
+ "TWENTY",
1297
+ "THIRTY",
1298
+ "FORTY",
1299
+ "FIFTY",
1300
+ "SIXTY",
1301
+ "SEVENTY",
1302
+ "EIGHTY",
1303
+ "NINETY"
1304
+ ];
1305
+ var DIGITS_100_EN = [
1306
+ "",
1307
+ "HUNDRED",
1308
+ "TWO HUNDRED",
1309
+ "THREE HUNDRED",
1310
+ "FOUR HUNDRED",
1311
+ "FIVE HUNDRED",
1312
+ "SIX HUNDRED",
1313
+ "SEVEN HUNDRED",
1314
+ "EIGHT HUNDRED",
1315
+ "NINE HUNDRED"
1316
+ ];
1317
+ var SCALE_EN = [
1318
+ "",
1319
+ "",
1320
+ "THOUSAND",
1321
+ "MILLION",
1322
+ "BILLION",
1323
+ "TRILLION",
1324
+ "QUADRILLION",
1325
+ "QUINTILLION",
1326
+ "SEXTILLION",
1327
+ "SEPTILLION",
1328
+ "OCTILLION"
1329
+ ];
1330
+ function toWordEN(value, useSpaces) {
1331
+ const formatted = phpNumberFormat(value);
1332
+ const [intPart, decPart] = formatted.split(DECIMAL_SEP);
1333
+ const groups = intPart.split(THOUSAND_SEP).reverse();
1334
+ let integerStr = "";
1335
+ groups.forEach((group, idx) => {
1336
+ const padded = group.padStart(3, "0");
1337
+ const d1 = parseInt(padded[0], 10);
1338
+ const d2 = parseInt(padded[1], 10);
1339
+ const d3 = parseInt(padded[2], 10);
1340
+ const groupIndex = groups.length - idx;
1341
+ if (groupIndex === groups.length && d1 === 0 && d2 === 0 && d3 === 1 && groups.length > 1) {
1342
+ integerStr += " ";
1343
+ } else if (d2 === 1 && d3 >= 1) {
1344
+ integerStr += ` ${DIGITS_100_EN[d1]} ${DIGITS_TEEN_EN[d3]} `;
1345
+ } else {
1346
+ integerStr += ` ${DIGITS_100_EN[d1]} ${DIGITS_10_EN[d2]} ${DIGITS_1_EN[d3]} `;
1347
+ }
1348
+ integerStr += SCALE_EN[groupIndex] || "";
1349
+ });
1350
+ const paddedDec = decPart.padEnd(2, "0");
1351
+ const dec1 = parseInt(paddedDec[0], 10);
1352
+ const dec2 = parseInt(paddedDec[1], 10);
1353
+ const decStr = dec1 === 1 && dec2 >= 1 ? DIGITS_TEEN_EN[dec2] : `${DIGITS_10_EN[dec1]} ${DIGITS_1_EN[dec2]}`;
1354
+ if (!useSpaces) {
1355
+ integerStr = integerStr.replace(/ /g, "");
1356
+ }
1357
+ return [integerStr.replace(/ {2,}/g, " ").trim(), decStr.replace(/ {2,}/g, " ").trim()];
1358
+ }
1359
+ var WORD_CONVERTERS = {
1360
+ TR: toWordTR,
1361
+ EN: toWordEN
1362
+ };
1363
+ var CURRENCY_LABELS = {
1364
+ TRY: { unit: "T\xDCRK L\u0130RASI", subunit: "KURU\u015E" },
1365
+ EUR: { unit: "EURO", subunit: "CENT" },
1366
+ USD: { unit: "DOLAR", subunit: "CENT" },
1367
+ GBP: { unit: "STERL\u0130N", subunit: "PENNY" },
1368
+ JPY: { unit: "YEN", subunit: "SEN" }
1369
+ };
1370
+ function formatNumberToWords(value, options) {
1371
+ const lang = options?.lang ?? "TR";
1372
+ const currency = options?.currency ?? "TRY";
1373
+ const useSpaces = options?.useSpaces ?? false;
1374
+ const num = value ?? 0;
1375
+ const [intWords, decWords] = WORD_CONVERTERS[lang](num, useSpaces);
1376
+ const labels = CURRENCY_LABELS[currency] ?? CURRENCY_LABELS.TRY;
1377
+ let result = "";
1378
+ if (intWords) {
1379
+ result += `${intWords} ${labels.unit}`;
1380
+ }
1381
+ if (decWords) {
1382
+ result += ` ${decWords} ${labels.subunit}`;
1383
+ }
1384
+ return result.trim();
1385
+ }
1386
+ function formatDurationAsTime(seconds) {
1387
+ const hours = Math.floor(seconds / 3600);
1388
+ const minutes = Math.floor(seconds % 3600 / 60);
1389
+ return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
1390
+ }
1391
+ function formatDurationAsHours(seconds, decimalPrecision = 2) {
1392
+ if (!seconds) return "0";
1393
+ return (seconds / 3600).toFixed(decimalPrecision);
1394
+ }
1395
+ function formatDurationAsWords(seconds) {
1396
+ const hours = Math.floor(seconds / 3600);
1397
+ const minutes = Math.floor(seconds % 3600 / 60);
1398
+ let result = "";
1399
+ if (hours > 0) {
1400
+ result += `${hours} hr${hours !== 1 ? "s" : ""} `;
1401
+ }
1402
+ if (minutes > 0) {
1403
+ result += `${minutes} min${minutes !== 1 ? "s" : ""}`;
1404
+ }
1405
+ return result.trim() || "0 mins";
1406
+ }
1407
+
1408
+ // src/template-engine.ts
1409
+ var import_handlebars_async_helpers = __toESM(require_handlebars_async_helpers());
1410
+
1411
+ // ../../node_modules/.pnpm/jsonpath-plus@10.4.0/node_modules/jsonpath-plus/dist/index-browser-esm.js
1412
+ var Hooks = class {
1413
+ /**
1414
+ * @callback HookCallback
1415
+ * @this {*|Jsep} this
1416
+ * @param {Jsep} env
1417
+ * @returns: void
1418
+ */
1419
+ /**
1420
+ * Adds the given callback to the list of callbacks for the given hook.
1421
+ *
1422
+ * The callback will be invoked when the hook it is registered for is run.
1423
+ *
1424
+ * One callback function can be registered to multiple hooks and the same hook multiple times.
1425
+ *
1426
+ * @param {string|object} name The name of the hook, or an object of callbacks keyed by name
1427
+ * @param {HookCallback|boolean} callback The callback function which is given environment variables.
1428
+ * @param {?boolean} [first=false] Will add the hook to the top of the list (defaults to the bottom)
1429
+ * @public
1430
+ */
1431
+ add(name, callback, first) {
1432
+ if (typeof arguments[0] != "string") {
1433
+ for (let name2 in arguments[0]) {
1434
+ this.add(name2, arguments[0][name2], arguments[1]);
1435
+ }
1436
+ } else {
1437
+ (Array.isArray(name) ? name : [name]).forEach(function(name2) {
1438
+ this[name2] = this[name2] || [];
1439
+ if (callback) {
1440
+ this[name2][first ? "unshift" : "push"](callback);
1441
+ }
1442
+ }, this);
1443
+ }
1444
+ }
1445
+ /**
1446
+ * Runs a hook invoking all registered callbacks with the given environment variables.
1447
+ *
1448
+ * Callbacks will be invoked synchronously and in the order in which they were registered.
1449
+ *
1450
+ * @param {string} name The name of the hook.
1451
+ * @param {Object<string, any>} env The environment variables of the hook passed to all callbacks registered.
1452
+ * @public
1453
+ */
1454
+ run(name, env) {
1455
+ this[name] = this[name] || [];
1456
+ this[name].forEach(function(callback) {
1457
+ callback.call(env && env.context ? env.context : env, env);
1458
+ });
1459
+ }
1460
+ };
1461
+ var Plugins = class {
1462
+ constructor(jsep2) {
1463
+ this.jsep = jsep2;
1464
+ this.registered = {};
1465
+ }
1466
+ /**
1467
+ * @callback PluginSetup
1468
+ * @this {Jsep} jsep
1469
+ * @returns: void
1470
+ */
1471
+ /**
1472
+ * Adds the given plugin(s) to the registry
1473
+ *
1474
+ * @param {object} plugins
1475
+ * @param {string} plugins.name The name of the plugin
1476
+ * @param {PluginSetup} plugins.init The init function
1477
+ * @public
1478
+ */
1479
+ register() {
1480
+ for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {
1481
+ plugins[_key] = arguments[_key];
1482
+ }
1483
+ plugins.forEach((plugin2) => {
1484
+ if (typeof plugin2 !== "object" || !plugin2.name || !plugin2.init) {
1485
+ throw new Error("Invalid JSEP plugin format");
1486
+ }
1487
+ if (this.registered[plugin2.name]) {
1488
+ return;
1489
+ }
1490
+ plugin2.init(this.jsep);
1491
+ this.registered[plugin2.name] = plugin2;
1492
+ });
1493
+ }
1494
+ };
1495
+ var Jsep = class _Jsep {
1496
+ /**
1497
+ * @returns {string}
1498
+ */
1499
+ static get version() {
1500
+ return "1.4.0";
1501
+ }
1502
+ /**
1503
+ * @returns {string}
1504
+ */
1505
+ static toString() {
1506
+ return "JavaScript Expression Parser (JSEP) v" + _Jsep.version;
1507
+ }
1508
+ // ==================== CONFIG ================================
1509
+ /**
1510
+ * @method addUnaryOp
1511
+ * @param {string} op_name The name of the unary op to add
1512
+ * @returns {Jsep}
1513
+ */
1514
+ static addUnaryOp(op_name) {
1515
+ _Jsep.max_unop_len = Math.max(op_name.length, _Jsep.max_unop_len);
1516
+ _Jsep.unary_ops[op_name] = 1;
1517
+ return _Jsep;
1518
+ }
1519
+ /**
1520
+ * @method jsep.addBinaryOp
1521
+ * @param {string} op_name The name of the binary op to add
1522
+ * @param {number} precedence The precedence of the binary op (can be a float). Higher number = higher precedence
1523
+ * @param {boolean} [isRightAssociative=false] whether operator is right-associative
1524
+ * @returns {Jsep}
1525
+ */
1526
+ static addBinaryOp(op_name, precedence, isRightAssociative) {
1527
+ _Jsep.max_binop_len = Math.max(op_name.length, _Jsep.max_binop_len);
1528
+ _Jsep.binary_ops[op_name] = precedence;
1529
+ if (isRightAssociative) {
1530
+ _Jsep.right_associative.add(op_name);
1531
+ } else {
1532
+ _Jsep.right_associative.delete(op_name);
1533
+ }
1534
+ return _Jsep;
1535
+ }
1536
+ /**
1537
+ * @method addIdentifierChar
1538
+ * @param {string} char The additional character to treat as a valid part of an identifier
1539
+ * @returns {Jsep}
1540
+ */
1541
+ static addIdentifierChar(char) {
1542
+ _Jsep.additional_identifier_chars.add(char);
1543
+ return _Jsep;
1544
+ }
1545
+ /**
1546
+ * @method addLiteral
1547
+ * @param {string} literal_name The name of the literal to add
1548
+ * @param {*} literal_value The value of the literal
1549
+ * @returns {Jsep}
1550
+ */
1551
+ static addLiteral(literal_name, literal_value) {
1552
+ _Jsep.literals[literal_name] = literal_value;
1553
+ return _Jsep;
1554
+ }
1555
+ /**
1556
+ * @method removeUnaryOp
1557
+ * @param {string} op_name The name of the unary op to remove
1558
+ * @returns {Jsep}
1559
+ */
1560
+ static removeUnaryOp(op_name) {
1561
+ delete _Jsep.unary_ops[op_name];
1562
+ if (op_name.length === _Jsep.max_unop_len) {
1563
+ _Jsep.max_unop_len = _Jsep.getMaxKeyLen(_Jsep.unary_ops);
1564
+ }
1565
+ return _Jsep;
1566
+ }
1567
+ /**
1568
+ * @method removeAllUnaryOps
1569
+ * @returns {Jsep}
1570
+ */
1571
+ static removeAllUnaryOps() {
1572
+ _Jsep.unary_ops = {};
1573
+ _Jsep.max_unop_len = 0;
1574
+ return _Jsep;
1575
+ }
1576
+ /**
1577
+ * @method removeIdentifierChar
1578
+ * @param {string} char The additional character to stop treating as a valid part of an identifier
1579
+ * @returns {Jsep}
1580
+ */
1581
+ static removeIdentifierChar(char) {
1582
+ _Jsep.additional_identifier_chars.delete(char);
1583
+ return _Jsep;
1584
+ }
1585
+ /**
1586
+ * @method removeBinaryOp
1587
+ * @param {string} op_name The name of the binary op to remove
1588
+ * @returns {Jsep}
1589
+ */
1590
+ static removeBinaryOp(op_name) {
1591
+ delete _Jsep.binary_ops[op_name];
1592
+ if (op_name.length === _Jsep.max_binop_len) {
1593
+ _Jsep.max_binop_len = _Jsep.getMaxKeyLen(_Jsep.binary_ops);
1594
+ }
1595
+ _Jsep.right_associative.delete(op_name);
1596
+ return _Jsep;
1597
+ }
1598
+ /**
1599
+ * @method removeAllBinaryOps
1600
+ * @returns {Jsep}
1601
+ */
1602
+ static removeAllBinaryOps() {
1603
+ _Jsep.binary_ops = {};
1604
+ _Jsep.max_binop_len = 0;
1605
+ return _Jsep;
1606
+ }
1607
+ /**
1608
+ * @method removeLiteral
1609
+ * @param {string} literal_name The name of the literal to remove
1610
+ * @returns {Jsep}
1611
+ */
1612
+ static removeLiteral(literal_name) {
1613
+ delete _Jsep.literals[literal_name];
1614
+ return _Jsep;
1615
+ }
1616
+ /**
1617
+ * @method removeAllLiterals
1618
+ * @returns {Jsep}
1619
+ */
1620
+ static removeAllLiterals() {
1621
+ _Jsep.literals = {};
1622
+ return _Jsep;
1623
+ }
1624
+ // ==================== END CONFIG ============================
1625
+ /**
1626
+ * @returns {string}
1627
+ */
1628
+ get char() {
1629
+ return this.expr.charAt(this.index);
1630
+ }
1631
+ /**
1632
+ * @returns {number}
1633
+ */
1634
+ get code() {
1635
+ return this.expr.charCodeAt(this.index);
1636
+ }
1637
+ /**
1638
+ * @param {string} expr a string with the passed in express
1639
+ * @returns Jsep
1640
+ */
1641
+ constructor(expr) {
1642
+ this.expr = expr;
1643
+ this.index = 0;
1644
+ }
1645
+ /**
1646
+ * static top-level parser
1647
+ * @returns {jsep.Expression}
1648
+ */
1649
+ static parse(expr) {
1650
+ return new _Jsep(expr).parse();
1651
+ }
1652
+ /**
1653
+ * Get the longest key length of any object
1654
+ * @param {object} obj
1655
+ * @returns {number}
1656
+ */
1657
+ static getMaxKeyLen(obj) {
1658
+ return Math.max(0, ...Object.keys(obj).map((k) => k.length));
1659
+ }
1660
+ /**
1661
+ * `ch` is a character code in the next three functions
1662
+ * @param {number} ch
1663
+ * @returns {boolean}
1664
+ */
1665
+ static isDecimalDigit(ch) {
1666
+ return ch >= 48 && ch <= 57;
1667
+ }
1668
+ /**
1669
+ * Returns the precedence of a binary operator or `0` if it isn't a binary operator. Can be float.
1670
+ * @param {string} op_val
1671
+ * @returns {number}
1672
+ */
1673
+ static binaryPrecedence(op_val) {
1674
+ return _Jsep.binary_ops[op_val] || 0;
1675
+ }
1676
+ /**
1677
+ * Looks for start of identifier
1678
+ * @param {number} ch
1679
+ * @returns {boolean}
1680
+ */
1681
+ static isIdentifierStart(ch) {
1682
+ return ch >= 65 && ch <= 90 || // A...Z
1683
+ ch >= 97 && ch <= 122 || // a...z
1684
+ ch >= 128 && !_Jsep.binary_ops[String.fromCharCode(ch)] || // any non-ASCII that is not an operator
1685
+ _Jsep.additional_identifier_chars.has(String.fromCharCode(ch));
1686
+ }
1687
+ /**
1688
+ * @param {number} ch
1689
+ * @returns {boolean}
1690
+ */
1691
+ static isIdentifierPart(ch) {
1692
+ return _Jsep.isIdentifierStart(ch) || _Jsep.isDecimalDigit(ch);
1693
+ }
1694
+ /**
1695
+ * throw error at index of the expression
1696
+ * @param {string} message
1697
+ * @throws
1698
+ */
1699
+ throwError(message) {
1700
+ const error = new Error(message + " at character " + this.index);
1701
+ error.index = this.index;
1702
+ error.description = message;
1703
+ throw error;
1704
+ }
1705
+ /**
1706
+ * Run a given hook
1707
+ * @param {string} name
1708
+ * @param {jsep.Expression|false} [node]
1709
+ * @returns {?jsep.Expression}
1710
+ */
1711
+ runHook(name, node) {
1712
+ if (_Jsep.hooks[name]) {
1713
+ const env = {
1714
+ context: this,
1715
+ node
1716
+ };
1717
+ _Jsep.hooks.run(name, env);
1718
+ return env.node;
1719
+ }
1720
+ return node;
1721
+ }
1722
+ /**
1723
+ * Runs a given hook until one returns a node
1724
+ * @param {string} name
1725
+ * @returns {?jsep.Expression}
1726
+ */
1727
+ searchHook(name) {
1728
+ if (_Jsep.hooks[name]) {
1729
+ const env = {
1730
+ context: this
1731
+ };
1732
+ _Jsep.hooks[name].find(function(callback) {
1733
+ callback.call(env.context, env);
1734
+ return env.node;
1735
+ });
1736
+ return env.node;
1737
+ }
1738
+ }
1739
+ /**
1740
+ * Push `index` up to the next non-space character
1741
+ */
1742
+ gobbleSpaces() {
1743
+ let ch = this.code;
1744
+ while (ch === _Jsep.SPACE_CODE || ch === _Jsep.TAB_CODE || ch === _Jsep.LF_CODE || ch === _Jsep.CR_CODE) {
1745
+ ch = this.expr.charCodeAt(++this.index);
1746
+ }
1747
+ this.runHook("gobble-spaces");
1748
+ }
1749
+ /**
1750
+ * Top-level method to parse all expressions and returns compound or single node
1751
+ * @returns {jsep.Expression}
1752
+ */
1753
+ parse() {
1754
+ this.runHook("before-all");
1755
+ const nodes = this.gobbleExpressions();
1756
+ const node = nodes.length === 1 ? nodes[0] : {
1757
+ type: _Jsep.COMPOUND,
1758
+ body: nodes
1759
+ };
1760
+ return this.runHook("after-all", node);
1761
+ }
1762
+ /**
1763
+ * top-level parser (but can be reused within as well)
1764
+ * @param {number} [untilICode]
1765
+ * @returns {jsep.Expression[]}
1766
+ */
1767
+ gobbleExpressions(untilICode) {
1768
+ let nodes = [], ch_i, node;
1769
+ while (this.index < this.expr.length) {
1770
+ ch_i = this.code;
1771
+ if (ch_i === _Jsep.SEMCOL_CODE || ch_i === _Jsep.COMMA_CODE) {
1772
+ this.index++;
1773
+ } else {
1774
+ if (node = this.gobbleExpression()) {
1775
+ nodes.push(node);
1776
+ } else if (this.index < this.expr.length) {
1777
+ if (ch_i === untilICode) {
1778
+ break;
1779
+ }
1780
+ this.throwError('Unexpected "' + this.char + '"');
1781
+ }
1782
+ }
1783
+ }
1784
+ return nodes;
1785
+ }
1786
+ /**
1787
+ * The main parsing function.
1788
+ * @returns {?jsep.Expression}
1789
+ */
1790
+ gobbleExpression() {
1791
+ const node = this.searchHook("gobble-expression") || this.gobbleBinaryExpression();
1792
+ this.gobbleSpaces();
1793
+ return this.runHook("after-expression", node);
1794
+ }
1795
+ /**
1796
+ * Search for the operation portion of the string (e.g. `+`, `===`)
1797
+ * Start by taking the longest possible binary operations (3 characters: `===`, `!==`, `>>>`)
1798
+ * and move down from 3 to 2 to 1 character until a matching binary operation is found
1799
+ * then, return that binary operation
1800
+ * @returns {string|boolean}
1801
+ */
1802
+ gobbleBinaryOp() {
1803
+ this.gobbleSpaces();
1804
+ let to_check = this.expr.substr(this.index, _Jsep.max_binop_len);
1805
+ let tc_len = to_check.length;
1806
+ while (tc_len > 0) {
1807
+ if (_Jsep.binary_ops.hasOwnProperty(to_check) && (!_Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !_Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
1808
+ this.index += tc_len;
1809
+ return to_check;
1810
+ }
1811
+ to_check = to_check.substr(0, --tc_len);
1812
+ }
1813
+ return false;
1814
+ }
1815
+ /**
1816
+ * This function is responsible for gobbling an individual expression,
1817
+ * e.g. `1`, `1+2`, `a+(b*2)-Math.sqrt(2)`
1818
+ * @returns {?jsep.BinaryExpression}
1819
+ */
1820
+ gobbleBinaryExpression() {
1821
+ let node, biop, prec, stack, biop_info, left, right, i, cur_biop;
1822
+ left = this.gobbleToken();
1823
+ if (!left) {
1824
+ return left;
1825
+ }
1826
+ biop = this.gobbleBinaryOp();
1827
+ if (!biop) {
1828
+ return left;
1829
+ }
1830
+ biop_info = {
1831
+ value: biop,
1832
+ prec: _Jsep.binaryPrecedence(biop),
1833
+ right_a: _Jsep.right_associative.has(biop)
1834
+ };
1835
+ right = this.gobbleToken();
1836
+ if (!right) {
1837
+ this.throwError("Expected expression after " + biop);
1838
+ }
1839
+ stack = [left, biop_info, right];
1840
+ while (biop = this.gobbleBinaryOp()) {
1841
+ prec = _Jsep.binaryPrecedence(biop);
1842
+ if (prec === 0) {
1843
+ this.index -= biop.length;
1844
+ break;
1845
+ }
1846
+ biop_info = {
1847
+ value: biop,
1848
+ prec,
1849
+ right_a: _Jsep.right_associative.has(biop)
1850
+ };
1851
+ cur_biop = biop;
1852
+ const comparePrev = (prev) => biop_info.right_a && prev.right_a ? prec > prev.prec : prec <= prev.prec;
1853
+ while (stack.length > 2 && comparePrev(stack[stack.length - 2])) {
1854
+ right = stack.pop();
1855
+ biop = stack.pop().value;
1856
+ left = stack.pop();
1857
+ node = {
1858
+ type: _Jsep.BINARY_EXP,
1859
+ operator: biop,
1860
+ left,
1861
+ right
1862
+ };
1863
+ stack.push(node);
1864
+ }
1865
+ node = this.gobbleToken();
1866
+ if (!node) {
1867
+ this.throwError("Expected expression after " + cur_biop);
1868
+ }
1869
+ stack.push(biop_info, node);
1870
+ }
1871
+ i = stack.length - 1;
1872
+ node = stack[i];
1873
+ while (i > 1) {
1874
+ node = {
1875
+ type: _Jsep.BINARY_EXP,
1876
+ operator: stack[i - 1].value,
1877
+ left: stack[i - 2],
1878
+ right: node
1879
+ };
1880
+ i -= 2;
1881
+ }
1882
+ return node;
1883
+ }
1884
+ /**
1885
+ * An individual part of a binary expression:
1886
+ * e.g. `foo.bar(baz)`, `1`, `"abc"`, `(a % 2)` (because it's in parenthesis)
1887
+ * @returns {boolean|jsep.Expression}
1888
+ */
1889
+ gobbleToken() {
1890
+ let ch, to_check, tc_len, node;
1891
+ this.gobbleSpaces();
1892
+ node = this.searchHook("gobble-token");
1893
+ if (node) {
1894
+ return this.runHook("after-token", node);
1895
+ }
1896
+ ch = this.code;
1897
+ if (_Jsep.isDecimalDigit(ch) || ch === _Jsep.PERIOD_CODE) {
1898
+ return this.gobbleNumericLiteral();
1899
+ }
1900
+ if (ch === _Jsep.SQUOTE_CODE || ch === _Jsep.DQUOTE_CODE) {
1901
+ node = this.gobbleStringLiteral();
1902
+ } else if (ch === _Jsep.OBRACK_CODE) {
1903
+ node = this.gobbleArray();
1904
+ } else {
1905
+ to_check = this.expr.substr(this.index, _Jsep.max_unop_len);
1906
+ tc_len = to_check.length;
1907
+ while (tc_len > 0) {
1908
+ if (_Jsep.unary_ops.hasOwnProperty(to_check) && (!_Jsep.isIdentifierStart(this.code) || this.index + to_check.length < this.expr.length && !_Jsep.isIdentifierPart(this.expr.charCodeAt(this.index + to_check.length)))) {
1909
+ this.index += tc_len;
1910
+ const argument = this.gobbleToken();
1911
+ if (!argument) {
1912
+ this.throwError("missing unaryOp argument");
1913
+ }
1914
+ return this.runHook("after-token", {
1915
+ type: _Jsep.UNARY_EXP,
1916
+ operator: to_check,
1917
+ argument,
1918
+ prefix: true
1919
+ });
1920
+ }
1921
+ to_check = to_check.substr(0, --tc_len);
1922
+ }
1923
+ if (_Jsep.isIdentifierStart(ch)) {
1924
+ node = this.gobbleIdentifier();
1925
+ if (_Jsep.literals.hasOwnProperty(node.name)) {
1926
+ node = {
1927
+ type: _Jsep.LITERAL,
1928
+ value: _Jsep.literals[node.name],
1929
+ raw: node.name
1930
+ };
1931
+ } else if (node.name === _Jsep.this_str) {
1932
+ node = {
1933
+ type: _Jsep.THIS_EXP
1934
+ };
1935
+ }
1936
+ } else if (ch === _Jsep.OPAREN_CODE) {
1937
+ node = this.gobbleGroup();
1938
+ }
1939
+ }
1940
+ if (!node) {
1941
+ return this.runHook("after-token", false);
1942
+ }
1943
+ node = this.gobbleTokenProperty(node);
1944
+ return this.runHook("after-token", node);
1945
+ }
1946
+ /**
1947
+ * Gobble properties of of identifiers/strings/arrays/groups.
1948
+ * e.g. `foo`, `bar.baz`, `foo['bar'].baz`
1949
+ * It also gobbles function calls:
1950
+ * e.g. `Math.acos(obj.angle)`
1951
+ * @param {jsep.Expression} node
1952
+ * @returns {jsep.Expression}
1953
+ */
1954
+ gobbleTokenProperty(node) {
1955
+ this.gobbleSpaces();
1956
+ let ch = this.code;
1957
+ while (ch === _Jsep.PERIOD_CODE || ch === _Jsep.OBRACK_CODE || ch === _Jsep.OPAREN_CODE || ch === _Jsep.QUMARK_CODE) {
1958
+ let optional;
1959
+ if (ch === _Jsep.QUMARK_CODE) {
1960
+ if (this.expr.charCodeAt(this.index + 1) !== _Jsep.PERIOD_CODE) {
1961
+ break;
1962
+ }
1963
+ optional = true;
1964
+ this.index += 2;
1965
+ this.gobbleSpaces();
1966
+ ch = this.code;
1967
+ }
1968
+ this.index++;
1969
+ if (ch === _Jsep.OBRACK_CODE) {
1970
+ node = {
1971
+ type: _Jsep.MEMBER_EXP,
1972
+ computed: true,
1973
+ object: node,
1974
+ property: this.gobbleExpression()
1975
+ };
1976
+ if (!node.property) {
1977
+ this.throwError('Unexpected "' + this.char + '"');
1978
+ }
1979
+ this.gobbleSpaces();
1980
+ ch = this.code;
1981
+ if (ch !== _Jsep.CBRACK_CODE) {
1982
+ this.throwError("Unclosed [");
1983
+ }
1984
+ this.index++;
1985
+ } else if (ch === _Jsep.OPAREN_CODE) {
1986
+ node = {
1987
+ type: _Jsep.CALL_EXP,
1988
+ "arguments": this.gobbleArguments(_Jsep.CPAREN_CODE),
1989
+ callee: node
1990
+ };
1991
+ } else if (ch === _Jsep.PERIOD_CODE || optional) {
1992
+ if (optional) {
1993
+ this.index--;
1994
+ }
1995
+ this.gobbleSpaces();
1996
+ node = {
1997
+ type: _Jsep.MEMBER_EXP,
1998
+ computed: false,
1999
+ object: node,
2000
+ property: this.gobbleIdentifier()
2001
+ };
2002
+ }
2003
+ if (optional) {
2004
+ node.optional = true;
2005
+ }
2006
+ this.gobbleSpaces();
2007
+ ch = this.code;
2008
+ }
2009
+ return node;
2010
+ }
2011
+ /**
2012
+ * Parse simple numeric literals: `12`, `3.4`, `.5`. Do this by using a string to
2013
+ * keep track of everything in the numeric literal and then calling `parseFloat` on that string
2014
+ * @returns {jsep.Literal}
2015
+ */
2016
+ gobbleNumericLiteral() {
2017
+ let number = "", ch, chCode;
2018
+ while (_Jsep.isDecimalDigit(this.code)) {
2019
+ number += this.expr.charAt(this.index++);
2020
+ }
2021
+ if (this.code === _Jsep.PERIOD_CODE) {
2022
+ number += this.expr.charAt(this.index++);
2023
+ while (_Jsep.isDecimalDigit(this.code)) {
2024
+ number += this.expr.charAt(this.index++);
2025
+ }
2026
+ }
2027
+ ch = this.char;
2028
+ if (ch === "e" || ch === "E") {
2029
+ number += this.expr.charAt(this.index++);
2030
+ ch = this.char;
2031
+ if (ch === "+" || ch === "-") {
2032
+ number += this.expr.charAt(this.index++);
2033
+ }
2034
+ while (_Jsep.isDecimalDigit(this.code)) {
2035
+ number += this.expr.charAt(this.index++);
2036
+ }
2037
+ if (!_Jsep.isDecimalDigit(this.expr.charCodeAt(this.index - 1))) {
2038
+ this.throwError("Expected exponent (" + number + this.char + ")");
2039
+ }
2040
+ }
2041
+ chCode = this.code;
2042
+ if (_Jsep.isIdentifierStart(chCode)) {
2043
+ this.throwError("Variable names cannot start with a number (" + number + this.char + ")");
2044
+ } else if (chCode === _Jsep.PERIOD_CODE || number.length === 1 && number.charCodeAt(0) === _Jsep.PERIOD_CODE) {
2045
+ this.throwError("Unexpected period");
2046
+ }
2047
+ return {
2048
+ type: _Jsep.LITERAL,
2049
+ value: parseFloat(number),
2050
+ raw: number
2051
+ };
2052
+ }
2053
+ /**
2054
+ * Parses a string literal, staring with single or double quotes with basic support for escape codes
2055
+ * e.g. `"hello world"`, `'this is\nJSEP'`
2056
+ * @returns {jsep.Literal}
2057
+ */
2058
+ gobbleStringLiteral() {
2059
+ let str = "";
2060
+ const startIndex = this.index;
2061
+ const quote = this.expr.charAt(this.index++);
2062
+ let closed = false;
2063
+ while (this.index < this.expr.length) {
2064
+ let ch = this.expr.charAt(this.index++);
2065
+ if (ch === quote) {
2066
+ closed = true;
2067
+ break;
2068
+ } else if (ch === "\\") {
2069
+ ch = this.expr.charAt(this.index++);
2070
+ switch (ch) {
2071
+ case "n":
2072
+ str += "\n";
2073
+ break;
2074
+ case "r":
2075
+ str += "\r";
2076
+ break;
2077
+ case "t":
2078
+ str += " ";
2079
+ break;
2080
+ case "b":
2081
+ str += "\b";
2082
+ break;
2083
+ case "f":
2084
+ str += "\f";
2085
+ break;
2086
+ case "v":
2087
+ str += "\v";
2088
+ break;
2089
+ default:
2090
+ str += ch;
2091
+ }
2092
+ } else {
2093
+ str += ch;
2094
+ }
2095
+ }
2096
+ if (!closed) {
2097
+ this.throwError('Unclosed quote after "' + str + '"');
2098
+ }
2099
+ return {
2100
+ type: _Jsep.LITERAL,
2101
+ value: str,
2102
+ raw: this.expr.substring(startIndex, this.index)
2103
+ };
2104
+ }
2105
+ /**
2106
+ * Gobbles only identifiers
2107
+ * e.g.: `foo`, `_value`, `$x1`
2108
+ * Also, this function checks if that identifier is a literal:
2109
+ * (e.g. `true`, `false`, `null`) or `this`
2110
+ * @returns {jsep.Identifier}
2111
+ */
2112
+ gobbleIdentifier() {
2113
+ let ch = this.code, start = this.index;
2114
+ if (_Jsep.isIdentifierStart(ch)) {
2115
+ this.index++;
2116
+ } else {
2117
+ this.throwError("Unexpected " + this.char);
2118
+ }
2119
+ while (this.index < this.expr.length) {
2120
+ ch = this.code;
2121
+ if (_Jsep.isIdentifierPart(ch)) {
2122
+ this.index++;
2123
+ } else {
2124
+ break;
2125
+ }
2126
+ }
2127
+ return {
2128
+ type: _Jsep.IDENTIFIER,
2129
+ name: this.expr.slice(start, this.index)
2130
+ };
2131
+ }
2132
+ /**
2133
+ * Gobbles a list of arguments within the context of a function call
2134
+ * or array literal. This function also assumes that the opening character
2135
+ * `(` or `[` has already been gobbled, and gobbles expressions and commas
2136
+ * until the terminator character `)` or `]` is encountered.
2137
+ * e.g. `foo(bar, baz)`, `my_func()`, or `[bar, baz]`
2138
+ * @param {number} termination
2139
+ * @returns {jsep.Expression[]}
2140
+ */
2141
+ gobbleArguments(termination) {
2142
+ const args = [];
2143
+ let closed = false;
2144
+ let separator_count = 0;
2145
+ while (this.index < this.expr.length) {
2146
+ this.gobbleSpaces();
2147
+ let ch_i = this.code;
2148
+ if (ch_i === termination) {
2149
+ closed = true;
2150
+ this.index++;
2151
+ if (termination === _Jsep.CPAREN_CODE && separator_count && separator_count >= args.length) {
2152
+ this.throwError("Unexpected token " + String.fromCharCode(termination));
2153
+ }
2154
+ break;
2155
+ } else if (ch_i === _Jsep.COMMA_CODE) {
2156
+ this.index++;
2157
+ separator_count++;
2158
+ if (separator_count !== args.length) {
2159
+ if (termination === _Jsep.CPAREN_CODE) {
2160
+ this.throwError("Unexpected token ,");
2161
+ } else if (termination === _Jsep.CBRACK_CODE) {
2162
+ for (let arg = args.length; arg < separator_count; arg++) {
2163
+ args.push(null);
2164
+ }
2165
+ }
2166
+ }
2167
+ } else if (args.length !== separator_count && separator_count !== 0) {
2168
+ this.throwError("Expected comma");
2169
+ } else {
2170
+ const node = this.gobbleExpression();
2171
+ if (!node || node.type === _Jsep.COMPOUND) {
2172
+ this.throwError("Expected comma");
2173
+ }
2174
+ args.push(node);
2175
+ }
2176
+ }
2177
+ if (!closed) {
2178
+ this.throwError("Expected " + String.fromCharCode(termination));
2179
+ }
2180
+ return args;
2181
+ }
2182
+ /**
2183
+ * Responsible for parsing a group of things within parentheses `()`
2184
+ * that have no identifier in front (so not a function call)
2185
+ * This function assumes that it needs to gobble the opening parenthesis
2186
+ * and then tries to gobble everything within that parenthesis, assuming
2187
+ * that the next thing it should see is the close parenthesis. If not,
2188
+ * then the expression probably doesn't have a `)`
2189
+ * @returns {boolean|jsep.Expression}
2190
+ */
2191
+ gobbleGroup() {
2192
+ this.index++;
2193
+ let nodes = this.gobbleExpressions(_Jsep.CPAREN_CODE);
2194
+ if (this.code === _Jsep.CPAREN_CODE) {
2195
+ this.index++;
2196
+ if (nodes.length === 1) {
2197
+ return nodes[0];
2198
+ } else if (!nodes.length) {
2199
+ return false;
2200
+ } else {
2201
+ return {
2202
+ type: _Jsep.SEQUENCE_EXP,
2203
+ expressions: nodes
2204
+ };
2205
+ }
2206
+ } else {
2207
+ this.throwError("Unclosed (");
2208
+ }
2209
+ }
2210
+ /**
2211
+ * Responsible for parsing Array literals `[1, 2, 3]`
2212
+ * This function assumes that it needs to gobble the opening bracket
2213
+ * and then tries to gobble the expressions as arguments.
2214
+ * @returns {jsep.ArrayExpression}
2215
+ */
2216
+ gobbleArray() {
2217
+ this.index++;
2218
+ return {
2219
+ type: _Jsep.ARRAY_EXP,
2220
+ elements: this.gobbleArguments(_Jsep.CBRACK_CODE)
2221
+ };
2222
+ }
2223
+ };
2224
+ var hooks = new Hooks();
2225
+ Object.assign(Jsep, {
2226
+ hooks,
2227
+ plugins: new Plugins(Jsep),
2228
+ // Node Types
2229
+ // ----------
2230
+ // This is the full set of types that any JSEP node can be.
2231
+ // Store them here to save space when minified
2232
+ COMPOUND: "Compound",
2233
+ SEQUENCE_EXP: "SequenceExpression",
2234
+ IDENTIFIER: "Identifier",
2235
+ MEMBER_EXP: "MemberExpression",
2236
+ LITERAL: "Literal",
2237
+ THIS_EXP: "ThisExpression",
2238
+ CALL_EXP: "CallExpression",
2239
+ UNARY_EXP: "UnaryExpression",
2240
+ BINARY_EXP: "BinaryExpression",
2241
+ ARRAY_EXP: "ArrayExpression",
2242
+ TAB_CODE: 9,
2243
+ LF_CODE: 10,
2244
+ CR_CODE: 13,
2245
+ SPACE_CODE: 32,
2246
+ PERIOD_CODE: 46,
2247
+ // '.'
2248
+ COMMA_CODE: 44,
2249
+ // ','
2250
+ SQUOTE_CODE: 39,
2251
+ // single quote
2252
+ DQUOTE_CODE: 34,
2253
+ // double quotes
2254
+ OPAREN_CODE: 40,
2255
+ // (
2256
+ CPAREN_CODE: 41,
2257
+ // )
2258
+ OBRACK_CODE: 91,
2259
+ // [
2260
+ CBRACK_CODE: 93,
2261
+ // ]
2262
+ QUMARK_CODE: 63,
2263
+ // ?
2264
+ SEMCOL_CODE: 59,
2265
+ // ;
2266
+ COLON_CODE: 58,
2267
+ // :
2268
+ // Operations
2269
+ // ----------
2270
+ // Use a quickly-accessible map to store all of the unary operators
2271
+ // Values are set to `1` (it really doesn't matter)
2272
+ unary_ops: {
2273
+ "-": 1,
2274
+ "!": 1,
2275
+ "~": 1,
2276
+ "+": 1
2277
+ },
2278
+ // Also use a map for the binary operations but set their values to their
2279
+ // binary precedence for quick reference (higher number = higher precedence)
2280
+ // see [Order of operations](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence)
2281
+ binary_ops: {
2282
+ "||": 1,
2283
+ "??": 1,
2284
+ "&&": 2,
2285
+ "|": 3,
2286
+ "^": 4,
2287
+ "&": 5,
2288
+ "==": 6,
2289
+ "!=": 6,
2290
+ "===": 6,
2291
+ "!==": 6,
2292
+ "<": 7,
2293
+ ">": 7,
2294
+ "<=": 7,
2295
+ ">=": 7,
2296
+ "<<": 8,
2297
+ ">>": 8,
2298
+ ">>>": 8,
2299
+ "+": 9,
2300
+ "-": 9,
2301
+ "*": 10,
2302
+ "/": 10,
2303
+ "%": 10,
2304
+ "**": 11
2305
+ },
2306
+ // sets specific binary_ops as right-associative
2307
+ right_associative: /* @__PURE__ */ new Set(["**"]),
2308
+ // Additional valid identifier chars, apart from a-z, A-Z and 0-9 (except on the starting char)
2309
+ additional_identifier_chars: /* @__PURE__ */ new Set(["$", "_"]),
2310
+ // Literals
2311
+ // ----------
2312
+ // Store the values to return for the various literals we may encounter
2313
+ literals: {
2314
+ "true": true,
2315
+ "false": false,
2316
+ "null": null
2317
+ },
2318
+ // Except for `this`, which is special. This could be changed to something like `'self'` as well
2319
+ this_str: "this"
2320
+ });
2321
+ Jsep.max_unop_len = Jsep.getMaxKeyLen(Jsep.unary_ops);
2322
+ Jsep.max_binop_len = Jsep.getMaxKeyLen(Jsep.binary_ops);
2323
+ var jsep = (expr) => new Jsep(expr).parse();
2324
+ var stdClassProps = Object.getOwnPropertyNames(class Test {
2325
+ });
2326
+ Object.getOwnPropertyNames(Jsep).filter((prop) => !stdClassProps.includes(prop) && jsep[prop] === void 0).forEach((m) => {
2327
+ jsep[m] = Jsep[m];
2328
+ });
2329
+ jsep.Jsep = Jsep;
2330
+ var CONDITIONAL_EXP = "ConditionalExpression";
2331
+ var ternary = {
2332
+ name: "ternary",
2333
+ init(jsep2) {
2334
+ jsep2.hooks.add("after-expression", function gobbleTernary(env) {
2335
+ if (env.node && this.code === jsep2.QUMARK_CODE) {
2336
+ this.index++;
2337
+ const test = env.node;
2338
+ const consequent = this.gobbleExpression();
2339
+ if (!consequent) {
2340
+ this.throwError("Expected expression");
2341
+ }
2342
+ this.gobbleSpaces();
2343
+ if (this.code === jsep2.COLON_CODE) {
2344
+ this.index++;
2345
+ const alternate = this.gobbleExpression();
2346
+ if (!alternate) {
2347
+ this.throwError("Expected expression");
2348
+ }
2349
+ env.node = {
2350
+ type: CONDITIONAL_EXP,
2351
+ test,
2352
+ consequent,
2353
+ alternate
2354
+ };
2355
+ if (test.operator && jsep2.binary_ops[test.operator] <= 0.9) {
2356
+ let newTest = test;
2357
+ while (newTest.right.operator && jsep2.binary_ops[newTest.right.operator] <= 0.9) {
2358
+ newTest = newTest.right;
2359
+ }
2360
+ env.node.test = newTest.right;
2361
+ newTest.right = env.node;
2362
+ env.node = test;
2363
+ }
2364
+ } else {
2365
+ this.throwError("Expected :");
2366
+ }
2367
+ }
2368
+ });
2369
+ }
2370
+ };
2371
+ jsep.plugins.register(ternary);
2372
+ var FSLASH_CODE = 47;
2373
+ var BSLASH_CODE = 92;
2374
+ var index = {
2375
+ name: "regex",
2376
+ init(jsep2) {
2377
+ jsep2.hooks.add("gobble-token", function gobbleRegexLiteral(env) {
2378
+ if (this.code === FSLASH_CODE) {
2379
+ const patternIndex = ++this.index;
2380
+ let inCharSet = false;
2381
+ while (this.index < this.expr.length) {
2382
+ if (this.code === FSLASH_CODE && !inCharSet) {
2383
+ const pattern = this.expr.slice(patternIndex, this.index);
2384
+ let flags = "";
2385
+ while (++this.index < this.expr.length) {
2386
+ const code = this.code;
2387
+ if (code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 48 && code <= 57) {
2388
+ flags += this.char;
2389
+ } else {
2390
+ break;
2391
+ }
2392
+ }
2393
+ let value;
2394
+ try {
2395
+ value = new RegExp(pattern, flags);
2396
+ } catch (e) {
2397
+ this.throwError(e.message);
2398
+ }
2399
+ env.node = {
2400
+ type: jsep2.LITERAL,
2401
+ value,
2402
+ raw: this.expr.slice(patternIndex - 1, this.index)
2403
+ };
2404
+ env.node = this.gobbleTokenProperty(env.node);
2405
+ return env.node;
2406
+ }
2407
+ if (this.code === jsep2.OBRACK_CODE) {
2408
+ inCharSet = true;
2409
+ } else if (inCharSet && this.code === jsep2.CBRACK_CODE) {
2410
+ inCharSet = false;
2411
+ }
2412
+ this.index += this.code === BSLASH_CODE ? 2 : 1;
2413
+ }
2414
+ this.throwError("Unclosed Regex");
2415
+ }
2416
+ });
2417
+ }
2418
+ };
2419
+ var PLUS_CODE = 43;
2420
+ var MINUS_CODE = 45;
2421
+ var plugin = {
2422
+ name: "assignment",
2423
+ assignmentOperators: /* @__PURE__ */ new Set(["=", "*=", "**=", "/=", "%=", "+=", "-=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "||=", "&&=", "??="]),
2424
+ updateOperators: [PLUS_CODE, MINUS_CODE],
2425
+ assignmentPrecedence: 0.9,
2426
+ init(jsep2) {
2427
+ const updateNodeTypes = [jsep2.IDENTIFIER, jsep2.MEMBER_EXP];
2428
+ plugin.assignmentOperators.forEach((op) => jsep2.addBinaryOp(op, plugin.assignmentPrecedence, true));
2429
+ jsep2.hooks.add("gobble-token", function gobbleUpdatePrefix(env) {
2430
+ const code = this.code;
2431
+ if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
2432
+ this.index += 2;
2433
+ env.node = {
2434
+ type: "UpdateExpression",
2435
+ operator: code === PLUS_CODE ? "++" : "--",
2436
+ argument: this.gobbleTokenProperty(this.gobbleIdentifier()),
2437
+ prefix: true
2438
+ };
2439
+ if (!env.node.argument || !updateNodeTypes.includes(env.node.argument.type)) {
2440
+ this.throwError(`Unexpected ${env.node.operator}`);
2441
+ }
2442
+ }
2443
+ });
2444
+ jsep2.hooks.add("after-token", function gobbleUpdatePostfix(env) {
2445
+ if (env.node) {
2446
+ const code = this.code;
2447
+ if (plugin.updateOperators.some((c) => c === code && c === this.expr.charCodeAt(this.index + 1))) {
2448
+ if (!updateNodeTypes.includes(env.node.type)) {
2449
+ this.throwError(`Unexpected ${env.node.operator}`);
2450
+ }
2451
+ this.index += 2;
2452
+ env.node = {
2453
+ type: "UpdateExpression",
2454
+ operator: code === PLUS_CODE ? "++" : "--",
2455
+ argument: env.node,
2456
+ prefix: false
2457
+ };
2458
+ }
2459
+ }
2460
+ });
2461
+ jsep2.hooks.add("after-expression", function gobbleAssignment(env) {
2462
+ if (env.node) {
2463
+ updateBinariesToAssignments(env.node);
2464
+ }
2465
+ });
2466
+ function updateBinariesToAssignments(node) {
2467
+ if (plugin.assignmentOperators.has(node.operator)) {
2468
+ node.type = "AssignmentExpression";
2469
+ updateBinariesToAssignments(node.left);
2470
+ updateBinariesToAssignments(node.right);
2471
+ } else if (!node.operator) {
2472
+ Object.values(node).forEach((val) => {
2473
+ if (val && typeof val === "object") {
2474
+ updateBinariesToAssignments(val);
2475
+ }
2476
+ });
2477
+ }
2478
+ }
2479
+ }
2480
+ };
2481
+ jsep.plugins.register(index, plugin);
2482
+ jsep.addUnaryOp("typeof");
2483
+ jsep.addUnaryOp("void");
2484
+ jsep.addLiteral("null", null);
2485
+ jsep.addLiteral("undefined", void 0);
2486
+ var BLOCKED_PROTO_PROPERTIES = /* @__PURE__ */ new Set(["constructor", "__proto__", "__defineGetter__", "__defineSetter__", "__lookupGetter__", "__lookupSetter__"]);
2487
+ var SafeEval = {
2488
+ /**
2489
+ * @param {jsep.Expression} ast
2490
+ * @param {Record<string, any>} subs
2491
+ */
2492
+ evalAst(ast, subs) {
2493
+ switch (ast.type) {
2494
+ case "BinaryExpression":
2495
+ case "LogicalExpression":
2496
+ return SafeEval.evalBinaryExpression(ast, subs);
2497
+ case "Compound":
2498
+ return SafeEval.evalCompound(ast, subs);
2499
+ case "ConditionalExpression":
2500
+ return SafeEval.evalConditionalExpression(ast, subs);
2501
+ case "Identifier":
2502
+ return SafeEval.evalIdentifier(ast, subs);
2503
+ case "Literal":
2504
+ return SafeEval.evalLiteral(ast);
2505
+ case "MemberExpression":
2506
+ return SafeEval.evalMemberExpression(ast, subs);
2507
+ case "UnaryExpression":
2508
+ return SafeEval.evalUnaryExpression(ast, subs);
2509
+ case "ArrayExpression":
2510
+ return SafeEval.evalArrayExpression(ast, subs);
2511
+ case "CallExpression":
2512
+ return SafeEval.evalCallExpression(ast, subs);
2513
+ case "AssignmentExpression":
2514
+ return SafeEval.evalAssignmentExpression(ast, subs);
2515
+ default:
2516
+ throw SyntaxError("Unexpected expression", ast);
2517
+ }
2518
+ },
2519
+ evalBinaryExpression(ast, subs) {
2520
+ const result = {
2521
+ "||": (a, b) => a || b(),
2522
+ "&&": (a, b) => a && b(),
2523
+ "|": (a, b) => a | b(),
2524
+ "^": (a, b) => a ^ b(),
2525
+ "&": (a, b) => a & b(),
2526
+ // eslint-disable-next-line eqeqeq -- API
2527
+ "==": (a, b) => a == b(),
2528
+ // eslint-disable-next-line eqeqeq -- API
2529
+ "!=": (a, b) => a != b(),
2530
+ "===": (a, b) => a === b(),
2531
+ "!==": (a, b) => a !== b(),
2532
+ "<": (a, b) => a < b(),
2533
+ ">": (a, b) => a > b(),
2534
+ "<=": (a, b) => a <= b(),
2535
+ ">=": (a, b) => a >= b(),
2536
+ "<<": (a, b) => a << b(),
2537
+ ">>": (a, b) => a >> b(),
2538
+ ">>>": (a, b) => a >>> b(),
2539
+ "+": (a, b) => a + b(),
2540
+ "-": (a, b) => a - b(),
2541
+ "*": (a, b) => a * b(),
2542
+ "/": (a, b) => a / b(),
2543
+ "%": (a, b) => a % b()
2544
+ }[ast.operator](SafeEval.evalAst(ast.left, subs), () => SafeEval.evalAst(ast.right, subs));
2545
+ return result;
2546
+ },
2547
+ evalCompound(ast, subs) {
2548
+ let last;
2549
+ for (let i = 0; i < ast.body.length; i++) {
2550
+ if (ast.body[i].type === "Identifier" && ["var", "let", "const"].includes(ast.body[i].name) && ast.body[i + 1] && ast.body[i + 1].type === "AssignmentExpression") {
2551
+ i += 1;
2552
+ }
2553
+ const expr = ast.body[i];
2554
+ last = SafeEval.evalAst(expr, subs);
2555
+ }
2556
+ return last;
2557
+ },
2558
+ evalConditionalExpression(ast, subs) {
2559
+ if (SafeEval.evalAst(ast.test, subs)) {
2560
+ return SafeEval.evalAst(ast.consequent, subs);
2561
+ }
2562
+ return SafeEval.evalAst(ast.alternate, subs);
2563
+ },
2564
+ evalIdentifier(ast, subs) {
2565
+ if (Object.hasOwn(subs, ast.name)) {
2566
+ return subs[ast.name];
2567
+ }
2568
+ throw ReferenceError(`${ast.name} is not defined`);
2569
+ },
2570
+ evalLiteral(ast) {
2571
+ return ast.value;
2572
+ },
2573
+ evalMemberExpression(ast, subs) {
2574
+ const prop = String(
2575
+ // NOTE: `String(value)` throws error when
2576
+ // value has overwritten the toString method to return non-string
2577
+ // i.e. `value = {toString: () => []}`
2578
+ ast.computed ? SafeEval.evalAst(ast.property) : ast.property.name
2579
+ // `object.property` property is Identifier
2580
+ );
2581
+ const obj = SafeEval.evalAst(ast.object, subs);
2582
+ if (obj === void 0 || obj === null) {
2583
+ throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
2584
+ }
2585
+ if (!Object.hasOwn(obj, prop) && BLOCKED_PROTO_PROPERTIES.has(prop)) {
2586
+ throw TypeError(`Cannot read properties of ${obj} (reading '${prop}')`);
2587
+ }
2588
+ const result = obj[prop];
2589
+ if (typeof result === "function") {
2590
+ return result.bind(obj);
2591
+ }
2592
+ return result;
2593
+ },
2594
+ evalUnaryExpression(ast, subs) {
2595
+ const result = {
2596
+ "-": (a) => -SafeEval.evalAst(a, subs),
2597
+ "!": (a) => !SafeEval.evalAst(a, subs),
2598
+ "~": (a) => ~SafeEval.evalAst(a, subs),
2599
+ // eslint-disable-next-line no-implicit-coercion -- API
2600
+ "+": (a) => +SafeEval.evalAst(a, subs),
2601
+ typeof: (a) => typeof SafeEval.evalAst(a, subs),
2602
+ // eslint-disable-next-line no-void, sonarjs/void-use -- feature
2603
+ void: (a) => void SafeEval.evalAst(a, subs)
2604
+ }[ast.operator](ast.argument);
2605
+ return result;
2606
+ },
2607
+ evalArrayExpression(ast, subs) {
2608
+ return ast.elements.map((el) => SafeEval.evalAst(el, subs));
2609
+ },
2610
+ evalCallExpression(ast, subs) {
2611
+ const args = ast.arguments.map((arg) => SafeEval.evalAst(arg, subs));
2612
+ const func = SafeEval.evalAst(ast.callee, subs);
2613
+ if (func === Function) {
2614
+ throw new Error("Function constructor is disabled");
2615
+ }
2616
+ return func(...args);
2617
+ },
2618
+ evalAssignmentExpression(ast, subs) {
2619
+ if (ast.left.type !== "Identifier") {
2620
+ throw SyntaxError("Invalid left-hand side in assignment");
2621
+ }
2622
+ const id = ast.left.name;
2623
+ const value = SafeEval.evalAst(ast.right, subs);
2624
+ subs[id] = value;
2625
+ return subs[id];
2626
+ }
2627
+ };
2628
+ var SafeScript = class {
2629
+ /**
2630
+ * @param {string} expr Expression to evaluate
2631
+ */
2632
+ constructor(expr) {
2633
+ this.code = expr;
2634
+ this.ast = jsep(this.code);
2635
+ }
2636
+ /**
2637
+ * @param {object} context Object whose items will be added
2638
+ * to evaluation
2639
+ * @returns {EvaluatedResult} Result of evaluated code
2640
+ */
2641
+ runInNewContext(context) {
2642
+ const keyMap = Object.assign(/* @__PURE__ */ Object.create(null), context);
2643
+ return SafeEval.evalAst(this.ast, keyMap);
2644
+ }
2645
+ };
2646
+ function push(arr, item) {
2647
+ arr = arr.slice();
2648
+ arr.push(item);
2649
+ return arr;
2650
+ }
2651
+ function unshift(item, arr) {
2652
+ arr = arr.slice();
2653
+ arr.unshift(item);
2654
+ return arr;
2655
+ }
2656
+ var NewError = class extends Error {
2657
+ /**
2658
+ * @param {AnyResult} value The evaluated scalar value
2659
+ */
2660
+ constructor(value) {
2661
+ super('JSONPath should not be called with "new" (it prevents return of (unwrapped) scalar values)');
2662
+ this.avoidNew = true;
2663
+ this.value = value;
2664
+ this.name = "NewError";
2665
+ }
2666
+ };
2667
+ function JSONPath(opts, expr, obj, callback, otherTypeCallback) {
2668
+ if (!(this instanceof JSONPath)) {
2669
+ try {
2670
+ return new JSONPath(opts, expr, obj, callback, otherTypeCallback);
2671
+ } catch (e) {
2672
+ if (!e.avoidNew) {
2673
+ throw e;
2674
+ }
2675
+ return e.value;
2676
+ }
2677
+ }
2678
+ if (typeof opts === "string") {
2679
+ otherTypeCallback = callback;
2680
+ callback = obj;
2681
+ obj = expr;
2682
+ expr = opts;
2683
+ opts = null;
2684
+ }
2685
+ const optObj = opts && typeof opts === "object";
2686
+ opts = opts || {};
2687
+ this.json = opts.json || obj;
2688
+ this.path = opts.path || expr;
2689
+ this.resultType = opts.resultType || "value";
2690
+ this.flatten = opts.flatten || false;
2691
+ this.wrap = Object.hasOwn(opts, "wrap") ? opts.wrap : true;
2692
+ this.sandbox = opts.sandbox || {};
2693
+ this.eval = opts.eval === void 0 ? "safe" : opts.eval;
2694
+ this.ignoreEvalErrors = typeof opts.ignoreEvalErrors === "undefined" ? false : opts.ignoreEvalErrors;
2695
+ this.parent = opts.parent || null;
2696
+ this.parentProperty = opts.parentProperty || null;
2697
+ this.callback = opts.callback || callback || null;
2698
+ this.otherTypeCallback = opts.otherTypeCallback || otherTypeCallback || function() {
2699
+ throw new TypeError("You must supply an otherTypeCallback callback option with the @other() operator.");
2700
+ };
2701
+ if (opts.autostart !== false) {
2702
+ const args = {
2703
+ path: optObj ? opts.path : expr
2704
+ };
2705
+ if (!optObj) {
2706
+ args.json = obj;
2707
+ } else if ("json" in opts) {
2708
+ args.json = opts.json;
2709
+ }
2710
+ const ret = this.evaluate(args);
2711
+ if (!ret || typeof ret !== "object") {
2712
+ throw new NewError(ret);
2713
+ }
2714
+ return ret;
2715
+ }
2716
+ }
2717
+ JSONPath.prototype.evaluate = function(expr, json, callback, otherTypeCallback) {
2718
+ let currParent = this.parent, currParentProperty = this.parentProperty;
2719
+ let {
2720
+ flatten,
2721
+ wrap
2722
+ } = this;
2723
+ this.currResultType = this.resultType;
2724
+ this.currEval = this.eval;
2725
+ this.currSandbox = this.sandbox;
2726
+ callback = callback || this.callback;
2727
+ this.currOtherTypeCallback = otherTypeCallback || this.otherTypeCallback;
2728
+ json = json || this.json;
2729
+ expr = expr || this.path;
2730
+ if (expr && typeof expr === "object" && !Array.isArray(expr)) {
2731
+ if (!expr.path && expr.path !== "") {
2732
+ throw new TypeError('You must supply a "path" property when providing an object argument to JSONPath.evaluate().');
2733
+ }
2734
+ if (!Object.hasOwn(expr, "json")) {
2735
+ throw new TypeError('You must supply a "json" property when providing an object argument to JSONPath.evaluate().');
2736
+ }
2737
+ ({
2738
+ json
2739
+ } = expr);
2740
+ flatten = Object.hasOwn(expr, "flatten") ? expr.flatten : flatten;
2741
+ this.currResultType = Object.hasOwn(expr, "resultType") ? expr.resultType : this.currResultType;
2742
+ this.currSandbox = Object.hasOwn(expr, "sandbox") ? expr.sandbox : this.currSandbox;
2743
+ wrap = Object.hasOwn(expr, "wrap") ? expr.wrap : wrap;
2744
+ this.currEval = Object.hasOwn(expr, "eval") ? expr.eval : this.currEval;
2745
+ callback = Object.hasOwn(expr, "callback") ? expr.callback : callback;
2746
+ this.currOtherTypeCallback = Object.hasOwn(expr, "otherTypeCallback") ? expr.otherTypeCallback : this.currOtherTypeCallback;
2747
+ currParent = Object.hasOwn(expr, "parent") ? expr.parent : currParent;
2748
+ currParentProperty = Object.hasOwn(expr, "parentProperty") ? expr.parentProperty : currParentProperty;
2749
+ expr = expr.path;
2750
+ }
2751
+ currParent = currParent || null;
2752
+ currParentProperty = currParentProperty || null;
2753
+ if (Array.isArray(expr)) {
2754
+ expr = JSONPath.toPathString(expr);
2755
+ }
2756
+ if (!expr && expr !== "" || !json) {
2757
+ return void 0;
2758
+ }
2759
+ const exprList = JSONPath.toPathArray(expr);
2760
+ if (exprList[0] === "$" && exprList.length > 1) {
2761
+ exprList.shift();
2762
+ }
2763
+ this._hasParentSelector = null;
2764
+ const result = this._trace(exprList, json, ["$"], currParent, currParentProperty, callback).filter(function(ea) {
2765
+ return ea && !ea.isParentSelector;
2766
+ });
2767
+ if (!result.length) {
2768
+ return wrap ? [] : void 0;
2769
+ }
2770
+ if (!wrap && result.length === 1 && !result[0].hasArrExpr) {
2771
+ return this._getPreferredOutput(result[0]);
2772
+ }
2773
+ return result.reduce((rslt, ea) => {
2774
+ const valOrPath = this._getPreferredOutput(ea);
2775
+ if (flatten && Array.isArray(valOrPath)) {
2776
+ rslt = rslt.concat(valOrPath);
2777
+ } else {
2778
+ rslt.push(valOrPath);
2779
+ }
2780
+ return rslt;
2781
+ }, []);
2782
+ };
2783
+ JSONPath.prototype._getPreferredOutput = function(ea) {
2784
+ const resultType = this.currResultType;
2785
+ switch (resultType) {
2786
+ case "all": {
2787
+ const path = Array.isArray(ea.path) ? ea.path : JSONPath.toPathArray(ea.path);
2788
+ ea.pointer = JSONPath.toPointer(path);
2789
+ ea.path = typeof ea.path === "string" ? ea.path : JSONPath.toPathString(ea.path);
2790
+ return ea;
2791
+ }
2792
+ case "value":
2793
+ case "parent":
2794
+ case "parentProperty":
2795
+ return ea[resultType];
2796
+ case "path":
2797
+ return JSONPath.toPathString(ea[resultType]);
2798
+ case "pointer":
2799
+ return JSONPath.toPointer(ea.path);
2800
+ default:
2801
+ throw new TypeError("Unknown result type");
2802
+ }
2803
+ };
2804
+ JSONPath.prototype._handleCallback = function(fullRetObj, callback, type) {
2805
+ if (callback) {
2806
+ const preferredOutput = this._getPreferredOutput(fullRetObj);
2807
+ fullRetObj.path = typeof fullRetObj.path === "string" ? fullRetObj.path : JSONPath.toPathString(fullRetObj.path);
2808
+ callback(preferredOutput, type, fullRetObj);
2809
+ }
2810
+ };
2811
+ JSONPath.prototype._trace = function(expr, val, path, parent, parentPropName, callback, hasArrExpr, literalPriority) {
2812
+ let retObj;
2813
+ if (!expr.length) {
2814
+ retObj = {
2815
+ path,
2816
+ value: val,
2817
+ parent,
2818
+ parentProperty: parentPropName,
2819
+ hasArrExpr
2820
+ };
2821
+ this._handleCallback(retObj, callback, "value");
2822
+ return retObj;
2823
+ }
2824
+ const loc = expr[0], x = expr.slice(1);
2825
+ const ret = [];
2826
+ function addRet(elems) {
2827
+ if (Array.isArray(elems)) {
2828
+ elems.forEach((t) => {
2829
+ ret.push(t);
2830
+ });
2831
+ } else {
2832
+ ret.push(elems);
2833
+ }
2834
+ }
2835
+ if ((typeof loc !== "string" || literalPriority) && val && Object.hasOwn(val, loc)) {
2836
+ addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr));
2837
+ } else if (loc === "*") {
2838
+ this._walk(val, (m) => {
2839
+ addRet(this._trace(x, val[m], push(path, m), val, m, callback, true, true));
2840
+ });
2841
+ } else if (loc === "..") {
2842
+ addRet(this._trace(x, val, path, parent, parentPropName, callback, hasArrExpr));
2843
+ this._walk(val, (m) => {
2844
+ if (typeof val[m] === "object") {
2845
+ addRet(this._trace(expr.slice(), val[m], push(path, m), val, m, callback, true));
2846
+ }
2847
+ });
2848
+ } else if (loc === "^") {
2849
+ this._hasParentSelector = true;
2850
+ return {
2851
+ path: path.slice(0, -1),
2852
+ expr: x,
2853
+ isParentSelector: true
2854
+ };
2855
+ } else if (loc === "~") {
2856
+ retObj = {
2857
+ path: push(path, loc),
2858
+ value: parentPropName,
2859
+ parent,
2860
+ parentProperty: null
2861
+ };
2862
+ this._handleCallback(retObj, callback, "property");
2863
+ return retObj;
2864
+ } else if (loc === "$") {
2865
+ addRet(this._trace(x, val, path, null, null, callback, hasArrExpr));
2866
+ } else if (/^(-?\d*):(-?\d*):?(\d*)$/u.test(loc)) {
2867
+ addRet(this._slice(loc, x, val, path, parent, parentPropName, callback));
2868
+ } else if (loc.indexOf("?(") === 0) {
2869
+ if (this.currEval === false) {
2870
+ throw new Error("Eval [?(expr)] prevented in JSONPath expression.");
2871
+ }
2872
+ const safeLoc = loc.replace(/^\?\((.*?)\)$/u, "$1");
2873
+ const nested = /@.?([^?]*)[['](\??\(.*?\))(?!.\)\])[\]']/gu.exec(safeLoc);
2874
+ if (nested) {
2875
+ this._walk(val, (m) => {
2876
+ const npath = [nested[2]];
2877
+ const nvalue = nested[1] ? val[m][nested[1]] : val[m];
2878
+ const filterResults = this._trace(npath, nvalue, path, parent, parentPropName, callback, true);
2879
+ if (filterResults.length > 0) {
2880
+ addRet(this._trace(x, val[m], push(path, m), val, m, callback, true));
2881
+ }
2882
+ });
2883
+ } else {
2884
+ this._walk(val, (m) => {
2885
+ if (this._eval(safeLoc, val[m], m, path, parent, parentPropName)) {
2886
+ addRet(this._trace(x, val[m], push(path, m), val, m, callback, true));
2887
+ }
2888
+ });
2889
+ }
2890
+ } else if (loc[0] === "(") {
2891
+ if (this.currEval === false) {
2892
+ throw new Error("Eval [(expr)] prevented in JSONPath expression.");
2893
+ }
2894
+ addRet(this._trace(unshift(this._eval(loc, val, path.at(-1), path.slice(0, -1), parent, parentPropName), x), val, path, parent, parentPropName, callback, hasArrExpr));
2895
+ } else if (loc[0] === "@") {
2896
+ let addType = false;
2897
+ const valueType = loc.slice(1, -2);
2898
+ switch (valueType) {
2899
+ case "scalar":
2900
+ if (!val || !["object", "function"].includes(typeof val)) {
2901
+ addType = true;
2902
+ }
2903
+ break;
2904
+ case "boolean":
2905
+ case "string":
2906
+ case "undefined":
2907
+ case "function":
2908
+ if (typeof val === valueType) {
2909
+ addType = true;
2910
+ }
2911
+ break;
2912
+ case "integer":
2913
+ if (Number.isFinite(val) && !(val % 1)) {
2914
+ addType = true;
2915
+ }
2916
+ break;
2917
+ case "number":
2918
+ if (Number.isFinite(val)) {
2919
+ addType = true;
2920
+ }
2921
+ break;
2922
+ case "nonFinite":
2923
+ if (typeof val === "number" && !Number.isFinite(val)) {
2924
+ addType = true;
2925
+ }
2926
+ break;
2927
+ case "object":
2928
+ if (val && typeof val === valueType) {
2929
+ addType = true;
2930
+ }
2931
+ break;
2932
+ case "array":
2933
+ if (Array.isArray(val)) {
2934
+ addType = true;
2935
+ }
2936
+ break;
2937
+ case "other":
2938
+ addType = this.currOtherTypeCallback(val, path, parent, parentPropName);
2939
+ break;
2940
+ case "null":
2941
+ if (val === null) {
2942
+ addType = true;
2943
+ }
2944
+ break;
2945
+ /* c8 ignore next 2 */
2946
+ default:
2947
+ throw new TypeError("Unknown value type " + valueType);
2948
+ }
2949
+ if (addType) {
2950
+ retObj = {
2951
+ path,
2952
+ value: val,
2953
+ parent,
2954
+ parentProperty: parentPropName
2955
+ };
2956
+ this._handleCallback(retObj, callback, "value");
2957
+ return retObj;
2958
+ }
2959
+ } else if (loc[0] === "`" && val && Object.hasOwn(val, loc.slice(1))) {
2960
+ const locProp = loc.slice(1);
2961
+ addRet(this._trace(x, val[locProp], push(path, locProp), val, locProp, callback, hasArrExpr, true));
2962
+ } else if (loc.includes(",")) {
2963
+ const parts = loc.split(",");
2964
+ for (const part of parts) {
2965
+ addRet(this._trace(unshift(part, x), val, path, parent, parentPropName, callback, true));
2966
+ }
2967
+ } else if (!literalPriority && val && Object.hasOwn(val, loc)) {
2968
+ addRet(this._trace(x, val[loc], push(path, loc), val, loc, callback, hasArrExpr, true));
2969
+ }
2970
+ if (this._hasParentSelector) {
2971
+ for (let t = 0; t < ret.length; t++) {
2972
+ const rett = ret[t];
2973
+ if (rett && rett.isParentSelector) {
2974
+ const tmp = this._trace(rett.expr, val, rett.path, parent, parentPropName, callback, hasArrExpr);
2975
+ if (Array.isArray(tmp)) {
2976
+ ret[t] = tmp[0];
2977
+ const tl = tmp.length;
2978
+ for (let tt = 1; tt < tl; tt++) {
2979
+ t++;
2980
+ ret.splice(t, 0, tmp[tt]);
2981
+ }
2982
+ } else {
2983
+ ret[t] = tmp;
2984
+ }
2985
+ }
2986
+ }
2987
+ }
2988
+ return ret;
2989
+ };
2990
+ JSONPath.prototype._walk = function(val, f) {
2991
+ if (Array.isArray(val)) {
2992
+ const n = val.length;
2993
+ for (let i = 0; i < n; i++) {
2994
+ f(i);
2995
+ }
2996
+ } else if (val && typeof val === "object") {
2997
+ Object.keys(val).forEach((m) => {
2998
+ f(m);
2999
+ });
3000
+ }
3001
+ };
3002
+ JSONPath.prototype._slice = function(loc, expr, val, path, parent, parentPropName, callback) {
3003
+ if (!Array.isArray(val)) {
3004
+ return void 0;
3005
+ }
3006
+ const len = val.length, parts = loc.split(":"), step = parts[2] && Number.parseInt(parts[2]) || 1;
3007
+ let start = parts[0] && Number.parseInt(parts[0]) || 0, end = parts[1] && Number.parseInt(parts[1]) || len;
3008
+ start = start < 0 ? Math.max(0, start + len) : Math.min(len, start);
3009
+ end = end < 0 ? Math.max(0, end + len) : Math.min(len, end);
3010
+ const ret = [];
3011
+ for (let i = start; i < end; i += step) {
3012
+ const tmp = this._trace(unshift(i, expr), val, path, parent, parentPropName, callback, true);
3013
+ tmp.forEach((t) => {
3014
+ ret.push(t);
3015
+ });
3016
+ }
3017
+ return ret;
3018
+ };
3019
+ JSONPath.prototype._eval = function(code, _v, _vname, path, parent, parentPropName) {
3020
+ this.currSandbox._$_parentProperty = parentPropName;
3021
+ this.currSandbox._$_parent = parent;
3022
+ this.currSandbox._$_property = _vname;
3023
+ this.currSandbox._$_root = this.json;
3024
+ this.currSandbox._$_v = _v;
3025
+ const containsPath = code.includes("@path");
3026
+ if (containsPath) {
3027
+ this.currSandbox._$_path = JSONPath.toPathString(path.concat([_vname]));
3028
+ }
3029
+ const scriptCacheKey = this.currEval + "Script:" + code;
3030
+ if (!JSONPath.cache[scriptCacheKey]) {
3031
+ let script = code.replaceAll("@parentProperty", "_$_parentProperty").replaceAll("@parent", "_$_parent").replaceAll("@property", "_$_property").replaceAll("@root", "_$_root").replaceAll(/@([.\s)[])/gu, "_$_v$1");
3032
+ if (containsPath) {
3033
+ script = script.replaceAll("@path", "_$_path");
3034
+ }
3035
+ if (this.currEval === "safe" || this.currEval === true || this.currEval === void 0) {
3036
+ JSONPath.cache[scriptCacheKey] = new this.safeVm.Script(script);
3037
+ } else if (this.currEval === "native") {
3038
+ JSONPath.cache[scriptCacheKey] = new this.vm.Script(script);
3039
+ } else if (typeof this.currEval === "function" && this.currEval.prototype && Object.hasOwn(this.currEval.prototype, "runInNewContext")) {
3040
+ const CurrEval = this.currEval;
3041
+ JSONPath.cache[scriptCacheKey] = new CurrEval(script);
3042
+ } else if (typeof this.currEval === "function") {
3043
+ JSONPath.cache[scriptCacheKey] = {
3044
+ runInNewContext: (context) => this.currEval(script, context)
3045
+ };
3046
+ } else {
3047
+ throw new TypeError(`Unknown "eval" property "${this.currEval}"`);
3048
+ }
3049
+ }
3050
+ try {
3051
+ return JSONPath.cache[scriptCacheKey].runInNewContext(this.currSandbox);
3052
+ } catch (e) {
3053
+ if (this.ignoreEvalErrors) {
3054
+ return false;
3055
+ }
3056
+ throw new Error("jsonPath: " + e.message + ": " + code);
3057
+ }
3058
+ };
3059
+ JSONPath.cache = {};
3060
+ JSONPath.toPathString = function(pathArr) {
3061
+ const x = pathArr, n = x.length;
3062
+ let p = "$";
3063
+ for (let i = 1; i < n; i++) {
3064
+ if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
3065
+ p += /^[0-9*]+$/u.test(x[i]) ? "[" + x[i] + "]" : "['" + x[i] + "']";
3066
+ }
3067
+ }
3068
+ return p;
3069
+ };
3070
+ JSONPath.toPointer = function(pointer) {
3071
+ const x = pointer, n = x.length;
3072
+ let p = "";
3073
+ for (let i = 1; i < n; i++) {
3074
+ if (!/^(~|\^|@.*?\(\))$/u.test(x[i])) {
3075
+ p += "/" + x[i].toString().replaceAll("~", "~0").replaceAll("/", "~1");
3076
+ }
3077
+ }
3078
+ return p;
3079
+ };
3080
+ JSONPath.toPathArray = function(expr) {
3081
+ const {
3082
+ cache
3083
+ } = JSONPath;
3084
+ if (cache[expr]) {
3085
+ return cache[expr].concat();
3086
+ }
3087
+ const subx = [];
3088
+ const normalized = expr.replaceAll(/@(?:null|boolean|number|string|integer|undefined|nonFinite|scalar|array|object|function|other)\(\)/gu, ";$&;").replaceAll(/[['](\??\(.*?\))[\]'](?!.\])/gu, function($0, $1) {
3089
+ return "[#" + (subx.push($1) - 1) + "]";
3090
+ }).replaceAll(/\[['"]([^'\]]*)['"]\]/gu, function($0, prop) {
3091
+ return "['" + prop.replaceAll(".", "%@%").replaceAll("~", "%%@@%%") + "']";
3092
+ }).replaceAll("~", ";~;").replaceAll(/['"]?\.['"]?(?![^[]*\])|\[['"]?/gu, ";").replaceAll("%@%", ".").replaceAll("%%@@%%", "~").replaceAll(/(?:;)?(\^+)(?:;)?/gu, function($0, ups) {
3093
+ return ";" + ups.split("").join(";") + ";";
3094
+ }).replaceAll(/;;;|;;/gu, ";..;").replaceAll(/;$|'?\]|'$/gu, "");
3095
+ const exprList = normalized.split(";").map(function(exp) {
3096
+ const match = exp.match(/#(\d+)/u);
3097
+ return !match || !match[1] ? exp : subx[match[1]];
3098
+ });
3099
+ cache[expr] = exprList;
3100
+ return cache[expr].concat();
3101
+ };
3102
+ JSONPath.prototype.safeVm = {
3103
+ Script: SafeScript
3104
+ };
3105
+ var moveToAnotherArray = function(source, target, conditionCb) {
3106
+ const il = source.length;
3107
+ for (let i = 0; i < il; i++) {
3108
+ const item = source[i];
3109
+ if (conditionCb(item)) {
3110
+ target.push(source.splice(i--, 1)[0]);
3111
+ }
3112
+ }
3113
+ };
3114
+ var Script = class {
3115
+ /**
3116
+ * @param {string} expr Expression to evaluate
3117
+ */
3118
+ constructor(expr) {
3119
+ this.code = expr;
3120
+ }
3121
+ /**
3122
+ * @param {object} context Object whose items will be added
3123
+ * to evaluation
3124
+ * @returns {EvaluatedResult} Result of evaluated code
3125
+ */
3126
+ runInNewContext(context) {
3127
+ let expr = this.code;
3128
+ const keys = Object.keys(context);
3129
+ const funcs = [];
3130
+ moveToAnotherArray(keys, funcs, (key) => {
3131
+ return typeof context[key] === "function";
3132
+ });
3133
+ const values = keys.map((vr) => {
3134
+ return context[vr];
3135
+ });
3136
+ const funcString = funcs.reduce((s, func) => {
3137
+ let fString = context[func].toString();
3138
+ if (!/function/u.test(fString)) {
3139
+ fString = "function " + fString;
3140
+ }
3141
+ return "var " + func + "=" + fString + ";" + s;
3142
+ }, "");
3143
+ expr = funcString + expr;
3144
+ if (!/(['"])use strict\1/u.test(expr) && !keys.includes("arguments")) {
3145
+ expr = "var arguments = undefined;" + expr;
3146
+ }
3147
+ expr = expr.replace(/;\s*$/u, "");
3148
+ const lastStatementEnd = expr.lastIndexOf(";");
3149
+ const code = lastStatementEnd !== -1 ? expr.slice(0, lastStatementEnd + 1) + " return " + expr.slice(lastStatementEnd + 1) : " return " + expr;
3150
+ return new Function(...keys, code)(...values);
3151
+ }
3152
+ };
3153
+ JSONPath.prototype.vm = {
3154
+ Script
3155
+ };
3156
+
3157
+ // src/async-each-helper.ts
3158
+ function isPromiseLike(value) {
3159
+ return value != null && typeof value.then === "function";
3160
+ }
3161
+ function createAsyncEachHelper(handlebars) {
3162
+ const {
3163
+ appendContextPath,
3164
+ blockParams,
3165
+ createFrame
3166
+ } = handlebars.Utils;
3167
+ return async function each(rawContext, options) {
3168
+ if (!options) {
3169
+ throw new Error("Must pass iterator to #each");
3170
+ }
3171
+ const fn = options.fn;
3172
+ const inverse = options.inverse;
3173
+ let context = typeof rawContext === "function" ? rawContext.call(this) : rawContext;
3174
+ if (isPromiseLike(context)) {
3175
+ context = await context;
3176
+ }
3177
+ const contextPath = options.data && options.ids ? `${appendContextPath(options.data.contextPath, options.ids[0] ?? "")}.` : void 0;
3178
+ const data = options.data ? createFrame(options.data) : void 0;
3179
+ const parts = [];
3180
+ const renderItem = async (item, key, index2, last) => {
3181
+ if (data) {
3182
+ data.key = key;
3183
+ data.index = index2;
3184
+ data.first = index2 === 0;
3185
+ data.last = last;
3186
+ if (contextPath) {
3187
+ data.contextPath = contextPath + key;
3188
+ }
3189
+ }
3190
+ parts.push(String(await fn(item, {
3191
+ data,
3192
+ blockParams: blockParams([item, key], [contextPath ? contextPath + key : void 0, null])
3193
+ }) ?? ""));
3194
+ };
3195
+ if (context && typeof context === "object") {
3196
+ if (Array.isArray(context)) {
3197
+ for (let i = 0; i < context.length; i += 1) {
3198
+ if (i in context) {
3199
+ await renderItem(context[i], i, i, i === context.length - 1);
3200
+ }
3201
+ }
3202
+ } else if (typeof context[Symbol.iterator] === "function") {
3203
+ const items = Array.from(context);
3204
+ for (let i = 0; i < items.length; i += 1) {
3205
+ await renderItem(items[i], i, i, i === items.length - 1);
3206
+ }
3207
+ } else {
3208
+ const keys = Object.keys(context);
3209
+ for (let i = 0; i < keys.length; i += 1) {
3210
+ const key = keys[i];
3211
+ await renderItem(context[key], key, i, i === keys.length - 1);
3212
+ }
3213
+ }
3214
+ }
3215
+ if (parts.length === 0) {
3216
+ return String(await inverse(this) ?? "");
3217
+ }
3218
+ return parts.join("");
3219
+ };
3220
+ }
3221
+ function dateWrapper(fn) {
3222
+ return ((...args) => {
3223
+ if (args[0] == null || args[0] === "") return null;
3224
+ if (typeof args[0] === "string") args[0] = new Date(args[0]);
3225
+ return fn(...args);
3226
+ });
3227
+ }
3228
+ function formatDecimal(...args) {
3229
+ if (!args || args.length < 1) {
3230
+ throw new Error("Missing required arguments.");
3231
+ }
3232
+ const numberValue = args[0];
3233
+ if (typeof numberValue !== "number" || isNaN(numberValue) || !isFinite(numberValue)) {
3234
+ throw new Error("The first argument must be a valid number.");
3235
+ }
3236
+ if (typeof args[1] === "string" && args[1].includes("-")) {
3237
+ return new Intl.NumberFormat(args[1]).format(numberValue);
3238
+ }
3239
+ const decimalPrecision = args[1] ?? 2;
3240
+ const decimalSeparator = args[2] || ".";
3241
+ const thousandsSeparator = args[3] || (decimalSeparator === "," ? "." : ",");
3242
+ if (!Number.isInteger(decimalPrecision)) {
3243
+ throw new Error("Invalid decimal precision.");
3244
+ }
3245
+ const validSeparators = [".", ","];
3246
+ if (decimalSeparator === thousandsSeparator || !validSeparators.includes(decimalSeparator) || !validSeparators.includes(thousandsSeparator)) {
3247
+ throw new Error("Invalid separators.");
3248
+ }
3249
+ const integerPart = Math.floor(numberValue);
3250
+ const decimalPart = Math.abs(numberValue - integerPart);
3251
+ const integerString = integerPart.toString().replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator);
3252
+ const decimalString = decimalPart.toFixed(decimalPrecision).slice(2);
3253
+ return decimalPrecision > 0 ? `${integerString}${decimalSeparator}${decimalString}` : integerString;
3254
+ }
3255
+ function formatMoney(...args) {
3256
+ if (!args || args.length < 1) {
3257
+ throw new Error("Missing required arguments.");
3258
+ }
3259
+ const numberValue = args[0];
3260
+ if (typeof numberValue !== "number" || isNaN(numberValue) || !isFinite(numberValue)) {
3261
+ throw new Error("The first argument must be a valid number.");
3262
+ }
3263
+ if (typeof args[1] === "string" && args[1].includes("-")) {
3264
+ return new Intl.NumberFormat(args[1], {
3265
+ style: "currency",
3266
+ currency: args[2]
3267
+ }).format(numberValue);
3268
+ }
3269
+ const currency = args[4] || "$";
3270
+ const currencyPosition = args[5] || "start";
3271
+ if (currencyPosition !== "start" && currencyPosition !== "end") {
3272
+ throw new Error("Invalid currency position. It must be 'start' or 'end'.");
3273
+ }
3274
+ const formattedNumber = formatDecimal(numberValue, args[1], args[2], args[3]);
3275
+ return currencyPosition === "start" ? `${currency}${formattedNumber}` : `${formattedNumber}${currency}`;
3276
+ }
3277
+ function percentage(...args) {
3278
+ const pct = args[0] / args[1] * 100;
3279
+ return pct.toFixed(args[2]);
3280
+ }
3281
+ function truncate(...args) {
3282
+ const text = args[0];
3283
+ const limit = args[1];
3284
+ return text.length > limit ? `${text.substring(0, limit)}...` : text;
3285
+ }
3286
+ function join(...args) {
3287
+ return args[0].join(args[1]);
3288
+ }
3289
+ function formatDurationInSeconds(durationInSeconds) {
3290
+ return formatDuration({
3291
+ hours: Math.floor(durationInSeconds / 3600),
3292
+ minutes: Math.floor(durationInSeconds % 3600 / 60),
3293
+ seconds: durationInSeconds % 60
3294
+ });
3295
+ }
3296
+ async function sha256(message) {
3297
+ if (!message) return "";
3298
+ const msgUint8 = new TextEncoder().encode(message);
3299
+ const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8);
3300
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
3301
+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
3302
+ }
3303
+ function ascii(str) {
3304
+ if (!str) return "";
3305
+ let s = str.replace(/^\s+|\s+$/g, "");
3306
+ const from = "\xC1\xC4\xC2\xC0\xC3\xC5\u010C\xC7\u0106\u010E\xC9\u011A\xCB\xC8\xCA\u1EBC\u0114\u0206\u011E\xCD\xCC\xCE\xCF\u0130\u0147\xD1\xD3\xD6\xD2\xD4\xD5\xD8\u0158\u0154\u0160\u015E\u0164\xDA\u016E\xDC\xD9\xDB\xDD\u0178\u017D\xE1\xE4\xE2\xE0\xE3\xE5\u010D\xE7\u0107\u010F\xE9\u011B\xEB\xE8\xEA\u1EBD\u0115\u0207\u011F\xED\xEC\xEE\xEF\u0131\u0148\xF1\xF3\xF6\xF2\xF4\xF5\xF8\xF0\u0159\u0155\u0161\u015F\u0165\xFA\u016F\xFC\xF9\xFB\xFD\xFF\u017E\xFE\xDE\u0110\u0111\xDF\xC6a";
3307
+ const to = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa";
3308
+ for (let i = 0; i < from.length; i++) {
3309
+ s = s.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
3310
+ }
3311
+ return s.replace(/[^a-zA-Z0-9\s\-.@]/g, "");
3312
+ }
3313
+ function extractNameFromEmail(email, nameOriginal) {
3314
+ const localPart = typeof email === "string" ? email.split("@")[0] : "";
3315
+ function capitalize(s) {
3316
+ return s.length === 0 ? "" : s.charAt(0).toLocaleUpperCase() + s.slice(1).toLowerCase();
3317
+ }
3318
+ function clean(s) {
3319
+ return capitalize(s.replace(/[^a-zA-Z]/g, ""));
3320
+ }
3321
+ if (localPart) {
3322
+ if (localPart.includes(".")) {
3323
+ const parts = localPart.split(".");
3324
+ return `${clean(parts[0])} ${clean(parts[1])}`;
3325
+ }
3326
+ return `${clean(localPart)} `;
3327
+ }
3328
+ return nameOriginal || "";
3329
+ }
3330
+ function slug(str, separator = "-") {
3331
+ let s = str.replace(/^\s+|\s+$/g, "").toLowerCase();
3332
+ const from = "\xC1\xC4\xC2\xC0\xC3\xC5\u010C\xC7\u0106\u010E\xC9\u011A\xCB\xC8\xCA\u1EBC\u0114\u0206\u011E\xCD\xCC\xCE\xCF\u0130\u0147\xD1\xD3\xD6\xD2\xD4\xD5\xD8\u0158\u0154\u0160\u015E\u0164\xDA\u016E\xDC\xD9\xDB\xDD\u0178\u017D\xE1\xE4\xE2\xE0\xE3\xE5\u010D\xE7\u0107\u010F\xE9\u011B\xEB\xE8\xEA\u1EBD\u0115\u0207\u011F\xED\xEC\xEE\xEF\u0131\u0148\xF1\xF3\xF6\xF2\xF4\xF5\xF8\xF0\u0159\u0155\u0161\u015F\u0165\xFA\u016F\xFC\xF9\xFB\xFD\xFF\u017E\xFE\xDE\u0110\u0111\xDF\xC6a\xB7/_,:;";
3333
+ const to = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------";
3334
+ for (let i = 0; i < from.length; i++) {
3335
+ s = s.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
3336
+ }
3337
+ return s.replace(/[^a-z0-9 -]/g, "").replace(/\s+/g, separator).replace(/-+/g, separator);
3338
+ }
3339
+ function filterEmpty(arr) {
3340
+ if (arr && arr.filter) {
3341
+ return arr.filter((el) => el != null && el !== "");
3342
+ }
3343
+ return arr;
3344
+ }
3345
+ function padLeft(value, totalLength, padChar = "0") {
3346
+ let s = String(value);
3347
+ while (s.length < totalLength) {
3348
+ s = padChar + s;
3349
+ }
3350
+ return s;
3351
+ }
3352
+ function padRight(value, totalLength, padChar = "0") {
3353
+ let s = String(value);
3354
+ while (s.length < totalLength) {
3355
+ s = s + padChar;
3356
+ }
3357
+ return s;
3358
+ }
3359
+ function ifNull(value, alternativeValue) {
3360
+ return value === null || value === void 0 ? alternativeValue : value;
3361
+ }
3362
+ function objectToString(objectValue) {
3363
+ let result = "";
3364
+ if (objectValue instanceof Object) {
3365
+ for (const [key, value] of Object.entries(objectValue)) {
3366
+ result = `${key}:${value}`;
3367
+ }
3368
+ }
3369
+ return result;
3370
+ }
3371
+ function isEqual(a, b) {
3372
+ if (a == null && b == null) return true;
3373
+ if (a == null || b == null) return false;
3374
+ if (a instanceof Date || b instanceof Date) {
3375
+ const da = typeof a === "string" ? new Date(a) : a;
3376
+ const db = typeof b === "string" ? new Date(b) : b;
3377
+ return da.getTime() === db.getTime();
3378
+ }
3379
+ if (typeof a === "object" && typeof b === "object") {
3380
+ if (a.id && b.id) return a.id === b.id;
3381
+ return JSON.stringify(a) === JSON.stringify(b);
3382
+ }
3383
+ if (typeof a === "object" && a.id && (typeof b === "string" || typeof b === "number")) {
3384
+ return a.id === b;
3385
+ }
3386
+ if ((typeof a === "string" || typeof a === "number") && typeof b === "object" && b.id) {
3387
+ return a === b.id;
3388
+ }
3389
+ return a === b;
3390
+ }
3391
+ function isEqualOrContained(needle, haystack) {
3392
+ if (Array.isArray(haystack)) {
3393
+ return haystack.some((item) => isEqual(item, needle));
3394
+ }
3395
+ if (typeof needle === "object" && typeof haystack === "object" && needle?.id && haystack?.id) {
3396
+ return needle.id === haystack.id;
3397
+ }
3398
+ return isEqual(needle, haystack);
3399
+ }
3400
+ function getDbValue(value) {
3401
+ if (typeof value === "object" && value !== null) {
3402
+ if (value.id) return value.id;
3403
+ if (Array.isArray(value) && value.length > 0 && value[0]?.id) return value[0].id;
3404
+ }
3405
+ return value;
3406
+ }
3407
+ function differenceInBusinessDaysCustom(startDate, endDate, options = {}) {
3408
+ if (!startDate || !endDate) return null;
3409
+ const start = new Date(startDate);
3410
+ const end = new Date(endDate);
3411
+ const config = {
3412
+ workStartHour: 9,
3413
+ workEndHour: 18,
3414
+ lunchBreakHours: 1,
3415
+ lunchStartHour: 12.5,
3416
+ lunchEndHour: 13.5,
3417
+ includePartialDays: true,
3418
+ ...options
3419
+ };
3420
+ const workingHoursPerDay = config.workEndHour - config.workStartHour - config.lunchBreakHours;
3421
+ const businessDays = differenceInBusinessDays(end, start);
3422
+ if (!config.includePartialDays) return businessDays;
3423
+ if (businessDays > 0) {
3424
+ const startHour2 = start.getHours() + start.getMinutes() / 60;
3425
+ const endHour2 = end.getHours() + end.getMinutes() / 60;
3426
+ if ((startHour2 < config.workStartHour || startHour2 > config.workEndHour) && (endHour2 < config.workStartHour || endHour2 > config.workEndHour)) {
3427
+ return 0;
3428
+ }
3429
+ let firstDayHours = 0;
3430
+ if (startHour2 >= config.workStartHour && startHour2 <= config.workEndHour) {
3431
+ firstDayHours = config.workEndHour - startHour2;
3432
+ if (startHour2 < config.lunchStartHour) {
3433
+ firstDayHours -= config.lunchBreakHours;
3434
+ } else if (startHour2 >= config.lunchStartHour && startHour2 < config.lunchEndHour) {
3435
+ firstDayHours -= config.lunchEndHour - startHour2;
3436
+ }
3437
+ }
3438
+ let lastDayHours = 0;
3439
+ if (endHour2 >= config.workStartHour) {
3440
+ const effectiveEndHour = Math.min(endHour2, config.workEndHour);
3441
+ lastDayHours = effectiveEndHour - config.workStartHour;
3442
+ if (effectiveEndHour > config.lunchEndHour) {
3443
+ lastDayHours -= config.lunchBreakHours;
3444
+ } else if (effectiveEndHour > config.lunchStartHour && effectiveEndHour <= config.lunchEndHour) {
3445
+ lastDayHours -= effectiveEndHour - config.lunchStartHour;
3446
+ }
3447
+ }
3448
+ const adjustedBusinessDays = businessDays - 1;
3449
+ const totalExtraHours = firstDayHours + lastDayHours;
3450
+ const hourDecimal = Math.max(0, totalExtraHours) / workingHoursPerDay;
3451
+ return Math.round((adjustedBusinessDays + hourDecimal) * 1e3) / 1e3;
3452
+ }
3453
+ const startHour = start.getHours() + start.getMinutes() / 60;
3454
+ const endHour = end.getHours() + end.getMinutes() / 60;
3455
+ if (businessDays === 0) {
3456
+ const dayOfWeek = start.getDay();
3457
+ if (dayOfWeek === 0 || dayOfWeek === 6) return 0;
3458
+ }
3459
+ if (businessDays === 0 && (startHour > config.workEndHour || endHour < config.workStartHour)) {
3460
+ return 0;
3461
+ }
3462
+ let workingHours = Math.max(0, endHour - startHour);
3463
+ if (startHour < config.lunchEndHour && endHour > config.lunchStartHour) {
3464
+ const lunchOverlap = Math.min(endHour, config.lunchEndHour) - Math.max(startHour, config.lunchStartHour);
3465
+ workingHours -= Math.max(0, lunchOverlap);
3466
+ }
3467
+ return Math.round(Math.max(0, workingHours / workingHoursPerDay) * 1e3) / 1e3;
3468
+ }
3469
+ var dateFunctions = {
3470
+ formatDate: format,
3471
+ formatDistance,
3472
+ formatDistanceStrict,
3473
+ formatDistanceToNow,
3474
+ formatDistanceToNowStrict,
3475
+ formatDuration,
3476
+ formatISO,
3477
+ formatRelative,
3478
+ addYears,
3479
+ addMonths,
3480
+ addWeeks,
3481
+ addDays,
3482
+ addHours,
3483
+ addMinutes,
3484
+ addSeconds,
3485
+ addMilliseconds,
3486
+ subYears,
3487
+ subMonths,
3488
+ subWeeks,
3489
+ subDays,
3490
+ subHours,
3491
+ subMinutes,
3492
+ subSeconds,
3493
+ subMilliseconds,
3494
+ isAfter,
3495
+ isBefore,
3496
+ isDatesEqual: isEqual$1,
3497
+ isPast,
3498
+ differenceInYears,
3499
+ differenceInMonths,
3500
+ differenceInWeeks,
3501
+ differenceInDays,
3502
+ differenceInHours,
3503
+ differenceInMinutes,
3504
+ differenceInSeconds,
3505
+ differenceInBusinessDays,
3506
+ differenceInBusinessDaysCustom,
3507
+ startOfDay,
3508
+ startOfMonth,
3509
+ startOfWeek,
3510
+ startOfToday,
3511
+ startOfQuarter,
3512
+ endOfDay,
3513
+ endOfMonth,
3514
+ endOfWeek,
3515
+ endOfToday,
3516
+ endOfQuarter
3517
+ };
3518
+ for (const key of Object.keys(dateFunctions)) {
3519
+ dateFunctions[key] = dateWrapper(dateFunctions[key]);
3520
+ }
3521
+ var jsonataHelpers = {
3522
+ ...dateFunctions,
3523
+ // Format functions
3524
+ formatDecimal,
3525
+ formatMoney,
3526
+ join,
3527
+ truncate,
3528
+ percentage,
3529
+ formatDurationInSeconds,
3530
+ // String / misc
3531
+ sha256,
3532
+ ascii,
3533
+ extractNameFromEmail,
3534
+ slug,
3535
+ filterEmpty,
3536
+ startsWith: (haystack, needle) => haystack.startsWith(needle),
3537
+ endsWith: (haystack, needle) => haystack.endsWith(needle),
3538
+ includes: (haystack, needle) => {
3539
+ if (!haystack || !needle) return false;
3540
+ return haystack.includes(needle);
3541
+ },
3542
+ objectToString,
3543
+ padLeft,
3544
+ padRight,
3545
+ ifNull,
3546
+ // Equality / DB helpers
3547
+ isEqual,
3548
+ isEqualOrContained,
3549
+ isNotEqualOrContained: (needle, haystack) => !isEqualOrContained(needle, haystack),
3550
+ getDbValue
3551
+ };
3552
+
3553
+ // src/template-engine.ts
3554
+ var HTML_ENTITIES = {
3555
+ amp: "&",
3556
+ lt: "<",
3557
+ gt: ">",
3558
+ quot: '"',
3559
+ apos: "'"
3560
+ };
3561
+ function decodeHtmlEntities(str) {
3562
+ return str.replace(/&(amp|lt|gt|quot|apos);/g, (match, entity) => HTML_ENTITIES[entity] ?? match);
3563
+ }
3564
+ function removeHtmlTags(str) {
3565
+ if (str === null || str === "") return "";
3566
+ return String(str).replace(/(<([^>]+)>)/gi, "");
3567
+ }
3568
+ var FORMULA_EXPR_RE = /(\{\{formula\s)(?<formula>[^}]+)(\}\})/g;
3569
+ var IF_FORMULA_RE = /(\{\{#if\s)(?<formula>[^}]+)(\}\})/g;
3570
+ var INLINE_RE = /\{\{<([^*]+)\}\}/g;
3571
+ function preprocessTemplate(tpl) {
3572
+ let result = tpl.replace(FORMULA_EXPR_RE, (_matched, g1, g2, g3) => {
3573
+ const escaped = decodeHtmlEntities(g2.replace(/'/g, "\\'"));
3574
+ return `${g1}'${removeHtmlTags(escaped)}'${g3}`;
3575
+ });
3576
+ result = result.replace(IF_FORMULA_RE, (_matched, g1, g2, g3) => {
3577
+ const escaped = decodeHtmlEntities(g2.replace(/'/g, "\\'"));
3578
+ return `${g1} (formula '${escaped}')${g3}`;
3579
+ });
3580
+ result = result.replace(INLINE_RE, (_matched, group) => {
3581
+ return removeHtmlTags(group);
3582
+ });
3583
+ return result;
3584
+ }
3585
+ function registerHelpers(hb, dateUtils, numberUtils, bindings) {
3586
+ hb.registerHelper("repeat", async (n, block) => {
3587
+ let accum = "";
3588
+ for (let i = 0; i < n; ++i) {
3589
+ accum += block.fn(i);
3590
+ }
3591
+ return accum;
3592
+ });
3593
+ hb.registerHelper("sum", (...args) => {
3594
+ args = args.slice(0, -1);
3595
+ if (args.length >= 2 && Array.isArray(args[0]) && typeof args[1] === "string") {
3596
+ const key = args[1];
3597
+ return Handlebars.escapeExpression(
3598
+ String(args[0].reduce((total, obj) => total + (Number(obj[key]) || 0), 0))
3599
+ );
3600
+ }
3601
+ const sumValue = (val) => {
3602
+ if (Array.isArray(val)) return val.reduce((acc, item) => acc + sumValue(item), 0);
3603
+ return Number(val) || 0;
3604
+ };
3605
+ return Handlebars.escapeExpression(
3606
+ String(args.reduce((total, num) => total + sumValue(num), 0))
3607
+ );
3608
+ });
3609
+ if (dateUtils) {
3610
+ hb.registerHelper("formatDate", (input, options) => {
3611
+ const dateFormat = options.hash.format || void 0;
3612
+ const result = Handlebars.escapeExpression(
3613
+ dateUtils.formatDate(input, dateFormat ? { format: dateFormat } : void 0) ?? ""
3614
+ );
3615
+ return new Handlebars.SafeString(result);
3616
+ });
3617
+ hb.registerHelper("formatDateTime", (input) => {
3618
+ const result = Handlebars.escapeExpression(
3619
+ dateUtils.formatDateTime(input) ?? ""
3620
+ );
3621
+ return new Handlebars.SafeString(result);
3622
+ });
3623
+ }
3624
+ if (numberUtils) {
3625
+ hb.registerHelper("formatNumber", (input, options) => {
3626
+ const result = Handlebars.escapeExpression(
3627
+ numberUtils.formatNumber(input, {
3628
+ decimalPrecision: options.hash.decimalPrecision || void 0,
3629
+ decimalSeparator: options.hash.decimalSeparator || void 0,
3630
+ thousandSeparator: options.hash.thousandSeparator !== void 0 ? options.hash.thousandSeparator : void 0
3631
+ }) ?? ""
3632
+ );
3633
+ return result;
3634
+ });
3635
+ }
3636
+ hb.registerHelper("formatNumberToWords", (number, options) => {
3637
+ return formatNumberToWords(number, {
3638
+ useSpaces: options.hash.useSpaces || false,
3639
+ lang: options.hash.lang || "TR",
3640
+ currency: options.hash.currency || "TRY"
3641
+ });
3642
+ });
3643
+ hb.registerHelper("formatDurationAsTime", (input) => {
3644
+ return Handlebars.escapeExpression(formatDurationAsTime(input));
3645
+ });
3646
+ hb.registerHelper("formatDurationAsWords", (input) => {
3647
+ return Handlebars.escapeExpression(formatDurationAsWords(input));
3648
+ });
3649
+ hb.registerHelper("formatDurationAsHours", (input, options) => {
3650
+ const decimalPrecision = options.hash.decimalPrecision || 2;
3651
+ return Handlebars.escapeExpression(formatDurationAsHours(input, decimalPrecision));
3652
+ });
3653
+ hb.registerHelper("formula", async function(context, options) {
3654
+ let data;
3655
+ let opts;
3656
+ if (!options && context && context.fn) {
3657
+ opts = context;
3658
+ data = Array.isArray(opts.data.root) ? opts.data.root[opts.data.index] : opts.data.root || {};
3659
+ } else {
3660
+ opts = options;
3661
+ data = opts.data.root;
3662
+ }
3663
+ if (opts.fn) {
3664
+ const expression = await opts.fn(this);
3665
+ if (!expression) return "";
3666
+ try {
3667
+ return await jsonata(expression).evaluate(data || {}, bindings);
3668
+ } catch (err) {
3669
+ console.warn("Error during jsonata evaluation", { expression, data });
3670
+ throw err;
3671
+ }
3672
+ }
3673
+ if (typeof context === "string") {
3674
+ try {
3675
+ return await jsonata(context).evaluate(data || {}, bindings);
3676
+ } catch (err) {
3677
+ console.warn("Error during jsonata evaluation", { context, data });
3678
+ throw err;
3679
+ }
3680
+ }
3681
+ return "";
3682
+ });
3683
+ hb.registerHelper("path", (...args) => {
3684
+ const options = args[args.length - 1];
3685
+ const expression = args[0];
3686
+ const result = JSONPath({ path: expression, json: options.data.root });
3687
+ if (result == null) return "";
3688
+ const ctx = Array.isArray(result) && result.length === 1 ? result[0] : result;
3689
+ return options.fn(ctx);
3690
+ });
3691
+ hb.registerHelper("json", (context) => {
3692
+ return JSON.stringify(context, null, 2);
3693
+ });
3694
+ }
3695
+ function createTemplateEngine(config = {}) {
3696
+ const {
3697
+ dateUtils,
3698
+ numberUtils,
3699
+ extraJsonataBindings = {},
3700
+ additionalHelpers = {},
3701
+ user
3702
+ } = config;
3703
+ const allBindings = { ...jsonataHelpers, ...extraJsonataBindings };
3704
+ const hb = (0, import_handlebars_async_helpers.default)(Handlebars);
3705
+ hb.registerHelper("each", createAsyncEachHelper(hb));
3706
+ registerHelpers(hb, dateUtils, numberUtils, allBindings);
3707
+ for (const [name, fn] of Object.entries(additionalHelpers)) {
3708
+ hb.registerHelper(name, fn);
3709
+ }
3710
+ function compileTpl(templateString) {
3711
+ const preprocessed = preprocessTemplate(templateString);
3712
+ return hb.compile(preprocessed);
3713
+ }
3714
+ async function compileFormula(expression, data) {
3715
+ try {
3716
+ const metadata = {
3717
+ ...data?.metadata || {},
3718
+ user: user ?? null
3719
+ };
3720
+ return await jsonata(expression).evaluate(
3721
+ { ...data, metadata },
3722
+ allBindings
3723
+ );
3724
+ } catch (err) {
3725
+ console.warn("Error during jsonata evaluation", { expression, data });
3726
+ console.warn(err);
3727
+ return void 0;
3728
+ }
3729
+ }
3730
+ return {
3731
+ compileTpl,
3732
+ compileFormula,
3733
+ jsonataHelpers: allBindings
3734
+ };
3735
+ }
3736
+
3737
+ // src/app-config-client.ts
3738
+ function createAppConfigClient(client, appId, options) {
3739
+ const basePath = `/v1/tenant/apps/${appId}/config`;
3740
+ const inventory = options?.inventory;
3741
+ async function get() {
3742
+ if (inventory) {
3743
+ const cached = await inventory.getAppConfig(appId);
3744
+ if (cached) return cached;
3745
+ }
3746
+ return unwrapEnvelope(await client.get(basePath));
3747
+ }
3748
+ async function upsert(body) {
3749
+ const result = unwrapEnvelope(await client.put(basePath, body));
3750
+ inventory?.setAppConfig(appId, result);
3751
+ return result;
3752
+ }
3753
+ async function remove() {
3754
+ await client.delete(basePath);
3755
+ inventory?.setAppConfig(appId, null);
3756
+ }
3757
+ return { get, upsert, remove };
3758
+ }
3759
+
3760
+ // src/user-app-config-client.ts
3761
+ function createUserAppConfigClient(client, appId, options) {
3762
+ const basePath = `/v1/tenant/apps/${appId}/user-config`;
3763
+ const inventory = options?.inventory;
3764
+ async function get() {
3765
+ if (inventory) {
3766
+ const cached = await inventory.getUserAppConfig(appId);
3767
+ if (cached) return cached;
3768
+ }
3769
+ return unwrapEnvelope(await client.get(basePath));
3770
+ }
3771
+ async function upsert(body) {
3772
+ const result = unwrapEnvelope(await client.put(basePath, body));
3773
+ inventory?.setUserAppConfig(appId, result);
3774
+ return result;
3775
+ }
3776
+ async function remove() {
3777
+ await client.delete(basePath);
3778
+ inventory?.setUserAppConfig(appId, null);
3779
+ }
3780
+ return { get, upsert, remove };
3781
+ }
3782
+
3783
+ // src/data-view-client.ts
3784
+ async function resolveDataSource(inventory, appSlug, dataSourceSlug) {
3785
+ const sources = await inventory.listDataSources();
3786
+ const match = sources.find(
3787
+ (ds) => (ds.appSlug ?? ds.app_slug) === appSlug && ds.slug === dataSourceSlug
3788
+ );
3789
+ return match ?? null;
3790
+ }
3791
+ function createDataViewClient(client, appSlug, dataSourceSlug, options) {
3792
+ const basePath = `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/views`;
3793
+ const inventory = options?.inventory;
3794
+ async function list(params) {
3795
+ if (inventory) {
3796
+ const dataSource = await resolveDataSource(inventory, appSlug, dataSourceSlug);
3797
+ if (dataSource) {
3798
+ const views = dataSource.views ?? [];
3799
+ return params?.appId ? views.filter((view) => view.tenant_app_id === params.appId) : views;
3800
+ }
3801
+ }
3802
+ return unwrapEnvelope(
3803
+ await client.get(basePath, params?.appId ? { appId: params.appId } : void 0)
3804
+ );
3805
+ }
3806
+ async function get(viewId) {
3807
+ if (inventory) {
3808
+ const dataSource = await resolveDataSource(inventory, appSlug, dataSourceSlug);
3809
+ const match = dataSource?.views?.find((view) => view.id === viewId);
3810
+ if (match) return match;
3811
+ }
3812
+ return unwrapEnvelope(await client.get(`${basePath}/${viewId}`));
3813
+ }
3814
+ async function create(body) {
3815
+ const result = unwrapEnvelope(await client.post(basePath, body));
3816
+ inventory?.upsertDataView(result);
3817
+ return result;
3818
+ }
3819
+ async function update(viewId, body) {
3820
+ const result = unwrapEnvelope(await client.put(`${basePath}/${viewId}`, body));
3821
+ if (body.archived === true) {
3822
+ inventory?.removeDataView(viewId);
3823
+ } else {
3824
+ inventory?.upsertDataView(result);
3825
+ }
3826
+ return result;
3827
+ }
3828
+ async function remove(viewId) {
3829
+ await client.delete(`${basePath}/${viewId}`);
3830
+ inventory?.removeDataView(viewId);
3831
+ }
3832
+ return {
3833
+ list,
3834
+ get,
3835
+ create,
3836
+ update,
3837
+ remove
3838
+ };
3839
+ }
3840
+
3841
+ // src/data-form-client.ts
3842
+ async function resolveDataSource2(inventory, appSlug, dataSourceSlug) {
3843
+ const sources = await inventory.listDataSources();
3844
+ const match = sources.find(
3845
+ (ds) => (ds.appSlug ?? ds.app_slug) === appSlug && ds.slug === dataSourceSlug
3846
+ );
3847
+ return match ?? null;
3848
+ }
3849
+ function createDataFormClient(client, appSlug, dataSourceSlug, options) {
3850
+ const basePath = `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/forms`;
3851
+ const inventory = options?.inventory;
3852
+ async function list() {
3853
+ if (inventory) {
3854
+ const dataSource = await resolveDataSource2(inventory, appSlug, dataSourceSlug);
3855
+ if (dataSource) return dataSource.forms ?? [];
3856
+ }
3857
+ return unwrapEnvelope(await client.get(basePath));
3858
+ }
3859
+ async function get(formId) {
3860
+ if (inventory) {
3861
+ const dataSource = await resolveDataSource2(inventory, appSlug, dataSourceSlug);
3862
+ const match = dataSource?.forms?.find((form) => form.id === formId);
3863
+ if (match) return match;
3864
+ }
3865
+ return unwrapEnvelope(await client.get(`${basePath}/${formId}`));
3866
+ }
3867
+ async function create(body) {
3868
+ const result = unwrapEnvelope(await client.post(basePath, body));
3869
+ inventory?.upsertDataForm(result);
3870
+ return result;
3871
+ }
3872
+ async function update(formId, body) {
3873
+ const result = unwrapEnvelope(await client.put(`${basePath}/${formId}`, body));
3874
+ if (body.archived === true) {
3875
+ inventory?.removeDataForm(formId);
3876
+ } else {
3877
+ inventory?.upsertDataForm(result);
3878
+ }
3879
+ return result;
3880
+ }
3881
+ async function remove(formId) {
3882
+ await client.delete(`${basePath}/${formId}`);
3883
+ inventory?.removeDataForm(formId);
3884
+ }
3885
+ return {
3886
+ list,
3887
+ get,
3888
+ create,
3889
+ update,
3890
+ remove
3891
+ };
3892
+ }
3893
+
3894
+ // src/data-source-client.ts
3895
+ function matchesSlug(dataSource, appSlug, dataSourceSlug) {
3896
+ const ownerAppSlug = dataSource.appSlug ?? dataSource.app_slug;
3897
+ return ownerAppSlug === appSlug && dataSource.slug === dataSourceSlug;
3898
+ }
3899
+ function normalizeFieldType(type) {
3900
+ return type.startsWith("field-") ? type.slice("field-".length) : type;
3901
+ }
3902
+ function getRelationTargetId(field) {
3903
+ if (normalizeFieldType(field.type) !== "relation") return void 0;
3904
+ const target = field.relation_data_source_id ?? field.relationDataSourceId;
3905
+ return typeof target === "string" && target.length > 0 ? target : void 0;
3906
+ }
3907
+ function addRelationEdge(map, key, value) {
3908
+ const existing = map.get(key);
3909
+ if (existing) existing.add(value);
3910
+ else map.set(key, /* @__PURE__ */ new Set([value]));
3911
+ }
3912
+ function buildRelationIndex(sources) {
3913
+ const byId = /* @__PURE__ */ new Map();
3914
+ const parentsByChild = /* @__PURE__ */ new Map();
3915
+ const childrenByParent = /* @__PURE__ */ new Map();
3916
+ for (const dataSource of sources) byId.set(dataSource.id, dataSource);
3917
+ for (const dataSource of sources) {
3918
+ for (const field of dataSource.fields ?? []) {
3919
+ const parentId = getRelationTargetId(field);
3920
+ if (!parentId || parentId === dataSource.id) continue;
3921
+ addRelationEdge(parentsByChild, dataSource.id, parentId);
3922
+ addRelationEdge(childrenByParent, parentId, dataSource.id);
3923
+ }
3924
+ }
3925
+ return { byId, parentsByChild, childrenByParent };
3926
+ }
3927
+ function createDataSourceClient(client, options) {
3928
+ const basePath = "/v1/apps/data-sources";
3929
+ const inventory = options?.inventory;
3930
+ function buildQueryParams(params) {
3931
+ if (!params?.expand) return void 0;
3932
+ return { expand: params.expand };
3933
+ }
3934
+ async function listApps() {
3935
+ if (inventory) return inventory.listApps();
3936
+ return unwrapEnvelope(await client.get("/v1/apps"));
3937
+ }
3938
+ async function list(params) {
3939
+ if (inventory && !params?.expand) return inventory.listDataSources();
3940
+ return unwrapEnvelope(
3941
+ await client.get(basePath, buildQueryParams(params))
3942
+ );
3943
+ }
3944
+ async function listByAppSlug(appSlug, params) {
3945
+ if (inventory && !params?.expand) {
3946
+ const sources = await inventory.listDataSources();
3947
+ return sources.filter((ds) => (ds.appSlug ?? ds.app_slug) === appSlug);
3948
+ }
3949
+ return unwrapEnvelope(
3950
+ await client.get(`/v1/apps/${appSlug}/data-sources`, buildQueryParams(params))
3951
+ );
3952
+ }
3953
+ async function listByAppId(appId, params) {
3954
+ if (inventory && !params?.expand) {
3955
+ const sources = await inventory.listDataSources();
3956
+ return sources.filter((ds) => ds.tenant_app_id === appId);
3957
+ }
3958
+ const queryParams = { appId };
3959
+ if (params?.expand) {
3960
+ queryParams.expand = params.expand;
3961
+ }
3962
+ return unwrapEnvelope(await client.get(basePath, queryParams));
3963
+ }
3964
+ async function getById(dataSourceId, params) {
3965
+ if (inventory && !params?.expand) {
3966
+ const sources = await inventory.listDataSources();
3967
+ const match = sources.find((ds) => ds.id === dataSourceId);
3968
+ if (match) return match;
3969
+ }
3970
+ return unwrapEnvelope(
3971
+ await client.get(`${basePath}/${dataSourceId}`, buildQueryParams(params))
3972
+ );
3973
+ }
3974
+ async function getBySlug(appSlug, dataSourceSlug, params) {
3975
+ if (inventory && !params?.expand) {
3976
+ const sources = await inventory.listDataSources();
3977
+ const match = sources.find((ds) => matchesSlug(ds, appSlug, dataSourceSlug));
3978
+ if (match) return match;
3979
+ }
3980
+ return unwrapEnvelope(
3981
+ await client.get(
3982
+ `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}`,
3983
+ buildQueryParams(params)
3984
+ )
3985
+ );
3986
+ }
3987
+ async function getFields(dataSourceId) {
3988
+ if (inventory) {
3989
+ const cached = await getById(dataSourceId);
3990
+ if (cached.fields) return cached.fields;
3991
+ }
3992
+ const dataSource = await getById(dataSourceId, { expand: "fields" });
3993
+ return dataSource.fields ?? [];
3994
+ }
3995
+ async function getFieldById(dataSourceId, fieldId) {
3996
+ return (await getFields(dataSourceId)).find((field) => field.id === fieldId);
3997
+ }
3998
+ async function getFieldBySlug(dataSourceId, fieldSlug) {
3999
+ return (await getFields(dataSourceId)).find((field) => field.slug === fieldSlug);
4000
+ }
4001
+ async function getEnumsByFieldId(dataSourceId, fieldId) {
4002
+ const field = await getFieldById(dataSourceId, fieldId);
4003
+ return field?.enums ?? [];
4004
+ }
4005
+ async function getEnumById(dataSourceId, fieldId, enumId) {
4006
+ return (await getEnumsByFieldId(dataSourceId, fieldId)).find((option) => option.id === enumId);
4007
+ }
4008
+ let relationIndexSource = null;
4009
+ let relationIndex = null;
4010
+ async function loadAllDataSources() {
4011
+ if (inventory) return inventory.listDataSources();
4012
+ return unwrapEnvelope(await client.get(basePath, { expand: "fields" }));
4013
+ }
4014
+ async function getRelationIndex() {
4015
+ const sources = await loadAllDataSources();
4016
+ if (relationIndex && relationIndexSource === sources) return relationIndex;
4017
+ relationIndex = buildRelationIndex(sources);
4018
+ relationIndexSource = sources;
4019
+ return relationIndex;
4020
+ }
4021
+ async function resolveRelated(dataSourceId, edge) {
4022
+ const index2 = await getRelationIndex();
4023
+ const ids = index2[edge].get(dataSourceId);
4024
+ if (!ids) return [];
4025
+ const out = [];
4026
+ for (const id of ids) {
4027
+ const match = index2.byId.get(id);
4028
+ if (match) out.push(match);
4029
+ }
4030
+ return out;
4031
+ }
4032
+ async function listParentDataSources(dataSourceId) {
4033
+ return resolveRelated(dataSourceId, "parentsByChild");
4034
+ }
4035
+ async function listChildDataSources(dataSourceId) {
4036
+ return resolveRelated(dataSourceId, "childrenByParent");
4037
+ }
4038
+ async function listParentDataSourceFields(dataSourceId) {
4039
+ return (await listParentDataSources(dataSourceId)).flatMap((ds) => ds.fields ?? []);
4040
+ }
4041
+ async function listChildDataSourceFields(dataSourceId) {
4042
+ return (await listChildDataSources(dataSourceId)).flatMap((ds) => ds.fields ?? []);
4043
+ }
4044
+ return {
4045
+ listApps,
4046
+ list,
4047
+ listByAppSlug,
4048
+ listByAppId,
4049
+ getById,
4050
+ getBySlug,
4051
+ getFields,
4052
+ getFieldById,
4053
+ getFieldBySlug,
4054
+ getEnumsByFieldId,
4055
+ getEnumById,
4056
+ listParentDataSources,
4057
+ listChildDataSources,
4058
+ listParentDataSourceFields,
4059
+ listChildDataSourceFields
4060
+ };
4061
+ }
4062
+
4063
+ // src/inventory-client.ts
4064
+ var DEFAULT_TTL_MS = 5 * 60 * 1e3;
4065
+ var DEFAULT_DATA_SOURCES_EXPAND = "views,forms,fields";
4066
+ var DEFAULT_STORAGE_KEY = "docyrus:inventory";
4067
+ var SNAPSHOT_VERSION = 1;
4068
+ var DEFAULT_LOAD_STEPS = [
4069
+ "apps",
4070
+ "data-sources",
4071
+ "users",
4072
+ "brands",
4073
+ "preferences"
4074
+ ];
4075
+ function resolveStorage(option) {
4076
+ if (!option) return null;
4077
+ if (typeof option !== "string") return option;
4078
+ try {
4079
+ const key = option === "session" ? "sessionStorage" : "localStorage";
4080
+ const store = globalThis[key];
4081
+ if (!store) return null;
4082
+ const probe = "__docyrus_inventory_probe__";
4083
+ store.setItem(probe, probe);
4084
+ store.removeItem(probe);
4085
+ return store;
4086
+ } catch {
4087
+ return null;
4088
+ }
4089
+ }
4090
+ function toIdSet(value) {
4091
+ if (value === void 0) return null;
4092
+ return new Set(Array.isArray(value) ? value : [value]);
4093
+ }
4094
+ function isNotFound(error) {
4095
+ return typeof error === "object" && error !== null && error.status === 404;
4096
+ }
4097
+ function readAppIdFromEnv() {
4098
+ let value;
4099
+ try {
4100
+ value = import.meta.env?.VITE_APP_ID;
4101
+ } catch {
4102
+ value = void 0;
4103
+ }
4104
+ if (!value && typeof process !== "undefined") {
4105
+ value = process.env?.VITE_APP_ID;
4106
+ }
4107
+ return value && value.length > 0 ? value : void 0;
4108
+ }
4109
+ function normalizeEmbeddedForm(raw, dataSourceId) {
4110
+ const isDefault = raw.is_default ?? raw.isDefault ?? false;
4111
+ const tenantDataSourceId = raw.tenant_data_source_id ?? dataSourceId;
4112
+ return {
4113
+ ...raw,
4114
+ tenant_data_source_id: tenantDataSourceId,
4115
+ is_default: isDefault,
4116
+ archived: raw.archived ?? false
4117
+ };
4118
+ }
4119
+ function normalizeEmbeddedView(raw) {
4120
+ return raw.archived === void 0 ? { ...raw, archived: false } : raw;
4121
+ }
4122
+ function normalizeDataSource(dataSource) {
4123
+ const views = Array.isArray(dataSource.views) ? dataSource.views.map(normalizeEmbeddedView) : dataSource.views;
4124
+ const forms = Array.isArray(dataSource.forms) ? dataSource.forms.map((form) => normalizeEmbeddedForm(form, dataSource.id)) : dataSource.forms;
4125
+ if (views === dataSource.views && forms === dataSource.forms) return dataSource;
4126
+ return { ...dataSource, views, forms };
4127
+ }
4128
+ function createInventoryClient(client, options) {
4129
+ const ttlMs = options?.ttlMs ?? DEFAULT_TTL_MS;
4130
+ const dataSourcesExpand = options?.dataSourcesExpand ?? DEFAULT_DATA_SOURCES_EXPAND;
4131
+ const storage = resolveStorage(options?.storage);
4132
+ const storageKey = options?.storageKey ?? DEFAULT_STORAGE_KEY;
4133
+ let apps = null;
4134
+ let dataSources = null;
4135
+ let users = null;
4136
+ let brands = null;
4137
+ let preferences = null;
4138
+ const appConfigs = /* @__PURE__ */ new Map();
4139
+ const userAppConfigs = /* @__PURE__ */ new Map();
4140
+ let appsInFlight = null;
4141
+ let dataSourcesInFlight = null;
4142
+ let usersInFlight = null;
4143
+ let brandsInFlight = null;
4144
+ let preferencesInFlight = null;
4145
+ const appConfigsInFlight = /* @__PURE__ */ new Map();
4146
+ const userAppConfigsInFlight = /* @__PURE__ */ new Map();
4147
+ function persist() {
4148
+ if (!storage) return;
4149
+ const snapshot = {
4150
+ v: SNAPSHOT_VERSION,
4151
+ apps,
4152
+ dataSources,
4153
+ users,
4154
+ brands,
4155
+ preferences,
4156
+ appConfigs: [...appConfigs],
4157
+ userAppConfigs: [...userAppConfigs]
4158
+ };
4159
+ try {
4160
+ storage.setItem(storageKey, JSON.stringify(snapshot));
4161
+ } catch {
4162
+ }
4163
+ }
4164
+ function hydrate() {
4165
+ if (!storage) return;
4166
+ let raw;
4167
+ try {
4168
+ raw = storage.getItem(storageKey);
4169
+ } catch {
4170
+ return;
4171
+ }
4172
+ if (!raw) return;
4173
+ let snapshot = null;
4174
+ try {
4175
+ const parsed = JSON.parse(raw);
4176
+ if (parsed && parsed.v === SNAPSHOT_VERSION) snapshot = parsed;
4177
+ } catch {
4178
+ snapshot = null;
4179
+ }
4180
+ if (!snapshot) return;
4181
+ apps = snapshot.apps ?? null;
4182
+ dataSources = snapshot.dataSources ?? null;
4183
+ users = snapshot.users ?? null;
4184
+ brands = snapshot.brands ?? null;
4185
+ preferences = snapshot.preferences ?? null;
4186
+ for (const [id, entry] of snapshot.appConfigs ?? []) appConfigs.set(id, entry);
4187
+ for (const [id, entry] of snapshot.userAppConfigs ?? []) userAppConfigs.set(id, entry);
4188
+ }
4189
+ hydrate();
4190
+ function isFresh(entry) {
4191
+ if (!entry) return false;
4192
+ if (!Number.isFinite(ttlMs)) return true;
4193
+ return Date.now() - entry.fetchedAt < ttlMs;
4194
+ }
4195
+ async function listApps() {
4196
+ if (isFresh(apps)) return apps.data;
4197
+ if (appsInFlight) return appsInFlight;
4198
+ appsInFlight = (async () => {
4199
+ try {
4200
+ const data = unwrapEnvelope(await client.get("/v1/apps"));
4201
+ apps = { data, fetchedAt: Date.now() };
4202
+ persist();
4203
+ return data;
4204
+ } finally {
4205
+ appsInFlight = null;
4206
+ }
4207
+ })();
4208
+ return appsInFlight;
4209
+ }
4210
+ async function listDataSources() {
4211
+ if (isFresh(dataSources)) return dataSources.data;
4212
+ if (dataSourcesInFlight) return dataSourcesInFlight;
4213
+ dataSourcesInFlight = (async () => {
4214
+ try {
4215
+ const queryParams = dataSourcesExpand ? { expand: dataSourcesExpand } : void 0;
4216
+ const raw = unwrapEnvelope(
4217
+ await client.get("/v1/apps/data-sources", queryParams)
4218
+ );
4219
+ const data = raw.map(normalizeDataSource);
4220
+ dataSources = { data, fetchedAt: Date.now() };
4221
+ persist();
4222
+ return data;
4223
+ } finally {
4224
+ dataSourcesInFlight = null;
4225
+ }
4226
+ })();
4227
+ return dataSourcesInFlight;
4228
+ }
4229
+ async function listUsers() {
4230
+ if (isFresh(users)) return users.data;
4231
+ if (usersInFlight) return usersInFlight;
4232
+ usersInFlight = (async () => {
4233
+ try {
4234
+ const data = unwrapEnvelope(await client.get("/v1/users"));
4235
+ users = { data, fetchedAt: Date.now() };
4236
+ persist();
4237
+ return data;
4238
+ } finally {
4239
+ usersInFlight = null;
4240
+ }
4241
+ })();
4242
+ return usersInFlight;
4243
+ }
4244
+ async function listBrands() {
4245
+ if (isFresh(brands)) return brands.data;
4246
+ if (brandsInFlight) return brandsInFlight;
4247
+ brandsInFlight = (async () => {
4248
+ try {
4249
+ const data = unwrapEnvelope(await client.get("/v1/tenant/brands"));
4250
+ brands = { data, fetchedAt: Date.now() };
4251
+ persist();
4252
+ return data;
4253
+ } finally {
4254
+ brandsInFlight = null;
4255
+ }
4256
+ })();
4257
+ return brandsInFlight;
4258
+ }
4259
+ async function getPreferences() {
4260
+ if (isFresh(preferences)) return preferences.data;
4261
+ if (preferencesInFlight) return preferencesInFlight;
4262
+ preferencesInFlight = (async () => {
4263
+ try {
4264
+ const data = unwrapEnvelope(await client.get("/v1/tenant/preferences"));
4265
+ preferences = { data, fetchedAt: Date.now() };
4266
+ persist();
4267
+ return data;
4268
+ } finally {
4269
+ preferencesInFlight = null;
4270
+ }
4271
+ })();
4272
+ return preferencesInFlight;
4273
+ }
4274
+ async function getAppConfig(appId) {
4275
+ return getConfig(appId, appConfigs, appConfigsInFlight, `/v1/tenant/apps/${appId}/config`);
4276
+ }
4277
+ async function getUserAppConfig(appId) {
4278
+ return getConfig(appId, userAppConfigs, userAppConfigsInFlight, `/v1/tenant/apps/${appId}/user-config`);
4279
+ }
4280
+ function getConfig(appId, cache, inFlight, path) {
4281
+ const cached = cache.get(appId);
4282
+ if (isFresh(cached)) return Promise.resolve(cached.data);
4283
+ const existing = inFlight.get(appId);
4284
+ if (existing) return existing;
4285
+ const promise = (async () => {
4286
+ try {
4287
+ const data = unwrapEnvelope(await client.get(path));
4288
+ cache.set(appId, { data, fetchedAt: Date.now() });
4289
+ persist();
4290
+ return data;
4291
+ } catch (error) {
4292
+ if (isNotFound(error)) {
4293
+ cache.set(appId, { data: null, fetchedAt: Date.now() });
4294
+ persist();
4295
+ return null;
4296
+ }
4297
+ throw error;
4298
+ } finally {
4299
+ inFlight.delete(appId);
4300
+ }
4301
+ })();
4302
+ inFlight.set(appId, promise);
4303
+ return promise;
4304
+ }
4305
+ async function listDataViews(params) {
4306
+ const sources = await listDataSources();
4307
+ const appIds = toIdSet(params?.appId);
4308
+ const dataSourceIds = toIdSet(params?.dataSourceId);
4309
+ const out = [];
4310
+ for (const dataSource of sources) {
4311
+ if (appIds && (dataSource.tenant_app_id == null || !appIds.has(dataSource.tenant_app_id))) continue;
4312
+ if (dataSourceIds && !dataSourceIds.has(dataSource.id)) continue;
4313
+ if (!dataSource.views) continue;
4314
+ for (const view of dataSource.views) {
4315
+ out.push(view);
4316
+ }
4317
+ }
4318
+ return out;
4319
+ }
4320
+ async function listDataForms(params) {
4321
+ const sources = await listDataSources();
4322
+ const appIds = toIdSet(params?.appId);
4323
+ const dataSourceIds = toIdSet(params?.dataSourceId);
4324
+ const out = [];
4325
+ for (const dataSource of sources) {
4326
+ if (appIds && (dataSource.tenant_app_id == null || !appIds.has(dataSource.tenant_app_id))) continue;
4327
+ if (dataSourceIds && !dataSourceIds.has(dataSource.id)) continue;
4328
+ if (!dataSource.forms) continue;
4329
+ for (const form of dataSource.forms) {
4330
+ out.push(form);
4331
+ }
4332
+ }
4333
+ return out;
4334
+ }
4335
+ function mutateCachedDataSources(mutator) {
4336
+ if (!dataSources) return;
4337
+ const next = mutator(dataSources.data);
4338
+ if (next) {
4339
+ dataSources = { data: next, fetchedAt: dataSources.fetchedAt };
4340
+ persist();
4341
+ }
4342
+ }
4343
+ function upsertDataView(view) {
4344
+ mutateCachedDataSources((sources) => {
4345
+ const index2 = sources.findIndex((ds) => ds.id === view.tenant_data_source_id);
4346
+ if (index2 === -1) return;
4347
+ const dataSource = sources[index2];
4348
+ const normalized = normalizeEmbeddedView(view);
4349
+ const existingViews = dataSource.views ?? [];
4350
+ const viewIndex = existingViews.findIndex((v) => v.id === view.id);
4351
+ const views = viewIndex === -1 ? [...existingViews, normalized] : existingViews.map((v, i) => i === viewIndex ? normalized : v);
4352
+ const next = [...sources];
4353
+ next[index2] = { ...dataSource, views };
4354
+ return next;
4355
+ });
4356
+ }
4357
+ function removeDataView(viewId) {
4358
+ mutateCachedDataSources((sources) => {
4359
+ let touched = false;
4360
+ const next = sources.map((dataSource) => {
4361
+ if (!dataSource.views?.some((v) => v.id === viewId)) return dataSource;
4362
+ touched = true;
4363
+ return { ...dataSource, views: dataSource.views.filter((v) => v.id !== viewId) };
4364
+ });
4365
+ return touched ? next : void 0;
4366
+ });
4367
+ }
4368
+ function upsertDataForm(form) {
4369
+ mutateCachedDataSources((sources) => {
4370
+ const index2 = sources.findIndex((ds) => ds.id === form.tenant_data_source_id);
4371
+ if (index2 === -1) return;
4372
+ const dataSource = sources[index2];
4373
+ const normalized = normalizeEmbeddedForm(form, dataSource.id);
4374
+ const existingForms = dataSource.forms ?? [];
4375
+ const formIndex = existingForms.findIndex((f) => f.id === form.id);
4376
+ const forms = formIndex === -1 ? [...existingForms, normalized] : existingForms.map((f, i) => i === formIndex ? normalized : f);
4377
+ const next = [...sources];
4378
+ next[index2] = { ...dataSource, forms };
4379
+ return next;
4380
+ });
4381
+ }
4382
+ function removeDataForm(formId) {
4383
+ mutateCachedDataSources((sources) => {
4384
+ let touched = false;
4385
+ const next = sources.map((dataSource) => {
4386
+ if (!dataSource.forms?.some((f) => f.id === formId)) return dataSource;
4387
+ touched = true;
4388
+ return { ...dataSource, forms: dataSource.forms.filter((f) => f.id !== formId) };
4389
+ });
4390
+ return touched ? next : void 0;
4391
+ });
4392
+ }
4393
+ function invalidateApps() {
4394
+ apps = null;
4395
+ persist();
4396
+ }
4397
+ function invalidateDataSources() {
4398
+ dataSources = null;
4399
+ persist();
4400
+ }
4401
+ function invalidateUsers() {
4402
+ users = null;
4403
+ persist();
4404
+ }
4405
+ function invalidateBrands() {
4406
+ brands = null;
4407
+ persist();
4408
+ }
4409
+ function invalidatePreferences() {
4410
+ preferences = null;
4411
+ persist();
4412
+ }
4413
+ function invalidateAppConfig(appId) {
4414
+ if (appId === void 0) appConfigs.clear();
4415
+ else appConfigs.delete(appId);
4416
+ persist();
4417
+ }
4418
+ function invalidateUserAppConfig(appId) {
4419
+ if (appId === void 0) userAppConfigs.clear();
4420
+ else userAppConfigs.delete(appId);
4421
+ persist();
4422
+ }
4423
+ function upsertBrand(brand) {
4424
+ if (!brands) return;
4425
+ const index2 = brands.data.findIndex((b) => b.id === brand.id);
4426
+ const data = index2 === -1 ? [...brands.data, brand] : brands.data.map((b, i) => i === index2 ? brand : b);
4427
+ brands = { data, fetchedAt: brands.fetchedAt };
4428
+ persist();
4429
+ }
4430
+ function removeBrand(brandId) {
4431
+ if (!brands?.data.some((b) => b.id === brandId)) return;
4432
+ brands = { data: brands.data.filter((b) => b.id !== brandId), fetchedAt: brands.fetchedAt };
4433
+ persist();
4434
+ }
4435
+ function setAppConfig(appId, config) {
4436
+ appConfigs.set(appId, { data: config, fetchedAt: Date.now() });
4437
+ persist();
4438
+ }
4439
+ function setUserAppConfig(appId, config) {
4440
+ userAppConfigs.set(appId, { data: config, fetchedAt: Date.now() });
4441
+ persist();
4442
+ }
4443
+ async function refresh() {
4444
+ invalidateApps();
4445
+ invalidateDataSources();
4446
+ invalidateUsers();
4447
+ invalidateBrands();
4448
+ invalidatePreferences();
4449
+ invalidateAppConfig();
4450
+ invalidateUserAppConfig();
4451
+ await Promise.all([listApps(), listDataSources()]);
4452
+ }
4453
+ const singletonLoaders = {
4454
+ apps: { message: "Loading apps\u2026", run: listApps },
4455
+ "data-sources": { message: "Loading data sources\u2026", run: listDataSources },
4456
+ users: { message: "Loading users\u2026", run: listUsers },
4457
+ brands: { message: "Loading brands\u2026", run: listBrands },
4458
+ preferences: { message: "Loading preferences\u2026", run: getPreferences }
4459
+ };
4460
+ function mapToRecord(map) {
4461
+ const out = {};
4462
+ for (const [key, entry] of map) out[key] = entry.data;
4463
+ return out;
4464
+ }
4465
+ function buildLoadResult() {
4466
+ return {
4467
+ apps: apps?.data ?? [],
4468
+ dataSources: dataSources?.data ?? [],
4469
+ users: users?.data ?? [],
4470
+ brands: brands?.data ?? [],
4471
+ preferences: preferences?.data ?? {},
4472
+ appConfigs: mapToRecord(appConfigs),
4473
+ userAppConfigs: mapToRecord(userAppConfigs)
4474
+ };
4475
+ }
4476
+ async function load(loadOptions) {
4477
+ const onProgress = loadOptions?.onProgress;
4478
+ const force = loadOptions?.force ?? true;
4479
+ const include = loadOptions?.include ?? DEFAULT_LOAD_STEPS;
4480
+ const envAppId = readAppIdFromEnv();
4481
+ const configAppIds = loadOptions?.configAppIds ?? (envAppId ? [envAppId] : []);
4482
+ const steps = [];
4483
+ for (const id of include) {
4484
+ if (id === "app-config" || id === "user-app-config") continue;
4485
+ steps.push({ id, message: singletonLoaders[id].message, run: singletonLoaders[id].run });
4486
+ }
4487
+ for (const appId of configAppIds) {
4488
+ steps.push({
4489
+ id: "app-config",
4490
+ appId,
4491
+ message: "Loading app config\u2026",
4492
+ run: () => getAppConfig(appId)
4493
+ });
4494
+ steps.push({
4495
+ id: "user-app-config",
4496
+ appId,
4497
+ message: "Loading user app config\u2026",
4498
+ run: () => getUserAppConfig(appId)
4499
+ });
4500
+ }
4501
+ if (force) {
4502
+ if (include.includes("apps")) invalidateApps();
4503
+ if (include.includes("data-sources")) invalidateDataSources();
4504
+ if (include.includes("users")) invalidateUsers();
4505
+ if (include.includes("brands")) invalidateBrands();
4506
+ if (include.includes("preferences")) invalidatePreferences();
4507
+ for (const appId of configAppIds) {
4508
+ invalidateAppConfig(appId);
4509
+ invalidateUserAppConfig(appId);
4510
+ }
4511
+ }
4512
+ const total = steps.length;
4513
+ for (let index2 = 0; index2 < total; index2++) {
4514
+ const step = steps[index2];
4515
+ const current = index2 + 1;
4516
+ onProgress?.({
4517
+ step: step.id,
4518
+ appId: step.appId,
4519
+ message: step.message,
4520
+ current,
4521
+ total,
4522
+ ratio: index2 / total,
4523
+ phase: "start"
4524
+ });
4525
+ try {
4526
+ await step.run();
4527
+ } catch (error) {
4528
+ onProgress?.({
4529
+ step: step.id,
4530
+ appId: step.appId,
4531
+ message: step.message,
4532
+ current,
4533
+ total,
4534
+ ratio: index2 / total,
4535
+ phase: "error",
4536
+ error
4537
+ });
4538
+ throw error;
4539
+ }
4540
+ onProgress?.({
4541
+ step: step.id,
4542
+ appId: step.appId,
4543
+ message: step.message,
4544
+ current,
4545
+ total,
4546
+ ratio: current / total,
4547
+ phase: "success"
4548
+ });
4549
+ }
4550
+ onProgress?.({
4551
+ step: null,
4552
+ message: "Ready",
4553
+ current: total,
4554
+ total,
4555
+ ratio: 1,
4556
+ phase: "complete"
4557
+ });
4558
+ return buildLoadResult();
4559
+ }
4560
+ return {
4561
+ listApps,
4562
+ listDataSources,
4563
+ listUsers,
4564
+ listBrands,
4565
+ getPreferences,
4566
+ getAppConfig,
4567
+ getUserAppConfig,
4568
+ load,
4569
+ listDataViews,
4570
+ listDataForms,
4571
+ refresh,
4572
+ invalidateApps,
4573
+ invalidateDataSources,
4574
+ invalidateUsers,
4575
+ invalidateBrands,
4576
+ invalidatePreferences,
4577
+ invalidateAppConfig,
4578
+ invalidateUserAppConfig,
4579
+ upsertDataView,
4580
+ removeDataView,
4581
+ upsertDataForm,
4582
+ removeDataForm,
4583
+ upsertBrand,
4584
+ removeBrand,
4585
+ setAppConfig,
4586
+ setUserAppConfig
4587
+ };
4588
+ }
4589
+
4590
+ // src/brand-client.ts
4591
+ function createBrandClient(client, options) {
4592
+ const basePath = "/v1/tenant/brands";
4593
+ const inventory = options?.inventory;
4594
+ async function list() {
4595
+ if (inventory) return inventory.listBrands();
4596
+ return unwrapEnvelope(await client.get(basePath));
4597
+ }
4598
+ async function get(brandId) {
4599
+ if (inventory) {
4600
+ const match = (await inventory.listBrands()).find((brand) => brand.id === brandId);
4601
+ if (match) return match;
4602
+ }
4603
+ return unwrapEnvelope(await client.get(`${basePath}/${brandId}`));
4604
+ }
4605
+ async function create(body) {
4606
+ const result = unwrapEnvelope(await client.post(basePath, body));
4607
+ inventory?.upsertBrand(result);
4608
+ return result;
4609
+ }
4610
+ async function update(brandId, body) {
4611
+ const result = unwrapEnvelope(await client.patch(`${basePath}/${brandId}`, body));
4612
+ if (body.archived === true) {
4613
+ inventory?.removeBrand(brandId);
4614
+ } else {
4615
+ inventory?.upsertBrand(result);
4616
+ }
4617
+ return result;
4618
+ }
4619
+ async function remove(brandId) {
4620
+ await client.delete(`${basePath}/${brandId}`);
4621
+ inventory?.removeBrand(brandId);
4622
+ }
4623
+ async function fetchFromWebsite(brandId) {
4624
+ const result = await client.put(
4625
+ `${basePath}/${brandId}/fetchFromWebsite`
4626
+ );
4627
+ if (inventory && result?.brand) {
4628
+ const existing = (await inventory.listBrands()).find((brand) => brand.id === brandId);
4629
+ if (existing) inventory.upsertBrand({ ...existing, ...result.brand });
4630
+ }
4631
+ return result;
4632
+ }
4633
+ return {
4634
+ list,
4635
+ get,
4636
+ create,
4637
+ update,
4638
+ remove,
4639
+ fetchFromWebsite
4640
+ };
4641
+ }
4642
+
4643
+ // src/user-identity-client.ts
4644
+ function createUserIdentityClient(client) {
4645
+ const basePath = "/v1/users/me/identity";
4646
+ async function saveMicrosoft(payload) {
4647
+ await client.put(`${basePath}/microsoft`, payload);
4648
+ }
4649
+ async function saveGoogle(payload) {
4650
+ await client.put(`${basePath}/google`, payload);
4651
+ }
4652
+ return { saveMicrosoft, saveGoogle };
4653
+ }
4654
+
4655
+ // src/envelope-interceptor.ts
4656
+ var STRIPPABLE_ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "success"]);
4657
+ function looksLikeEnvelope(value) {
4658
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
4659
+ return false;
4660
+ }
4661
+ const keys = Object.keys(value);
4662
+ return "data" in value && keys.every((key) => STRIPPABLE_ENVELOPE_KEYS.has(key));
4663
+ }
4664
+ var envelopeUnwrapInterceptor = {
4665
+ response: (response) => {
4666
+ if (looksLikeEnvelope(response.data)) {
4667
+ return {
4668
+ ...response,
4669
+ data: response.data.data
4670
+ };
4671
+ }
4672
+ return response;
4673
+ }
4674
+ };
4675
+ /*! Bundled license information:
4676
+
4677
+ php-date-formatter/js/php-date-formatter.js:
4678
+ (*!
4679
+ * @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2025
4680
+ * @version 1.3.6
4681
+ *
4682
+ * Date formatter utility library that allows formatting date/time variables or Date objects using PHP DateTime format.
4683
+ * This library is a standalone javascript library and does not depend on other libraries or plugins like jQuery. The
4684
+ * library also adds support for Universal Module Definition (UMD).
4685
+ *
4686
+ * @see http://php.net/manual/en/function.date.php
4687
+ *
4688
+ * For more JQuery plugins visit http://plugins.krajee.com
4689
+ * For more Yii related demos visit http://demos.krajee.com
4690
+ *)
4691
+ */
4692
+
4693
+ export { createAppConfigClient, createBrandClient, createDataFormClient, createDataSourceClient, createDataViewClient, createDateUtils, createInventoryClient, createNumberUtils, createTemplateEngine, createUserAppConfigClient, createUserIdentityClient, envelopeUnwrapInterceptor, formatDurationAsHours, formatDurationAsTime, formatDurationAsWords, formatNumberToWords, getTenantPreferenceSummary, getTenantPreferences, jsonataHelpers, unwrapEnvelope };
4694
+ //# sourceMappingURL=index.native.js.map
4695
+ //# sourceMappingURL=index.native.js.map