@altertable/data-app 0.67.0 → 0.69.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 (183) hide show
  1. package/AGENTS.md +6 -0
  2. package/CONTRIBUTING.md +27 -1
  3. package/README.md +18 -21
  4. package/THIRD_PARTY_NOTICES +18 -0
  5. package/dist/chunks/index-22d576sn.js +153 -0
  6. package/dist/chunks/index-22d576sn.js.map +11 -0
  7. package/dist/chunks/{index-ktmvs916.js → index-2sbp9h2b.js} +37 -21
  8. package/dist/chunks/index-2sbp9h2b.js.map +13 -0
  9. package/dist/chunks/{index-23dktynd.js → index-ap60vggk.js} +4 -4
  10. package/dist/chunks/{index-m6n8ctfc.js → index-cv36cyna.js} +4 -4
  11. package/dist/chunks/index-cv36cyna.js.map +10 -0
  12. package/dist/chunks/{index-ag0cgnvq.js → index-k766wwwr.js} +13 -9
  13. package/dist/chunks/index-k766wwwr.js.map +13 -0
  14. package/dist/chunks/{index-mt93ff2b.js → index-kwnqycjt.js} +2 -2
  15. package/dist/chunks/index-kwnqycjt.js.map +10 -0
  16. package/dist/chunks/index-m0gbxtgp.js +355 -0
  17. package/dist/chunks/index-m0gbxtgp.js.map +13 -0
  18. package/dist/chunks/{index-8qfxv0h5.js → index-qhzdzca2.js} +3951 -2242
  19. package/dist/chunks/index-qhzdzca2.js.map +118 -0
  20. package/dist/chunks/{index-x69p7cv7.js → index-r7b1ftwy.js} +3 -3
  21. package/dist/chunks/index-r7b1ftwy.js.map +10 -0
  22. package/dist/chunks/{index-ev2b5aaf.js → index-sx488hvs.js} +4 -4
  23. package/dist/chunks/{index-f5cnbrjz.js → index-wss3gd3h.js} +39 -9
  24. package/dist/chunks/index-wss3gd3h.js.map +13 -0
  25. package/dist/chunks/{index-qd5xgx6y.js → index-zcqxfwdq.js} +5 -12
  26. package/dist/chunks/index-zcqxfwdq.js.map +13 -0
  27. package/dist/client/index.js +6 -6
  28. package/dist/core/appearance.js +1 -1
  29. package/dist/core/config.js +3 -3
  30. package/dist/core/contract.js +3 -3
  31. package/dist/core/format.js +10 -2
  32. package/dist/core/format.js.map +1 -1
  33. package/dist/embed/index.js +26 -25
  34. package/dist/embed/index.js.map +4 -4
  35. package/dist/index.js +3 -3
  36. package/dist/local.js +166 -144
  37. package/dist/local.js.map +8 -7
  38. package/dist/preview.js +1456 -0
  39. package/dist/preview.js.map +17 -0
  40. package/dist/react/embed/index.js +1 -1
  41. package/dist/react/index.js +272 -103
  42. package/dist/react/index.js.map +10 -11
  43. package/dist/react/ui/index.js +2124 -1254
  44. package/dist/react/ui/index.js.map +20 -13
  45. package/dist/server.js +68 -57
  46. package/dist/server.js.map +7 -6
  47. package/dist/types/client/download.d.ts +5 -0
  48. package/dist/types/client/iframe.d.ts +4 -2
  49. package/dist/types/client/logger.d.ts +10 -2
  50. package/dist/types/core/annotations.d.ts +5 -0
  51. package/dist/types/core/appearance.d.ts +2 -0
  52. package/dist/types/core/bridge-endpoint.d.ts +2 -2
  53. package/dist/types/core/bridge.d.ts +22 -0
  54. package/dist/types/core/config.d.ts +5 -0
  55. package/dist/types/core/contract.d.ts +3 -1
  56. package/dist/types/core/date-format.d.ts +24 -0
  57. package/dist/types/core/dimension.d.ts +2 -1
  58. package/dist/types/core/filters.d.ts +4 -3
  59. package/dist/types/core/format.d.ts +5 -3
  60. package/dist/types/core/messages.d.ts +3 -1
  61. package/dist/types/core/operation-types.d.ts +7 -7
  62. package/dist/types/core/time-interval.d.ts +96 -0
  63. package/dist/types/core/variables.d.ts +13 -4
  64. package/dist/types/embed/host.d.ts +4 -4
  65. package/dist/types/react/annotations/annotation-editor-state.d.ts +2 -0
  66. package/dist/types/react/annotations/annotation-targets.d.ts +1 -0
  67. package/dist/types/react/annotations/getAnnotationProps.d.ts +5 -3
  68. package/dist/types/react/annotations/useAnnotationGeometry.d.ts +2 -2
  69. package/dist/types/react/bindings.d.ts +26 -3
  70. package/dist/types/react/date-formatting.d.ts +12 -0
  71. package/dist/types/react/hooks.d.ts +10 -9
  72. package/dist/types/react/index.d.ts +7 -2
  73. package/dist/types/react/search-suggestions.d.ts +8 -0
  74. package/dist/types/react/style-contract.d.ts +13 -5
  75. package/dist/types/react/ui/ChartLegend.d.ts +4 -3
  76. package/dist/types/react/ui/ChoicePicker.d.ts +2 -0
  77. package/dist/types/react/ui/ComposedChart.d.ts +1 -1
  78. package/dist/types/react/ui/DataApp.d.ts +5 -4
  79. package/dist/types/react/ui/DataAppFrame.d.ts +14 -3
  80. package/dist/types/react/ui/DataTable.d.ts +6 -4
  81. package/dist/types/react/ui/DataWidget.d.ts +4 -0
  82. package/dist/types/react/ui/DateDisplay.d.ts +9 -0
  83. package/dist/types/react/ui/DateRangePicker.d.ts +3 -1
  84. package/dist/types/react/ui/DateTimeTooltip.d.ts +3 -2
  85. package/dist/types/react/ui/DimensionPicker.d.ts +3 -1
  86. package/dist/types/react/ui/EmptyState.d.ts +1 -1
  87. package/dist/types/react/ui/FunnelChart.d.ts +20 -0
  88. package/dist/types/react/ui/GradientScroll.d.ts +8 -0
  89. package/dist/types/react/ui/Grid.d.ts +1 -1
  90. package/dist/types/react/ui/JourneyChart.d.ts +10 -0
  91. package/dist/types/react/ui/MetricWidget.d.ts +2 -0
  92. package/dist/types/react/ui/NumberFilterPicker.d.ts +3 -1
  93. package/dist/types/react/ui/PeriodSummary.d.ts +2 -1
  94. package/dist/types/react/ui/PickerField.d.ts +15 -0
  95. package/dist/types/react/ui/PopoverSurface.d.ts +5 -0
  96. package/dist/types/react/ui/RequestHint.d.ts +2 -2
  97. package/dist/types/react/ui/RetentionChart.d.ts +27 -0
  98. package/dist/types/react/ui/SearchField.d.ts +3 -1
  99. package/dist/types/react/ui/SearchTypeahead.d.ts +15 -0
  100. package/dist/types/react/ui/SectionHeading.d.ts +8 -0
  101. package/dist/types/react/ui/Select.d.ts +5 -1
  102. package/dist/types/react/ui/Sheet.d.ts +3 -1
  103. package/dist/types/react/ui/TableWidget.d.ts +8 -0
  104. package/dist/types/react/ui/Tabs.d.ts +4 -3
  105. package/dist/types/react/ui/VariableBar.d.ts +1 -1
  106. package/dist/types/react/ui/VisualizationWidget.d.ts +1 -1
  107. package/dist/types/react/ui/chart-data.d.ts +9 -0
  108. package/dist/types/react/ui/chart-date-axis.d.ts +15 -0
  109. package/dist/types/react/ui/chart-interaction.d.ts +21 -0
  110. package/dist/types/react/ui/chart-primitives.d.ts +7 -5
  111. package/dist/types/react/ui/chart-time.d.ts +16 -0
  112. package/dist/types/react/ui/chartColor.d.ts +1 -0
  113. package/dist/types/react/ui/icons.d.ts +3 -1
  114. package/dist/types/react/ui/index.d.ts +15 -4
  115. package/dist/types/react/ui/journey-flow.d.ts +49 -0
  116. package/dist/types/react/ui/metric-comparison.d.ts +2 -2
  117. package/dist/types/react/ui/metric.d.ts +2 -2
  118. package/dist/types/react/ui/presentation.d.ts +2 -0
  119. package/dist/types/react/ui/searchItems.d.ts +2 -0
  120. package/dist/types/react/ui/useSvgId.d.ts +2 -0
  121. package/dist/types/react/ui/variables.d.ts +1 -1
  122. package/dist/types/react/view-control-bar.d.ts +16 -0
  123. package/dist/types/react/view-controls.d.ts +3 -2
  124. package/dist/types/react/view-runtime.d.ts +3 -1
  125. package/dist/types/react/view.d.ts +14 -2
  126. package/dist/types/server/local.d.ts +3 -1
  127. package/dist/types/server/preview/host.d.ts +1 -0
  128. package/dist/types/server/preview/index.d.ts +16 -0
  129. package/dist/types/server/reload-channel.d.ts +6 -0
  130. package/dist/types/server/request-body.d.ts +4 -0
  131. package/dist/worker.js +2 -2
  132. package/docs/app-authoring.md +17 -9
  133. package/docs/client.md +1 -1
  134. package/docs/contract.md +10 -10
  135. package/docs/embed.md +11 -3
  136. package/docs/formatting-and-appearance.md +36 -5
  137. package/docs/layout.md +31 -8
  138. package/docs/react-embed.md +4 -4
  139. package/docs/react.md +1 -1
  140. package/docs/server-bun.md +25 -0
  141. package/docs/server.md +1 -1
  142. package/docs/styling.md +7 -28
  143. package/docs/ui.md +33 -12
  144. package/docs/variables.md +92 -15
  145. package/docs/views.md +13 -36
  146. package/docs/widgets.md +38 -23
  147. package/docs/worker.md +2 -1
  148. package/examples/starter-data-app/index.tsx +0 -1
  149. package/examples/starter-local-data-app/.bun-version +1 -0
  150. package/examples/starter-local-data-app/.node-version +1 -0
  151. package/examples/starter-local-data-app/.oxfmtrc.json +4 -0
  152. package/examples/starter-local-data-app/.oxlintrc.json +33 -0
  153. package/examples/starter-local-data-app/AGENTS.md +22 -0
  154. package/examples/starter-local-data-app/README.md +54 -0
  155. package/examples/starter-local-data-app/app.ts +22 -0
  156. package/examples/starter-local-data-app/bunfig.toml +2 -0
  157. package/examples/starter-local-data-app/package.json +33 -0
  158. package/examples/starter-local-data-app/src/App.tsx +8 -0
  159. package/examples/starter-local-data-app/src/assets.d.ts +1 -0
  160. package/examples/starter-local-data-app/src/data-context.ts +21 -0
  161. package/examples/starter-local-data-app/src/favicon.svg +13 -0
  162. package/examples/starter-local-data-app/src/index.html +14 -0
  163. package/examples/starter-local-data-app/src/main.tsx +7 -0
  164. package/examples/starter-local-data-app/src/operations.ts +6 -0
  165. package/examples/starter-local-data-app/src/server.ts +6 -0
  166. package/examples/starter-local-data-app/tsconfig.json +15 -0
  167. package/package.json +13 -3
  168. package/dist/chunks/index-8qfxv0h5.js.map +0 -108
  169. package/dist/chunks/index-ag0cgnvq.js.map +0 -13
  170. package/dist/chunks/index-dq7b35fn.js +0 -307
  171. package/dist/chunks/index-dq7b35fn.js.map +0 -13
  172. package/dist/chunks/index-f5cnbrjz.js.map +0 -13
  173. package/dist/chunks/index-ktmvs916.js.map +0 -13
  174. package/dist/chunks/index-m6n8ctfc.js.map +0 -10
  175. package/dist/chunks/index-mev09s5v.js +0 -77
  176. package/dist/chunks/index-mev09s5v.js.map +0 -10
  177. package/dist/chunks/index-mt93ff2b.js.map +0 -10
  178. package/dist/chunks/index-qd5xgx6y.js.map +0 -13
  179. package/dist/chunks/index-x69p7cv7.js.map +0 -10
  180. package/dist/types/react/shellStyles.d.ts +0 -3
  181. package/dist/types/react/ui/DataAppSkeleton.d.ts +0 -7
  182. /package/dist/chunks/{index-23dktynd.js.map → index-ap60vggk.js.map} +0 -0
  183. /package/dist/chunks/{index-ev2b5aaf.js.map → index-sx488hvs.js.map} +0 -0
