@startsimpli/integrations 0.2.100 → 0.2.101

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 (40) hide show
  1. package/package.json +5 -5
  2. package/src/native/app/FoundryApp.tsx +144 -0
  3. package/src/native/app/__tests__/FoundryApp.test.tsx +61 -0
  4. package/src/native/app/__tests__/ShellBanners.test.tsx +37 -0
  5. package/src/native/app/__tests__/banners-restore.test.ts +65 -0
  6. package/src/native/app/__tests__/launch.test.ts +31 -0
  7. package/src/native/app/__tests__/registry.test.tsx +102 -0
  8. package/src/native/app/banners.ts +46 -0
  9. package/src/native/app/config/__tests__/links.test.ts +43 -0
  10. package/src/native/app/config/__tests__/validate.test.ts +71 -0
  11. package/src/native/app/config/defaults.ts +51 -0
  12. package/src/native/app/config/index.ts +4 -0
  13. package/src/native/app/config/links.ts +75 -0
  14. package/src/native/app/config/types.ts +127 -0
  15. package/src/native/app/config/validate.ts +221 -0
  16. package/src/native/app/data.ts +48 -0
  17. package/src/native/app/device.ts +38 -0
  18. package/src/native/app/entity/EntityTab.tsx +90 -0
  19. package/src/native/app/entity/format.ts +35 -0
  20. package/src/native/app/icon.tsx +7 -0
  21. package/src/native/app/index.ts +11 -0
  22. package/src/native/app/launch.ts +42 -0
  23. package/src/native/app/registry.tsx +104 -0
  24. package/src/native/app/restore.ts +42 -0
  25. package/src/native/app/screens/DiagnosticsScreen.tsx +22 -0
  26. package/src/native/app/screens/RecordScreen.tsx +93 -0
  27. package/src/native/app/screens/ShellBanners.tsx +18 -0
  28. package/src/native/app/screens/SignInScreen.tsx +34 -0
  29. package/src/native/app/services.ts +150 -0
  30. package/src/native/app/strings.ts +74 -0
  31. package/src/native/components/FoundryTabsShell.tsx +4 -1
  32. package/src/native/home/tab.tsx +3 -8
  33. package/src/native/index.ts +2 -1
  34. package/src/native/recording/__tests__/authRefresh.test.ts +1 -1
  35. package/src/native/recording/__tests__/deeplink.test.ts +18 -3
  36. package/src/native/recording/__tests__/diagnostics.test.ts +2 -2
  37. package/src/native/recording/__tests__/session.test.ts +27 -1
  38. package/src/native/recording/deeplink.ts +25 -20
  39. package/src/native/recording/diagnostics.ts +3 -3
  40. package/src/native/recording/session.ts +20 -6
