@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.
- package/README.md +1515 -1
- package/dist/index.d.ts +82 -0
- package/dist/index.js +2304 -0
- package/dist/index.js.map +1 -0
- package/dist/index.native.js +4695 -0
- package/dist/index.native.js.map +1 -0
- package/dist/query.d.ts +54 -0
- package/dist/query.js +269 -0
- package/dist/query.js.map +1 -0
- package/dist/types-GNkXRpu4.d.ts +754 -0
- package/package.json +57 -3
- package/src/app-config-client.ts +48 -0
- package/src/async-each-helper.ts +98 -0
- package/src/brand-client.ts +80 -0
- package/src/data-form-client.ts +85 -0
- package/src/data-source-client.ts +298 -0
- package/src/data-source-queries.ts +149 -0
- package/src/data-view-client.ts +92 -0
- package/src/date-utils.test.ts +48 -0
- package/src/date-utils.ts +146 -0
- package/src/envelope-interceptor.ts +65 -0
- package/src/get-tenant-preferences.test.ts +42 -0
- package/src/get-tenant-preferences.ts +30 -0
- package/src/handlebars-async-helpers.d.ts +12 -0
- package/src/index.native.ts +9 -0
- package/src/index.ts +88 -0
- package/src/inventory-client.ts +725 -0
- package/src/jsonata-helpers.ts +545 -0
- package/src/number-utils.ts +305 -0
- package/src/php-date-formatter.d.ts +8 -0
- package/src/query.ts +5 -0
- package/src/shims/stream.ts +11 -0
- package/src/template-engine.test.ts +47 -0
- package/src/template-engine.ts +298 -0
- package/src/types.ts +871 -0
- package/src/unwrap-envelope.ts +51 -0
- package/src/user-app-config-client.ts +44 -0
- package/src/user-identity-client.ts +21 -0
- package/tsconfig.json +9 -0
- package/tsup.config.ts +71 -0
- package/vitest.config.mts +13 -0
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { type QueryClient, type QueryKey } from '@tanstack/query-core';
|
|
2
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
3
|
+
|
|
4
|
+
import { createDataSourceClient } from './data-source-client';
|
|
5
|
+
import { type DataSourceListParams } from './types';
|
|
6
|
+
|
|
7
|
+
interface QueryOptionsShape<TData, TKey extends QueryKey> {
|
|
8
|
+
queryKey: TKey;
|
|
9
|
+
queryFn: () => Promise<TData>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function defineQuery<TData, TKey extends QueryKey>(
|
|
13
|
+
opts: QueryOptionsShape<TData, TKey>
|
|
14
|
+
): QueryOptionsShape<TData, TKey> {
|
|
15
|
+
return opts;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const ROOT = ['docyrus', 'data-sources'] as const;
|
|
19
|
+
|
|
20
|
+
export const dataSourceKeys = {
|
|
21
|
+
all: () => ROOT,
|
|
22
|
+
apps: () => [...ROOT, 'apps'] as const,
|
|
23
|
+
lists: () => [...ROOT, 'list'] as const,
|
|
24
|
+
list: (params?: DataSourceListParams) => [
|
|
25
|
+
...ROOT,
|
|
26
|
+
'list',
|
|
27
|
+
'all',
|
|
28
|
+
params ?? {}
|
|
29
|
+
] as const,
|
|
30
|
+
listsByAppSlug: (appSlug: string) => [
|
|
31
|
+
...ROOT,
|
|
32
|
+
'list',
|
|
33
|
+
'by-app-slug',
|
|
34
|
+
appSlug
|
|
35
|
+
] as const,
|
|
36
|
+
listByAppSlug: (appSlug: string, params?: DataSourceListParams) => [
|
|
37
|
+
...ROOT,
|
|
38
|
+
'list',
|
|
39
|
+
'by-app-slug',
|
|
40
|
+
appSlug,
|
|
41
|
+
params ?? {}
|
|
42
|
+
] as const,
|
|
43
|
+
listsByAppId: (appId: string) => [
|
|
44
|
+
...ROOT,
|
|
45
|
+
'list',
|
|
46
|
+
'by-app-id',
|
|
47
|
+
appId
|
|
48
|
+
] as const,
|
|
49
|
+
listByAppId: (appId: string, params?: DataSourceListParams) => [
|
|
50
|
+
...ROOT,
|
|
51
|
+
'list',
|
|
52
|
+
'by-app-id',
|
|
53
|
+
appId,
|
|
54
|
+
params ?? {}
|
|
55
|
+
] as const,
|
|
56
|
+
details: () => [...ROOT, 'detail'] as const,
|
|
57
|
+
byId: (dataSourceId: string, params?: DataSourceListParams) => [
|
|
58
|
+
...ROOT,
|
|
59
|
+
'detail',
|
|
60
|
+
'by-id',
|
|
61
|
+
dataSourceId,
|
|
62
|
+
params ?? {}
|
|
63
|
+
] as const,
|
|
64
|
+
bySlug: (appSlug: string, dataSourceSlug: string, params?: DataSourceListParams) => [
|
|
65
|
+
...ROOT,
|
|
66
|
+
'detail',
|
|
67
|
+
'by-slug',
|
|
68
|
+
appSlug,
|
|
69
|
+
dataSourceSlug,
|
|
70
|
+
params ?? {}
|
|
71
|
+
] as const
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export function createDataSourceQueries(client: RestApiClient) {
|
|
75
|
+
const ds = createDataSourceClient(client);
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
keys: dataSourceKeys,
|
|
79
|
+
|
|
80
|
+
listAppsOptions: () => defineQuery({
|
|
81
|
+
queryKey: dataSourceKeys.apps(),
|
|
82
|
+
queryFn: () => ds.listApps()
|
|
83
|
+
}),
|
|
84
|
+
|
|
85
|
+
listOptions: (params?: DataSourceListParams) => defineQuery({
|
|
86
|
+
queryKey: dataSourceKeys.list(params),
|
|
87
|
+
queryFn: () => ds.list(params)
|
|
88
|
+
}),
|
|
89
|
+
|
|
90
|
+
listByAppSlugOptions: (appSlug: string, params?: DataSourceListParams) => defineQuery({
|
|
91
|
+
queryKey: dataSourceKeys.listByAppSlug(appSlug, params),
|
|
92
|
+
queryFn: () => ds.listByAppSlug(appSlug, params)
|
|
93
|
+
}),
|
|
94
|
+
|
|
95
|
+
listByAppIdOptions: (appId: string, params?: DataSourceListParams) => defineQuery({
|
|
96
|
+
queryKey: dataSourceKeys.listByAppId(appId, params),
|
|
97
|
+
queryFn: () => ds.listByAppId(appId, params)
|
|
98
|
+
}),
|
|
99
|
+
|
|
100
|
+
getByIdOptions: (dataSourceId: string, params?: DataSourceListParams) => defineQuery({
|
|
101
|
+
queryKey: dataSourceKeys.byId(dataSourceId, params),
|
|
102
|
+
queryFn: () => ds.getById(dataSourceId, params)
|
|
103
|
+
}),
|
|
104
|
+
|
|
105
|
+
getBySlugOptions: (
|
|
106
|
+
appSlug: string,
|
|
107
|
+
dataSourceSlug: string,
|
|
108
|
+
params?: DataSourceListParams
|
|
109
|
+
) => defineQuery({
|
|
110
|
+
queryKey: dataSourceKeys.bySlug(appSlug, dataSourceSlug, params),
|
|
111
|
+
queryFn: () => ds.getBySlug(appSlug, dataSourceSlug, params)
|
|
112
|
+
}),
|
|
113
|
+
|
|
114
|
+
invalidateAll: (queryClient: QueryClient) => queryClient.invalidateQueries({ queryKey: dataSourceKeys.all() }),
|
|
115
|
+
|
|
116
|
+
invalidateApps: (queryClient: QueryClient) => queryClient.invalidateQueries({ queryKey: dataSourceKeys.apps() }),
|
|
117
|
+
|
|
118
|
+
invalidateLists: (queryClient: QueryClient) => queryClient.invalidateQueries({ queryKey: dataSourceKeys.lists() }),
|
|
119
|
+
|
|
120
|
+
invalidateDetails: (queryClient: QueryClient) => queryClient.invalidateQueries({ queryKey: dataSourceKeys.details() }),
|
|
121
|
+
|
|
122
|
+
invalidateById: (queryClient: QueryClient, dataSourceId: string) => queryClient.invalidateQueries({
|
|
123
|
+
queryKey: [
|
|
124
|
+
...dataSourceKeys.details(),
|
|
125
|
+
'by-id',
|
|
126
|
+
dataSourceId
|
|
127
|
+
]
|
|
128
|
+
}),
|
|
129
|
+
|
|
130
|
+
invalidateBySlug: (
|
|
131
|
+
queryClient: QueryClient,
|
|
132
|
+
appSlug: string,
|
|
133
|
+
dataSourceSlug: string
|
|
134
|
+
) => queryClient.invalidateQueries({
|
|
135
|
+
queryKey: [
|
|
136
|
+
...dataSourceKeys.details(),
|
|
137
|
+
'by-slug',
|
|
138
|
+
appSlug,
|
|
139
|
+
dataSourceSlug
|
|
140
|
+
]
|
|
141
|
+
}),
|
|
142
|
+
|
|
143
|
+
invalidateForAppSlug: (queryClient: QueryClient, appSlug: string) => queryClient.invalidateQueries({ queryKey: dataSourceKeys.listsByAppSlug(appSlug) }),
|
|
144
|
+
|
|
145
|
+
invalidateForAppId: (queryClient: QueryClient, appId: string) => queryClient.invalidateQueries({ queryKey: dataSourceKeys.listsByAppId(appId) })
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export type DataSourceQueries = ReturnType<typeof createDataSourceQueries>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
type CreateDataViewBody,
|
|
5
|
+
type CreateDataViewClientOptions,
|
|
6
|
+
type DataSource,
|
|
7
|
+
type DataView,
|
|
8
|
+
type DataViewClient,
|
|
9
|
+
type InventoryClient,
|
|
10
|
+
type ListDataViewsParams,
|
|
11
|
+
type UpdateDataViewBody
|
|
12
|
+
} from './types';
|
|
13
|
+
import { unwrapEnvelope } from './unwrap-envelope';
|
|
14
|
+
|
|
15
|
+
async function resolveDataSource(
|
|
16
|
+
inventory: InventoryClient,
|
|
17
|
+
appSlug: string,
|
|
18
|
+
dataSourceSlug: string
|
|
19
|
+
): Promise<DataSource | null> {
|
|
20
|
+
const sources = await inventory.listDataSources();
|
|
21
|
+
const match = sources.find(
|
|
22
|
+
(ds: DataSource) => (ds.appSlug ?? ds.app_slug) === appSlug && ds.slug === dataSourceSlug
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
return match ?? null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createDataViewClient(
|
|
29
|
+
client: RestApiClient,
|
|
30
|
+
appSlug: string,
|
|
31
|
+
dataSourceSlug: string,
|
|
32
|
+
options?: CreateDataViewClientOptions
|
|
33
|
+
): DataViewClient {
|
|
34
|
+
const basePath = `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/views`;
|
|
35
|
+
const inventory: InventoryClient | undefined = options?.inventory;
|
|
36
|
+
|
|
37
|
+
async function list(params?: ListDataViewsParams): Promise<DataView[]> {
|
|
38
|
+
if (inventory) {
|
|
39
|
+
const dataSource = await resolveDataSource(inventory, appSlug, dataSourceSlug);
|
|
40
|
+
|
|
41
|
+
if (dataSource) {
|
|
42
|
+
const views = dataSource.views ?? [];
|
|
43
|
+
|
|
44
|
+
return params?.appId ? views.filter(view => view.tenant_app_id === params.appId) : views;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return unwrapEnvelope<DataView[]>(
|
|
49
|
+
await client.get(basePath, params?.appId ? { appId: params.appId } : undefined)
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function get(viewId: string): Promise<DataView> {
|
|
54
|
+
if (inventory) {
|
|
55
|
+
const dataSource = await resolveDataSource(inventory, appSlug, dataSourceSlug);
|
|
56
|
+
const match = dataSource?.views?.find(view => view.id === viewId);
|
|
57
|
+
|
|
58
|
+
if (match) return match;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return unwrapEnvelope<DataView>(await client.get(`${basePath}/${viewId}`));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function create(body: CreateDataViewBody): Promise<DataView> {
|
|
65
|
+
const result = unwrapEnvelope<DataView>(await client.post(basePath, body));
|
|
66
|
+
|
|
67
|
+
inventory?.upsertDataView(result);
|
|
68
|
+
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function update(viewId: string, body: UpdateDataViewBody): Promise<DataView> {
|
|
73
|
+
const result = unwrapEnvelope<DataView>(await client.put(`${basePath}/${viewId}`, body));
|
|
74
|
+
|
|
75
|
+
if (body.archived === true) {
|
|
76
|
+
inventory?.removeDataView(viewId);
|
|
77
|
+
} else {
|
|
78
|
+
inventory?.upsertDataView(result);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function remove(viewId: string): Promise<void> {
|
|
85
|
+
await client.delete(`${basePath}/${viewId}`);
|
|
86
|
+
inventory?.removeDataView(viewId);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
list, get, create, update, remove
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
|
|
3
|
+
import { createDateUtils } from './date-utils';
|
|
4
|
+
|
|
5
|
+
// 31 December 2026 (a Thursday), 14:05 UTC.
|
|
6
|
+
const SAMPLE = '2026-12-31T14:05:00Z';
|
|
7
|
+
const LONG = 'l, j F Y';
|
|
8
|
+
const SHORT = 'D, j M Y';
|
|
9
|
+
|
|
10
|
+
function format(locale: string | undefined, pattern: string): string | null {
|
|
11
|
+
return createDateUtils({ preferences: {}, userTimezone: 'UTC', locale })
|
|
12
|
+
.formatDateTime(SAMPLE, { format: pattern });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
describe('createDateUtils locale', () => {
|
|
16
|
+
it('uses English names by default', () => {
|
|
17
|
+
expect(format(undefined, LONG)).toBe('Thursday, 31 December 2026');
|
|
18
|
+
expect(format(undefined, SHORT)).toBe('Thu, 31 Dec 2026');
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('uses Turkish names for tr', () => {
|
|
22
|
+
expect(format('tr', LONG)).toBe('Perşembe, 31 Aralık 2026');
|
|
23
|
+
expect(format('tr', 'j F Y')).toBe('31 Aralık 2026');
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
it('accepts underscore and hyphen region tags', () => {
|
|
27
|
+
expect(format('tr_TR', 'F')).toBe('Aralık');
|
|
28
|
+
expect(format('de-DE', 'F')).toBe('Dezember');
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('uses the month form languages put inside a date', () => {
|
|
32
|
+
expect(format('el', 'j F Y')).toBe('31 Δεκεμβρίου 2026');
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it('keeps numeric tokens and AM/PM unchanged', () => {
|
|
36
|
+
expect(format('tr', 'd.m.Y g:i A')).toBe('31.12.2026 2:05 PM');
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('falls back to English for an unknown locale', () => {
|
|
40
|
+
expect(format('not a locale!', 'F')).toBe('December');
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('does not leak a locale into later formatters', () => {
|
|
44
|
+
expect(format('tr', 'F')).toBe('Aralık');
|
|
45
|
+
expect(format(undefined, 'F')).toBe('December');
|
|
46
|
+
expect(format('en', 'F')).toBe('December');
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import DateFormatter from 'php-date-formatter';
|
|
2
|
+
|
|
3
|
+
import { type DateUtils, type DateUtilsConfig, type FormatOptions } from './types';
|
|
4
|
+
|
|
5
|
+
const TIMEZONE_SUFFIX_RE = /([+-]\d{2}:\d{2}|Z)\s*$/;
|
|
6
|
+
|
|
7
|
+
function applyTimezone(date: Date, timezone: string): Date {
|
|
8
|
+
return new Date(date.toLocaleString('en-US', { timeZone: timezone }));
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function parseDate(value: string): Date {
|
|
12
|
+
return new Date(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function parseDatetime(value: string): Date {
|
|
16
|
+
const hasTimezone = TIMEZONE_SUFFIX_RE.test(value);
|
|
17
|
+
|
|
18
|
+
return hasTimezone ? new Date(value) : new Date(`${value}Z`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface DateNameSettings {
|
|
22
|
+
days: string[];
|
|
23
|
+
daysShort: string[];
|
|
24
|
+
months: string[];
|
|
25
|
+
monthsShort: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const dateNameCache = new Map<string, DateNameSettings | null>();
|
|
29
|
+
|
|
30
|
+
function partOf(formatter: Intl.DateTimeFormat, date: Date, type: Intl.DateTimeFormatPartTypes): string {
|
|
31
|
+
return formatter.formatToParts(date).find(part => part.type === type)?.value ?? '';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Day and month names for `locale`, read from Intl. Month names are taken
|
|
36
|
+
* from a "day month" date so languages that inflect them inside a date get
|
|
37
|
+
* that form (Greek "31 Δεκεμβρίου", not the standalone "Δεκέμβριος").
|
|
38
|
+
* Returns null for English or an unknown locale, which keeps the
|
|
39
|
+
* formatter's built-in English names.
|
|
40
|
+
*/
|
|
41
|
+
function getDateNames(locale: string | undefined): DateNameSettings | null {
|
|
42
|
+
const tag = locale?.trim().replace(/_/g, '-');
|
|
43
|
+
|
|
44
|
+
if (!tag || /^en(-|$)/i.test(tag)) return null;
|
|
45
|
+
|
|
46
|
+
const cached = dateNameCache.get(tag);
|
|
47
|
+
|
|
48
|
+
if (cached !== undefined) return cached;
|
|
49
|
+
|
|
50
|
+
let names: DateNameSettings | null = null;
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
const weekdayLong = new Intl.DateTimeFormat(tag, { weekday: 'long', timeZone: 'UTC' });
|
|
54
|
+
const weekdayShort = new Intl.DateTimeFormat(tag, { weekday: 'short', timeZone: 'UTC' });
|
|
55
|
+
const monthLong = new Intl.DateTimeFormat(tag, { day: 'numeric', month: 'long', timeZone: 'UTC' });
|
|
56
|
+
const monthShort = new Intl.DateTimeFormat(tag, { day: 'numeric', month: 'short', timeZone: 'UTC' });
|
|
57
|
+
// 1 January 2023 was a Sunday, so day i of that week is weekday i.
|
|
58
|
+
const weekdays = Array.from({ length: 7 }, (_, i) => new Date(Date.UTC(2023, 0, 1 + i)));
|
|
59
|
+
const months = Array.from({ length: 12 }, (_, i) => new Date(Date.UTC(2023, i, 15)));
|
|
60
|
+
|
|
61
|
+
names = {
|
|
62
|
+
days: weekdays.map(date => partOf(weekdayLong, date, 'weekday')),
|
|
63
|
+
daysShort: weekdays.map(date => partOf(weekdayShort, date, 'weekday')),
|
|
64
|
+
months: months.map(date => partOf(monthLong, date, 'month')),
|
|
65
|
+
monthsShort: months.map(date => partOf(monthShort, date, 'month'))
|
|
66
|
+
};
|
|
67
|
+
} catch {
|
|
68
|
+
names = null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
dateNameCache.set(tag, names);
|
|
72
|
+
|
|
73
|
+
return names;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function createFormatter(locale: string | undefined): DateFormatter {
|
|
77
|
+
const formatter = new DateFormatter();
|
|
78
|
+
const names = getDateNames(locale);
|
|
79
|
+
|
|
80
|
+
/*
|
|
81
|
+
* Set the names on this instance only. Passing them to the constructor
|
|
82
|
+
* would merge them into php-date-formatter's shared defaults and change
|
|
83
|
+
* every formatter created after it.
|
|
84
|
+
*/
|
|
85
|
+
if (names) {
|
|
86
|
+
const instance = formatter as unknown as { dateSettings: Record<string, unknown> };
|
|
87
|
+
|
|
88
|
+
instance.dateSettings = { ...instance.dateSettings, ...names };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return formatter;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function createDateUtils(config: DateUtilsConfig): DateUtils {
|
|
95
|
+
const { preferences, userTimezone = 'UTC', locale } = config;
|
|
96
|
+
const formatter = createFormatter(locale);
|
|
97
|
+
|
|
98
|
+
function formatDate(date: string | Date, options?: FormatOptions): string | null {
|
|
99
|
+
if (!date) return null;
|
|
100
|
+
|
|
101
|
+
const format = options?.format ?? preferences.date_format ?? 'Y-m-d';
|
|
102
|
+
const timezone = options?.timezone ?? userTimezone;
|
|
103
|
+
const parsed = applyTimezone(
|
|
104
|
+
typeof date === 'string' ? parseDate(date) : date,
|
|
105
|
+
timezone
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
return formatter.formatDate(parsed, format);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function formatDateTime(date: string | Date, options?: FormatOptions): string | null {
|
|
112
|
+
if (!date) return null;
|
|
113
|
+
|
|
114
|
+
const format = options?.format ?? preferences.date_time_format ?? 'Y-m-d H:i:s';
|
|
115
|
+
const timezone = options?.timezone ?? userTimezone;
|
|
116
|
+
const parsed = applyTimezone(
|
|
117
|
+
typeof date === 'string' ? parseDatetime(date) : date,
|
|
118
|
+
timezone
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
return formatter.formatDate(parsed, format);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function formatDateLong(date: string | Date, options?: FormatOptions): string | null {
|
|
125
|
+
if (!date) return null;
|
|
126
|
+
|
|
127
|
+
const format = options?.format ?? preferences.long_date_format ?? 'Y-m-d H:i:s';
|
|
128
|
+
const timezone = options?.timezone ?? userTimezone;
|
|
129
|
+
const parsed = applyTimezone(
|
|
130
|
+
typeof date === 'string' ? parseDate(date) : date,
|
|
131
|
+
timezone
|
|
132
|
+
);
|
|
133
|
+
|
|
134
|
+
return formatter.formatDate(parsed, format);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function toUserTimezone(date: string | Date): Date {
|
|
138
|
+
const parsed = typeof date === 'string' ? parseDatetime(date) : date;
|
|
139
|
+
|
|
140
|
+
return applyTimezone(parsed, userTimezone);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
formatDate, formatDateTime, formatDateLong, toUserTimezone
|
|
145
|
+
};
|
|
146
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { type Interceptor } from '@kivacore/api-client';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Top-level keys we consider lossless to strip from a Docyrus API
|
|
5
|
+
* envelope — i.e. the response carries nothing besides `data` and an
|
|
6
|
+
* optional trivial `success` flag. When the envelope additionally
|
|
7
|
+
* carries `meta` (paginated lists), `error`, or `message`, we leave
|
|
8
|
+
* it intact so callers can read those fields.
|
|
9
|
+
*/
|
|
10
|
+
const STRIPPABLE_ENVELOPE_KEYS = new Set(['data', 'success']);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Detect a Docyrus API envelope that's safe to unwrap losslessly — a
|
|
14
|
+
* non-array object whose only top-level keys are `data` and optionally
|
|
15
|
+
* `success`. Domain payloads with their own `data` field (`AppConfig`,
|
|
16
|
+
* `UserAppConfig`, records carrying a `data` column) are protected
|
|
17
|
+
* because they also carry off-set keys (`id`, `status`,
|
|
18
|
+
* `tenant_app_id`, …) that fail the membership check.
|
|
19
|
+
*/
|
|
20
|
+
function looksLikeEnvelope(value: unknown): value is { data: unknown } {
|
|
21
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const keys = Object.keys(value);
|
|
26
|
+
|
|
27
|
+
return 'data' in value && keys.every(key => STRIPPABLE_ENVELOPE_KEYS.has(key));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Response interceptor that unwraps Docyrus' `{ data }` / `{ success,
|
|
32
|
+
* data }` API envelope at the api-client layer. After it runs,
|
|
33
|
+
* `response.data` holds the inner payload directly, so generated
|
|
34
|
+
* TanStack DB collections, hand-written code, and `@kivacore/app-utils`
|
|
35
|
+
* clients can all `await client.get(url)` as if the envelope didn't
|
|
36
|
+
* exist.
|
|
37
|
+
*
|
|
38
|
+
* Envelopes that carry `meta` (paginated lists), `error`, or `message`
|
|
39
|
+
* are intentionally left alone — pagination consumers (data grids)
|
|
40
|
+
* read `meta.count` / `meta.total` off the envelope. Idempotent:
|
|
41
|
+
* applying it twice is a no-op for the second pass because the
|
|
42
|
+
* unwrapped value no longer matches the strippable shape.
|
|
43
|
+
*
|
|
44
|
+
* Register on a `RestApiClient`:
|
|
45
|
+
*
|
|
46
|
+
* ```ts
|
|
47
|
+
* import { RestApiClient } from '@kivacore/api-client';
|
|
48
|
+
* import { envelopeUnwrapInterceptor } from '@kivacore/app-utils';
|
|
49
|
+
*
|
|
50
|
+
* const client = new RestApiClient({ baseURL });
|
|
51
|
+
* client.addInterceptor(envelopeUnwrapInterceptor);
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export const envelopeUnwrapInterceptor: Interceptor = {
|
|
55
|
+
response: (response) => {
|
|
56
|
+
if (looksLikeEnvelope(response.data)) {
|
|
57
|
+
return {
|
|
58
|
+
...response,
|
|
59
|
+
data: response.data.data
|
|
60
|
+
} as typeof response;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return response;
|
|
64
|
+
}
|
|
65
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
2
|
+
import { expect, it, vi } from 'vitest';
|
|
3
|
+
|
|
4
|
+
import { createDateUtils } from './date-utils';
|
|
5
|
+
import { getTenantPreferenceSummary } from './get-tenant-preferences';
|
|
6
|
+
import { createNumberUtils } from './number-utils';
|
|
7
|
+
|
|
8
|
+
const payload = {
|
|
9
|
+
preferences: {
|
|
10
|
+
dateFormat: 'd/m/Y', timeZone: 'Europe/Ljubljana', decimalPrecision: 3, decimalSeparator: ',', thousandSeparator: '.'
|
|
11
|
+
},
|
|
12
|
+
tenant: { name: 'Test' },
|
|
13
|
+
product: null,
|
|
14
|
+
enums: []
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
it.each([payload, { success: true, data: payload }])('returns compact formatting preferences from %j', async (response) => {
|
|
18
|
+
const get = vi.fn(async () => response);
|
|
19
|
+
const client = { get } as unknown as RestApiClient;
|
|
20
|
+
|
|
21
|
+
await expect(getTenantPreferenceSummary(client)).resolves.toMatchObject({
|
|
22
|
+
preferences: {
|
|
23
|
+
date_format: 'd/m/Y',
|
|
24
|
+
time_zone: 'Europe/Ljubljana',
|
|
25
|
+
decimal_precision: 3,
|
|
26
|
+
decimal_separator: ','
|
|
27
|
+
},
|
|
28
|
+
tenant: { name: 'Test' },
|
|
29
|
+
product: null
|
|
30
|
+
});
|
|
31
|
+
expect(get).toHaveBeenCalledExactlyOnceWith('/v1/tenant/preferences', { includeEnums: false });
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('applies the configured date format, time zone and decimal precision', async () => {
|
|
35
|
+
const client = { get: async () => payload } as unknown as RestApiClient;
|
|
36
|
+
const { preferences } = await getTenantPreferenceSummary(client);
|
|
37
|
+
const dates = createDateUtils({ preferences: preferences ?? {}, userTimezone: preferences?.time_zone });
|
|
38
|
+
const numbers = createNumberUtils({ preferences: preferences ?? {} });
|
|
39
|
+
|
|
40
|
+
expect(dates.formatDate('2026-11-23T23:50:00Z')).toBe('24/11/2026');
|
|
41
|
+
expect(numbers.formatNumber(1234.5)).toBe('1.234,500');
|
|
42
|
+
});
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
2
|
+
|
|
3
|
+
import { type TenantPreferenceSummary, type TenantPreferences } from './types';
|
|
4
|
+
import { unwrapEnvelope } from './unwrap-envelope';
|
|
5
|
+
|
|
6
|
+
export async function getTenantPreferences(client: RestApiClient): Promise<TenantPreferences> {
|
|
7
|
+
return client.get<TenantPreferences>('/v1/tenant/preferences');
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export async function getTenantPreferenceSummary(client: RestApiClient): Promise<TenantPreferenceSummary> {
|
|
11
|
+
const { preferences, tenant, product } = unwrapEnvelope<TenantPreferenceSummary>(
|
|
12
|
+
await client.get('/v1/tenant/preferences', { includeEnums: false })
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
return {
|
|
16
|
+
preferences: preferences ? {
|
|
17
|
+
...preferences,
|
|
18
|
+
date_format: (preferences.date_format ?? preferences.dateFormat) as string | undefined,
|
|
19
|
+
date_time_format: (preferences.date_time_format ?? preferences.dateTimeFormat) as string | undefined,
|
|
20
|
+
long_date_format: (preferences.long_date_format ?? preferences.longDateFormat) as string | undefined,
|
|
21
|
+
time_format: (preferences.time_format ?? preferences.timeFormat) as string | undefined,
|
|
22
|
+
time_zone: (preferences.time_zone ?? preferences.timeZone) as string | undefined,
|
|
23
|
+
thousand_separator: (preferences.thousand_separator ?? preferences.thousandSeparator) as string | undefined,
|
|
24
|
+
decimal_separator: (preferences.decimal_separator ?? preferences.decimalSeparator) as string | undefined,
|
|
25
|
+
decimal_precision: (preferences.decimal_precision ?? preferences.decimalPrecision) as number | undefined
|
|
26
|
+
} : null,
|
|
27
|
+
tenant,
|
|
28
|
+
product
|
|
29
|
+
};
|
|
30
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
declare module 'handlebars-async-helpers' {
|
|
2
|
+
import Handlebars from 'handlebars';
|
|
3
|
+
|
|
4
|
+
interface AsyncHandlebars extends Omit<typeof Handlebars, 'compile'> {
|
|
5
|
+
compile(template: string, options?: Handlebars.CompileOptions): (context: any, options?: Handlebars.RuntimeOptions) => Promise<string>;
|
|
6
|
+
registerHelper(name: string, fn: Handlebars.HelperDelegate): void;
|
|
7
|
+
escapeExpression(str: string): string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function asyncHelpers(handlebars: typeof Handlebars): AsyncHandlebars;
|
|
11
|
+
export default asyncHelpers;
|
|
12
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* React Native entry (resolved through the `react-native` export condition).
|
|
3
|
+
*
|
|
4
|
+
* Same public API as `./index`. The tsup native build bundles
|
|
5
|
+
* `handlebars-async-helpers` and `jsonpath-plus` with Node-only imports
|
|
6
|
+
* (`stream`, `vm`) redirected to RN-safe code, so Metro never has to resolve a
|
|
7
|
+
* Node core module.
|
|
8
|
+
*/
|
|
9
|
+
export * from './index';
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
export { getTenantPreferences, getTenantPreferenceSummary } from './get-tenant-preferences';
|
|
2
|
+
export { createDateUtils } from './date-utils';
|
|
3
|
+
export {
|
|
4
|
+
createNumberUtils, formatNumberToWords, formatDurationAsTime, formatDurationAsHours, formatDurationAsWords
|
|
5
|
+
} from './number-utils';
|
|
6
|
+
export { createTemplateEngine } from './template-engine';
|
|
7
|
+
export { jsonataHelpers } from './jsonata-helpers';
|
|
8
|
+
export { createAppConfigClient } from './app-config-client';
|
|
9
|
+
export { createUserAppConfigClient } from './user-app-config-client';
|
|
10
|
+
export { createDataViewClient } from './data-view-client';
|
|
11
|
+
export { createDataFormClient } from './data-form-client';
|
|
12
|
+
export { createDataSourceClient } from './data-source-client';
|
|
13
|
+
export { createInventoryClient } from './inventory-client';
|
|
14
|
+
export { createBrandClient } from './brand-client';
|
|
15
|
+
export { createUserIdentityClient } from './user-identity-client';
|
|
16
|
+
export { envelopeUnwrapInterceptor } from './envelope-interceptor';
|
|
17
|
+
export { unwrapEnvelope } from './unwrap-envelope';
|
|
18
|
+
export type {
|
|
19
|
+
TenantPreferences,
|
|
20
|
+
TenantPreferenceSummary,
|
|
21
|
+
DateUtilsConfig,
|
|
22
|
+
FormatOptions,
|
|
23
|
+
DateUtils,
|
|
24
|
+
NumberFormatOptions,
|
|
25
|
+
NumberToWordsOptions,
|
|
26
|
+
NumberUtils,
|
|
27
|
+
NumberUtilsConfig,
|
|
28
|
+
NumberWordLang,
|
|
29
|
+
CurrencyCode,
|
|
30
|
+
TemplateEngineConfig,
|
|
31
|
+
TemplateEngine,
|
|
32
|
+
AppConfig,
|
|
33
|
+
UpsertAppConfigBody,
|
|
34
|
+
AppConfigClient,
|
|
35
|
+
CreateAppConfigClientOptions,
|
|
36
|
+
UserAppConfig,
|
|
37
|
+
UpsertUserAppConfigBody,
|
|
38
|
+
UserAppConfigClient,
|
|
39
|
+
CreateUserAppConfigClientOptions,
|
|
40
|
+
User,
|
|
41
|
+
DataView,
|
|
42
|
+
CreateDataViewBody,
|
|
43
|
+
UpdateDataViewBody,
|
|
44
|
+
ListDataViewsParams,
|
|
45
|
+
DataViewClient,
|
|
46
|
+
DataForm,
|
|
47
|
+
CreateDataFormBody,
|
|
48
|
+
UpdateDataFormBody,
|
|
49
|
+
DataFormClient,
|
|
50
|
+
DataSourceExpand,
|
|
51
|
+
DataSourceField,
|
|
52
|
+
DataSourceEnumOption,
|
|
53
|
+
DataSource,
|
|
54
|
+
DataSourceApp,
|
|
55
|
+
DataSourceListParams,
|
|
56
|
+
DataSourceClient,
|
|
57
|
+
CreateDataSourceClientOptions,
|
|
58
|
+
CreateDataViewClientOptions,
|
|
59
|
+
CreateDataFormClientOptions,
|
|
60
|
+
ListInventoryParams,
|
|
61
|
+
InventoryClient,
|
|
62
|
+
InventoryClientOptions,
|
|
63
|
+
InventoryStorage,
|
|
64
|
+
InventoryStorageOption,
|
|
65
|
+
InventoryLoadStepId,
|
|
66
|
+
InventoryLoadPhase,
|
|
67
|
+
InventoryLoadProgress,
|
|
68
|
+
InventoryLoadResult,
|
|
69
|
+
InventoryLoadOptions,
|
|
70
|
+
Brand,
|
|
71
|
+
BrandColorScheme,
|
|
72
|
+
BrandActiveVoicePreference,
|
|
73
|
+
BrandDirectness,
|
|
74
|
+
BrandEmojiPolicy,
|
|
75
|
+
BrandFormalityLevel,
|
|
76
|
+
BrandMetricEmphasis,
|
|
77
|
+
BrandSlideDensity,
|
|
78
|
+
BrandIllustrationStyle,
|
|
79
|
+
CreateBrandBody,
|
|
80
|
+
UpdateBrandBody,
|
|
81
|
+
FetchBrandFromWebsiteResponse,
|
|
82
|
+
BrandClient,
|
|
83
|
+
CreateBrandClientOptions,
|
|
84
|
+
MicrosoftIdentityPayload,
|
|
85
|
+
GoogleIdentityPayload,
|
|
86
|
+
UserIdentityClient,
|
|
87
|
+
AppUtilsConfig
|
|
88
|
+
} from './types';
|