@startsimpli/integrations 0.2.67 → 0.2.68

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 CHANGED
@@ -189,6 +189,31 @@ the screens need the OPTIONAL peers `react-native`, `react-native-safe-area-cont
189
189
  5. Check without a login: launch with `-tgFakeNotes list` (or a note id such as `n1`) to see the screens over `createFakeVoiceApi`.
190
190
  6. `npx expo prebuild --platform ios`, then `npx expo run:ios --configuration Release` (Hermes). Signing and device install are per-Apple-team, see the template README.
191
191
 
192
+ ### Tabs: `FoundryTabsShell` and the shared corpus data layer (bd startsim-23np6.1)
193
+
194
+ Every Tandem web tab becomes an iOS tab from config. `NotesShell` is just the first preset.
195
+
196
+ | Export | What |
197
+ |---|---|
198
+ | `FoundryTabsShell({ tabs, initialTab?, initialDetail?, navigator? })` | Bottom tabs driven by `[{ key, label, icon?, render(ctx), safeArea?, resetOnLeave? }]`. A tab is mounted when first shown and then kept (hidden) so its state survives switching. `ctx` = `{ route, push(id, params?), back(), openTab(key, id?), active }`: `route` null = your list, set = your detail with Back. |
199
+ | `createTabsNavigator`, `parseTabLink`, `readTabLaunchTarget` | The framework-free state behind the shell. Deep links: `navigator.open('tracker', { id })`; launch args: `-tgTab tracker -tgDetail <id>`. |
200
+ | `createNativeCorpusApi({ baseUrl, authorizedFetch })` | One object: `entities` (`list`/`get`/`facets`), `relationships.list`, `corpus` (the web composers' own Library / Tracker / Planning api), `commitments.setStatus`, `ask` (POST `corpus/ask`), and `lists.*` paged controllers. |
201
+ | `createPagedList({ fetchPage })` | Server paging as a controller: `refresh`, `loadMore`, `setQuery`; state has `items`, `count`, `hasMore`, `error` and `ignoredFilters`. |
202
+ | `entityParams` / `reconcileFilters` / `toEntityPage` (also exported from the package root) | The ONE spelling of the tenant query (`page`, `page_size` max 200, `search`, `order=recent\|oldest\|relevance\|[-]attr.x`, `filters`, `attr`) and the check of the server's `applied_filters`. The web adapter uses the same function. |
203
+ | `createFakeNativeCorpusApi()`, `createFakeTenantHttp()` | The real adapters over an in-memory tenant that honours the same query contract (paging, order, attr operators, edge walks, applied/ignored report). `unsupported: ['attr.status']` plays a fork that ignores a filter. |
204
+
205
+ Rules every list tab follows: one server request per page (never load a list and filter/sort/page it on the phone); show `ignoredFilters` instead of presenting an unapplied filter as applied; sort by an attribute with `order: 'attr.due_at'` (undated rows sort last).
206
+
207
+ **Adding a tab** (a screen agent's whole job):
208
+
209
+ 1. **Controller** (pure, vitest): wrap `api.lists.<x>(query)` or `createPagedList` with your actions (for example `api.commitments.setStatus` optimistic with rollback). Put it in `src/native/<tab>/controller.ts` with tests that use `createFakeNativeCorpusApi()`.
210
+ 2. **Screen** (`src/native/<tab>/ListScreen.tsx`, `DetailScreen.tsx`): `@startsimpli/ui-native` primitives only; subscribe with `useSyncExternalStore`; `onEndReached={() => list.loadMore()}`.
211
+ 3. **Config entry**: `{ key: 'tracker', label: 'To-dos', render: ({ route, push, back }) => route ? <Detail id={route.id} onBack={back} /> : <List onOpen={(c) => push(c.id)} /> }`, added to the `tabs` array the app passes to `FoundryTabsShell` (or a new preset beside `NotesShell`).
212
+ 4. **Fake**: extend `sampleTenantEntities()` / `sampleTenantRelationships()` in `native/corpus/fake-data.ts` with rows for your tab. The fake tenant already serves them through the contract, so the simulator (`-tgTab <key>`) and the tests show real mapped data with no sign-in and no tenant.
213
+ 5. Export from `native/index.ts`, run `pnpm type-check && pnpm test` in this package.
214
+
215
+ Not wired yet: `mcpTokens` and `connectionsMe` (`src/api/*`) call a module-global `request()` that does not use `authorizedFetch`; the Connections / Connect Claude tabs need a `create*Api(fetch)` factory first.
216
+
192
217
  ## Verification
193
218
 
194
219
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.67",
3
+ "version": "0.2.68",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -0,0 +1,122 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ entityParams, facetParams, reconcileFilters, relationshipParams, toEntityPage,
4
+ } from '../corpus/entity-query';
5
+
6
+ describe('entityParams serialization', () => {
7
+ it('defaults to page 1 and always carries the type', () => {
8
+ expect(entityParams({ type: 'commitment' })).toEqual({ type: 'commitment', page: 1 });
9
+ });
10
+ it('caps page_size at the server max and floors it at 1', () => {
11
+ expect(entityParams({ type: 't', pageSize: 999 }).page_size).toBe(200);
12
+ expect(entityParams({ type: 't', pageSize: 0 }).page_size).toBeUndefined();
13
+ expect(entityParams({ type: 't', pageSize: 25, page: 3 })).toMatchObject({ page: 3, page_size: 25 });
14
+ });
15
+ it('sends a trimmed search, never a blank one', () => {
16
+ expect(entityParams({ type: 't', search: ' lease ' }).search).toBe('lease');
17
+ expect(entityParams({ type: 't', search: ' ' }).search).toBeUndefined();
18
+ });
19
+ it('sends relevance only alongside a search', () => {
20
+ expect(entityParams({ type: 't', order: 'relevance' }).order).toBeUndefined();
21
+ expect(entityParams({ type: 't', order: 'relevance', search: 'x' }).order).toBe('relevance');
22
+ expect(entityParams({ type: 't', order: 'oldest' }).order).toBe('oldest');
23
+ expect(entityParams({ type: 't', order: 'recent' }).order).toBe('recent');
24
+ });
25
+ it('orders by an attribute, either direction', () => {
26
+ expect(entityParams({ type: 't', order: 'attr.due_at' }).order).toBe('attr.due_at');
27
+ expect(entityParams({ type: 't', order: '-attr.progress' }).order).toBe('-attr.progress');
28
+ });
29
+ it('serializes every first-class filter', () => {
30
+ expect(entityParams({
31
+ type: 't',
32
+ filters: {
33
+ id: 'i', idIn: ['a', 'b'], externalId: 'e', externalIdIn: ['x,1', 'y'], source: 's', party: 'p', scope: '/ogmc',
34
+ occurredAfter: 'oa', occurredBefore: 'ob', createdAfter: 'ca', createdBefore: 'cb',
35
+ },
36
+ })).toMatchObject({
37
+ id: 'i', id__in: 'a,b', external_id: 'e', source: 's', party: 'p', scope: '/ogmc',
38
+ occurred_after: 'oa', occurred_before: 'ob', created_after: 'ca', created_before: 'cb',
39
+ });
40
+ });
41
+ it('sends external_id__in as a repeated parameter, not a comma list', () => {
42
+ expect(entityParams({ type: 't', filters: { externalIdIn: ['x,1', 'y'] } }).external_id__in).toEqual(['x,1', 'y']);
43
+ });
44
+ it('refuses more than 200 ids in a list rather than letting the server 400', () => {
45
+ const ids = Array.from({ length: 201 }, (_, i) => String(i));
46
+ expect(() => entityParams({ type: 't', filters: { idIn: ids } })).toThrow(/at most 200/);
47
+ expect(() => entityParams({ type: 't', filters: { externalIdIn: ids } })).toThrow(/at most 200/);
48
+ });
49
+ it('serializes an edge walk, and drops companions that have no target', () => {
50
+ expect(entityParams({
51
+ type: 't', filters: { relatedTo: 'f1', relatedVia: ['in_focus', 'about_focus'], relatedDirection: 'out', relatedDepth: 2 },
52
+ })).toMatchObject({ related_to: 'f1', related_via: 'in_focus,about_focus', related_direction: 'out', related_depth: 2 });
53
+ const orphan = entityParams({ type: 't', filters: { relatedDirection: 'out', relatedVia: 'in_focus' } });
54
+ expect(orphan.related_direction).toBeUndefined();
55
+ expect(orphan.related_via).toBeUndefined();
56
+ });
57
+ it('serializes attribute filters with operators and comma-joined __in lists', () => {
58
+ expect(entityParams({
59
+ type: 't',
60
+ attr: { status: 'open', status__in: ['open', 'blocked'], due_at__lte: '2026-11-01', done: false, n__gte: 0, skip: undefined, none: null, empty: [] },
61
+ })).toMatchObject({
62
+ 'attr.status': 'open', 'attr.status__in': 'open,blocked', 'attr.due_at__lte': '2026-11-01', 'attr.done': false, 'attr.n__gte': 0,
63
+ });
64
+ const p = entityParams({ type: 't', attr: { skip: undefined, none: null, empty: [] } });
65
+ expect(Object.keys(p)).toEqual(['type', 'page']);
66
+ });
67
+ });
68
+
69
+ describe('facetParams and relationshipParams', () => {
70
+ it('facets carry attr + under + the entity vocabulary, and never search/order', () => {
71
+ const p = facetParams({ type: 'source_document', facetAttr: 'path', under: '/Contracts', filters: { source: 'dropbox' }, attr: { status: 'open' } });
72
+ expect(p).toEqual({ type: 'source_document', attr: 'path', page: 1, under: '/Contracts', source: 'dropbox', 'attr.status': 'open' });
73
+ });
74
+ it('relationships serialize every filter', () => {
75
+ expect(relationshipParams({
76
+ source: 's', target: 't', entity: 'e', sourceIn: ['a'], targetIn: ['b', 'c'], entityIn: ['d'],
77
+ relType: ['in_focus', 'involves'], sourceType: 'commitment', targetType: 'focus', page: 2, pageSize: 50,
78
+ })).toEqual({
79
+ page: 2, page_size: 50, source: 's', target: 't', entity: 'e', source__in: 'a', target__in: 'b,c', entity__in: 'd',
80
+ rel_type: 'in_focus,involves', source_type: 'commitment', target_type: 'focus',
81
+ });
82
+ });
83
+ });
84
+
85
+ describe('reconcileFilters: an ignored filter is never shown as applied', () => {
86
+ const sent = entityParams({ type: 'commitment', search: 'x', order: 'attr.due_at', attr: { status: 'open' }, filters: { relatedTo: 'f', relatedDirection: 'out' } });
87
+ it('confirms what the server names in applied_filters', () => {
88
+ const v = reconcileFilters(sent, { applied_filters: ['type', 'search', 'order', 'attr.status', 'related_to', 'related_direction'] });
89
+ expect(v.ignored).toEqual([]);
90
+ expect(v.reported).toBe(true);
91
+ expect(v.applied).toContain('attr.status');
92
+ });
93
+ it('flags a filter the server left out or listed under ignored_filters', () => {
94
+ const v = reconcileFilters(sent, {
95
+ applied_filters: ['type', 'search', 'related_to', 'related_direction'],
96
+ ignored_filters: ['attr.status'],
97
+ });
98
+ expect(v.ignored.sort()).toEqual(['attr.status', 'order']);
99
+ });
100
+ it('reads the camelCased spelling too', () => {
101
+ expect(reconcileFilters({ type: 't', page: 1, search: 'x' }, { appliedFilters: ['type', 'search'] }).ignored).toEqual([]);
102
+ });
103
+ it('treats a server that reports nothing as unconfirmed, not applied', () => {
104
+ const v = reconcileFilters({ type: 't', page: 1, 'attr.status': 'open' }, {});
105
+ expect(v.reported).toBe(false);
106
+ expect(v.ignored).toEqual(['type', 'attr.status']);
107
+ });
108
+ it('accepts related_to as confirmation of a party filter', () => {
109
+ expect(reconcileFilters({ type: 't', page: 1, party: 'p' }, { applied_filters: ['type', 'related_to'] }).ignored).toEqual([]);
110
+ });
111
+ it('does not count paging as a filter', () => {
112
+ expect(reconcileFilters({ type: 't', page: 2, page_size: 10 }, { applied_filters: ['type'] }).ignored).toEqual([]);
113
+ });
114
+ });
115
+
116
+ describe('toEntityPage', () => {
117
+ it('maps rows and derives the next page from the server next link', () => {
118
+ const page = toEntityPage({ type: 't', page: 2 }, { count: 7, next: '?page=3', results: [1, 2], applied_filters: ['type'] }, (n: number) => n * 2);
119
+ expect(page).toMatchObject({ items: [2, 4], count: 7, next: '?page=3', nextPage: 3, ignoredFilters: [], filtersReported: true });
120
+ expect(toEntityPage({ type: 't', page: 3 }, { results: [], applied_filters: ['type'] }, (n: number) => n).nextPage).toBeNull();
121
+ });
122
+ });
@@ -49,6 +49,7 @@ import {
49
49
  import type {
50
50
  CorpusTypeKeys, TenantEntity, TenantFacetRow, TenantRelationship,
51
51
  } from './entities';
52
+ import { entityParams } from './entity-query';
52
53
  import { ABOUT_FOCUS, createFilingApi } from './filing';
53
54
  import {
54
55
  FOCUS_TYPE,
@@ -363,32 +364,32 @@ function isALiveSource(connection: Record<string, unknown>): boolean {
363
364
  const WRITE_CONCURRENCY = 6;
364
365
 
365
366
  function params(query: DocumentQuery, type: string) {
366
- const out: Record<string, unknown> = { type, page: query.page ?? 1 };
367
- if (query.pageSize) out.page_size = query.pageSize;
368
- if (query.search) out.search = query.search;
369
- // Only alongside a term: `order=relevance` with nothing to be relevant TO is a
370
- // parameter the server has to reject or ignore, and neither is worth asking.
371
- if (query.order && (query.order !== 'relevance' || query.search)) out.order = query.order;
372
- if (query.source) out.source = query.source;
373
- if (query.partyId) out.party = query.partyId;
374
- if (query.focus) {
375
- // Filing is an edge, so "the documents in this project" is an edge walk. A
376
- // document is the SOURCE of its own `about_focus` edge: `out` returns
377
- // documents, `in` returns an empty page (see `commitmentParams`).
378
- out.related_to = query.focus;
379
- out.related_via = ABOUT_FOCUS;
380
- out.related_direction = 'out';
381
- }
382
- if (query.occurredAfter) out.occurred_after = query.occurredAfter;
383
- if (query.occurredBefore) out.occurred_before = query.occurredBefore;
384
- // THE FOLDER BOUNDS, and only ever one of them. `attr.path` is the shelf and
385
- // `attr.path__under` is the subtree; sending both would AND an exact match
386
- // with its own subtree and answer with the shelf, which is the exact-match
387
- // query wearing a second parameter. The composer chooses; this just refuses to
388
- // send a contradiction.
389
- if (query.underFolder) out['attr.path__under'] = query.underFolder;
390
- else if (query.folder) out['attr.path'] = query.folder;
391
- return out;
367
+ // Spelled once, in `entity-query.ts`, so the native adapter cannot drift from
368
+ // this one. Filing is an edge, so "the documents in this project" is an edge
369
+ // walk: a document is the SOURCE of its own `about_focus` edge, `out` returns
370
+ // documents and `in` returns an empty page rather than an error.
371
+ return entityParams({
372
+ type,
373
+ page: query.page,
374
+ pageSize: query.pageSize,
375
+ search: query.search,
376
+ order: query.order,
377
+ filters: {
378
+ source: query.source,
379
+ party: query.partyId,
380
+ occurredAfter: query.occurredAfter,
381
+ occurredBefore: query.occurredBefore,
382
+ ...(query.focus
383
+ ? { relatedTo: query.focus, relatedVia: ABOUT_FOCUS, relatedDirection: 'out' as const }
384
+ : {}),
385
+ },
386
+ // THE FOLDER BOUNDS, and only ever one of them: `attr.path` is the shelf and
387
+ // `attr.path__under` the subtree; sending both would AND an exact match with
388
+ // its own subtree. The composer chooses; this refuses to send a contradiction.
389
+ attr: query.underFolder
390
+ ? { path__under: query.underFolder }
391
+ : query.folder ? { path: query.folder } : undefined,
392
+ });
392
393
  }
393
394
 
394
395
  /**
@@ -436,7 +437,7 @@ function appliedFilters(
436
437
  * verified on the live tenant, 200 with count 180), a body with no id at all,
437
438
  * and a row whose id is somebody else's.
438
439
  */
