@holistics/anfra-sdk 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2020 @@
1
+ import {
2
+ FILTER_AGGREGATIONS
3
+ } from "./chunk-XIUFHRZE.js";
4
+ import {
5
+ createEndpoint
6
+ } from "./chunk-ADWBOQW2.js";
7
+ import {
8
+ PROVISION_ELEMENT_ID
9
+ } from "./chunk-33B2D4U5.js";
10
+ import {
11
+ version
12
+ } from "./chunk-ENWRS6AT.js";
13
+ import {
14
+ DataAppError,
15
+ PermissionError,
16
+ QueryError,
17
+ TransportError,
18
+ ValidationError
19
+ } from "./chunk-KCTLO3CO.js";
20
+ import {
21
+ __publicField
22
+ } from "./chunk-PKBMQBKP.js";
23
+
24
+ // src/app/observable.ts
25
+ var Observable = class {
26
+ constructor(parent) {
27
+ __publicField(this, "listeners", /* @__PURE__ */ new Set());
28
+ __publicField(this, "parent");
29
+ this.parent = parent;
30
+ }
31
+ subscribe(listener) {
32
+ this.listeners.add(listener);
33
+ return () => {
34
+ this.listeners.delete(listener);
35
+ };
36
+ }
37
+ /**
38
+ * Public only so a child observable can bubble into its parent — an app subscriber sees every
39
+ * entity's changes through one subscription. Subclasses call the protected `notify` instead.
40
+ */
41
+ notifyChange() {
42
+ this.listeners.forEach((listener) => listener());
43
+ this.parent?.notifyChange();
44
+ }
45
+ notify() {
46
+ this.notifyChange();
47
+ }
48
+ };
49
+
50
+ // src/app/query.ts
51
+ var Query = class extends Observable {
52
+ constructor(name, app, declaration) {
53
+ super(app);
54
+ __publicField(this, "kind", "query");
55
+ __publicField(this, "name");
56
+ __publicField(this, "declaration");
57
+ __publicField(this, "dataset");
58
+ __publicField(this, "app");
59
+ __publicField(this, "_state", "idle");
60
+ __publicField(this, "_result");
61
+ __publicField(this, "_error");
62
+ __publicField(this, "_page", 1);
63
+ /**
64
+ * A sort applied to the result, independent of the query's own AQL — the same mechanism a click
65
+ * on a table's column header uses. Kept off the declaration so setting it never re-authors the
66
+ * query. See docs/adr/0001.
67
+ */
68
+ __publicField(this, "_sort", []);
69
+ /** The input signature of the last successful run; undefined until one has happened. */
70
+ __publicField(this, "lastRunSignature");
71
+ /**
72
+ * Rows in the most recent page, not in the accumulated result. `fetchMore` appends, so comparing
73
+ * the total against the page size would report "more" forever once two pages are held.
74
+ */
75
+ __publicField(this, "lastPageRows", 0);
76
+ /** @internal Set by the executor so `abort()` can reach the in-flight request. */
77
+ __publicField(this, "controller");
78
+ if (!declaration.aql?.trim()) {
79
+ throw new ValidationError(`Query '${name}' declares no AQL.`, name);
80
+ }
81
+ const { pageSize } = declaration;
82
+ if (pageSize !== void 0 && !(Number.isInteger(pageSize) && pageSize >= 1)) {
83
+ throw new ValidationError(
84
+ `Query '${name}' declares pageSize ${pageSize}; it must be a whole number of at least 1.`,
85
+ name
86
+ );
87
+ }
88
+ this.name = name;
89
+ this.app = app;
90
+ this.declaration = declaration;
91
+ this.dataset = app.datasetIndex(declaration.dataset, name);
92
+ }
93
+ /**
94
+ * Bring the elements marked `data-anfra-query` with this query's name into view: scroll to the
95
+ * first and show them all for a moment. False, and nothing done, when no element on the page is
96
+ * marked with it yet; never throws, so an author's own button is safe.
97
+ */
98
+ locate() {
99
+ return this.app.locate("query", this.name);
100
+ }
101
+ get state() {
102
+ return this._state;
103
+ }
104
+ get result() {
105
+ return this._result;
106
+ }
107
+ get error() {
108
+ return this._error;
109
+ }
110
+ /** Rows per page, or undefined for a query that isn't paged and gets every row. */
111
+ get pageSize() {
112
+ return this.declaration.pageSize;
113
+ }
114
+ get page() {
115
+ return this._page;
116
+ }
117
+ get sort() {
118
+ return this._sort;
119
+ }
120
+ /** Replaces the sort applied to this query's result. Pass `[]` to clear it back to the AQL's own. */
121
+ setSort(sort) {
122
+ this._sort = [...sort];
123
+ this.notify();
124
+ }
125
+ get hasMore() {
126
+ if (!this._result || this.pageSize === void 0) return false;
127
+ return this.lastPageRows >= this.pageSize;
128
+ }
129
+ /**
130
+ * Everything that changes the rows: the declaration, the conditions reaching this query through
131
+ * mappings, the conditions reaching it from the selection, the sort override, the app's timezone,
132
+ * and the page. Compared against the last successful run to decide whether re-running would
133
+ * produce anything new.
134
+ */
135
+ signature() {
136
+ const conditions = this.app.mappingsTo(this.name).map((mapping) => ({
137
+ field: mapping.field,
138
+ aggregation: mapping.aggregation,
139
+ condition: mapping.from.condition
140
+ })).sort((a, b) => a.field.localeCompare(b.field) || JSON.stringify(a).localeCompare(JSON.stringify(b)));
141
+ return JSON.stringify({
142
+ declaration: this.declaration,
143
+ conditions,
144
+ selection: this.app.selectionConditionsFor(this.name, "pending"),
145
+ // Separate from `selection`, and not optional: a selection sent as one expression leaves
146
+ // `conditions` empty, so without this every such selection has the same signature as the
147
+ // next one and the query is never re-run.
148
+ selectionExpression: this.app.selectionExpressionFor(this.name, "pending"),
149
+ sort: this._sort,
150
+ timezone: this.app.timezone,
151
+ page: this._page
152
+ });
153
+ }
154
+ /**
155
+ * False before the first run: with nothing applied there is nothing to have changed. Distinct
156
+ * from `shouldRun`, which is true in that case precisely because there is no result yet.
157
+ */
158
+ get isDirty() {
159
+ return this.lastRunSignature !== void 0 && this.signature() !== this.lastRunSignature;
160
+ }
161
+ /** @internal */
162
+ shouldRun(force = false) {
163
+ return force || this.lastRunSignature === void 0 || this.isDirty;
164
+ }
165
+ /** Stops the in-flight request for this query. The pending `execute()` resolves without it. */
166
+ abort() {
167
+ this.controller?.abort();
168
+ }
169
+ /** Fetches the next page and appends it. Rejects rather than swallowing, unlike `execute()`. */
170
+ async fetchMore() {
171
+ if (this.pageSize === void 0) {
172
+ throw new ValidationError(`Query '${this.name}' declares no pageSize, so it has no more pages.`, this.name);
173
+ }
174
+ if (!this.hasMore) return;
175
+ this._page += 1;
176
+ await this.app.fetchPage(this);
177
+ }
178
+ /**
179
+ * Cross-filters this query's targets by the rows the reader picked.
180
+ *
181
+ * Replaces whatever was selected, here or in another query: an app holds one selection at a time.
182
+ * Pass no rows to clear it. The SDK never sees the click, so the author calls this from their own
183
+ * chart's handler, passing the result rows they rendered.
184
+ *
185
+ * `fields` narrows which result columns take part, for a chart that renders fewer than the query
186
+ * returned. A measure or an adhoc column never takes part, whether or not it is named here.
187
+ */
188
+ select(rows, options = {}) {
189
+ this.app.select(this, Array.isArray(rows) ? rows : [rows], options.fields);
190
+ }
191
+ /**
192
+ * The rows of this query's current result that the reader has selected, for redrawing its own
193
+ * highlight. Empty unless this query is the selection's source.
194
+ *
195
+ * Matched by value rather than by object identity. A source is never filtered by its own
196
+ * selection, but it does re-run when it stops being some *other* query's target — which is
197
+ * exactly what happens when the reader moves their selection from another panel to this one. Its
198
+ * rows come back as new objects, and identity would drop the highlight at that moment.
199
+ *
200
+ * `app.selection.rows` still holds what the author passed, verbatim.
201
+ */
202
+ get selectedRows() {
203
+ const { selection } = this.app;
204
+ if (selection?.source !== this.name) return [];
205
+ const rows = this._result?.rows;
206
+ if (!rows) return selection.rows;
207
+ const key = (row) => JSON.stringify(
208
+ selection.fields.map((alias) => row[alias] ?? null)
209
+ );
210
+ const picked = new Set(selection.rows.map(key));
211
+ return rows.filter((row) => picked.has(key(row)));
212
+ }
213
+ /** @internal */
214
+ markExecuting() {
215
+ this._state = "executing";
216
+ this._error = void 0;
217
+ this.notify();
218
+ }
219
+ /** @internal */
220
+ markSuccess(result, signature, append) {
221
+ this._state = "success";
222
+ this._error = void 0;
223
+ this.lastRunSignature = signature;
224
+ this.lastPageRows = result.rows.length;
225
+ if (append && this._result) {
226
+ const rows = [...this._result.rows, ...result.rows];
227
+ this._result = { ...result, rows, meta: { ...result.meta, numRows: rows.length } };
228
+ } else {
229
+ this._result = result;
230
+ }
231
+ this.notify();
232
+ }
233
+ /** @internal */
234
+ markError(error) {
235
+ this._state = "error";
236
+ this._error = error;
237
+ this.notify();
238
+ }
239
+ /** @internal Reverts an optimistic page bump when a `fetchMore` fails. */
240
+ rewindPage() {
241
+ if (this._page > 1) this._page -= 1;
242
+ }
243
+ /** @internal */
244
+ resetPage() {
245
+ this._page = 1;
246
+ this.lastPageRows = 0;
247
+ }
248
+ toJSON() {
249
+ return this.declaration;
250
+ }
251
+ };
252
+
253
+ // src/app/controls.ts
254
+ var DATE_GRAINS = ["year", "quarter", "month", "week", "day", "hour", "minute"];
255
+ function assertGrain(entity, grain) {
256
+ if (!DATE_GRAINS.includes(grain)) {
257
+ throw new ValidationError(
258
+ `Invalid grain '${grain}'. Expected one of: ${DATE_GRAINS.join(", ")}.`,
259
+ entity
260
+ );
261
+ }
262
+ }
263
+ function drillCondition(entity, grain) {
264
+ if (!grain) return { operator: "none" };
265
+ assertGrain(entity, grain);
266
+ return { operator: "transform_date_drill", values: [`datetrunc ${grain}`] };
267
+ }
268
+ function inferType(fieldType) {
269
+ const type = fieldType.toLowerCase();
270
+ if (type.includes("date") || type.includes("time")) return "date";
271
+ if (type.includes("int") || type.includes("number") || type.includes("float") || type.includes("decimal")) return "number";
272
+ if (type.includes("bool")) return "boolean";
273
+ return "string";
274
+ }
275
+ function sameCondition(a, b) {
276
+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
277
+ }
278
+ var Control = class extends Observable {
279
+ constructor(name, app, initial) {
280
+ super(app);
281
+ __publicField(this, "name");
282
+ __publicField(this, "app");
283
+ __publicField(this, "pending");
284
+ __publicField(this, "applied");
285
+ __publicField(this, "initial");
286
+ this.name = name;
287
+ this.app = app;
288
+ this.initial = initial;
289
+ this.pending = initial;
290
+ }
291
+ /**
292
+ * Bring the elements marked `data-anfra-control` with this control's name into view. False when
293
+ * none is on the page yet; never throws.
294
+ */
295
+ locate() {
296
+ return this.app.locate("control", this.name);
297
+ }
298
+ /** The reader's current value, which `execute()` will commit. */
299
+ get condition() {
300
+ return this.pending;
301
+ }
302
+ /** The value this control's mapped queries last ran with. Undefined before the first execution. */
303
+ get appliedCondition() {
304
+ return this.applied;
305
+ }
306
+ /**
307
+ * False before the first execution: with nothing applied there is nothing to differ from, so a
308
+ * control set from a URL at startup is not an unapplied change.
309
+ */
310
+ get isDirty() {
311
+ return this.applied !== void 0 && !sameCondition(this.pending, this.applied);
312
+ }
313
+ setCondition(condition) {
314
+ this.pending = condition;
315
+ this.notify();
316
+ }
317
+ reset() {
318
+ this.setCondition(this.initial);
319
+ }
320
+ /** @internal Called by the executor once the queries reading this control have been submitted. */
321
+ commit() {
322
+ this.applied = this.pending;
323
+ }
324
+ };
325
+ var Filter = class extends Control {
326
+ constructor(name, app, declaration, dataset, backend) {
327
+ super(name, app, declaration.default ?? { operator: "is", values: [] });
328
+ __publicField(this, "kind", "filter");
329
+ __publicField(this, "declaration");
330
+ __publicField(this, "type");
331
+ __publicField(this, "resolved");
332
+ __publicField(this, "datasetName");
333
+ __publicField(this, "backend");
334
+ __publicField(this, "loadedOptions");
335
+ this.declaration = declaration;
336
+ this.backend = backend;
337
+ if (declaration.field) {
338
+ if (!dataset) {
339
+ throw new ValidationError(
340
+ `Filter '${name}' names a field but no dataset. Pass \`dataset\` alongside \`field\`.`,
341
+ name
342
+ );
343
+ }
344
+ this.resolved = dataset.resolve(declaration.field, name);
345
+ this.datasetName = dataset.descriptor.name;
346
+ this.type = declaration.type ?? inferType(this.resolved.type);
347
+ } else {
348
+ if (!declaration.type) {
349
+ throw new ValidationError(
350
+ `Filter '${name}' is a manual filter, so it needs a \`type\`.`,
351
+ name
352
+ );
353
+ }
354
+ this.type = declaration.type;
355
+ }
356
+ this.assertValues(this.condition.values ?? []);
357
+ this.assertValues(declaration.options ?? []);
358
+ }
359
+ setCondition(condition) {
360
+ this.assertValues(condition.values ?? []);
361
+ super.setCondition(condition);
362
+ }
363
+ /**
364
+ * A number filter's values are strings, as query results give them, which keep every digit. A JS
365
+ * number may already have lost some (`Number("9007199254740993")` is ...992), and nothing after
366
+ * can tell, so the core API refuses one; this says so where the app hands it over.
367
+ */
368
+ assertValues(values) {
369
+ if (this.type !== "number") return;
370
+ const number = values.find((value) => typeof value === "number");
371
+ if (number === void 0) return;
372
+ throw new ValidationError(
373
+ `Filter '${this.name}' filters numbers: give its values as strings, as query results give them (${JSON.stringify(String(number))}, not ${String(number)}), so none has lost a digit.`,
374
+ this.name
375
+ );
376
+ }
377
+ /** True for a field-backed filter, false for a manual one. The two are separate axes from `type`. */
378
+ get isFieldBacked() {
379
+ return this.resolved !== void 0;
380
+ }
381
+ /** A manual filter's static list, or whatever the last `loadOptions()` returned. */
382
+ get options() {
383
+ return this.loadedOptions ?? this.declaration.options ?? [];
384
+ }
385
+ /**
386
+ * Fetches option values for a field-backed filter.
387
+ *
388
+ * Lazy rather than fetched up front: building a distinct-values query for every filter is slow,
389
+ * and readers often touch none of them. The backend decides which values this reader may see.
390
+ */
391
+ async loadOptions(search, signal = new AbortController().signal) {
392
+ const model = this.resolved?.modelName;
393
+ if (!this.resolved || !model || !this.backend || !this.datasetName) return this.options;
394
+ const options = await this.backend.fieldSuggestions(
395
+ {
396
+ dataset: this.datasetName,
397
+ model,
398
+ field: this.resolved.fieldName,
399
+ q: search ?? ""
400
+ },
401
+ signal
402
+ );
403
+ this.loadedOptions = [...options ?? []];
404
+ this.notify();
405
+ return this.loadedOptions;
406
+ }
407
+ toJSON() {
408
+ return this.declaration;
409
+ }
410
+ };
411
+ var DateDrillControl = class extends Control {
412
+ constructor(name, app, declaration = {}) {
413
+ super(name, app, drillCondition(name, declaration.default));
414
+ __publicField(this, "kind", "dateDrill");
415
+ __publicField(this, "declaration");
416
+ this.declaration = declaration;
417
+ }
418
+ setGrain(grain) {
419
+ this.setCondition(drillCondition(this.name, grain));
420
+ }
421
+ toJSON() {
422
+ return this.declaration;
423
+ }
424
+ };
425
+
426
+ // src/app/mapping.ts
427
+ var Mapping = class {
428
+ constructor(from, to, field, aggregation) {
429
+ __publicField(this, "kind", "control");
430
+ __publicField(this, "from");
431
+ __publicField(this, "to");
432
+ __publicField(this, "field");
433
+ __publicField(this, "aggregation");
434
+ this.from = from;
435
+ this.to = to;
436
+ this.field = field;
437
+ this.aggregation = aggregation;
438
+ }
439
+ /**
440
+ * Includes the field, unlike Dashboard as Code's `${from}.${to}` — that form collides the moment
441
+ * one control maps onto one query on two fields.
442
+ */
443
+ get id() {
444
+ return `${this.from.name}.${this.to.name}.${this.field}`;
445
+ }
446
+ toJSON() {
447
+ return {
448
+ kind: this.kind,
449
+ id: this.id,
450
+ from: { kind: this.from.kind, name: this.from.name },
451
+ to: { kind: "query", name: this.to.name },
452
+ field: this.field,
453
+ ...this.aggregation ? { aggregation: this.aggregation } : {}
454
+ };
455
+ }
456
+ };
457
+ var CrossFilter = class {
458
+ constructor(from, to) {
459
+ __publicField(this, "kind", "crossFilter");
460
+ __publicField(this, "from");
461
+ __publicField(this, "to");
462
+ this.from = from;
463
+ this.to = to;
464
+ }
465
+ /** No field to disambiguate, and one pair may only be declared once, so the pair is the id. */
466
+ get id() {
467
+ return `${this.from.name}.${this.to.name}`;
468
+ }
469
+ toJSON() {
470
+ return {
471
+ kind: this.kind,
472
+ id: this.id,
473
+ from: { kind: "query", name: this.from.name },
474
+ to: { kind: "query", name: this.to.name }
475
+ };
476
+ }
477
+ };
478
+
479
+ // src/app/structure.ts
480
+ var ATTR = {
481
+ container: "data-anfra-container",
482
+ block: "data-anfra-block",
483
+ query: "data-anfra-query",
484
+ control: "data-anfra-control",
485
+ label: "data-anfra-label"
486
+ };
487
+ var MARKED = `[${ATTR.container}],[${ATTR.block}],[${ATTR.query}],[${ATTR.control}]`;
488
+ function parseRef(token) {
489
+ const match = /^(?:(\d+)\/)?([^/\s]+)$/.exec(token);
490
+ if (!match) return void 0;
491
+ return { app: match[1] === void 0 ? 0 : Number(match[1]), name: match[2] };
492
+ }
493
+ var tokens = (value) => (value ?? "").split(/\s+/).filter(Boolean);
494
+ function markersFor(doc, kind, app, name) {
495
+ const attr = kind === "query" ? ATTR.query : ATTR.control;
496
+ return [...doc.querySelectorAll(`[${attr}]`)].filter((element) => tokens(element.getAttribute(attr)).some((token) => {
497
+ const ref = parseRef(token);
498
+ return ref?.app === app && ref.name === name;
499
+ }));
500
+ }
501
+ var hasEntity = (apps, kind, ref) => {
502
+ const app = apps[ref.app];
503
+ if (!app) return false;
504
+ return Object.prototype.hasOwnProperty.call(kind === "query" ? app.queries : app.controls, ref.name);
505
+ };
506
+ function buildStructure(doc, apps) {
507
+ var _a;
508
+ const roots = [];
509
+ const elements = /* @__PURE__ */ new Map();
510
+ const keysOf = /* @__PURE__ */ new Map();
511
+ const nodeOf = /* @__PURE__ */ new Map();
512
+ const kindOf = /* @__PURE__ */ new Map();
513
+ const seenIds = { container: /* @__PURE__ */ new Set(), block: /* @__PURE__ */ new Set() };
514
+ const usage = {};
515
+ const place = (parent, node, element) => {
516
+ const siblings = parent ? nodeOf.get(parent).children : roots;
517
+ const prefix = parent ? `${nodeOf.get(parent).key}.` : "";
518
+ const full = { ...node, key: `${prefix}${siblings.length}`, children: [] };
519
+ siblings.push(full);
520
+ elements.set(full.key, element);
521
+ keysOf.set(element, [...keysOf.get(element) ?? [], full.key]);
522
+ return full;
523
+ };
524
+ for (const element of doc.querySelectorAll(MARKED)) {
525
+ const parent = element.parentElement?.closest(MARKED) ?? null;
526
+ const containerId = element.getAttribute(ATTR.container);
527
+ const blockId = element.getAttribute(ATTR.block);
528
+ const label = element.getAttribute(ATTR.label) ?? void 0;
529
+ const enclosingBlock = parent && (kindOf.get(parent) === "block" ? parent : parent.closest(`[${ATTR.block}]`));
530
+ let own;
531
+ if (containerId !== null || blockId !== null) {
532
+ const kind = containerId !== null ? "container" : "block";
533
+ const id = (containerId ?? blockId ?? "").trim();
534
+ const problems = [];
535
+ if (containerId !== null && blockId !== null) problems.push("This element is marked as a container and as a block. It counts as a container.");
536
+ if (!id) problems.push(`This ${kind} has no id.`);
537
+ else if (seenIds[kind].has(id)) problems.push(`Another ${kind} already has the id "${id}".`);
538
+ else seenIds[kind].add(id);
539
+ if (enclosingBlock) {
540
+ problems.push(`A block can't hold a ${kind}. This one is inside the block "${enclosingBlock.getAttribute(ATTR.block)}".`);
541
+ }
542
+ own = place(parent, {
543
+ kind,
544
+ id,
545
+ ...label !== void 0 ? { label } : {},
546
+ problems
547
+ }, element);
548
+ nodeOf.set(element, own);
549
+ kindOf.set(element, kind);
550
+ }
551
+ const under = own ? element : parent;
552
+ for (const kind of ["query", "control"]) {
553
+ for (const token of tokens(element.getAttribute(kind === "query" ? ATTR.query : ATTR.control))) {
554
+ const ref = parseRef(token);
555
+ const problems = [];
556
+ if (!ref) problems.push(`Can't read "${token}". Write the ${kind}'s name, or app/name when the page has several apps.`);
557
+ else if (!hasEntity(apps, kind, ref)) {
558
+ problems.push(apps[ref.app] ? `No ${kind} is called "${ref.name}" in app ${ref.app}.` : `The page has no app ${ref.app}.`);
559
+ }
560
+ place(under, {
561
+ kind,
562
+ name: ref?.name ?? token,
563
+ app: ref?.app ?? 0,
564
+ problems
565
+ }, element);
566
+ if (ref && !problems.length) {
567
+ const key = `${ref.app}/${ref.name}`;
568
+ const entry = usage[_a = `${kind}:${key}`] ?? (usage[_a] = { elements: /* @__PURE__ */ new Set(), blocks: /* @__PURE__ */ new Set() });
569
+ entry.elements.add(element);
570
+ const block = own?.kind === "block" ? own.id : enclosingBlock?.getAttribute(ATTR.block);
571
+ if (block) entry.blocks.add(block);
572
+ }
573
+ }
574
+ }
575
+ }
576
+ const usageOut = Object.fromEntries(
577
+ Object.entries(usage).map(([key, entry]) => [key, { markers: entry.elements.size, blocks: [...entry.blocks] }])
578
+ );
579
+ return {
580
+ nodes: roots,
581
+ usage: usageOut,
582
+ elements,
583
+ keysOf
584
+ };
585
+ }
586
+
587
+ // src/app/layer.ts
588
+ var LAYER_ATTRIBUTE = "data-anfra-layer";
589
+ var LAYER_STYLE = "position:absolute;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483647;";
590
+ function layerOf(doc) {
591
+ const existing = doc.querySelector(`[${LAYER_ATTRIBUTE}]`);
592
+ if (existing instanceof (doc.defaultView?.HTMLElement ?? HTMLElement)) return existing;
593
+ const layer = doc.createElement("div");
594
+ layer.setAttribute(LAYER_ATTRIBUTE, "");
595
+ layer.setAttribute("style", LAYER_STYLE);
596
+ (doc.body ?? doc.documentElement).appendChild(layer);
597
+ return layer;
598
+ }
599
+ function layerRoot(doc, part) {
600
+ const layer = layerOf(doc);
601
+ const host = [...layer.children].find((child) => child.getAttribute("data-part") === part);
602
+ if (host?.shadowRoot) return host.shadowRoot;
603
+ const element = doc.createElement("div");
604
+ element.setAttribute("data-part", part);
605
+ layer.appendChild(element);
606
+ return element.attachShadow({ mode: "open" });
607
+ }
608
+
609
+ // src/app/overlay.ts
610
+ var OVERLAY_ID = "anfra-overlay";
611
+ var FLASH_MS = 1500;
612
+ var BOX_STYLE = "position:fixed;box-sizing:border-box;background:rgba(37,99,235,0.22);outline:1px solid #2563eb;outline-offset:-1px;";
613
+ var LABEL_STYLE = "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);";
614
+ var PART_STYLE = {
615
+ kind: "color:#94a3b8;",
616
+ name: "color:#93c5fd;font-weight:700;",
617
+ label: "color:#f8fafc;",
618
+ note: "color:#94a3b8;",
619
+ size: "color:#94a3b8;margin-left:10px;"
620
+ };
621
+ var Overlay = class {
622
+ constructor(doc) {
623
+ __publicField(this, "doc", doc);
624
+ __publicField(this, "root");
625
+ __publicField(this, "shown", []);
626
+ __publicField(this, "text", { kind: "", name: "" });
627
+ __publicField(this, "timer");
628
+ __publicField(this, "reposition", () => this.draw());
629
+ const layer = layerRoot(doc, "anfra");
630
+ const existing = layer.getElementById(OVERLAY_ID);
631
+ if (existing instanceof (doc.defaultView?.HTMLElement ?? HTMLElement)) {
632
+ this.root = existing;
633
+ } else {
634
+ this.root = doc.createElement("div");
635
+ this.root.id = OVERLAY_ID;
636
+ this.root.setAttribute("aria-hidden", "true");
637
+ this.root.setAttribute("style", "position:fixed;inset:0;z-index:2147483647;pointer-events:none;display:none;");
638
+ layer.appendChild(this.root);
639
+ }
640
+ }
641
+ /** Show the overlay on these elements, labelled, until `hide()` or the next `show()`. */
642
+ show(elements, text) {
643
+ this.clearTimer();
644
+ if (!this.root.isConnected) layerRoot(this.doc, "anfra").appendChild(this.root);
645
+ this.shown = [...elements];
646
+ this.text = text;
647
+ if (!this.shown.length) {
648
+ this.hide();
649
+ return;
650
+ }
651
+ this.root.style.display = "block";
652
+ this.draw();
653
+ this.doc.addEventListener("scroll", this.reposition, { capture: true, passive: true });
654
+ this.doc.defaultView?.addEventListener("resize", this.reposition);
655
+ }
656
+ /** Show for a moment, then hide. */
657
+ flash(elements, text, ms = FLASH_MS) {
658
+ this.show(elements, text);
659
+ this.timer = setTimeout(() => this.hide(), ms);
660
+ }
661
+ hide() {
662
+ this.clearTimer();
663
+ this.shown = [];
664
+ this.root.style.display = "none";
665
+ this.root.replaceChildren();
666
+ this.doc.removeEventListener("scroll", this.reposition, { capture: true });
667
+ this.doc.defaultView?.removeEventListener("resize", this.reposition);
668
+ }
669
+ get visible() {
670
+ return this.shown.length > 0;
671
+ }
672
+ clearTimer() {
673
+ if (this.timer !== void 0) clearTimeout(this.timer);
674
+ this.timer = void 0;
675
+ }
676
+ draw() {
677
+ const boxes = this.shown.map((element) => {
678
+ const r = element.getBoundingClientRect();
679
+ const box = this.doc.createElement("div");
680
+ box.setAttribute("style", `${BOX_STYLE}left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;`);
681
+ return box;
682
+ });
683
+ const first = this.shown[0].getBoundingClientRect();
684
+ const label = this.doc.createElement("div");
685
+ label.setAttribute("data-testid", "anfra-overlay-label");
686
+ const viewportHeight = this.doc.defaultView?.innerHeight ?? 0;
687
+ const top = first.top >= 26 ? first.top - 24 : Math.max(4, first.top + 4);
688
+ const left = Math.max(4, Math.min(first.left, (this.doc.defaultView?.innerWidth ?? 0) - 24));
689
+ label.setAttribute("style", `${LABEL_STYLE}left:${left}px;top:${Math.min(top, viewportHeight - 24)}px;`);
690
+ for (const part of ["kind", "name", "label", "note", "size"]) {
691
+ const value = this.text[part];
692
+ if (!value) continue;
693
+ const span = this.doc.createElement("span");
694
+ span.setAttribute("style", PART_STYLE[part]);
695
+ span.setAttribute("data-part", part);
696
+ span.textContent = value;
697
+ label.appendChild(span);
698
+ }
699
+ this.root.replaceChildren(...boxes, label);
700
+ }
701
+ };
702
+ var overlays = /* @__PURE__ */ new WeakMap();
703
+ function overlayFor(doc) {
704
+ let overlay = overlays.get(doc);
705
+ if (!overlay) {
706
+ overlay = new Overlay(doc);
707
+ overlays.set(doc, overlay);
708
+ }
709
+ return overlay;
710
+ }
711
+ function scrollTo(element) {
712
+ if (typeof element.scrollIntoView === "function") {
713
+ element.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });
714
+ }
715
+ }
716
+
717
+ // src/app/suggest.ts
718
+ function editDistance(a, b) {
719
+ const rows = a.length + 1;
720
+ const cols = b.length + 1;
721
+ let prev = Array.from({ length: cols }, (_, j) => j);
722
+ for (let i = 1; i < rows; i++) {
723
+ const curr = [i];
724
+ for (let j = 1; j < cols; j++) {
725
+ curr[j] = Math.min(
726
+ prev[j] + 1,
727
+ curr[j - 1] + 1,
728
+ prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
729
+ );
730
+ }
731
+ prev = curr;
732
+ }
733
+ return prev[cols - 1];
734
+ }
735
+ function suggest(value, candidates) {
736
+ let best;
737
+ let bestDistance = Infinity;
738
+ candidates.forEach((candidate) => {
739
+ const distance = editDistance(value.toLowerCase(), candidate.toLowerCase());
740
+ if (distance < bestDistance) {
741
+ bestDistance = distance;
742
+ best = candidate;
743
+ }
744
+ });
745
+ const threshold = Math.max(2, Math.floor(value.length / 3));
746
+ return bestDistance <= threshold ? best : void 0;
747
+ }
748
+ function withSuggestion(message, value, candidates) {
749
+ const hint = suggest(value, candidates);
750
+ return hint ? `${message} Did you mean '${hint}'?` : message;
751
+ }
752
+
753
+ // src/app/validation.ts
754
+ var DatasetIndex = class {
755
+ constructor(descriptor) {
756
+ __publicField(this, "descriptor");
757
+ __publicField(this, "fields", /* @__PURE__ */ new Map());
758
+ __publicField(this, "references");
759
+ this.descriptor = descriptor;
760
+ descriptor.data_models.forEach((model) => {
761
+ model.fields.forEach((field) => {
762
+ const modelName = String(model.name);
763
+ this.fields.set(`${modelName}.${field.name}`, {
764
+ modelName,
765
+ fieldName: field.name,
766
+ isMetric: false,
767
+ type: field.type,
768
+ label: field.label ?? field.name
769
+ });
770
+ });
771
+ });
772
+ descriptor.metrics.forEach((metric) => {
773
+ this.fields.set(metric.name, {
774
+ fieldName: metric.name,
775
+ isMetric: true,
776
+ type: metric.type,
777
+ label: metric.label ?? metric.name
778
+ });
779
+ });
780
+ this.references = [...this.fields.keys()];
781
+ }
782
+ resolve(reference, entity) {
783
+ const field = this.fields.get(reference);
784
+ if (field) return field;
785
+ throw new ValidationError(
786
+ withSuggestion(
787
+ `Unknown field '${reference}' on dataset '${this.descriptor.name}'.`,
788
+ reference,
789
+ this.references
790
+ ),
791
+ entity
792
+ );
793
+ }
794
+ };
795
+ function resolveDataset(datasets, uname, entity) {
796
+ const dataset = datasets[uname];
797
+ if (dataset) return dataset;
798
+ throw new ValidationError(
799
+ withSuggestion(
800
+ `Unknown dataset '${uname}'.`,
801
+ uname,
802
+ Object.keys(datasets)
803
+ ),
804
+ entity
805
+ );
806
+ }
807
+ function assertValidFilterAggregation(aggregation, entity) {
808
+ if (!FILTER_AGGREGATIONS.includes(aggregation)) {
809
+ throw new ValidationError(
810
+ withSuggestion(
811
+ `Invalid filter aggregation '${aggregation}'.`,
812
+ aggregation,
813
+ [...FILTER_AGGREGATIONS]
814
+ ),
815
+ entity
816
+ );
817
+ }
818
+ }
819
+ function assertUniqueName(taken, name, kind) {
820
+ if (!name) {
821
+ throw new ValidationError(`A ${kind} needs a name.`);
822
+ }
823
+ for (const existing of taken) {
824
+ if (existing === name) {
825
+ throw new ValidationError(`'${name}' is already declared in this app.`, name);
826
+ }
827
+ }
828
+ }
829
+
830
+ // src/app/execution/submitQuery.ts
831
+ function toFilter(mapping, condition) {
832
+ if (!condition || condition.operator === "none" || condition.operator === "transform_date_drill") return void 0;
833
+ const needsValues = !["is_null", "not_null", "is_true", "is_false", "transform_pop_none"].includes(condition.operator);
834
+ if (needsValues && !condition.values?.length) return void 0;
835
+ return {
836
+ field: mapping.field,
837
+ operator: condition.operator,
838
+ values: condition.values ?? [],
839
+ ...condition.modifier ? { modifier: condition.modifier } : {},
840
+ ...mapping.aggregation ? { aggregation: mapping.aggregation } : {}
841
+ };
842
+ }
843
+ function toDateDrill(mapping, condition) {
844
+ if (condition?.operator !== "transform_date_drill") return void 0;
845
+ const transformation = condition.values?.[0];
846
+ if (typeof transformation !== "string") return void 0;
847
+ const grain = transformation.replace(/^datetrunc\s+/, "");
848
+ return { field: mapping.field, grain };
849
+ }
850
+ function toResult(query, data) {
851
+ const columns = data.columns ?? [];
852
+ const rows = (data.values ?? []).map((row) => {
853
+ const record = {};
854
+ columns.forEach((column, index) => {
855
+ record[column.name] = row[index];
856
+ });
857
+ return record;
858
+ });
859
+ const { pageSize } = query;
860
+ return {
861
+ columns,
862
+ rows,
863
+ meta: {
864
+ // Only a paged query has a page to report.
865
+ ...pageSize !== void 0 ? { page: data.meta?.page ?? query.page, pageSize: data.meta?.pageSize ?? pageSize } : {},
866
+ numRows: data.meta?.numRows ?? rows.length
867
+ },
868
+ ...data.debug ? { debug: data.debug } : {}
869
+ };
870
+ }
871
+ function buildQuery(query, mappings, selection, context) {
872
+ const mappedFilters = mappings.map((mapping) => toFilter(mapping, mapping.from.appliedCondition)).filter((filter) => filter !== void 0);
873
+ const dateDrills = mappings.map((mapping) => toDateDrill(mapping, mapping.from.appliedCondition)).filter((drill) => drill !== void 0);
874
+ const selectionFilters = selection.conditions.map((condition) => ({
875
+ field: condition.field,
876
+ operator: condition.operator,
877
+ values: condition.values
878
+ }));
879
+ const conditions = selection.expression ? [{ expr: selection.expression }] : [];
880
+ return {
881
+ dataset: query.dataset.descriptor.name,
882
+ aql: query.declaration.aql,
883
+ input: {
884
+ filters: [...mappedFilters, ...selectionFilters],
885
+ conditions,
886
+ sorts: query.sort.map((sort) => ({ field: sort.field, direction: sort.direction ?? "asc" })),
887
+ dateDrills
888
+ },
889
+ // Omitted entirely when the app declares none, so the backend applies its own default rather
890
+ // than the SDK guessing the browser's.
891
+ ...context.timezone ? { timezone: context.timezone } : {}
892
+ };
893
+ }
894
+ function buildRequest(query, mappings, selection, context) {
895
+ return {
896
+ ...buildQuery(query, mappings, selection, context),
897
+ // Omitted for a query that declares no page size, so the backend returns every row.
898
+ ...query.pageSize !== void 0 ? { page: query.page, pageSize: query.pageSize } : {},
899
+ ...context.bustCache ? { bustCache: true } : {}
900
+ };
901
+ }
902
+ function defaultExportFilename(query, title) {
903
+ const safeTitle = title?.replace(/[/\\]/g, "-").replace(/\p{Cc}/gu, "").trim();
904
+ return safeTitle ? `${safeTitle} - ${query.name}` : query.name;
905
+ }
906
+ function buildExportRequest(query, mappings, selection, context, options) {
907
+ const format2 = options.format ?? "csv";
908
+ const formatOptions = format2 === "csv" ? { bom: true, ...options.formatOptions } : options.formatOptions;
909
+ return {
910
+ ...buildQuery(query, mappings, selection, context),
911
+ format: format2,
912
+ ...formatOptions ? { formatOptions } : {},
913
+ filename: options.filename?.trim() || defaultExportFilename(query, context.title)
914
+ };
915
+ }
916
+ async function runQuery(query, mappings, selection, context, signal) {
917
+ const request = buildRequest(query, mappings, selection, context);
918
+ const data = await context.backend.submitQuery(request, signal);
919
+ return toResult(query, data);
920
+ }
921
+
922
+ // src/app/aql.ts
923
+ var LINE_SEPARATOR = String.fromCharCode(8232);
924
+ var PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
925
+ function literal(value, semanticType) {
926
+ if (value === null) return "null";
927
+ if (typeof value === "boolean") return value ? "true" : "false";
928
+ if (semanticType === "number" && typeof value === "string") return numberLiteral(value);
929
+ if (typeof value === "number") {
930
+ if (!Number.isFinite(value)) {
931
+ throw new RangeError(`Cannot express ${value} in AQL.`);
932
+ }
933
+ return Math.abs(value) >= 1e21 ? BigInt(value).toString() : String(value);
934
+ }
935
+ return JSON.stringify(value).split(LINE_SEPARATOR).join("\\u2028").split(PARAGRAPH_SEPARATOR).join("\\u2029");
936
+ }
937
+ function equals(field, value, semanticType) {
938
+ return value === null ? `is(${field}, null)` : `${field} is ${literal(value, semanticType)}`;
939
+ }
940
+ var NON_FINITE = /* @__PURE__ */ new Set(["NaN", "Infinity", "-Infinity"]);
941
+ var JSON_NUMBER = /^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/;
942
+ function numberLiteral(value) {
943
+ const match = JSON_NUMBER.exec(value);
944
+ if (!match) {
945
+ if (NON_FINITE.has(value)) throw new RangeError(`Cannot express ${value} in AQL.`);
946
+ throw new TypeError(`${JSON.stringify(value)} is not a number: a number is a string in JSON's number syntax.`);
947
+ }
948
+ const [, sign, whole, fraction = "", exponent] = match;
949
+ if (exponent === void 0) return value;
950
+ const digits = whole + fraction;
951
+ const point = whole.length + Number(exponent);
952
+ let out;
953
+ if (point <= 0) out = `0.${"0".repeat(-point)}${digits}`;
954
+ else if (point >= digits.length) out = digits + "0".repeat(point - digits.length);
955
+ else out = `${digits.slice(0, point)}.${digits.slice(point)}`;
956
+ return sign + out.replace(/^0+(?=\d)/, "");
957
+ }
958
+ function dateRange(field, start, end) {
959
+ return `${field} matches @(${start} until ${end})`;
960
+ }
961
+ function combine(fn, parts) {
962
+ if (parts.length === 0) {
963
+ throw new RangeError(`\`${fn}\` needs at least one operand.`);
964
+ }
965
+ return parts.length === 1 ? parts[0] : `${fn}(${parts.join(", ")})`;
966
+ }
967
+ var and = (parts) => combine("and", parts);
968
+ var or = (parts) => combine("or", parts);
969
+
970
+ // src/app/selection.ts
971
+ var TIMESTAMP = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2}))?)?/;
972
+ var FIXED_MS = {
973
+ week: 7 * 864e5,
974
+ day: 864e5,
975
+ hour: 36e5,
976
+ minute: 6e4
977
+ };
978
+ function parseStamp(value) {
979
+ if (typeof value !== "string") return void 0;
980
+ const match = TIMESTAMP.exec(value);
981
+ if (!match) return void 0;
982
+ return {
983
+ year: Number(match[1]),
984
+ month: Number(match[2]) - 1,
985
+ day: Number(match[3]),
986
+ hour: Number(match[4] ?? 0),
987
+ minute: Number(match[5] ?? 0),
988
+ second: Number(match[6] ?? 0),
989
+ hasTime: match[4] !== void 0
990
+ };
991
+ }
992
+ function format(ms, hasTime) {
993
+ const date = new Date(ms);
994
+ const pad = (value) => String(value).padStart(2, "0");
995
+ const day = `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}`;
996
+ if (!hasTime) return day;
997
+ return `${day} ${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`;
998
+ }
999
+ function toMs(stamp) {
1000
+ return Date.UTC(stamp.year, stamp.month, stamp.day, stamp.hour, stamp.minute, stamp.second);
1001
+ }
1002
+ function normalise(value) {
1003
+ const stamp = parseStamp(value);
1004
+ if (!stamp) return void 0;
1005
+ return format(toMs(stamp), stamp.hasTime);
1006
+ }
1007
+ function addGrain(value, grain) {
1008
+ const stamp = parseStamp(value);
1009
+ if (!stamp) return void 0;
1010
+ const {
1011
+ year,
1012
+ month,
1013
+ day,
1014
+ hour,
1015
+ minute,
1016
+ second,
1017
+ hasTime
1018
+ } = stamp;
1019
+ if (grain === "year") return format(Date.UTC(year + 1, month, day, hour, minute, second), hasTime);
1020
+ if (grain === "quarter") return format(Date.UTC(year, month + 3, day, hour, minute, second), hasTime);
1021
+ if (grain === "month") return format(Date.UTC(year, month + 1, day, hour, minute, second), hasTime);
1022
+ return format(toMs(stamp) + FIXED_MS[grain], hasTime);
1023
+ }
1024
+ function grainOf(transformation) {
1025
+ if (!transformation?.startsWith("datetrunc ")) return void 0;
1026
+ return transformation.slice("datetrunc ".length);
1027
+ }
1028
+ function distinct(values) {
1029
+ const seen = /* @__PURE__ */ new Set();
1030
+ return values.filter((value) => {
1031
+ const key = `${typeof value}:${String(value)}`;
1032
+ if (seen.has(key)) return false;
1033
+ seen.add(key);
1034
+ return true;
1035
+ });
1036
+ }
1037
+ function isContiguous(values, grain) {
1038
+ const stamps = values.map(normalise);
1039
+ if (stamps.some((stamp) => stamp === void 0)) return false;
1040
+ const sorted = stamps.slice().sort();
1041
+ for (let index = 1; index < sorted.length; index += 1) {
1042
+ if (addGrain(sorted[index - 1], grain) !== sorted[index]) return false;
1043
+ }
1044
+ return true;
1045
+ }
1046
+ function dateRange2(field, values, grain) {
1047
+ const stamps = values.map(normalise);
1048
+ if (stamps.some((stamp) => stamp === void 0)) return void 0;
1049
+ const sorted = stamps.slice().sort();
1050
+ const start = sorted[0];
1051
+ const end = addGrain(sorted[sorted.length - 1], grain);
1052
+ if (!end) return void 0;
1053
+ const contiguous = isContiguous(values, grain);
1054
+ return {
1055
+ // End-exclusive: `until` is the start of the bucket after the last one selected.
1056
+ condition: { field, operator: "matches", values: [`${start} until ${end}`] },
1057
+ admits: contiguous ? values.length : Number.POSITIVE_INFINITY,
1058
+ lossy: !contiguous
1059
+ };
1060
+ }
1061
+ function deriveOne(field, transformation, raw) {
1062
+ const present = raw.filter((value) => value !== null && value !== void 0);
1063
+ const values = distinct(present);
1064
+ if (!values.length) {
1065
+ return { condition: { field, operator: "is_null", values: [] }, admits: 1, lossy: false };
1066
+ }
1067
+ const droppedNulls = present.length !== raw.length;
1068
+ const grain = grainOf(transformation);
1069
+ if (grain) {
1070
+ const range = dateRange2(field, values, grain);
1071
+ if (range) return { ...range, lossy: range.lossy || droppedNulls };
1072
+ }
1073
+ return {
1074
+ condition: { field, operator: "is", values },
1075
+ admits: values.length,
1076
+ lossy: droppedNulls
1077
+ };
1078
+ }
1079
+ function fieldReferenceOf(column) {
1080
+ return column.modelId ? `${column.modelId}.${column.fieldName}` : column.fieldName;
1081
+ }
1082
+ function selectionExpression(columnsByAlias, aliases, rows, transformations) {
1083
+ try {
1084
+ const perRow = rows.map((row) => and(aliases.map((alias) => {
1085
+ const column = columnsByAlias.get(alias);
1086
+ const field = fieldReferenceOf(column);
1087
+ const raw = row[alias] ?? null;
1088
+ const grain = grainOf(transformations[field]);
1089
+ if (grain && typeof raw === "string") {
1090
+ const start = normalise(raw);
1091
+ const end = addGrain(raw, grain);
1092
+ if (start && end) return dateRange(field, start, end);
1093
+ }
1094
+ if (raw !== null && typeof raw !== "string" && typeof raw !== "number" && typeof raw !== "boolean") {
1095
+ throw new TypeError("no AQL spelling");
1096
+ }
1097
+ return equals(field, raw, column.semantic_type);
1098
+ })));
1099
+ return or(perRow);
1100
+ } catch {
1101
+ return void 0;
1102
+ }
1103
+ }
1104
+ function deriveSelection(query, rows, fields, transformations = {}) {
1105
+ const columns = query.result?.columns ?? [];
1106
+ const columnsByAlias = new Map(columns.map((column) => [column.name, column]));
1107
+ fields?.forEach((alias) => {
1108
+ const column = columnsByAlias.get(alias);
1109
+ if (column) {
1110
+ if (column.adhoc) {
1111
+ throw new ValidationError(
1112
+ `Query '${query.name}' cannot cross-filter on '${alias}': 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.`,
1113
+ query.name
1114
+ );
1115
+ }
1116
+ if (column.isMeasure) {
1117
+ throw new ValidationError(
1118
+ `Query '${query.name}' cannot cross-filter on '${alias}': it is a measure, and a selection conditions dimensions only.`,
1119
+ query.name
1120
+ );
1121
+ }
1122
+ return;
1123
+ }
1124
+ throw new ValidationError(
1125
+ withSuggestion(
1126
+ `Query '${query.name}' has no column '${alias}' in its last result.`,
1127
+ alias,
1128
+ [...columnsByAlias.keys()]
1129
+ ),
1130
+ query.name
1131
+ );
1132
+ });
1133
+ const dimensionLike = columns.filter((column) => !column.isMeasure);
1134
+ const selectable = dimensionLike.filter((column) => !column.adhoc).map((column) => column.name);
1135
+ const aliases = fields ? [...fields] : selectable;
1136
+ if (!rows.length || !aliases.length) return void 0;
1137
+ const conditions = [];
1138
+ let admitted = 1;
1139
+ const droppedColumns = !fields && selectable.length !== dimensionLike.length;
1140
+ let collapseLossy = false;
1141
+ aliases.forEach((alias) => {
1142
+ const column = columnsByAlias.get(alias);
1143
+ const field = fieldReferenceOf(column);
1144
+ const derived = deriveOne(field, transformations[field], rows.map((row) => row[alias]));
1145
+ conditions.push(derived.condition);
1146
+ admitted *= derived.admits;
1147
+ collapseLossy = collapseLossy || derived.lossy;
1148
+ });
1149
+ const picked = new Set(rows.map((row) => JSON.stringify(aliases.map((alias) => row[alias] ?? null))));
1150
+ if (admitted > picked.size) collapseLossy = true;
1151
+ const sorted = conditions.sort((a, b) => a.field.localeCompare(b.field));
1152
+ const base = { source: query.name, rows: [...rows], fields: aliases };
1153
+ if (collapseLossy) {
1154
+ const expression = selectionExpression(columnsByAlias, aliases, rows, transformations);
1155
+ if (expression) {
1156
+ return {
1157
+ ...base,
1158
+ conditions: [],
1159
+ expression,
1160
+ lossy: droppedColumns
1161
+ };
1162
+ }
1163
+ }
1164
+ return { ...base, conditions: sorted, lossy: droppedColumns || collapseLossy };
1165
+ }
1166
+
1167
+ // src/app/extensions.ts
1168
+ function addExtension(extensions, prototype, kind, name, factory) {
1169
+ if (name in prototype || extensions.has(name)) {
1170
+ throw new ValidationError(`Plugin '${name}' can't add '${name}' to a ${kind}: it already has one.`);
1171
+ }
1172
+ extensions.set(name, factory);
1173
+ }
1174
+ function applyExtensions(entity, extensions) {
1175
+ extensions?.forEach((factory, name) => {
1176
+ let made = false;
1177
+ let value;
1178
+ Object.defineProperty(entity, name, {
1179
+ configurable: true,
1180
+ enumerable: false,
1181
+ get() {
1182
+ if (!made) {
1183
+ value = factory(entity);
1184
+ made = true;
1185
+ }
1186
+ return value;
1187
+ }
1188
+ });
1189
+ });
1190
+ return entity;
1191
+ }
1192
+
1193
+ // src/app/app.ts
1194
+ var NO_CONDITIONS = Object.freeze([]);
1195
+ function isAbort(err) {
1196
+ return err instanceof Error && err.name === "AbortError";
1197
+ }
1198
+ function superseded(query, controller) {
1199
+ return query.controller !== controller;
1200
+ }
1201
+ function inspectError(error) {
1202
+ return {
1203
+ name: error.name,
1204
+ message: error.message,
1205
+ ...error.entity ? { entity: error.entity } : {},
1206
+ ...typeof error.status === "number" ? { status: error.status } : {},
1207
+ ...error.stack ? { stack: error.stack } : {}
1208
+ };
1209
+ }
1210
+ function inspectQuery(query) {
1211
+ const { result } = query;
1212
+ return {
1213
+ state: query.state,
1214
+ isDirty: query.isDirty,
1215
+ page: query.page,
1216
+ hasMore: query.hasMore,
1217
+ // Metadata, never rows: rows are the one unbounded thing here, and the one thing already on
1218
+ // screen in the preview beside the panel.
1219
+ columns: result ? result.columns.map((column) => ({ ...column })) : [],
1220
+ rowCount: result?.meta.numRows ?? 0,
1221
+ selectedRowCount: query.selectedRows.length,
1222
+ signature: query.signature(),
1223
+ ...query.error ? { error: inspectError(query.error) } : {},
1224
+ ...result?.debug ? { debug: { ...result.debug } } : {}
1225
+ };
1226
+ }
1227
+ function inspectControl(control) {
1228
+ const { options } = control;
1229
+ return {
1230
+ kind: control.kind,
1231
+ condition: { ...control.condition },
1232
+ ...control.appliedCondition ? { appliedCondition: { ...control.appliedCondition } } : {},
1233
+ isDirty: control.isDirty,
1234
+ ...options ? { options: [...options] } : {}
1235
+ };
1236
+ }
1237
+ function inspectSelection(selection) {
1238
+ return {
1239
+ source: selection.source,
1240
+ fields: [...selection.fields],
1241
+ rowCount: selection.rows.length,
1242
+ conditions: selection.conditions.map((condition) => ({ ...condition })),
1243
+ ...selection.expression ? { expression: selection.expression } : {},
1244
+ lossy: selection.lossy
1245
+ };
1246
+ }
1247
+ function selectionKey(selection) {
1248
+ if (!selection) return "none";
1249
+ return JSON.stringify({
1250
+ source: selection.source,
1251
+ conditions: selection.conditions,
1252
+ expression: selection.expression
1253
+ });
1254
+ }
1255
+ function toDataAppError(err, entity) {
1256
+ if (err instanceof DataAppError) return err;
1257
+ return new QueryError(err?.message ?? "The query failed.", entity, err);
1258
+ }
1259
+ function toExportError(err, entity) {
1260
+ if (err instanceof DataAppError && err.entity) return err;
1261
+ const message = err?.message || "The export failed.";
1262
+ if (err instanceof PermissionError) return new PermissionError(message, entity);
1263
+ if (err instanceof TransportError) return new TransportError(message, err.status, entity);
1264
+ if (err instanceof ValidationError) return new ValidationError(message, entity);
1265
+ return new QueryError(message, entity, err);
1266
+ }
1267
+ var App = class extends Observable {
1268
+ constructor(declaration, datasets, backend, features, extensions) {
1269
+ super();
1270
+ __publicField(this, "extensions", extensions);
1271
+ __publicField(this, "title");
1272
+ __publicField(this, "_timezone");
1273
+ __publicField(this, "datasets");
1274
+ __publicField(this, "backend");
1275
+ __publicField(this, "features");
1276
+ __publicField(this, "_queries", /* @__PURE__ */ new Map());
1277
+ __publicField(this, "_controls", /* @__PURE__ */ new Map());
1278
+ __publicField(this, "_mappings", []);
1279
+ __publicField(this, "_crossFilters", []);
1280
+ __publicField(this, "_selection");
1281
+ __publicField(this, "_appliedSelection");
1282
+ /**
1283
+ * Whether a run has ever committed the selection. Needed because `undefined` is a real applied
1284
+ * value — "nothing selected" — unlike a control's condition, which is always present.
1285
+ */
1286
+ __publicField(this, "selectionCommitted", false);
1287
+ /**
1288
+ * @internal This app's index among the frame's apps, which is how a marked element names it
1289
+ * (`data-anfra-query="1/revenue"`); 0 unless set by the instance that created it.
1290
+ */
1291
+ __publicField(this, "index", 0);
1292
+ this.title = declaration.title;
1293
+ this._timezone = declaration.timezone;
1294
+ this.datasets = datasets;
1295
+ this.backend = backend;
1296
+ this.features = features;
1297
+ }
1298
+ /* ----------------------------------------------------------------
1299
+ Declaration
1300
+ ---------------------------------------------------------------- */
1301
+ get queries() {
1302
+ return Object.fromEntries(this._queries);
1303
+ }
1304
+ get controls() {
1305
+ return Object.fromEntries(this._controls);
1306
+ }
1307
+ /** Every edge in the app's entity graph, of both kinds. Narrow on `kind`. */
1308
+ get mappings() {
1309
+ return [...this._mappings, ...this._crossFilters];
1310
+ }
1311
+ get crossFilters() {
1312
+ return this._crossFilters;
1313
+ }
1314
+ createQuery(name, declaration) {
1315
+ this.assertNameFree(name, "query");
1316
+ const query = applyExtensions(new Query(name, this, declaration), this.extensions?.query);
1317
+ this._queries.set(name, query);
1318
+ this.notify();
1319
+ return query;
1320
+ }
1321
+ createFilter(name, declaration) {
1322
+ this.assertNameFree(name, "filter");
1323
+ const dataset = declaration.dataset ? this.datasetIndex(declaration.dataset, name) : this.soleDataset(name, declaration.field);
1324
+ const filter = applyExtensions(new Filter(name, this, declaration, dataset, this.backend), this.extensions?.control);
1325
+ this._controls.set(name, filter);
1326
+ this.notify();
1327
+ return filter;
1328
+ }
1329
+ createDateDrill(name, declaration = {}) {
1330
+ if (this.features?.dateDrill === false) {
1331
+ throw new ValidationError(
1332
+ `Date drill '${name}' needs a capability this workspace has not enabled. Ask an admin to turn on \`interactive_control:date_drill\`.`,
1333
+ name
1334
+ );
1335
+ }
1336
+ this.assertNameFree(name, "date drill control");
1337
+ const control = applyExtensions(new DateDrillControl(name, this, declaration), this.extensions?.control);
1338
+ this._controls.set(name, control);
1339
+ this.notify();
1340
+ return control;
1341
+ }
1342
+ /**
1343
+ * Declares one edge. Always explicit — the field is never inferred from the control's own field,
1344
+ * because "the control happens to name a field this query also has" is exactly the coupling that
1345
+ * breaks silently when someone renames a dimension.
1346
+ *
1347
+ * There is no `unmap`: a mapping you do not want is one you do not declare.
1348
+ */
1349
+ mapControl(from, to, options) {
1350
+ if (!(from instanceof Control)) {
1351
+ throw new ValidationError(
1352
+ "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."
1353
+ );
1354
+ }
1355
+ if (this._controls.get(from.name) !== from) {
1356
+ throw new ValidationError(`Control '${from.name}' belongs to a different app.`, from.name);
1357
+ }
1358
+ if (this._queries.get(to.name) !== to) {
1359
+ throw new ValidationError(`Query '${to.name}' belongs to a different app.`, to.name);
1360
+ }
1361
+ if (options.aggregation) {
1362
+ assertValidFilterAggregation(options.aggregation, from.name);
1363
+ }
1364
+ const mapping = new Mapping(from, to, options.field, options.aggregation);
1365
+ if (this._mappings.some((existing) => existing.id === mapping.id)) {
1366
+ throw new ValidationError(`Mapping '${mapping.id}' is already declared.`, from.name);
1367
+ }
1368
+ this.assertAcyclic(mapping);
1369
+ this._mappings.push(mapping);
1370
+ this.notify();
1371
+ return mapping;
1372
+ }
1373
+ /**
1374
+ * Declares that selecting rows in `from` may cross-filter `to`.
1375
+ *
1376
+ * No field: which fields a selection conditions is decided when the reader picks rows, not here.
1377
+ * Explicit, like every other edge — there is no "cross-filter everything on this dataset",
1378
+ * because an author who adds a sixth query should not silently acquire five new edges.
1379
+ *
1380
+ * Declaring both directions is normal and is not a cycle: one selection is live at a time and
1381
+ * never cascades, so `a -> b` and `b -> a` simply means either chart may drive the other.
1382
+ */
1383
+ mapCrossFilter(from, to) {
1384
+ if (!(from instanceof Query) || !(to instanceof Query)) {
1385
+ throw new ValidationError(
1386
+ "mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field })."
1387
+ );
1388
+ }
1389
+ if (this._queries.get(from.name) !== from) {
1390
+ throw new ValidationError(`Query '${from.name}' belongs to a different app.`, from.name);
1391
+ }
1392
+ if (this._queries.get(to.name) !== to) {
1393
+ throw new ValidationError(`Query '${to.name}' belongs to a different app.`, to.name);
1394
+ }
1395
+ if (from === to) {
1396
+ throw new ValidationError(
1397
+ `Query '${from.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.`,
1398
+ from.name
1399
+ );
1400
+ }
1401
+ if (from.declaration.dataset !== to.declaration.dataset) {
1402
+ throw new ValidationError(
1403
+ `Cross-filter '${from.name}' -> '${to.name}' spans two datasets ('${from.declaration.dataset}' and '${to.declaration.dataset}'). A selection carries field references, which mean nothing outside the dataset that resolved them.`,
1404
+ from.name
1405
+ );
1406
+ }
1407
+ const edge = new CrossFilter(from, to);
1408
+ if (this._crossFilters.some((existing) => existing.id === edge.id)) {
1409
+ throw new ValidationError(`Cross-filter '${edge.id}' is already declared.`, from.name);
1410
+ }
1411
+ this._crossFilters.push(edge);
1412
+ this.notify();
1413
+ return edge;
1414
+ }
1415
+ /* ----------------------------------------------------------------
1416
+ Selection
1417
+ ---------------------------------------------------------------- */
1418
+ /**
1419
+ * What the reader has picked, if anything.
1420
+ *
1421
+ * Held here rather than on a query because it belongs to none of them: picking rows in a second
1422
+ * query replaces it. Every control still owns its own condition — this is the one piece of
1423
+ * reader state with no natural owner.
1424
+ */
1425
+ get selection() {
1426
+ return this._selection;
1427
+ }
1428
+ /** The selection the cross-filtered queries last ran with. */
1429
+ get appliedSelection() {
1430
+ return this._appliedSelection;
1431
+ }
1432
+ clearSelection() {
1433
+ if (!this._selection) return;
1434
+ this._selection = void 0;
1435
+ this.notify();
1436
+ }
1437
+ /** Part of the declaration, not the environment. Changing it makes every query dirty. */
1438
+ setTimezone(timezone) {
1439
+ this._timezone = timezone;
1440
+ this.notify();
1441
+ }
1442
+ get timezone() {
1443
+ return this._timezone;
1444
+ }
1445
+ /* ----------------------------------------------------------------
1446
+ AppContext
1447
+ ---------------------------------------------------------------- */
1448
+ datasetIndex(uname, entity) {
1449
+ return resolveDataset(this.datasets, uname, entity);
1450
+ }
1451
+ mappingsTo(queryName) {
1452
+ return this._mappings.filter((mapping) => mapping.to.name === queryName);
1453
+ }
1454
+ /** The expression form, set only when the structured conditions would have been lossy. */
1455
+ selectionExpressionFor(queryName, phase) {
1456
+ return this.selectionFor(queryName, phase)?.expression;
1457
+ }
1458
+ selectionFor(queryName, phase) {
1459
+ const selection = phase === "pending" ? this._selection : this._appliedSelection;
1460
+ if (!selection) return void 0;
1461
+ if (selection.source === queryName) return void 0;
1462
+ const reached = this._crossFilters.some(
1463
+ (edge) => edge.from.name === selection.source && edge.to.name === queryName
1464
+ );
1465
+ return reached ? selection : void 0;
1466
+ }
1467
+ selectionConditionsFor(queryName, phase) {
1468
+ const selection = phase === "pending" ? this._selection : this._appliedSelection;
1469
+ if (!selection) return NO_CONDITIONS;
1470
+ if (selection.source === queryName) return NO_CONDITIONS;
1471
+ const reached = this._crossFilters.some(
1472
+ (edge) => edge.from.name === selection.source && edge.to.name === queryName
1473
+ );
1474
+ return reached ? selection.conditions : NO_CONDITIONS;
1475
+ }
1476
+ /**
1477
+ * The transformation each of this query's fields is currently drawn at, from the date drills
1478
+ * mapped onto it.
1479
+ *
1480
+ * `appliedCondition`, not `condition`: a drill the reader has changed but not applied has not
1481
+ * rebucketed anything yet, so the rows they are clicking still belong to the applied grain.
1482
+ */
1483
+ drillTransformations(query) {
1484
+ const byField = {};
1485
+ this._mappings.forEach((mapping) => {
1486
+ if (mapping.to !== query) return;
1487
+ const condition = mapping.from.appliedCondition;
1488
+ if (condition?.operator !== "transform_date_drill") return;
1489
+ const [value] = condition.values ?? [];
1490
+ if (typeof value === "string") byField[mapping.field] = value;
1491
+ });
1492
+ return byField;
1493
+ }
1494
+ select(query, rows, fields) {
1495
+ if (this._queries.get(query.name) !== query) {
1496
+ throw new ValidationError(`Query '${query.name}' belongs to a different app.`, query.name);
1497
+ }
1498
+ const selection = deriveSelection(query, rows, fields, this.drillTransformations(query));
1499
+ if (selection?.lossy) {
1500
+ console.warn(
1501
+ `[anfra-sdk] The selection in '${query.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.`
1502
+ );
1503
+ }
1504
+ this._selection = selection;
1505
+ this.notify();
1506
+ }
1507
+ /* ----------------------------------------------------------------
1508
+ Execution
1509
+ ---------------------------------------------------------------- */
1510
+ /** True when a control or the selection has changed since the queries reading it last ran. */
1511
+ get hasChanges() {
1512
+ return [...this._controls.values()].some((control) => control.isDirty) || this.isSelectionDirty;
1513
+ }
1514
+ /**
1515
+ * False before the first execution, matching `Control.isDirty`: with nothing applied there is
1516
+ * nothing to differ from, so a selection restored at startup is not an unapplied change.
1517
+ */
1518
+ get isSelectionDirty() {
1519
+ if (!this.selectionCommitted) return false;
1520
+ return selectionKey(this._selection) !== selectionKey(this._appliedSelection);
1521
+ }
1522
+ /**
1523
+ * Runs every query that would produce something new, and resolves with which succeeded and which
1524
+ * failed. Never rejects: a failed query sets its own `state` and `error`, because one broken
1525
+ * query must not blank the other four. See docs/adr/0002.
1526
+ */
1527
+ async execute(options = {}) {
1528
+ const targets = [...this._queries.values()].filter((query) => query.shouldRun(options.force));
1529
+ this._controls.forEach((control) => control.commit());
1530
+ this._appliedSelection = this._selection;
1531
+ this.selectionCommitted = true;
1532
+ targets.forEach((query) => {
1533
+ query.controller?.abort();
1534
+ query.resetPage();
1535
+ });
1536
+ const context = {
1537
+ backend: this.backend,
1538
+ timezone: this._timezone,
1539
+ bustCache: options.bustCache
1540
+ };
1541
+ const succeeded = [];
1542
+ const failed = [];
1543
+ await Promise.all(targets.map(async (query) => {
1544
+ const controller = new AbortController();
1545
+ query.controller = controller;
1546
+ const signature = query.signature();
1547
+ query.markExecuting();
1548
+ try {
1549
+ const result = await runQuery(
1550
+ query,
1551
+ this.mappingsTo(query.name),
1552
+ {
1553
+ conditions: this.selectionConditionsFor(query.name, "applied"),
1554
+ expression: this.selectionExpressionFor(query.name, "applied")
1555
+ },
1556
+ context,
1557
+ controller.signal
1558
+ );
1559
+ if (superseded(query, controller)) return;
1560
+ query.markSuccess(result, signature, false);
1561
+ succeeded.push(query.name);
1562
+ } catch (err) {
1563
+ if (superseded(query, controller)) return;
1564
+ if (isAbort(err)) return;
1565
+ query.markError(toDataAppError(err, query.name));
1566
+ failed.push(query.name);
1567
+ } finally {
1568
+ if (query.controller === controller) query.controller = void 0;
1569
+ }
1570
+ }));
1571
+ return { succeeded, failed };
1572
+ }
1573
+ /** Re-runs everything and asks the server to skip its result cache. */
1574
+ async refresh() {
1575
+ return this.execute({ force: true, bustCache: true });
1576
+ }
1577
+ abort() {
1578
+ this._queries.forEach((query) => query.abort());
1579
+ }
1580
+ /** @internal Backs `query.fetchMore()`. Rejects, so an explicit page request reports its failure. */
1581
+ async fetchPage(query) {
1582
+ const controller = new AbortController();
1583
+ query.controller = controller;
1584
+ const signature = query.signature();
1585
+ query.markExecuting();
1586
+ try {
1587
+ const result = await runQuery(
1588
+ query,
1589
+ this.mappingsTo(query.name),
1590
+ {
1591
+ conditions: this.selectionConditionsFor(query.name, "applied"),
1592
+ expression: this.selectionExpressionFor(query.name, "applied")
1593
+ },
1594
+ {
1595
+ backend: this.backend,
1596
+ timezone: this._timezone
1597
+ },
1598
+ controller.signal
1599
+ );
1600
+ query.markSuccess(result, signature, true);
1601
+ } catch (err) {
1602
+ query.rewindPage();
1603
+ if (isAbort(err)) return;
1604
+ const error = toDataAppError(err, query.name);
1605
+ query.markError(error);
1606
+ throw error;
1607
+ } finally {
1608
+ if (query.controller === controller) query.controller = void 0;
1609
+ }
1610
+ }
1611
+ /**
1612
+ * @internal Backs the `export` plugin's `query.export()`. Built from the applied state, as
1613
+ * `fetchPage` is, so the file holds what the reader is looking at, every row of it. `send` makes
1614
+ * the export (the plugin's call); this touches nothing on the query.
1615
+ */
1616
+ async exportQuery(query, options, send) {
1617
+ const request = buildExportRequest(
1618
+ query,
1619
+ this.mappingsTo(query.name),
1620
+ {
1621
+ conditions: this.selectionConditionsFor(query.name, "applied"),
1622
+ expression: this.selectionExpressionFor(query.name, "applied")
1623
+ },
1624
+ { backend: this.backend, timezone: this._timezone, title: this.title },
1625
+ options
1626
+ );
1627
+ try {
1628
+ return await send(request, options.signal ?? new AbortController().signal);
1629
+ } catch (err) {
1630
+ if (isAbort(err)) throw err;
1631
+ throw toExportError(err, query.name);
1632
+ }
1633
+ }
1634
+ /* ----------------------------------------------------------------
1635
+ Serialisation
1636
+ ---------------------------------------------------------------- */
1637
+ /**
1638
+ * The declaration and nothing else — no datasets, no backend, no reader state. This is the
1639
+ * shape a persisted Data App record will take, which is why mapping edges are already generic.
1640
+ */
1641
+ toJSON() {
1642
+ const byKind = (kind) => Object.fromEntries(
1643
+ [...this._controls.entries()].filter(([, control]) => control.kind === kind).map(([name, control]) => [name, control.toJSON()])
1644
+ );
1645
+ return {
1646
+ ...this.title ? { title: this.title } : {},
1647
+ ...this._timezone ? { timezone: this._timezone } : {},
1648
+ queries: Object.fromEntries([...this._queries.entries()].map(([name, q]) => [name, q.toJSON()])),
1649
+ filters: byKind("filter"),
1650
+ dateDrills: byKind("dateDrill"),
1651
+ mappings: [
1652
+ ...this._mappings.map((mapping) => mapping.toJSON()),
1653
+ ...this._crossFilters.map((edge) => edge.toJSON())
1654
+ ]
1655
+ };
1656
+ }
1657
+ /**
1658
+ * Everything a host needs to render this app, as plain data.
1659
+ *
1660
+ * Separate from `toJSON()` rather than an option on it: `toJSON()` is the declaration and is the
1661
+ * shape a persisted app takes, while this is a reading taken at a moment and already behind by
1662
+ * the time anyone sees it. Written out field by field because the live objects cannot cross a
1663
+ * port — getters are not cloned, and `Query.controller` holds an `AbortController` for exactly
1664
+ * as long as someone is likely to be watching. See docs/adr/0007.
1665
+ */
1666
+ toInspectJSON() {
1667
+ return {
1668
+ ...this.title ? { title: this.title } : {},
1669
+ ...this._timezone ? { timezone: this._timezone } : {},
1670
+ hasChanges: this.hasChanges,
1671
+ declaration: this.toJSON(),
1672
+ queries: Object.fromEntries(
1673
+ [...this._queries.entries()].map(([name, query]) => [name, inspectQuery(query)])
1674
+ ),
1675
+ controls: Object.fromEntries(
1676
+ [...this._controls.entries()].map(([name, control]) => [name, inspectControl(control)])
1677
+ ),
1678
+ ...this._selection ? { selection: inspectSelection(this._selection) } : {},
1679
+ ...this._appliedSelection ? { appliedSelection: inspectSelection(this._appliedSelection) } : {}
1680
+ };
1681
+ }
1682
+ /**
1683
+ * Bring an entity's marked elements into view: scroll to the first, show the overlay on all for
1684
+ * a moment. False, and nothing done, when the document has none marked with it (or there is no
1685
+ * document at all). Used by `Query.locate()` and `Control.locate()`, and by the bootstrap for a
1686
+ * host's locate-by-entity.
1687
+ */
1688
+ locate(kind, name) {
1689
+ const doc = globalThis.document;
1690
+ if (!doc) return false;
1691
+ const elements = markersFor(doc, kind, this.index, name);
1692
+ if (!elements.length) return false;
1693
+ scrollTo(elements[0]);
1694
+ overlayFor(doc).flash(elements, {
1695
+ kind,
1696
+ name,
1697
+ ...elements.length > 1 ? { note: `in ${elements.length} places` } : {}
1698
+ });
1699
+ return true;
1700
+ }
1701
+ /* ----------------------------------------------------------------
1702
+ Internals
1703
+ ---------------------------------------------------------------- */
1704
+ assertNameFree(name, kind) {
1705
+ assertUniqueName([...this._queries.keys(), ...this._controls.keys()], name, kind);
1706
+ }
1707
+ /**
1708
+ * A field-backed filter usually lives in an app with one dataset, so requiring `dataset` on every
1709
+ * filter would be noise. With several, it has to be said.
1710
+ */
1711
+ soleDataset(entity, field) {
1712
+ if (!field) return void 0;
1713
+ const unames = Object.keys(this.datasets);
1714
+ if (unames.length === 1) return this.datasets[unames[0]];
1715
+ throw new ValidationError(
1716
+ unames.length ? `Filter '${entity}' names a field but the environment has ${unames.length} datasets. Say which one: ${unames.join(", ")}.` : `Filter '${entity}' names a field but the environment has no datasets.`,
1717
+ entity
1718
+ );
1719
+ }
1720
+ assertAcyclic(candidate) {
1721
+ const edges = [...this._mappings, candidate];
1722
+ const outgoing = /* @__PURE__ */ new Map();
1723
+ edges.forEach((edge) => {
1724
+ const key = edge.from.name;
1725
+ outgoing.set(key, [...outgoing.get(key) ?? [], edge.to.name]);
1726
+ });
1727
+ const visiting = /* @__PURE__ */ new Set();
1728
+ const done = /* @__PURE__ */ new Set();
1729
+ const walk = (node) => {
1730
+ if (visiting.has(node)) return true;
1731
+ if (done.has(node)) return false;
1732
+ visiting.add(node);
1733
+ const cycle = (outgoing.get(node) ?? []).some(walk);
1734
+ visiting.delete(node);
1735
+ done.add(node);
1736
+ return cycle;
1737
+ };
1738
+ if ([...outgoing.keys()].some(walk)) {
1739
+ throw new ValidationError(
1740
+ `Mapping '${candidate.id}' would make the app's mappings cyclic.`,
1741
+ candidate.from.name
1742
+ );
1743
+ }
1744
+ }
1745
+ };
1746
+
1747
+ // src/app/sdk.ts
1748
+ var InstalledPlugins = class {
1749
+ constructor(plugins) {
1750
+ /** Each plugin's name and version, in the order the host installed them. */
1751
+ __publicField(this, "list");
1752
+ this.list = Object.freeze(plugins.map(({ name, version: version2 }) => Object.freeze({ name, version: version2 })));
1753
+ }
1754
+ /**
1755
+ * Whether the host installed the plugin named `name`. To call a plugin's member, check the member
1756
+ * itself (`if (Anfra.render)`, `query.export?.()`): TypeScript narrows that, not this.
1757
+ */
1758
+ has(name) {
1759
+ return this.list.some((plugin) => plugin.name === name);
1760
+ }
1761
+ /** The installed plugin's version, or undefined. */
1762
+ version(name) {
1763
+ return this.list.find((plugin) => plugin.name === name)?.version;
1764
+ }
1765
+ };
1766
+ var VERSION = version;
1767
+ var Sdk = class {
1768
+ constructor(environment) {
1769
+ __publicField(this, "version", VERSION);
1770
+ __publicField(this, "_apps", []);
1771
+ /**
1772
+ * Readable on purpose: an agent can check a field name against the real schema before writing
1773
+ * it. This is the useful half of runtime introspection *for an author*, which is why there is
1774
+ * still no `describe()` on this surface. Describing a running app is a separate thing, addressed
1775
+ * to the host rather than the author — see `App.toInspectJSON` and docs/adr/0007.
1776
+ */
1777
+ __publicField(this, "datasets");
1778
+ /**
1779
+ * Who the app is running as. Provisioned like `datasets` rather than fetched, so author code
1780
+ * needs no await and no null check to greet someone or hide a control they cannot use.
1781
+ */
1782
+ __publicField(this, "user");
1783
+ __publicField(this, "indices");
1784
+ __publicField(this, "backend");
1785
+ /**
1786
+ * The plugins the host installed. A plugin adds its API under its own name (`Anfra.lineage`,
1787
+ * `query.export`), and a plugin that isn't installed adds nothing: check `Anfra.plugins.has(name)`
1788
+ * before using an optional one.
1789
+ */
1790
+ __publicField(this, "plugins");
1791
+ __publicField(this, "features");
1792
+ /** @internal What plugins add to each query and control, by plugin name (the kernel's `provideOn*`). */
1793
+ __publicField(this, "extensions", { query: /* @__PURE__ */ new Map(), control: /* @__PURE__ */ new Map() });
1794
+ if (!environment?.datasets) {
1795
+ throw new ValidationError(
1796
+ "No datasets provided. The host must call createSdk({ datasets }) before an app can be declared."
1797
+ );
1798
+ }
1799
+ if (!environment.user) {
1800
+ throw new ValidationError(
1801
+ "No user provided. The host must call createSdk({ user }) before an app can be declared."
1802
+ );
1803
+ }
1804
+ if (!environment.backend) {
1805
+ throw new ValidationError(
1806
+ "No backend provided. The host must call createSdk({ backend }) before an app can run a query."
1807
+ );
1808
+ }
1809
+ this.datasets = Object.freeze({ ...environment.datasets });
1810
+ this.user = Object.freeze({
1811
+ ...environment.user,
1812
+ permissions: Object.freeze({ ...environment.user.permissions })
1813
+ });
1814
+ this.indices = Object.fromEntries(
1815
+ Object.entries(environment.datasets).map(([uname, descriptor]) => [
1816
+ uname,
1817
+ new DatasetIndex(descriptor)
1818
+ ])
1819
+ );
1820
+ this.backend = environment.backend;
1821
+ this.features = Object.freeze({ ...environment.features });
1822
+ this.plugins = new InstalledPlugins(environment.plugins ?? []);
1823
+ }
1824
+ createApp(declaration = {}) {
1825
+ const app = new App(declaration, this.indices, this.backend, this.features, this.extensions);
1826
+ app.index = this._apps.length;
1827
+ this._apps.push(app);
1828
+ return app;
1829
+ }
1830
+ /**
1831
+ * Every app this instance has built, for a host rendering an inspection panel.
1832
+ *
1833
+ * Not addressed to author code, which already holds whatever it created — this exists because the
1834
+ * bootstrap does not, and cannot otherwise reach an app at all. Holding them means they outlive
1835
+ * the author's own reference; the frame is discarded and rebuilt on every Run, which is what
1836
+ * bounds it. See docs/adr/0007.
1837
+ */
1838
+ get apps() {
1839
+ return this._apps;
1840
+ }
1841
+ };
1842
+ function createSdk(environment) {
1843
+ return new Sdk(environment);
1844
+ }
1845
+
1846
+ // src/app/sandbox.ts
1847
+ var SANDBOX_GLOBAL = "Anfra";
1848
+ function installSandbox(sdk, target = globalThis) {
1849
+ const previous = target[SANDBOX_GLOBAL];
1850
+ const existed = SANDBOX_GLOBAL in target;
1851
+ target[SANDBOX_GLOBAL] = sdk;
1852
+ return () => {
1853
+ if (existed) {
1854
+ target[SANDBOX_GLOBAL] = previous;
1855
+ } else {
1856
+ delete target[SANDBOX_GLOBAL];
1857
+ }
1858
+ };
1859
+ }
1860
+
1861
+ // src/app/kernel.ts
1862
+ var BODY_CALL = "anfra.body";
1863
+ var BODY_GLOBAL = "__anfraBodyExports";
1864
+ var KERNEL_ERRORS = {
1865
+ DataAppError,
1866
+ ValidationError,
1867
+ QueryError,
1868
+ PermissionError,
1869
+ TransportError
1870
+ };
1871
+ function runBody(win, code) {
1872
+ const target = win;
1873
+ const script = win.document.createElement("script");
1874
+ script.textContent = `(function () { var __anfraBody;
1875
+ ${code}
1876
+ ;self[${JSON.stringify(BODY_GLOBAL)}] = __anfraBody; })();`;
1877
+ (win.document.head ?? win.document.documentElement).appendChild(script);
1878
+ script.remove();
1879
+ const exported = target[BODY_GLOBAL];
1880
+ delete target[BODY_GLOBAL];
1881
+ if (!exported) throw new ValidationError("The host sent a plugin body that did not run.");
1882
+ return exported.default ?? exported;
1883
+ }
1884
+ function createKernel(plugin, shared, entities) {
1885
+ const { window: win, sdk, endpoint } = shared;
1886
+ let loading;
1887
+ return {
1888
+ plugin,
1889
+ window: win,
1890
+ sdk,
1891
+ errors: KERNEL_ERRORS,
1892
+ // Made on first use: a frame nobody inspects or locates in draws no layer at all.
1893
+ get overlay() {
1894
+ return overlayFor(win.document);
1895
+ },
1896
+ structure: () => buildStructure(win.document, sdk.apps),
1897
+ call: (name, request, signal) => endpoint.call(name, request ?? null, signal),
1898
+ emit: (name, payload) => endpoint.emit(`${plugin}.${name}`, payload ?? null),
1899
+ handle(name, handler) {
1900
+ shared.handlers.set(`${plugin}.${name}`, handler);
1901
+ },
1902
+ on(name, listener) {
1903
+ const full = `${plugin}.${name}`;
1904
+ if (!shared.listeners.has(full)) shared.listeners.set(full, /* @__PURE__ */ new Set());
1905
+ shared.listeners.get(full).add(listener);
1906
+ },
1907
+ onApp(listener) {
1908
+ shared.appListeners.add(listener);
1909
+ sdk.apps.forEach((app) => listener(app));
1910
+ },
1911
+ provide(api) {
1912
+ if (plugin in sdk) throw new ValidationError(`Plugin '${plugin}' can't add a member Anfra already has.`);
1913
+ Object.defineProperty(sdk, plugin, { value: api, enumerable: true });
1914
+ },
1915
+ provideOnQuery: (factory) => addExtension(sdk.extensions.query, entities.Query.prototype, "query", plugin, factory),
1916
+ provideOnControl: (factory) => addExtension(sdk.extensions.control, entities.Control.prototype, "control", plugin, factory),
1917
+ layer: () => layerRoot(win.document, plugin),
1918
+ body() {
1919
+ loading ?? (loading = endpoint.call(BODY_CALL, { plugin }).then((code) => runBody(win, code)).catch((err) => {
1920
+ loading = void 0;
1921
+ throw err;
1922
+ }));
1923
+ return loading;
1924
+ }
1925
+ };
1926
+ }
1927
+
1928
+ // src/app/bootstrap.ts
1929
+ function bootstrap(win, setups = []) {
1930
+ const element = win.document.getElementById(PROVISION_ELEMENT_ID);
1931
+ if (!element?.textContent) throw new Error("anfra: this frame was not provisioned by a host.");
1932
+ const provision = JSON.parse(element.textContent);
1933
+ const post = (message) => win.parent.postMessage(message, provision.hostOrigin);
1934
+ const handlers = /* @__PURE__ */ new Map();
1935
+ const listeners = /* @__PURE__ */ new Map();
1936
+ const endpoint = createEndpoint(post, {
1937
+ answer: async (name, request, signal) => {
1938
+ const handler = handlers.get(name);
1939
+ if (!handler) throw new TransportError(`Nothing in this frame answers '${name}'.`);
1940
+ return handler(request, signal);
1941
+ },
1942
+ event: (name, payload) => {
1943
+ listeners.get(name)?.forEach((listener) => {
1944
+ try {
1945
+ listener(payload);
1946
+ } catch {
1947
+ }
1948
+ });
1949
+ }
1950
+ });
1951
+ win.addEventListener("message", (event) => {
1952
+ if (event.source !== win.parent) return;
1953
+ endpoint.receive(event.data);
1954
+ });
1955
+ const backend = {
1956
+ submitQuery: (request, signal) => endpoint.call("core.submitQuery", request, signal).then((result) => {
1957
+ if (result.debug?.executedAt) result.debug.executedAt = new Date(result.debug.executedAt);
1958
+ return result;
1959
+ }),
1960
+ fieldSuggestions: (request, signal) => endpoint.call("core.fieldSuggestions", request, signal)
1961
+ };
1962
+ const instance = createSdk({
1963
+ datasets: provision.datasets,
1964
+ user: provision.user,
1965
+ backend,
1966
+ plugins: provision.plugins ?? []
1967
+ });
1968
+ const appListeners = /* @__PURE__ */ new Set();
1969
+ const createApp = instance.createApp.bind(instance);
1970
+ instance.createApp = (declaration) => {
1971
+ const app = createApp(declaration);
1972
+ appListeners.forEach((listener) => {
1973
+ try {
1974
+ listener(app);
1975
+ } catch {
1976
+ }
1977
+ });
1978
+ return app;
1979
+ };
1980
+ const shared = {
1981
+ window: win,
1982
+ sdk: instance,
1983
+ endpoint,
1984
+ handlers,
1985
+ listeners,
1986
+ appListeners
1987
+ };
1988
+ for (const [name, setup] of setups) {
1989
+ if (typeof setup !== "function") continue;
1990
+ try {
1991
+ setup(createKernel(name, shared, { Query, Control }));
1992
+ } catch (err) {
1993
+ win.console?.error(`anfra: plugin '${name}' failed to set up:`, err);
1994
+ }
1995
+ }
1996
+ installSandbox(instance, win);
1997
+ post({ type: "anfra:ready" });
1998
+ }
1999
+
2000
+ export {
2001
+ Query,
2002
+ Control,
2003
+ Filter,
2004
+ DateDrillControl,
2005
+ Mapping,
2006
+ CrossFilter,
2007
+ ATTR,
2008
+ parseRef,
2009
+ buildStructure,
2010
+ LAYER_ATTRIBUTE,
2011
+ OVERLAY_ID,
2012
+ App,
2013
+ InstalledPlugins,
2014
+ VERSION,
2015
+ Sdk,
2016
+ createSdk,
2017
+ SANDBOX_GLOBAL,
2018
+ installSandbox,
2019
+ bootstrap
2020
+ };