@altertable/data-app 0.72.0 → 0.74.0

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 (112) hide show
  1. package/AGENTS.md +5 -61
  2. package/CONTRIBUTING.md +130 -181
  3. package/README.md +3 -4
  4. package/REFERENCE.md +35 -345
  5. package/dist/chunks/contract-BeLPJwlO.js +558 -0
  6. package/dist/chunks/contract-BeLPJwlO.js.map +1 -0
  7. package/dist/chunks/contract-Di8SP74I.js +462 -0
  8. package/dist/chunks/contract-Di8SP74I.js.map +1 -0
  9. package/dist/chunks/diagnostics-BTZSlNtW.js +967 -0
  10. package/dist/chunks/diagnostics-BTZSlNtW.js.map +1 -0
  11. package/dist/chunks/format-BdFlv_xa.js +148 -0
  12. package/dist/chunks/format-BdFlv_xa.js.map +1 -0
  13. package/dist/chunks/operation-CSM9UmO3.js +134 -0
  14. package/dist/chunks/operation-CSM9UmO3.js.map +1 -0
  15. package/dist/chunks/request-body-H1qPmmTN.js +50 -0
  16. package/dist/chunks/request-body-H1qPmmTN.js.map +1 -0
  17. package/dist/client/index.js +273 -285
  18. package/dist/client/index.js.map +1 -13
  19. package/dist/core/appearance.js +171 -162
  20. package/dist/core/appearance.js.map +1 -10
  21. package/dist/core/config.js +49 -11
  22. package/dist/core/config.js.map +1 -9
  23. package/dist/core/contract.js +3 -73
  24. package/dist/core/format.js +1 -26
  25. package/dist/index.js +1 -12
  26. package/dist/internal.js +352 -397
  27. package/dist/internal.js.map +1 -15
  28. package/dist/server/index.js +85 -97
  29. package/dist/server/index.js.map +1 -10
  30. package/dist/types/chunks/appearance.d.ts +45 -0
  31. package/dist/types/chunks/contract.d.ts +720 -0
  32. package/dist/types/chunks/index.d.ts +240 -0
  33. package/dist/types/client/index.d.ts +3 -13
  34. package/dist/types/core/appearance.d.ts +2 -42
  35. package/dist/types/core/config.d.ts +36 -39
  36. package/dist/types/core/contract.d.ts +2 -114
  37. package/dist/types/core/format.d.ts +44 -17
  38. package/dist/types/index.d.ts +3 -3
  39. package/dist/types/internal.d.ts +312 -22
  40. package/dist/types/server/index.d.ts +15 -4
  41. package/docs/app-authoring.md +77 -128
  42. package/docs/client.md +29 -63
  43. package/docs/composition.md +44 -75
  44. package/docs/contract.md +60 -100
  45. package/docs/data-context.md +35 -61
  46. package/docs/diagnostics.md +45 -0
  47. package/docs/embed.md +86 -55
  48. package/docs/formatting-and-appearance.md +17 -38
  49. package/docs/hosted-apps.md +7 -14
  50. package/docs/layout.md +30 -47
  51. package/docs/local-data-apps.md +7 -7
  52. package/docs/react-embed.md +20 -26
  53. package/docs/react.md +10 -27
  54. package/docs/server-bun.md +2 -27
  55. package/docs/server.md +6 -12
  56. package/docs/stories-and-export.md +38 -40
  57. package/docs/styling.md +14 -22
  58. package/docs/ui-quality.md +5 -5
  59. package/docs/ui.md +93 -70
  60. package/docs/variables.md +142 -254
  61. package/docs/views.md +85 -116
  62. package/docs/widgets.md +100 -153
  63. package/docs/worker.md +15 -27
  64. package/package.json +3 -2
  65. package/dist/chunks/index-5a27erdg.js +0 -54
  66. package/dist/chunks/index-5a27erdg.js.map +0 -10
  67. package/dist/chunks/index-9yxr7nmm.js +0 -742
  68. package/dist/chunks/index-9yxr7nmm.js.map +0 -17
  69. package/dist/chunks/index-j5q5n3ra.js +0 -151
  70. package/dist/chunks/index-j5q5n3ra.js.map +0 -10
  71. package/dist/chunks/index-q75zm3a7.js +0 -153
  72. package/dist/chunks/index-q75zm3a7.js.map +0 -11
  73. package/dist/chunks/index-vhaec7m5.js +0 -30
  74. package/dist/chunks/index-vhaec7m5.js.map +0 -10
  75. package/dist/chunks/index-zp78caex.js +0 -1047
  76. package/dist/chunks/index-zp78caex.js.map +0 -19
  77. package/dist/core/contract.js.map +0 -9
  78. package/dist/core/format.js.map +0 -9
  79. package/dist/index.js.map +0 -9
  80. package/dist/types/client/annotations.d.ts +0 -27
  81. package/dist/types/client/data-client.d.ts +0 -43
  82. package/dist/types/client/download.d.ts +0 -5
  83. package/dist/types/client/iframe.d.ts +0 -59
  84. package/dist/types/client/location.d.ts +0 -13
  85. package/dist/types/client/logger.d.ts +0 -14
  86. package/dist/types/client/messages.d.ts +0 -7
  87. package/dist/types/client/navigation.d.ts +0 -15
  88. package/dist/types/client/transport.d.ts +0 -15
  89. package/dist/types/core/annotations.d.ts +0 -99
  90. package/dist/types/core/bridge-endpoint.d.ts +0 -21
  91. package/dist/types/core/bridge.d.ts +0 -172
  92. package/dist/types/core/data-view.d.ts +0 -46
  93. package/dist/types/core/date-format.d.ts +0 -24
  94. package/dist/types/core/date-range.d.ts +0 -20
  95. package/dist/types/core/dimension-source.d.ts +0 -64
  96. package/dist/types/core/dimension.d.ts +0 -71
  97. package/dist/types/core/facets.d.ts +0 -13
  98. package/dist/types/core/filters.d.ts +0 -45
  99. package/dist/types/core/invariant.d.ts +0 -2
  100. package/dist/types/core/keys.d.ts +0 -2
  101. package/dist/types/core/logger.d.ts +0 -12
  102. package/dist/types/core/messages.d.ts +0 -62
  103. package/dist/types/core/navigation.d.ts +0 -11
  104. package/dist/types/core/operation-types.d.ts +0 -80
  105. package/dist/types/core/operation.d.ts +0 -20
  106. package/dist/types/core/presentation.d.ts +0 -9
  107. package/dist/types/core/queries.d.ts +0 -84
  108. package/dist/types/core/reading.d.ts +0 -17
  109. package/dist/types/core/uuid.d.ts +0 -2
  110. package/dist/types/core/variables.d.ts +0 -133
  111. package/dist/types/server/handler.d.ts +0 -13
  112. package/dist/types/server/request-body.d.ts +0 -4
