@holistics/anfra-sdk 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -51,6 +51,10 @@ Everything beyond queries comes from a **plugin** the host installed, which adds
51
51
  own name (`query.export`, `Anfra.render`, `Anfra.lineage`). Where the host didn't install it, the
52
52
  member isn't there: check `Anfra.plugins.has(name)` before using an optional one.
53
53
 
54
+ Data Apps written before plugins read `Anfra.features.export` (`.render`, `.lineage`). It still
55
+ answers, from the installed plugins, but it is deprecated and warns in the console: replace it with
56
+ `Anfra.plugins.has('export')`. It goes in the next breaking release.
57
+
54
58
  A reader can download a query's whole result, with the inputs its result on screen was run with
55
59
  (the `export` plugin):
56
60
 
package/dist/api.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Client } from 'openapi-fetch';
2
- import { aj as paths, D as DatasetDescriptor, B as Backend, f as BackendExportRequest, ak as components, i as BackendQueryRequest } from './types-BTyDyld7.js';
2
+ import { ak as paths, D as DatasetDescriptor, B as Backend, f as BackendExportRequest, al as components, i as BackendQueryRequest } from './types-plgahUrN.js';
3
3
  import { D as DataAppError } from './errors-CKvqVaqU.js';
4
4
 
5
5
  /** The core API, typed from anfra core's spec (`api/openapi.yaml`, generated into `schema.d.ts`). */
package/dist/api.js CHANGED
@@ -44,6 +44,42 @@ function toSdkError(status, body) {
44
44
  }
45
45
  }
46
46
 
47
+ // src/api/stream.ts
48
+ async function readEvents(body, onEvent) {
49
+ const reader = body.getReader();
50
+ const decoder = new TextDecoder();
51
+ let buffered = "";
52
+ const line = (text) => {
53
+ if (!text.trim()) return false;
54
+ const event = JSON.parse(text);
55
+ if (event.type === "ping") return false;
56
+ if (event.type === "end") {
57
+ const end = event;
58
+ if (end.status === "failed") throw toSdkError(end.error?.status ?? 500, end.error);
59
+ return true;
60
+ }
61
+ onEvent(event);
62
+ return false;
63
+ };
64
+ try {
65
+ for (; ; ) {
66
+ const { value, done } = await reader.read();
67
+ if (done) break;
68
+ buffered += decoder.decode(value, { stream: true });
69
+ let start = 0;
70
+ for (let newline = buffered.indexOf("\n"); newline >= 0; newline = buffered.indexOf("\n", start)) {
71
+ if (line(buffered.slice(start, newline))) return;
72
+ start = newline + 1;
73
+ }
74
+ buffered = buffered.slice(start);
75
+ }
76
+ if (line(buffered + decoder.decode())) return;
77
+ } finally {
78
+ reader.releaseLock();
79
+ }
80
+ throw new TransportError("The connection to the server was cut before the answer ended.");
81
+ }
82
+
47
83
  // src/api/backend.ts
48
84
  var SUGGESTION_LIMIT = 100;
49
85
  function isAbort(err) {
@@ -94,8 +130,40 @@ async function callCoreAPI(call) {
94
130
  if (!data) throw toSdkError(response.status, error?.error);
95
131
  return data;
96
132
  }
97
- function runQuery(client, body, signal) {
98
- return callCoreAPI(() => client.POST("/core.query", { body, signal }));
133
+ async function runQuery(client, body, signal) {
134
+ const stream = await callCoreAPI(() => client.POST("/core.query", {
135
+ body,
136
+ signal,
137
+ parseAs: "stream",
138
+ headers: { Accept: "application/x-ndjson" }
139
+ }));
140
+ if (!stream) throw new TransportError("The server answered the query with no body.");
141
+ const result = { sql: "", columns: [], result: { fields: [], records: [] }, has_more: false, timings: { steps: [], end_ms: 0 } };
142
+ try {
143
+ await readEvents(stream, (event) => {
144
+ switch (event.type) {
145
+ case "compiled":
146
+ result.sql = event.sql;
147
+ if (event.aql) result.aql = event.aql;
148
+ break;
149
+ case "header":
150
+ result.columns = event.columns;
151
+ result.result.fields = event.fields;
152
+ break;
153
+ case "rows":
154
+ for (const row of event.records) result.result.records.push(row);
155
+ break;
156
+ case "summary":
157
+ result.has_more = event.has_more;
158
+ result.timings = event.timings;
159
+ break;
160
+ }
161
+ });
162
+ } catch (err) {
163
+ if (isAbort(err) || !(err instanceof Error) || err.name !== "TypeError") throw err;
164
+ throw new TransportError(`The connection to the server failed: ${err.message}`);
165
+ }
166
+ return result;
99
167
  }
100
168
  function coreApiBackend(base, options = {}) {
101
169
  const client = typeof base === "string" ? coreClient(base) : base;
@@ -107,13 +175,17 @@ function coreApiBackend(base, options = {}) {
107
175
  columns: toColumns(data.columns),
108
176
  values,
109
177
  meta: {
110
- ...request.pageSize !== void 0 ? { page: request.page ?? 1, pageSize: request.pageSize } : {},
178
+ ...request.pageSize !== void 0 ? { page: request.page ?? 1, pageSize: request.pageSize, hasMore: data.has_more } : {},
111
179
  numRows: values.length
112
180
  },
113
181
  debug: {
114
182
  ...data.aql ? { executedAql: data.aql } : {},
115
183
  executedSql: data.sql,
116
184
  fromCache: false,
185
+ timings: {
186
+ steps: data.timings.steps.map((s) => ({ step: s.step, startMs: s.start_ms })),
187
+ endMs: data.timings.end_ms
188
+ },
117
189
  executedAt: /* @__PURE__ */ new Date()
118
190
  }
119
191
  };
package/dist/app.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { S as Sdk } from './bootstrap-B7r0ggJN.js';
2
- export { A as AnfraPlugins, a as App, C as Control, b as CrossFilter, D as DateDrillControl, E as Edge, F as Filter, c as FrameKernel, I as InstalledPlugins, M as Mapping, O as OVERLAY_ID, d as PluginApi, e as PluginMembers, f as PluginName, P as PluginSetup, Q as Query, g as STRUCTURE_ATTRIBUTES, V as VERSION, h as bootstrap, i as buildStructure, j as createSdk, p as parseRef } from './bootstrap-B7r0ggJN.js';
1
+ import { S as Sdk } from './bootstrap-BkiMDMcp.js';
2
+ export { A as AnfraPlugins, a as App, C as Control, b as CrossFilter, D as DateDrillControl, c as DeprecatedFeatures, E as Edge, F as Filter, d as FrameKernel, I as InstalledPlugins, M as Mapping, O as OVERLAY_ID, e as PluginApi, f as PluginMembers, g as PluginName, P as PluginSetup, Q as Query, h as STRUCTURE_ATTRIBUTES, V as VERSION, i as bootstrap, j as buildStructure, k as createSdk, p as parseRef } from './bootstrap-BkiMDMcp.js';
3
3
  export { D as DataAppError, P as PermissionError, Q as QueryError, T as TransportError, V as ValidationError } from './errors-CKvqVaqU.js';
4
- export { A as Aggregation, a as AppDeclaration, b as AppJson, c as ArrowType, B as Backend, d as BackendCondition, e as BackendDateDrill, f as BackendExportRequest, g as BackendFilter, h as BackendLineageRequest, i as BackendQueryRequest, j as BackendQueryResult, k as BackendSort, C as ColumnMeta, l as Condition, m as ConditionValue, n as ControlMappingJson, o as CrossFilterJson, D as DatasetDescriptor, p as DateDrillDeclaration, q as DateGrain, r as DateTransformation, E as EntityKind, s as EntityRef, t as EntityUsage, u as ExecuteOptions, v as ExecuteSummary, w as ExportFormat, x as ExportFormatOptions, y as ExportOptions, z as ExportResult, F as FILTER_AGGREGATIONS, G as FieldLineage, H as FieldSuggestionsRequest, I as FilterAggregation, J as FilterDeclaration, K as FilterValueType, L as InspectedApp, M as InspectedControl, N as InspectedError, O as InspectedQuery, P as InspectedSelection, Q as InspectedStructure, R as LineageCard, S as LineageDiagram, T as LineageNode, U as LineageOptions, V as LineageResult, W as LineageTarget, X as Listener, Y as LocateKind, Z as LocateTarget, _ as MappingJson, $ as Operator, a0 as QueryDebug, a1 as QueryDeclaration, a2 as QueryInput, a3 as QueryResult, a4 as QuerySort, a5 as QueryState, a6 as RenderFormat, a7 as RenderRequest, a8 as Rendering, a9 as Row, aa as SdkEnvironment, ab as SdkFeatures, ac as Selection, ad as SelectionCondition, ae as SemanticType, af as StructureKind, ag as StructureNode, ah as Unsubscribe, ai as User } from './types-BTyDyld7.js';
5
- export { B as BridgeError, a as BridgeMessage, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as PluginInfo, c as Provision } from './bridge-Byq62yS8.js';
4
+ export { A as Aggregation, a as AppDeclaration, b as AppJson, c as ArrowType, B as Backend, d as BackendCondition, e as BackendDateDrill, f as BackendExportRequest, g as BackendFilter, h as BackendLineageRequest, i as BackendQueryRequest, j as BackendQueryResult, k as BackendSort, C as ColumnMeta, l as Condition, m as ConditionValue, n as ControlMappingJson, o as CrossFilterJson, D as DatasetDescriptor, p as DateDrillDeclaration, q as DateGrain, r as DateTransformation, E as EntityKind, s as EntityRef, t as EntityUsage, u as ExecuteOptions, v as ExecuteSummary, w as ExportFormat, x as ExportFormatOptions, y as ExportOptions, z as ExportResult, F as FILTER_AGGREGATIONS, G as FieldLineage, H as FieldSuggestionsRequest, I as FilterAggregation, J as FilterDeclaration, K as FilterValueType, L as InspectedApp, M as InspectedControl, N as InspectedError, O as InspectedQuery, P as InspectedSelection, Q as InspectedStructure, R as LineageCard, S as LineageDiagram, T as LineageNode, U as LineageOptions, V as LineageResult, W as LineageTarget, X as Listener, Y as LocateKind, Z as LocateTarget, _ as MappingJson, $ as Operator, a0 as QueryDebug, a1 as QueryDeclaration, a2 as QueryInput, a3 as QueryResult, a4 as QuerySort, a5 as QueryState, a6 as QueryTimings, a7 as RenderFormat, a8 as RenderRequest, a9 as Rendering, aa as Row, ab as SdkEnvironment, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, af as SemanticType, ag as StructureKind, ah as StructureNode, ai as Unsubscribe, aj as User } from './types-plgahUrN.js';
5
+ export { B as BridgeError, a as BridgeMessage, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as PluginInfo, c as Provision } from './bridge-BCJklF4M.js';
6
6
 
7
7
  declare const SANDBOX_GLOBAL = "Anfra";
8
8
  /**
package/dist/app.js CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  createSdk,
20
20
  installSandbox,
21
21
  parseRef
22
- } from "./chunk-BL7SPVAS.js";
22
+ } from "./chunk-O3S2GQ5N.js";
23
23
  import {
24
24
  FILTER_AGGREGATIONS
25
25
  } from "./chunk-XIUFHRZE.js";
@@ -27,7 +27,7 @@ import "./chunk-ADWBOQW2.js";
27
27
  import {
28
28
  PROVISION_ELEMENT_ID
29
29
  } from "./chunk-33B2D4U5.js";
30
- import "./chunk-ENWRS6AT.js";
30
+ import "./chunk-MIHZUF2H.js";
31
31
  import {
32
32
  DataAppError,
33
33
  PermissionError,
@@ -1,6 +1,6 @@
1
1
  import { D as DataAppError, V as ValidationError, Q as QueryError, P as PermissionError, T as TransportError } from './errors-CKvqVaqU.js';
2
- import { X as Listener, ah as Unsubscribe, D as DatasetDescriptor, y as ExportOptions, z as ExportResult, a7 as RenderRequest, a8 as Rendering, W as LineageTarget, U as LineageOptions, V as LineageResult, E as EntityKind, l as Condition, J as FilterDeclaration, K as FilterValueType, B as Backend, m as ConditionValue, p as DateDrillDeclaration, q as DateGrain, I as FilterAggregation, n as ControlMappingJson, o as CrossFilterJson, ab as SdkFeatures, ac as Selection, ad as SelectionCondition, a9 as Row, Y as LocateKind, a1 as QueryDeclaration, a5 as QueryState, a3 as QueryResult, a4 as QuerySort, a as AppDeclaration, u as ExecuteOptions, v as ExecuteSummary, f as BackendExportRequest, b as AppJson, L as InspectedApp, ai as User, aa as SdkEnvironment, Q as InspectedStructure } from './types-BTyDyld7.js';
3
- import { b as PluginInfo } from './bridge-Byq62yS8.js';
2
+ import { X as Listener, ai as Unsubscribe, D as DatasetDescriptor, y as ExportOptions, z as ExportResult, a8 as RenderRequest, a9 as Rendering, W as LineageTarget, U as LineageOptions, V as LineageResult, E as EntityKind, l as Condition, J as FilterDeclaration, K as FilterValueType, B as Backend, m as ConditionValue, p as DateDrillDeclaration, q as DateGrain, I as FilterAggregation, n as ControlMappingJson, o as CrossFilterJson, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, aa as Row, Y as LocateKind, a1 as QueryDeclaration, a5 as QueryState, a3 as QueryResult, a4 as QuerySort, a as AppDeclaration, u as ExecuteOptions, v as ExecuteSummary, f as BackendExportRequest, b as AppJson, L as InspectedApp, aj as User, ab as SdkEnvironment, Q as InspectedStructure } from './types-plgahUrN.js';
3
+ import { b as PluginInfo } from './bridge-BCJklF4M.js';
4
4
 
5
5
  interface NotificationTarget {
6
6
  notifyChange(): void;
@@ -301,6 +301,10 @@ declare class Query extends Observable {
301
301
  get sort(): readonly QuerySort[];
302
302
  /** Replaces the sort applied to this query's result. Pass `[]` to clear it back to the AQL's own. */
303
303
  setSort(sort: readonly QuerySort[]): void;
304
+ /**
305
+ * Whether another page may follow: as the backend said of the last page, or, when it did not
306
+ * say, whether that page came back full.
307
+ */
304
308
  get hasMore(): boolean;
305
309
  /**
306
310
  * Everything that changes the rows: the declaration, the conditions reaching this query through
@@ -523,6 +527,21 @@ declare class InstalledPlugins {
523
527
  /** The installed plugin's version, or undefined. */
524
528
  version(name: PluginName): string | undefined;
525
529
  }
530
+ /**
531
+ * What `Anfra.features` says: the kernel's gates, and whether each of anfra's optional plugins is
532
+ * installed.
533
+ *
534
+ * @deprecated Check `Anfra.plugins.has(name)` instead. Kept so Data Apps written before plugins keep
535
+ * working; removed in the next breaking release.
536
+ */
537
+ interface DeprecatedFeatures extends SdkFeatures {
538
+ /** `Anfra.plugins.has('export')`. */
539
+ readonly export: boolean;
540
+ /** `Anfra.plugins.has('render')`. */
541
+ readonly render: boolean;
542
+ /** `Anfra.plugins.has('lineage')`. */
543
+ readonly lineage: boolean;
544
+ }
526
545
  /** The package's version: anfra's own, as each release publishes the SDK with it. */
527
546
  declare const VERSION: string;
528
547
  /**
@@ -555,10 +574,21 @@ declare class Sdk {
555
574
  * before using an optional one.
556
575
  */
557
576
  readonly plugins: InstalledPlugins;
558
- private readonly features;
577
+ /** The kernel's gates (`dateDrill`), as the environment gave them. */
578
+ private readonly gates;
579
+ private deprecatedFeatures?;
559
580
  /** @internal What plugins add to each query and control, by plugin name (the kernel's `provideOn*`). */
560
581
  readonly extensions: EntityExtensions<Query, Control>;
561
582
  constructor(environment: SdkEnvironment);
583
+ /**
584
+ * Whether the host offers each of anfra's optional plugins, from before there were plugins. The
585
+ * first read warns once, in the console.
586
+ *
587
+ * @deprecated Check `Anfra.plugins.has(name)` instead: `Anfra.plugins.has('export')` for
588
+ * `Anfra.features.export`. Kept so Data Apps written before plugins keep working; removed in the
589
+ * next breaking release.
590
+ */
591
+ get features(): Readonly<DeprecatedFeatures>;
562
592
  createApp(declaration?: AppDeclaration): App;
563
593
  /**
564
594
  * Every app this instance has built, for a host rendering an inspection panel.
@@ -691,4 +721,4 @@ type PluginSetup = readonly [name: string, setup: ((kernel: FrameKernel) => void
691
721
  /** Provision the SDK in `win` from its host, run the plugins' setups, and install it. Returns once `Anfra` exists. */
692
722
  declare function bootstrap(win: Window, setups?: readonly PluginSetup[]): void;
693
723
 
694
- export { type AnfraPlugins as A, Control as C, DateDrillControl as D, type Edge as E, Filter as F, InstalledPlugins as I, Mapping as M, OVERLAY_ID as O, type PluginSetup as P, Query as Q, Sdk as S, VERSION as V, App as a, CrossFilter as b, type FrameKernel as c, type PluginApi as d, type PluginMembers as e, type PluginName as f, ATTR as g, bootstrap as h, buildStructure as i, createSdk as j, parseRef as p };
724
+ export { type AnfraPlugins as A, Control as C, DateDrillControl as D, type Edge as E, Filter as F, InstalledPlugins as I, Mapping as M, OVERLAY_ID as O, type PluginSetup as P, Query as Q, Sdk as S, VERSION as V, App as a, CrossFilter as b, type DeprecatedFeatures as c, type FrameKernel as d, type PluginApi as e, type PluginMembers as f, type PluginName as g, ATTR as h, bootstrap as i, buildStructure as j, createSdk as k, parseRef as p };
@@ -1,4 +1,4 @@
1
- import { D as DatasetDescriptor, ai as User } from './types-BTyDyld7.js';
1
+ import { D as DatasetDescriptor, aj as User } from './types-plgahUrN.js';
2
2
 
3
3
  /**
4
4
  * The bridge: the postMessage protocol between a Data App's frame (`app`'s bootstrap) and the
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.11.0";
2
+ var version = "0.11.1";
3
3
 
4
4
  export {
5
5
  version
@@ -9,7 +9,7 @@ import {
9
9
  } from "./chunk-33B2D4U5.js";
10
10
  import {
11
11
  version
12
- } from "./chunk-ENWRS6AT.js";
12
+ } from "./chunk-MIHZUF2H.js";
13
13
  import {
14
14
  DataAppError,
15
15
  PermissionError,
@@ -122,9 +122,13 @@ var Query = class extends Observable {
122
122
  this._sort = [...sort];
123
123
  this.notify();
124
124
  }
125
+ /**
126
+ * Whether another page may follow: as the backend said of the last page, or, when it did not
127
+ * say, whether that page came back full.
128
+ */
125
129
  get hasMore() {
126
130
  if (!this._result || this.pageSize === void 0) return false;
127
- return this.lastPageRows >= this.pageSize;
131
+ return this._result.meta.hasMore ?? this.lastPageRows >= this.pageSize;
128
132
  }
129
133
  /**
130
134
  * Everything that changes the rows: the declaration, the conditions reaching this query through
@@ -862,7 +866,11 @@ function toResult(query, data) {
862
866
  rows,
863
867
  meta: {
864
868
  // Only a paged query has a page to report.
865
- ...pageSize !== void 0 ? { page: data.meta?.page ?? query.page, pageSize: data.meta?.pageSize ?? pageSize } : {},
869
+ ...pageSize !== void 0 ? {
870
+ page: data.meta?.page ?? query.page,
871
+ pageSize: data.meta?.pageSize ?? pageSize,
872
+ ...data.meta?.hasMore !== void 0 ? { hasMore: data.meta.hasMore } : {}
873
+ } : {},
866
874
  numRows: data.meta?.numRows ?? rows.length
867
875
  },
868
876
  ...data.debug ? { debug: data.debug } : {}
@@ -1788,7 +1796,9 @@ var Sdk = class {
1788
1796
  * before using an optional one.
1789
1797
  */
1790
1798
  __publicField(this, "plugins");
1791
- __publicField(this, "features");
1799
+ /** The kernel's gates (`dateDrill`), as the environment gave them. */
1800
+ __publicField(this, "gates");
1801
+ __publicField(this, "deprecatedFeatures");
1792
1802
  /** @internal What plugins add to each query and control, by plugin name (the kernel's `provideOn*`). */
1793
1803
  __publicField(this, "extensions", { query: /* @__PURE__ */ new Map(), control: /* @__PURE__ */ new Map() });
1794
1804
  if (!environment?.datasets) {
@@ -1818,11 +1828,31 @@ var Sdk = class {
1818
1828
  ])
1819
1829
  );
1820
1830
  this.backend = environment.backend;
1821
- this.features = Object.freeze({ ...environment.features });
1831
+ this.gates = Object.freeze({ ...environment.features });
1822
1832
  this.plugins = new InstalledPlugins(environment.plugins ?? []);
1823
1833
  }
