@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
package/src/types.ts ADDED
@@ -0,0 +1,871 @@
1
+ import { type RestApiClient } from '@kivacore/api-client';
2
+
3
+ // --- Tenant Preferences ---
4
+
5
+ export interface TenantPreferences {
6
+ date_format?: string;
7
+ date_time_format?: string;
8
+ long_date_format?: string;
9
+ time_format?: string;
10
+ time_zone?: string;
11
+ locale?: string;
12
+ thousand_separator?: string;
13
+ decimal_separator?: string;
14
+ decimal_precision?: number;
15
+ [key: string]: unknown;
16
+ }
17
+
18
+ export interface TenantPreferenceSummary {
19
+ preferences: TenantPreferences | null;
20
+ tenant: Record<string, unknown> | null;
21
+ product: Record<string, unknown> | null;
22
+ }
23
+
24
+ // --- Date Utils ---
25
+
26
+ export interface DateUtilsConfig {
27
+ preferences: TenantPreferences;
28
+ userTimezone?: string;
29
+ /**
30
+ * Language for day and month names (`l`, `D`, `F`, `M`), e.g. `tr`,
31
+ * `tr_TR` or `de-DE`. Defaults to English; an unknown tag falls back to
32
+ * English too.
33
+ */
34
+ locale?: string;
35
+ }
36
+
37
+ export interface FormatOptions {
38
+ format?: string;
39
+ timezone?: string;
40
+ }
41
+
42
+ export interface DateUtils {
43
+ formatDate(date: string | Date, options?: FormatOptions): string | null;
44
+ formatDateTime(date: string | Date, options?: FormatOptions): string | null;
45
+ formatDateLong(date: string | Date, options?: FormatOptions): string | null;
46
+ toUserTimezone(date: string | Date): Date;
47
+ }
48
+
49
+ // --- Number Utils ---
50
+
51
+ export type NumberWordLang = 'TR' | 'EN';
52
+
53
+ export type CurrencyCode = 'TRY' | 'EUR' | 'USD' | 'GBP' | 'JPY';
54
+
55
+ export interface NumberFormatOptions {
56
+ decimalPrecision?: number;
57
+ decimalSeparator?: string;
58
+ thousandSeparator?: string;
59
+ }
60
+
61
+ export interface NumberToWordsOptions {
62
+ lang?: NumberWordLang;
63
+ currency?: CurrencyCode;
64
+ useSpaces?: boolean;
65
+ }
66
+
67
+ export interface NumberUtilsConfig {
68
+ preferences: TenantPreferences;
69
+ }
70
+
71
+ export interface NumberUtils {
72
+ formatNumber(value: number, options?: NumberFormatOptions): string | null;
73
+ }
74
+
75
+ // --- Template Engine ---
76
+
77
+ export interface TemplateEngineConfig {
78
+ dateUtils?: DateUtils;
79
+ numberUtils?: NumberUtils;
80
+ extraJsonataBindings?: Record<string, unknown>;
81
+ user?: Record<string, unknown> | null;
82
+ /**
83
+ * Extra Handlebars helpers registered after the built-in set. Lets consumers
84
+ * (e.g. the HtmlTemplateEditor) add domain helpers like `formatCurrency`,
85
+ * `lineNet`, `sumGrandTotal`, comparison helpers, etc.
86
+ */
87
+ additionalHelpers?: Record<string, (...args: any[]) => any>;
88
+ }
89
+
90
+ export interface TemplateEngine {
91
+ compileTpl(templateString: string): (data: any) => Promise<string>;
92
+ compileFormula(expression: string, data?: any): Promise<any>;
93
+ jsonataHelpers: Record<string, any>;
94
+ }
95
+
96
+ // --- App Config ---
97
+
98
+ export interface AppConfig {
99
+ id: string;
100
+ data: Record<string, unknown>;
101
+ status: number;
102
+ tenant_app_id: string;
103
+ created_by: string | null;
104
+ created_on: string;
105
+ last_modified_by: string | null;
106
+ last_modified_on: string;
107
+ }
108
+
109
+ export interface UpsertAppConfigBody {
110
+ data?: Record<string, unknown>;
111
+ status?: number;
112
+ }
113
+
114
+ export interface AppConfigClient {
115
+ get(): Promise<AppConfig>;
116
+ upsert(body: UpsertAppConfigBody): Promise<AppConfig>;
117
+ remove(): Promise<void>;
118
+ }
119
+
120
+ export interface CreateAppConfigClientOptions {
121
+ /**
122
+ * Optional `InventoryClient`. When provided, `get` reads through the
123
+ * inventory's per-app config cache and `upsert` / `remove` patch it in place
124
+ * (`setAppConfig`) — so a shared inventory instance stays consistent without
125
+ * a refetch.
126
+ */
127
+ inventory?: InventoryClient;
128
+ }
129
+
130
+ // --- User App Config ---
131
+
132
+ export interface UserAppConfig {
133
+ id: string;
134
+ data: Record<string, unknown>;
135
+ status: number;
136
+ tenant_app_id: string;
137
+ user_id: string;
138
+ created_by: string | null;
139
+ created_on: string;
140
+ last_modified_by: string | null;
141
+ last_modified_on: string;
142
+ }
143
+
144
+ export interface UpsertUserAppConfigBody {
145
+ data?: Record<string, unknown>;
146
+ status?: number;
147
+ }
148
+
149
+ export interface UserAppConfigClient {
150
+ get(): Promise<UserAppConfig>;
151
+ upsert(body: UpsertUserAppConfigBody): Promise<UserAppConfig>;
152
+ remove(): Promise<void>;
153
+ }
154
+
155
+ export interface CreateUserAppConfigClientOptions {
156
+ /**
157
+ * Optional `InventoryClient`. When provided, `get` reads through the
158
+ * inventory's per-app user-config cache and `upsert` / `remove` patch it in
159
+ * place (`setUserAppConfig`).
160
+ */
161
+ inventory?: InventoryClient;
162
+ }
163
+
164
+ // --- User ---
165
+
166
+ /**
167
+ * A tenant user as returned by `GET /v1/users` (the `UserEntity` shape).
168
+ * Distinct from signin's `DocyrusUser` (`GET /v1/users/me`), which carries
169
+ * resolved `roles` / `aclRules` for the *current* user.
170
+ */
171
+ export interface User {
172
+ id: string;
173
+ email: string;
174
+ firstname?: string | null;
175
+ lastname?: string | null;
176
+ name?: string | null;
177
+ gender?: string | null;
178
+ mobile?: string | null;
179
+ photo?: string | null;
180
+ time_zone?: string | null;
181
+ language?: string | null;
182
+ job_title?: string | null;
183
+ primary_role?: string | null;
184
+ role?: string[] | null;
185
+ date_of_birth?: string | null;
186
+ notify_user?: boolean;
187
+ tenant_user_hierarchy_unit_id?: string | null;
188
+ no?: string | null;
189
+ created_by?: string | null;
190
+ created_on?: string | null;
191
+ last_modified_by?: string | null;
192
+ last_modified_on?: string | null;
193
+ [key: string]: unknown;
194
+ }
195
+
196
+ // --- Data View ---
197
+
198
+ export interface DataView {
199
+ id: string;
200
+ name: string;
201
+ description: string | null;
202
+ tenant_data_source_id: string;
203
+ tenant_app_id?: string | null;
204
+ columns: Record<string, unknown> | null;
205
+ filters: Record<string, unknown> | null;
206
+ sort: Record<string, unknown> | null;
207
+ color: string | null;
208
+ icon: string | null;
209
+ color_rules: Record<string, unknown> | null;
210
+ quick_filter_fields: string[] | null;
211
+ is_default: boolean;
212
+ archived: boolean;
213
+ sort_order: number | null;
214
+ created_by: string | null;
215
+ created_on: string;
216
+ last_modified_by: string | null;
217
+ last_modified_on: string;
218
+ }
219
+
220
+ export interface CreateDataViewBody {
221
+ name: string;
222
+ description?: string;
223
+ columns?: Record<string, unknown>;
224
+ filters?: Record<string, unknown>;
225
+ sort?: Record<string, unknown>;
226
+ color?: string;
227
+ icon?: string;
228
+ color_rules?: Record<string, unknown>;
229
+ quick_filter_fields?: string[];
230
+ is_default?: boolean;
231
+ sort_order?: number;
232
+ }
233
+
234
+ export interface UpdateDataViewBody {
235
+ name?: string;
236
+ description?: string;
237
+ columns?: Record<string, unknown>;
238
+ filters?: Record<string, unknown>;
239
+ sort?: Record<string, unknown>;
240
+ color?: string;
241
+ icon?: string;
242
+ color_rules?: Record<string, unknown>;
243
+ quick_filter_fields?: string[];
244
+ is_default?: boolean;
245
+ sort_order?: number;
246
+ archived?: boolean;
247
+ }
248
+
249
+ export interface ListDataViewsParams {
250
+ appId?: string;
251
+ }
252
+
253
+ export interface DataViewClient {
254
+ list(params?: ListDataViewsParams): Promise<DataView[]>;
255
+ get(viewId: string): Promise<DataView>;
256
+ create(body: CreateDataViewBody): Promise<DataView>;
257
+ update(viewId: string, body: UpdateDataViewBody): Promise<DataView>;
258
+ remove(viewId: string): Promise<void>;
259
+ }
260
+
261
+ export interface CreateDataViewClientOptions {
262
+ /**
263
+ * Optional `InventoryClient`. When provided, `list` and `get` read from
264
+ * the embedded `views` array on the cached data source (one network call
265
+ * across the whole inventory). Mutations patch the cache directly via
266
+ * `upsertDataView` / `removeDataView` — no refetch.
267
+ */
268
+ inventory?: InventoryClient;
269
+ }
270
+
271
+ // --- Data Form ---
272
+
273
+ export interface DataForm {
274
+ id: string;
275
+ name: string;
276
+ description?: string | null;
277
+ title: string | null;
278
+ subtopic: string | null;
279
+ color: string | null;
280
+ icon: string | null;
281
+ layout: Record<string, unknown> | null;
282
+ tenant_data_source_id: string;
283
+ is_default: boolean;
284
+ archived?: boolean;
285
+ status?: number;
286
+ created_by?: string | null;
287
+ created_on?: string | null;
288
+ last_modified_by?: string | null;
289
+ last_modified_on?: string | null;
290
+ /** Present on embedded forms (data-source `expand=forms`). */
291
+ ownership?: 'SYSTEM' | 'APP' | 'CUSTOM' | string;
292
+ /** Present on embedded forms. Owning product ids. */
293
+ ownerProductId?: string[];
294
+ /** Present (`true`) on embedded forms when CUSTOM ownership shadows defaults. */
295
+ customized?: boolean;
296
+ }
297
+
298
+ export interface CreateDataFormBody {
299
+ name: string;
300
+ description?: string;
301
+ title?: string;
302
+ subtopic?: string;
303
+ color?: string;
304
+ icon?: string;
305
+ layout?: Record<string, unknown>;
306
+ is_default?: boolean;
307
+ status?: number;
308
+ }
309
+
310
+ export interface UpdateDataFormBody {
311
+ name?: string;
312
+ description?: string;
313
+ title?: string;
314
+ subtopic?: string;
315
+ color?: string;
316
+ icon?: string;
317
+ layout?: Record<string, unknown>;
318
+ is_default?: boolean;
319
+ status?: number;
320
+ archived?: boolean;
321
+ }
322
+
323
+ export interface DataFormClient {
324
+ list(): Promise<DataForm[]>;
325
+ get(formId: string): Promise<DataForm>;
326
+ create(body: CreateDataFormBody): Promise<DataForm>;
327
+ update(formId: string, body: UpdateDataFormBody): Promise<DataForm>;
328
+ remove(formId: string): Promise<void>;
329
+ }
330
+
331
+ export interface CreateDataFormClientOptions {
332
+ /**
333
+ * Optional `InventoryClient`. When provided, `list` and `get` read from
334
+ * the embedded `forms` array on the cached data source (one network call
335
+ * across the whole inventory). Mutations patch the cache directly via
336
+ * `upsertDataForm` / `removeDataForm` — no refetch.
337
+ *
338
+ * Note: embedded forms are a reduced shape (no audit timestamps, no
339
+ * `status`); use a non-inventory-backed form client when you need those.
340
+ */
341
+ inventory?: InventoryClient;
342
+ }
343
+
344
+ // --- Data Source Metadata ---
345
+
346
+ export type DataSourceExpand
347
+ = | 'children'
348
+ | 'fields'
349
+ | 'views'
350
+ | 'forms'
351
+ | 'acl'
352
+ | 'templates'
353
+ | 'client-configuration'
354
+ | 'misc';
355
+
356
+ export interface DataSourceEnumOption {
357
+ id: string;
358
+ slug: string;
359
+ name: string;
360
+ color: string | null;
361
+ icon: string | null;
362
+ sortOrder: number;
363
+ isFinalOption: boolean;
364
+ }
365
+
366
+ export interface DataSourceField {
367
+ id: string;
368
+ name: string;
369
+ slug: string;
370
+ type: string;
371
+ required?: boolean;
372
+ default_value?: unknown;
373
+ description?: string | null;
374
+ /** Present on select-type fields when `expand=fields` is requested. */
375
+ enums?: DataSourceEnumOption[];
376
+ [key: string]: unknown;
377
+ }
378
+
379
+ export interface DataSource {
380
+ id: string;
381
+ name: string;
382
+ slug: string;
383
+ appSlug?: string;
384
+ app_slug?: string;
385
+ tenant_app_id?: string | null;
386
+ fields?: DataSourceField[];
387
+ /** Present when `expand=views`. Normalized to full `DataView` shape (`archived: false`). */
388
+ views?: DataView[];
389
+ /** Present when `expand=forms`. Normalized from the embedded camelCased shape. */
390
+ forms?: DataForm[];
391
+ /** Present when `expand=forms`. Data-source form actions. */
392
+ actions?: Array<Record<string, unknown>>;
393
+ children?: DataSource[];
394
+ [key: string]: unknown;
395
+ }
396
+
397
+ export interface DataSourceListParams {
398
+ expand?: string;
399
+ }
400
+
401
+ export interface DataSourceApp {
402
+ id: string;
403
+ name: string;
404
+ slug: string;
405
+ logo_url?: string | null;
406
+ status?: string;
407
+ [key: string]: unknown;
408
+ }
409
+
410
+ export interface DataSourceClient {
411
+ listApps(): Promise<DataSourceApp[]>;
412
+ list(params?: DataSourceListParams): Promise<DataSource[]>;
413
+ listByAppSlug(appSlug: string, params?: DataSourceListParams): Promise<DataSource[]>;
414
+ listByAppId(appId: string, params?: DataSourceListParams): Promise<DataSource[]>;
415
+ getById(dataSourceId: string, params?: DataSourceListParams): Promise<DataSource>;
416
+ getBySlug(appSlug: string, dataSourceSlug: string, params?: DataSourceListParams): Promise<DataSource>;
417
+ /**
418
+ * Returns the field metadata for a data source. Served from the inventory
419
+ * cache when one is wired in (fields are embedded via `dataSourcesExpand`);
420
+ * otherwise fetched with `expand=fields`. Empty array when the data source
421
+ * has no fields.
422
+ */
423
+ getFields(dataSourceId: string): Promise<DataSourceField[]>;
424
+ /** Finds a field of a data source by its id. `undefined` when not found. */
425
+ getFieldById(dataSourceId: string, fieldId: string): Promise<DataSourceField | undefined>;
426
+ /** Finds a field of a data source by its slug. `undefined` when not found. */
427
+ getFieldBySlug(dataSourceId: string, fieldSlug: string): Promise<DataSourceField | undefined>;
428
+ /**
429
+ * Returns the enum options of a select-type field. Empty array when the
430
+ * field has no enums or the field itself isn't found.
431
+ */
432
+ getEnumsByFieldId(dataSourceId: string, fieldId: string): Promise<DataSourceEnumOption[]>;
433
+ /** Finds a single enum option of a field by its id. `undefined` when not found. */
434
+ getEnumById(dataSourceId: string, fieldId: string, enumId: string): Promise<DataSourceEnumOption | undefined>;
435
+ /**
436
+ * Lists the data sources this one links **to** through its `relation` fields —
437
+ * its parents (the `relation_data_source_id` targets). Derived from cached
438
+ * field metadata via a memoized relation index, so it's fast and issues no
439
+ * per-call network request when backed by an inventory. Distinct, self-links
440
+ * excluded, unreachable targets (no permission) omitted. `[]` when none.
441
+ */
442
+ listParentDataSources(dataSourceId: string): Promise<DataSource[]>;
443
+ /**
444
+ * Lists the data sources that link **to** this one through a `relation` field —
445
+ * its children (data sources whose `relation_data_source_id` equals this id).
446
+ * Same index/perf characteristics as `listParentDataSources`. `[]` when none.
447
+ */
448
+ listChildDataSources(dataSourceId: string): Promise<DataSource[]>;
449
+ /**
450
+ * The combined `fields` of every parent data source (see
451
+ * `listParentDataSources`), flattened for a field selector. Field ids are
452
+ * globally unique so there are no duplicates; use `listParentDataSources` if
453
+ * you need the fields grouped by their owning data source.
454
+ */
455
+ listParentDataSourceFields(dataSourceId: string): Promise<DataSourceField[]>;
456
+ /** The combined `fields` of every child data source (see `listChildDataSources`). */
457
+ listChildDataSourceFields(dataSourceId: string): Promise<DataSourceField[]>;
458
+ }
459
+
460
+ export interface CreateDataSourceClientOptions {
461
+ /**
462
+ * Optional `InventoryClient`. When provided, every read method consults
463
+ * the inventory cache first — cached data sources arrive pre-populated
464
+ * with their embedded `views`, `forms`, and `fields` (with enum options)
465
+ * thanks to `dataSourcesExpand`. Passing a custom `params.expand`
466
+ * bypasses the cache.
467
+ */
468
+ inventory?: InventoryClient;
469
+ }
470
+
471
+ // --- Inventory ---
472
+
473
+ export interface ListInventoryParams {
474
+ appId?: string | string[];
475
+ dataSourceId?: string | string[];
476
+ }
477
+
478
+ /** Identifies which inventory resource a load step is processing. */
479
+ export type InventoryLoadStepId
480
+ = | 'apps'
481
+ | 'data-sources'
482
+ | 'users'
483
+ | 'brands'
484
+ | 'preferences'
485
+ | 'app-config'
486
+ | 'user-app-config';
487
+
488
+ /**
489
+ * Lifecycle phase of an `InventoryLoadProgress` event.
490
+ * - `start` — the step's fetch is about to begin
491
+ * - `success` — the step's fetch completed
492
+ * - `error` — the step's fetch threw (load will reject right after)
493
+ * - `complete` — every step finished; the terminal aggregate event
494
+ */
495
+ export type InventoryLoadPhase = 'start' | 'success' | 'error' | 'complete';
496
+
497
+ export interface InventoryLoadProgress {
498
+ /** The step this event refers to, or `null` for the terminal `complete` event. */
499
+ step: InventoryLoadStepId | null;
500
+ /**
501
+ * The app id for per-app config steps (`app-config` / `user-app-config`);
502
+ * `undefined` for tenant-wide steps and the terminal `complete` event.
503
+ */
504
+ appId?: string;
505
+ /** Default English message suitable for a progress bar label. */
506
+ message: string;
507
+ /** 1-based index of the current step. */
508
+ current: number;
509
+ /** Total number of steps in the load sequence. */
510
+ total: number;
511
+ /** Completion fraction in `[0, 1]` — drive a determinate progress bar with this. */
512
+ ratio: number;
513
+ /** Lifecycle phase of this event. */
514
+ phase: InventoryLoadPhase;
515
+ /** Present only when `phase === 'error'`: the thrown value. */
516
+ error?: unknown;
517
+ }
518
+
519
+ export interface InventoryLoadResult {
520
+ apps: DataSourceApp[];
521
+ dataSources: DataSource[];
522
+ users: User[];
523
+ brands: Brand[];
524
+ preferences: TenantPreferences;
525
+ /** Per-app config keyed by app id — only populated for `configAppIds`. `null` = no config exists. */
526
+ appConfigs: Record<string, AppConfig | null>;
527
+ /** Per-app user-config keyed by app id — only populated for `configAppIds`. `null` = no config exists. */
528
+ userAppConfigs: Record<string, UserAppConfig | null>;
529
+ }
530
+
531
+ export interface InventoryLoadOptions {
532
+ /**
533
+ * Invoked for every lifecycle event: a `start`/`success` pair per step, an
534
+ * `error` if a step throws, and one terminal `complete`. Use `step` to map
535
+ * to your own i18n messages and `ratio` to drive a progress bar.
536
+ */
537
+ onProgress?: (progress: InventoryLoadProgress) => void;
538
+ /**
539
+ * When `true` (the default), invalidates the caches for the resources about
540
+ * to be loaded so the sequence always issues fresh network calls. Set to
541
+ * `false` to reuse still-fresh cache entries (steps then resolve instantly).
542
+ */
543
+ force?: boolean;
544
+ /**
545
+ * Which tenant-wide steps to run, in order. Defaults to `['apps',
546
+ * 'data-sources', 'users', 'brands', 'preferences']`. Narrow it when the
547
+ * signed-in user lacks a scope (e.g. drop `'users'`, which needs
548
+ * `Users.Read.All`) or when you only need a subset.
549
+ */
550
+ include?: InventoryLoadStepId[];
551
+ /**
552
+ * App ids whose per-app config + user-config to warm as extra steps
553
+ * (appended after the tenant-wide steps, two steps per id). Missing configs
554
+ * are cached as `null` (a `404` is not treated as an error).
555
+ *
556
+ * When omitted, defaults to the current app from the `VITE_APP_ID` env var
557
+ * (a single-element list), or no config steps at all when that is unset.
558
+ * Pass an explicit `[]` to force-skip config warm-up regardless of the env.
559
+ */
560
+ configAppIds?: string[];
561
+ }
562
+
563
+ /**
564
+ * Minimal structural subset of the Web Storage API. Both `window.localStorage`
565
+ * and `window.sessionStorage` satisfy it, so you can also pass a custom adapter
566
+ * (an in-memory shim for tests, a namespaced wrapper, an async-backed mirror,
567
+ * etc.). Only synchronous `getItem` / `setItem` / `removeItem` are used.
568
+ */
569
+ export interface InventoryStorage {
570
+ getItem(key: string): string | null;
571
+ setItem(key: string, value: string): void;
572
+ removeItem(key: string): void;
573
+ }
574
+
575
+ /**
576
+ * Where an `InventoryClient` persists its cache:
577
+ * - `'local'` — `window.localStorage` (survives tab close / browser restart)
578
+ * - `'session'` — `window.sessionStorage` (cleared when the tab closes)
579
+ * - a custom `InventoryStorage` adapter
580
+ */
581
+ export type InventoryStorageOption = 'local' | 'session' | InventoryStorage;
582
+
583
+ export interface InventoryClientOptions {
584
+ /**
585
+ * Cache time-to-live in milliseconds. Pass `Infinity` to cache until
586
+ * `refresh()` / `invalidate*()` is called. Defaults to 5 minutes.
587
+ */
588
+ ttlMs?: number;
589
+ /**
590
+ * Comma-separated `expand` value used by `listDataSources`. Defaults to
591
+ * `'views,forms,fields'` so every cached data source carries its views,
592
+ * forms, and field metadata (with enum options) — `listDataViews` and
593
+ * `listDataForms` then derive from this single fetch with no extra
594
+ * network round-trips.
595
+ */
596
+ dataSourcesExpand?: string;
597
+ /**
598
+ * Persist the cache so it survives page reloads. `'local'` uses
599
+ * `window.localStorage`, `'session'` uses `window.sessionStorage`, or pass any
600
+ * `InventoryStorage` adapter. Omit for an in-memory-only cache (the default).
601
+ *
602
+ * Persisted entries keep their `fetchedAt`, so `ttlMs` still applies across
603
+ * reloads: a hydrated snapshot older than the TTL is treated as stale and
604
+ * refetched on first read. Resolution is defensive — if the chosen storage is
605
+ * unavailable (SSR, private mode, disabled cookies, quota/security errors) the
606
+ * client silently falls back to in-memory and never throws.
607
+ */
608
+ storage?: InventoryStorageOption;
609
+ /**
610
+ * Key under which the persisted snapshot is stored. Defaults to
611
+ * `'docyrus:inventory'`. Namespace it per tenant/user (e.g.
612
+ * `` `docyrus:inventory:${tenantId}` ``) so separate sessions don't read or
613
+ * overwrite one another's cache. Ignored when `storage` is unset.
614
+ */
615
+ storageKey?: string;
616
+ }
617
+
618
+ export interface InventoryClient {
619
+ listApps(): Promise<DataSourceApp[]>;
620
+ /**
621
+ * Source of truth. Triggers one call to `/v1/apps/data-sources` with the
622
+ * configured `dataSourcesExpand`; subsequent reads (including the derived
623
+ * `listDataViews` / `listDataForms`) are served from this cache.
624
+ */
625
+ listDataSources(): Promise<DataSource[]>;
626
+ /**
627
+ * Lists every tenant user. Backed by one `GET /v1/users` (requires the
628
+ * `Users.Read.All` scope). Cached separately with the same TTL.
629
+ */
630
+ listUsers(): Promise<User[]>;
631
+ /** Lists every tenant brand. Backed by one `GET /v1/tenant/brands`. Cached separately. */
632
+ listBrands(): Promise<Brand[]>;
633
+ /** Fetches the tenant preferences. Backed by one `GET /v1/tenant/preferences`. Cached separately. */
634
+ getPreferences(): Promise<TenantPreferences>;
635
+ /**
636
+ * Fetches an app's config (`GET /v1/tenant/apps/{appId}/config`), cached per
637
+ * app id. Resolves to `null` when no config exists (`404`) — that `null` is
638
+ * cached too, so repeat calls don't re-hit the API.
639
+ */
640
+ getAppConfig(appId: string): Promise<AppConfig | null>;
641
+ /** Same as `getAppConfig`, for the per-user app config (`.../user-config`). */
642
+ getUserAppConfig(appId: string): Promise<UserAppConfig | null>;
643
+ /**
644
+ * Warms the inventory in one sequence, emitting progress events per step via
645
+ * `options.onProgress`. Intended to be called once right after sign-in —
646
+ * behind a progress dialog — so every later read across all inventory-backed
647
+ * clients is a cache hit. Runs `options.include` (default: apps, data
648
+ * sources, users, brands, preferences) then any `options.configAppIds`
649
+ * config steps. Resolves with the loaded resources; rejects (after an
650
+ * `error` event) if a step fails.
651
+ */
652
+ load(options?: InventoryLoadOptions): Promise<InventoryLoadResult>;
653
+ /** Derived from cached data sources' embedded `views`. No network call. */
654
+ listDataViews(params?: ListInventoryParams): Promise<DataView[]>;
655
+ /** Derived from cached data sources' embedded `forms`. No network call. */
656
+ listDataForms(params?: ListInventoryParams): Promise<DataForm[]>;
657
+ /** Drop every cached entry and re-fetch apps + data sources. */
658
+ refresh(): Promise<void>;
659
+ invalidateApps(): void;
660
+ invalidateDataSources(): void;
661
+ invalidateUsers(): void;
662
+ invalidateBrands(): void;
663
+ invalidatePreferences(): void;
664
+ /** Drop one app's cached config, or all cached app configs when `appId` is omitted. */
665
+ invalidateAppConfig(appId?: string): void;
666
+ /** Drop one app's cached user-config, or all cached user-configs when `appId` is omitted. */
667
+ invalidateUserAppConfig(appId?: string): void;
668
+ /**
669
+ * Insert or replace a view inside the cached data source identified by
670
+ * `view.tenant_data_source_id`. Called by `createDataViewClient` after
671
+ * `create` / `update` so a successful mutation patches the cache without
672
+ * forcing a refetch. No-op when the data source isn't in the cache yet.
673
+ */
674
+ upsertDataView(view: DataView): void;
675
+ /** Remove a view from whichever cached data source carries it. */
676
+ removeDataView(viewId: string): void;
677
+ /** Same as `upsertDataView`, for forms. */
678
+ upsertDataForm(form: DataForm): void;
679
+ /** Same as `removeDataView`, for forms. */
680
+ removeDataForm(formId: string): void;
681
+ /**
682
+ * Insert or replace a brand in the cached brand list by id. Called by
683
+ * `createBrandClient` after `create` / `update`. No-op until the brand cache
684
+ * has been populated (`listBrands`).
685
+ */
686
+ upsertBrand(brand: Brand): void;
687
+ /** Remove a brand from the cached brand list by id. */
688
+ removeBrand(brandId: string): void;
689
+ /** Set (or clear, with `null`) an app's cached config. Called by `createAppConfigClient` after a mutation. */
690
+ setAppConfig(appId: string, config: AppConfig | null): void;
691
+ /** Set (or clear, with `null`) an app's cached user-config. Called by `createUserAppConfigClient` after a mutation. */
692
+ setUserAppConfig(appId: string, config: UserAppConfig | null): void;
693
+ }
694
+
695
+ // --- Tenant Brand ---
696
+
697
+ export type BrandColorScheme = 'light' | 'dark';
698
+
699
+ export type BrandActiveVoicePreference = 'prefer_active' | 'neutral' | 'allow_passive';
700
+
701
+ export type BrandDirectness = 'direct' | 'balanced' | 'explanatory';
702
+
703
+ export type BrandEmojiPolicy = 'none' | 'limited' | 'allowed';
704
+
705
+ export type BrandFormalityLevel = 'formal' | 'semi_formal' | 'conversational';
706
+
707
+ export type BrandMetricEmphasis = 'numbers' | 'percentages' | 'balanced';
708
+
709
+ export type BrandSlideDensity = 'minimal' | 'standard' | 'dense';
710
+
711
+ export type BrandIllustrationStyle = 'flat' | 'line' | 'isometric' | '3d' | 'mixed';
712
+
713
+ export interface Brand {
714
+ id: string;
715
+ name: string;
716
+ description: string | null;
717
+ website_url: string | null;
718
+ is_default: boolean;
719
+ archived: boolean;
720
+
721
+ color_scheme: BrandColorScheme | string | null;
722
+ color_primary: string | null;
723
+ color_secondary: string | null;
724
+ color_accent: string | null;
725
+ color_background: string | null;
726
+ color_text_primary: string | null;
727
+ color_text_secondary: string | null;
728
+ color_link: string | null;
729
+ color_success: string | null;
730
+ color_warning: string | null;
731
+ color_error: string | null;
732
+
733
+ font_family_primary: string | null;
734
+ font_family_heading: string | null;
735
+ font_family_code: string | null;
736
+ font_size_h1: string | null;
737
+ font_size_h2: string | null;
738
+ font_size_h3: string | null;
739
+ font_size_body: string | null;
740
+ font_weight_light: number | null;
741
+ font_weight_regular: number | null;
742
+ font_weight_medium: number | null;
743
+ font_weight_bold: number | null;
744
+ line_height_heading: string | null;
745
+ line_height_body: string | null;
746
+ fonts: Array<{ family: string }> | null;
747
+
748
+ spacing_base_unit: number | null;
749
+ spacing_border_radius: string | null;
750
+ spacing_padding: Record<string, unknown> | null;
751
+ spacing_margins: Record<string, unknown> | null;
752
+
753
+ component_button_primary: Record<string, unknown> | null;
754
+ component_button_secondary: Record<string, unknown> | null;
755
+ component_input: Record<string, unknown> | null;
756
+
757
+ logo_url: string | null;
758
+ favicon_url: string | null;
759
+ og_image_url: string | null;
760
+
761
+ icon_style: Record<string, unknown> | null;
762
+ animations: Record<string, unknown> | null;
763
+ layout: Record<string, unknown> | null;
764
+ personality: Record<string, unknown> | null;
765
+
766
+ active_voice_preference: BrandActiveVoicePreference | string | null;
767
+ directness: BrandDirectness | string | null;
768
+ emoji_policy: BrandEmojiPolicy | string | null;
769
+ formality_level: BrandFormalityLevel | string | null;
770
+ grammar_do: string[] | null;
771
+ grammar_dont: string[] | null;
772
+ metric_emphasis: BrandMetricEmphasis | string | null;
773
+ messaging_framework: Record<string, unknown> | null;
774
+ tone_by_context: Record<string, unknown> | null;
775
+ voice_intent: string[] | null;
776
+ preferred_terminology: string[] | null;
777
+ restricted_terminology: string[] | null;
778
+ prohibited_phrases: string[] | null;
779
+ slogans_and_taglines: string[] | null;
780
+ punctuation_rules: string | null;
781
+ style_rules: string | null;
782
+ preferred_sentence_length: number | null;
783
+
784
+ cover_slide_layout: string | null;
785
+ section_divider_slides: string | null;
786
+ closing_and_cta_slides: string | null;
787
+ slide_density: BrandSlideDensity | string | null;
788
+ text_visual_balance: string | null;
789
+ max_text_per_slide: number | null;
790
+ heading_to_body_ratio: number | string | null;
791
+
792
+ preferred_chart_colors: string[] | null;
793
+ preferred_chart_types: string[] | null;
794
+ annotation_labeling_rules: string | null;
795
+ competitive_comparison_rules: string | null;
796
+
797
+ illustration_style: BrandIllustrationStyle | string | null;
798
+ illustration_notes: string | null;
799
+ use_human_figures: boolean | null;
800
+ visual_realism_level: number | null;
801
+
802
+ industry_constraints: string[] | null;
803
+ regulatory_considerations: string[] | null;
804
+ cultural_sensitivity_guidelines: string | null;
805
+ legal_ethical_boundaries: string | null;
806
+
807
+ created_by: string | null;
808
+ created_on: string;
809
+ last_modified_by: string | null;
810
+ last_modified_on: string | null;
811
+ }
812
+
813
+ export interface CreateBrandBody extends Partial<Omit<Brand, 'id' | 'name' | 'archived' | 'created_by' | 'created_on' | 'last_modified_by' | 'last_modified_on'>> {
814
+ name: string;
815
+ }
816
+
817
+ export type UpdateBrandBody = Partial<Omit<Brand, 'id' | 'created_by' | 'created_on' | 'last_modified_by' | 'last_modified_on'>>;
818
+
819
+ export interface FetchBrandFromWebsiteResponse {
820
+ brand: Partial<Brand> & { id: string };
821
+ scrapedBranding: Record<string, unknown>;
822
+ }
823
+
824
+ export interface BrandClient {
825
+ list(): Promise<Brand[]>;
826
+ get(brandId: string): Promise<Brand>;
827
+ create(body: CreateBrandBody): Promise<Brand>;
828
+ update(brandId: string, body: UpdateBrandBody): Promise<Brand>;
829
+ remove(brandId: string): Promise<void>;
830
+ fetchFromWebsite(brandId: string): Promise<FetchBrandFromWebsiteResponse>;
831
+ }
832
+
833
+ export interface CreateBrandClientOptions {
834
+ /**
835
+ * Optional `InventoryClient`. When provided, `list` / `get` read from the
836
+ * inventory's brand cache and `create` / `update` / `remove` patch it in
837
+ * place (`upsertBrand` / `removeBrand`) — no refetch. `fetchFromWebsite`
838
+ * also refreshes the cached brand with the returned partial.
839
+ */
840
+ inventory?: InventoryClient;
841
+ }
842
+
843
+ // --- User Identity ---
844
+
845
+ export interface MicrosoftIdentityPayload {
846
+ sub: string;
847
+ oid?: string;
848
+ tid?: string;
849
+ email?: string;
850
+ name?: string;
851
+ preferred_username?: string;
852
+ [key: string]: unknown;
853
+ }
854
+
855
+ export interface GoogleIdentityPayload {
856
+ sub: string;
857
+ email?: string;
858
+ name?: string;
859
+ [key: string]: unknown;
860
+ }
861
+
862
+ export interface UserIdentityClient {
863
+ saveMicrosoft(payload: MicrosoftIdentityPayload): Promise<void>;
864
+ saveGoogle(payload: GoogleIdentityPayload): Promise<void>;
865
+ }
866
+
867
+ // --- App Utils ---
868
+
869
+ export interface AppUtilsConfig {
870
+ client: RestApiClient;
871
+ }