package/docs/client.md CHANGED
@@ -1,20 +1,23 @@
1
1
  # Client
2
2
 
3
- Import `createDataClient()` and `DataAppError` from
4
- `@altertable/data-app/client`. The client uses Fetch APIs and has no React or
5
- server dependency.
3
+ Use this guide when customizing client delivery. Standard apps keep the
4
+ starter's client. Import `createDataClient()` from `@altertable/data-app/client`.
6
5
 
7
6
  ## HTTP operations
8
7
 
9
8
  ```ts
10
9
  import { createDataClient } from '@altertable/data-app/client';
11
- import type { operations } from './operations';
10
+ import type { operations } from './operations.ts';
12
11
 
13
12
  const client = createDataClient<typeof operations>();
14
- const response = await client.query('activity', input, { signal });
13
+ const response = await client.query(
14
+ 'sampleCountsByGroup',
15
+ { groupName: '' },
16
+ { signal }
17
+ );
15
18
  ```
16
19
 
17
- The app defines `operations`, `input`, and an optional cancellation `signal`.
20
+ The app supplies `operations` and an optional cancellation `signal`.
18
21
  Inputs and data are inferred from the operation map and `run()`. Keep the import
19
22
  type-only so operation implementations stay on the server.
20
23
 
@@ -23,51 +26,33 @@ The default endpoint is `/api/data`. Override it with
23
26
  implementation. Calls POST JSON to `/api/data/:operation`; the client sends
24
27
  operation inputs rather than SQL or credentials.
25
28
 
26
- `DataResponse` contains `data`, the exact request `input`, `requestId`,
27
- `queriedAt`, `queryIds`, and executed `queries`. Use the returned input when labeling stale data during a refresh.
28
- HTTP and iframe delivery validate the success envelope: data, request ID,
29
- query timestamp, query IDs, and optional query evidence. Malformed responses
30
- reject with `invalid_response`.
31
-
32
- `DataAppError` exposes a `code` and optional `requestId`; cancellation follows
33
- the supplied abort signal.
29
+ For direct client calls, render `response.data` and label it with `response.input`
30
+ so retained results keep their original scope during refresh. React views handle
31
+ this automatically. For custom error handling, import `DataAppError` from the same
32
+ entry for public codes and request IDs. Pass an abort signal to cancel a request.
34
33
 
35
34
  See [contracts](contract.md), [server handlers](server.md), and
36
35
  [React bindings](react.md).
37
36
 