1834
+ /**
1835
+ * Whether the host offers each of anfra's optional plugins, from before there were plugins. The
1836
+ * first read warns once, in the console.
1837
+ *
1838
+ * @deprecated Check `Anfra.plugins.has(name)` instead: `Anfra.plugins.has('export')` for
1839
+ * `Anfra.features.export`. Kept so Data Apps written before plugins keep working; removed in the
1840
+ * next breaking release.
1841
+ */
1842
+ get features() {
1843
+ if (!this.deprecatedFeatures) {
1844
+ console.warn("anfra: Anfra.features is deprecated and will be removed. Check Anfra.plugins.has('export'), Anfra.plugins.has('render') or Anfra.plugins.has('lineage') instead.");
1845
+ this.deprecatedFeatures = Object.freeze({
1846
+ ...this.gates,
1847
+ export: this.plugins.has("export"),
1848
+ render: this.plugins.has("render"),
1849
+ lineage: this.plugins.has("lineage")
1850
+ });
1851
+ }
1852
+ return this.deprecatedFeatures;
1853
+ }
1824
1854
  createApp(declaration = {}) {
1825
- const app = new App(declaration, this.indices, this.backend, this.features, this.extensions);
1855
+ const app = new App(declaration, this.indices, this.backend, this.gates, this.extensions);
1826
1856
  app.index = this._apps.length;
1827
1857
  this._apps.push(app);
1828
1858
  return app;
package/dist/common.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { D as DataAppError, P as PermissionError, Q as QueryError, T as TransportError, V as ValidationError } from './errors-CKvqVaqU.js';
2
- export { A as Aggregation, a as AppDeclaration, b as AppJson, c as ArrowType, B as Backend, d as BackendCondition, e as BackendDateDrill, f as BackendExportRequest, g as BackendFilter, h as BackendLineageRequest, i as BackendQueryRequest, j as BackendQueryResult, k as BackendSort, C as ColumnMeta, l as Condition, m as ConditionValue, n as ControlMappingJson, o as CrossFilterJson, D as DatasetDescriptor, p as DateDrillDeclaration, q as DateGrain, r as DateTransformation, E as EntityKind, s as EntityRef, t as EntityUsage, u as ExecuteOptions, v as ExecuteSummary, w as ExportFormat, x as ExportFormatOptions, y as ExportOptions, z as ExportResult, F as FILTER_AGGREGATIONS, G as FieldLineage, H as FieldSuggestionsRequest, I as FilterAggregation, J as FilterDeclaration, K as FilterValueType, L as InspectedApp, M as InspectedControl, N as InspectedError, O as InspectedQuery, P as InspectedSelection, Q as InspectedStructure, R as LineageCard, S as LineageDiagram, T as LineageNode, U as LineageOptions, V as LineageResult, W as LineageTarget, X as Listener, Y as LocateKind, Z as LocateTarget, _ as MappingJson, $ as Operator, a0 as QueryDebug, a1 as QueryDeclaration, a2 as QueryInput, a3 as QueryResult, a4 as QuerySort, a5 as QueryState, a6 as RenderFormat, a7 as RenderRequest, a8 as Rendering, a9 as Row, aa as SdkEnvironment, ab as SdkFeatures, ac as Selection, ad as SelectionCondition, ae as SemanticType, af as StructureKind, ag as StructureNode, ah as Unsubscribe, ai as User } from './types-BTyDyld7.js';
3
- export { B as BridgeError, a as BridgeMessage, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as PluginInfo, c as Provision } from './bridge-Byq62yS8.js';
2
+ export { A as Aggregation, a as AppDeclaration, b as AppJson, c as ArrowType, B as Backend, d as BackendCondition, e as BackendDateDrill, f as BackendExportRequest, g as BackendFilter, h as BackendLineageRequest, i as BackendQueryRequest, j as BackendQueryResult, k as BackendSort, C as ColumnMeta, l as Condition, m as ConditionValue, n as ControlMappingJson, o as CrossFilterJson, D as DatasetDescriptor, p as DateDrillDeclaration, q as DateGrain, r as DateTransformation, E as EntityKind, s as EntityRef, t as EntityUsage, u as ExecuteOptions, v as ExecuteSummary, w as ExportFormat, x as ExportFormatOptions, y as ExportOptions, z as ExportResult, F as FILTER_AGGREGATIONS, G as FieldLineage, H as FieldSuggestionsRequest, I as FilterAggregation, J as FilterDeclaration, K as FilterValueType, L as InspectedApp, M as InspectedControl, N as InspectedError, O as InspectedQuery, P as InspectedSelection, Q as InspectedStructure, R as LineageCard, S as LineageDiagram, T as LineageNode, U as LineageOptions, V as LineageResult, W as LineageTarget, X as Listener, Y as LocateKind, Z as LocateTarget, _ as MappingJson, $ as Operator, a0 as QueryDebug, a1 as QueryDeclaration, a2 as QueryInput, a3 as QueryResult, a4 as QuerySort, a5 as QueryState, a6 as QueryTimings, a7 as RenderFormat, a8 as RenderRequest, a9 as Rendering, aa as Row, ab as SdkEnvironment, ac as SdkFeatures, ad as Selection, ae as SelectionCondition, af as SemanticType, ag as StructureKind, ah as StructureNode, ai as Unsubscribe, aj as User } from './types-plgahUrN.js';
3
+ export { B as BridgeError, a as BridgeMessage, F as FrameMessage, H as HostMessage, P as PROVISION_ELEMENT_ID, b as PluginInfo, c as Provision } from './bridge-BCJklF4M.js';
package/dist/host.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { b as PluginInfo, c as Provision } from './bridge-Byq62yS8.js';
2
- import { D as DatasetDescriptor, ai as User } from './types-BTyDyld7.js';
1
+ import { b as PluginInfo, c as Provision } from './bridge-BCJklF4M.js';
2
+ import { D as DatasetDescriptor, aj as User } from './types-plgahUrN.js';
3
3
  import { C as CallOptions, P as Plugin, M as Middleware } from './plugin-C5cihcQD.js';
4
4
  export { a as CallContext, b as CallDefinition, c as CallHandler, d as Caller, E as EventCheck, F as FrameHalf, H as HandlerCallOptions, e as HandlerContext, f as HostHalf, g as MountContext, h as definePlugin } from './plugin-C5cihcQD.js';
5
5
 
package/dist/host.js CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  import "./chunk-PKBMQBKP.js";
17
17
 
18
18
  // anfra-sdk:anfra-sdk:frame-script
19
- var anfra_sdk_frame_script_default = '"use strict";var __anfraKernel=(()=>{var M=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var pt=Object.prototype.hasOwnProperty;var ut=(t,n,e)=>n in t?M(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var o=(t,n)=>M(t,"name",{value:n,configurable:!0});var ft=(t,n)=>{for(var e in n)M(t,e,{get:n[e],enumerable:!0})},mt=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of ct(n))!pt.call(t,i)&&i!==e&&M(t,i,{get:()=>n[i],enumerable:!(r=dt(n,i))||r.enumerable});return t};var ht=t=>mt(M({},"__esModule",{value:!0}),t);var c=(t,n,e)=>ut(t,typeof n!="symbol"?n+"":n,e);var rn={};ft(rn,{bootstrap:()=>at});var Se="anfra-provision";var U=class U extends Error{constructor(e,r){super(e);c(this,"entity");this.name=new.target.name,this.entity=r,Object.setPrototypeOf(this,new.target.prototype)}};o(U,"DataAppError");var S=U,H=class H extends S{};o(H,"ValidationError");var u=H,Y=class Y extends S{constructor(e,r,i){super(e,r);c(this,"cause");this.cause=i}};o(Y,"QueryError");var R=Y,W=class W extends S{};o(W,"PermissionError");var D=W,X=class X extends S{constructor(e,r,i){super(e,i);c(this,"status");this.status=r}};o(X,"TransportError");var C=X;function Ce(){let t=new Error("Aborted");return t.name="AbortError",t}o(Ce,"abortError");function gt(t){return t?.name==="AbortError"}o(gt,"isAbortError");var yt=new Set(["ValidationError","QueryError","PermissionError","TransportError"]);function bt(t){let n=t;return n instanceof Error&&yt.has(n.name)?{name:n.name,message:n.message||"The call failed."}:{name:"QueryError",message:"The call failed."}}o(bt,"toBridgeError");function wt(t){switch(t?.name){case"PermissionError":return new D(t.message);case"TransportError":return new C(t.message);case"ValidationError":return new u(t.message);default:return new R(t?.message||"The call failed.")}}o(wt,"fromBridgeError");function Ae(t,n){let e=new Map,r=new Map,i=1,s=o((l,a,d)=>{let p=new AbortController;r.set(l,p),Promise.resolve().then(()=>n.answer(a,d,p.signal)).then(g=>{p.signal.aborted||t({type:"anfra:result",id:l,ok:!0,result:g})}).catch(g=>{p.signal.aborted||gt(g)||t({type:"anfra:result",id:l,ok:!1,error:bt(g)})}).finally(()=>{r.get(l)===p&&r.delete(l)})},"answer");return{call(l,a,d){return new Promise((p,g)=>{if(d?.aborted){g(Ce());return}let k=i++;e.set(k,{resolve:p,reject:g}),d?.addEventListener("abort",()=>{e.delete(k)&&(t({type:"anfra:cancel",id:k}),g(Ce()))},{once:!0}),t({type:"anfra:call",id:k,name:l,request:a})})},emit(l,a){t({type:"anfra:event",name:l,payload:a})},receive(l){switch(l?.type){case"anfra:call":return s(l.id,l.name,l.request),!0;case"anfra:result":{let a=e.get(l.id);return a&&(e.delete(l.id),l.ok?a.resolve(l.result):a.reject(wt(l.error))),!0}case"anfra:cancel":return r.get(l.id)?.abort(),r.delete(l.id),!0;case"anfra:event":return n.event(l.name,l.payload),!0;default:return!1}},close(l){r.forEach(a=>a.abort()),r.clear(),e.forEach(({reject:a})=>a(l)),e.clear()}}}o(Ae,"createEndpoint");var Z=class Z{constructor(n){c(this,"listeners",new Set);c(this,"parent");this.parent=n}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}notifyChange(){this.listeners.forEach(n=>n()),this.parent?.notifyChange()}notify(){this.notifyChange()}};o(Z,"Observable");var $=Z;var Re=["year","quarter","month","week","day","hour","minute"];function xt(t,n){if(!Re.includes(n))throw new u(`Invalid grain \'${n}\'. Expected one of: ${Re.join(", ")}.`,t)}o(xt,"assertGrain");function De(t,n){return n?(xt(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}o(De,"drillCondition");function Et(t){let n=t.toLowerCase();return n.includes("date")||n.includes("time")?"date":n.includes("int")||n.includes("number")||n.includes("float")||n.includes("decimal")?"number":n.includes("bool")?"boolean":"string"}o(Et,"inferType");function kt(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}o(kt,"sameCondition");var ee=class ee extends ${constructor(e,r,i){super(r);c(this,"name");c(this,"app");c(this,"pending");c(this,"applied");c(this,"initial");this.name=e,this.app=r,this.initial=i,this.pending=i}locate(){return this.app.locate("control",this.name)}get condition(){return this.pending}get appliedCondition(){return this.applied}get isDirty(){return this.applied!==void 0&&!kt(this.pending,this.applied)}setCondition(e){this.pending=e,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};o(ee,"Control");var T=ee,te=class te extends T{constructor(e,r,i,s,l){super(e,r,i.default??{operator:"is",values:[]});c(this,"kind","filter");c(this,"declaration");c(this,"type");c(this,"resolved");c(this,"datasetName");c(this,"backend");c(this,"loadedOptions");if(this.declaration=i,this.backend=l,i.field){if(!s)throw new u(`Filter \'${e}\' names a field but no dataset. Pass \\`dataset\\` alongside \\`field\\`.`,e);this.resolved=s.resolve(i.field,e),this.datasetName=s.descriptor.name,this.type=i.type??Et(this.resolved.type)}else{if(!i.type)throw new u(`Filter \'${e}\' is a manual filter, so it needs a \\`type\\`.`,e);this.type=i.type}this.assertValues(this.condition.values??[]),this.assertValues(i.options??[])}setCondition(e){this.assertValues(e.values??[]),super.setCondition(e)}assertValues(e){if(this.type!=="number")return;let r=e.find(i=>typeof i=="number");if(r!==void 0)throw new u(`Filter \'${this.name}\' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(r))}, not ${String(r)}), so none has lost a digit.`,this.name)}get isFieldBacked(){return this.resolved!==void 0}get options(){return this.loadedOptions??this.declaration.options??[]}async loadOptions(e,r=new AbortController().signal){let i=this.resolved?.modelName;if(!this.resolved||!i||!this.backend||!this.datasetName)return this.options;let s=await this.backend.fieldSuggestions({dataset:this.datasetName,model:i,field:this.resolved.fieldName,q:e??""},r);return this.loadedOptions=[...s??[]],this.notify(),this.loadedOptions}toJSON(){return this.declaration}};o(te,"Filter");var P=te,ne=class ne extends T{constructor(e,r,i={}){super(e,r,De(e,i.default));c(this,"kind","dateDrill");c(this,"declaration");this.declaration=i}setGrain(e){this.setCondition(De(this.name,e))}toJSON(){return this.declaration}};o(ne,"DateDrillControl");var z=ne;var v={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},_e=`[${v.container}],[${v.block}],[${v.query}],[${v.control}]`;function $e(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}o($e,"parseRef");var Te=o(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Oe(t,n,e,r){let i=n==="query"?v.query:v.control;return[...t.querySelectorAll(`[${i}]`)].filter(s=>Te(s.getAttribute(i)).some(l=>{let a=$e(l);return a?.app===e&&a.name===r}))}o(Oe,"markersFor");var vt=o((t,n,e)=>{let r=t[e.app];return r?Object.prototype.hasOwnProperty.call(n==="query"?r.queries:r.controls,e.name):!1},"hasEntity");function Ne(t,n){var k;let e=[],r=new Map,i=new Map,s=new Map,l=new Map,a={container:new Set,block:new Set},d={},p=o((h,f,y)=>{let b=h?s.get(h).children:e,m=h?`${s.get(h).key}.`:"",w={...f,key:`${m}${b.length}`,children:[]};return b.push(w),r.set(w.key,y),i.set(y,[...i.get(y)??[],w.key]),w},"place");for(let h of t.querySelectorAll(_e)){let f=h.parentElement?.closest(_e)??null,y=h.getAttribute(v.container),b=h.getAttribute(v.block),m=h.getAttribute(v.label)??void 0,w=f&&(l.get(f)==="block"?f:f.closest(`[${v.block}]`)),_;if(y!==null||b!==null){let E=y!==null?"container":"block",A=(y??b??"").trim(),x=[];y!==null&&b!==null&&x.push("This element is marked as a container and as a block. It counts as a container."),A?a[E].has(A)?x.push(`Another ${E} already has the id "${A}".`):a[E].add(A):x.push(`This ${E} has no id.`),w&&x.push(`A block can\'t hold a ${E}. This one is inside the block "${w.getAttribute(v.block)}".`),_=p(f,{kind:E,id:A,...m!==void 0?{label:m}:{},problems:x},h),s.set(h,_),l.set(h,E)}let F=_?h:f;for(let E of["query","control"])for(let A of Te(h.getAttribute(E==="query"?v.query:v.control))){let x=$e(A),L=[];if(x?vt(n,E,x)||L.push(n[x.app]?`No ${E} is called "${x.name}" in app ${x.app}.`:`The page has no app ${x.app}.`):L.push(`Can\'t read "${A}". Write the ${E}\'s name, or app/name when the page has several apps.`),p(F,{kind:E,name:x?.name??A,app:x?.app??0,problems:L},h),x&&!L.length){let lt=`${x.app}/${x.name}`,ke=d[k=`${E}:${lt}`]??(d[k]={elements:new Set,blocks:new Set});ke.elements.add(h);let ve=_?.kind==="block"?_.id:w?.getAttribute(v.block);ve&&ke.blocks.add(ve)}}}let g=Object.fromEntries(Object.entries(d).map(([h,f])=>[h,{markers:f.elements.size,blocks:[...f.blocks]}]));return{nodes:e,usage:g,elements:r,keysOf:i}}o(Ne,"buildStructure");var Fe="data-anfra-layer",St="position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";function Ct(t){let n=t.querySelector(`[${Fe}]`);if(n instanceof(t.defaultView?.HTMLElement??HTMLElement))return n;let e=t.createElement("div");return e.setAttribute(Fe,""),e.setAttribute("style",St),(t.body??t.documentElement).appendChild(e),e}o(Ct,"layerOf");function Q(t,n){let e=Ct(t),r=[...e.children].find(s=>s.getAttribute("data-part")===n);if(r?.shadowRoot)return r.shadowRoot;let i=t.createElement("div");return i.setAttribute("data-part",n),e.appendChild(i),i.attachShadow({mode:"open"})}o(Q,"layerRoot");var Me="anfra-overlay",At=1500,Rt="position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;",Dt="position:fixed;max-width:60vw;display:flex;gap:6px;align-items:baseline;padding:3px 8px;border-radius:4px;background:#0f172a;color:#f8fafc;font:12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,0.35);",_t={kind:"color:#94a3b8;",name:"color:#93c5fd;font-weight:700;",label:"color:#f8fafc;",note:"color:#94a3b8;",size:"color:#94a3b8;margin-left:10px;"},ie=class ie{constructor(n){c(this,"doc",n);c(this,"root");c(this,"shown",[]);c(this,"text",{kind:"",name:""});c(this,"timer");c(this,"reposition",o(()=>this.draw(),"reposition"));let e=Q(n,"anfra"),r=e.getElementById(Me);r instanceof(n.defaultView?.HTMLElement??HTMLElement)?this.root=r:(this.root=n.createElement("div"),this.root.id=Me,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),e.appendChild(this.root))}show(n,e){if(this.clearTimer(),this.root.isConnected||Q(this.doc,"anfra").appendChild(this.root),this.shown=[...n],this.text=e,!this.shown.length){this.hide();return}this.root.style.display="block",this.draw(),this.doc.addEventListener("scroll",this.reposition,{capture:!0,passive:!0}),this.doc.defaultView?.addEventListener("resize",this.reposition)}flash(n,e,r=At){this.show(n,e),this.timer=setTimeout(()=>this.hide(),r)}hide(){this.clearTimer(),this.shown=[],this.root.style.display="none",this.root.replaceChildren(),this.doc.removeEventListener("scroll",this.reposition,{capture:!0}),this.doc.defaultView?.removeEventListener("resize",this.reposition)}get visible(){return this.shown.length>0}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}draw(){let n=this.shown.map(a=>{let d=a.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${Rt}left:${d.left}px;top:${d.top}px;width:${d.width}px;height:${d.height}px;`),p}),e=this.shown[0].getBoundingClientRect(),r=this.doc.createElement("div");r.setAttribute("data-testid","anfra-overlay-label");let i=this.doc.defaultView?.innerHeight??0,s=e.top>=26?e.top-24:Math.max(4,e.top+4),l=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${Dt}left:${l}px;top:${Math.min(s,i-24)}px;`);for(let a of["kind","name","label","note","size"]){let d=this.text[a];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",_t[a]),p.setAttribute("data-part",a),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};o(ie,"Overlay");var re=ie,Qe=new WeakMap;function V(t){let n=Qe.get(t);return n||(n=new re(t),Qe.set(t,n)),n}o(V,"overlayFor");function Ie(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}o(Ie,"scrollTo");function oe(t,n,e,r,i){if(r in n||t.has(r))throw new u(`Plugin \'${r}\' can\'t add \'${r}\' to a ${e}: it already has one.`);t.set(r,i)}o(oe,"addExtension");function j(t,n){return n?.forEach((e,r)=>{let i=!1,s;Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){return i||(s=e(t),i=!0),s}})}),t}o(j,"applyExtensions");var $t="anfra.body",se="__anfraBodyExports",Tt={DataAppError:S,ValidationError:u,QueryError:R,PermissionError:D,TransportError:C};function Ot(t,n){let e=t,r=t.document.createElement("script");r.textContent=`(function () { var __anfraBody;\n${n}\n;self[${JSON.stringify(se)}] = __anfraBody; })();`,(t.document.head??t.document.documentElement).appendChild(r),r.remove();let i=e[se];if(delete e[se],!i)throw new u("The host sent a plugin body that did not run.");return i.default??i}o(Ot,"runBody");function Be(t,n,e){let{window:r,sdk:i,endpoint:s}=n,l;return{plugin:t,window:r,sdk:i,errors:Tt,get overlay(){return V(r.document)},structure:o(()=>Ne(r.document,i.apps),"structure"),call:o((a,d,p)=>s.call(a,d??null,p),"call"),emit:o((a,d)=>s.emit(`${t}.${a}`,d??null),"emit"),handle(a,d){n.handlers.set(`${t}.${a}`,d)},on(a,d){let p=`${t}.${a}`;n.listeners.has(p)||n.listeners.set(p,new Set),n.listeners.get(p).add(d)},onApp(a){n.appListeners.add(a),i.apps.forEach(d=>a(d))},provide(a){if(t in i)throw new u(`Plugin \'${t}\' can\'t add a member Anfra already has.`);Object.defineProperty(i,t,{value:a,enumerable:!0})},provideOnQuery:o(a=>oe(i.extensions.query,e.Query.prototype,"query",t,a),"provideOnQuery"),provideOnControl:o(a=>oe(i.extensions.control,e.Control.prototype,"control",t,a),"provideOnControl"),layer:o(()=>Q(r.document,t),"layer"),body(){return l??(l=s.call($t,{plugin:t}).then(a=>Ot(r,a)).catch(a=>{throw l=void 0,a})),l}}}o(Be,"createKernel");var ae=class ae extends ${constructor(e,r,i){super(r);c(this,"kind","query");c(this,"name");c(this,"declaration");c(this,"dataset");c(this,"app");c(this,"_state","idle");c(this,"_result");c(this,"_error");c(this,"_page",1);c(this,"_sort",[]);c(this,"lastRunSignature");c(this,"lastPageRows",0);c(this,"controller");if(!i.aql?.trim())throw new u(`Query \'${e}\' declares no AQL.`,e);let{pageSize:s}=i;if(s!==void 0&&!(Number.isInteger(s)&&s>=1))throw new u(`Query \'${e}\' declares pageSize ${s}; it must be a whole number of at least 1.`,e);this.name=e,this.app=r,this.declaration=i,this.dataset=r.datasetIndex(i.dataset,e)}locate(){return this.app.locate("query",this.name)}get state(){return this._state}get result(){return this._result}get error(){return this._error}get pageSize(){return this.declaration.pageSize}get page(){return this._page}get sort(){return this._sort}setSort(e){this._sort=[...e],this.notify()}get hasMore(){return!this._result||this.pageSize===void 0?!1:this.lastPageRows>=this.pageSize}signature(){let e=this.app.mappingsTo(this.name).map(r=>({field:r.field,aggregation:r.aggregation,condition:r.from.condition})).sort((r,i)=>r.field.localeCompare(i.field)||JSON.stringify(r).localeCompare(JSON.stringify(i)));return JSON.stringify({declaration:this.declaration,conditions:e,selection:this.app.selectionConditionsFor(this.name,"pending"),selectionExpression:this.app.selectionExpressionFor(this.name,"pending"),sort:this._sort,timezone:this.app.timezone,page:this._page})}get isDirty(){return this.lastRunSignature!==void 0&&this.signature()!==this.lastRunSignature}shouldRun(e=!1){return e||this.lastRunSignature===void 0||this.isDirty}abort(){this.controller?.abort()}async fetchMore(){if(this.pageSize===void 0)throw new u(`Query \'${this.name}\' declares no pageSize, so it has no more pages.`,this.name);this.hasMore&&(this._page+=1,await this.app.fetchPage(this))}select(e,r={}){this.app.select(this,Array.isArray(e)?e:[e],r.fields)}get selectedRows(){let{selection:e}=this.app;if(e?.source!==this.name)return[];let r=this._result?.rows;if(!r)return e.rows;let i=o(l=>JSON.stringify(e.fields.map(a=>l[a]??null)),"key"),s=new Set(e.rows.map(i));return r.filter(l=>s.has(i(l)))}markExecuting(){this._state="executing",this._error=void 0,this.notify()}markSuccess(e,r,i){if(this._state="success",this._error=void 0,this.lastRunSignature=r,this.lastPageRows=e.rows.length,i&&this._result){let s=[...this._result.rows,...e.rows];this._result={...e,rows:s,meta:{...e.meta,numRows:s.length}}}else this._result=e;this.notify()}markError(e){this._state="error",this._error=e,this.notify()}rewindPage(){this._page>1&&(this._page-=1)}resetPage(){this._page=1,this.lastPageRows=0}toJSON(){return this.declaration}};o(ae,"Query");var O=ae;var le=class le{constructor(n,e,r,i){c(this,"kind","control");c(this,"from");c(this,"to");c(this,"field");c(this,"aggregation");this.from=n,this.to=e,this.field=r,this.aggregation=i}get id(){return`${this.from.name}.${this.to.name}.${this.field}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:this.from.kind,name:this.from.name},to:{kind:"query",name:this.to.name},field:this.field,...this.aggregation?{aggregation:this.aggregation}:{}}}};o(le,"Mapping");var J=le,de=class de{constructor(n,e){c(this,"kind","crossFilter");c(this,"from");c(this,"to");this.from=n,this.to=e}get id(){return`${this.from.name}.${this.to.name}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:"query",name:this.from.name},to:{kind:"query",name:this.to.name}}}};o(de,"CrossFilter");var q=de;var ce=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function Nt(t,n){let e=t.length+1,r=n.length+1,i=Array.from({length:r},(s,l)=>l);for(let s=1;s<e;s++){let l=[s];for(let a=1;a<r;a++)l[a]=Math.min(i[a]+1,l[a-1]+1,i[a-1]+(t[s-1]===n[a-1]?0:1));i=l}return i[r-1]}o(Nt,"editDistance");function Ft(t,n){let e,r=1/0;n.forEach(s=>{let l=Nt(t.toLowerCase(),s.toLowerCase());l<r&&(r=l,e=s)});let i=Math.max(2,Math.floor(t.length/3));return r<=i?e:void 0}o(Ft,"suggest");function N(t,n,e){let r=Ft(n,e);return r?`${t} Did you mean \'${r}\'?`:t}o(N,"withSuggestion");var pe=class pe{constructor(n){c(this,"descriptor");c(this,"fields",new Map);c(this,"references");this.descriptor=n,n.data_models.forEach(e=>{e.fields.forEach(r=>{let i=String(e.name);this.fields.set(`${i}.${r.name}`,{modelName:i,fieldName:r.name,isMetric:!1,type:r.type,label:r.label??r.name})})}),n.metrics.forEach(e=>{this.fields.set(e.name,{fieldName:e.name,isMetric:!0,type:e.type,label:e.label??e.name})}),this.references=[...this.fields.keys()]}resolve(n,e){let r=this.fields.get(n);if(r)return r;throw new u(N(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};o(pe,"DatasetIndex");var G=pe;function Le(t,n,e){let r=t[n];if(r)return r;throw new u(N(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}o(Le,"resolveDataset");function Pe(t,n){if(!ce.includes(t))throw new u(N(`Invalid filter aggregation \'${t}\'.`,t,[...ce]),n)}o(Pe,"assertValidFilterAggregation");function ze(t,n,e){if(!n)throw new u(`A ${e} needs a name.`);for(let r of t)if(r===n)throw new u(`\'${n}\' is already declared in this app.`,n)}o(ze,"assertUniqueName");function Mt(t,n){if(!(!n||n.operator==="none"||n.operator==="transform_date_drill"||!["is_null","not_null","is_true","is_false","transform_pop_none"].includes(n.operator)&&!n.values?.length))return{field:t.field,operator:n.operator,values:n.values??[],...n.modifier?{modifier:n.modifier}:{},...t.aggregation?{aggregation:t.aggregation}:{}}}o(Mt,"toFilter");function Qt(t,n){if(n?.operator!=="transform_date_drill")return;let e=n.values?.[0];if(typeof e!="string")return;let r=e.replace(/^datetrunc\\s+/,"");return{field:t.field,grain:r}}o(Qt,"toDateDrill");function It(t,n){let e=n.columns??[],r=(n.values??[]).map(s=>{let l={};return e.forEach((a,d)=>{l[a.name]=s[d]}),l}),{pageSize:i}=t;return{columns:e,rows:r,meta:{...i!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??i}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}o(It,"toResult");function Ve(t,n,e,r){let i=n.map(d=>Mt(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=n.map(d=>Qt(d,d.from.appliedCondition)).filter(d=>d!==void 0),l=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),a=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...i,...l],conditions:a,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:s},...r.timezone?{timezone:r.timezone}:{}}}o(Ve,"buildQuery");function Bt(t,n,e,r){return{...Ve(t,n,e,r),...t.pageSize!==void 0?{page:t.page,pageSize:t.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}o(Bt,"buildRequest");function Lt(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}o(Lt,"defaultExportFilename");function je(t,n,e,r,i){let s=i.format??"csv",l=s==="csv"?{bom:!0,...i.formatOptions}:i.formatOptions;return{...Ve(t,n,e,r),format:s,...l?{formatOptions:l}:{},filename:i.filename?.trim()||Lt(t,r.title)}}o(je,"buildExportRequest");async function ue(t,n,e,r,i){let s=Bt(t,n,e,r),l=await r.backend.submitQuery(s,i);return It(t,l)}o(ue,"runQuery");function Pt(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return jt(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError(`Cannot express ${t} in AQL.`);return Math.abs(t)>=1e21?BigInt(t).toString():String(t)}return JSON.stringify(t).split("\\u2028").join("\\\\u2028").split("\\u2029").join("\\\\u2029")}o(Pt,"literal");function Je(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${Pt(n,e)}`}o(Je,"equals");var zt=new Set(["NaN","Infinity","-Infinity"]),Vt=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function jt(t){let n=Vt.exec(t);if(!n)throw zt.has(t)?new RangeError(`Cannot express ${t} in AQL.`):new TypeError(`${JSON.stringify(t)} is not a number: a number is a string in JSON\'s number syntax.`);let[,e,r,i="",s]=n;if(s===void 0)return t;let l=r+i,a=r.length+Number(s),d;return a<=0?d=`0.${"0".repeat(-a)}${l}`:a>=l.length?d=l+"0".repeat(a-l.length):d=`${l.slice(0,a)}.${l.slice(a)}`,e+d.replace(/^0+(?=\\d)/,"")}o(jt,"numberLiteral");function qe(t,n,e){return`${t} matches @(${n} until ${e})`}o(qe,"dateRange");function Ge(t,n){if(n.length===0)throw new RangeError(`\\`${t}\\` needs at least one operand.`);return n.length===1?n[0]:`${t}(${n.join(", ")})`}o(Ge,"combine");var Ke=o(t=>Ge("and",t),"and"),Ue=o(t=>Ge("or",t),"or");var Jt=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,qt={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function He(t){if(typeof t!="string")return;let n=Jt.exec(t);if(n)return{year:Number(n[1]),month:Number(n[2])-1,day:Number(n[3]),hour:Number(n[4]??0),minute:Number(n[5]??0),second:Number(n[6]??0),hasTime:n[4]!==void 0}}o(He,"parseStamp");function I(t,n){let e=new Date(t),r=o(s=>String(s).padStart(2,"0"),"pad"),i=`${e.getUTCFullYear()}-${r(e.getUTCMonth()+1)}-${r(e.getUTCDate())}`;return n?`${i} ${r(e.getUTCHours())}:${r(e.getUTCMinutes())}:${r(e.getUTCSeconds())}`:i}o(I,"format");function Ye(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}o(Ye,"toMs");function fe(t){let n=He(t);if(n)return I(Ye(n),n.hasTime)}o(fe,"normalise");function me(t,n){let e=He(t);if(!e)return;let{year:r,month:i,day:s,hour:l,minute:a,second:d,hasTime:p}=e;return I(n==="year"?Date.UTC(r+1,i,s,l,a,d):n==="quarter"?Date.UTC(r,i+3,s,l,a,d):n==="month"?Date.UTC(r,i+1,s,l,a,d):Ye(e)+qt[n],p)}o(me,"addGrain");function We(t){if(t?.startsWith("datetrunc "))return t.slice(10)}o(We,"grainOf");function Gt(t){let n=new Set;return t.filter(e=>{let r=`${typeof e}:${String(e)}`;return n.has(r)?!1:(n.add(r),!0)})}o(Gt,"distinct");function Kt(t,n){let e=t.map(fe);if(e.some(i=>i===void 0))return!1;let r=e.slice().sort();for(let i=1;i<r.length;i+=1)if(me(r[i-1],n)!==r[i])return!1;return!0}o(Kt,"isContiguous");function Ut(t,n,e){let r=n.map(fe);if(r.some(d=>d===void 0))return;let i=r.slice().sort(),s=i[0],l=me(i[i.length-1],e);if(!l)return;let a=Kt(n,e);return{condition:{field:t,operator:"matches",values:[`${s} until ${l}`]},admits:a?n.length:Number.POSITIVE_INFINITY,lossy:!a}}o(Ut,"dateRange");function Ht(t,n,e){let r=e.filter(a=>a!=null),i=Gt(r);if(!i.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let s=r.length!==e.length,l=We(n);if(l){let a=Ut(t,i,l);if(a)return{...a,lossy:a.lossy||s}}return{condition:{field:t,operator:"is",values:i},admits:i.length,lossy:s}}o(Ht,"deriveOne");function Xe(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}o(Xe,"fieldReferenceOf");function Yt(t,n,e,r){try{let i=e.map(s=>Ke(n.map(l=>{let a=t.get(l),d=Xe(a),p=s[l]??null,g=We(r[d]);if(g&&typeof p=="string"){let k=fe(p),h=me(p,g);if(k&&h)return qe(d,k,h)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return Je(d,p,a.semantic_type)})));return Ue(i)}catch{return}}o(Yt,"selectionExpression");function Ze(t,n,e,r={}){let i=t.result?.columns??[],s=new Map(i.map(m=>[m.name,m]));e?.forEach(m=>{let w=s.get(m);if(w){if(w.adhoc)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${m}\': it is a query-local AQL expression, which only this query\'s result carries. The target query would receive a condition naming a field it has never heard of.`,t.name);if(w.isMeasure)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${m}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new u(N(`Query \'${t.name}\' has no column \'${m}\' in its last result.`,m,[...s.keys()]),t.name)});let l=i.filter(m=>!m.isMeasure),a=l.filter(m=>!m.adhoc).map(m=>m.name),d=e?[...e]:a;if(!n.length||!d.length)return;let p=[],g=1,k=!e&&a.length!==l.length,h=!1;d.forEach(m=>{let w=s.get(m),_=Xe(w),F=Ht(_,r[_],n.map(E=>E[m]));p.push(F.condition),g*=F.admits,h=h||F.lossy});let f=new Set(n.map(m=>JSON.stringify(d.map(w=>m[w]??null))));g>f.size&&(h=!0);let y=p.sort((m,w)=>m.field.localeCompare(w.field)),b={source:t.name,rows:[...n],fields:d};if(h){let m=Yt(s,d,n,r);if(m)return{...b,conditions:[],expression:m,lossy:k}}return{...b,conditions:y,lossy:k||h}}o(Ze,"deriveSelection");var he=Object.freeze([]);function ge(t){return t instanceof Error&&t.name==="AbortError"}o(ge,"isAbort");function et(t,n){return t.controller!==n}o(et,"superseded");function Wt(t){return{name:t.name,message:t.message,...t.entity?{entity:t.entity}:{},...typeof t.status=="number"?{status:t.status}:{},...t.stack?{stack:t.stack}:{}}}o(Wt,"inspectError");function Xt(t){let{result:n}=t;return{state:t.state,isDirty:t.isDirty,page:t.page,hasMore:t.hasMore,columns:n?n.columns.map(e=>({...e})):[],rowCount:n?.meta.numRows??0,selectedRowCount:t.selectedRows.length,signature:t.signature(),...t.error?{error:Wt(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}o(Xt,"inspectQuery");function Zt(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}o(Zt,"inspectControl");function tt(t){return{source:t.source,fields:[...t.fields],rowCount:t.rows.length,conditions:t.conditions.map(n=>({...n})),...t.expression?{expression:t.expression}:{},lossy:t.lossy}}o(tt,"inspectSelection");function nt(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}o(nt,"selectionKey");function rt(t,n){return t instanceof S?t:new R(t?.message??"The query failed.",n,t)}o(rt,"toDataAppError");function en(t,n){if(t instanceof S&&t.entity)return t;let e=t?.message||"The export failed.";return t instanceof D?new D(e,n):t instanceof C?new C(e,t.status,n):t instanceof u?new u(e,n):new R(e,n,t)}o(en,"toExportError");var ye=class ye extends ${constructor(e,r,i,s,l){super();c(this,"extensions",l);c(this,"title");c(this,"_timezone");c(this,"datasets");c(this,"backend");c(this,"features");c(this,"_queries",new Map);c(this,"_controls",new Map);c(this,"_mappings",[]);c(this,"_crossFilters",[]);c(this,"_selection");c(this,"_appliedSelection");c(this,"selectionCommitted",!1);c(this,"index",0);this.title=e.title,this._timezone=e.timezone,this.datasets=r,this.backend=i,this.features=s}get queries(){return Object.fromEntries(this._queries)}get controls(){return Object.fromEntries(this._controls)}get mappings(){return[...this._mappings,...this._crossFilters]}get crossFilters(){return this._crossFilters}createQuery(e,r){this.assertNameFree(e,"query");let i=j(new O(e,this,r),this.extensions?.query);return this._queries.set(e,i),this.notify(),i}createFilter(e,r){this.assertNameFree(e,"filter");let i=r.dataset?this.datasetIndex(r.dataset,e):this.soleDataset(e,r.field),s=j(new P(e,this,r,i,this.backend),this.extensions?.control);return this._controls.set(e,s),this.notify(),s}createDateDrill(e,r={}){if(this.features?.dateDrill===!1)throw new u(`Date drill \'${e}\' needs a capability this workspace has not enabled. Ask an admin to turn on \\`interactive_control:date_drill\\`.`,e);this.assertNameFree(e,"date drill control");let i=j(new z(e,this,r),this.extensions?.control);return this._controls.set(e,i),this.notify(),i}mapControl(e,r,i){if(!(e instanceof T))throw new u("mapControl expects a control as its source. To let one query cross-filter another, use app.mapCrossFilter(from, to) \\u2014 a cross-filter edge names no field.");if(this._controls.get(e.name)!==e)throw new u(`Control \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);i.aggregation&&Pe(i.aggregation,e.name);let s=new J(e,r,i.field,i.aggregation);if(this._mappings.some(l=>l.id===s.id))throw new u(`Mapping \'${s.id}\' is already declared.`,e.name);return this.assertAcyclic(s),this._mappings.push(s),this.notify(),s}mapCrossFilter(e,r){if(!(e instanceof O)||!(r instanceof O))throw new u("mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field }).");if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);if(e===r)throw new u(`Query \'${e.name}\' cannot cross-filter itself. A source keeps its own rows so it can show what is selected; filtering it would erase the very rows the reader clicked.`,e.name);if(e.declaration.dataset!==r.declaration.dataset)throw new u(`Cross-filter \'${e.name}\' -> \'${r.name}\' spans two datasets (\'${e.declaration.dataset}\' and \'${r.declaration.dataset}\'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,e.name);let i=new q(e,r);if(this._crossFilters.some(s=>s.id===i.id))throw new u(`Cross-filter \'${i.id}\' is already declared.`,e.name);return this._crossFilters.push(i),this.notify(),i}get selection(){return this._selection}get appliedSelection(){return this._appliedSelection}clearSelection(){this._selection&&(this._selection=void 0,this.notify())}setTimezone(e){this._timezone=e,this.notify()}get timezone(){return this._timezone}datasetIndex(e,r){return Le(this.datasets,e,r)}mappingsTo(e){return this._mappings.filter(r=>r.to.name===e)}selectionExpressionFor(e,r){return this.selectionFor(e,r)?.expression}selectionFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?void 0:this._crossFilters.some(l=>l.from.name===i.source&&l.to.name===e)?i:void 0}selectionConditionsFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?he:this._crossFilters.some(l=>l.from.name===i.source&&l.to.name===e)?i.conditions:he}drillTransformations(e){let r={};return this._mappings.forEach(i=>{if(i.to!==e)return;let s=i.from.appliedCondition;if(s?.operator!=="transform_date_drill")return;let[l]=s.values??[];typeof l=="string"&&(r[i.field]=l)}),r}select(e,r,i){if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);let s=Ze(e,r,i,this.drillTransformations(e));s?.lossy&&console.warn(`[anfra-sdk] The selection in \'${e.name}\' filters more broadly than it was made. Its conditions are combined field by field and ANDed, which cannot express "(A and B) or (C and D)", so the targets will also show combinations that were not selected. Select within one dimension, or narrow with \\`fields\\`, to avoid this.`),this._selection=s,this.notify()}get hasChanges(){return[...this._controls.values()].some(e=>e.isDirty)||this.isSelectionDirty}get isSelectionDirty(){return this.selectionCommitted?nt(this._selection)!==nt(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(a=>a.shouldRun(e.force));this._controls.forEach(a=>a.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(a=>{a.controller?.abort(),a.resetPage()});let i={backend:this.backend,timezone:this._timezone,bustCache:e.bustCache},s=[],l=[];return await Promise.all(r.map(async a=>{let d=new AbortController;a.controller=d;let p=a.signature();a.markExecuting();try{let g=await ue(a,this.mappingsTo(a.name),{conditions:this.selectionConditionsFor(a.name,"applied"),expression:this.selectionExpressionFor(a.name,"applied")},i,d.signal);if(et(a,d))return;a.markSuccess(g,p,!1),s.push(a.name)}catch(g){if(et(a,d)||ge(g))return;a.markError(rt(g,a.name)),l.push(a.name)}finally{a.controller===d&&(a.controller=void 0)}})),{succeeded:s,failed:l}}async refresh(){return this.execute({force:!0,bustCache:!0})}abort(){this._queries.forEach(e=>e.abort())}async fetchPage(e){let r=new AbortController;e.controller=r;let i=e.signature();e.markExecuting();try{let s=await ue(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone},r.signal);e.markSuccess(s,i,!0)}catch(s){if(e.rewindPage(),ge(s))return;let l=rt(s,e.name);throw e.markError(l),l}finally{e.controller===r&&(e.controller=void 0)}}async exportQuery(e,r,i){let s=je(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone,title:this.title},r);try{return await i(s,r.signal??new AbortController().signal)}catch(l){throw ge(l)?l:en(l,e.name)}}toJSON(){let e=o(r=>Object.fromEntries([...this._controls.entries()].filter(([,i])=>i.kind===r).map(([i,s])=>[i,s.toJSON()])),"byKind");return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},queries:Object.fromEntries([...this._queries.entries()].map(([r,i])=>[r,i.toJSON()])),filters:e("filter"),dateDrills:e("dateDrill"),mappings:[...this._mappings.map(r=>r.toJSON()),...this._crossFilters.map(r=>r.toJSON())]}}toInspectJSON(){return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},hasChanges:this.hasChanges,declaration:this.toJSON(),queries:Object.fromEntries([...this._queries.entries()].map(([e,r])=>[e,Xt(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,Zt(r)])),...this._selection?{selection:tt(this._selection)}:{},...this._appliedSelection?{appliedSelection:tt(this._appliedSelection)}:{}}}locate(e,r){let i=globalThis.document;if(!i)return!1;let s=Oe(i,e,this.index,r);return s.length?(Ie(s[0]),V(i).flash(s,{kind:e,name:r,...s.length>1?{note:`in ${s.length} places`}:{}}),!0):!1}assertNameFree(e,r){ze([...this._queries.keys(),...this._controls.keys()],e,r)}soleDataset(e,r){if(!r)return;let i=Object.keys(this.datasets);if(i.length===1)return this.datasets[i[0]];throw new u(i.length?`Filter \'${e}\' names a field but the environment has ${i.length} datasets. Say which one: ${i.join(", ")}.`:`Filter \'${e}\' names a field but the environment has no datasets.`,e)}assertAcyclic(e){let r=[...this._mappings,e],i=new Map;r.forEach(d=>{let p=d.from.name;i.set(p,[...i.get(p)??[],d.to.name])});let s=new Set,l=new Set,a=o(d=>{if(s.has(d))return!0;if(l.has(d))return!1;s.add(d);let p=(i.get(d)??[]).some(a);return s.delete(d),l.add(d),p},"walk");if([...i.keys()].some(a))throw new u(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};o(ye,"App");var K=ye;var it="0.11.0";var xe=class xe{constructor(n){c(this,"list");this.list=Object.freeze(n.map(({name:e,version:r})=>Object.freeze({name:e,version:r})))}has(n){return this.list.some(e=>e.name===n)}version(n){return this.list.find(e=>e.name===n)?.version}};o(xe,"InstalledPlugins");var be=xe,nn=it,Ee=class Ee{constructor(n){c(this,"version",nn);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"plugins");c(this,"features");c(this,"extensions",{query:new Map,control:new Map});if(!n?.datasets)throw new u("No datasets provided. The host must call createSdk({ datasets }) before an app can be declared.");if(!n.user)throw new u("No user provided. The host must call createSdk({ user }) before an app can be declared.");if(!n.backend)throw new u("No backend provided. The host must call createSdk({ backend }) before an app can run a query.");this.datasets=Object.freeze({...n.datasets}),this.user=Object.freeze({...n.user,permissions:Object.freeze({...n.user.permissions})}),this.indices=Object.fromEntries(Object.entries(n.datasets).map(([e,r])=>[e,new G(r)])),this.backend=n.backend,this.features=Object.freeze({...n.features}),this.plugins=new be(n.plugins??[])}createApp(n={}){let e=new K(n,this.indices,this.backend,this.features,this.extensions);return e.index=this._apps.length,this._apps.push(e),e}get apps(){return this._apps}};o(Ee,"Sdk");var we=Ee;function ot(t){return new we(t)}o(ot,"createSdk");var B="Anfra";function st(t,n=globalThis){let e=n[B],r=B in n;return n[B]=t,()=>{r?n[B]=e:delete n[B]}}o(st,"installSandbox");function at(t,n=[]){let e=t.document.getElementById(Se);if(!e?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let r=JSON.parse(e.textContent),i=o(f=>t.parent.postMessage(f,r.hostOrigin),"post"),s=new Map,l=new Map,a=Ae(i,{answer:o(async(f,y,b)=>{let m=s.get(f);if(!m)throw new C(`Nothing in this frame answers \'${f}\'.`);return m(y,b)},"answer"),event:o((f,y)=>{l.get(f)?.forEach(b=>{try{b(y)}catch{}})},"event")});t.addEventListener("message",f=>{f.source===t.parent&&a.receive(f.data)});let d={submitQuery:o((f,y)=>a.call("core.submitQuery",f,y).then(b=>(b.debug?.executedAt&&(b.debug.executedAt=new Date(b.debug.executedAt)),b)),"submitQuery"),fieldSuggestions:o((f,y)=>a.call("core.fieldSuggestions",f,y),"fieldSuggestions")},p=ot({datasets:r.datasets,user:r.user,backend:d,plugins:r.plugins??[]}),g=new Set,k=p.createApp.bind(p);p.createApp=f=>{let y=k(f);return g.forEach(b=>{try{b(y)}catch{}}),y};let h={window:t,sdk:p,endpoint:a,handlers:s,listeners:l,appListeners:g};for(let[f,y]of n)if(typeof y=="function")try{y(Be(f,h,{Query:O,Control:T}))}catch(b){t.console?.error(`anfra: plugin \'${f}\' failed to set up:`,b)}st(p,t),i({type:"anfra:ready"})}o(at,"bootstrap");return ht(rn);})();\n';
19
+ var anfra_sdk_frame_script_default = '"use strict";var __anfraKernel=(()=>{var M=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var pt=Object.prototype.hasOwnProperty;var ut=(t,n,e)=>n in t?M(t,n,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[n]=e;var o=(t,n)=>M(t,"name",{value:n,configurable:!0});var ft=(t,n)=>{for(var e in n)M(t,e,{get:n[e],enumerable:!0})},mt=(t,n,e,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of ct(n))!pt.call(t,i)&&i!==e&&M(t,i,{get:()=>n[i],enumerable:!(r=dt(n,i))||r.enumerable});return t};var ht=t=>mt(M({},"__esModule",{value:!0}),t);var c=(t,n,e)=>ut(t,typeof n!="symbol"?n+"":n,e);var rn={};ft(rn,{bootstrap:()=>at});var Se="anfra-provision";var U=class U extends Error{constructor(e,r){super(e);c(this,"entity");this.name=new.target.name,this.entity=r,Object.setPrototypeOf(this,new.target.prototype)}};o(U,"DataAppError");var S=U,H=class H extends S{};o(H,"ValidationError");var u=H,Y=class Y extends S{constructor(e,r,i){super(e,r);c(this,"cause");this.cause=i}};o(Y,"QueryError");var D=Y,W=class W extends S{};o(W,"PermissionError");var R=W,X=class X extends S{constructor(e,r,i){super(e,i);c(this,"status");this.status=r}};o(X,"TransportError");var C=X;function Ce(){let t=new Error("Aborted");return t.name="AbortError",t}o(Ce,"abortError");function gt(t){return t?.name==="AbortError"}o(gt,"isAbortError");var yt=new Set(["ValidationError","QueryError","PermissionError","TransportError"]);function bt(t){let n=t;return n instanceof Error&&yt.has(n.name)?{name:n.name,message:n.message||"The call failed."}:{name:"QueryError",message:"The call failed."}}o(bt,"toBridgeError");function wt(t){switch(t?.name){case"PermissionError":return new R(t.message);case"TransportError":return new C(t.message);case"ValidationError":return new u(t.message);default:return new D(t?.message||"The call failed.")}}o(wt,"fromBridgeError");function Ae(t,n){let e=new Map,r=new Map,i=1,s=o((l,a,d)=>{let p=new AbortController;r.set(l,p),Promise.resolve().then(()=>n.answer(a,d,p.signal)).then(g=>{p.signal.aborted||t({type:"anfra:result",id:l,ok:!0,result:g})}).catch(g=>{p.signal.aborted||gt(g)||t({type:"anfra:result",id:l,ok:!1,error:bt(g)})}).finally(()=>{r.get(l)===p&&r.delete(l)})},"answer");return{call(l,a,d){return new Promise((p,g)=>{if(d?.aborted){g(Ce());return}let E=i++;e.set(E,{resolve:p,reject:g}),d?.addEventListener("abort",()=>{e.delete(E)&&(t({type:"anfra:cancel",id:E}),g(Ce()))},{once:!0}),t({type:"anfra:call",id:E,name:l,request:a})})},emit(l,a){t({type:"anfra:event",name:l,payload:a})},receive(l){switch(l?.type){case"anfra:call":return s(l.id,l.name,l.request),!0;case"anfra:result":{let a=e.get(l.id);return a&&(e.delete(l.id),l.ok?a.resolve(l.result):a.reject(wt(l.error))),!0}case"anfra:cancel":return r.get(l.id)?.abort(),r.delete(l.id),!0;case"anfra:event":return n.event(l.name,l.payload),!0;default:return!1}},close(l){r.forEach(a=>a.abort()),r.clear(),e.forEach(({reject:a})=>a(l)),e.clear()}}}o(Ae,"createEndpoint");var Z=class Z{constructor(n){c(this,"listeners",new Set);c(this,"parent");this.parent=n}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}notifyChange(){this.listeners.forEach(n=>n()),this.parent?.notifyChange()}notify(){this.notifyChange()}};o(Z,"Observable");var $=Z;var De=["year","quarter","month","week","day","hour","minute"];function xt(t,n){if(!De.includes(n))throw new u(`Invalid grain \'${n}\'. Expected one of: ${De.join(", ")}.`,t)}o(xt,"assertGrain");function Re(t,n){return n?(xt(t,n),{operator:"transform_date_drill",values:[`datetrunc ${n}`]}):{operator:"none"}}o(Re,"drillCondition");function kt(t){let n=t.toLowerCase();return n.includes("date")||n.includes("time")?"date":n.includes("int")||n.includes("number")||n.includes("float")||n.includes("decimal")?"number":n.includes("bool")?"boolean":"string"}o(kt,"inferType");function Et(t,n){return JSON.stringify(t??null)===JSON.stringify(n??null)}o(Et,"sameCondition");var ee=class ee extends ${constructor(e,r,i){super(r);c(this,"name");c(this,"app");c(this,"pending");c(this,"applied");c(this,"initial");this.name=e,this.app=r,this.initial=i,this.pending=i}locate(){return this.app.locate("control",this.name)}get condition(){return this.pending}get appliedCondition(){return this.applied}get isDirty(){return this.applied!==void 0&&!Et(this.pending,this.applied)}setCondition(e){this.pending=e,this.notify()}reset(){this.setCondition(this.initial)}commit(){this.applied=this.pending}};o(ee,"Control");var T=ee,te=class te extends T{constructor(e,r,i,s,l){super(e,r,i.default??{operator:"is",values:[]});c(this,"kind","filter");c(this,"declaration");c(this,"type");c(this,"resolved");c(this,"datasetName");c(this,"backend");c(this,"loadedOptions");if(this.declaration=i,this.backend=l,i.field){if(!s)throw new u(`Filter \'${e}\' names a field but no dataset. Pass \\`dataset\\` alongside \\`field\\`.`,e);this.resolved=s.resolve(i.field,e),this.datasetName=s.descriptor.name,this.type=i.type??kt(this.resolved.type)}else{if(!i.type)throw new u(`Filter \'${e}\' is a manual filter, so it needs a \\`type\\`.`,e);this.type=i.type}this.assertValues(this.condition.values??[]),this.assertValues(i.options??[])}setCondition(e){this.assertValues(e.values??[]),super.setCondition(e)}assertValues(e){if(this.type!=="number")return;let r=e.find(i=>typeof i=="number");if(r!==void 0)throw new u(`Filter \'${this.name}\' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(r))}, not ${String(r)}), so none has lost a digit.`,this.name)}get isFieldBacked(){return this.resolved!==void 0}get options(){return this.loadedOptions??this.declaration.options??[]}async loadOptions(e,r=new AbortController().signal){let i=this.resolved?.modelName;if(!this.resolved||!i||!this.backend||!this.datasetName)return this.options;let s=await this.backend.fieldSuggestions({dataset:this.datasetName,model:i,field:this.resolved.fieldName,q:e??""},r);return this.loadedOptions=[...s??[]],this.notify(),this.loadedOptions}toJSON(){return this.declaration}};o(te,"Filter");var P=te,ne=class ne extends T{constructor(e,r,i={}){super(e,r,Re(e,i.default));c(this,"kind","dateDrill");c(this,"declaration");this.declaration=i}setGrain(e){this.setCondition(Re(this.name,e))}toJSON(){return this.declaration}};o(ne,"DateDrillControl");var z=ne;var v={container:"data-anfra-container",block:"data-anfra-block",query:"data-anfra-query",control:"data-anfra-control",label:"data-anfra-label"},_e=`[${v.container}],[${v.block}],[${v.query}],[${v.control}]`;function $e(t){let n=/^(?:(\\d+)\\/)?([^/\\s]+)$/.exec(t);if(n)return{app:n[1]===void 0?0:Number(n[1]),name:n[2]}}o($e,"parseRef");var Te=o(t=>(t??"").split(/\\s+/).filter(Boolean),"tokens");function Oe(t,n,e,r){let i=n==="query"?v.query:v.control;return[...t.querySelectorAll(`[${i}]`)].filter(s=>Te(s.getAttribute(i)).some(l=>{let a=$e(l);return a?.app===e&&a.name===r}))}o(Oe,"markersFor");var vt=o((t,n,e)=>{let r=t[e.app];return r?Object.prototype.hasOwnProperty.call(n==="query"?r.queries:r.controls,e.name):!1},"hasEntity");function Fe(t,n){var E;let e=[],r=new Map,i=new Map,s=new Map,l=new Map,a={container:new Set,block:new Set},d={},p=o((h,f,y)=>{let b=h?s.get(h).children:e,m=h?`${s.get(h).key}.`:"",w={...f,key:`${m}${b.length}`,children:[]};return b.push(w),r.set(w.key,y),i.set(y,[...i.get(y)??[],w.key]),w},"place");for(let h of t.querySelectorAll(_e)){let f=h.parentElement?.closest(_e)??null,y=h.getAttribute(v.container),b=h.getAttribute(v.block),m=h.getAttribute(v.label)??void 0,w=f&&(l.get(f)==="block"?f:f.closest(`[${v.block}]`)),_;if(y!==null||b!==null){let k=y!==null?"container":"block",A=(y??b??"").trim(),x=[];y!==null&&b!==null&&x.push("This element is marked as a container and as a block. It counts as a container."),A?a[k].has(A)?x.push(`Another ${k} already has the id "${A}".`):a[k].add(A):x.push(`This ${k} has no id.`),w&&x.push(`A block can\'t hold a ${k}. This one is inside the block "${w.getAttribute(v.block)}".`),_=p(f,{kind:k,id:A,...m!==void 0?{label:m}:{},problems:x},h),s.set(h,_),l.set(h,k)}let N=_?h:f;for(let k of["query","control"])for(let A of Te(h.getAttribute(k==="query"?v.query:v.control))){let x=$e(A),L=[];if(x?vt(n,k,x)||L.push(n[x.app]?`No ${k} is called "${x.name}" in app ${x.app}.`:`The page has no app ${x.app}.`):L.push(`Can\'t read "${A}". Write the ${k}\'s name, or app/name when the page has several apps.`),p(N,{kind:k,name:x?.name??A,app:x?.app??0,problems:L},h),x&&!L.length){let lt=`${x.app}/${x.name}`,Ee=d[E=`${k}:${lt}`]??(d[E]={elements:new Set,blocks:new Set});Ee.elements.add(h);let ve=_?.kind==="block"?_.id:w?.getAttribute(v.block);ve&&Ee.blocks.add(ve)}}}let g=Object.fromEntries(Object.entries(d).map(([h,f])=>[h,{markers:f.elements.size,blocks:[...f.blocks]}]));return{nodes:e,usage:g,elements:r,keysOf:i}}o(Fe,"buildStructure");var Ne="data-anfra-layer",St="position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";function Ct(t){let n=t.querySelector(`[${Ne}]`);if(n instanceof(t.defaultView?.HTMLElement??HTMLElement))return n;let e=t.createElement("div");return e.setAttribute(Ne,""),e.setAttribute("style",St),(t.body??t.documentElement).appendChild(e),e}o(Ct,"layerOf");function Q(t,n){let e=Ct(t),r=[...e.children].find(s=>s.getAttribute("data-part")===n);if(r?.shadowRoot)return r.shadowRoot;let i=t.createElement("div");return i.setAttribute("data-part",n),e.appendChild(i),i.attachShadow({mode:"open"})}o(Q,"layerRoot");var Me="anfra-overlay",At=1500,Dt="position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;",Rt="position:fixed;max-width:60vw;display:flex;gap:6px;align-items:baseline;padding:3px 8px;border-radius:4px;background:#0f172a;color:#f8fafc;font:12px/1.4 system-ui,sans-serif;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,0.35);",_t={kind:"color:#94a3b8;",name:"color:#93c5fd;font-weight:700;",label:"color:#f8fafc;",note:"color:#94a3b8;",size:"color:#94a3b8;margin-left:10px;"},ie=class ie{constructor(n){c(this,"doc",n);c(this,"root");c(this,"shown",[]);c(this,"text",{kind:"",name:""});c(this,"timer");c(this,"reposition",o(()=>this.draw(),"reposition"));let e=Q(n,"anfra"),r=e.getElementById(Me);r instanceof(n.defaultView?.HTMLElement??HTMLElement)?this.root=r:(this.root=n.createElement("div"),this.root.id=Me,this.root.setAttribute("aria-hidden","true"),this.root.setAttribute("style","position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;"),e.appendChild(this.root))}show(n,e){if(this.clearTimer(),this.root.isConnected||Q(this.doc,"anfra").appendChild(this.root),this.shown=[...n],this.text=e,!this.shown.length){this.hide();return}this.root.style.display="block",this.draw(),this.doc.addEventListener("scroll",this.reposition,{capture:!0,passive:!0}),this.doc.defaultView?.addEventListener("resize",this.reposition)}flash(n,e,r=At){this.show(n,e),this.timer=setTimeout(()=>this.hide(),r)}hide(){this.clearTimer(),this.shown=[],this.root.style.display="none",this.root.replaceChildren(),this.doc.removeEventListener("scroll",this.reposition,{capture:!0}),this.doc.defaultView?.removeEventListener("resize",this.reposition)}get visible(){return this.shown.length>0}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}draw(){let n=this.shown.map(a=>{let d=a.getBoundingClientRect(),p=this.doc.createElement("div");return p.setAttribute("style",`${Dt}left:${d.left}px;top:${d.top}px;width:${d.width}px;height:${d.height}px;`),p}),e=this.shown[0].getBoundingClientRect(),r=this.doc.createElement("div");r.setAttribute("data-testid","anfra-overlay-label");let i=this.doc.defaultView?.innerHeight??0,s=e.top>=26?e.top-24:Math.max(4,e.top+4),l=Math.max(4,Math.min(e.left,(this.doc.defaultView?.innerWidth??0)-24));r.setAttribute("style",`${Rt}left:${l}px;top:${Math.min(s,i-24)}px;`);for(let a of["kind","name","label","note","size"]){let d=this.text[a];if(!d)continue;let p=this.doc.createElement("span");p.setAttribute("style",_t[a]),p.setAttribute("data-part",a),p.textContent=d,r.appendChild(p)}this.root.replaceChildren(...n,r)}};o(ie,"Overlay");var re=ie,Qe=new WeakMap;function V(t){let n=Qe.get(t);return n||(n=new re(t),Qe.set(t,n)),n}o(V,"overlayFor");function Ie(t){typeof t.scrollIntoView=="function"&&t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}o(Ie,"scrollTo");function oe(t,n,e,r,i){if(r in n||t.has(r))throw new u(`Plugin \'${r}\' can\'t add \'${r}\' to a ${e}: it already has one.`);t.set(r,i)}o(oe,"addExtension");function j(t,n){return n?.forEach((e,r)=>{let i=!1,s;Object.defineProperty(t,r,{configurable:!0,enumerable:!1,get(){return i||(s=e(t),i=!0),s}})}),t}o(j,"applyExtensions");var $t="anfra.body",se="__anfraBodyExports",Tt={DataAppError:S,ValidationError:u,QueryError:D,PermissionError:R,TransportError:C};function Ot(t,n){let e=t,r=t.document.createElement("script");r.textContent=`(function () { var __anfraBody;\n${n}\n;self[${JSON.stringify(se)}] = __anfraBody; })();`,(t.document.head??t.document.documentElement).appendChild(r),r.remove();let i=e[se];if(delete e[se],!i)throw new u("The host sent a plugin body that did not run.");return i.default??i}o(Ot,"runBody");function Be(t,n,e){let{window:r,sdk:i,endpoint:s}=n,l;return{plugin:t,window:r,sdk:i,errors:Tt,get overlay(){return V(r.document)},structure:o(()=>Fe(r.document,i.apps),"structure"),call:o((a,d,p)=>s.call(a,d??null,p),"call"),emit:o((a,d)=>s.emit(`${t}.${a}`,d??null),"emit"),handle(a,d){n.handlers.set(`${t}.${a}`,d)},on(a,d){let p=`${t}.${a}`;n.listeners.has(p)||n.listeners.set(p,new Set),n.listeners.get(p).add(d)},onApp(a){n.appListeners.add(a),i.apps.forEach(d=>a(d))},provide(a){if(t in i)throw new u(`Plugin \'${t}\' can\'t add a member Anfra already has.`);Object.defineProperty(i,t,{value:a,enumerable:!0})},provideOnQuery:o(a=>oe(i.extensions.query,e.Query.prototype,"query",t,a),"provideOnQuery"),provideOnControl:o(a=>oe(i.extensions.control,e.Control.prototype,"control",t,a),"provideOnControl"),layer:o(()=>Q(r.document,t),"layer"),body(){return l??(l=s.call($t,{plugin:t}).then(a=>Ot(r,a)).catch(a=>{throw l=void 0,a})),l}}}o(Be,"createKernel");var ae=class ae extends ${constructor(e,r,i){super(r);c(this,"kind","query");c(this,"name");c(this,"declaration");c(this,"dataset");c(this,"app");c(this,"_state","idle");c(this,"_result");c(this,"_error");c(this,"_page",1);c(this,"_sort",[]);c(this,"lastRunSignature");c(this,"lastPageRows",0);c(this,"controller");if(!i.aql?.trim())throw new u(`Query \'${e}\' declares no AQL.`,e);let{pageSize:s}=i;if(s!==void 0&&!(Number.isInteger(s)&&s>=1))throw new u(`Query \'${e}\' declares pageSize ${s}; it must be a whole number of at least 1.`,e);this.name=e,this.app=r,this.declaration=i,this.dataset=r.datasetIndex(i.dataset,e)}locate(){return this.app.locate("query",this.name)}get state(){return this._state}get result(){return this._result}get error(){return this._error}get pageSize(){return this.declaration.pageSize}get page(){return this._page}get sort(){return this._sort}setSort(e){this._sort=[...e],this.notify()}get hasMore(){return!this._result||this.pageSize===void 0?!1:this._result.meta.hasMore??this.lastPageRows>=this.pageSize}signature(){let e=this.app.mappingsTo(this.name).map(r=>({field:r.field,aggregation:r.aggregation,condition:r.from.condition})).sort((r,i)=>r.field.localeCompare(i.field)||JSON.stringify(r).localeCompare(JSON.stringify(i)));return JSON.stringify({declaration:this.declaration,conditions:e,selection:this.app.selectionConditionsFor(this.name,"pending"),selectionExpression:this.app.selectionExpressionFor(this.name,"pending"),sort:this._sort,timezone:this.app.timezone,page:this._page})}get isDirty(){return this.lastRunSignature!==void 0&&this.signature()!==this.lastRunSignature}shouldRun(e=!1){return e||this.lastRunSignature===void 0||this.isDirty}abort(){this.controller?.abort()}async fetchMore(){if(this.pageSize===void 0)throw new u(`Query \'${this.name}\' declares no pageSize, so it has no more pages.`,this.name);this.hasMore&&(this._page+=1,await this.app.fetchPage(this))}select(e,r={}){this.app.select(this,Array.isArray(e)?e:[e],r.fields)}get selectedRows(){let{selection:e}=this.app;if(e?.source!==this.name)return[];let r=this._result?.rows;if(!r)return e.rows;let i=o(l=>JSON.stringify(e.fields.map(a=>l[a]??null)),"key"),s=new Set(e.rows.map(i));return r.filter(l=>s.has(i(l)))}markExecuting(){this._state="executing",this._error=void 0,this.notify()}markSuccess(e,r,i){if(this._state="success",this._error=void 0,this.lastRunSignature=r,this.lastPageRows=e.rows.length,i&&this._result){let s=[...this._result.rows,...e.rows];this._result={...e,rows:s,meta:{...e.meta,numRows:s.length}}}else this._result=e;this.notify()}markError(e){this._state="error",this._error=e,this.notify()}rewindPage(){this._page>1&&(this._page-=1)}resetPage(){this._page=1,this.lastPageRows=0}toJSON(){return this.declaration}};o(ae,"Query");var O=ae;var le=class le{constructor(n,e,r,i){c(this,"kind","control");c(this,"from");c(this,"to");c(this,"field");c(this,"aggregation");this.from=n,this.to=e,this.field=r,this.aggregation=i}get id(){return`${this.from.name}.${this.to.name}.${this.field}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:this.from.kind,name:this.from.name},to:{kind:"query",name:this.to.name},field:this.field,...this.aggregation?{aggregation:this.aggregation}:{}}}};o(le,"Mapping");var J=le,de=class de{constructor(n,e){c(this,"kind","crossFilter");c(this,"from");c(this,"to");this.from=n,this.to=e}get id(){return`${this.from.name}.${this.to.name}`}toJSON(){return{kind:this.kind,id:this.id,from:{kind:"query",name:this.from.name},to:{kind:"query",name:this.to.name}}}};o(de,"CrossFilter");var q=de;var ce=["sum","avg","max","min","count","count distinct","median","stdev","stdevp","var","varp"];function Ft(t,n){let e=t.length+1,r=n.length+1,i=Array.from({length:r},(s,l)=>l);for(let s=1;s<e;s++){let l=[s];for(let a=1;a<r;a++)l[a]=Math.min(i[a]+1,l[a-1]+1,i[a-1]+(t[s-1]===n[a-1]?0:1));i=l}return i[r-1]}o(Ft,"editDistance");function Nt(t,n){let e,r=1/0;n.forEach(s=>{let l=Ft(t.toLowerCase(),s.toLowerCase());l<r&&(r=l,e=s)});let i=Math.max(2,Math.floor(t.length/3));return r<=i?e:void 0}o(Nt,"suggest");function F(t,n,e){let r=Nt(n,e);return r?`${t} Did you mean \'${r}\'?`:t}o(F,"withSuggestion");var pe=class pe{constructor(n){c(this,"descriptor");c(this,"fields",new Map);c(this,"references");this.descriptor=n,n.data_models.forEach(e=>{e.fields.forEach(r=>{let i=String(e.name);this.fields.set(`${i}.${r.name}`,{modelName:i,fieldName:r.name,isMetric:!1,type:r.type,label:r.label??r.name})})}),n.metrics.forEach(e=>{this.fields.set(e.name,{fieldName:e.name,isMetric:!0,type:e.type,label:e.label??e.name})}),this.references=[...this.fields.keys()]}resolve(n,e){let r=this.fields.get(n);if(r)return r;throw new u(F(`Unknown field \'${n}\' on dataset \'${this.descriptor.name}\'.`,n,this.references),e)}};o(pe,"DatasetIndex");var G=pe;function Le(t,n,e){let r=t[n];if(r)return r;throw new u(F(`Unknown dataset \'${n}\'.`,n,Object.keys(t)),e)}o(Le,"resolveDataset");function Pe(t,n){if(!ce.includes(t))throw new u(F(`Invalid filter aggregation \'${t}\'.`,t,[...ce]),n)}o(Pe,"assertValidFilterAggregation");function ze(t,n,e){if(!n)throw new u(`A ${e} needs a name.`);for(let r of t)if(r===n)throw new u(`\'${n}\' is already declared in this app.`,n)}o(ze,"assertUniqueName");function Mt(t,n){if(!(!n||n.operator==="none"||n.operator==="transform_date_drill"||!["is_null","not_null","is_true","is_false","transform_pop_none"].includes(n.operator)&&!n.values?.length))return{field:t.field,operator:n.operator,values:n.values??[],...n.modifier?{modifier:n.modifier}:{},...t.aggregation?{aggregation:t.aggregation}:{}}}o(Mt,"toFilter");function Qt(t,n){if(n?.operator!=="transform_date_drill")return;let e=n.values?.[0];if(typeof e!="string")return;let r=e.replace(/^datetrunc\\s+/,"");return{field:t.field,grain:r}}o(Qt,"toDateDrill");function It(t,n){let e=n.columns??[],r=(n.values??[]).map(s=>{let l={};return e.forEach((a,d)=>{l[a.name]=s[d]}),l}),{pageSize:i}=t;return{columns:e,rows:r,meta:{...i!==void 0?{page:n.meta?.page??t.page,pageSize:n.meta?.pageSize??i,...n.meta?.hasMore!==void 0?{hasMore:n.meta.hasMore}:{}}:{},numRows:n.meta?.numRows??r.length},...n.debug?{debug:n.debug}:{}}}o(It,"toResult");function Ve(t,n,e,r){let i=n.map(d=>Mt(d,d.from.appliedCondition)).filter(d=>d!==void 0),s=n.map(d=>Qt(d,d.from.appliedCondition)).filter(d=>d!==void 0),l=e.conditions.map(d=>({field:d.field,operator:d.operator,values:d.values})),a=e.expression?[{expr:e.expression}]:[];return{dataset:t.dataset.descriptor.name,aql:t.declaration.aql,input:{filters:[...i,...l],conditions:a,sorts:t.sort.map(d=>({field:d.field,direction:d.direction??"asc"})),dateDrills:s},...r.timezone?{timezone:r.timezone}:{}}}o(Ve,"buildQuery");function Bt(t,n,e,r){return{...Ve(t,n,e,r),...t.pageSize!==void 0?{page:t.page,pageSize:t.pageSize}:{},...r.bustCache?{bustCache:!0}:{}}}o(Bt,"buildRequest");function Lt(t,n){let e=n?.replace(/[/\\\\]/g,"-").replace(/\\p{Cc}/gu,"").trim();return e?`${e} - ${t.name}`:t.name}o(Lt,"defaultExportFilename");function je(t,n,e,r,i){let s=i.format??"csv",l=s==="csv"?{bom:!0,...i.formatOptions}:i.formatOptions;return{...Ve(t,n,e,r),format:s,...l?{formatOptions:l}:{},filename:i.filename?.trim()||Lt(t,r.title)}}o(je,"buildExportRequest");async function ue(t,n,e,r,i){let s=Bt(t,n,e,r),l=await r.backend.submitQuery(s,i);return It(t,l)}o(ue,"runQuery");function Pt(t,n){if(t===null)return"null";if(typeof t=="boolean")return t?"true":"false";if(n==="number"&&typeof t=="string")return jt(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new RangeError(`Cannot express ${t} in AQL.`);return Math.abs(t)>=1e21?BigInt(t).toString():String(t)}return JSON.stringify(t).split("\\u2028").join("\\\\u2028").split("\\u2029").join("\\\\u2029")}o(Pt,"literal");function Je(t,n,e){return n===null?`is(${t}, null)`:`${t} is ${Pt(n,e)}`}o(Je,"equals");var zt=new Set(["NaN","Infinity","-Infinity"]),Vt=/^(-?)(0|[1-9]\\d*)(?:\\.(\\d+))?(?:[eE]([+-]?\\d+))?$/;function jt(t){let n=Vt.exec(t);if(!n)throw zt.has(t)?new RangeError(`Cannot express ${t} in AQL.`):new TypeError(`${JSON.stringify(t)} is not a number: a number is a string in JSON\'s number syntax.`);let[,e,r,i="",s]=n;if(s===void 0)return t;let l=r+i,a=r.length+Number(s),d;return a<=0?d=`0.${"0".repeat(-a)}${l}`:a>=l.length?d=l+"0".repeat(a-l.length):d=`${l.slice(0,a)}.${l.slice(a)}`,e+d.replace(/^0+(?=\\d)/,"")}o(jt,"numberLiteral");function qe(t,n,e){return`${t} matches @(${n} until ${e})`}o(qe,"dateRange");function Ge(t,n){if(n.length===0)throw new RangeError(`\\`${t}\\` needs at least one operand.`);return n.length===1?n[0]:`${t}(${n.join(", ")})`}o(Ge,"combine");var Ke=o(t=>Ge("and",t),"and"),Ue=o(t=>Ge("or",t),"or");var Jt=/^(\\d{4})-(\\d{2})-(\\d{2})(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2}))?)?/,qt={week:7*864e5,day:864e5,hour:36e5,minute:6e4};function He(t){if(typeof t!="string")return;let n=Jt.exec(t);if(n)return{year:Number(n[1]),month:Number(n[2])-1,day:Number(n[3]),hour:Number(n[4]??0),minute:Number(n[5]??0),second:Number(n[6]??0),hasTime:n[4]!==void 0}}o(He,"parseStamp");function I(t,n){let e=new Date(t),r=o(s=>String(s).padStart(2,"0"),"pad"),i=`${e.getUTCFullYear()}-${r(e.getUTCMonth()+1)}-${r(e.getUTCDate())}`;return n?`${i} ${r(e.getUTCHours())}:${r(e.getUTCMinutes())}:${r(e.getUTCSeconds())}`:i}o(I,"format");function Ye(t){return Date.UTC(t.year,t.month,t.day,t.hour,t.minute,t.second)}o(Ye,"toMs");function fe(t){let n=He(t);if(n)return I(Ye(n),n.hasTime)}o(fe,"normalise");function me(t,n){let e=He(t);if(!e)return;let{year:r,month:i,day:s,hour:l,minute:a,second:d,hasTime:p}=e;return I(n==="year"?Date.UTC(r+1,i,s,l,a,d):n==="quarter"?Date.UTC(r,i+3,s,l,a,d):n==="month"?Date.UTC(r,i+1,s,l,a,d):Ye(e)+qt[n],p)}o(me,"addGrain");function We(t){if(t?.startsWith("datetrunc "))return t.slice(10)}o(We,"grainOf");function Gt(t){let n=new Set;return t.filter(e=>{let r=`${typeof e}:${String(e)}`;return n.has(r)?!1:(n.add(r),!0)})}o(Gt,"distinct");function Kt(t,n){let e=t.map(fe);if(e.some(i=>i===void 0))return!1;let r=e.slice().sort();for(let i=1;i<r.length;i+=1)if(me(r[i-1],n)!==r[i])return!1;return!0}o(Kt,"isContiguous");function Ut(t,n,e){let r=n.map(fe);if(r.some(d=>d===void 0))return;let i=r.slice().sort(),s=i[0],l=me(i[i.length-1],e);if(!l)return;let a=Kt(n,e);return{condition:{field:t,operator:"matches",values:[`${s} until ${l}`]},admits:a?n.length:Number.POSITIVE_INFINITY,lossy:!a}}o(Ut,"dateRange");function Ht(t,n,e){let r=e.filter(a=>a!=null),i=Gt(r);if(!i.length)return{condition:{field:t,operator:"is_null",values:[]},admits:1,lossy:!1};let s=r.length!==e.length,l=We(n);if(l){let a=Ut(t,i,l);if(a)return{...a,lossy:a.lossy||s}}return{condition:{field:t,operator:"is",values:i},admits:i.length,lossy:s}}o(Ht,"deriveOne");function Xe(t){return t.modelId?`${t.modelId}.${t.fieldName}`:t.fieldName}o(Xe,"fieldReferenceOf");function Yt(t,n,e,r){try{let i=e.map(s=>Ke(n.map(l=>{let a=t.get(l),d=Xe(a),p=s[l]??null,g=We(r[d]);if(g&&typeof p=="string"){let E=fe(p),h=me(p,g);if(E&&h)return qe(d,E,h)}if(p!==null&&typeof p!="string"&&typeof p!="number"&&typeof p!="boolean")throw new TypeError("no AQL spelling");return Je(d,p,a.semantic_type)})));return Ue(i)}catch{return}}o(Yt,"selectionExpression");function Ze(t,n,e,r={}){let i=t.result?.columns??[],s=new Map(i.map(m=>[m.name,m]));e?.forEach(m=>{let w=s.get(m);if(w){if(w.adhoc)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${m}\': it is a query-local AQL expression, which only this query\'s result carries. The target query would receive a condition naming a field it has never heard of.`,t.name);if(w.isMeasure)throw new u(`Query \'${t.name}\' cannot cross-filter on \'${m}\': it is a measure, and a selection conditions dimensions only.`,t.name);return}throw new u(F(`Query \'${t.name}\' has no column \'${m}\' in its last result.`,m,[...s.keys()]),t.name)});let l=i.filter(m=>!m.isMeasure),a=l.filter(m=>!m.adhoc).map(m=>m.name),d=e?[...e]:a;if(!n.length||!d.length)return;let p=[],g=1,E=!e&&a.length!==l.length,h=!1;d.forEach(m=>{let w=s.get(m),_=Xe(w),N=Ht(_,r[_],n.map(k=>k[m]));p.push(N.condition),g*=N.admits,h=h||N.lossy});let f=new Set(n.map(m=>JSON.stringify(d.map(w=>m[w]??null))));g>f.size&&(h=!0);let y=p.sort((m,w)=>m.field.localeCompare(w.field)),b={source:t.name,rows:[...n],fields:d};if(h){let m=Yt(s,d,n,r);if(m)return{...b,conditions:[],expression:m,lossy:E}}return{...b,conditions:y,lossy:E||h}}o(Ze,"deriveSelection");var he=Object.freeze([]);function ge(t){return t instanceof Error&&t.name==="AbortError"}o(ge,"isAbort");function et(t,n){return t.controller!==n}o(et,"superseded");function Wt(t){return{name:t.name,message:t.message,...t.entity?{entity:t.entity}:{},...typeof t.status=="number"?{status:t.status}:{},...t.stack?{stack:t.stack}:{}}}o(Wt,"inspectError");function Xt(t){let{result:n}=t;return{state:t.state,isDirty:t.isDirty,page:t.page,hasMore:t.hasMore,columns:n?n.columns.map(e=>({...e})):[],rowCount:n?.meta.numRows??0,selectedRowCount:t.selectedRows.length,signature:t.signature(),...t.error?{error:Wt(t.error)}:{},...n?.debug?{debug:{...n.debug}}:{}}}o(Xt,"inspectQuery");function Zt(t){let{options:n}=t;return{kind:t.kind,condition:{...t.condition},...t.appliedCondition?{appliedCondition:{...t.appliedCondition}}:{},isDirty:t.isDirty,...n?{options:[...n]}:{}}}o(Zt,"inspectControl");function tt(t){return{source:t.source,fields:[...t.fields],rowCount:t.rows.length,conditions:t.conditions.map(n=>({...n})),...t.expression?{expression:t.expression}:{},lossy:t.lossy}}o(tt,"inspectSelection");function nt(t){return t?JSON.stringify({source:t.source,conditions:t.conditions,expression:t.expression}):"none"}o(nt,"selectionKey");function rt(t,n){return t instanceof S?t:new D(t?.message??"The query failed.",n,t)}o(rt,"toDataAppError");function en(t,n){if(t instanceof S&&t.entity)return t;let e=t?.message||"The export failed.";return t instanceof R?new R(e,n):t instanceof C?new C(e,t.status,n):t instanceof u?new u(e,n):new D(e,n,t)}o(en,"toExportError");var ye=class ye extends ${constructor(e,r,i,s,l){super();c(this,"extensions",l);c(this,"title");c(this,"_timezone");c(this,"datasets");c(this,"backend");c(this,"features");c(this,"_queries",new Map);c(this,"_controls",new Map);c(this,"_mappings",[]);c(this,"_crossFilters",[]);c(this,"_selection");c(this,"_appliedSelection");c(this,"selectionCommitted",!1);c(this,"index",0);this.title=e.title,this._timezone=e.timezone,this.datasets=r,this.backend=i,this.features=s}get queries(){return Object.fromEntries(this._queries)}get controls(){return Object.fromEntries(this._controls)}get mappings(){return[...this._mappings,...this._crossFilters]}get crossFilters(){return this._crossFilters}createQuery(e,r){this.assertNameFree(e,"query");let i=j(new O(e,this,r),this.extensions?.query);return this._queries.set(e,i),this.notify(),i}createFilter(e,r){this.assertNameFree(e,"filter");let i=r.dataset?this.datasetIndex(r.dataset,e):this.soleDataset(e,r.field),s=j(new P(e,this,r,i,this.backend),this.extensions?.control);return this._controls.set(e,s),this.notify(),s}createDateDrill(e,r={}){if(this.features?.dateDrill===!1)throw new u(`Date drill \'${e}\' needs a capability this workspace has not enabled. Ask an admin to turn on \\`interactive_control:date_drill\\`.`,e);this.assertNameFree(e,"date drill control");let i=j(new z(e,this,r),this.extensions?.control);return this._controls.set(e,i),this.notify(),i}mapControl(e,r,i){if(!(e instanceof T))throw new u("mapControl expects a control as its source. To let one query cross-filter another, use app.mapCrossFilter(from, to) \\u2014 a cross-filter edge names no field.");if(this._controls.get(e.name)!==e)throw new u(`Control \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);i.aggregation&&Pe(i.aggregation,e.name);let s=new J(e,r,i.field,i.aggregation);if(this._mappings.some(l=>l.id===s.id))throw new u(`Mapping \'${s.id}\' is already declared.`,e.name);return this.assertAcyclic(s),this._mappings.push(s),this.notify(),s}mapCrossFilter(e,r){if(!(e instanceof O)||!(r instanceof O))throw new u("mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field }).");if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);if(this._queries.get(r.name)!==r)throw new u(`Query \'${r.name}\' belongs to a different app.`,r.name);if(e===r)throw new u(`Query \'${e.name}\' cannot cross-filter itself. A source keeps its own rows so it can show what is selected; filtering it would erase the very rows the reader clicked.`,e.name);if(e.declaration.dataset!==r.declaration.dataset)throw new u(`Cross-filter \'${e.name}\' -> \'${r.name}\' spans two datasets (\'${e.declaration.dataset}\' and \'${r.declaration.dataset}\'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,e.name);let i=new q(e,r);if(this._crossFilters.some(s=>s.id===i.id))throw new u(`Cross-filter \'${i.id}\' is already declared.`,e.name);return this._crossFilters.push(i),this.notify(),i}get selection(){return this._selection}get appliedSelection(){return this._appliedSelection}clearSelection(){this._selection&&(this._selection=void 0,this.notify())}setTimezone(e){this._timezone=e,this.notify()}get timezone(){return this._timezone}datasetIndex(e,r){return Le(this.datasets,e,r)}mappingsTo(e){return this._mappings.filter(r=>r.to.name===e)}selectionExpressionFor(e,r){return this.selectionFor(e,r)?.expression}selectionFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?void 0:this._crossFilters.some(l=>l.from.name===i.source&&l.to.name===e)?i:void 0}selectionConditionsFor(e,r){let i=r==="pending"?this._selection:this._appliedSelection;return!i||i.source===e?he:this._crossFilters.some(l=>l.from.name===i.source&&l.to.name===e)?i.conditions:he}drillTransformations(e){let r={};return this._mappings.forEach(i=>{if(i.to!==e)return;let s=i.from.appliedCondition;if(s?.operator!=="transform_date_drill")return;let[l]=s.values??[];typeof l=="string"&&(r[i.field]=l)}),r}select(e,r,i){if(this._queries.get(e.name)!==e)throw new u(`Query \'${e.name}\' belongs to a different app.`,e.name);let s=Ze(e,r,i,this.drillTransformations(e));s?.lossy&&console.warn(`[anfra-sdk] The selection in \'${e.name}\' filters more broadly than it was made. Its conditions are combined field by field and ANDed, which cannot express "(A and B) or (C and D)", so the targets will also show combinations that were not selected. Select within one dimension, or narrow with \\`fields\\`, to avoid this.`),this._selection=s,this.notify()}get hasChanges(){return[...this._controls.values()].some(e=>e.isDirty)||this.isSelectionDirty}get isSelectionDirty(){return this.selectionCommitted?nt(this._selection)!==nt(this._appliedSelection):!1}async execute(e={}){let r=[...this._queries.values()].filter(a=>a.shouldRun(e.force));this._controls.forEach(a=>a.commit()),this._appliedSelection=this._selection,this.selectionCommitted=!0,r.forEach(a=>{a.controller?.abort(),a.resetPage()});let i={backend:this.backend,timezone:this._timezone,bustCache:e.bustCache},s=[],l=[];return await Promise.all(r.map(async a=>{let d=new AbortController;a.controller=d;let p=a.signature();a.markExecuting();try{let g=await ue(a,this.mappingsTo(a.name),{conditions:this.selectionConditionsFor(a.name,"applied"),expression:this.selectionExpressionFor(a.name,"applied")},i,d.signal);if(et(a,d))return;a.markSuccess(g,p,!1),s.push(a.name)}catch(g){if(et(a,d)||ge(g))return;a.markError(rt(g,a.name)),l.push(a.name)}finally{a.controller===d&&(a.controller=void 0)}})),{succeeded:s,failed:l}}async refresh(){return this.execute({force:!0,bustCache:!0})}abort(){this._queries.forEach(e=>e.abort())}async fetchPage(e){let r=new AbortController;e.controller=r;let i=e.signature();e.markExecuting();try{let s=await ue(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone},r.signal);e.markSuccess(s,i,!0)}catch(s){if(e.rewindPage(),ge(s))return;let l=rt(s,e.name);throw e.markError(l),l}finally{e.controller===r&&(e.controller=void 0)}}async exportQuery(e,r,i){let s=je(e,this.mappingsTo(e.name),{conditions:this.selectionConditionsFor(e.name,"applied"),expression:this.selectionExpressionFor(e.name,"applied")},{backend:this.backend,timezone:this._timezone,title:this.title},r);try{return await i(s,r.signal??new AbortController().signal)}catch(l){throw ge(l)?l:en(l,e.name)}}toJSON(){let e=o(r=>Object.fromEntries([...this._controls.entries()].filter(([,i])=>i.kind===r).map(([i,s])=>[i,s.toJSON()])),"byKind");return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},queries:Object.fromEntries([...this._queries.entries()].map(([r,i])=>[r,i.toJSON()])),filters:e("filter"),dateDrills:e("dateDrill"),mappings:[...this._mappings.map(r=>r.toJSON()),...this._crossFilters.map(r=>r.toJSON())]}}toInspectJSON(){return{...this.title?{title:this.title}:{},...this._timezone?{timezone:this._timezone}:{},hasChanges:this.hasChanges,declaration:this.toJSON(),queries:Object.fromEntries([...this._queries.entries()].map(([e,r])=>[e,Xt(r)])),controls:Object.fromEntries([...this._controls.entries()].map(([e,r])=>[e,Zt(r)])),...this._selection?{selection:tt(this._selection)}:{},...this._appliedSelection?{appliedSelection:tt(this._appliedSelection)}:{}}}locate(e,r){let i=globalThis.document;if(!i)return!1;let s=Oe(i,e,this.index,r);return s.length?(Ie(s[0]),V(i).flash(s,{kind:e,name:r,...s.length>1?{note:`in ${s.length} places`}:{}}),!0):!1}assertNameFree(e,r){ze([...this._queries.keys(),...this._controls.keys()],e,r)}soleDataset(e,r){if(!r)return;let i=Object.keys(this.datasets);if(i.length===1)return this.datasets[i[0]];throw new u(i.length?`Filter \'${e}\' names a field but the environment has ${i.length} datasets. Say which one: ${i.join(", ")}.`:`Filter \'${e}\' names a field but the environment has no datasets.`,e)}assertAcyclic(e){let r=[...this._mappings,e],i=new Map;r.forEach(d=>{let p=d.from.name;i.set(p,[...i.get(p)??[],d.to.name])});let s=new Set,l=new Set,a=o(d=>{if(s.has(d))return!0;if(l.has(d))return!1;s.add(d);let p=(i.get(d)??[]).some(a);return s.delete(d),l.add(d),p},"walk");if([...i.keys()].some(a))throw new u(`Mapping \'${e.id}\' would make the app\'s mappings cyclic.`,e.from.name)}};o(ye,"App");var K=ye;var it="0.11.1";var xe=class xe{constructor(n){c(this,"list");this.list=Object.freeze(n.map(({name:e,version:r})=>Object.freeze({name:e,version:r})))}has(n){return this.list.some(e=>e.name===n)}version(n){return this.list.find(e=>e.name===n)?.version}};o(xe,"InstalledPlugins");var be=xe,nn=it,ke=class ke{constructor(n){c(this,"version",nn);c(this,"_apps",[]);c(this,"datasets");c(this,"user");c(this,"indices");c(this,"backend");c(this,"plugins");c(this,"gates");c(this,"deprecatedFeatures");c(this,"extensions",{query:new Map,control:new Map});if(!n?.datasets)throw new u("No datasets provided. The host must call createSdk({ datasets }) before an app can be declared.");if(!n.user)throw new u("No user provided. The host must call createSdk({ user }) before an app can be declared.");if(!n.backend)throw new u("No backend provided. The host must call createSdk({ backend }) before an app can run a query.");this.datasets=Object.freeze({...n.datasets}),this.user=Object.freeze({...n.user,permissions:Object.freeze({...n.user.permissions})}),this.indices=Object.fromEntries(Object.entries(n.datasets).map(([e,r])=>[e,new G(r)])),this.backend=n.backend,this.gates=Object.freeze({...n.features}),this.plugins=new be(n.plugins??[])}get features(){return this.deprecatedFeatures||(console.warn("anfra: Anfra.features is deprecated and will be removed. Check Anfra.plugins.has(\'export\'), Anfra.plugins.has(\'render\') or Anfra.plugins.has(\'lineage\') instead."),this.deprecatedFeatures=Object.freeze({...this.gates,export:this.plugins.has("export"),render:this.plugins.has("render"),lineage:this.plugins.has("lineage")})),this.deprecatedFeatures}createApp(n={}){let e=new K(n,this.indices,this.backend,this.gates,this.extensions);return e.index=this._apps.length,this._apps.push(e),e}get apps(){return this._apps}};o(ke,"Sdk");var we=ke;function ot(t){return new we(t)}o(ot,"createSdk");var B="Anfra";function st(t,n=globalThis){let e=n[B],r=B in n;return n[B]=t,()=>{r?n[B]=e:delete n[B]}}o(st,"installSandbox");function at(t,n=[]){let e=t.document.getElementById(Se);if(!e?.textContent)throw new Error("anfra: this frame was not provisioned by a host.");let r=JSON.parse(e.textContent),i=o(f=>t.parent.postMessage(f,r.hostOrigin),"post"),s=new Map,l=new Map,a=Ae(i,{answer:o(async(f,y,b)=>{let m=s.get(f);if(!m)throw new C(`Nothing in this frame answers \'${f}\'.`);return m(y,b)},"answer"),event:o((f,y)=>{l.get(f)?.forEach(b=>{try{b(y)}catch{}})},"event")});t.addEventListener("message",f=>{f.source===t.parent&&a.receive(f.data)});let d={submitQuery:o((f,y)=>a.call("core.submitQuery",f,y).then(b=>(b.debug?.executedAt&&(b.debug.executedAt=new Date(b.debug.executedAt)),b)),"submitQuery"),fieldSuggestions:o((f,y)=>a.call("core.fieldSuggestions",f,y),"fieldSuggestions")},p=ot({datasets:r.datasets,user:r.user,backend:d,plugins:r.plugins??[]}),g=new Set,E=p.createApp.bind(p);p.createApp=f=>{let y=E(f);return g.forEach(b=>{try{b(y)}catch{}}),y};let h={window:t,sdk:p,endpoint:a,handlers:s,listeners:l,appListeners:g};for(let[f,y]of n)if(typeof y=="function")try{y(Be(f,h,{Query:O,Control:T}))}catch(b){t.console?.error(`anfra: plugin \'${f}\' failed to set up:`,b)}st(p,t),i({type:"anfra:ready"})}o(at,"bootstrap");return ht(rn);})();\n';
20
20
 
21
21
  // src/host/frameScript.ts
22
22
  function builtFrameScript() {
package/dist/plugins.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as Backend } from './types-BTyDyld7.js';
1
+ import { B as Backend } from './types-plgahUrN.js';
2
2
  import { P as Plugin } from './plugin-C5cihcQD.js';
3
3
 
4
4
  /**
package/dist/plugins.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-TQ7S5DRE.js";
4
4
  import {
5
5
  version
6
- } from "./chunk-ENWRS6AT.js";
6
+ } from "./chunk-MIHZUF2H.js";
7
7
  import {
8
8
  ValidationError
9
9
  } from "./chunk-KCTLO3CO.js";
package/dist/testing.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { b as PluginInfo } from './bridge-Byq62yS8.js';
2
- import { ai as User, D as DatasetDescriptor } from './types-BTyDyld7.js';
3
- import { S as Sdk, P as PluginSetup } from './bootstrap-B7r0ggJN.js';
1
+ import { b as PluginInfo } from './bridge-BCJklF4M.js';
2
+ import { aj as User, D as DatasetDescriptor } from './types-plgahUrN.js';
3
+ import { S as Sdk, P as PluginSetup } from './bootstrap-BkiMDMcp.js';
4
4
  import './errors-CKvqVaqU.js';
5
5
 
6
6
  /** The reader a test frame is provisioned with unless given. */
package/dist/testing.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  bootstrap
3
- } from "./chunk-BL7SPVAS.js";
3
+ } from "./chunk-O3S2GQ5N.js";
4
4
  import "./chunk-XIUFHRZE.js";