439
- function isRecord(value: unknown, id: string): value is TenantEntity {
440
+ export function isRecord(value: unknown, id: string): value is TenantEntity {
440
441
  if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
441
442
  // A page is the shape a LIST answers with. It is never one record, whatever
442
443
  // its count happens to be.
@@ -456,7 +457,7 @@ function isRecord(value: unknown, id: string): value is TenantEntity {
456
457
  * principal may not see ABSENT rather than refused — so callers get one status
457
458
  * to branch on, and "not found" is already the honest word for both.
458
459
  */
459
- function notFound(id: string): Error & { status: number } {
460
+ export function notFound(id: string): Error & { status: number } {
460
461
  return Object.assign(new Error(`No record ${id} in this workspace.`), { status: 404 });
461
462
  }
462
463
 
@@ -0,0 +1,269 @@
1
+ /**
2
+ * The ONE query vocabulary for the tenant's generic `GET api/v1/entities/`
3
+ * (and `/entities/facets/`, `/relationships/`), as pure functions.
4
+ *
5
+ * Every list screen — web composer or native tab — asks the server for its page,
6
+ * its order and its filters; nothing loads a full list and narrows it locally
7
+ * (CLAUDE.md rule 8). This module is the shared place that spelling lives, so the
8
+ * web adapter (`client.ts`) and the native adapter cannot drift apart.
9
+ *
10
+ * Server contract: start-simpli-api `tenant-starter/apps/api/filters.py`.
11
+ * page, page_size (max 200), search, order=recent|oldest|relevance|[-]attr.<name>,
12
+ * type, id, id__in (comma list), external_id, external_id__in (REPEATED param),
13
+ * source, party, scope, occurred_after/before, created_after/before,
14
+ * related_to + related_via/related_direction/related_depth,
15
+ * attr.<name>[__op] (op: in gt gte lt lte icontains isnull isblank startswith
16
+ * istartswith under).
17
+ * Every parameter is either applied (named in `applied_filters`) or reported in
18
+ * `ignored_filters`; `reconcileFilters` turns that report into a verdict a screen
19
+ * can show, so a filter the server ignored is never presented as applied.
20
+ */
21
+ import { MAX_ID_LIST } from './entities';
22
+
23
+ export type EntityOrder =
24
+ | 'recent'
25
+ | 'oldest'
26
+ | 'relevance'
27
+ | `attr.${string}`
28
+ | `-attr.${string}`;
29
+
30
+ export type AttrValue = string | number | boolean | null | undefined;
31
+
32
+ export interface EntityFilters {
33
+ id?: string;
34
+ idIn?: string[];
35
+ externalId?: string;
36
+ /** Sent as a REPEATED parameter: the server never splits these on a comma. */
37
+ externalIdIn?: string[];
38
+ source?: string;
39
+ party?: string;
40
+ scope?: string;
41
+ occurredAfter?: string;
42
+ occurredBefore?: string;
43
+ createdAfter?: string;
44
+ createdBefore?: string;
45
+ relatedTo?: string;
46
+ relatedVia?: string | string[];
47
+ relatedDirection?: 'out' | 'in' | 'any';
48
+ relatedDepth?: 1 | 2;
49
+ }
50
+
51
+ export interface EntityQuery {
52
+ type: string;
53
+ search?: string;
54
+ order?: EntityOrder;
55
+ filters?: EntityFilters;
56
+ /**
57
+ * Attribute filters keyed by `<name>` or `<name>__<op>` (no `attr.` prefix):
58
+ * `{ status: 'open' }`, `{ status__in: ['open', 'blocked'], due_at__lte: iso }`.
59
+ * Arrays under an `__in` key are comma-joined.
60
+ */
61
+ attr?: Record<string, AttrValue | AttrValue[]>;
62
+ page?: number;
63
+ pageSize?: number;
64
+ }
65
+
66
+ export const MAX_PAGE_SIZE = 200;
67
+ export const TEXT_FILTER_MAX = 500;
68
+ const NOT_A_FILTER = new Set(['page', 'page_size', 'format']);
69
+
70
+ function idList(key: string, ids: string[]): string {
71
+ if (ids.length > MAX_ID_LIST) {
72
+ throw new Error(`${key}: at most ${MAX_ID_LIST} ids per request — page the ids.`);
73
+ }
74
+ return ids.join(',');
75
+ }
76
+
77
+ function put(out: Record<string, unknown>, key: string, value: unknown): void {
78
+ if (value === undefined || value === null || value === '') return;
79
+ out[key] = value;
80
+ }
81
+
82
+ /** Filters that are common to the list and to facets. */
83
+ export function entityFilterParams(filters: EntityFilters = {}): Record<string, unknown> {
84
+ const out: Record<string, unknown> = {};
85
+ put(out, 'id', filters.id);
86
+ if (filters.idIn?.length) out.id__in = idList('id__in', filters.idIn);
87
+ put(out, 'external_id', filters.externalId);
88
+ if (filters.externalIdIn?.length) {
89
+ if (filters.externalIdIn.length > MAX_ID_LIST) {
90
+ throw new Error(`external_id__in: at most ${MAX_ID_LIST} values per request.`);
91
+ }
92
+ out.external_id__in = filters.externalIdIn;
93
+ }
94
+ put(out, 'source', filters.source);
95
+ put(out, 'party', filters.party);
96
+ put(out, 'scope', filters.scope);
97
+ put(out, 'occurred_after', filters.occurredAfter);
98
+ put(out, 'occurred_before', filters.occurredBefore);
99
+ put(out, 'created_after', filters.createdAfter);
100
+ put(out, 'created_before', filters.createdBefore);
101
+ if (filters.relatedTo) {
102
+ out.related_to = filters.relatedTo;
103
+ // Companions only ride along with a target: alone the server ignores them.
104
+ const via = Array.isArray(filters.relatedVia) ? filters.relatedVia.join(',') : filters.relatedVia;
105
+ put(out, 'related_via', via);
106
+ put(out, 'related_direction', filters.relatedDirection);
107
+ put(out, 'related_depth', filters.relatedDepth);
108
+ }
109
+ return out;
110
+ }
111
+
112
+ export function attrParams(attr: EntityQuery['attr'] = {}): Record<string, unknown> {
113
+ const out: Record<string, unknown> = {};
114
+ for (const [name, raw] of Object.entries(attr)) {
115
+ if (raw === undefined || raw === null) continue;
116
+ if (Array.isArray(raw)) {
117
+ const items = raw.filter((v) => v !== undefined && v !== null);
118
+ if (items.length === 0) continue;
119
+ out[`attr.${name}`] = idList(`attr.${name}`, items.map(String));
120
+ } else if (raw !== '') {
121
+ out[`attr.${name}`] = raw;
122
+ }
123
+ }
124
+ return out;
125
+ }
126
+
127
+ /** `EntityQuery` -> the query string parameters of `GET api/v1/entities/`. */
128
+ export function entityParams(query: EntityQuery): Record<string, unknown> {
129
+ const out: Record<string, unknown> = { type: query.type, page: query.page ?? 1 };
130
+ if (query.pageSize) out.page_size = Math.min(Math.max(1, query.pageSize), MAX_PAGE_SIZE);
131
+ const search = query.search?.trim();
132
+ if (search) out.search = search.slice(0, TEXT_FILTER_MAX);
133
+ // `relevance` ranks a search; with no term there is nothing to be relevant TO.
134
+ if (query.order && (query.order !== 'relevance' || search)) out.order = query.order;
135
+ Object.assign(out, entityFilterParams(query.filters), attrParams(query.attr));
136
+ return out;
137
+ }
138
+
139
+ export interface FacetQuery extends Omit<EntityQuery, 'order' | 'search'> {
140
+ /** The attribute whose distinct values are enumerated (`attr=`). */
141
+ facetAttr: string;
142
+ /** Narrow to the subtree under this value (`under=`). */
143
+ under?: string;
144
+ }
145
+
146
+ /** The facet route's vocabulary: entity filters PLUS `attr` and `under`. */
147
+ export function facetParams(query: FacetQuery): Record<string, unknown> {
148
+ const out: Record<string, unknown> = { type: query.type, attr: query.facetAttr, page: query.page ?? 1 };
149
+ if (query.pageSize) out.page_size = Math.min(Math.max(1, query.pageSize), MAX_PAGE_SIZE);
150
+ if (query.under) out.under = query.under;
151
+ Object.assign(out, entityFilterParams(query.filters), attrParams(query.attr));
152
+ return out;
153
+ }
154
+
155
+ export interface RelationshipListQuery {
156
+ source?: string;
157
+ target?: string;
158
+ entity?: string;
159
+ sourceIn?: string[];
160
+ targetIn?: string[];
161
+ entityIn?: string[];
162
+ relType?: string | string[];
163
+ sourceType?: string;
164
+ targetType?: string;
165
+ page?: number;
166
+ pageSize?: number;
167
+ }
168
+
169
+ export function relationshipParams(query: RelationshipListQuery): Record<string, unknown> {
170
+ const out: Record<string, unknown> = { page: query.page ?? 1 };
171
+ if (query.pageSize) out.page_size = Math.min(Math.max(1, query.pageSize), MAX_PAGE_SIZE);
172
+ put(out, 'source', query.source);
173
+ put(out, 'target', query.target);
174
+ put(out, 'entity', query.entity);
175
+ if (query.sourceIn?.length) out.source__in = idList('source__in', query.sourceIn);
176
+ if (query.targetIn?.length) out.target__in = idList('target__in', query.targetIn);
177
+ if (query.entityIn?.length) out.entity__in = idList('entity__in', query.entityIn);
178
+ const rel = Array.isArray(query.relType) ? query.relType.join(',') : query.relType;
179
+ put(out, 'rel_type', rel);
180
+ put(out, 'source_type', query.sourceType);
181
+ put(out, 'target_type', query.targetType);
182
+ return out;
183
+ }
184
+
185
+ /** What the server says about the query it was handed. Both key spellings. */
186
+ export interface FilterReport {
187
+ applied_filters?: string[];
188
+ appliedFilters?: string[];
189
+ ignored_filters?: string[];
190
+ ignoredFilters?: string[];
191
+ }
192
+
193
+ export interface FilterVerdict {
194
+ /** Sent filters the server confirmed it applied. */
195
+ applied: string[];
196
+ /**
197
+ * Sent filters the server did NOT confirm: reported ignored, or absent from
198
+ * `applied_filters`, or the server reports nothing at all. A screen must say
199
+ * so rather than present the list as filtered/ordered.
200
+ */
201
+ ignored: string[];
202
+ /** False when the response carried no `applied_filters` (a fork older than the contract). */
203
+ reported: boolean;
204
+ }
205
+
206
+ /** `party` is confirmed under either spelling: the server labels a party walk `related_to`. */
207
+ const ALIASES: Record<string, string[]> = { party: ['related_to'] };
208
+
209
+ export function sentFilterNames(params: Record<string, unknown>): string[] {
210
+ return Object.keys(params).filter((key) => !NOT_A_FILTER.has(key));
211
+ }
212
+
213
+ export function reconcileFilters(params: Record<string, unknown>, report: FilterReport | undefined): FilterVerdict {
214
+ const sent = sentFilterNames(params);
215
+ const appliedRaw = report?.applied_filters ?? report?.appliedFilters;
216
+ const ignoredRaw = report?.ignored_filters ?? report?.ignoredFilters ?? [];
217
+ if (!Array.isArray(appliedRaw)) return { applied: [], ignored: sent, reported: false };
218
+ const confirmed = new Set(appliedRaw);
219
+ const refused = new Set(ignoredRaw);
220
+ const applied: string[] = [];
221
+ const ignored: string[] = [];
222
+ for (const key of sent) {
223
+ const names = [key, ...(ALIASES[key] ?? [])];
224
+ if (!refused.has(key) && names.some((n) => confirmed.has(n))) applied.push(key);
225
+ else ignored.push(key);
226
+ }
227
+ return { applied, ignored, reported: true };
228
+ }
229
+
230
+ export interface EntityPage<T> {
231
+ items: T[];
232
+ /** Total rows matching, from the server's own COUNT. */
233
+ count: number;
234
+ /** The server's `next` link, or null on the last page. */
235
+ next: string | null;
236
+ /** The page number to ask for next, or null on the last page. */
237
+ nextPage: number | null;
238
+ appliedFilters: string[];
239
+ ignoredFilters: string[];
240
+ /** False when the server did not report which filters it applied. */
241
+ filtersReported: boolean;
242
+ }
243
+
244
+ interface DrfEnvelope<R> extends FilterReport {
245
+ count?: number;
246
+ next?: string | null;
247
+ results?: R[];
248
+ }
249
+
250
+ /** Envelope -> typed page, with the server's filter report reconciled. */
251
+ export function toEntityPage<R, T>(
252
+ params: Record<string, unknown>,
253
+ response: DrfEnvelope<R>,
254
+ map: (row: R) => T,
255
+ ): EntityPage<T> {
256
+ const verdict = reconcileFilters(params, response);
257
+ const page = Number(params.page ?? 1) || 1;
258
+ const items = (response.results ?? []).map(map);
259
+ const next = response.next ?? null;
260
+ return {
261
+ items,
262
+ count: response.count ?? items.length,
263
+ next,
264
+ nextPage: next ? page + 1 : null,
265
+ appliedFilters: verdict.applied,
266
+ ignoredFilters: verdict.ignored,
267
+ filtersReported: verdict.reported,
268
+ };
269
+ }
@@ -261,3 +261,12 @@ export type {
261
261
  VoiceSubmission,
262
262
  VoiceTranscriber,
263
263
  } from './voice';
264
+
265
+ export {
266
+ attrParams, entityFilterParams, entityParams, facetParams, reconcileFilters, relationshipParams,
267
+ sentFilterNames, toEntityPage,
268
+ } from './entity-query';
269
+ export type {
270
+ AttrValue, EntityFilters, EntityOrder, EntityPage, EntityQuery, FacetQuery, FilterReport,
271
+ FilterVerdict, RelationshipListQuery,
272
+ } from './entity-query';
@@ -0,0 +1,81 @@
1
+ import { useMemo, useSyncExternalStore, type ReactNode } from 'react';
2
+ import { View } from 'react-native';
3
+ import { useSafeAreaInsets } from 'react-native-safe-area-context';
4
+ import { TabBar, useTheme, type TabItem } from '@startsimpli/ui-native';
5
+ import { createTabsNavigator, type Route, type TabsNavigator } from '../shell/navigator';
6
+
7
+ /** What a tab's `render` is given. */
8
+ export interface TabContext {
9
+ tab: string;
10
+ /** True while this tab is the one on screen (a visited tab stays mounted, hidden, when it is not). */
11
+ active: boolean;
12
+ /** The detail open on this tab, or null while its list shows. */
13
+ route: Route | null;
14
+ /** list -> detail. */
15
+ push(id: string, params?: Record<string, unknown>): void;
16
+ /** detail -> list. */
17
+ back(): void;
18
+ /** Jump to another tab, optionally straight onto a detail. */
19
+ openTab(key: string, detailId?: string): void;
20
+ }
21
+
22
+ export interface FoundryTab {
23
+ key: string;
24
+ label: string;
25
+ icon?: TabItem['icon'];
26
+ render(ctx: TabContext): ReactNode;
27
+ /** Pad the top safe area for this tab. Default true; a screen that draws under the status bar sets false. */
28
+ safeArea?: boolean;
29
+ /** Pop to the list when the user leaves the tab. Default: keep state. */
30
+ resetOnLeave?: boolean;
31
+ }
32
+
33
+ export interface FoundryTabsShellProps {
34
+ tabs: FoundryTab[];
35
+ initialTab?: string;
36
+ /** Open straight on one detail (implies its tab). From a launch arg or deep link. */
37
+ initialDetail?: { tab: string; id: string; params?: Record<string, unknown> };
38
+ /** Drive the shell from outside (warm deep links): `navigator.open(tab, {id})`. */
39
+ navigator?: TabsNavigator;
40
+ }
41
+
42
+ /**
43
+ * Generic bottom-tab shell. Each tab owns a stack (list -> detail with Back); a
44
+ * tab is mounted the first time it is shown and then kept mounted (hidden) so
45
+ * its state - and a recording on the GO tab - survives switching away.
46
+ */
47
+ export function FoundryTabsShell({ tabs, initialTab, initialDetail, navigator }: FoundryTabsShellProps) {
48
+ const theme = useTheme();
49
+ const insets = useSafeAreaInsets();
50
+ const nav = useMemo(
51
+ () => navigator ?? createTabsNavigator({ tabs, initialTab, initialDetail }),
52
+ // The config is read once; tabs are expected to be a stable array.
53
+ // eslint-disable-next-line react-hooks/exhaustive-deps
54
+ [navigator],
55
+ );
56
+ const state = useSyncExternalStore(nav.subscribe, nav.getState, nav.getState);
57
+ return (
58
+ <View style={{ flex: 1, backgroundColor: theme.colors.background }}>
59
+ {tabs.filter((t) => state.visited.includes(t.key)).map((t) => {
60
+ const active = t.key === state.activeKey;
61
+ const route = state.stacks[t.key]?.slice(-1)[0] ?? null;
62
+ const ctx: TabContext = {
63
+ tab: t.key, active, route,
64
+ push: (id, params) => nav.push({ id, ...(params ? { params } : {}) }, t.key),
65
+ back: () => nav.pop(t.key),
66
+ openTab: (key, detailId) => (detailId ? nav.open(key, { id: detailId }) : nav.select(key)),
67
+ };
68
+ return (
69
+ <View key={t.key} style={{ flex: 1, display: active ? 'flex' : 'none', paddingTop: t.safeArea === false ? 0 : insets.top }}>
70
+ {t.render(ctx)}
71
+ </View>
72
+ );
73
+ })}
74
+ <TabBar
75
+ items={tabs.map(({ key, label, icon }) => ({ key, label, icon }))}
76
+ activeKey={state.activeKey}
77
+ onChange={(key) => nav.select(key)}
78
+ />
79
+ </View>
80
+ );
81
+ }