@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
package/package.json
CHANGED
|
@@ -1,10 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kivacore/app-utils",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.22.1",
|
|
4
|
+
"description": "Utility functions for frontend applications using Docyrus as backend",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "https://github.com/Docyrus/docyrus-devkit.git",
|
|
8
8
|
"directory": "packages/app-utils"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"module": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"react-native": "./dist/index.native.js",
|
|
18
|
+
"import": "./dist/index.js"
|
|
19
|
+
},
|
|
20
|
+
"./query": {
|
|
21
|
+
"import": "./dist/query.js",
|
|
22
|
+
"types": "./dist/query.d.ts"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"jsonpath-plus": "^10.4.0",
|
|
27
|
+
"php-date-formatter": "^1.3.7"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@kivacore/api-client": "0.3.7",
|
|
31
|
+
"@tanstack/query-core": "5.107.1",
|
|
32
|
+
"@types/node": "26.6.6",
|
|
33
|
+
"date-fns": "^4.4.0",
|
|
34
|
+
"handlebars": "^4.7.10",
|
|
35
|
+
"handlebars-async-helpers": "^1.0.6",
|
|
36
|
+
"jsonata": "^2.2.2",
|
|
37
|
+
"tsup": "9.0.0",
|
|
38
|
+
"typescript": "7.0.2",
|
|
39
|
+
"vitest": "5.1.0"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@kivacore/api-client": ">=0.1.0",
|
|
43
|
+
"@tanstack/query-core": ">=5.17.0",
|
|
44
|
+
"date-fns": ">=3.0.0",
|
|
45
|
+
"handlebars": ">=4.7.0",
|
|
46
|
+
"jsonata": ">=2.0.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"@tanstack/query-core": {
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
"react-native": "./dist/index.native.js",
|
|
54
|
+
"scripts": {
|
|
55
|
+
"build": "tsup",
|
|
56
|
+
"dev": "tsup --watch",
|
|
57
|
+
"lint": "eslint src",
|
|
58
|
+
"format": "eslint src --fix",
|
|
59
|
+
"typecheck": "eslint src && tsc --noEmit",
|
|
60
|
+
"test": "vitest run --passWithNoTests",
|
|
61
|
+
"test:watch": "vitest",
|
|
62
|
+
"deploy": "pnpm run build && pnpm publish --access public"
|
|
9
63
|
}
|
|
10
|
-
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
type AppConfig,
|
|
5
|
+
type AppConfigClient,
|
|
6
|
+
type CreateAppConfigClientOptions,
|
|
7
|
+
type InventoryClient,
|
|
8
|
+
type UpsertAppConfigBody
|
|
9
|
+
} from './types';
|
|
10
|
+
import { unwrapEnvelope } from './unwrap-envelope';
|
|
11
|
+
|
|
12
|
+
export function createAppConfigClient(
|
|
13
|
+
client: RestApiClient,
|
|
14
|
+
appId: string,
|
|
15
|
+
options?: CreateAppConfigClientOptions
|
|
16
|
+
): AppConfigClient {
|
|
17
|
+
const basePath = `/v1/tenant/apps/${appId}/config`;
|
|
18
|
+
const inventory: InventoryClient | undefined = options?.inventory;
|
|
19
|
+
|
|
20
|
+
async function get(): Promise<AppConfig> {
|
|
21
|
+
if (inventory) {
|
|
22
|
+
const cached = await inventory.getAppConfig(appId);
|
|
23
|
+
|
|
24
|
+
/*
|
|
25
|
+
* `null` means the inventory confirmed no config exists — fall through to
|
|
26
|
+
* the API so callers still get a real `404` if they rely on it.
|
|
27
|
+
*/
|
|
28
|
+
if (cached) return cached;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return unwrapEnvelope<AppConfig>(await client.get(basePath));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function upsert(body: UpsertAppConfigBody): Promise<AppConfig> {
|
|
35
|
+
const result = unwrapEnvelope<AppConfig>(await client.put(basePath, body));
|
|
36
|
+
|
|
37
|
+
inventory?.setAppConfig(appId, result);
|
|
38
|
+
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function remove(): Promise<void> {
|
|
43
|
+
await client.delete(basePath);
|
|
44
|
+
inventory?.setAppConfig(appId, null);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return { get, upsert, remove };
|
|
48
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type Handlebars from 'handlebars';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Async-aware `#each`, registered over the one `handlebars-async-helpers`
|
|
5
|
+
* installs. That helper breaks in browsers and on empty lists:
|
|
6
|
+
* - it reads Node's `global` (`global.Symbol`) for every non-array value, so
|
|
7
|
+
* `{{#each someObject}}` throws "global is not defined" in browsers;
|
|
8
|
+
* - it keeps the `{{else}}` result as a string and then calls `.join` on it,
|
|
9
|
+
* so `{{#each emptyList}}…{{else}}…{{/each}}` throws;
|
|
10
|
+
* - it imports Node's `stream` only for an `instanceof Readable` check.
|
|
11
|
+
*
|
|
12
|
+
* Same semantics otherwise: awaits a promised list, iterates arrays (skipping
|
|
13
|
+
* holes), other iterables (Map, Set, …) and plain objects, sets
|
|
14
|
+
* `@index`/`@key`/`@first`/`@last` and block params, and renders sequentially
|
|
15
|
+
* so async helpers inside the block keep their order.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
type HelperOptions = Handlebars.HelperOptions & { ids?: string[] };
|
|
19
|
+
type AsyncBlock = (context: unknown, options?: { data?: unknown; blockParams?: unknown[] }) => unknown;
|
|
20
|
+
|
|
21
|
+
function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
|
|
22
|
+
return value != null && typeof (value as { then?: unknown }).then === 'function';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function createAsyncEachHelper(handlebars: Pick<typeof Handlebars, 'Utils'>) {
|
|
26
|
+
const {
|
|
27
|
+
appendContextPath, blockParams, createFrame
|
|
28
|
+
} = handlebars.Utils as typeof Handlebars.Utils & {
|
|
29
|
+
appendContextPath: (contextPath: string | undefined, id: string) => string;
|
|
30
|
+
blockParams: (params: unknown[], ids: unknown[]) => unknown[];
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
return async function each(this: unknown, rawContext: unknown, options: HelperOptions): Promise<string> {
|
|
34
|
+
if (!options) {
|
|
35
|
+
throw new Error('Must pass iterator to #each');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const fn = options.fn as unknown as AsyncBlock;
|
|
39
|
+
const inverse = options.inverse as unknown as AsyncBlock;
|
|
40
|
+
let context = typeof rawContext === 'function' ? (rawContext as () => unknown).call(this) : rawContext;
|
|
41
|
+
|
|
42
|
+
if (isPromiseLike(context)) {
|
|
43
|
+
context = await context;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const contextPath = options.data && options.ids ? `${appendContextPath(options.data.contextPath as string | undefined, options.ids[0] ?? '')}.` : undefined;
|
|
47
|
+
const data = options.data ? createFrame(options.data) as Record<string, unknown> : undefined;
|
|
48
|
+
const parts: string[] = [];
|
|
49
|
+
|
|
50
|
+
const renderItem = async (item: unknown, key: string | number, index: number, last: boolean) => {
|
|
51
|
+
if (data) {
|
|
52
|
+
data.key = key;
|
|
53
|
+
data.index = index;
|
|
54
|
+
data.first = index === 0;
|
|
55
|
+
data.last = last;
|
|
56
|
+
|
|
57
|
+
if (contextPath) {
|
|
58
|
+
data.contextPath = contextPath + key;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
parts.push(String(await fn(item, {
|
|
63
|
+
data,
|
|
64
|
+
blockParams: blockParams([item, key], [contextPath ? contextPath + key : undefined, null])
|
|
65
|
+
}) ?? ''));
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
if (context && typeof context === 'object') {
|
|
69
|
+
if (Array.isArray(context)) {
|
|
70
|
+
for (let i = 0; i < context.length; i += 1) {
|
|
71
|
+
if (i in context) {
|
|
72
|
+
await renderItem(context[i], i, i, i === context.length - 1);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
} else if (typeof (context as Iterable<unknown>)[Symbol.iterator] === 'function') {
|
|
76
|
+
const items = Array.from(context as Iterable<unknown>);
|
|
77
|
+
|
|
78
|
+
for (let i = 0; i < items.length; i += 1) {
|
|
79
|
+
await renderItem(items[i], i, i, i === items.length - 1);
|
|
80
|
+
}
|
|
81
|
+
} else {
|
|
82
|
+
const keys = Object.keys(context);
|
|
83
|
+
|
|
84
|
+
for (let i = 0; i < keys.length; i += 1) {
|
|
85
|
+
const key = keys[i] as string;
|
|
86
|
+
|
|
87
|
+
await renderItem((context as Record<string, unknown>)[key], key, i, i === keys.length - 1);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (parts.length === 0) {
|
|
93
|
+
return String(await inverse(this) ?? '');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return parts.join('');
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
type Brand,
|
|
5
|
+
type BrandClient,
|
|
6
|
+
type CreateBrandBody,
|
|
7
|
+
type CreateBrandClientOptions,
|
|
8
|
+
type FetchBrandFromWebsiteResponse,
|
|
9
|
+
type InventoryClient,
|
|
10
|
+
type UpdateBrandBody
|
|
11
|
+
} from './types';
|
|
12
|
+
import { unwrapEnvelope } from './unwrap-envelope';
|
|
13
|
+
|
|
14
|
+
export function createBrandClient(
|
|
15
|
+
client: RestApiClient,
|
|
16
|
+
options?: CreateBrandClientOptions
|
|
17
|
+
): BrandClient {
|
|
18
|
+
const basePath = '/v1/tenant/brands';
|
|
19
|
+
const inventory: InventoryClient | undefined = options?.inventory;
|
|
20
|
+
|
|
21
|
+
async function list(): Promise<Brand[]> {
|
|
22
|
+
if (inventory) return inventory.listBrands();
|
|
23
|
+
|
|
24
|
+
return unwrapEnvelope<Brand[]>(await client.get(basePath));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function get(brandId: string): Promise<Brand> {
|
|
28
|
+
if (inventory) {
|
|
29
|
+
const match = (await inventory.listBrands()).find(brand => brand.id === brandId);
|
|
30
|
+
|
|
31
|
+
if (match) return match;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return unwrapEnvelope<Brand>(await client.get(`${basePath}/${brandId}`));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function create(body: CreateBrandBody): Promise<Brand> {
|
|
38
|
+
const result = unwrapEnvelope<Brand>(await client.post(basePath, body));
|
|
39
|
+
|
|
40
|
+
inventory?.upsertBrand(result);
|
|
41
|
+
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function update(brandId: string, body: UpdateBrandBody): Promise<Brand> {
|
|
46
|
+
const result = unwrapEnvelope<Brand>(await client.patch(`${basePath}/${brandId}`, body));
|
|
47
|
+
|
|
48
|
+
if (body.archived === true) {
|
|
49
|
+
inventory?.removeBrand(brandId);
|
|
50
|
+
} else {
|
|
51
|
+
inventory?.upsertBrand(result);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function remove(brandId: string): Promise<void> {
|
|
58
|
+
await client.delete(`${basePath}/${brandId}`);
|
|
59
|
+
inventory?.removeBrand(brandId);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function fetchFromWebsite(brandId: string): Promise<FetchBrandFromWebsiteResponse> {
|
|
63
|
+
const result = await client.put<FetchBrandFromWebsiteResponse>(
|
|
64
|
+
`${basePath}/${brandId}/fetchFromWebsite`
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
// The RPC returns a partial brand; merge it into the cached copy if present.
|
|
68
|
+
if (inventory && result?.brand) {
|
|
69
|
+
const existing = (await inventory.listBrands()).find(brand => brand.id === brandId);
|
|
70
|
+
|
|
71
|
+
if (existing) inventory.upsertBrand({ ...existing, ...result.brand });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
list, get, create, update, remove, fetchFromWebsite
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
type CreateDataFormBody,
|
|
5
|
+
type CreateDataFormClientOptions,
|
|
6
|
+
type DataForm,
|
|
7
|
+
type DataFormClient,
|
|
8
|
+
type DataSource,
|
|
9
|
+
type InventoryClient,
|
|
10
|
+
type UpdateDataFormBody
|
|
11
|
+
} from './types';
|
|
12
|
+
import { unwrapEnvelope } from './unwrap-envelope';
|
|
13
|
+
|
|
14
|
+
async function resolveDataSource(
|
|
15
|
+
inventory: InventoryClient,
|
|
16
|
+
appSlug: string,
|
|
17
|
+
dataSourceSlug: string
|
|
18
|
+
): Promise<DataSource | null> {
|
|
19
|
+
const sources = await inventory.listDataSources();
|
|
20
|
+
const match = sources.find(
|
|
21
|
+
(ds: DataSource) => (ds.appSlug ?? ds.app_slug) === appSlug && ds.slug === dataSourceSlug
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
return match ?? null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createDataFormClient(
|
|
28
|
+
client: RestApiClient,
|
|
29
|
+
appSlug: string,
|
|
30
|
+
dataSourceSlug: string,
|
|
31
|
+
options?: CreateDataFormClientOptions
|
|
32
|
+
): DataFormClient {
|
|
33
|
+
const basePath = `/v1/apps/${appSlug}/data-sources/${dataSourceSlug}/forms`;
|
|
34
|
+
const inventory: InventoryClient | undefined = options?.inventory;
|
|
35
|
+
|
|
36
|
+
async function list(): Promise<DataForm[]> {
|
|
37
|
+
if (inventory) {
|
|
38
|
+
const dataSource = await resolveDataSource(inventory, appSlug, dataSourceSlug);
|
|
39
|
+
|
|
40
|
+
if (dataSource) return dataSource.forms ?? [];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return unwrapEnvelope<DataForm[]>(await client.get(basePath));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function get(formId: string): Promise<DataForm> {
|
|
47
|
+
if (inventory) {
|
|
48
|
+
const dataSource = await resolveDataSource(inventory, appSlug, dataSourceSlug);
|
|
49
|
+
const match = dataSource?.forms?.find(form => form.id === formId);
|
|
50
|
+
|
|
51
|
+
if (match) return match;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return unwrapEnvelope<DataForm>(await client.get(`${basePath}/${formId}`));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function create(body: CreateDataFormBody): Promise<DataForm> {
|
|
58
|
+
const result = unwrapEnvelope<DataForm>(await client.post(basePath, body));
|
|
59
|
+
|
|
60
|
+
inventory?.upsertDataForm(result);
|
|
61
|
+
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function update(formId: string, body: UpdateDataFormBody): Promise<DataForm> {
|
|
66
|
+
const result = unwrapEnvelope<DataForm>(await client.put(`${basePath}/${formId}`, body));
|
|
67
|
+
|
|
68
|
+
if (body.archived === true) {
|
|
69
|
+
inventory?.removeDataForm(formId);
|
|
70
|
+
} else {
|
|
71
|
+
inventory?.upsertDataForm(result);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function remove(formId: string): Promise<void> {
|
|
78
|
+
await client.delete(`${basePath}/${formId}`);
|
|
79
|
+
inventory?.removeDataForm(formId);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
list, get, create, update, remove
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { type RestApiClient } from '@kivacore/api-client';
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
type CreateDataSourceClientOptions,
|
|
5
|
+
type DataSource,
|
|
6
|
+
type DataSourceApp,
|
|
7
|
+
type DataSourceClient,
|
|
8
|
+
type DataSourceEnumOption,
|
|
9
|
+
type DataSourceField,
|
|
10
|
+
type DataSourceListParams,
|
|
11
|
+
type InventoryClient
|
|
12
|
+
} from './types';
|
|
13
|
+
import { unwrapEnvelope } from './unwrap-envelope';
|
|
14
|
+
|
|
15
|
+
function matchesSlug(dataSource: DataSource, appSlug: string, dataSourceSlug: string): boolean {
|
|
16
|
+
const ownerAppSlug = dataSource.appSlug ?? dataSource.app_slug;
|
|
17
|
+
|
|
18
|
+
return ownerAppSlug === appSlug && dataSource.slug === dataSourceSlug;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Directed relation graph over all data sources: `relation` fields point from a
|
|
23
|
+
* child to its parent (`relation_data_source_id`). `parentsByChild` maps a
|
|
24
|
+
* child id → its parent ids; `childrenByParent` is the reverse.
|
|
25
|
+
*/
|
|
26
|
+
interface RelationIndex {
|
|
27
|
+
byId: Map<string, DataSource>;
|
|
28
|
+
parentsByChild: Map<string, Set<string>>;
|
|
29
|
+
childrenByParent: Map<string, Set<string>>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Normalizes a field type to its bare name (`field-relation` → `relation`). */
|
|
33
|
+
function normalizeFieldType(type: string): string {
|
|
34
|
+
return type.startsWith('field-') ? type.slice('field-'.length) : type;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The parent data source id a `relation` field targets, or `undefined` for non-relation fields. */
|
|
38
|
+
function getRelationTargetId(field: DataSourceField): string | undefined {
|
|
39
|
+
if (normalizeFieldType(field.type) !== 'relation') return undefined;
|
|
40
|
+
|
|
41
|
+
const target = field.relation_data_source_id ?? (field as Record<string, unknown>).relationDataSourceId;
|
|
42
|
+
|
|
43
|
+
return typeof target === 'string' && target.length > 0 ? target : undefined;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function addRelationEdge(map: Map<string, Set<string>>, key: string, value: string): void {
|
|
47
|
+
const existing = map.get(key);
|
|
48
|
+
|
|
49
|
+
if (existing) existing.add(value);
|
|
50
|
+
else map.set(key, new Set([value]));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function buildRelationIndex(sources: DataSource[]): RelationIndex {
|
|
54
|
+
const byId = new Map<string, DataSource>();
|
|
55
|
+
const parentsByChild = new Map<string, Set<string>>();
|
|
56
|
+
const childrenByParent = new Map<string, Set<string>>();
|
|
57
|
+
|
|
58
|
+
for (const dataSource of sources) byId.set(dataSource.id, dataSource);
|
|
59
|
+
|
|
60
|
+
for (const dataSource of sources) {
|
|
61
|
+
for (const field of dataSource.fields ?? []) {
|
|
62
|
+
const parentId = getRelationTargetId(field);
|
|
63
|
+
|
|
64
|
+
// Skip non-relations and self-links (e.g. a hierarchical `parent` field).
|
|
65
|
+
if (!parentId || parentId === dataSource.id) continue;
|
|
66
|
+
|
|
67
|
+
addRelationEdge(parentsByChild, dataSource.id, parentId);
|
|
68
|
+
addRelationEdge(childrenByParent, parentId, dataSource.id);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return { byId, parentsByChild, childrenByParent };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function createDataSourceClient(
|
|
76
|
+
client: RestApiClient,
|
|
77
|
+
options?: CreateDataSourceClientOptions
|
|
78
|
+
): DataSourceClient {
|
|
79
|
+
const basePath = '/v1/apps/data-sources';
|
|
80
|
+
const inventory: InventoryClient | undefined = options?.inventory;
|
|
81
|
+
|
|
82
|
+
function buildQueryParams(params?: DataSourceListParams): Record<string, string> | undefined {
|
|
83
|
+
if (!params?.expand) return undefined;
|
|
84
|
+
|
|
85
|
+
return { expand: params.expand };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function listApps(): Promise<DataSourceApp[]> {
|
|
89
|
+
if (inventory) return inventory.listApps();
|
|
90
|
+
|
|
91
|
+
return unwrapEnvelope<DataSourceApp[]>(await client.get('/v1/apps'));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function list(params?: DataSourceListParams): Promise<DataSource[]> {
|
|
95
|
+
if (inventory && !params?.expand) return inventory.listDataSources();
|
|
96
|
+
|
|
97
|
+
return unwrapEnvelope<DataSource[]>(
|
|
98
|
+
await client.get(basePath, buildQueryParams(params))
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function listByAppSlug(
|
|
103
|
+
appSlug: string,
|
|
104
|
+
params?: DataSourceListParams
|
|
105
|
+
): Promise<DataSource[]> {
|
|
106
|
+
if (inventory && !params?.expand) {
|
|
107
|
+
const sources = await inventory.listDataSources();
|
|
108
|
+
|
|
109
|
+
return sources.filter(ds => (ds.appSlug ?? ds.app_slug) === appSlug);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return unwrapEnvelope<DataSource[]>(
|
|
113
|
+
await client.get(`/v1/apps/${appSlug}/data-sources`, buildQueryParams(params))
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function listByAppId(
|
|
118
|
+
appId: string,
|
|
119
|
+
params?: DataSourceListParams
|
|
120
|
+
): Promise<DataSource[]> {
|
|
121
|
+
if (inventory && !params?.expand) {
|
|
122
|
+
const sources = await inventory.listDataSources();
|
|
123
|
+
|
|
124
|
+
return sources.filter(ds => ds.tenant_app_id === appId);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const queryParams: Record<string, string> = { appId };
|
|
128
|
+
|
|
129
|
+
if (params?.expand) {
|
|
130
|
+
queryParams.expand = params.expand;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
return unwrapEnvelope<DataSource[]>(await client.get(basePath, queryParams));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function getById(
|
|
137
|
+
dataSourceId: string,
|
|
138
|
+
params?: DataSourceListParams
|
|
139
|
+
): Promise<DataSource> {
|
|
140
|
+
if (inventory && !params?.expand) {
|
|
141
|
+
const sources = await inventory.listDataSources();
|
|
142
|
+
const match = sources.find(ds => ds.id === dataSourceId);
|
|
143
|
+
|
|
144
|
+
if (match) return match;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return unwrapEnvelope<DataSource>(
|
|
148
|
+
await client.get(`${basePath}/${dataSourceId}`, buildQueryParams(params))
|
|
149
|
+
);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function getBySlug(
|
|
153
|
+
appSlug: string,
|
|
154
|
+
dataSourceSlug: string,
|
|
155
|
+
params?: DataSourceListParams
|
|
156
|
+
): Promise<DataSource> {
|
|
157
|
+
if (inventory && !params?.expand) {
|
|
158
|
+
const sources = await inventory.listDataSources();
|
|
159
|
+
const match = sources.find(ds => matchesSlug(ds, appSlug, dataSourceSlug));
|
|
160
|
+
|
|
161
|
+
if (match) return match;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return unwrapEnvelope<DataSource>(
|
|
165
|
+
await client.get(
|
|
166
|
+
`/v1/apps/${appSlug}/data-sources/${dataSourceSlug}`,
|
|
167
|
+
buildQueryParams(params)
|
|
168
|
+
)
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async function getFields(dataSourceId: string): Promise<DataSourceField[]> {
|
|
173
|
+
/*
|
|
174
|
+
* Prefer the inventory cache — cached data sources already carry their
|
|
175
|
+
* fields (with enums) via `dataSourcesExpand`.
|
|
176
|
+
*/
|
|
177
|
+
if (inventory) {
|
|
178
|
+
const cached = await getById(dataSourceId);
|
|
179
|
+
|
|
180
|
+
if (cached.fields) return cached.fields;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// No inventory (or cache miss): fetch the fields explicitly.
|
|
184
|
+
const dataSource = await getById(dataSourceId, { expand: 'fields' });
|
|
185
|
+
|
|
186
|
+
return dataSource.fields ?? [];
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function getFieldById(
|
|
190
|
+
dataSourceId: string,
|
|
191
|
+
fieldId: string
|
|
192
|
+
): Promise<DataSourceField | undefined> {
|
|
193
|
+
return (await getFields(dataSourceId)).find(field => field.id === fieldId);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function getFieldBySlug(
|
|
197
|
+
dataSourceId: string,
|
|
198
|
+
fieldSlug: string
|
|
199
|
+
): Promise<DataSourceField | undefined> {
|
|
200
|
+
return (await getFields(dataSourceId)).find(field => field.slug === fieldSlug);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function getEnumsByFieldId(
|
|
204
|
+
dataSourceId: string,
|
|
205
|
+
fieldId: string
|
|
206
|
+
): Promise<DataSourceEnumOption[]> {
|
|
207
|
+
const field = await getFieldById(dataSourceId, fieldId);
|
|
208
|
+
|
|
209
|
+
return field?.enums ?? [];
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function getEnumById(
|
|
213
|
+
dataSourceId: string,
|
|
214
|
+
fieldId: string,
|
|
215
|
+
enumId: string
|
|
216
|
+
): Promise<DataSourceEnumOption | undefined> {
|
|
217
|
+
return (await getEnumsByFieldId(dataSourceId, fieldId)).find(option => option.id === enumId);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/*
|
|
221
|
+
* Relation index, memoized against the data-source array it was built from.
|
|
222
|
+
* The inventory returns the same array reference until it's invalidated, so
|
|
223
|
+
* this rebuilds only when the underlying cache changes.
|
|
224
|
+
*/
|
|
225
|
+
let relationIndexSource: DataSource[] | null = null;
|
|
226
|
+
let relationIndex: RelationIndex | null = null;
|
|
227
|
+
|
|
228
|
+
async function loadAllDataSources(): Promise<DataSource[]> {
|
|
229
|
+
if (inventory) return inventory.listDataSources();
|
|
230
|
+
|
|
231
|
+
return unwrapEnvelope<DataSource[]>(await client.get(basePath, { expand: 'fields' }));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async function getRelationIndex(): Promise<RelationIndex> {
|
|
235
|
+
const sources = await loadAllDataSources();
|
|
236
|
+
|
|
237
|
+
if (relationIndex && relationIndexSource === sources) return relationIndex;
|
|
238
|
+
|
|
239
|
+
relationIndex = buildRelationIndex(sources);
|
|
240
|
+
relationIndexSource = sources;
|
|
241
|
+
|
|
242
|
+
return relationIndex;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async function resolveRelated(
|
|
246
|
+
dataSourceId: string,
|
|
247
|
+
edge: 'parentsByChild' | 'childrenByParent'
|
|
248
|
+
): Promise<DataSource[]> {
|
|
249
|
+
const index = await getRelationIndex();
|
|
250
|
+
const ids = index[edge].get(dataSourceId);
|
|
251
|
+
|
|
252
|
+
if (!ids) return [];
|
|
253
|
+
|
|
254
|
+
const out: DataSource[] = [];
|
|
255
|
+
|
|
256
|
+
for (const id of ids) {
|
|
257
|
+
const match = index.byId.get(id);
|
|
258
|
+
|
|
259
|
+
if (match) out.push(match);
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return out;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async function listParentDataSources(dataSourceId: string): Promise<DataSource[]> {
|
|
266
|
+
return resolveRelated(dataSourceId, 'parentsByChild');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function listChildDataSources(dataSourceId: string): Promise<DataSource[]> {
|
|
270
|
+
return resolveRelated(dataSourceId, 'childrenByParent');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async function listParentDataSourceFields(dataSourceId: string): Promise<DataSourceField[]> {
|
|
274
|
+
return (await listParentDataSources(dataSourceId)).flatMap(ds => ds.fields ?? []);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function listChildDataSourceFields(dataSourceId: string): Promise<DataSourceField[]> {
|
|
278
|
+
return (await listChildDataSources(dataSourceId)).flatMap(ds => ds.fields ?? []);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
return {
|
|
282
|
+
listApps,
|
|
283
|
+
list,
|
|
284
|
+
listByAppSlug,
|
|
285
|
+
listByAppId,
|
|
286
|
+
getById,
|
|
287
|
+
getBySlug,
|
|
288
|
+
getFields,
|
|
289
|
+
getFieldById,
|
|
290
|
+
getFieldBySlug,
|
|
291
|
+
getEnumsByFieldId,
|
|
292
|
+
getEnumById,
|
|
293
|
+
listParentDataSources,
|
|
294
|
+
listChildDataSources,
|
|
295
|
+
listParentDataSourceFields,
|
|
296
|
+
listChildDataSourceFields
|
|
297
|
+
};
|
|
298
|
+
}
|