@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,305 @@
1
+ import {
2
+ type CurrencyCode,
3
+ type NumberFormatOptions,
4
+ type NumberToWordsOptions,
5
+ type NumberUtils,
6
+ type NumberUtilsConfig,
7
+ type NumberWordLang
8
+ } from './types';
9
+
10
+ // --- createNumberUtils factory ---
11
+
12
+ export function createNumberUtils(config: NumberUtilsConfig): NumberUtils {
13
+ const { preferences } = config;
14
+
15
+ function formatNumber(value: number, options?: NumberFormatOptions): string | null {
16
+ if (value == null) return null;
17
+
18
+ const precision = options?.decimalPrecision ?? preferences.decimal_precision ?? 2;
19
+ const thousandSep = options?.thousandSeparator !== undefined ? options.thousandSeparator : preferences.thousand_separator;
20
+ const decimalSep = options?.decimalSeparator || preferences.decimal_separator;
21
+
22
+ if (thousandSep && decimalSep) {
23
+ const formatted = parseFloat(String(value)).toFixed(precision);
24
+ const parts = formatted.split('.');
25
+
26
+ parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSep);
27
+
28
+ return parts.join(decimalSep);
29
+ }
30
+
31
+ const resolvedLocale = preferences.locale?.replace('_', '-') || 'en-US';
32
+
33
+ return value.toLocaleString(resolvedLocale, {
34
+ minimumFractionDigits: precision,
35
+ maximumFractionDigits: precision,
36
+ useGrouping: !!thousandSep
37
+ });
38
+ }
39
+
40
+ return { formatNumber };
41
+ }
42
+
43
+ // --- Number to words ---
44
+
45
+ const THOUSAND_SEP = '.';
46
+ const DECIMAL_SEP = ',';
47
+
48
+ function phpNumberFormat(value: number, decimals = 2): string {
49
+ const num = Number(value);
50
+
51
+ if (isNaN(num)) return `0${DECIMAL_SEP}${'0'.repeat(decimals)}`;
52
+
53
+ const [intPart, decPart] = num.toFixed(decimals).split('.');
54
+
55
+ return `${intPart.replace(/\B(?=(\d{3})+(?!\d))/g, THOUSAND_SEP)}${DECIMAL_SEP}${decPart}`;
56
+ }
57
+
58
+ // Turkish
59
+
60
+ const DIGITS_1_TR = [
61
+ '',
62
+ 'BİR',
63
+ 'İKİ',
64
+ 'ÜÇ',
65
+ 'DÖRT',
66
+ 'BEŞ',
67
+ 'ALTI',
68
+ 'YEDİ',
69
+ 'SEKİZ',
70
+ 'DOKUZ'
71
+ ];
72
+ const DIGITS_10_TR = [
73
+ '',
74
+ 'ON',
75
+ 'YİRMİ',
76
+ 'OTUZ',
77
+ 'KIRK',
78
+ 'ELLİ',
79
+ 'ALTMIŞ',
80
+ 'YETMİŞ',
81
+ 'SEKSEN',
82
+ 'DOKSAN'
83
+ ];
84
+ const DIGITS_100_TR = [
85
+ '',
86
+ 'YÜZ',
87
+ 'İKİYÜZ',
88
+ 'ÜÇYÜZ',
89
+ 'DÖRTYÜZ',
90
+ 'BEŞYÜZ',
91
+ 'ALTIYÜZ',
92
+ 'YEDİYÜZ',
93
+ 'SEKİZYÜZ',
94
+ 'DOKUZYÜZ'
95
+ ];
96
+ const SCALE_TR = [
97
+ '',
98
+ '',
99
+ 'BİN',
100
+ 'MİLYON',
101
+ 'MİLYAR',
102
+ 'TRİLYON',
103
+ 'KATİRİLYON',
104
+ 'KENTİLYON',
105
+ 'SEKSİLYON',
106
+ 'SEPTİLYON',
107
+ 'OKTİLYON'
108
+ ];
109
+
110
+ function toWordTR(value: number, useSpaces: boolean): [string, string] {
111
+ const formatted = phpNumberFormat(value);
112
+ const [intPart, decPart] = formatted.split(DECIMAL_SEP);
113
+ const groups = intPart.split(THOUSAND_SEP).reverse();
114
+ let integerStr = '';
115
+
116
+ groups.forEach((group, idx) => {
117
+ const padded = group.padStart(3, '0');
118
+ const d1 = parseInt(padded[0], 10);
119
+ const d2 = parseInt(padded[1], 10);
120
+ const d3 = parseInt(padded[2], 10);
121
+ const groupIndex = groups.length - idx;
122
+
123
+ if (groupIndex === groups.length && d1 === 0 && d2 === 0 && d3 === 1 && groups.length > 1) {
124
+ integerStr += ' ';
125
+ } else {
126
+ integerStr += ` ${DIGITS_100_TR[d1]} ${DIGITS_10_TR[d2]} ${DIGITS_1_TR[d3]} `;
127
+ }
128
+
129
+ integerStr += SCALE_TR[groupIndex] || '';
130
+ });
131
+
132
+ const paddedDec = decPart.padEnd(2, '0');
133
+ const decStr = `${DIGITS_10_TR[parseInt(paddedDec[0], 10)]} ${DIGITS_1_TR[parseInt(paddedDec[1], 10)]}`;
134
+
135
+ if (!useSpaces) {
136
+ integerStr = integerStr.replace(/ /g, '');
137
+ }
138
+
139
+ return [integerStr.replace(/ {2,}/g, ' ').trim(), decStr.replace(/ {2,}/g, ' ').trim()];
140
+ }
141
+
142
+ // English
143
+
144
+ const DIGITS_1_EN = [
145
+ '',
146
+ 'ONE',
147
+ 'TWO',
148
+ 'THREE',
149
+ 'FOUR',
150
+ 'FIVE',
151
+ 'SIX',
152
+ 'SEVEN',
153
+ 'EIGHT',
154
+ 'NINE'
155
+ ];
156
+ const DIGITS_TEEN_EN = [
157
+ '',
158
+ 'ELEVEN',
159
+ 'TWELVE',
160
+ 'THIRTEEN',
161
+ 'FOURTEEN',
162
+ 'FIFTEEN',
163
+ 'SIXTEEN',
164
+ 'SEVENTEEN',
165
+ 'EIGHTEEN',
166
+ 'NINETEEN'
167
+ ];
168
+ const DIGITS_10_EN = [
169
+ '',
170
+ 'TEN',
171
+ 'TWENTY',
172
+ 'THIRTY',
173
+ 'FORTY',
174
+ 'FIFTY',
175
+ 'SIXTY',
176
+ 'SEVENTY',
177
+ 'EIGHTY',
178
+ 'NINETY'
179
+ ];
180
+ const DIGITS_100_EN = [
181
+ '',
182
+ 'HUNDRED',
183
+ 'TWO HUNDRED',
184
+ 'THREE HUNDRED',
185
+ 'FOUR HUNDRED',
186
+ 'FIVE HUNDRED',
187
+ 'SIX HUNDRED',
188
+ 'SEVEN HUNDRED',
189
+ 'EIGHT HUNDRED',
190
+ 'NINE HUNDRED'
191
+ ];
192
+ const SCALE_EN = [
193
+ '',
194
+ '',
195
+ 'THOUSAND',
196
+ 'MILLION',
197
+ 'BILLION',
198
+ 'TRILLION',
199
+ 'QUADRILLION',
200
+ 'QUINTILLION',
201
+ 'SEXTILLION',
202
+ 'SEPTILLION',
203
+ 'OCTILLION'
204
+ ];
205
+
206
+ function toWordEN(value: number, useSpaces: boolean): [string, string] {
207
+ const formatted = phpNumberFormat(value);
208
+ const [intPart, decPart] = formatted.split(DECIMAL_SEP);
209
+ const groups = intPart.split(THOUSAND_SEP).reverse();
210
+ let integerStr = '';
211
+
212
+ groups.forEach((group, idx) => {
213
+ const padded = group.padStart(3, '0');
214
+ const d1 = parseInt(padded[0], 10);
215
+ const d2 = parseInt(padded[1], 10);
216
+ const d3 = parseInt(padded[2], 10);
217
+ const groupIndex = groups.length - idx;
218
+
219
+ if (groupIndex === groups.length && d1 === 0 && d2 === 0 && d3 === 1 && groups.length > 1) {
220
+ integerStr += ' ';
221
+ } else if (d2 === 1 && d3 >= 1) {
222
+ integerStr += ` ${DIGITS_100_EN[d1]} ${DIGITS_TEEN_EN[d3]} `;
223
+ } else {
224
+ integerStr += ` ${DIGITS_100_EN[d1]} ${DIGITS_10_EN[d2]} ${DIGITS_1_EN[d3]} `;
225
+ }
226
+
227
+ integerStr += SCALE_EN[groupIndex] || '';
228
+ });
229
+
230
+ const paddedDec = decPart.padEnd(2, '0');
231
+ const dec1 = parseInt(paddedDec[0], 10);
232
+ const dec2 = parseInt(paddedDec[1], 10);
233
+ const decStr = dec1 === 1 && dec2 >= 1 ? DIGITS_TEEN_EN[dec2] : `${DIGITS_10_EN[dec1]} ${DIGITS_1_EN[dec2]}`;
234
+
235
+ if (!useSpaces) {
236
+ integerStr = integerStr.replace(/ /g, '');
237
+ }
238
+
239
+ return [integerStr.replace(/ {2,}/g, ' ').trim(), decStr.replace(/ {2,}/g, ' ').trim()];
240
+ }
241
+
242
+ // Converter map
243
+
244
+ const WORD_CONVERTERS: Record<NumberWordLang, (value: number, useSpaces: boolean) => [string, string]> = {
245
+ TR: toWordTR,
246
+ EN: toWordEN
247
+ };
248
+
249
+ const CURRENCY_LABELS: Record<CurrencyCode, { unit: string; subunit: string }> = {
250
+ TRY: { unit: 'TÜRK LİRASI', subunit: 'KURUŞ' },
251
+ EUR: { unit: 'EURO', subunit: 'CENT' },
252
+ USD: { unit: 'DOLAR', subunit: 'CENT' },
253
+ GBP: { unit: 'STERLİN', subunit: 'PENNY' },
254
+ JPY: { unit: 'YEN', subunit: 'SEN' }
255
+ };
256
+
257
+ export function formatNumberToWords(value: number, options?: NumberToWordsOptions): string {
258
+ const lang = options?.lang ?? 'TR';
259
+ const currency = options?.currency ?? 'TRY';
260
+ const useSpaces = options?.useSpaces ?? false;
261
+
262
+ const num = value ?? 0;
263
+ const [intWords, decWords] = WORD_CONVERTERS[lang](num, useSpaces);
264
+ const labels = CURRENCY_LABELS[currency] ?? CURRENCY_LABELS.TRY;
265
+ let result = '';
266
+
267
+ if (intWords) {
268
+ result += `${intWords} ${labels.unit}`;
269
+ }
270
+ if (decWords) {
271
+ result += ` ${decWords} ${labels.subunit}`;
272
+ }
273
+
274
+ return result.trim();
275
+ }
276
+
277
+ // --- Duration formatters ---
278
+
279
+ export function formatDurationAsTime(seconds: number): string {
280
+ const hours = Math.floor(seconds / 3600);
281
+ const minutes = Math.floor((seconds % 3600) / 60);
282
+
283
+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
284
+ }
285
+
286
+ export function formatDurationAsHours(seconds: number, decimalPrecision = 2): string {
287
+ if (!seconds) return '0';
288
+
289
+ return (seconds / 3600).toFixed(decimalPrecision);
290
+ }
291
+
292
+ export function formatDurationAsWords(seconds: number): string {
293
+ const hours = Math.floor(seconds / 3600);
294
+ const minutes = Math.floor((seconds % 3600) / 60);
295
+ let result = '';
296
+
297
+ if (hours > 0) {
298
+ result += `${hours} hr${hours !== 1 ? 's' : ''} `;
299
+ }
300
+ if (minutes > 0) {
301
+ result += `${minutes} min${minutes !== 1 ? 's' : ''}`;
302
+ }
303
+
304
+ return result.trim() || '0 mins';
305
+ }
@@ -0,0 +1,8 @@
1
+ declare module 'php-date-formatter' {
2
+ export default class DateFormatter {
3
+ constructor(options?: Record<string, unknown>);
4
+ formatDate(date: Date, format: string): string;
5
+ parseDate(date: string, format: string): Date | null;
6
+ guessDate(dateStr: string, format: string): Date | null;
7
+ }
8
+ }
package/src/query.ts ADDED
@@ -0,0 +1,5 @@
1
+ export {
2
+ createDataSourceQueries,
3
+ dataSourceKeys,
4
+ type DataSourceQueries
5
+ } from './data-source-queries';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Minimal `stream` stand-in for the bundled `handlebars-async-helpers` (web
3
+ * and React Native builds).
4
+ *
5
+ * The library only uses `Readable` for an `instanceof` check in its `#each`
6
+ * helper, which app-utils replaces anyway (see `async-each-helper.ts`); an
7
+ * empty class keeps the import resolvable without Node.
8
+ */
9
+ export class Readable {}
10
+
11
+ export default { Readable };
@@ -0,0 +1,47 @@
1
+ import {
2
+ afterEach, describe, expect, it
3
+ } from 'vitest';
4
+
5
+ import { createTemplateEngine } from './template-engine';
6
+
7
+ const render = (template: string, data: Record<string, unknown>) => createTemplateEngine().compileTpl(template)(data);
8
+
9
+ describe('template engine #each', () => {
10
+ const globalDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'global');
11
+
12
+ afterEach(() => {
13
+ if (globalDescriptor) {
14
+ Object.defineProperty(globalThis, 'global', globalDescriptor);
15
+ }
16
+ });
17
+
18
+ it('iterates arrays with @index, @first and @last', async () => {
19
+ await expect(render('{{#each a}}{{@index}}:{{this}}:{{@first}}:{{@last}},{{/each}}', { a: ['x', 'y'] }))
20
+ .resolves.toBe('0:x:true:false,1:y:false:true,');
21
+ });
22
+
23
+ it('iterates plain objects with @key', async () => {
24
+ await expect(render('{{#each o}}{{@key}}={{this}};{{/each}}', { o: { x: 1, y: 2 } })).resolves.toBe('x=1;y=2;');
25
+ });
26
+
27
+ it('iterates other iterables such as Map entries', async () => {
28
+ await expect(render('{{#each m}}{{this.[0]}}={{this.[1]}};{{/each}}', { m: new Map([['k', 'v']]) })).resolves.toBe('k=v;');
29
+ });
30
+
31
+ it('renders the {{else}} block for an empty array or object', async () => {
32
+ await expect(render('{{#each a}}x{{else}}none{{/each}}', { a: [] })).resolves.toBe('none');
33
+ await expect(render('{{#each o}}x{{else}}none{{/each}}', { o: {} })).resolves.toBe('none');
34
+ await expect(render('{{#each missing}}x{{else}}none{{/each}}', {})).resolves.toBe('none');
35
+ });
36
+
37
+ it('resolves a promised list before iterating', async () => {
38
+ await expect(render('{{#each p}}{{this}}{{/each}}', { p: Promise.resolve([1, 2]) })).resolves.toBe('12');
39
+ });
40
+
41
+ it('works without the Node `global` (browsers)', async () => {
42
+ // Browsers have no `global`; the upstream helper referenced it for every non-array object.
43
+ Reflect.deleteProperty(globalThis, 'global');
44
+
45
+ await expect(render('{{#each o}}{{@key}}={{this}};{{/each}}', { o: { x: 1 } })).resolves.toBe('x=1;');
46
+ });
47
+ });
@@ -0,0 +1,298 @@
1
+ import Handlebars from 'handlebars';
2
+ import asyncHelpers from 'handlebars-async-helpers';
3
+
4
+ import jsonata from 'jsonata';
5
+ import { JSONPath } from 'jsonpath-plus';
6
+
7
+ import { createAsyncEachHelper } from './async-each-helper';
8
+
9
+ import { jsonataHelpers } from './jsonata-helpers';
10
+ import {
11
+ formatDurationAsHours, formatDurationAsTime, formatDurationAsWords, formatNumberToWords
12
+ } from './number-utils';
13
+ import {
14
+ type DateUtils, type NumberUtils, type TemplateEngine, type TemplateEngineConfig
15
+ } from './types';
16
+
17
+ /*
18
+ * ---------------------------------------------------------------------------
19
+ * HTML entity decode + strip tags
20
+ * ---------------------------------------------------------------------------
21
+ */
22
+
23
+ const HTML_ENTITIES: Record<string, string> = {
24
+ amp: '&',
25
+ lt: '<',
26
+ gt: '>',
27
+ quot: '"',
28
+ apos: "'"
29
+ };
30
+
31
+ function decodeHtmlEntities(str: string): string {
32
+ return str.replace(/&(amp|lt|gt|quot|apos);/g, (match, entity: string) => HTML_ENTITIES[entity] ?? match);
33
+ }
34
+
35
+ function removeHtmlTags(str: string | null): string {
36
+ if (str === null || str === '') return '';
37
+
38
+ return String(str).replace(/(<([^>]+)>)/gi, '');
39
+ }
40
+
41
+ /*
42
+ * ---------------------------------------------------------------------------
43
+ * Template preprocessor
44
+ * ---------------------------------------------------------------------------
45
+ */
46
+
47
+ const FORMULA_EXPR_RE = /(\{\{formula\s)(?<formula>[^}]+)(\}\})/g;
48
+ const IF_FORMULA_RE = /(\{\{#if\s)(?<formula>[^}]+)(\}\})/g;
49
+ const INLINE_RE = /\{\{<([^*]+)\}\}/g;
50
+
51
+ function preprocessTemplate(tpl: string): string {
52
+ // Convert {{formula <expr>}} → {{formula '<escaped-expr>'}}
53
+ let result = tpl.replace(FORMULA_EXPR_RE, (_matched, g1: string, g2: string, g3: string) => {
54
+ const escaped = decodeHtmlEntities(g2.replace(/'/g, "\\'"));
55
+
56
+ return `${g1}'${removeHtmlTags(escaped)}'${g3}`;
57
+ });
58
+
59
+ // Convert {{#if <expr>}} → {{#if (formula '<escaped-expr>')}}
60
+ result = result.replace(IF_FORMULA_RE, (_matched, g1: string, g2: string, g3: string) => {
61
+ const escaped = decodeHtmlEntities(g2.replace(/'/g, "\\'"));
62
+
63
+ return `${g1} (formula '${escaped}')${g3}`;
64
+ });
65
+
66
+ // Convert {{<content}} → stripped content (remove HTML tags)
67
+ result = result.replace(INLINE_RE, (_matched, group: string) => {
68
+ return removeHtmlTags(group);
69
+ });
70
+
71
+ return result;
72
+ }
73
+
74
+ /*
75
+ * ---------------------------------------------------------------------------
76
+ * Register Handlebars helpers
77
+ * ---------------------------------------------------------------------------
78
+ */
79
+
80
+ function registerHelpers(
81
+ hb: ReturnType<typeof asyncHelpers>,
82
+ dateUtils: DateUtils | undefined,
83
+ numberUtils: NumberUtils | undefined,
84
+ bindings: Record<string, any>
85
+ ): void {
86
+ // --- repeat ---
87
+ hb.registerHelper('repeat', async (n: number, block: any) => {
88
+ let accum = '';
89
+
90
+ for (let i = 0; i < n; ++i) {
91
+ accum += block.fn(i);
92
+ }
93
+
94
+ return accum;
95
+ });
96
+
97
+ // --- sum ---
98
+ hb.registerHelper('sum', (...args: any[]) => {
99
+ args = args.slice(0, -1); // remove Handlebars options
100
+
101
+ if (args.length >= 2 && Array.isArray(args[0]) && typeof args[1] === 'string') {
102
+ const key = args[1];
103
+
104
+ return Handlebars.escapeExpression(
105
+ String(args[0].reduce((total: number, obj: any) => total + (Number(obj[key]) || 0), 0))
106
+ );
107
+ }
108
+
109
+ const sumValue = (val: any): number => {
110
+ if (Array.isArray(val)) return val.reduce((acc, item) => acc + sumValue(item), 0);
111
+
112
+ return Number(val) || 0;
113
+ };
114
+
115
+ return Handlebars.escapeExpression(
116
+ String(args.reduce((total: number, num: any) => total + sumValue(num), 0))
117
+ );
118
+ });
119
+
120
+ // --- date / number formatting ---
121
+ if (dateUtils) {
122
+ hb.registerHelper('formatDate', (input: any, options: any) => {
123
+ const dateFormat = options.hash.format || undefined;
124
+ const result = Handlebars.escapeExpression(
125
+ dateUtils.formatDate(input, dateFormat ? { format: dateFormat } : undefined) ?? ''
126
+ );
127
+
128
+ return new Handlebars.SafeString(result);
129
+ });
130
+
131
+ hb.registerHelper('formatDateTime', (input: any) => {
132
+ const result = Handlebars.escapeExpression(
133
+ dateUtils.formatDateTime(input) ?? ''
134
+ );
135
+
136
+ return new Handlebars.SafeString(result);
137
+ });
138
+ }
139
+
140
+ if (numberUtils) {
141
+ hb.registerHelper('formatNumber', (input: any, options: any) => {
142
+ const result = Handlebars.escapeExpression(
143
+ numberUtils.formatNumber(input, {
144
+ decimalPrecision: options.hash.decimalPrecision || undefined,
145
+ decimalSeparator: options.hash.decimalSeparator || undefined,
146
+ thousandSeparator: options.hash.thousandSeparator !== undefined ? options.hash.thousandSeparator : undefined
147
+ }) ?? ''
148
+ );
149
+
150
+ return result;
151
+ });
152
+ }
153
+
154
+ hb.registerHelper('formatNumberToWords', (number: any, options: any) => {
155
+ return formatNumberToWords(number, {
156
+ useSpaces: options.hash.useSpaces || false,
157
+ lang: options.hash.lang || 'TR',
158
+ currency: options.hash.currency || 'TRY'
159
+ });
160
+ });
161
+
162
+ hb.registerHelper('formatDurationAsTime', (input: any) => {
163
+ return Handlebars.escapeExpression(formatDurationAsTime(input));
164
+ });
165
+
166
+ hb.registerHelper('formatDurationAsWords', (input: any) => {
167
+ return Handlebars.escapeExpression(formatDurationAsWords(input));
168
+ });
169
+
170
+ hb.registerHelper('formatDurationAsHours', (input: any, options: any) => {
171
+ const decimalPrecision = options.hash.decimalPrecision || 2;
172
+
173
+ return Handlebars.escapeExpression(formatDurationAsHours(input, decimalPrecision));
174
+ });
175
+
176
+ // --- formula (jsonata evaluation inside Handlebars) ---
177
+ hb.registerHelper('formula', async function (this: any, context: any, options: any) {
178
+ let data: any;
179
+ let opts: any;
180
+
181
+ if (!options && context && context.fn) {
182
+ opts = context;
183
+ data = Array.isArray(opts.data.root) ? opts.data.root[opts.data.index] : opts.data.root || {};
184
+ } else {
185
+ opts = options;
186
+ data = opts.data.root;
187
+ }
188
+
189
+ if (opts.fn) {
190
+ const expression = await opts.fn(this);
191
+
192
+ if (!expression) return '';
193
+
194
+ try {
195
+ return await jsonata(expression).evaluate(data || {}, bindings);
196
+ } catch (err) {
197
+ console.warn('Error during jsonata evaluation', { expression, data });
198
+ throw err;
199
+ }
200
+ }
201
+
202
+ if (typeof context === 'string') {
203
+ try {
204
+ return await jsonata(context).evaluate(data || {}, bindings);
205
+ } catch (err) {
206
+ console.warn('Error during jsonata evaluation', { context, data });
207
+ throw err;
208
+ }
209
+ }
210
+
211
+ return '';
212
+ });
213
+
214
+ // --- path (JSONPath) ---
215
+ hb.registerHelper('path', (...args: any[]) => {
216
+ const options = args[args.length - 1];
217
+ const expression = args[0];
218
+ const result = JSONPath({ path: expression, json: options.data.root });
219
+
220
+ if (result == null) return '';
221
+
222
+ const ctx = Array.isArray(result) && result.length === 1 ? result[0] : result;
223
+
224
+ return options.fn(ctx);
225
+ });
226
+
227
+ // --- json ---
228
+ hb.registerHelper('json', (context: any) => {
229
+ return JSON.stringify(context, null, 2);
230
+ });
231
+ }
232
+
233
+ /*
234
+ * ---------------------------------------------------------------------------
235
+ * Factory
236
+ * ---------------------------------------------------------------------------
237
+ */
238
+
239
+ export function createTemplateEngine(config: TemplateEngineConfig = {}): TemplateEngine {
240
+ const {
241
+ dateUtils,
242
+ numberUtils,
243
+ extraJsonataBindings = {},
244
+ additionalHelpers = {},
245
+ user
246
+ } = config;
247
+
248
+ const allBindings = { ...jsonataHelpers, ...extraJsonataBindings };
249
+
250
+ /*
251
+ * `asyncHelpers` calls `.create()` on the passed instance internally, so it
252
+ * already returns an isolated Handlebars copy (the global is never mutated).
253
+ * Passing `Handlebars.create()` here would double-create and throw, because
254
+ * a `.create()`d instance has no `.create()` method of its own.
255
+ */
256
+ const hb = asyncHelpers(Handlebars);
257
+
258
+ // Replaces the library's `#each`, which breaks in browsers and on `{{else}}`.
259
+ hb.registerHelper('each', createAsyncEachHelper(hb));
260
+
261
+ registerHelpers(hb, dateUtils, numberUtils, allBindings);
262
+
263
+ // Consumer-supplied helpers, registered after the built-in set.
264
+ for (const [name, fn] of Object.entries(additionalHelpers)) {
265
+ hb.registerHelper(name, fn);
266
+ }
267
+
268
+ function compileTpl(templateString: string): (data: any) => Promise<string> {
269
+ const preprocessed = preprocessTemplate(templateString);
270
+
271
+ return hb.compile(preprocessed);
272
+ }
273
+
274
+ async function compileFormula(expression: string, data?: any): Promise<any> {
275
+ try {
276
+ const metadata = {
277
+ ...(data?.metadata || {}),
278
+ user: user ?? null
279
+ };
280
+
281
+ return await jsonata(expression).evaluate(
282
+ { ...data, metadata },
283
+ allBindings
284
+ );
285
+ } catch (err) {
286
+ console.warn('Error during jsonata evaluation', { expression, data });
287
+ console.warn(err);
288
+
289
+ return undefined;
290
+ }
291
+ }
292
+
293
+ return {
294
+ compileTpl,
295
+ compileFormula,
296
+ jsonataHelpers: allBindings
297
+ };
298
+ }