38
37
  ## Browser-owned operations for bundle apps
39
38
 
40
- Start with the complete [single-file example](app-authoring.md#use-release-matched-starters)
41
- and [data app authoring guide](hosted-apps.md).
42
39
  Bundle apps pass their operation registry as a value:
43
40
 
44
41
  ```ts
45
- import { connectionCheck } from '@altertable/data-app/contract';
46
42
  import { createDataClient } from '@altertable/data-app/client';
47
43
 
48
- // dataApp declares a connection query.
49
- const client = createDataClient({
50
- operations: { connection: connectionCheck(dataApp.queries) },
51
- });
52
- const response = await client.query('connection', {});
44
+ // ... operations declared with dataApp.defineOperation()
45
+ const client = createDataClient({ operations });
46
+ const response = await client.query('sampleCountsByGroup', { groupName: '' });
53
47
  ```
54
48
 
55
- The client runs input parsing and operation logic in the browser.
56
- Operation policy bounds rows, duration, and response size and records query evidence. Each query sends `{ statement, limit, params? }`
57
- to the installed iframe bridge's `data:sql` route; the host needs no operation
58
- registry. Results include query evidence. Credentials remain backend-owned.
49
+ Operations run in the browser and query through the host's `data:sql` route.
50
+ The trusted bootstrap installs the bridge before app execution. A custom runtime
51
+ must install it first or supply an authorized `lakehouse` adapter.
59
52
 
60
- The trusted bootstrap installs the bridge for bundle apps. A custom runtime must
61
- install it before querying. An explicit `lakehouse` can supply another authorized
62
- adapter, including `bridge.lakehouse` or a local server adapter. `operations` cannot
63
- be combined with `transport`, `endpoint`, or `fetch`; a `lakehouse` requires
64
- `operations`. The exported `DataClientOptions` union rejects mixed configurations
65
- at compile time. Omitting `operations` preserves named HTTP/iframe operation delivery.
66
-
67
- The host must implement and authorize the [SQL route](embed.md#sql-query-route).
68
- Browser policies improve app behavior; backend access and resource limits must be
69
- enforced independently because a frame can forge requests. Cancellation reaches
70
- the host through the existing bridge cancellation protocol.
53
+ Do not combine `operations` with `transport`, `endpoint`, or `fetch`. Browser
54
+ policy bounds app requests; the [host SQL handler](embed.md#sql-query-route)
55
+ must independently enforce access and resource limits.
71
56
 
72
57
  ## Iframe transport
73
58
 
@@ -110,10 +95,9 @@ const messages = createMessageClient(routes, bridge.request);
110
95
  const result = await messages.request('demo:echo', 'hello', { signal });
111
96
  ```
112
97
 
113
- The app supplies shared `routes` and optional `signal`. Both client and host
114
- validate messages. The bridge retains opaque host state through `snapshot()` and
115
- `subscribe(listener)`; only authenticated, current-session state reaches subscribers.
116
- It never changes browser history or interprets the host state.
98
+ The app supplies shared `routes` and optional `signal`. For a framework-neutral
99
+ UI that supports [content sizing](embed.md#content-sizing), call
100
+ `bridge.supportContentSizing()` and use its returned cleanup function.
117
101
 
118
102
  ## App navigation
119
103
 
@@ -131,25 +115,7 @@ navigation.publish('replace');
131
115
  navigation.dispose();
132
116
  ```
133
117
 
134
- The adapter provides `snapshot()`, `subscribe()`, and `update()`. Opaque sandboxes keep
135
- search/hash in memory; URL frames preserve their URL and local-preview parent
136
- marker. Host Back/Forward state is applied without publishing it back.
137
-
138
- `getDataAppNavigation()` discovers an installed or verified local-preview bridge
139
- and shares one adapter per document. React mounting and URL-backed controls call
140
- it automatically. Apps that only use data delivery do not attach navigation.
141
-
142
- ## Pending request limits
143
-
144
- Each iframe bridge accepts at most 128 unresolved requests, including requests
145
- waiting for the connection handshake. Further calls reject with `bridge_busy`
146
- until a pending call completes, is cancelled, or times out. This bounds the
147
- client's promises, timers, and queued messages.
148
-
149
- Hosts enforce their own request limits independently of the client.
150
-
151
- A failed local-preview verification can be retried by the next explicit data
152
- request. Concurrent callers share the current verification attempt; aborting
153
- one caller does not cancel the others. Retrying does not automatically repeat
154
- a data operation or bypass the configured parent-origin check, and verification
155
- failure never falls back to untrusted iframe or HTTP delivery.
118
+ The adapter owns search/hash synchronization with host Back/Forward navigation.
119
+ Opaque frames keep location in memory. `getDataAppNavigation()` discovers and
120
+ shares the installed adapter; React mounting and URL-backed controls attach it
121
+ automatically. Dispose a manually created adapter before removing its transport.
@@ -1,84 +1,53 @@
1
1
  # Compose an exploration
2
2
 
3
- Start with the question the user needs to answer. Define its population, period,
4
- measures, and comparison. Choose the analytical flow before choosing widgets;
5
- a focused answer may need only a chart and a paragraph.
3
+ Define the question, population, period, measures, and comparison before choosing
4
+ widgets. A focused answer may need only a chart and a paragraph.
6
5
 
7
6
  ## Build a sequence of questions
8
7
 
9
8
  Lead with the strongest supported result and visible scope. Give each section a
10
- question that advances the investigation: what happened, when or against what
11
- baseline, where it differs, and which details support the finding. Omit steps
12
- that add no useful evidence.
13
-
14
- Give each element a purpose:
15
-
16
- | Element | Purpose |
17
- | --------- | ------------------------------------------------------------------------ |
18
- | Metric | Establish magnitude or change. |
19
- | Chart | Reveal the pattern that answers the section's question. |
20
- | Narrative | Explain interpretation, qualify a claim, or suggest the next comparison. |
21
- | Table | Support exact comparisons and inspection. |
22
- | Filter | Test a relevant hypothesis or change the scope. |
23
-
24
- Use `<Stack>` for reading order, `<SectionHeading>` for questions, and `<Grid>`
25
- for peer widgets users should compare together. Give the main visual enough
26
- space and preserve reading order on phones. Place explanations beside their
27
- evidence, using `<TextContent>` for introductions or `<TextWidget>` for a panel.
28
- See [layout](layout.md) and [widget selection](widgets.md#choose-a-visualization).
29
-
30
- Keep a connected investigation on one page. Use app tabs for distinct analytical
31
- questions and widget `views` for alternate representations of the same dataset.
32
-
33
- ## Make filters serve the question
34
-
35
- Offer controls with a clear analytical use, such as dates to locate a change or
36
- channels to test whether it is widespread. Choose useful defaults with adequate
37
- coverage and make each filter's scope clear.
38
-
39
- Keep related metrics, charts, and prose consistent in population, definitions,
40
- units, and comparison periods. Explain deliberate differences. Show counts
41
- alongside rates when sample size matters; calculate overall rates from their
42
- numerators and denominators rather than averaging subgroup rates.
43
-
44
- Derive findings and qualifications from the displayed result and its input.
45
- A claim about all channels may no longer hold after selecting one. Retain the
46
- displayed scope during refresh or failure. See [variables](variables.md) and
47
- [displayed results](views.md#preserve-displayed-results).
9
+ question: what happened, when, where it differs, or what supports the finding.
10
+ Omit sections that add no evidence.
11
+
12
+ | Element | Purpose |
13
+ | --------- | ------------------------------------------------------ |
14
+ | Metric | Establish magnitude or change |
15
+ | Chart | Reveal the pattern that answers the section's question |
16
+ | Narrative | Interpret, qualify, or suggest the next comparison |
17
+ | Table | Support exact comparisons and inspection |
18
+ | Filter | Test a hypothesis or change scope |
19
+
20
+ Place explanations beside their evidence. Use [layout primitives](layout.md)
21
+ for reading order and peer comparisons, and [choose charts](widgets.md#choose-a-visualization)
22
+ by the question they answer. Use app tabs for distinct questions and widget
23
+ `views` for alternate representations of one dataset.
24
+
25
+ ## Keep comparisons consistent
26
+
27
+ Choose useful filter defaults with adequate coverage. Keep related metrics,
28
+ charts, and prose consistent in population, definitions, units, and periods;
29
+ explain deliberate differences. Show counts alongside rates when sample size
30
+ matters. Compute overall rates from numerators and denominators rather than
31
+ averaging subgroup rates.
32
+
33
+ Derive claims from the [displayed result and its input](views.md#preserve-displayed-results).
34
+ A claim about all channels may stop being valid after selecting one. Observed
35
+ differences support investigation; they do not establish a cause.
48
36
 
49
37
  ## Example: where are we losing signups?
50
38
 
51
- Define funnel entry, the completion window, and channel attribution. Compare
52
- populations with equal opportunity to complete; identify incomplete observations.
53
- Then compose the page in this order:
54
-
55
- | Question | Display and purpose |
56
- | -------------------------------------- | ---------------------------------------------------------------------------------------------------- |
57
- | How many starters complete? | Conversion against a comparable prior period, with starter and completion counts to establish scale. |
58
- | When does conversion change? | Trend to locate the change, with incomplete periods identified. |
59
- | At which step, and for which channels? | Funnel and channel comparisons with counts and rates to locate differences. |
60
- | What supports the comparison? | Table of channel and step counts, denominators, and rates for inspection and export. |
61
-
62
- Use one declared view for these related datasets. Put outcome metrics in a
63
- `<Grid>`, give the trend its own row, then show the funnel, channel comparison,
64
- and table. Reuse datasets for charts and tables, and bind narrative to the same
65
- source. See [views](views.md) and [bindings](widgets.md#declare-datasets-and-metrics).
66
-
67
- Let the date filter select funnel entry dates and the channel filter affect every
68
- section. Start with all channels and adequate coverage. Selecting one channel
69
- should help compare its steps and periods; update the headline to match that scope.
70
-
71
- ## Distill the story
72
-
73
- Select one to four findings that answer the main question from the displayed
74
- result. Reuse its bindings, scope, and evidence in the story and CSV export.
75
- See [stories and export](stories-and-export.md).
76
-
77
- For the signup example, present the conversion change, the step or channel where
78
- the difference is largest, and any qualification about counts or coverage, when
79
- supported. Observed differences suggest where to investigate; they do not
80
- establish a cause.
81
-
82
- Verify the initial scope and a changed filter: does each section advance the
83
- question, and does the story agree with the visible evidence? Check reading order
84
- and context on phones and through the [UI quality states](ui-quality.md).
39
+ Define funnel entry, completion window, and channel attribution. Compare
40
+ populations with equal opportunity to complete and identify incomplete periods.
41
+
42
+ | Question | Display |
43
+ | ------------------------------------- | -------------------------------------------------------- |
44
+ | How many starters complete? | Conversion versus a comparable prior period, with counts |
45
+ | When does conversion change? | Trend with incomplete periods identified |
46
+ | At which step and for which channels? | Funnel and channel comparisons with counts and rates |
47
+ | What supports the comparison? | Table of counts, denominators, and rates |
48
+
49
+ Use one view for these related datasets. Let dates select funnel entry dates and
50
+ channel filters affect every section. Reuse datasets for charts and tables.
51
+ Select one to four supported findings for the [story](stories-and-export.md).
52
+ Verify that changing a filter updates every claim and preserves a useful reading
53
+ order.
package/docs/contract.md CHANGED
@@ -1,139 +1,99 @@
1
- # Contracts
1
+ # Queries and operations
2
2
 
3
- Import operation definitions, parsers, and shared types from
4
- `@altertable/data-app/contract`. This entry is safe to import in browser and server
5
- modules. The app declaration is browser-safe and includes its SQL registry. For HTTP apps,
6
- keep operation implementations, credentials, and authorization on the server; browser modules
7
- import operation types using `import type`.
3
+ Keep the starter's `defineDataApp()` declaration and operation registry. Declare
4
+ named SQL queries with typed `params` and `projections`; execute them through
5
+ `dataApp.defineOperation()`. Use descriptive `lowerCamelCase` query names.
8
6
 
9
7
  ## Execute named queries
10
8
 
11
- Declare queries with `defineDataApp()` and operations with `dataApp.defineOperation()`.
12
- Use descriptive `lowerCamelCase` query names. Declare parameter types in `params`
13
- (use `{}` for none) and returned aliases in `projections`.
9
+ This is the hosted starter's query contract inside `defineDataApp()`:
14
10
 
15
11
  ```ts
16
12
  import { defineDataApp } from '@altertable/data-app';
17
13
 
18
14
  const dataApp = defineDataApp({
19
- title: 'Products',
20
- description: 'Explore products for the selected organization.',
21
- scope: { organization: 'demo', environment: 'production' },
22
- appearance: { theme: 'system' },
15
+ // ... title, description, and scope
23
16
  queries: {
24
- products: {
25
- statement:
26
- 'SELECT name, unit_price AS "unitPrice" FROM products WHERE org_id = $orgId LIMIT $limit',
17
+ sampleCountsByGroup: {
18
+ statement: `
19
+ WITH sample_counts(group_name, sample_count) AS (VALUES ('Alpha', 2200000), ('Beta', 0))
20
+ SELECT group_name, sample_count FROM sample_counts
21
+ WHERE $groupName = '' OR group_name = $groupName
22
+ ORDER BY group_name LIMIT $limit`,
27
23
  params: {
28
- orgId: { type: 'string' },
24
+ groupName: { type: 'string', defaultValue: '' },
29
25
  limit: { type: 'number', defaultValue: 10 },
30
26
  },
31
27
  projections: {
32
- name: { type: 'string' },
33
- unitPrice: { type: 'number', nullable: true },
28
+ group_name: { type: 'string' },
29
+ sample_count: { type: 'number' },
34
30
  },
35
31
  },
36
32
  },
37
33
  });
34
+ ```
38
35
 
39
- const products = dataApp.defineOperation({
40
- input: parseProductInput,
41
- checks: [{}],
42
- policy: { maxQueryRows: 100, maxDurationMs: 15000 },
43
- async run({ query }, input) {
44
- const result = await query('products', input);
45
- return result.rows;
46
- },
47
- });
36
+ Replace fixture SQL with inspected data. Preserve supplied registry SQL. Keep
37
+ operation inputs flat; derive SQL parameters inside `run()`:
38
+
39
+ ```ts
40
+ import { parseCount } from '@altertable/data-app/contract';
41
+
42
+ // ... dataApp and parseSampleCountFilter
43
+ const operations = {
44
+ sampleCountsByGroup: dataApp.defineOperation({
45
+ input: parseSampleCountFilter,
46
+ checks: [
47
+ { groupName: '' },
48
+ { groupName: 'Alpha' },
49
+ { groupName: 'missing' },
50
+ ],
51
+ policy: { maxQueryRows: 10, maxDurationMs: 15000 },
52
+ async run({ query }, { groupName }) {
53
+ const result = await query('sampleCountsByGroup', { groupName });
54
+ return result.rows.map(row => ({
55
+ groupName: row.group_name,
56
+ sampleCount: parseCount(row.sample_count),
57
+ }));
58
+ },
59
+ }),
60
+ };
48
61
  ```
49
62
 
50
- `parseProductInput()` is app-owned. Validate inputs there and business rules in
51
- `run()`. Derive operation data from `query()` rows; clients and views infer the
52
- returned type. Handle empty results. HTTP results must be JSON-serializable.
53
- Include representative valid inputs in `checks`.
63
+ The starter supplies `parseSampleCountFilter()` and `parseCount()`. Validate
64
+ unknown input in the parser and business rules in `run()`. Include representative
65
+ valid inputs in `checks`. Derive results from `query()` rows without duplicate
66
+ schemas or type assertions; clients and views infer the returned type.
67
+ HTTP results must be JSON-serializable.
54
68
 
55
- Host `queryParams` supplies protected parameters; callers cannot override them.
56
- Other values come from `query()` arguments or `defaultValue`. Missing values are
57
- checked before execution. `query(name, params, { limit })` inherits the operation's
58
- row limit and cancellation signal.
69
+ Host `queryParams` supplies protected parameters that callers cannot override.
70
+ Other values come from `query()` arguments or defaults. The host/backend enforces
71
+ data access and limits.
59
72
 
60
73
  ### Declare query projections
61
74
 
62
- Inspect each query and declare every returned alias with `{ type, nullable? }`.
63
- Result keys keep the exact SQL names; alias columns in SQL to change casing, as
64
- with `"unitPrice"` above.
65
- Determine nullability from the schema and SQL, even when sampled rows contain no
66
- nulls. Update projections when changing SQL.
75
+ Declare every returned SQL alias with `{ type, nullable? }` and keep its exact
76
+ casing. Infer nullability from the schema and SQL, not sampled rows. Update
77
+ projections when changing SQL. `query()` converts cells to declared types;
78
+ return SQL text and declare `string` when exact numeric precision matters.
67
79
 
68
- `query()` converts result cells to the declared types before `run()` uses them.
69
- Numbers that cannot be converted become `"##ERROR##"`; booleans use JavaScript
70
- truthiness. Nulls pass through unless `nullable: false`. Parameters are validated
71
- without conversion. For exact numeric precision, return SQL text
72
- and declare `string`.
73
-
74
- Results include query evidence; use `products.queryNames` with `createDataContext()`
75
- to bind it. The host/backend enforces data access and limits; see
76
- [server authorization](server.md).
80
+ Use `operations.sampleCountsByGroup.queryNames` for context and evidence.
77
81
 
78
82
  ## Shared date ranges
79
83
 
80
- Use `defineDateRangeContract()` in a browser-safe module to share source coverage,
81
- time zone, maximum range, and comparison rules between the server parser and
82
- React variables. The server uses `calendar.parseRequest()`; React uses the same
83
- contract with `dateRangeVariable()`.
84
+ For period-driven analysis, declare `defineDateRangeContract()` from
85
+ `@altertable/data-app/contract` once and share it between the operation's parser
86
+ and `defineTimeView()`:
84
87
 
85
88
  ```ts
86
89
  import { defineDateRangeContract } from '@altertable/data-app/contract';
87
90
 
88
- export const calendar = defineDateRangeContract({
91
+ const calendar = defineDateRangeContract({
89
92
  minDate: '2026-01-01',
90
93
  maxRangeDays: 90,
91
94
  timeZone: 'UTC',
92
95
  });
93
96
  ```
94
97
 
95
- `parseEmptyInput()`, `parseCount()`, and `parseDateRangeInput()` validate common inputs
96
- and query values. `connectionCheck(dataApp.queries)` runs the registered `connection` query. A successful connectivity check confirms access; it is not an
97
- analysis result.
98
-
99
- See [server authorization](server.md) and [React views](react.md) for the two
100
- sides of an operation.
101
-
102
- ## Message routes
103
-
104
- Message contracts describe the payloads allowed between an embedded app and its
105
- host. Share these contracts with the app; keep handlers and authorization in the
106
- host/server.
107
-
108
- Name routes `{scope}:{action}`, for example `data:query` or `navigation:update`.
109
-
110
- ```ts
111
- import {
112
- createMessageRouter,
113
- defineMessageRoute,
114
- navigationUpdateRoute,
115
- } from '@altertable/data-app/contract';
116
- import { createNavigationHandler } from '@altertable/data-app-embed';
117
-
118
- const routes = {
119
- 'demo:echo': defineMessageRoute({ input: parseString, output: parseString }),
120
- 'navigation:update': navigationUpdateRoute,
121
- };
122
- const router = createMessageRouter(routes, {
123
- 'demo:echo': value => value,
124
- 'navigation:update': createNavigationHandler(),
125
- });
126
- ```
127
-
128
- The app defines `parseString()` to validate unknown values. `router.dispatch()` checks
129
- registered routes, input, output, and cancellation. `MessageRoutingError` exposes
130
- an intentional public code, message, and optional request ID; other handler
131
- errors are replaced with a generic failure.
132
-
133
- `defineDataQueryRoute(operationContracts)` validates the selected operation's
134
- input and preserves its response evidence. It infers the result type from the
135
- selected operation's `run` when used with `createMessageClient()`. Share input
136
- parsers and operation types, not operation implementations containing SQL or credentials.
137
- `dataAppRoutes` supplies generic `data:query` and `navigation:update` contracts;
138
- generic hosts must delegate operation validation and authorization to their
139
- server. Request handlers receive `{ signal }` for cancellation.
98
+ Use `calendar.parseRequest()` to validate periods. The contract owns source
99
+ coverage, time zone, maximum range, and comparison rules.
@@ -1,23 +1,43 @@
1
1
  # Data context and evidence
2
2
 
3
- Set `dataContext: context` in each view for source descriptions, glossary, and
4
- permitted query evidence. App inspection and the view's sections use that context.
5
- Keep glossary query references scoped to that view's executed queries. Detail
6
- views declare their own context when their queries differ.
7
- Render registered identifiers where `<DataIdentifier>` is used.
3
+ Continue the starter's operation and context. Use its derived `queryNames` for
4
+ business definitions and evidence. Reference only queries the view executes.
8
5
 
9
- Physical source identifiers name inspected tables and columns. Glossary entries
10
- explain business meaning. Query names link those definitions and displayed claims
11
- to their execution evidence. Keep all three explicit.
6
+ ## Bind evidence
7
+
8
+ ```tsx
9
+ import { createDataContext } from '@altertable/data-app-react';
10
+
11
+ // ... operations
12
+ const queryNames = operations.sampleCountsByGroup.queryNames;
13
+ const sampleDataContext = createDataContext(queryNames)({
14
+ description: 'Sample counts for the selected groups.',
15
+ glossary: {
16
+ sampleCount: {
17
+ term: 'Sample count',
18
+ definition: 'The number of samples in each group.',
19
+ queryNames: [queryNames.sampleCountsByGroup],
20
+ },
21
+ },
22
+ });
23
+ ```
24
+
25
+ Import `createDataContext()` from `@altertable/data-app-react`. Supply
26
+ `dataContext: sampleDataContext` on `sampleCountsView`, then use its glossary IDs
27
+ in `view.metric()` and `view.dataset()`. Reuse those bindings in widgets and stories.
28
+ Detail views need their own context when their queries differ.
12
29
 
13
30
  ## Register source identifiers
14
31
 
15
- Use `defineDataIdentifiers()` from `@altertable/data-app-react` to register exact catalog, schema,
32
+ Once the queries use inspected physical sources, use `defineDataIdentifiers()` from `@altertable/data-app-react` to register exact catalog, schema,
16
33
  table, and field names. Use `<DataIdentifier>` in descriptions and glossary
17
34
  entries to render those source references consistently.
18
35
 
19
36
  ```tsx
20
- import { defineDataIdentifiers } from '@altertable/data-app-react';
37
+ import {
38
+ createDataContext,
39
+ defineDataIdentifiers,
40
+ } from '@altertable/data-app-react';
21
41
 
22
42
  const identifiers = defineDataIdentifiers({
23
43
  tables: {
@@ -31,63 +51,17 @@ const identifiers = defineDataIdentifiers({
31
51
  });
32
52
  const { DataIdentifier } = identifiers;
33
53
 
34
- <DataIdentifier id="tables.events" />;
35
- <DataIdentifier id="columns.events.identity" />;
36
- ```
37
-
38
- Pass `identifiers.definitions` to `createDataContext()` to reuse the source
39
- registry.
40
-
41
- ## Bind evidence
42
-
43
- ```tsx
44
- const queries = activity.queryNames;
45
- const context = createDataContext(queries)({
54
+ // ... queryNames for the inspected source
55
+ const eventDataContext = createDataContext(queryNames)({
46
56
  identifiers: identifiers.definitions,
47
57
  description: (
48
58
  <>
49
- Explore activity in <DataIdentifier id="tables.events" />.
59
+ Distinct <DataIdentifier id="columns.events.identity" /> values in{' '}
60
+ <DataIdentifier id="tables.events" />.
50
61
  </>
51
62
  ),
52
63
  glossary: {
53
- identities: {
54
- term: 'Tracked identities',
55
- definition: (
56
- <>
57
- Distinct <DataIdentifier id="columns.events.identity" /> values.
58
- </>
59
- ),
60
- queryNames: [queries.activity],
61
- },
64
+ // ... business definitions
62
65
  },
63
66
  });
64
- const evidence = context.evidence({
65
- id: 'identities',
66
- glossaryIds: ['identities'],
67
- queryNames: [queries.activity],
68
- });
69
- // activityView is declared with dataContext: context.
70
- const trackedIdentities = activityView.metric(
71
- {
72
- id: 'identities',
73
- glossaryId: 'identities',
74
- format: { kind: 'count', compact: true },
75
- },
76
- data => ({ current: data.count })
77
- );
78
- const finding = context.finding({
79
- id: 'activity',
80
- headline: 'What people do',
81
- visual: <ActivityChart />,
82
- evidence: { id: 'activity-evidence', queryNames: [queries.activity] },
83
- });
84
67
  ```
85
-
86
- Query inspection shows the executed SQL and resolved parameters; copy actions include both.
87
-
88
- Import context and identifier factories from `@altertable/data-app-react`. Use the operation’s derived `queryNames` for evidence.
89
-
90
- Use `view.metric(definition, select)` to register and bind a metric in one call.
91
- Declare dataset evidence references inside `view.dataset()`; the view registers
92
- and validates them too.
93
- Widgets and stories share its values and evidence; see [datasets and metrics](widgets.md#declare-datasets-and-metrics).
@@ -0,0 +1,45 @@
1
+ # App diagnostics and repair
2
+
3
+ Live capture reports observed query, operation, and widget failures together.
4
+ Repair actions send the complete observed report. Unvisited views and interactions
5
+ remain unverified. Reports include unfinished checks and omitted failure counts.
6
+
7
+ ## Host integration
8
+
9
+ Create one session outside the viewer lifecycle. Restore and retain its updated
10
+ state across revisions, reloads, and viewer recreation, even if saving fails.
11
+ Change the revision identifier when app source changes.
12
+
13
+ ```tsx
14
+ import { createDataAppRepairSession } from '@altertable/data-app-embed';
15
+ import {
16
+ DataAppBridge,
17
+ DataAppRepairBanner,
18
+ } from '@altertable/data-app-embed/react';
19
+
20
+ const session = createDataAppRepairSession({
21
+ state: restoredState, // New app: { automaticRequests: 0, attemptedRevisions: [] }
22
+ onStateChange: saveRepairState,
23
+ onRepairRequest: requestAgentRepair,
24
+ });
25
+
26
+ const viewer = (
27
+ <>
28
+ <DataAppRepairBanner session={session} />
29
+ <DataAppBridge
30
+ source={{ type: 'bundle', javascript }}
31
+ title="Data app"
32
+ repair={{ session, revision }}
33
+ onMessage={onMessage}
34
+ />
35
+ </>
36
+ );
37
+ ```
38
+
39
+ The host owns authorization, delivery, and state retention. `onStateChange` is
40
+ awaited before automatic delivery; reject if state cannot be retained. Three automatic
41
+ requests are allowed per session; manual requests and healthy revisions do not
42
+ reset the allowance. Callback resolution means acceptance, not agent execution.
43
+ Omit `onRepairRequest` when delivery or reliable state retention is unavailable;
44
+ the banner offers diagnostics to copy instead. Avoid sensitive values in errors.
45
+ Source locations use generated filenames and positions.