@@ -25,6 +25,8 @@ export type SearchItemsOptions<Item> = {
25
25
  limit?: number;
26
26
  fuzzyThreshold?: number;
27
27
  };
28
+ /** Highlight literal query terms in supplied text without filtering or reordering results. */
29
+ export declare function matchSearchText(text: string, query: string): SearchMatchValue;
28
30
  /**
29
31
  * Search only a complete local collection. Empty queries retain every item.
30
32
  * When a searched field is displayed, render its match with SearchMatch:
@@ -0,0 +1,2 @@
1
+ /** Stable React ID for SVG definitions and their URL references; safe with identifier prefixes. */
2
+ export declare function useSvgId(): string;
@@ -1,7 +1,7 @@
1
1
  import type { DatePresetId, DateRange } from '../../core/date-range.js';
2
2
  import { type AppVariableValues, type DateRangeSelection, type DateRangeVariable, type HistoryMode, type VariableCollection } from '../../core/variables.js';
3
3
  export { defineAppVariables, searchVariable, choiceVariable, multiChoiceVariable, dateRangeVariable, } from '../../core/variables.js';
4
- export type { AppVariable, AppVariableValues, ChoiceOption, ChoiceVariable, MultiChoiceVariable, SearchVariable, DateRangeSelection, DateRangeVariable, DateRangeVariableOptions, VariableCollection, } from '../../core/variables.js';
4
+ export type { VariablePresentation, AppVariable, AppVariableValues, ChoiceOption, ChoiceVariable, MultiChoiceVariable, SearchVariable, DateRangeSelection, DateRangeVariable, DateRangeVariableOptions, VariableCollection, } from '../../core/variables.js';
5
5
  /** Adapt one date variable to the controlled picker without giving the picker URL ownership. */
6
6
  export declare function dateRangeControl(variable: DateRangeVariable, selection: DateRangeSelection, onChange: (selection: DateRangeSelection) => void): {
7
7
  minDate?: string;
@@ -0,0 +1,16 @@
1
+ import { type ReactNode } from 'react';
2
+ export type ActiveFilterControl = {
3
+ id: string;
4
+ label: string;
5
+ renderControl: (onDeactivate: () => void) => ReactNode;
6
+ onClear?: () => void;
7
+ };
8
+ export declare function ViewControlBar({ primaryFilters, activeSecondaryFilters, allFilters, activeFilterCount, displayOptions, changedDisplayOptionCount, onClear, }: {
9
+ primaryFilters: ReactNode[];
10
+ allFilters: ReactNode[];
11
+ activeSecondaryFilters: ActiveFilterControl[];
12
+ activeFilterCount: number;
13
+ displayOptions: ReactNode[];
14
+ changedDisplayOptionCount: number;
15
+ onClear?: () => void;
16
+ }): import("react").JSX.Element;
@@ -1,4 +1,4 @@
1
- import type { ReactNode } from 'react';
1
+ import { type ReactNode } from 'react';
2
2
  import { type AppVariableValues, type VariableCollection } from './ui/variables.js';
3
3
  import type { ResolvedVariables } from './view.js';
4
4
  /** URL values resolve before facets; facet keys include their dependent inputs for cached, bounded loading. */
@@ -15,5 +15,6 @@ export declare function useViewVariables<Variables extends VariableCollection>(d
15
15
  resetValue: AppVariableValues<Variables>[Key];
16
16
  };
17
17
  resolved: ResolvedVariables<Variables>;
18
- controls: ReactNode[] | null;
18
+ searchControls: ReactNode[] | null;
19
+ filterControls: import("react").JSX.Element | null;
19
20
  };
@@ -5,13 +5,15 @@ import type { DisclosedQuery } from '../core/contract.js';
5
5
  import type { EmptyContent } from './ui/presentation.js';
6
6
  export type ViewResult<Data, Input> = {
7
7
  dataContext: DataContext;
8
+ timeZone?: string;
8
9
  view: DataView<Data, Input>;
9
10
  snapshot?: DisplayedSnapshot<Data, Input>;
10
11
  refetch: () => unknown;
11
12
  cancel: () => unknown;
12
13
  refreshing: boolean;
13
14
  queries?: DisclosedQuery[];
14
- controls?: ReactNode;
15
+ searchControls?: ReactNode;
16
+ filterControls?: ReactNode;
15
17
  emptyFallback: EmptyContent;
16
18
  };
17
19
  /** The executor is private; declarations expose data composition, not subscription hooks. */
