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