@@ -0,0 +1,51 @@
1
+ import { BUILTIN_SCREENS, type FoundryAppConfig, type FoundryFeatures, type FoundryHomeType, type FoundryTabConfig } from './types';
2
+
3
+ export const DEFAULT_CENTRAL_URL = 'https://api.startsimpli.com';
4
+
5
+ export const DEFAULT_FEATURES: FoundryFeatures = {
6
+ recording: true, notes: true, tracker: true, library: true, ask: true, planning: true, connections: true, connectClaude: true,
7
+ };
8
+
9
+ /** The feature a built-in screen needs. `home` and `entity` need none. */
10
+ export const SCREEN_FEATURE: Partial<Record<string, keyof FoundryFeatures>> = {
11
+ record: 'recording', notes: 'notes', tracker: 'tracker', library: 'library', ask: 'ask',
12
+ planning: 'planning', connections: 'connections', 'connect-claude': 'connectClaude',
13
+ };
14
+
15
+ /** Entity types a built-in screen shows (the `entity` screen names its own in `options.entityType`). */
16
+ export const SCREEN_ENTITY_TYPES: Record<string, string[]> = {
17
+ tracker: ['commitment'], notes: ['source_document'], library: ['source_document'], planning: ['focus'],
18
+ };
19
+
20
+ export const DEFAULT_HOME_TYPES: FoundryHomeType[] = [
21
+ { key: 'commitment', label: 'To-dos' },
22
+ { key: 'source_document', label: 'Documents' },
23
+ { key: 'focus', label: 'Projects' },
24
+ ];
25
+
26
+ /** Default label / More blurb / bar priority per built-in screen. */
27
+ export const SCREEN_DEFAULTS: Record<string, { label: string; description?: string; priority?: number }> = {
28
+ home: { label: 'Home', priority: 100 },
29
+ record: { label: 'GO', priority: 90 },
30
+ notes: { label: 'Notes', priority: 80 },
31
+ tracker: { label: 'To-dos', priority: 70 },
32
+ library: { label: 'Library', description: 'Documents and recordings' },
33
+ ask: { label: 'Ask', description: 'Ask questions across your documents' },
34
+ planning: { label: 'Planning', description: 'Focuses and items' },
35
+ connections: { label: 'Connections', description: 'Accounts and data sources' },
36
+ 'connect-claude': { label: 'Claude', description: 'Use your workspace from Claude' },
37
+ entity: { label: 'Records' },
38
+ };
39
+
40
+ /** The tab each built-in screen takes when the config names no tabs. `record` keeps the key `go`. */
41
+ const DEFAULT_KEYS: Record<string, string> = { record: 'go' };
42
+
43
+ export function defaultTabs(features: FoundryFeatures): FoundryTabConfig[] {
44
+ const on = (screen: string) => { const f = SCREEN_FEATURE[screen]; return !f || features[f]; };
45
+ return BUILTIN_SCREENS.filter((s) => s !== 'entity' && on(s)).map((screen) => ({ key: DEFAULT_KEYS[screen] ?? screen, screen }));
46
+ }
47
+
48
+ export function defaultBrandTagline(): string { return 'Your workspace'; }
49
+
50
+ export type ResolvedBase = Pick<FoundryAppConfig, 'maxVisibleTabs' | 'moreLabel' | 'theme'>;
51
+ export const DEFAULT_BASE: ResolvedBase = { maxVisibleTabs: 5, moreLabel: 'More', theme: { mode: 'dark' } };
@@ -0,0 +1,4 @@
1
+ export * from './types';
2
+ export * from './defaults';
3
+ export * from './validate';
4
+ export * from './links';
@@ -0,0 +1,75 @@
1
+ import { tabForEntityType } from './validate';
2
+ import type { FoundryAppConfig } from './types';
3
+
4
+ /** What a link asks the app to do. */
5
+ export type LinkAction =
6
+ | { kind: 'record'; autostop?: number }
7
+ | { kind: 'open'; tab: string; id?: string };
8
+
9
+ export interface LinkResolver {
10
+ /** `null` when the URL is not ours or names nothing the app has (an unknown tab, record with recording off). */
11
+ resolve(url: string): LinkAction | null;
12
+ }
13
+
14
+ type LinkConfig = Pick<FoundryAppConfig, 'app' | 'tabs' | 'links' | 'entityTypes' | 'features'>;
15
+
16
+ const decode = (s: string) => { try { return decodeURIComponent(s); } catch { return s; } };
17
+
18
+ /** Compile a `/n/:id` pattern to a matcher that returns the id. */
19
+ function routeMatcher(pattern: string): (path: string) => string | null {
20
+ const parts = pattern.split('/').filter(Boolean);
21
+ return (path) => {
22
+ const segs = path.split('/').filter(Boolean);
23
+ if (segs.length !== parts.length) return null;
24
+ let id: string | null = null;
25
+ for (let i = 0; i < parts.length; i += 1) {
26
+ if (parts[i] === ':id') id = decode(segs[i]);
27
+ else if (parts[i] !== segs[i]) return null;
28
+ }
29
+ return id;
30
+ };
31
+ }
32
+
33
+ /**
34
+ * The one deep-link table: `<scheme>://record[?autostop=N]`, `<scheme>://tab/<key>[/<id>]`,
35
+ * `<scheme>://entity/<type>/<id>`, `<scheme>://<key>[/<id>]`, plus the config's own `links.routes`; the same
36
+ * paths on `https://<host>/...` for each host in `links.hosts` (universal links).
37
+ */
38
+ export function createLinkResolver(config: LinkConfig): LinkResolver {
39
+ const tabKeys = new Set(config.tabs.map((t) => t.key));
40
+ const hosts = new Set(config.links.hosts.map((h) => h.toLowerCase()));
41
+ const routes = config.links.routes.map((r) => ({ match: routeMatcher(r.pattern), tab: r.tab }));
42
+ const scheme = config.app.scheme.toLowerCase();
43
+
44
+ return {
45
+ resolve(url) {
46
+ const m = /^([a-z][a-z0-9+.-]*):\/\/([^/?#]*)([^?#]*)(?:\?([^#]*))?/i.exec(url.trim());
47
+ if (!m) return null;
48
+ const proto = m[1].toLowerCase();
49
+ let path: string;
50
+ if (proto === scheme) path = `/${m[2]}${m[3]}`;
51
+ else if ((proto === 'https' || proto === 'http') && hosts.has(m[2].toLowerCase())) path = m[3] || '/';
52
+ else return null;
53
+ const segs = path.split('/').filter(Boolean);
54
+ const [head, a, b] = segs.map(decode);
55
+ if (!head) return null;
56
+
57
+ if (head === 'record' && segs.length === 1) {
58
+ if (!config.features.recording) return null;
59
+ const seconds = Number(new URLSearchParams(m[4] ?? '').get('autostop'));
60
+ return Number.isFinite(seconds) && seconds > 0 ? { kind: 'record', autostop: seconds } : { kind: 'record' };
61
+ }
62
+ for (const r of routes) {
63
+ const id = r.match(path);
64
+ if (id !== null) return { kind: 'open', tab: r.tab, id };
65
+ }
66
+ if (head === 'entity' && a && b) {
67
+ const tab = tabForEntityType(config as FoundryAppConfig, a);
68
+ return tab ? { kind: 'open', tab, id: b } : null;
69
+ }
70
+ if (head === 'tab' && a) return tabKeys.has(a) ? (b ? { kind: 'open', tab: a, id: segs.slice(2).map(decode).join('/') } : { kind: 'open', tab: a }) : null;
71
+ if (tabKeys.has(head)) return a ? { kind: 'open', tab: head, id: segs.slice(1).map(decode).join('/') } : { kind: 'open', tab: head };
72
+ return null;
73
+ },
74
+ };
75
+ }
@@ -0,0 +1,127 @@
1
+ /**
2
+ * The typed app config of a Foundry companion iPhone app. Pure data (JSON-serialisable, no react-native import) so the
3
+ * app, `simpli ios new` and tests all validate the same file with the same code (`validateFoundryApp`).
4
+ */
5
+
6
+ /** Screen kinds the shell ships. An app can add or override kinds through a screen registry. */
7
+ export const BUILTIN_SCREENS = [
8
+ 'home', 'record', 'notes', 'tracker', 'library', 'ask', 'planning', 'connections', 'connect-claude', 'entity',
9
+ ] as const;
10
+ export type BuiltinScreen = (typeof BUILTIN_SCREENS)[number];
11
+
12
+ /** Features switch whole capabilities off. A tab whose screen needs a disabled feature is a config error. */
13
+ export interface FoundryFeatures {
14
+ /** The GO screen, the upload queue and the `<scheme>://record` link. */
15
+ recording: boolean;
16
+ /** Voice notes list and detail (needs the tenant's voice endpoint). */
17
+ notes: boolean;
18
+ /** To-dos (commitments). */
19
+ tracker: boolean;
20
+ library: boolean;
21
+ ask: boolean;
22
+ planning: boolean;
23
+ connections: boolean;
24
+ /** Mint an MCP token to use the Foundry from Claude. */
25
+ connectClaude: boolean;
26
+ }
27
+
28
+ export interface FoundryTabConfig {
29
+ /** Unique; also the launch-arg / deep-link name of the tab (`<scheme>://tab/<key>`). */
30
+ key: string;
31
+ /** A screen kind from the registry. */
32
+ screen: string;
33
+ label?: string;
34
+ /** A glyph (emoji or symbol) drawn above the label. */
35
+ icon?: string;
36
+ /** One line under the label in the More list. */
37
+ description?: string;
38
+ /** Higher stays in the bar when tabs overflow. */
39
+ priority?: number;
40
+ /** Per-screen settings; `entity` needs `{ entityType }`. */
41
+ options?: Record<string, unknown>;
42
+ }
43
+
44
+ /** How one tenant entity type reads in lists and details. The `entity` screen is driven by this. */
45
+ export interface FoundryEntityType {
46
+ label: string;
47
+ plural?: string;
48
+ /** Attribute shown as the row title; default `name`. */
49
+ titleField?: string;
50
+ /** Attributes joined into the row subtitle. */
51
+ subtitleFields?: string[];
52
+ /** Attribute shown as a status chip. */
53
+ statusField?: string;
54
+ /** The tab that opens records of this type (Home taps, entity deep links). Default: the first tab that shows the type. */
55
+ tab?: string;
56
+ }
57
+
58
+ export interface FoundryLinkRoute {
59
+ /** Path pattern with `:id`, e.g. `/n/:id` (matched on universal links and after `<scheme>://`). */
60
+ pattern: string;
61
+ tab: string;
62
+ }
63
+
64
+ export interface FoundryHomeType { key: string; label: string }
65
+
66
+ export interface FoundryAppConfig {
67
+ version: 1;
68
+ app: {
69
+ /** Display name on the home screen, e.g. "Acme Go". */
70
+ name: string;
71
+ /** Expo slug / package name. */
72
+ slug: string;
73
+ /** URL scheme, `<scheme>://`. */
74
+ scheme: string;
75
+ bundleId: string;
76
+ };
77
+ brand: {
78
+ /** The Foundry's product name: Home title, sign-in title. */
79
+ name: string;
80
+ tagline: string;
81
+ /** The app slug central auth signs in against. */
82
+ authApp: string;
83
+ /** Prefix of the diagnostics log. */
84
+ logTag: string;
85
+ };
86
+ tenant: {
87
+ /** The Foundry's tenant API origin. */
88
+ url: string;
89
+ /** Central auth + member-level APIs. */
90
+ centralUrl: string;
91
+ };
92
+ theme: { mode: 'dark' | 'light' | 'system' };
93
+ features: FoundryFeatures;
94
+ tabs: FoundryTabConfig[];
95
+ /** Record types the Home tab counts, in order. */
96
+ home: { types: FoundryHomeType[] };
97
+ entityTypes: Record<string, FoundryEntityType>;
98
+ links: {
99
+ /** Hosts whose https links open the app (needs the associated-domains entitlement + an apple-app-site-association file). */
100
+ hosts: string[];
101
+ routes: FoundryLinkRoute[];
102
+ };
103
+ /** Bar slots, More included. */
104
+ maxVisibleTabs: number;
105
+ moreLabel: string;
106
+ /** Overrides for user-facing strings; unset keys keep the shell default. */
107
+ strings: Record<string, string>;
108
+ }
109
+
110
+ /** What a `foundry.config.json` holds: only identity and tenant are required; everything else defaults. */
111
+ export type FoundryAppInput = {
112
+ version?: 1;
113
+ app: Pick<FoundryAppConfig['app'], 'name'> & Partial<FoundryAppConfig['app']>;
114
+ brand?: Partial<FoundryAppConfig['brand']>;
115
+ tenant: Pick<FoundryAppConfig['tenant'], 'url'> & Partial<FoundryAppConfig['tenant']>;
116
+ theme?: Partial<FoundryAppConfig['theme']>;
117
+ features?: Partial<FoundryFeatures>;
118
+ tabs?: FoundryTabConfig[];
119
+ home?: Partial<FoundryAppConfig['home']>;
120
+ entityTypes?: Record<string, FoundryEntityType>;
121
+ links?: Partial<FoundryAppConfig['links']>;
122
+ maxVisibleTabs?: number;
123
+ moreLabel?: string;
124
+ strings?: Record<string, string>;
125
+ };
126
+
127
+ export interface ConfigIssue { path: string; message: string }
@@ -0,0 +1,221 @@
1
+ import { BUILTIN_SCREENS, type ConfigIssue, type FoundryAppConfig, type FoundryAppInput, type FoundryTabConfig } from './types';
2
+ import {
3
+ DEFAULT_BASE, DEFAULT_CENTRAL_URL, DEFAULT_FEATURES, DEFAULT_HOME_TYPES, SCREEN_DEFAULTS, SCREEN_ENTITY_TYPES, SCREEN_FEATURE, defaultBrandTagline, defaultTabs,
4
+ } from './defaults';
5
+
6
+ export type ValidateResult = { ok: true; config: FoundryAppConfig; warnings: ConfigIssue[] } | { ok: false; issues: ConfigIssue[] };
7
+
8
+ export class FoundryConfigError extends Error {
9
+ constructor(readonly issues: ConfigIssue[]) {
10
+ super(`Invalid foundry app config:\n${issues.map((i) => ` ${i.path}: ${i.message}`).join('\n')}`);
11
+ this.name = 'FoundryConfigError';
12
+ }
13
+ }
14
+
15
+ export interface ValidateOptions {
16
+ /** Screen kinds an app registers beyond the built-ins. */
17
+ extraScreens?: string[];
18
+ }
19
+
20
+ const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);
21
+ const trimSlash = (u: string) => u.replace(/\/+$/, '');
22
+ const KEY = /^[a-z][a-z0-9-]*$/;
23
+ const SCHEME = /^[a-z][a-z0-9+.-]*$/;
24
+ const BUNDLE = /^[A-Za-z][A-Za-z0-9-]*(\.[A-Za-z][A-Za-z0-9-]*)+$/;
25
+ const HTTP = /^https?:\/\/[^/\s]+/;
26
+ const HOST = /^[a-z0-9.-]+$/i;
27
+
28
+ export function deriveAppNames(name: string): { slug: string; scheme: string; bundleId: string } {
29
+ const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
30
+ if (!slug) throw new Error(`name "${name}" has no letters or digits to build a slug from`);
31
+ const scheme = slug.replace(/-/g, '');
32
+ return { slug, scheme, bundleId: `com.startsimpli.${scheme}` };
33
+ }
34
+
35
+ const str = (v: unknown): v is string => typeof v === 'string' && v.trim() !== '';
36
+
37
+ /**
38
+ * Check a `foundry.config.json` and fill every default. Returns every problem with its field path, not just the first,
39
+ * so one run of the generator names everything to fix. Unknown keys are errors: a typo must not silently do nothing.
40
+ */
41
+ export function validateFoundryApp(input: unknown, options: ValidateOptions = {}): ValidateResult {
42
+ const issues: ConfigIssue[] = [];
43
+ const warnings: ConfigIssue[] = [];
44
+ const bad = (path: string, message: string) => { issues.push({ path, message }); };
45
+ if (!isObj(input)) return { ok: false, issues: [{ path: '', message: 'config must be a JSON object' }] };
46
+
47
+ const allowed = (obj: Record<string, unknown>, keys: string[], path: string) => {
48
+ for (const k of Object.keys(obj)) if (!keys.includes(k)) bad(path ? `${path}.${k}` : k, `unknown key (allowed: ${keys.join(', ')})`);
49
+ };
50
+ const section = (key: string, required = false): Record<string, unknown> => {
51
+ const v = input[key];
52
+ if (v === undefined) { if (required) bad(key, 'is required'); return {}; }
53
+ if (!isObj(v)) { bad(key, 'must be an object'); return {}; }
54
+ return v;
55
+ };
56
+
57
+ allowed(input, ['version', 'app', 'brand', 'tenant', 'theme', 'features', 'tabs', 'home', 'entityTypes', 'links', 'maxVisibleTabs', 'moreLabel', 'strings', '$schema'], '');
58
+ if (input.version !== undefined && input.version !== 1) bad('version', 'must be 1');
59
+
60
+ // app
61
+ const app = section('app', true);
62
+ allowed(app, ['name', 'slug', 'scheme', 'bundleId'], 'app');
63
+ let derived = { slug: '', scheme: '', bundleId: '' };
64
+ if (!str(app.name)) bad('app.name', 'is required (a display name, e.g. "Acme Go")');
65
+ else { try { derived = deriveAppNames(app.name); } catch (e) { bad('app.name', (e as Error).message); } }
66
+ const slug = (app.slug as string | undefined) ?? derived.slug;
67
+ const scheme = (app.scheme as string | undefined) ?? derived.scheme;
68
+ const bundleId = (app.bundleId as string | undefined) ?? derived.bundleId;
69
+ if (slug && !/^[a-z][a-z0-9-]*$/.test(slug)) bad('app.slug', `"${slug}" must be lowercase letters, digits and dashes`);
70
+ if (scheme && !SCHEME.test(scheme)) bad('app.scheme', `"${scheme}" must be a URL scheme (lowercase letters, digits, + . -)`);
71
+ if (bundleId && !BUNDLE.test(bundleId)) bad('app.bundleId', `"${bundleId}" must look like com.example.app`);
72
+
73
+ // brand
74
+ const brand = section('brand');
75
+ allowed(brand, ['name', 'tagline', 'authApp', 'logTag'], 'brand');
76
+ for (const k of ['name', 'tagline', 'authApp', 'logTag']) if (brand[k] !== undefined && !str(brand[k])) bad(`brand.${k}`, 'must be a non-empty string');
77
+
78
+ // tenant
79
+ const tenant = section('tenant', true);
80
+ allowed(tenant, ['url', 'centralUrl'], 'tenant');
81
+ if (!str(tenant.url)) bad('tenant.url', 'is required (the Foundry tenant URL)');
82
+ else if (!HTTP.test(tenant.url)) bad('tenant.url', `"${tenant.url}" must start with http:// or https://`);
83
+ if (tenant.centralUrl !== undefined && !(str(tenant.centralUrl) && HTTP.test(tenant.centralUrl))) bad('tenant.centralUrl', 'must start with http:// or https://');
84
+
85
+ // theme
86
+ const theme = section('theme');
87
+ allowed(theme, ['mode'], 'theme');
88
+ if (theme.mode !== undefined && !['dark', 'light', 'system'].includes(theme.mode as string)) bad('theme.mode', 'must be dark, light or system');
89
+
90
+ // features
91
+ const featuresIn = section('features');
92
+ allowed(featuresIn, Object.keys(DEFAULT_FEATURES), 'features');
93
+ const features = { ...DEFAULT_FEATURES };
94
+ for (const k of Object.keys(DEFAULT_FEATURES) as Array<keyof typeof DEFAULT_FEATURES>) {
95
+ const v = featuresIn[k];
96
+ if (v === undefined) continue;
97
+ if (typeof v !== 'boolean') bad(`features.${k}`, 'must be true or false'); else features[k] = v;
98
+ }
99
+
100
+ // tabs
101
+ const known = new Set<string>([...BUILTIN_SCREENS, ...(options.extraScreens ?? [])]);
102
+ const tabsIn = input.tabs;
103
+ const tabs: FoundryTabConfig[] = [];
104
+ if (tabsIn !== undefined && !Array.isArray(tabsIn)) bad('tabs', 'must be an array');
105
+ const tabList = Array.isArray(tabsIn) ? tabsIn : defaultTabs(features);
106
+ const seen = new Set<string>();
107
+ tabList.forEach((raw, i) => {
108
+ const p = `tabs[${i}]`;
109
+ if (!isObj(raw)) return bad(p, 'must be an object');
110
+ allowed(raw, ['key', 'screen', 'label', 'icon', 'description', 'priority', 'options'], p);
111
+ if (!str(raw.screen)) return bad(`${p}.screen`, `is required (one of: ${[...known].join(', ')})`);
112
+ const screen = raw.screen;
113
+ if (!known.has(screen)) bad(`${p}.screen`, `unknown screen "${screen}" (known: ${[...known].join(', ')}; register custom screens in the app's screen registry)`);
114
+ const feature = SCREEN_FEATURE[screen];
115
+ if (feature && !features[feature]) bad(`${p}.screen`, `"${screen}" needs features.${feature}, which is off`);
116
+ const key = str(raw.key) ? raw.key : screen === 'record' ? 'go' : screen;
117
+ if (!KEY.test(key)) bad(`${p}.key`, `"${key}" must be lowercase letters, digits and dashes`);
118
+ if (seen.has(key)) bad(`${p}.key`, `duplicate tab key "${key}"`);
119
+ seen.add(key);
120
+ if (raw.priority !== undefined && typeof raw.priority !== 'number') bad(`${p}.priority`, 'must be a number');
121
+ for (const k of ['label', 'icon', 'description']) if (raw[k] !== undefined && !str(raw[k])) bad(`${p}.${k}`, 'must be a non-empty string');
122
+ if (raw.options !== undefined && !isObj(raw.options)) bad(`${p}.options`, 'must be an object');
123
+ tabs.push({ ...(raw as unknown as FoundryTabConfig), key, screen });
124
+ });
125
+ if (Array.isArray(tabsIn) && tabs.length === 0) bad('tabs', 'needs at least one tab');
126
+
127
+ // entity types
128
+ const etIn = section('entityTypes');
129
+ const entityTypes: FoundryAppConfig['entityTypes'] = {};
130
+ for (const [type, raw] of Object.entries(etIn)) {
131
+ const p = `entityTypes.${type}`;
132
+ if (!isObj(raw)) { bad(p, 'must be an object'); continue; }
133
+ allowed(raw, ['label', 'plural', 'titleField', 'subtitleFields', 'statusField', 'tab'], p);
134
+ if (!str(raw.label)) bad(`${p}.label`, 'is required');
135
+ if (raw.subtitleFields !== undefined && !(Array.isArray(raw.subtitleFields) && raw.subtitleFields.every(str))) bad(`${p}.subtitleFields`, 'must be an array of attribute names');
136
+ if (raw.tab !== undefined && !seen.has(raw.tab as string)) bad(`${p}.tab`, `"${String(raw.tab)}" is not a tab key (tabs: ${[...seen].join(', ')})`);
137
+ entityTypes[type] = raw as unknown as FoundryAppConfig['entityTypes'][string];
138
+ }
139
+ tabs.forEach((t, i) => {
140
+ if (t.screen !== 'entity') return;
141
+ const type = t.options?.entityType;
142
+ if (!str(type)) bad(`tabs[${i}].options.entityType`, 'is required for the entity screen');
143
+ else if (!entityTypes[type]) bad(`tabs[${i}].options.entityType`, `"${type}" is not declared in entityTypes`);
144
+ });
145
+
146
+ // home
147
+ const homeIn = section('home');
148
+ allowed(homeIn, ['types'], 'home');
149
+ let homeTypes = DEFAULT_HOME_TYPES;
150
+ if (homeIn.types !== undefined) {
151
+ if (!Array.isArray(homeIn.types) || !homeIn.types.every((t) => isObj(t) && str(t.key) && str(t.label))) bad('home.types', 'must be an array of { key, label }');
152
+ else homeTypes = homeIn.types as typeof DEFAULT_HOME_TYPES;
153
+ }
154
+
155
+ // links
156
+ const linksIn = section('links');
157
+ allowed(linksIn, ['hosts', 'routes'], 'links');
158
+ const hosts = (linksIn.hosts ?? []) as unknown[];
159
+ if (!Array.isArray(hosts) || !hosts.every((h) => str(h) && HOST.test(h))) bad('links.hosts', 'must be an array of bare host names (no scheme or path)');
160
+ const routes = (linksIn.routes ?? []) as unknown[];
161
+ if (!Array.isArray(routes)) bad('links.routes', 'must be an array');
162
+ else routes.forEach((r, i) => {
163
+ const p = `links.routes[${i}]`;
164
+ if (!isObj(r)) return bad(p, 'must be an object');
165
+ allowed(r, ['pattern', 'tab'], p);
166
+ if (!str(r.pattern) || !r.pattern.startsWith('/') || !r.pattern.includes(':id')) bad(`${p}.pattern`, 'must start with / and contain :id, e.g. /n/:id');
167
+ if (!str(r.tab) || !seen.has(r.tab)) bad(`${p}.tab`, `"${String(r.tab)}" is not a tab key (tabs: ${[...seen].join(', ')})`);
168
+ });
169
+
170
+ if (input.maxVisibleTabs !== undefined && !(Number.isInteger(input.maxVisibleTabs) && (input.maxVisibleTabs as number) >= 2)) bad('maxVisibleTabs', 'must be an integer of at least 2');
171
+ if (input.moreLabel !== undefined && !str(input.moreLabel)) bad('moreLabel', 'must be a non-empty string');
172
+ const stringsIn = section('strings');
173
+ for (const [k, v] of Object.entries(stringsIn)) if (typeof v !== 'string') bad(`strings.${k}`, 'must be a string');
174
+
175
+ if (issues.length) return { ok: false, issues };
176
+
177
+ const resolvedBrandName = (brand.name as string | undefined) ?? (app.name as string);
178
+ const config: FoundryAppConfig = {
179
+ version: 1,
180
+ app: { name: app.name as string, slug, scheme, bundleId },
181
+ brand: {
182
+ name: resolvedBrandName,
183
+ tagline: (brand.tagline as string | undefined) ?? defaultBrandTagline(),
184
+ authApp: (brand.authApp as string | undefined) ?? scheme,
185
+ logTag: (brand.logTag as string | undefined) ?? scheme,
186
+ },
187
+ tenant: { url: trimSlash(tenant.url as string), centralUrl: trimSlash((tenant.centralUrl as string | undefined) ?? DEFAULT_CENTRAL_URL) },
188
+ theme: { mode: (theme.mode as FoundryAppConfig['theme']['mode'] | undefined) ?? DEFAULT_BASE.theme.mode },
189
+ features,
190
+ tabs,
191
+ home: { types: homeTypes },
192
+ entityTypes,
193
+ links: { hosts: hosts as string[], routes: routes as FoundryAppConfig['links']['routes'] },
194
+ maxVisibleTabs: (input.maxVisibleTabs as number | undefined) ?? DEFAULT_BASE.maxVisibleTabs,
195
+ moreLabel: (input.moreLabel as string | undefined) ?? DEFAULT_BASE.moreLabel,
196
+ strings: stringsIn as Record<string, string>,
197
+ };
198
+ for (const t of config.home.types) {
199
+ if (!tabForEntityType(config, t.key)) warnings.push({ path: 'home.types', message: `no tab shows "${t.key}" records, so its Home card is not tappable` });
200
+ }
201
+ return { ok: true, config, warnings };
202
+ }
203
+
204
+ /** Validate or throw one error that lists every problem. */
205
+ export function resolveFoundryApp(input: unknown, options?: ValidateOptions): FoundryAppConfig {
206
+ const r = validateFoundryApp(input, options);
207
+ if (!r.ok) throw new FoundryConfigError(r.issues);
208
+ return r.config;
209
+ }
210
+
211
+ /** The tab key that opens records of `type`: an explicit `entityTypes[type].tab`, else the first tab showing the type. */
212
+ export function tabForEntityType(config: FoundryAppConfig, type: string): string | undefined {
213
+ const explicit = config.entityTypes[type]?.tab;
214
+ if (explicit) return explicit;
215
+ return config.tabs.find((t) => (t.screen === 'entity' ? t.options?.entityType === type : SCREEN_ENTITY_TYPES[t.screen]?.includes(type)))?.key;
216
+ }
217
+
218
+ /** The tab's label, falling back to its screen's default. */
219
+ export function tabLabel(tab: FoundryTabConfig): string {
220
+ return tab.label ?? SCREEN_DEFAULTS[tab.screen]?.label ?? tab.key;
221
+ }
@@ -0,0 +1,48 @@
1
+ import { createConnectionsMeApi } from '../../api/connections';
2
+ import { createMcpTokensApi, type McpTokensApi } from '../../api/mcp-tokens';
3
+ import type { MemberConnectionsApi } from '../../components/pages/types';
4
+ import { createNativeCorpusApi, type NativeCorpusApi } from '../corpus/api';
5
+ import { createFakeNativeCorpusApi } from '../corpus/fake';
6
+ import { withScenario, type FakeScenario } from '../corpus/fake-scenarios';
7
+ import { createFakeConnectionsApi } from '../screens/connections/fake';
8
+ import { createFakeMcpTokensApi } from '../screens/connect-claude/fake';
9
+ import { createFakeVoiceApi } from '../voice/fake';
10
+ import { createVoiceNotesController, type VoiceNotesController } from '../voice/controller';
11
+ import { createNativeVoiceApi } from '../voice/http';
12
+ import type { FoundryAppConfig } from './config/types';
13
+
14
+ type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Response>;
15
+
16
+ export interface FoundryData {
17
+ corpus: NativeCorpusApi;
18
+ notes: VoiceNotesController | null;
19
+ member: { connections: MemberConnectionsApi; mcpTokens: McpTokensApi };
20
+ }
21
+
22
+ /**
23
+ * The data layer every screen reads: the signed-in tenant over the session's authorized fetch, or in-memory fakes
24
+ * (`fake`) for simulator checks that need no sign-in and no network.
25
+ */
26
+ export function createFoundryData(deps: { config: FoundryAppConfig; authorizedFetch: AuthorizedFetch; fake?: boolean; scenario?: FakeScenario }): FoundryData {
27
+ const { config, authorizedFetch, fake, scenario } = deps;
28
+ const wantsNotes = config.tabs.some((t) => t.screen === 'notes');
29
+ if (fake) {
30
+ return {
31
+ corpus: createFakeNativeCorpusApi({ scenario }),
32
+ notes: wantsNotes ? createVoiceNotesController({ api: createFakeVoiceApi({ scenario }) }) : null,
33
+ member: {
34
+ connections: withScenario(createFakeConnectionsApi({ connections: scenario === 'empty' ? [] : undefined }), scenario),
35
+ mcpTokens: withScenario(createFakeMcpTokensApi(), scenario),
36
+ },
37
+ };
38
+ }
39
+ // The tenant serves /api/v1/*, and proxies /api/v1/auth/* (the MCP token mint) to central.
40
+ const tenant = { baseUrl: `${config.tenant.url}/api/v1`, fetch: authorizedFetch as typeof fetch };
41
+ // A member's own connected accounts are served by central (the tenant answers 404 for /connections/me/); the tenant-audience token is accepted there.
42
+ const central = { baseUrl: `${config.tenant.centralUrl}/api/v1`, fetch: authorizedFetch as typeof fetch };
43
+ return {
44
+ corpus: createNativeCorpusApi({ baseUrl: config.tenant.url, authorizedFetch }),
45
+ notes: wantsNotes ? createVoiceNotesController({ api: createNativeVoiceApi({ baseUrl: config.tenant.url, authorizedFetch }) }) : null,
46
+ member: { connections: createConnectionsMeApi(central), mcpTokens: createMcpTokensApi(tenant) },
47
+ };
48
+ }
@@ -0,0 +1,38 @@
1
+ import type { SecretStore } from '../recording/session';
2
+ import type { AudioDriver, SessionInspector } from '../recording/recorderAudio';
3
+ import type { BackgroundTasks } from '../recording/lifecycle';
4
+ import type { PermissionsApi } from '../recording/permissions';
5
+ import type { RecordingFile } from '../recording/recovery';
6
+
7
+ export interface TextFiles {
8
+ exists(path: string): Promise<boolean>;
9
+ read(path: string): Promise<string>;
10
+ write(path: string, value: string): Promise<void>;
11
+ }
12
+
13
+ /** The device bindings of the recording path (expo-audio, the audio-session native module, the file system). */
14
+ export interface RecordingDevice {
15
+ driver: AudioDriver;
16
+ session: SessionInspector;
17
+ background: BackgroundTasks;
18
+ permissions: PermissionsApi;
19
+ openSettings(): Promise<void>;
20
+ fileSize(uri: string): Promise<number>;
21
+ removeFile(uri: string): Promise<void>;
22
+ listRecordings(): Promise<RecordingFile[]>;
23
+ /** A multipart file part for an upload. */
24
+ filePart(uri: string): Blob;
25
+ }
26
+
27
+ /**
28
+ * Everything the app shell cannot get from the packages: native modules the Expo app autolinks. A Foundry app supplies
29
+ * this once (`src/device.ts` in the template) and never touches app logic.
30
+ */
31
+ export interface FoundryDevice {
32
+ /** Keychain-backed refresh-token storage (`new SecureTokenStorage()`). */
33
+ tokenStorage: SecretStore;
34
+ files: TextFiles;
35
+ documentUri(name: string): string;
36
+ /** Required when `features.recording` is on. */
37
+ recording?: RecordingDevice;
38
+ }
@@ -0,0 +1,90 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { ScrollView, View } from 'react-native';
3
+ import { Alert, DataList, Header, ListRow, Spinner, StatusChip, Text, useTheme } from '@startsimpli/ui-native';
4
+ import type { TenantEntity } from '../../../corpus/entities';
5
+ import type { FoundryTab, TabContext } from '../../components/FoundryTabsShell';
6
+ import { useControllerState } from '../../components/useControllerState';
7
+ import type { NativeCorpusApi } from '../../corpus/api';
8
+ import type { FoundryEntityType } from '../config/types';
9
+ import { entityFields, entityRow, type EntityRowView } from './format';
10
+
11
+ type Api = Pick<NativeCorpusApi, 'entities' | 'lists'>;
12
+
13
+ function EntityList({ api, type, spec, onOpen }: { api: Api; type: string; spec: FoundryEntityType; onOpen: (id: string) => void }) {
14
+ const list = useMemo(() => api.lists.entities({ type }), [api, type]);
15
+ const state = useControllerState(list);
16
+ useEffect(() => { void list.refresh(); }, [list]);
17
+ const rows = useMemo(() => state.items.map((e) => entityRow(e, spec)), [state.items, spec]);
18
+ const plural = spec.plural ?? `${spec.label}s`;
19
+ return (
20
+ <View style={{ flex: 1 }} testID={`entity-${type}-screen`}>
21
+ <Header title={plural} subtitle={state.count !== null ? `${state.count}` : undefined} />
22
+ <DataList<EntityRowView>
23
+ testID={`entity-${type}-list`}
24
+ data={rows}
25
+ keyExtractor={(r) => r.id}
26
+ renderItem={({ item }) => (
27
+ <View testID={`entity-${item.id}`}>
28
+ <ListRow
29
+ title={item.title}
30
+ subtitle={item.subtitle}
31
+ trailing={item.status ? <StatusChip status={item.status} /> : undefined}
32
+ onPress={() => onOpen(item.id)}
33
+ />
34
+ </View>
35
+ )}
36
+ loading={state.loading}
37
+ onRefresh={() => { void list.refresh(); }}
38
+ error={state.error}
39
+ onRetry={() => { void list.refresh(); }}
40
+ hasMore={state.hasMore}
41
+ loadingMore={state.loadingMore}
42
+ onLoadMore={() => { void list.loadMore(); }}
43
+ emptyTitle={`No ${plural.toLowerCase()} yet`}
44
+ emptyDescription={`${plural} show up here as they arrive.`}
45
+ />
46
+ </View>
47
+ );
48
+ }
49
+
50
+ function EntityDetail({ api, spec, id, onBack }: { api: Api; spec: FoundryEntityType; id: string; onBack: () => void }) {
51
+ const theme = useTheme();
52
+ const [entity, setEntity] = useState<TenantEntity | null>(null);
53
+ const [error, setError] = useState<string | null>(null);
54
+ useEffect(() => {
55
+ let live = true;
56
+ setEntity(null);
57
+ setError(null);
58
+ api.entities.get(id).then((e) => { if (live) setEntity(e); }, (e: unknown) => { if (live) setError(e instanceof Error ? e.message : 'Could not load this record.'); });
59
+ return () => { live = false; };
60
+ }, [api, id]);
61
+ const row = entity ? entityRow(entity, spec) : null;
62
+ return (
63
+ <View style={{ flex: 1 }}>
64
+ <Header testID="entity-detail" title={row?.title ?? spec.label} subtitle={row?.subtitle} onBack={onBack} />
65
+ <ScrollView contentContainerStyle={{ padding: theme.spacing.lg, gap: theme.spacing.md }}>
66
+ {error ? <Alert variant="destructive">{error}</Alert> : null}
67
+ {!entity && !error ? <Spinner /> : null}
68
+ {row?.status ? <StatusChip status={row.status} /> : null}
69
+ {entity ? entityFields(entity).map((f) => (
70
+ <View key={f.key} style={{ gap: 2 }}>
71
+ <Text variant="caption">{f.label}</Text>
72
+ <Text selectable>{f.value}</Text>
73
+ </View>
74
+ )) : null}
75
+ </ScrollView>
76
+ </View>
77
+ );
78
+ }
79
+
80
+ /** A tab over any tenant entity type, driven by the config's `entityTypes[type]` (fields, labels). */
81
+ export function entityTab({ api, tab, type, spec }: { api: Api; tab: { key: string; label: string }; type: string; spec: FoundryEntityType }): FoundryTab {
82
+ return {
83
+ key: tab.key,
84
+ label: tab.label,
85
+ resetOnLeave: true,
86
+ render: (ctx: TabContext) => (ctx.route
87
+ ? <EntityDetail api={api} spec={spec} id={ctx.route.id} onBack={ctx.back} />
88
+ : <EntityList api={api} type={type} spec={spec} onOpen={(id) => ctx.push(id)} />),
89
+ };
90
+ }