@@ -17,6 +17,19 @@ export type ViewDate<Variables extends VariableCollection, Input> = {
17
17
  export type ViewBindings<Variables extends VariableCollection, Input> = Partial<{
18
18
  [Key in keyof Variables]: (input: Input) => ResolvedVariables<Variables>[Key];
19
19
  }>;
20
+ type RequiredFilterBindingKeys<Variables extends VariableCollection, Input> = {
21
+ [Key in keyof Variables]: Extract<Variables[Key]['kind'], 'dimension' | 'numberFilter' | 'booleanFilter'> extends never ? never : [Input] extends [Record<Key, ResolvedVariables<Variables>[Key]>] ? [ResolvedVariables<Variables>[Key]] extends [Input[Key]] ? never : Key : Key;
22
+ }[keyof Variables];
23
+ /** Derive compatible top-level filter bindings; require readers for other input shapes. */
24
+ export type ViewBindingOptions<Variables extends VariableCollection, Input, AdditionalRequired extends keyof Variables = never> = [RequiredFilterBindingKeys<Variables, Input> | AdditionalRequired] extends [
25
+ never
26
+ ] ? {
27
+ bindings?: ViewBindings<Variables, Input>;
28
+ } : {
29
+ bindings: ViewBindings<Variables, Input> & {
30
+ [Key in RequiredFilterBindingKeys<Variables, Input> | AdditionalRequired]-?: (input: Input) => ResolvedVariables<Variables>[Key];
31
+ };
32
+ };
20
33
  type SameViewInput<Variables extends VariableCollection, Input> = [
21
34
  ResolvedVariables<Variables>
22
35
  ] extends [Input] ? [Input] extends [ResolvedVariables<Variables>] ? [Input] extends [Record<string, never>] ? true : [keyof Input] extends [keyof Variables] ? true : false : false : false;
@@ -28,7 +41,6 @@ type ViewInputMapping<Variables extends VariableCollection, Input> = SameViewInp
28
41
  export type DataViewDefinition<Name extends string, Variables extends VariableCollection, Input, Data> = {
29
42
  operation: Name;
30
43
  dataContext: DataContext;
31
- bindings?: ViewBindings<Variables, Input>;
32
44
  /** App-owned semantics: measured zero need not mean an empty result. */
33
45
  isEmpty: (data: Data) => boolean;
34
46
  /** Inherited by DataSection unless it supplies its own copy. */
@@ -37,7 +49,7 @@ export type DataViewDefinition<Name extends string, Variables extends VariableCo
37
49
  variables?: Variables;
38
50
  } : {
39
51
  variables: Variables;
40
- }) & ViewInputMapping<NoInfer<Variables>, Input> & ({
52
+ }) & ViewInputMapping<NoInfer<Variables>, Input> & ViewBindingOptions<NoInfer<Variables>, Input> & ({
41
53
  date: ViewDate<Variables, Input>;
42
54
  describeInput?: (input: Input) => string;
43
55
  } | {
@@ -13,5 +13,7 @@ export declare function serveLocalApp({ page, operations, title, port, }: {
13
13
  title: string;
14
14
  port?: number;
15
15
  }): Bun.Server<undefined>;
16
- /** Server-only lakehouse adapter. Local development uses the selected CLI profile's proxy. */
16
+ /** Throw an actionable startup error when the selected lakehouse credentials are missing. */
17
+ export declare function validateLakehouseCredentials(environment?: Record<string, string | undefined>): void;
18
+ /** Server-only SDK adapter. Local development uses the selected CLI profile's proxy. */
17
19
  export declare function localLakehouse(environment?: Record<string, string | undefined>, request?: typeof fetch): Lakehouse;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ import { type Lakehouse } from '../../core/contract.js';
2
+ export type AppFilePreviewOptions = {
3
+ /** Absolute path to the app source. */
4
+ file: string;
5
+ /** Localhost port. Use 0 to select an available port. Defaults to 25837. */
6
+ port?: number;
7
+ /** Server-only query backend; the caller owns credentials and profile selection. */
8
+ lakehouse: Lakehouse;
9
+ };
10
+ export type AppFilePreview = {
11
+ url: URL;
12
+ /** Stop serving, close reload connections, and release all file watchers. */
13
+ stop(): Promise<void>;
14
+ };
15
+ /** Preview a single-file app in the hosted sandbox. Requires the Bun runtime. */
16
+ export declare function serveAppFile({ file: appFile, port, lakehouse, }: AppFilePreviewOptions): Promise<AppFilePreview>;
@@ -0,0 +1,6 @@
1
+ /** Owns reload-event connections. The caller owns watching and debounce timing. */
2
+ export declare function createReloadChannel(): {
3
+ connect: (request: Request) => Response;
4
+ notify: () => void;
5
+ close: () => void;
6
+ };
@@ -0,0 +1,4 @@
1
+ export declare class RequestBodyTooLargeError extends Error {
2
+ }
3
+ /** Count encoded bytes before retaining chunks; cancellation also interrupts waiting reads. */
4
+ export declare function readRequestBody(request: Request, maxBytes: number): Promise<string>;
package/dist/worker.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/embed/runtime-html.ts
2
2
  var PAGE_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; connect-src 'none'; form-action 'none'; base-uri 'none'";
3
- var inlineBootstrap = '(()=>{function q(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,(r)=>r.toString(16).padStart(2,"0"));return[t.slice(0,4),t.slice(4,6),t.slice(6,8),t.slice(8,10),t.slice(10)].map((r)=>r.join("")).join("-")}function X(e){if(!e||typeof e!=="object")return!1;let t=e;return(t.method==="log"||t.method==="info"||t.method==="warn"||t.method==="error")&&Array.isArray(t.args)&&t.args.length<=128}var U="altertable:data-app";var J=128,Z=60000;function M(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,128}$/.test(e)}function g({wire:e,from:t,session:r,parse:n}){return{wire:e,from:t,session:r,parse:n}}function j(e){if(!M(e.id))throw Error("Invalid request ID.");return e.id}function L(e,t){let r=e[t];if(typeof r!=="string")throw Error(`Invalid ${t}.`);return r}function A(){return{}}var m={channel:U,version:1,events:{connect:g({wire:"bridge:connect",from:"host",session:"none",parse:A}),ready:g({wire:"bridge:ready",from:"app",session:"none",parse:A}),initialize:g({wire:"bridge:initialize",from:"host",session:"establish",parse:(e)=>({state:e.state})}),request:g({wire:"bridge:request",from:"app",session:"current",parse:(e)=>{let t=L(e,"route");if(!t||t.length>256)throw Error("Invalid message route.");return{id:j(e),route:t,payload:e.payload}}}),result:g({wire:"bridge:result",from:"host",session:"current",parse:(e)=>{if(!Object.hasOwn(e,"response"))throw Error("Missing response.");return{id:j(e),response:e.response}}}),error:g({wire:"bridge:error",from:"host",session:"current",parse:(e)=>{if(e.requestId!==void 0&&typeof e.requestId!=="string")throw Error("Invalid requestId.");return{id:j(e),code:L(e,"code"),message:L(e,"message"),...e.requestId===void 0?{}:{requestId:e.requestId}}}}),cancel:g({wire:"bridge:cancel",from:"app",session:"current",parse:(e)=>({id:j(e)})}),disconnect:g({wire:"bridge:disconnect",from:"app",session:"current",parse:A}),scriptLoad:g({wire:"script:load",from:"host",session:"current",parse:(e)=>({javascript:L(e,"javascript")})}),stateUpdate:g({wire:"state:update",from:"host",session:"current",parse:(e)=>({state:e.state})}),runtimeLog:g({wire:"runtime:log",from:"app",session:"current",parse:(e)=>{if(!X(e.payload))throw Error("Invalid log entry.");return{payload:e.payload}}}),runtimeReady:g({wire:"runtime:ready",from:"app",session:"current",parse:A}),runtimeError:g({wire:"runtime:error",from:"app",session:"current",parse:A})}},_=new Map;for(let e of Object.keys(m.events)){let t=m.events[e].wire;if(_.has(t))throw Error(`Duplicate bridge event: ${t}`);_.set(t,e)}function C(e){return _.get(e)}function F(e){if(!e||typeof e!=="object")return;let t=e;if(t.channel!==U||t.version!==m.version||typeof t.type!=="string"||typeof t.documentId!=="string"||!t.documentId||t.documentId.length>128||t.sessionId!==void 0&&!M(t.sessionId)||t.token!==void 0&&typeof t.token!=="string")return;return t}function W(e,t){try{return{channel:U,version:m.version,documentId:e.documentId,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.token===void 0?{}:{token:e.token},type:t.wire,...t.parse(e)}}catch{return}}function Y(e){let t=F(e);if(!t)return;let r=C(t.type);if(!r)return;let n=m.events[r];if(n.session!=="none"&&t.sessionId===void 0)return;return W(t,n)}function ee({role:e,origin:t,source:r,opaque:n,context:o,post:d,diagnostic:a,invalidRequest:u,handlers:l}){let c=!1;function p(b,R){if(c)throw Error("The bridge endpoint has closed.");let i=m.events[b],f=o(),k=Y({...R,channel:m.channel,version:m.version,type:i.wire,documentId:b==="connect"?"host":f.documentId,sessionId:f.sessionId,token:n?f.token:void 0});if(!k||n&&!M(f.token))throw Error("The bridge is not ready to send this event.");if(a?.("send",i.wire),c)return;d(k)}function v(b){let R=r();if(c||!R||b.origin!==t||b.source!==R)return;let i=F(b.data);if(!i)return;let f=o(),k=e==="app"&&i.type===m.events.connect.wire;if(n&&(k?!M(i.token):!f.token||i.token!==f.token))return;let B=C(i.type);if(!B)return;let x=m.events[B];if(x.from===e)return;if(x.session==="establish"){if(i.documentId!==f.documentId||i.sessionId===void 0)return}else if(x.session==="current"){if(!f.sessionId||i.sessionId!==f.sessionId||i.documentId!==f.documentId)return}let N=W(i,x);if(!N){if(e==="host"&&B==="request"&&M(i.id))u?.(i.id);return}if(a?.("receive",x.wire),c)return;let T=l[B];T(N)}return{send:p,receive:v,dispose(){c=!0}}}function ge(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&Number.isFinite(e)}function V(e){return!!e&&typeof e==="object"&&!Array.isArray(e)&&Object.values(e).every(ge)}var te=Symbol.for("@altertable/data-app/MessageRoutingError");class h extends Error{code;requestId;[te]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[te]===!0}constructor(e,t,r){super(t);this.code=e;this.requestId=r;this.name="MessageRoutingError"}}function me(e){return e}function re(e){return{operations:e,input(t){if(!t||typeof t!=="object")throw Error("Invalid query.");let r=t;if(typeof r.operation!=="string"||!r.operation||r.operation.length>256||r.operation.includes("/"))throw Error("Invalid operation.");let n=e&&Object.hasOwn(e,r.operation)?e[r.operation]:void 0;if(e&&!n)throw Error("Unknown operation.");return{operation:r.operation,input:n?n.input(r.input):r.input}},output(t,r){if(!t||typeof t!=="object")throw Error("Invalid data response.");let n=t;if(!Number.isInteger(n.status)||n.status<100||n.status>599||!n.body||typeof n.body!=="object"||Array.isArray(n.body))throw Error("Invalid data response.");let o=n.body;if(n.status<200||n.status>=300){let a=o.error;throw new h(typeof a?.code==="string"?a.code:"request_failed",typeof a?.message==="string"?a.message:"Could not load data.",typeof a?.requestId==="string"?a.requestId:void 0)}if(!("data"in o)||typeof o.requestId!=="string"||typeof o.queriedAt!=="string"||!Array.isArray(o.queryIds)||!o.queryIds.every((a)=>typeof a==="string"))throw Error("Invalid data envelope.");if(o.queries!==void 0&&(!Array.isArray(o.queries)||!o.queries.every((a)=>a&&typeof a==="object"&&typeof a.name==="string"&&typeof a.statement==="string"&&(a.params===void 0||V(a.params))&&(a.queryId===void 0||typeof a.queryId==="string"))))throw Error("Invalid query evidence.");let d=e?.[r.operation];return{status:n.status,body:{...o,data:d?d.output(o.data):o.data}}}}}var ne=me({input(e){if(!e||typeof e!=="object")throw Error("Invalid SQL query.");let t=e;if(typeof t.statement!=="string"||!t.statement.trim()||typeof t.limit!=="number"||!Number.isSafeInteger(t.limit)||t.limit<1||t.params!==void 0&&!V(t.params))throw Error("Invalid SQL query.");return{statement:t.statement,limit:t.limit,...t.params===void 0?{}:{params:t.params}}},output(e,t){if(!e||typeof e!=="object")throw Error("Invalid query result.");let r=e;if(!Array.isArray(r.columns)||!r.columns.every((n)=>n&&typeof n.name==="string"&&(n.type===void 0||typeof n.type==="string"))||!Array.isArray(r.rows)||r.rows.length>t.limit||!r.rows.every((n)=>Array.isArray(n)&&n.length===r.columns.length)||r.queryId!==void 0&&typeof r.queryId!=="string")throw Error("Invalid query result.");return{columns:r.columns,rows:r.rows,...r.queryId===void 0?{}:{queryId:r.queryId}}}});function oe(e,t){return{async request(r,n,{signal:o}={}){if(o?.throwIfAborted(),!Object.hasOwn(e,r))throw new h("unknown_route","Unknown message route.");let d=e[r],a;try{a=d.input(n)}catch{throw new h("invalid_payload","Invalid message payload.")}let u=await t({route:r,payload:a},o);o?.throwIfAborted();try{return d.output(u,a)}catch(l){if(l instanceof h)throw l;throw new h("invalid_response","Invalid message response.")}}}}var se=Symbol.for("@altertable/data-app/DataAppError");class E extends Error{code;requestId;[se]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[se]===!0}constructor(e,t,r){super(e);this.code=t;this.requestId=r;this.name="DataAppError"}}function ae(e,t){function r(o){if(o.length===1&&typeof o[0]==="function"){let d=o[0]();return Array.isArray(d)?d:[d]}return o.map((d)=>typeof d==="function"?d():d)}function n(o,d){if(!e())return;try{t({method:o,args:r(d)})}catch{}}return{log:(...o)=>n("log",o),info:(...o)=>n("info",o),warn:(...o)=>n("warn",o),error:(...o)=>n("error",o)}}function ie(e,t){if(t.type==="runtime:log")return;e.log(()=>{let r={type:t.type};if("id"in t)r.id=t.id;if(t.type==="bridge:request"){r.route=t.route;let n=t.payload;if(t.route==="data:query"&&n&&typeof n==="object"&&"operation"in n&&typeof n.operation==="string")r.operation=n.operation}return["Sending message to parent",r]})}function de(e){if(e instanceof h)throw new E(e.message,e.code,e.requestId);throw e}function ue({parentOrigin:e,window:t=window,timeoutMs:r=Z,mode:n="url",loadScript:o}){if(new URL(e).origin!==e)throw Error("Expected an exact parent origin.");let d=q(),a,u,l=!1,c=new Map,p,v=new Set,b=ae(()=>!l&&!!u&&!!p&&typeof p==="object"&&("logging"in p)&&p.logging===!0,(s)=>i("runtimeLog",{payload:s})),R=ee({role:"app",origin:e,source:()=>t.parent,opaque:n==="bundle",context:()=>({documentId:d,sessionId:u,token:a}),post(s){t.parent.postMessage(s,e),ie(b,s)},handlers:{connect(s){if(n==="bundle")a=s.token;i("ready",{})},initialize(s){if(u&&u!==s.sessionId)for(let I of c.values())I.reject(new E("The preview reconnected. Retry the request.","bridge_reset"));let y=!u;if(u=s.sessionId,k(s.state),y)for(let I of c.values())I.start();if(l)return;if(n==="url")i("runtimeReady",{})},stateUpdate(s){k(s.state)},scriptLoad(s){if(n==="bundle")o?.(s.javascript)},result(s){c.get(s.id)?.resolve(s.response)},error(s){c.get(s.id)?.reject(new h(s.code,s.message,s.requestId))}}}),{send:i,receive:f}=R;function k(s){p=s;for(let y of v)y(s)}t.addEventListener("message",f);function B(s,y){return new Promise((I,w)=>{if(l)return w(new E("The preview has closed.","bridge_closed"));if(y?.aborted)return w(y.reason);if(c.size>=J)return w(new E("Too many pending data requests.","bridge_busy"));let O=q(),Q=!1;function P(){clearTimeout(ye),y?.removeEventListener("abort",G),c.delete(O)}function G(){if(Q)i("cancel",{id:O});P(),w(y?.reason)}let ye=setTimeout(()=>{if(Q)i("cancel",{id:O});P(),w(new E(u?"The data request timed out.":"The preview shell is unavailable. Reload the preview.",u?"timeout":"bridge_unavailable"))},r),K={start(){if(Q)return;try{i("request",{id:O,route:s.route,payload:s.payload}),Q=!0}catch{P(),w(new E("The message payload could not be sent.","invalid_payload"))}},resolve(S){P(),I(S)},reject(S){P(),w(S)}};if(c.set(O,K),y?.addEventListener("abort",G,{once:!0}),u)K.start();else if(n==="url"||a)i("ready",{})})}let x=oe({"data:query":re(),"data:sql":ne},B);function N(s,y,I){return x.request("data:query",{operation:s,input:y},{signal:I}).catch(de)}function T(){if(u)i("disconnect",{});u=void 0;for(let s of c.values())s.reject(new E("The preview has closed.","bridge_closed"))}function H(s){if(s.persisted&&(n==="url"||a))i("ready",{})}function fe(){if(l)return;T(),l=!0,R.dispose(),t.removeEventListener("message",f),t.removeEventListener("pagehide",T),t.removeEventListener("pageshow",H),v.clear()}if(t.addEventListener("pagehide",T),t.addEventListener("pageshow",H),n==="url")i("ready",{});return{logger:b,request:B,transport:N,lakehouse:{queryAll(s,{limit:y,signal:I,params:w}){return x.request("data:sql",{statement:s,limit:y,...w===void 0?{}:{params:w}},{signal:I}).catch(de)}},dispose:fe,mode:n,snapshot(){return p},subscribe(s){return v.add(s),()=>{v.delete(s)}},ready(){if(!l&&u)i("runtimeReady",{})},fail(){if(!l&&u)i("runtimeError",{})}}}var z=Symbol.for("altertable.localFrameBridge"),D=Symbol.for("altertable.installedTransport");function pe(e,t=window){let r=t;if(r[D])throw Error("A data app transport is already installed.");return r[z]=e,r[D]=e,()=>{if(r[z]===e)delete r[z];if(r[D]===e)delete r[D];e.dispose()}}function ce({parentOrigin:e,window:t=window}){let r,n=!1,o=`altertable-data-app-${q()}.js`,d=ue({parentOrigin:e,window:t,mode:"bundle",loadScript(p){if(r!==void 0){if(p===r)if(n)d.fail();else d.ready();else d.fail();return}r=p;try{let v=t.document.createElement("script");if(v.textContent=`${p}\n//# sourceURL=${o}`,t.document.body.append(v),!n)d.ready()}catch{a()}}});function a(){n=!0,d.fail()}function u(p){if(p.filename===o)a()}function l(p){if(p.reason instanceof Error&&p.reason.stack?.includes(o))a()}t.addEventListener("error",u),t.addEventListener("unhandledrejection",l);let c=pe(d,t);return()=>{t.removeEventListener("error",u),t.removeEventListener("unhandledrejection",l),c()}}var le=document.currentScript?.dataset.parentOrigin;if(!le)throw Error("Missing trusted parent origin.");ce({parentOrigin:le});})();\n'.replace(/<\/script/gi, (match) => `<\\${match.slice(1)}`);
3
+ var inlineBootstrap = '(()=>{function D(){if(typeof crypto.randomUUID==="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,(n)=>n.toString(16).padStart(2,"0"));return[t.slice(0,4),t.slice(4,6),t.slice(6,8),t.slice(8,10),t.slice(10)].map((n)=>n.join("")).join("-")}function Z(e){if(!e||typeof e!=="object")return!1;let t=e;return(t.method==="log"||t.method==="info"||t.method==="warn"||t.method==="error")&&Array.isArray(t.args)&&t.args.length<=128}var F="altertable:data-app";var Y=128,ee=60000;function P(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,128}$/.test(e)}function w({wire:e,from:t,session:n,parse:r}){return{wire:e,from:t,session:n,parse:r}}function L(e){if(!P(e.id))throw Error("Invalid request ID.");return e.id}function S(e,t){let n=e[t];if(typeof n!=="string")throw Error(`Invalid ${t}.`);return n}function j(){return{}}var h={channel:F,version:1,events:{connect:w({wire:"bridge:connect",from:"host",session:"none",parse:j}),ready:w({wire:"bridge:ready",from:"app",session:"none",parse:j}),initialize:w({wire:"bridge:initialize",from:"host",session:"establish",parse:(e)=>({state:e.state})}),request:w({wire:"bridge:request",from:"app",session:"current",parse:(e)=>{let t=S(e,"route");if(!t||t.length>256)throw Error("Invalid message route.");return{id:L(e),route:t,payload:e.payload}}}),result:w({wire:"bridge:result",from:"host",session:"current",parse:(e)=>{if(!Object.hasOwn(e,"response"))throw Error("Missing response.");return{id:L(e),response:e.response}}}),error:w({wire:"bridge:error",from:"host",session:"current",parse:(e)=>{if(e.requestId!==void 0&&typeof e.requestId!=="string")throw Error("Invalid requestId.");return{id:L(e),code:S(e,"code"),message:S(e,"message"),...e.requestId===void 0?{}:{requestId:e.requestId}}}}),cancel:w({wire:"bridge:cancel",from:"app",session:"current",parse:(e)=>({id:L(e)})}),disconnect:w({wire:"bridge:disconnect",from:"app",session:"current",parse:j}),scriptLoad:w({wire:"script:load",from:"host",session:"current",parse:(e)=>({javascript:S(e,"javascript")})}),stateUpdate:w({wire:"state:update",from:"host",session:"current",parse:(e)=>({state:e.state})}),runtimeLog:w({wire:"runtime:log",from:"app",session:"current",parse:(e)=>{if(!Z(e.payload))throw Error("Invalid log entry.");return{payload:e.payload}}}),runtimeReady:w({wire:"runtime:ready",from:"app",session:"current",parse:j}),runtimeError:w({wire:"runtime:error",from:"app",session:"current",parse:j})}};function W(e){let t={type:e.type};if("id"in e)t.id=e.id;if(e.type==="bridge:request"){t.route=e.route;let n=e.payload;if(e.route==="data:query"&&n&&typeof n==="object"&&"operation"in n&&typeof n.operation==="string")t.operation=n.operation.slice(0,256)}if(e.type==="bridge:error")t.error={code:e.code,message:e.message,...e.requestId===void 0?{}:{requestId:e.requestId}};return t}var C=new Map;for(let e of Object.keys(h.events)){let t=h.events[e].wire;if(C.has(t))throw Error(`Duplicate bridge event: ${t}`);C.set(t,e)}function z(e){return C.get(e)}function V(e){if(!e||typeof e!=="object")return;let t=e;if(t.channel!==F||t.version!==h.version||typeof t.type!=="string"||typeof t.documentId!=="string"||!t.documentId||t.documentId.length>128||t.sessionId!==void 0&&!P(t.sessionId)||t.token!==void 0&&typeof t.token!=="string")return;return t}function H(e,t){try{return{channel:F,version:h.version,documentId:e.documentId,...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.token===void 0?{}:{token:e.token},type:t.wire,...t.parse(e)}}catch{return}}function te(e){let t=V(e);if(!t)return;let n=z(t.type);if(!n)return;let r=h.events[n];if(r.session!=="none"&&t.sessionId===void 0)return;return H(t,r)}function ne({role:e,origin:t,source:n,opaque:r,context:o,post:a,diagnostic:l,invalidRequest:u,handlers:f}){let c=!1;function i(y,p){l?.({direction:"drop",reason:y,...typeof p==="string"?{type:p.slice(0,64)}:{}})}function v(y,p){if(c)throw Error("The bridge endpoint has closed.");let d=h.events[y],g=o(),x=te({...p,channel:h.channel,version:h.version,type:d.wire,documentId:y==="connect"?"host":g.documentId,sessionId:g.sessionId,token:r?g.token:void 0});if(!x||r&&!P(g.token))throw Error("The bridge is not ready to send this event.");if(l?.({direction:"send",...W(x)}),c)return;a(x)}function B(y){let p=n();if(c||!p||y.origin!==t||y.source!==p)return;let d=V(y.data);if(!d){let k=y.data;if(k&&typeof k==="object"&&"channel"in k&&k.channel===h.channel)i("invalid_envelope","type"in k?k.type:void 0);return}let g=o(),x=e==="app"&&d.type===h.events.connect.wire;if(r&&(x?!P(d.token):!g.token||d.token!==g.token))return i("token_mismatch",d.type);let M=z(d.type);if(!M)return i("unexpected_type",d.type);let T=h.events[M];if(T.from===e)return i("unexpected_type",d.type);if(T.session==="establish"){if(d.documentId!==g.documentId||d.sessionId===void 0)return i("session_mismatch",d.type)}else if(T.session==="current"){if(!g.sessionId||d.sessionId!==g.sessionId||d.documentId!==g.documentId)return i("session_mismatch",d.type)}let q=H(d,T);if(!q){if(i("invalid_payload",d.type),e==="host"&&M==="request"&&P(d.id))u?.(d.id);return}if(l?.({direction:"receive",...W(q)}),c)return;let Q=f[M];Q(q)}return{send:v,receive:B,dispose(){c=!0}}}function we(e){return e===null||typeof e==="string"||typeof e==="boolean"||typeof e==="number"&&Number.isFinite(e)}function G(e){return!!e&&typeof e==="object"&&!Array.isArray(e)&&Object.values(e).every(we)}var re=Symbol.for("@altertable/data-app/MessageRoutingError");class I extends Error{code;requestId;[re]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[re]===!0}constructor(e,t,n,r){super(t,r);this.code=e;this.requestId=n;this.name="MessageRoutingError"}}function he(e){return e}function oe(e){return{operations:e,input(t){if(!t||typeof t!=="object")throw Error("Invalid query.");let n=t;if(typeof n.operation!=="string"||!n.operation||n.operation.length>256||n.operation.includes("/"))throw Error("Invalid operation.");let r=e&&Object.hasOwn(e,n.operation)?e[n.operation]:void 0;if(e&&!r)throw Error("Unknown operation.");return{operation:n.operation,input:r?r.input(n.input):n.input}},output(t){if(!t||typeof t!=="object")throw Error("Invalid data response.");let n=t;if(!Number.isInteger(n.status)||n.status<100||n.status>599||!n.body||typeof n.body!=="object"||Array.isArray(n.body))throw Error("Invalid data response.");let r=n.body;if(n.status<200||n.status>=300){let o=r.error;throw new I(typeof o?.code==="string"?o.code:"request_failed",typeof o?.message==="string"?o.message:"Could not load data.",typeof o?.requestId==="string"?o.requestId:void 0)}if(!("data"in r)||typeof r.requestId!=="string"||typeof r.queriedAt!=="string"||!Array.isArray(r.queryIds)||!r.queryIds.every((o)=>typeof o==="string"))throw Error("Invalid data envelope.");if(r.queries!==void 0&&(!Array.isArray(r.queries)||!r.queries.every((o)=>o&&typeof o==="object"&&typeof o.name==="string"&&typeof o.statement==="string"&&(o.params===void 0||G(o.params))&&(o.queryId===void 0||typeof o.queryId==="string"))))throw Error("Invalid query evidence.");return{status:n.status,body:r}}}}var se=he({input(e){if(!e||typeof e!=="object")throw Error("Invalid SQL query.");let t=e;if(typeof t.statement!=="string"||!t.statement.trim()||typeof t.limit!=="number"||!Number.isSafeInteger(t.limit)||t.limit<1||t.params!==void 0&&!G(t.params))throw Error("Invalid SQL query.");return{statement:t.statement,limit:t.limit,...t.params===void 0?{}:{params:t.params}}},output(e,t){if(!e||typeof e!=="object")throw Error("Invalid query result.");let n=e;if(!Array.isArray(n.columns)||!n.columns.every((r)=>r&&typeof r.name==="string"&&(r.type===void 0||typeof r.type==="string"))||!Array.isArray(n.rows)||n.rows.length>t.limit||!n.rows.every((r)=>Array.isArray(r)&&r.length===n.columns.length)||n.queryId!==void 0&&typeof n.queryId!=="string")throw Error("Invalid query result.");return{columns:n.columns,rows:n.rows,...n.queryId===void 0?{}:{queryId:n.queryId}}}});function ie(e,t){return{async request(n,r,{signal:o}={}){if(o?.throwIfAborted(),!Object.hasOwn(e,n))throw new I("unknown_route","Unknown message route.");let a=e[n],l;try{l=a.input(r)}catch{throw new I("invalid_payload","Invalid message payload.")}let u=await t({route:n,payload:l},o);o?.throwIfAborted();try{return a.output(u,l)}catch(f){if(f instanceof I)throw f;throw new I("invalid_response","Invalid message response.")}}}}var ae=Symbol.for("@altertable/data-app/DataAppError");class R extends Error{code;requestId;[ae]=!0;static[Symbol.hasInstance](e){return e instanceof Error&&e[ae]===!0}constructor(e,t,n){super(e);this.code=t;this.requestId=n;this.name="DataAppError"}}function de(e,t){function n(o){if(o.length===1&&typeof o[0]==="function"){let a=o[0]();return Array.isArray(a)?a:[a]}return o.map((a)=>typeof a==="function"?a():a)}function r(o,a){if(!e())return;try{t({method:o,args:n(a)})}catch{}}return{log:(...o)=>r("log",o),info:(...o)=>r("info",o),warn:(...o)=>r("warn",o),error:(...o)=>r("error",o)}}var ve={send:"Sending message to parent",receive:"Received message from parent",drop:"Ignored message from parent"};function ue(e,{direction:t,...n}){if(n.type==="runtime:log")return;e.log(ve[t],n)}function pe(e){if(e instanceof Error)return{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{}};return{message:String(e)}}function ce(e){if(e instanceof I)throw new R(e.message,e.code,e.requestId);throw e}function le({parentOrigin:e,window:t=window,timeoutMs:n=ee,mode:r="url",loadScript:o}){if(new URL(e).origin!==e)throw Error("Expected an exact parent origin.");let a=D(),l,u,f=!1,c=new Map,i,v=new Set,B=de(()=>!f&&!!u&&!!i&&typeof i==="object"&&("logging"in i)&&i.logging===!0,(s)=>p("runtimeLog",{payload:s})),y=ne({role:"app",origin:e,source:()=>t.parent,opaque:r==="bundle",context:()=>({documentId:a,sessionId:u,token:l}),post(s){t.parent.postMessage(s,e)},diagnostic:(s)=>ue(B,s),handlers:{connect(s){if(r==="bundle")l=s.token;p("ready",{})},initialize(s){if(u&&u!==s.sessionId){if(c.size)B.warn("Preview reconnected; rejecting pending requests",{count:c.size});for(let E of c.values())E.reject(new R("The preview reconnected. Retry the request.","bridge_reset"))}let m=!u;if(u=s.sessionId,g(s.state),m)for(let E of c.values())E.start();if(f)return;if(r==="url")p("runtimeReady",{})},stateUpdate(s){g(s.state)},scriptLoad(s){if(r==="bundle")o?.(s.javascript)},result(s){c.get(s.id)?.resolve(s.response)},error(s){c.get(s.id)?.reject(new I(s.code,s.message,s.requestId))}}}),{send:p,receive:d}=y;function g(s){i=s;for(let m of v)m(s)}t.addEventListener("message",d);function x(s,m){return new Promise((E,b)=>{if(f)return b(new R("The preview has closed.","bridge_closed"));if(m?.aborted)return b(m.reason);if(c.size>=Y)return b(new R("Too many pending data requests.","bridge_busy"));let O=D(),A=!1;function N(){clearTimeout(me),m?.removeEventListener("abort",X),c.delete(O)}function X(){if(A)p("cancel",{id:O});N(),b(m?.reason)}let me=setTimeout(()=>{if(B.warn("Message request timed out",{id:O,route:s.route,timeoutMs:n,sent:A}),A)p("cancel",{id:O});N(),b(new R(u?"The data request timed out.":"The preview shell is unavailable. Reload the preview.",u?"timeout":"bridge_unavailable"))},n),J={start(){if(A)return;try{p("request",{id:O,route:s.route,payload:s.payload}),A=!0}catch{N(),b(new R("The message payload could not be sent.","invalid_payload"))}},resolve(U){N(),E(U)},reject(U){N(),b(U)}};if(c.set(O,J),m?.addEventListener("abort",X,{once:!0}),u)J.start();else if(r==="url"||l)p("ready",{})})}let M=ie({"data:query":oe(),"data:sql":se},x);function T(s,m,E){return M.request("data:query",{operation:s,input:m},{signal:E}).catch(ce)}function q(){if(u)p("disconnect",{});u=void 0;for(let s of c.values())s.reject(new R("The preview has closed.","bridge_closed"))}function Q(s){if(s.persisted&&(r==="url"||l))p("ready",{})}function k(){if(f)return;q(),f=!0,y.dispose(),t.removeEventListener("message",d),t.removeEventListener("pagehide",q),t.removeEventListener("pageshow",Q),v.clear()}if(t.addEventListener("pagehide",q),t.addEventListener("pageshow",Q),r==="url")p("ready",{});return{logger:B,request:x,transport:T,lakehouse:{queryAll(s,{limit:m,signal:E,params:b}){return M.request("data:sql",{statement:s,limit:m,...b===void 0?{}:{params:b}},{signal:E}).catch(ce)}},dispose:k,mode:r,snapshot(){return i},subscribe(s){return v.add(s),()=>{v.delete(s)}},ready(){if(!f&&u)p("runtimeReady",{})},fail(s){if(f||!u)return;if(s!==void 0)B.error(()=>["Data app failed",pe(s)]);p("runtimeError",{})}}}var K=Symbol.for("altertable.localFrameBridge"),_=Symbol.for("altertable.installedTransport");function fe(e,t=window){let n=t;if(n[_])throw Error("A data app transport is already installed.");return n[K]=e,n[_]=e,()=>{if(n[K]===e)delete n[K];if(n[_]===e)delete n[_];e.dispose()}}function ge({parentOrigin:e,window:t=window}){let n,r,o=`altertable-data-app-${D()}.js`,a=le({parentOrigin:e,window:t,mode:"bundle",loadScript(i){if(n!==void 0){if(i!==n)a.fail(Error("This frame already evaluated a different app script."));else if(r)a.fail(r.cause);else a.ready();return}n=i;try{let v=t.document.createElement("script");if(v.textContent=`${i}\n//# sourceURL=${o}`,t.document.body.append(v),!r)a.ready()}catch(v){l(v)}}});function l(i){r={cause:i},a.fail(i)}function u(i){if(i.filename===o)l(i.error??i.message)}function f(i){if(i.reason instanceof Error&&i.reason.stack?.includes(o))l(i.reason)}t.addEventListener("error",u),t.addEventListener("unhandledrejection",f);let c=fe(a,t);return()=>{t.removeEventListener("error",u),t.removeEventListener("unhandledrejection",f),c()}}var ye=document.currentScript?.dataset.parentOrigin;if(!ye)throw Error("Missing trusted parent origin.");ge({parentOrigin:ye});})();\n'.replace(/<\/script/gi, (match) => `<\\${match.slice(1)}`);
4
4
  function runtimeHtml(parentOrigin) {
5
5
  const attribute = parentOrigin.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("'", "&#39;");
6
6
  return `<!doctype html>
@@ -65,7 +65,7 @@ function trustedParent(config, searchParams) {
65
65
  }
66
66
 
67
67
  // src/worker/index.ts
68
- var TOKEN_RE = /^(?=.{1,63}$)[a-z0-9]+(?:-[a-z0-9]+)+-app-[1-9][0-9]*$/;
68
+ var TOKEN_RE = /^(?=.{1,63}$)[a-z0-9]+(?:-+[a-z0-9]+)+$/;
69
69
  function isPreviewHost(hostname, domainName) {
70
70
  const suffix = `.${domainName}`;
71
71
  return hostname.endsWith(suffix) && TOKEN_RE.test(hostname.slice(0, -suffix.length));
@@ -1,7 +1,7 @@
1
1
  # Author a data app
2
2
 
3
3
  Build an exploration that answers the user's question and a story that presents
4
- its strongest findings. Include CSV export so readers can take the displayed
4
+ its strongest findings. Include CSV export so users can take the displayed
5
5
  results into their own tools. Exploration, export, and story use the same
6
6
  queries, definitions, and evidence.
7
7
 
@@ -17,6 +17,15 @@ Derive displays, exports, and findings from their results. See
17
17
  Inspect the relevant catalogs, tables, and fields, their time coverage, and
18
18
  existing definitions. Choose a question the available data can answer.
19
19
 
20
+ ## Choose the visualizations
21
+
22
+ Before implementing queries and rendering, identify the question each visual
23
+ answers, [choose its component](widgets.md#choose-a-visualization), and establish
24
+ the required result shape: population, grain, units, ordering, and observation
25
+ status. Prefer a specialized chart when its semantics fit. Check the component's
26
+ input contract before reducing results to generic labels and values; preserve
27
+ supplied query definitions when adapting their results.
28
+
20
29
  ## Build the exploration
21
30
 
22
31
  Choose the execution path:
@@ -37,7 +46,7 @@ and internal execution settings out of filter controls.
37
46
 
38
47
  Register inspected tables and fields with `defineDataIdentifiers()` and use
39
48
  `<DataIdentifier>` when naming sources. Register terms and query evidence so
40
- readers can inspect the source of each claim.
49
+ users can inspect the source of each claim.
41
50
 
42
51
  Connect visualizations with introductions and explanations. Use `<TextWidget>`
43
52
  for a narrative panel with the standard widget frame, or `<TextContent>` for
@@ -67,12 +76,12 @@ on the view so tables, exports, and stories share values and evidence.
67
76
  Every data app supplies a [story and CSV export](stories-and-export.md)
68
77
  from the displayed result. Export all distinct datasets at their displayed grain;
69
78
  reuse a dataset when several visuals derive from the same rows. Present the
70
- findings that answer the reader's question, rather than every row or chart.
79
+ findings that answer the user's question, rather than every row or chart.
71
80
  Use the [standard layout](layout.md) and built-in toolbar actions.
72
81
 
73
82
  ### Organize the exploration
74
83
 
75
- Use sections for a focused question and for findings readers should compare
84
+ Use sections for a focused question and for findings users should compare
76
85
  side by side. Add app-level `<Tabs>` from `/react/ui` when the exploration has
77
86
  distinct analytical questions, such as Overview, Retention, and Segments, each
78
87
  with its own context and group of widgets. Lead with the most useful overview
@@ -80,7 +89,7 @@ and label tabs by the question or subject they explore.
80
89
 
81
90
  Use `<VisualizationWidget>`'s `views` for alternate representations of the same
82
91
  dataset, such as a chart and its rows. Keep these choices within the widget;
83
- use filter variables when the reader is changing the data scope.
92
+ use filter variables when the user is changing the data scope.
84
93
 
85
94
  Navigation tabs, widget views, and declared data views have different roles.
86
95
  A declared view owns inputs, requests, and displayed results; a tab does not
@@ -90,15 +99,14 @@ needs separate requests. Keep filter placement consistent across tabs and make
90
99
  each filter's scope clear. Derive findings, story, and export from the displayed
91
100
  results and their inputs.
92
101
 
93
- Choose each visual for the question it answers; see
94
- [visualization selection](widgets.md#choose-a-visualization).
95
-
96
102
  ## Verify the app
97
103
 
98
104
  Follow the [UI quality contract](ui-quality.md) for hierarchy, responsive
99
105
  composition, typography, and control states.
100
106
 
101
- Verify findings against the source and the user's question. Distinguish measured
107
+ Verify that each visual answers its intended question and preserves the source
108
+ population, units, ordering, and missing or incomplete observations. Check
109
+ findings against the source and the user's question. Distinguish measured
102
110
  zero, unavailable values, and empty results. Check filters, refresh, loading,
103
111
  empty, error, and stale states, then present the story. Download CSV from the
104
112
  standalone and embedded toolbar and verify its filename, columns, raw values,
package/docs/client.md CHANGED
@@ -53,7 +53,7 @@ const client = createDataClient({
53
53
  const response = await client.query('connection', {});
54
54
  ```
55
55
 
56
- The client runs input parsing, operation logic, and output parsing in the browser.
56
+ The client runs input parsing and operation logic in the browser.
57
57
  Operation policy bounds rows, duration, and response size and records query evidence. Each query sends `{ statement, limit, params? }`
58
58
  to the installed iframe bridge's `data:sql` route; the host needs no operation
59
59
  registry. Results include query evidence. Credentials remain backend-owned.
package/docs/contract.md CHANGED
@@ -11,7 +11,8 @@ import operation types using `import type`.
11
11
  Declare SQL once with `defineDataApp()` to preserve exact query and parameter
12
12
  names. Use stable `lowerCamelCase` IDs describing the result, such as `products`,
13
13
  `productsByCategory`, or `dailyRevenue`. Use plural names for row lists; keep parameter
14
- values in `params`.
14
+ values in `params`. Every query must include `params`; use `{}` when it declares no
15
+ parameters.
15
16
  The app owns an immutable registry snapshot. Define operations with
16
17
  `dataApp.defineOperation()`.
17
18
 
@@ -34,19 +35,18 @@ const dataApp = defineDataApp({
34
35
 
35
36
  const products = dataApp.defineOperation({
36
37
  input: parseProductInput,
37
- output: parseProducts,
38
38
  checks: [{}],
39
39
  policy: { maxQueryRows: 100, maxDurationMs: 15000 },
40
40
  async run({ query }, input) {
41
41
  const result = await query('products', input);
42
- return rowsAsRecords(result, ['org_id']);
42
+ return parseProducts(rowsAsRecords(result, ['name', 'price']));
43
43
  },
44
44
  });
45
45
  ```
46
46
 
47
47
  `parseProductInput()` and `parseProducts()` are app-owned example functions, not
48
- package exports. Validate
49
- filter values in the input parser. `{}` declares a required parameter; `{ defaultValue }` supplies
48
+ package exports. Validate filter values in the input parser. Parse query rows once, in
49
+ `run`: the value it returns is the operation's data and type, sent to the view as is. `{}` declares a required parameter; `{ defaultValue }` supplies
50
50
  a fallback. `query(name, params, { limit })` executes only registered queries and
51
51
  inherits the operation's row limit and cancellation signal.
52
52
 
@@ -72,8 +72,8 @@ export const calendar = defineDateRangeContract({
72
72
  });
73
73
  ```
74
74
 
75
- `parseEmptyInput()`, `parseTrue()`, `parseCount()`, and `parseDateRangeInput()` validate
76
- common inputs and results. `connectionCheck(dataApp.queries)` runs the registered `connection` query. A successful connectivity check confirms access; it is not an
75
+ `parseEmptyInput()`, `parseCount()`, and `parseDateRangeInput()` validate common inputs
76
+ and query values. `connectionCheck(dataApp.queries)` runs the registered `connection` query. A successful connectivity check confirms access; it is not an
77
77
  analysis result.
78
78
 
79
79
  See [server authorization](server.md) and [React views](react.md) for the two
@@ -111,9 +111,9 @@ an intentional public code, message, and optional request ID; other handler
111
111
  errors are replaced with a generic failure.
112
112
 
113
113
  `defineDataQueryRoute(operationContracts)` validates the selected operation's
114
- input and output and preserves its response evidence. It infers the result type
115
- from the selected operation when used with `createMessageClient()`. Share input and
116
- output parsers, not operation implementations containing SQL or credentials.
114
+ input and preserves its response evidence. It infers the result type from the
115
+ selected operation's `run` when used with `createMessageClient()`. Share input
116
+ parsers and operation types, not operation implementations containing SQL or credentials.
117
117
  `dataAppRoutes` supplies generic `data:query` and `navigation:update` contracts;
118
118
  generic hosts must delegate operation validation and authorization to their
119
119
  server. Request handlers receive `{ signal }` for cancellation.
package/docs/embed.md CHANGED
@@ -100,9 +100,17 @@ client acknowledged initialization or a bundle script finished evaluation. It
100
100
  does not mean asynchronous data queries finished. Script errors report `failed`.
101
101
  The source bridge's `startupTimeoutMs` defaults to 30 seconds.
102
102
 
103
- `onDiagnostic` receives only message `direction` and `type`, never tokens or
104
- payloads. Routed handlers must authorize every data request. Message validation
105
- and iframe isolation do not grant access to data or execute SQL.
103
+ `onDiagnostic` receives delivery metadata, never tokens or payloads: `direction`
104
+ (`send`, `receive`, or `drop`), message `type`, and, when present, the request
105
+ `id`, `route`, query `operation`, and error `code`, `message`, and `requestId`.
106
+ Results and errors include `durationMs`, the host handling time. `drop` events
107
+ report why a message from the connected iframe was ignored, such as a stale
108
+ session or token; messages from other windows are not reported.
109
+
110
+ When a `logger` is set, the iframe also forwards its view of the bridge: messages
111
+ it sends, receives, and ignores, local timeouts, reconnect resets, and the cause
112
+ of a `failed` status. Routed handlers must authorize every data request. Message
113
+ validation and iframe isolation do not grant access to data or execute SQL.
106
114
 
107
115
  ## SQL query route
108
116
 
@@ -13,6 +13,9 @@ Import formatting helpers from `@altertable/data-app/format`.
13
13
  | `formatCount()` | Nonnegative integer counts, optionally compact |
14
14
  | `formatPercent()` | Ratios represented as a fraction, such as 0.12 for 12% |
15
15
  | `formatMetric()` | A metric definition's count, ratio, or currency format |
16
+ | `formatDate()` | Calendar dates without time-zone shifts |
17
+ | `formatDateTime()` | Event timestamps in the reporting time zone |
18
+ | `formatTime()` | Intraday chart labels |
16
19
  | `formatDateRange()` | Inclusive calendar ranges |
17
20
  | `pluralize()` | Count-dependent labels |
18
21
 
@@ -37,6 +40,32 @@ Import `chartColor()` from `/react` to select colors from the configured palette
37
40
  `<DateTimeTooltip>` expose readable timestamps with exact-date details.
38
41
  `<DataTableTimestamp>` and `<DataTableShare>` format custom table cells.
39
42
 
43
+ ## Display dates consistently
44
+
45
+ Declare date meaning on dataset columns so tables use readable values and CSV
46
+ keeps the originals:
47
+
48
+ ```ts
49
+ columns: {
50
+ day: { value: row => row.day, format: { kind: 'date' } },
51
+ observed: {
52
+ value: row => row.observed,
53
+ format: { kind: 'dateTime', precision: 'second' },
54
+ },
55
+ }
56
+ ```
57
+
58
+ Calendar dates use `YYYY-MM-DD`. Instants accept epoch milliseconds or timestamp
59
+ strings; `<DateDisplay>` also accepts `Date`. Timestamp strings require `Z` or an explicit
60
+ offset; convert database-local timestamps in the operation using their known
61
+ source zone. Ambiguous or invalid values display as missing.
62
+
63
+ Use `<DateDisplay>` for prose and `useDateFormatting()` with format helpers for
64
+ custom chart labels. Defaults are `en-US` and UTC; configure app-wide
65
+ `dateFormatting: { locale, timeZone }` when appropriate. A time view supplies its
66
+ reporting zone, and an explicit field zone overrides it. Keep seconds when event
67
+ ordering matters; exact-time details remain available on timestamps.
68
+
40
69
  ## Configure identity and appearance
41
70
 
42
71
  ```ts
@@ -48,7 +77,7 @@ const dataApp = defineDataApp({
48
77
  scope: { organization: 'Acme', environment: 'Production' },
49
78
  appearance: {
50
79
  theme: 'system',
51
- accentColor: '#405d47',
80
+ baseColor: 'neutral',
52
81
  density: 'comfortable',
53
82
  },
54
83
  queries: {},
@@ -56,13 +85,15 @@ const dataApp = defineDataApp({
56
85
  ```
57
86
 
58
87
  Scope labels describe the configured connection; they do not grant access.
59
- `dataAppTitle()` produces the scoped document title used by `mountDataApp()`.
60
88
 
61
89
  Title and description explain the app and can be revised when regenerating it.
62
90
  Omit appearance to use the standard defaults.
63
91
 
64
- Appearance controls the brand palette, typography, density, corner radius, and
65
- elevation. Those settings apply consistently to the app instead of tuning each
66
- widget. Theme preference is reader-owned in standalone apps. A trusted parent's
92
+ The default UI is neutral in light and dark themes. Use `baseColor` for the base
93
+ palette and `accentColor` with optional `darkAccentColor` for brand emphasis.
94
+ Configure chart colors separately with `chartColors`; preserve semantic status
95
+ colors for favorable and unfavorable outcomes.
96
+
97
+ Configure appearance once for the app. Theme preference is user-owned in standalone apps. A trusted parent's
67
98
  resolved theme takes precedence and hides local theme controls; see
68
99
  [parent presentation](embed.md#parent-presentation).
package/docs/layout.md CHANGED
@@ -2,20 +2,17 @@
2
2
 
3
3
  The shell owns page width, outer gutters, and header/body spacing. Use `<Stack>`
4
4
  for sections, `<Grid>` for peer widgets, and `<GridItem>` for spans. Use
5
- `<TextContent>` for prose. Widgets own their internal padding; their parents own
5
+ `<SectionHeading>` to name widget groups and `<TextContent>` for prose. Widgets own their internal padding; their parents own
6
6
  external spacing. Keep widget customization inside the widget so its parent can maintain consistent
7
7
  spacing between sections and cards.
8
8
 
9
- By default, section and widget gaps use `--atbl-layout-gap`, with density configured once
10
- in `app.appearance`. The package owns wrapping and span collapse based
11
- on the available container width and configured gap. Custom length values for
12
- `--atbl-layout-gap`, `--atbl-space-sm`, and `--atbl-space-md` also drive span
13
- collapse; a two-column span activates only when two minimum-width tracks fit.
9
+ Configure density once in `app.appearance`. `<Grid>` wraps to fit its container;
10
+ spans collapse when there is not enough space.
14
11
 
15
12
  ```tsx
16
13
  <Stack>
14
+ <SectionHeading>Activity</SectionHeading>
17
15
  <TextContent>
18
- <h2>Activity</h2>
19
16
  <p>Explore the sources behind this finding.</p>
20
17
  </TextContent>
21
18
  <Grid columns={3}>
@@ -25,9 +22,35 @@ collapse; a two-column span activates only when two minimum-width tracks fit.
25
22
  </Stack>
26
23
  ```
27
24
 
25
+ Set widget `headingLevel={3}` beneath a section heading; visual styling stays
26
+ consistent across widget types.
27
+
28
+ Use `<DataApp footer={...}>` for an optional source, coverage, or methodology
29
+ note below the app content. The footer provides muted body text across the content
30
+ width and top spacing. Compose paragraphs, links, lists, and inline components such
31
+ as `<DataIdentifier>` or `<DateDisplay>` directly; no `<TextContent>` wrapper is
32
+ needed. Keep headings and data widgets in the body, and app controls in
33
+ `footerActions`. Keep static notes outside loading sections.
34
+
35
+ ```tsx
36
+ <DataApp
37
+ {...appProps}
38
+ footer={
39
+ <>
40
+ <p>
41
+ <strong>Coverage.</strong> Records include the last 90 days.
42
+ </p>
43
+ <p>Counts reflect current inventory, not an activity log.</p>
44
+ </>
45
+ }
46
+ >
47
+ <DataSection content={content} />
48
+ </DataApp>
49
+ ```
50
+
28
51
  ## Verify rendered layouts
29
52
 
30
- Check computed section/widget gaps, sibling alignment, outer gutters, and
53
+ Check spacing, alignment, outer gutters, and
31
54
  horizontal overflow at phone and desktop iframe widths. Check loading, empty,
32
55
  error, ready, and stale states. Loading placeholders should use the same grid as
33
56
  the ready content.
@@ -94,10 +94,10 @@ are mutually exclusive.
94
94
 
95
95
  ## Loading an embedded app
96
96
 
97
- Use `<DataAppSkeleton>` from `/react/ui` while the host builds or starts an app.
98
- Call `injectDataAppShellStyles()` from `/react/ui` before rendering the placeholder.
99
- The host owns when to show it and supplies any surrounding header or footer.
100
- `/react/embed` itself remains independent of UI components and styles.
97
+ The host owns loading and generation UI while an app starts. Use a neutral
98
+ status that does not imply a particular app layout. `/react/embed` remains
99
+ independent of UI components and styles. Once the app loads, its query and
100
+ widget loading states describe the content they replace.
101
101
 
102
102
  ## Parent-owned presentation
103
103
 
package/docs/react.md CHANGED
@@ -7,7 +7,7 @@ React 19.2 or newer and React DOM 19.2 or newer are peer dependencies.
7
7
 
8
8
  Use `mountDataApp({ app, component })` to mount into `#root`. When mounting
9
9
  through another framework, wrap the root in `<DataAppProvider app={app}>` from `/react/ui`.
10
- `<DataApp>` inherits identity and appearance from that root. Mounting sets the document title before React renders.
10
+ `<DataApp>` inherits identity and appearance from that root.
11
11
 
12
12
  ```tsx
13
13
  import { injectDataAppStyles, mountDataApp } from '@altertable/data-app/react';
@@ -27,3 +27,28 @@ Missing credentials fail the query. Keep these variables out of browser code.
27
27
  Local serving does not authenticate hosted viewers.
28
28
  Use [the portable server handler](server.md) with per-request authorization when
29
29
  hosting an app for other people.
30
+
31
+ ## Preview a single-file app
32
+
33
+ Import `serveAppFile()` from `@altertable/data-app/server/bun/preview` to preview
34
+ an app in the hosted sandbox. The caller supplies the server-only lakehouse.
35
+ The runtime owns bundling, imported-file watching, reloads, navigation, and exports.
36
+
37
+ ```ts
38
+ import { serveAppFile } from '@altertable/data-app/server/bun/preview';
39
+ import { localLakehouse } from '@altertable/data-app/server/bun';
40
+
41
+ const preview = await serveAppFile({
42
+ file: '/absolute/path/index.tsx',
43
+ lakehouse: localLakehouse(),
44
+ });
45
+ console.log(preview.url);
46
+ // When the launcher stops:
47
+ await preview.stop();
48
+ ```
49
+
50
+ The preview resolves `@altertable/data-app` and React from its own installation.
51
+ It binds to localhost and accepts SQL only from its own origin,
52
+ with a streaming limit of 100,000 UTF-8 bytes per query request. The caller
53
+ owns profile validation, dependency installation, and credentials. This entry requires Bun and adds no Bun installation or dependency
54
+ to browser consumers. Keep it separate from browser imports.
package/docs/server.md CHANGED
@@ -27,7 +27,7 @@ returned lakehouse to the viewer's permitted data. Supply trusted registry
27
27
  parameters through `queryParams`; query callers cannot override these values. Origin and Fetch Metadata
28
28
  checks reject cross-site browser requests; they do not authenticate viewers.
29
29
 
30
- The handler validates operation input and output, enforces query row and duration
30
+ The handler validates operation input, enforces query row and duration
31
31
  bounds, propagates cancellation, and returns query evidence and request IDs.
32
32
  Keep credentials and operation implementations on the server.
33
33