5
5
  import {
6
6
  createEndpoint
@@ -8,7 +8,7 @@ import {
8
8
  import {
9
9
  PROVISION_ELEMENT_ID
10
10
  } from "./chunk-33B2D4U5.js";
11
- import "./chunk-ENWRS6AT.js";
11
+ import "./chunk-MIHZUF2H.js";
12
12
  import "./chunk-KCTLO3CO.js";
13
13
  import "./chunk-PKBMQBKP.js";
14
14
 
@@ -51,7 +51,12 @@ interface paths {
51
51
  };
52
52
  get?: never;
53
53
  put?: never;
54
- /** Run a query: its rows, and the SQL that produced them */
54
+ /**
55
+ * Run a query: its rows, and the SQL that produced them
56
+ * @description Answers one page of rows: page_size's, or without it the first 10000, with has_more saying whether there may be more.
57
+ * Ask the query for what you need (aggregate, filter, a limit: directive) rather than paging through rows; for every row of a large result, export it.
58
+ * Over HTTP, a request that accepts application/x-ndjson is answered as the query runs: its phase, its SQL, its columns, then its rows in batches — every row without page_size, up to the server's maximum.
59
+ */
55
60
  post: operations["core.query"];
56
61
  delete?: never;
57
62
  options?: never;
@@ -407,6 +412,19 @@ interface components {
407
412
  /** @constant */
408
413
  status: 400;
409
414
  };
415
+ /** @description The page is larger than this server answers at once. */
416
+ ErrorBodyPageTooLarge: {
417
+ /** @constant */
418
+ code: "page_too_large";
419
+ context?: components["schemas"]["ContextEntry"][];
420
+ details?: components["schemas"]["PageLimit"];
421
+ message: string;
422
+ request_id: string;
423
+ /** @constant */
424
+ scope: "user";
425
+ /** @constant */
426
+ status: 422;
427
+ };
410
428
  /** @description The query failed to run on its data source. */
411
429
  ErrorBodyQueryFailed: {
412
430
  /** @constant */
@@ -415,9 +433,9 @@ interface components {
415
433
  message: string;
416
434
  request_id: string;
417
435
  /** @constant */
418
- scope: "server";
436
+ scope: "user";
419
437
  /** @constant */
420
- status: 502;
438
+ status: 422;
421
439
  };
422
440
  /** @description The query is invalid. */
423
441
  ErrorBodyQueryInvalid: {
@@ -432,6 +450,19 @@ interface components {
432
450
  /** @constant */
433
451
  status: 422;
434
452
  };
453
+ /** @description The query's result is larger than this server allows. */
454
+ ErrorBodyResultTooLarge: {
455
+ /** @constant */
456
+ code: "result_too_large";
457
+ context?: components["schemas"]["ContextEntry"][];
458
+ details?: components["schemas"]["ResultLimit"];
459
+ message: string;
460
+ request_id: string;
461
+ /** @constant */
462
+ scope: "user";
463
+ /** @constant */
464
+ status: 422;
465
+ };
435
466
  /** @description A sidecar is unavailable. */
436
467
  ErrorBodySidecarUnavailable: {
437
468
  /** @constant */
@@ -550,6 +581,20 @@ interface components {
550
581
  parent: string;
551
582
  };
552
583
  NoInput: Record<string, never>;
584
+ PageLimit: {
585
+ /** Format: int64 */
586
+ max_bytes: number;
587
+ };
588
+ QueryCompiled: {
589
+ /** @description the AQL that runs: the query with its Query Input applied; absent for a SQL query */
590
+ aql?: string;
591
+ sql: string;
592
+ /**
593
+ * @description discriminator enum property added by openapi-typescript
594
+ * @enum {string}
595
+ */
596
+ type: "compiled";
597
+ };
553
598
  QueryCondition: {
554
599
  /** @description an AQL condition */
555
600
  expr: string;
@@ -572,6 +617,16 @@ interface components {
572
617
  /** @description the operator's values, by the field's type: a number as a string in JSON's number syntax, such as "9007199254740993" (a JSON number is refused, since it may have lost digits before it was sent); true or false; a date or text as a string. Empty for an operator that takes none */
573
618
  values: unknown[];
574
619
  };
620
+ QueryHeader: {
621
+ /** @description one per field, in order */
622
+ columns: components["schemas"]["Column"][];
623
+ fields: string[];
624
+ /**
625
+ * @description discriminator enum property added by openapi-typescript
626
+ * @enum {string}
627
+ */
628
+ type: "header";
629
+ };
575
630
  QueryInput: {
576
631
  /** @description the data source a SQL query runs against */
577
632
  data_source?: string;
@@ -586,13 +641,26 @@ interface components {
586
641
  /** @description the query */
587
642
  query: string;
588
643
  };
644
+ QueryRecords: {
645
+ /** @description one array per row, its values in fields' order, written as a page's records are */
646
+ records: unknown[][];
647
+ /**
648
+ * @description discriminator enum property added by openapi-typescript
649
+ * @enum {string}
650
+ */
651
+ type: "rows";
652
+ };
589
653
  QueryResult: {
590
654
  /** @description the AQL that ran: the query with its Query Input applied; absent for a SQL query */
591
655
  aql?: string;
592
656
  /** @description one per field of result, in order */
593
657
  columns: components["schemas"]["Column"][];
658
+ /** @description there may be rows after this page: ask for the next page, or stream the query (without page_size) for every row */
659
+ has_more: boolean;
594
660
  result: components["schemas"]["QueryRows"];
595
661
  sql: string;
662
+ /** @description the query's steps: compiling_query, for AQL; canal-query's own (connecting_to_dw, executing_query, fetching_query_result, and their children, as <parent>.<child>); retrying_query, the wait before canal-query attempts the query again */
663
+ timings: components["schemas"]["Timings"];
596
664
  };
597
665
  QueryRows: {
598
666
  fields: string[];
@@ -636,6 +704,24 @@ interface components {
636
704
  /** @description a result column's name */
637
705
  field: string;
638
706
  };
707
+ QuerySummary: {
708
+ /**
709
+ * Format: int64
710
+ * @description the bytes the warehouse read to run the query, where it reports them (BigQuery, Athena)
711
+ */
712
+ bytes_scanned?: number;
713
+ /** @description a page that may not be the last: there may be rows after it. Without page_size, every row was sent, and this is false */
714
+ has_more: boolean;
715
+ /** Format: int64 */
716
+ row_count: number;
717
+ /** @description the query's steps: compiling_query, for AQL; canal-query's own (connecting_to_dw, executing_query, fetching_query_result, and their children, as <parent>.<child>); retrying_query, the wait before canal-query attempts the query again */
718
+ timings: components["schemas"]["Timings"];
719
+ /**
720
+ * @description discriminator enum property added by openapi-typescript
721
+ * @enum {string}
722
+ */
723
+ type: "summary";
724
+ };
639
725
  QueryTransforms: {
640
726
  /** @description AQL conditions ANDed with the query's own filters */
641
727
  conditions?: components["schemas"]["QueryCondition"][];
@@ -650,6 +736,15 @@ interface components {
650
736
  diagnostics: components["schemas"]["AQLDiagnostic"][];
651
737
  valid: boolean;
652
738
  };
739
+ QueryWarehouse: {
740
+ /** @description the warehouse's own id of the query; for Postgres, the process id of the backend running it */
741
+ id: string;
742
+ /**
743
+ * @description discriminator enum property added by openapi-typescript
744
+ * @enum {string}
745
+ */
746
+ type: "warehouse_query";
747
+ };
653
748
  RepoValidation: {
654
749
  diagnostics: components["schemas"]["CompileError"][];
655
750
  reports: components["schemas"]["ValidationReport"][];
@@ -667,6 +762,22 @@ interface components {
667
762
  /** Format: int64 */
668
763
  line?: number;
669
764
  };
765
+ Response: {
766
+ code: string;
767
+ context?: components["schemas"]["ContextEntry"][];
768
+ details?: unknown;
769
+ message: string;
770
+ request_id: string;
771
+ scope: string;
772
+ /** Format: int64 */
773
+ status?: number;
774
+ };
775
+ ResultLimit: {
776
+ /** Format: int64 */
777
+ max_bytes?: number;
778
+ /** Format: int64 */
779
+ max_rows?: number;
780
+ };
670
781
  SearchInput: {
671
782
  /** @description search query */
672
783
  query?: string[];
@@ -756,6 +867,63 @@ interface components {
756
867
  /** @enum {string} */
757
868
  state: "healthy" | "degraded" | "not_running";
758
869
  };
870
+ StreamEnd: {
871
+ error?: components["schemas"]["Response"];
872
+ /** @enum {string} */
873
+ status: "succeeded" | "failed";
874
+ /**
875
+ * @description discriminator enum property added by openapi-typescript
876
+ * @enum {string}
877
+ */
878
+ type: "end";
879
+ };
880
+ StreamPing: {
881
+ /**
882
+ * @description discriminator enum property added by openapi-typescript
883
+ * @enum {string}
884
+ */
885
+ type: "ping";
886
+ };
887
+ StreamStart: {
888
+ /** @description the run's id, on a host that keeps a record of runs */
889
+ id?: string;
890
+ /**
891
+ * @description discriminator enum property added by openapi-typescript
892
+ * @enum {string}
893
+ */
894
+ type: "start";
895
+ };
896
+ StreamStatus: {
897
+ phase: string;
898
+ /**
899
+ * Format: int64
900
+ * @description while queued: how many runs are ahead of this one, 0 being next; absent otherwise
901
+ */
902
+ position?: number;
903
+ /**
904
+ * @description discriminator enum property added by openapi-typescript
905
+ * @enum {string}
906
+ */
907
+ type: "status";
908
+ };
909
+ TimedStep: {
910
+ /**
911
+ * Format: int64
912
+ * @description when it started, in ms since the run started
913
+ */
914
+ start_ms: number;
915
+ /** @description the step's name, as what ran names it; a child step as <parent>.<child>, within its parent */
916
+ step: string;
917
+ };
918
+ Timings: {
919
+ /**
920
+ * Format: int64
921
+ * @description when the run ended, in ms since it started: its total time, and where its last steps end
922
+ */
923
+ end_ms: number;
924
+ /** @description each step as it started, in order; a step run again is here again */
925
+ steps: components["schemas"]["TimedStep"][];
926
+ };
759
927
  UpdateInfo: {
760
928
  available: boolean;
761
929
  latest: string;
@@ -950,6 +1118,7 @@ interface operations {
950
1118
  };
951
1119
  content: {
952
1120
  "application/json": components["schemas"]["QueryResult"];
1121
+ "application/x-ndjson": components["schemas"]["QueryCompiled"] | components["schemas"]["QueryWarehouse"] | components["schemas"]["QueryHeader"] | components["schemas"]["QueryRecords"] | components["schemas"]["QuerySummary"] | components["schemas"]["StreamStart"] | components["schemas"]["StreamStatus"] | components["schemas"]["StreamEnd"] | components["schemas"]["StreamPing"];
953
1122
  };
954
1123
  };
955
1124
  /** @description invalid_request */
@@ -963,14 +1132,14 @@ interface operations {
963
1132
  };
964
1133
  };
965
1134
  };
966
- /** @description validation_failed, query_invalid */
1135
+ /** @description validation_failed, query_invalid, query_failed, result_too_large, page_too_large */
967
1136
  422: {
968
1137
  headers: {
969
1138
  [name: string]: unknown;
970
1139
  };
971
1140
  content: {
972
1141
  "application/json": {
973
- error: components["schemas"]["ErrorBodyValidationFailed"] | components["schemas"]["ErrorBodyQueryInvalid"];
1142
+ error: components["schemas"]["ErrorBodyValidationFailed"] | components["schemas"]["ErrorBodyQueryInvalid"] | components["schemas"]["ErrorBodyQueryFailed"] | components["schemas"]["ErrorBodyResultTooLarge"] | components["schemas"]["ErrorBodyPageTooLarge"];
974
1143
  };
975
1144
  };
976
1145
  };
@@ -985,17 +1154,6 @@ interface operations {
985
1154
  };
986
1155
  };
987
1156
  };
988
- /** @description query_failed */
989
- 502: {
990
- headers: {
991
- [name: string]: unknown;
992
- };
993
- content: {
994
- "application/json": {
995
- error: components["schemas"]["ErrorBodyQueryFailed"];
996
- };
997
- };
998
- };
999
1157
  /** @description sidecar_unavailable */
1000
1158
  503: {
1001
1159
  headers: {
@@ -1110,14 +1268,14 @@ interface operations {
1110
1268
  };
1111
1269
  };
1112
1270
  };
1113
- /** @description validation_failed, query_invalid */
1271
+ /** @description validation_failed, query_invalid, query_failed */
1114
1272
  422: {
1115
1273
  headers: {
1116
1274
  [name: string]: unknown;
1117
1275
  };
1118
1276
  content: {
1119
1277
  "application/json": {
1120
- error: components["schemas"]["ErrorBodyValidationFailed"] | components["schemas"]["ErrorBodyQueryInvalid"];
1278
+ error: components["schemas"]["ErrorBodyValidationFailed"] | components["schemas"]["ErrorBodyQueryInvalid"] | components["schemas"]["ErrorBodyQueryFailed"];
1121
1279
  };
1122
1280
  };
1123
1281
  };
@@ -1143,17 +1301,6 @@ interface operations {
1143
1301
  };
1144
1302
  };
1145
1303
  };
1146
- /** @description query_failed */
1147
- 502: {
1148
- headers: {
1149
- [name: string]: unknown;
1150
- };
1151
- content: {
1152
- "application/json": {
1153
- error: components["schemas"]["ErrorBodyQueryFailed"];
1154
- };
1155
- };
1156
- };
1157
1304
  /** @description sidecar_unavailable */
1158
1305
  503: {
1159
1306
  headers: {
@@ -1842,6 +1989,22 @@ interface QueryDebug {
1842
1989
  executedSql?: string;
1843
1990
  fromCache: boolean;
1844
1991
  executedAt?: Date;
1992
+ /** How the run's time went, where the server reports it. */
1993
+ timings?: QueryTimings;
1994
+ }
1995
+ /**
1996
+ * When each step of a query's run started, in order, in milliseconds since the run started; and
1997
+ * when it ended. A step ends where the next step at its level or above starts — a child step,
1998
+ * `executing_query.poll_query`, is within its parent — or at `endMs`. A step run again after a
1999
+ * retry is listed again. Steps: `compiling_query`; canal-query's `connecting_to_dw`,
2000
+ * `executing_query`, `fetching_query_result` and their children; `retrying_query`.
2001
+ */
2002
+ interface QueryTimings {
2003
+ steps: {
2004
+ step: string;
2005
+ startMs: number;
2006
+ }[];
2007
+ endMs: number;
1845
2008
  }
1846
2009
  interface QueryResult {
1847
2010
  columns: ColumnMeta[];
@@ -1852,6 +2015,12 @@ interface QueryResult {
1852
2015
  /** Present only for a query that declares a `pageSize`. */
1853
2016
  pageSize?: number;
1854
2017
  numRows: number;
2018
+ /**
2019
+ * For a query that declares a `pageSize`: whether rows may follow this page, as its backend
2020
+ * knows it. Absent when the backend does not say; `query.hasMore` then takes a full page to
2021
+ * mean more may follow.
2022
+ */
2023
+ hasMore?: boolean;
1855
2024
  };
1856
2025
  debug?: QueryDebug;
1857
2026
  }
@@ -2112,6 +2281,8 @@ interface BackendQueryResult {
2112
2281
  page?: number;
2113
2282
  pageSize?: number;
2114
2283
  numRows?: number;
2284
+ /** For a paged query: whether rows may follow this page. Omit it when not known. */
2285
+ hasMore?: boolean;
2115
2286
  };
2116
2287
  debug?: QueryDebug;
2117
2288
  }
@@ -2220,4 +2391,4 @@ interface Backend {
2220
2391
  lineage?(request: BackendLineageRequest, signal: AbortSignal): Promise<LineageResult>;
2221
2392
  }
2222
2393
 
2223
- export { type Operator as $, type Aggregation as A, type Backend as B, type ColumnMeta as C, type DatasetDescriptor as D, type EntityKind as E, FILTER_AGGREGATIONS as F, type FieldLineage as G, type FieldSuggestionsRequest as H, type FilterAggregation as I, type FilterDeclaration as J, type FilterValueType as K, type InspectedApp as L, type InspectedControl as M, type InspectedError as N, type InspectedQuery as O, type InspectedSelection as P, type InspectedStructure as Q, type LineageCard as R, type LineageDiagram as S, type LineageNode as T, type LineageOptions as U, type LineageResult as V, type LineageTarget as W, type Listener as X, type LocateKind as Y, type LocateTarget as Z, type MappingJson as _, type AppDeclaration as a, type QueryDebug as a0, type QueryDeclaration as a1, type QueryInput as a2, type QueryResult as a3, type QuerySort as a4, type QueryState as a5, type RenderFormat as a6, type RenderRequest as a7, type Rendering as a8, type Row as a9, type SdkEnvironment as aa, type SdkFeatures as ab, type Selection as ac, type SelectionCondition as ad, type SemanticType as ae, type StructureKind as af, type StructureNode as ag, type Unsubscribe as ah, type User as ai, type paths as aj, type components as ak, type AppJson as b, type ArrowType as c, type BackendCondition as d, type BackendDateDrill as e, type BackendExportRequest as f, type BackendFilter as g, type BackendLineageRequest as h, type BackendQueryRequest as i, type BackendQueryResult as j, type BackendSort as k, type Condition as l, type ConditionValue as m, type ControlMappingJson as n, type CrossFilterJson as o, type DateDrillDeclaration as p, type DateGrain as q, type DateTransformation as r, type EntityRef as s, type EntityUsage as t, type ExecuteOptions as u, type ExecuteSummary as v, type ExportFormat as w, type ExportFormatOptions as x, type ExportOptions as y, type ExportResult as z };
2394
+ export { type Operator as $, type Aggregation as A, type Backend as B, type ColumnMeta as C, type DatasetDescriptor as D, type EntityKind as E, FILTER_AGGREGATIONS as F, type FieldLineage as G, type FieldSuggestionsRequest as H, type FilterAggregation as I, type FilterDeclaration as J, type FilterValueType as K, type InspectedApp as L, type InspectedControl as M, type InspectedError as N, type InspectedQuery as O, type InspectedSelection as P, type InspectedStructure as Q, type LineageCard as R, type LineageDiagram as S, type LineageNode as T, type LineageOptions as U, type LineageResult as V, type LineageTarget as W, type Listener as X, type LocateKind as Y, type LocateTarget as Z, type MappingJson as _, type AppDeclaration as a, type QueryDebug as a0, type QueryDeclaration as a1, type QueryInput as a2, type QueryResult as a3, type QuerySort as a4, type QueryState as a5, type QueryTimings as a6, type RenderFormat as a7, type RenderRequest as a8, type Rendering as a9, type Row as aa, type SdkEnvironment as ab, type SdkFeatures as ac, type Selection as ad, type SelectionCondition as ae, type SemanticType as af, type StructureKind as ag, type StructureNode as ah, type Unsubscribe as ai, type User as aj, type paths as ak, type components as al, type AppJson as b, type ArrowType as c, type BackendCondition as d, type BackendDateDrill as e, type BackendExportRequest as f, type BackendFilter as g, type BackendLineageRequest as h, type BackendQueryRequest as i, type BackendQueryResult as j, type BackendSort as k, type Condition as l, type ConditionValue as m, type ControlMappingJson as n, type CrossFilterJson as o, type DateDrillDeclaration as p, type DateGrain as q, type DateTransformation as r, type EntityRef as s, type EntityUsage as t, type ExecuteOptions as u, type ExecuteSummary as v, type ExportFormat as w, type ExportFormatOptions as x, type ExportOptions as y, type ExportResult as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@holistics/anfra-sdk",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "description": "Data Apps on anfra: the authoring layer (app), what hosts one (host), anfra's plugins (plugins), the core API client (api), and their shared contract (common)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {