@holistics/anfra-sdk 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +5 -0
  2. package/dist/api.d.ts +11 -8
  3. package/dist/api.js +45 -22
  4. package/dist/app.d.ts +5 -5
  5. package/dist/app.js +4 -3
  6. package/dist/{bootstrap-DHU2haC5.d.ts → bootstrap-BxBqFhgm.d.ts} +279 -27
  7. package/dist/build.d.ts +2 -2
  8. package/dist/{chunk-32566ZNE.js → chunk-2TTGSNHA.js} +1 -1
  9. package/dist/{chunk-H52PO7MP.js → chunk-33HI2ODM.js} +25 -0
  10. package/dist/chunk-4UEESYHH.js +32 -0
  11. package/dist/{chunk-4TXKXLWK.js → chunk-7I2HXY72.js} +1 -1
  12. package/dist/{chunk-KKSOTHP4.js → chunk-7NZOMBYE.js} +1 -1
  13. package/dist/{chunk-DITKCHFQ.js → chunk-CLXZMA5D.js} +1 -1
  14. package/dist/{chunk-GBXK7F2V.js → chunk-D7DIJRAC.js} +14 -1
  15. package/dist/{chunk-FTTVLHNN.js → chunk-E3Q3FRKQ.js} +1 -1
  16. package/dist/{chunk-SXKJQU7A.js → chunk-GPBYPSWK.js} +22 -36
  17. package/dist/{chunk-T5T76SAR.js → chunk-IHRNKDMO.js} +830 -265
  18. package/dist/{chunk-EIPHDMZ7.js → chunk-UWRQXPPG.js} +69 -24
  19. package/dist/common.d.ts +3 -3
  20. package/dist/{data-ESPFZ5IM.js → data-SZDYO55C.js} +7 -5
  21. package/dist/{declaration-RYRBX7PH.js → declaration-GYV6OUR3.js} +5 -3
  22. package/dist/{errors-189T_Mnc.d.ts → errors-DR05L6-y.d.ts} +1 -1
  23. package/dist/host.d.ts +2 -2
  24. package/dist/host.js +29 -6
  25. package/dist/{menu-Cam-hOdJ.d.ts → menu-CuTKq-dC.d.ts} +2 -1
  26. package/dist/{overview-AWPXJACF.js → overview-KOQJNG2Y.js} +28 -13
  27. package/dist/{plugin-rRd-zHGt.d.ts → plugin-BIcighnC.d.ts} +7 -2
  28. package/dist/plugins.d.ts +1 -7
  29. package/dist/plugins.js +53 -17
  30. package/dist/{queries-FWMX7H5Z.js → queries-BWKWZQMG.js} +70 -17
  31. package/dist/{structure-VFRJFC4C.js → structure-JO4YZHKZ.js} +5 -3
  32. package/dist/{tab-XL2HS5W4.js → tab-QPHE7YUQ.js} +3 -3
  33. package/dist/testing.d.ts +2 -1
  34. package/dist/testing.js +8 -7
  35. package/dist/{types-N0V9n38H.d.ts → types-C_-1rgj2.d.ts} +781 -123
  36. package/package.json +1 -1
@@ -2,11 +2,10 @@ import {
2
2
  FILTER_AGGREGATIONS
3
3
  } from "./chunk-XIUFHRZE.js";
4
4
  import {
5
- createEndpoint,
6
5
  eventShortcut,
7
6
  isTyping,
8
7
  normalizeShortcut
9
- } from "./chunk-SXKJQU7A.js";
8
+ } from "./chunk-4UEESYHH.js";
10
9
  import {
11
10
  DEFAULT_TOKENS,
12
11
  PROVISION_ELEMENT_ID,
@@ -15,7 +14,11 @@ import {
15
14
  } from "./chunk-RXPNL7UR.js";
16
15
  import {
17
16
  version
18
- } from "./chunk-FTTVLHNN.js";
17
+ } from "./chunk-E3Q3FRKQ.js";
18
+ import {
19
+ abortError,
20
+ createEndpoint
21
+ } from "./chunk-GPBYPSWK.js";
19
22
  import {
20
23
  DataAppError,
21
24
  MESSAGE_LIMIT,
@@ -132,14 +135,180 @@ var Observable = class {
132
135
  }
133
136
  };
134
137
 
138
+ // src/app/suggest.ts
139
+ function editDistance(a, b) {
140
+ const rows = a.length + 1;
141
+ const cols = b.length + 1;
142
+ let prev = Array.from({ length: cols }, (_, j) => j);
143
+ for (let i = 1; i < rows; i++) {
144
+ const curr = [i];
145
+ for (let j = 1; j < cols; j++) {
146
+ curr[j] = Math.min(
147
+ prev[j] + 1,
148
+ curr[j - 1] + 1,
149
+ prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
150
+ );
151
+ }
152
+ prev = curr;
153
+ }
154
+ return prev[cols - 1];
155
+ }
156
+ function suggest(value, candidates) {
157
+ let best;
158
+ let bestDistance = Infinity;
159
+ candidates.forEach((candidate) => {
160
+ const distance = editDistance(value.toLowerCase(), candidate.toLowerCase());
161
+ if (distance < bestDistance) {
162
+ bestDistance = distance;
163
+ best = candidate;
164
+ }
165
+ });
166
+ const threshold = Math.max(2, Math.floor(value.length / 3));
167
+ return bestDistance <= threshold ? best : void 0;
168
+ }
169
+ function withSuggestion(message, value, candidates) {
170
+ const hint = suggest(value, candidates);
171
+ return hint ? `${message} Did you mean '${hint}'?` : message;
172
+ }
173
+
174
+ // src/app/validation.ts
175
+ var DatasetIndex = class {
176
+ constructor(descriptor) {
177
+ __publicField(this, "descriptor");
178
+ __publicField(this, "fields", /* @__PURE__ */ new Map());
179
+ __publicField(this, "references");
180
+ this.descriptor = descriptor;
181
+ descriptor.data_models.forEach((model) => {
182
+ model.fields.forEach((field) => {
183
+ const modelName = String(model.name);
184
+ this.fields.set(`${modelName}.${field.name}`, {
185
+ modelName,
186
+ fieldName: field.name,
187
+ isMetric: false,
188
+ type: field.type,
189
+ label: field.label ?? field.name
190
+ });
191
+ });
192
+ });
193
+ descriptor.metrics.forEach((metric) => {
194
+ this.fields.set(metric.name, {
195
+ fieldName: metric.name,
196
+ isMetric: true,
197
+ type: metric.type,
198
+ label: metric.label ?? metric.name
199
+ });
200
+ });
201
+ this.references = [...this.fields.keys()];
202
+ }
203
+ resolve(reference, entity) {
204
+ const field = this.fields.get(reference);
205
+ if (field) return field;
206
+ throw new ValidationError(
207
+ withSuggestion(
208
+ `Unknown field '${reference}' on dataset '${this.descriptor.name}'.`,
209
+ reference,
210
+ this.references
211
+ ),
212
+ entity
213
+ );
214
+ }
215
+ };
216
+ function resolveDataset(datasets, uname, entity) {
217
+ const dataset = datasets[uname];
218
+ if (dataset) return dataset;
219
+ throw new ValidationError(
220
+ withSuggestion(
221
+ `Unknown dataset '${uname}'.`,
222
+ uname,
223
+ Object.keys(datasets)
224
+ ),
225
+ entity
226
+ );
227
+ }
228
+ function assertValidFilterAggregation(aggregation, entity) {
229
+ if (!FILTER_AGGREGATIONS.includes(aggregation)) {
230
+ throw new ValidationError(
231
+ withSuggestion(
232
+ `Invalid filter aggregation '${aggregation}'.`,
233
+ aggregation,
234
+ [...FILTER_AGGREGATIONS]
235
+ ),
236
+ entity
237
+ );
238
+ }
239
+ }
240
+ function assertUniqueName(taken, name, kind) {
241
+ if (!name) {
242
+ throw new ValidationError(`A ${kind} needs a name.`);
243
+ }
244
+ for (const existing of taken) {
245
+ if (existing === name) {
246
+ throw new ValidationError(`'${name}' is already declared in this app.`, name);
247
+ }
248
+ }
249
+ }
250
+ var DURATION_UNITS = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
251
+ var MAX_CACHE_DURATION_MS = 168 * 36e5;
252
+ function parseDuration(text) {
253
+ if (text === "0") return 0;
254
+ const part = /(\d+(?:\.\d*)?|\.\d+)(ns|us|µs|ms|s|m|h)/y;
255
+ let total = 0;
256
+ let end = 0;
257
+ for (let match = part.exec(text); match; match = part.exec(text)) {
258
+ total += parseFloat(match[1]) * DURATION_UNITS[match[2]];
259
+ end = part.lastIndex;
260
+ }
261
+ return end > 0 && end === text.length ? total : void 0;
262
+ }
263
+ function gave(declarer, setting, value, how) {
264
+ const shown = JSON.stringify(value);
265
+ return how === "sets" ? `${declarer} sets ${setting} to ${shown}` : `${declarer} declares ${setting} ${shown}`;
266
+ }
267
+ var WEEK_START_DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
268
+ function assertWeekStartDay(day, declarer, setting, how = "declares") {
269
+ if (day === void 0 || WEEK_START_DAYS.includes(day)) return;
270
+ const said = `${gave(declarer, setting, day, how)}.`;
271
+ const meant = typeof day === "string" ? suggest(day.trim(), [...WEEK_START_DAYS]) : void 0;
272
+ if (meant) throw new ValidationError(`${said} Did you mean ${JSON.stringify(meant)}?`);
273
+ const choices = WEEK_START_DAYS.map((d) => JSON.stringify(d));
274
+ throw new ValidationError(`${said} Use one of: ${choices.slice(0, -1).join(", ")}, or ${choices[choices.length - 1]}.`);
275
+ }
276
+ function assertCacheDuration(duration, declarer, setting, entity, how = "declares") {
277
+ if (duration === void 0) return;
278
+ const ms = typeof duration === "string" ? parseDuration(duration) : void 0;
279
+ if (ms === void 0) {
280
+ throw new ValidationError(`${gave(declarer, setting, duration, how)}, which isn't a duration. Use one such as 30s, 10m or 2h.`, entity);
281
+ }
282
+ if (ms > MAX_CACHE_DURATION_MS) {
283
+ throw new ValidationError(`${gave(declarer, setting, duration, how)}, which is over 168h (7 days), the longest a result can be cached.`, entity);
284
+ }
285
+ }
286
+
135
287
  // src/app/query.ts
288
+ function assertDeclaration(name, declaration, how = "declares") {
289
+ if (!declaration.aql?.trim()) {
290
+ throw new ValidationError(`Query '${name}' ${how} no AQL.`, name);
291
+ }
292
+ const { pageSize } = declaration;
293
+ if (pageSize !== void 0 && !(Number.isInteger(pageSize) && pageSize >= 1)) {
294
+ throw new ValidationError(`${gave(`Query '${name}'`, "pageSize", pageSize, how)}, but it must be a whole number of at least 1.`, name);
295
+ }
296
+ assertCacheDuration(declaration.cache?.duration, `Query '${name}'`, "cache.duration", name, how);
297
+ }
136
298
  var Query = class extends Observable {
137
- constructor(name, app, declaration) {
299
+ constructor(name, app, declaration, id) {
138
300
  super(app);
139
301
  __publicField(this, "kind", "query");
140
302
  __publicField(this, "name");
141
- __publicField(this, "declaration");
142
- __publicField(this, "dataset");
303
+ /**
304
+ * @internal Which query of its name: its app numbers them as they are created, so one removed and
305
+ * created again by its name is told apart from the first, in the stamp on its calls.
306
+ */
307
+ __publicField(this, "id");
308
+ __publicField(this, "_declaration");
309
+ __publicField(this, "_dataset");
310
+ /** Set once `remove()` took it out of its app; every method then throws. */
311
+ __publicField(this, "removed", false);
143
312
  __publicField(this, "app");
144
313
  __publicField(this, "_state", "idle");
145
314
  /** Its last run failed: not a `fetchMore`, whose failure leaves the pages already loaded to keep. */
@@ -147,12 +316,19 @@ var Query = class extends Observable {
147
316
  __publicField(this, "_result");
148
317
  __publicField(this, "_error");
149
318
  __publicField(this, "_page", 1);
319
+ // The input the result's run came back with: its next page and its export replay it.
320
+ __publicField(this, "_run");
150
321
  /**
151
322
  * A sort applied to the result, independent of the query's own AQL — the same mechanism a click
152
323
  * on a table's column header uses. Kept off the declaration so setting it never re-authors the
153
324
  * query. See docs/adr/0001.
154
325
  */
155
326
  __publicField(this, "_sort", []);
327
+ /**
328
+ * The result belongs to the declaration before the last `update`: it stays on screen until the
329
+ * rerun, but its pages can't be continued with the new AQL. Cleared when a run's first page lands.
330
+ */
331
+ __publicField(this, "resultSuperseded", false);
156
332
  /** The input signature of the last successful run; undefined until one has happened. */
157
333
  __publicField(this, "lastRunSignature");
158
334
  /**
@@ -162,20 +338,80 @@ var Query = class extends Observable {
162
338
  __publicField(this, "lastPageRows", 0);
163
339
  /** @internal Set by the executor so `abort()` can reach the in-flight request. */
164
340
  __publicField(this, "controller");
165
- if (!declaration.aql?.trim()) {
166
- throw new ValidationError(`Query '${name}' declares no AQL.`, name);
167
- }
168
- const { pageSize } = declaration;
169
- if (pageSize !== void 0 && !(Number.isInteger(pageSize) && pageSize >= 1)) {
170
- throw new ValidationError(
171
- `Query '${name}' declares pageSize ${pageSize}; it must be a whole number of at least 1.`,
172
- name
173
- );
174
- }
341
+ /**
342
+ * @internal The signature the run or page in flight was sent with; set and cleared with
343
+ * `controller`, so a run the reader is waiting on is not counted as a change.
344
+ */
345
+ __publicField(this, "runningSignature");
346
+ /** The signature of its last run, when that run failed. */
347
+ __publicField(this, "failedSignature");
348
+ assertDeclaration(name, declaration);
175
349
  this.name = name;
350
+ this.id = id;
176
351
  this.app = app;
177
- this.declaration = declaration;
178
- this.dataset = app.datasetIndex(declaration.dataset, name);
352
+ this._declaration = declaration;
353
+ this._dataset = app.datasetIndex(declaration.dataset, name);
354
+ }
355
+ /** What it was declared with, or last updated to. */
356
+ get declaration() {
357
+ return this._declaration;
358
+ }
359
+ /** The dataset its declaration names, resolved. */
360
+ get dataset() {
361
+ return this._dataset;
362
+ }
363
+ /** False once `remove()` took it out of its app. */
364
+ get isRemoved() {
365
+ return this.removed;
366
+ }
367
+ /**
368
+ * Swaps what this query is: its dataset, its AQL, its page size, its cache, checked as `createQuery` checks
369
+ * them. Its name, its edges and its result stay; the result until the rerun replaces it. Runs
370
+ * nothing: the query is dirty, and the next `app.execute()` reruns it, so several edits go out
371
+ * as one run. Back to the first page. A run or page in flight is aborted, and `fetchMore` does
372
+ * nothing until the rerun. A new AQL or dataset clears the sort (unless `sort` is given) and a
373
+ * selection made in this query, whose rows no longer mean the same.
374
+ */
375
+ update(changes) {
376
+ this.assertLive();
377
+ this.app.updateQuery(this, changes);
378
+ }
379
+ /**
380
+ * Takes this query out of its app: its control mappings and cross-filters go with it, a run in
381
+ * flight is aborted, a selection made in it is cleared, and its name is free again. The queries
382
+ * it cross-filtered rerun without it at the next `app.execute()`. Every method of it throws from
383
+ * then on.
384
+ */
385
+ remove() {
386
+ this.assertLive();
387
+ this.app.removeEntity(this);
388
+ }
389
+ /** @internal Throws once the query was removed. */
390
+ assertLive() {
391
+ if (this.removed) {
392
+ throw new ValidationError(`Query '${this.name}' was removed from its app; it can't be used any more.`, this.name);
393
+ }
394
+ }
395
+ /** @internal The app's half of `update`, checked by then: swap the declaration. */
396
+ replaceDeclaration(declaration, dataset, sort) {
397
+ this.controller?.abort();
398
+ this.controller = void 0;
399
+ this.runningSignature = void 0;
400
+ if (this._state === "executing") this._state = this._result ? "success" : "idle";
401
+ this.resultSuperseded = true;
402
+ this._declaration = declaration;
403
+ this._dataset = dataset;
404
+ this._sort = [...sort];
405
+ this._run = void 0;
406
+ this.resetPage();
407
+ this.notify();
408
+ }
409
+ /** @internal The app's half of `remove`: stop what is in flight, and stay quiet from then on. */
410
+ markRemoved() {
411
+ this.removed = true;
412
+ this.controller?.abort();
413
+ this.controller = void 0;
414
+ this.runningSignature = void 0;
179
415
  }
180
416
  /**
181
417
  * Bring the elements marked `data-anfra-query` with this query's name into view: scroll to the
@@ -183,6 +419,7 @@ var Query = class extends Observable {
183
419
  * marked with it yet; never throws, so an author's own button is safe.
184
420
  */
185
421
  locate() {
422
+ this.assertLive();
186
423
  return this.app.locate("query", this.name);
187
424
  }
188
425
  get state() {
@@ -206,39 +443,41 @@ var Query = class extends Observable {
206
443
  }
207
444
  /** Replaces the sort applied to this query's result. Pass `[]` to clear it back to the AQL's own. */
208
445
  setSort(sort) {
446
+ this.assertLive();
209
447
  this._sort = [...sort];
210
448
  this.notify();
211
449
  }
212
450
  /**
213
451
  * Whether another page may follow: as the backend said of the last page, or, when it did not
214
- * say, whether that page came back full.
452
+ * say, whether that page came back full. False after `update` until the rerun.
215
453
  */
216
454
  get hasMore() {
217
- if (!this._result || this.pageSize === void 0) return false;
455
+ if (!this._result || this.pageSize === void 0 || this.resultSuperseded) return false;
218
456
  return this._result.meta.hasMore ?? this.lastPageRows >= this.pageSize;
219
457
  }
220
458
  /**
221
459
  * Everything that changes the rows: the declaration, the conditions reaching this query through
222
460
  * mappings, the conditions reaching it from the selection, the sort override, the app's timezone,
223
461
  * and the page. Compared against the last successful run to decide whether re-running would
224
- * produce anything new.
462
+ * produce anything new. `pending` reads the controls and selection as the reader has them,
463
+ * `applied` as the app last applied them; they differ only between a change and `app.execute()`.
225
464
  */
226
- signature() {
465
+ signature(phase = "pending") {
227
466
  const conditions = this.app.mappingsTo(this.name).map((mapping) => ({
228
467
  field: mapping.field,
229
468
  aggregation: mapping.aggregation,
230
- condition: mapping.from.condition
469
+ condition: phase === "pending" ? mapping.from.condition : mapping.from.appliedCondition
231
470
  })).sort((a, b) => a.field.localeCompare(b.field) || JSON.stringify(a).localeCompare(JSON.stringify(b)));
232
471
  return JSON.stringify({
233
472
  declaration: this.declaration,
234
473
  conditions,
235
- selection: this.app.selectionConditionsFor(this.name, "pending"),
474
+ selection: this.app.selectionConditionsFor(this.name, phase),
236
475
  // Separate from `selection`, and not optional: a selection sent as one expression leaves
237
476
  // `conditions` empty, so without this every such selection has the same signature as the
238
477
  // next one and the query is never re-run.
239
- selectionExpression: this.app.selectionExpressionFor(this.name, "pending"),
478
+ selectionExpression: this.app.selectionExpressionFor(this.name, phase),
240
479
  sort: this._sort,
241
- timezone: this.app.timezone,
480
+ inputDefaults: this.app.queryInputDefaults,
242
481
  page: this._page
243
482
  });
244
483
  }
@@ -249,6 +488,19 @@ var Query = class extends Observable {
249
488
  get isDirty() {
250
489
  return this.lastRunSignature !== void 0 && this.signature() !== this.lastRunSignature;
251
490
  }
491
+ /**
492
+ * @internal For `app.hasChanges`: whether the next `app.execute()` would run it with inputs no run
493
+ * of it has had. Not when its pending inputs are those of its run in flight, its last successful
494
+ * run or, when it last failed, its failed run: a failure is not a change. Never attempted, only
495
+ * once `executed` (the app has run): before that, nothing has been applied to differ from.
496
+ */
497
+ hasUnappliedChange(executed) {
498
+ const pending = this.signature();
499
+ if (pending === this.runningSignature) return false;
500
+ if (this.runFailed) return pending !== this.failedSignature;
501
+ if (this.lastRunSignature === void 0) return executed && this.runningSignature === void 0;
502
+ return pending !== this.lastRunSignature;
503
+ }
252
504
  /**
253
505
  * @internal Also when its last run failed, whatever its inputs: so `execute()` is the retry, of
254
506
  * the failed queries only, even after a forced run (`refresh()`) failed with unchanged inputs. Not
@@ -257,13 +509,33 @@ var Query = class extends Observable {
257
509
  shouldRun(force = false) {
258
510
  return force || this.runFailed || this.lastRunSignature === void 0 || this.isDirty;
259
511
  }
512
+ /**
513
+ * @internal For `query.execute()`: like `shouldRun`, but against what is applied, since applying
514
+ * the reader's pending changes is the app's, for every query at once. Its own sort and the
515
+ * timezone count; a control or selection the reader changed and the app has not applied does not.
516
+ */
517
+ shouldRunAlone(force = false) {
518
+ return force || this.runFailed || this.lastRunSignature === void 0 || this.signature("applied") !== this.lastRunSignature;
519
+ }
520
+ /**
521
+ * Runs this query alone, with the inputs the app last applied, if that would produce something
522
+ * new; with `force`, whatever its inputs (a paged query starts over at its first page). Applies
523
+ * none of the reader's pending changes: that is `app.execute()`'s, so the query stays dirty and
524
+ * the next `app.execute()` runs it with them. Never rejects, as `app.execute()` doesn't.
525
+ */
526
+ execute(options = {}) {
527
+ this.assertLive();
528
+ return this.app.executeQuery(this, options);
529
+ }
260
530
  /** Stops the in-flight request for this query. The pending `execute()` resolves without it. */
261
531
  abort() {
532
+ this.assertLive();
262
533
  this.controller?.abort();
263
534
  }
264
535
  /** Fetches the next page and appends it. Rejects rather than swallowing, unlike `execute()`. */
265
536
  async fetchMore() {
266
537
  try {
538
+ this.assertLive();
267
539
  if (this.pageSize === void 0) {
268
540
  throw new ValidationError(`Query '${this.name}' declares no pageSize, so it has no more pages.`, this.name);
269
541
  }
@@ -284,6 +556,7 @@ var Query = class extends Observable {
284
556
  * browser's menu) is prevented, and when none would (no plugin offers one), nothing happens.
285
557
  */
286
558
  menu(event, rows, options = {}) {
559
+ this.assertLive();
287
560
  return this.app.menu(this, event, Array.isArray(rows) ? rows : [rows], options.fields, options.measure);
288
561
  }
289
562
  /**
@@ -297,6 +570,7 @@ var Query = class extends Observable {
297
570
  * returned. A measure or an adhoc column never takes part, whether or not it is named here.
298
571
  */
299
572
  select(rows, options = {}) {
573
+ this.assertLive();
300
574
  this.app.select(this, Array.isArray(rows) ? rows : [rows], options.fields);
301
575
  }
302
576
  /**
@@ -323,28 +597,50 @@ var Query = class extends Observable {
323
597
  }
324
598
  /** @internal */
325
599
  markExecuting() {
600
+ if (this.removed) return;
326
601
  this._state = "executing";
327
602
  this._error = void 0;
328
603
  this.notify();
329
604
  }
605
+ /** @internal The cache duration it runs with: its own, or its app's default. Absent: the backend's default. */
606
+ get cacheDuration() {
607
+ return this.declaration.cache?.duration ?? this.app.queryCacheDefaultDuration;
608
+ }
609
+ /** @internal The run the result on screen came from, for its next page and its export. */
610
+ get run() {
611
+ return this._run;
612
+ }
330
613
  /** @internal */
331
- markSuccess(result, signature, append) {
614
+ markSuccess(result, signature, append, run) {
615
+ if (this.removed) return;
332
616
  this._state = "success";
617
+ if (!append) {
618
+ this._run = run;
619
+ this.resultSuperseded = false;
620
+ }
333
621
  this._error = void 0;
334
622
  if (!append) this.runFailed = false;
335
623
  this.lastRunSignature = signature;
336
624
  this.lastPageRows = result.rows.length;
337
625
  if (append && this._result) {
338
- const rows = [...this._result.rows, ...result.rows];
626
+ const added = result.meta.pivot ? newGridRows(this._result.rows, result.rows) : result.rows;
627
+ const rows = [...this._result.rows, ...added];
339
628
  this._result = { ...result, rows, meta: { ...result.meta, numRows: rows.length } };
340
629
  } else {
341
630
  this._result = result;
342
631
  }
343
632
  this.notify();
344
633
  }
345
- /** @internal `page` when it is a `fetchMore` that failed, not a run. */
346
- markError(error, page = false) {
347
- if (!page) this.runFailed = true;
634
+ /**
635
+ * @internal `page` when it is a `fetchMore` that failed, not a run; `signature`, a failed run's
636
+ * inputs.
637
+ */
638
+ markError(error, page = false, signature) {
639
+ if (this.removed) return;
640
+ if (!page) {
641
+ this.runFailed = true;
642
+ this.failedSignature = signature;
643
+ }
348
644
  this._state = "error";
349
645
  this._error = error;
350
646
  this.notify();
@@ -359,9 +655,26 @@ var Query = class extends Observable {
359
655
  this.lastPageRows = 0;
360
656
  }
361
657
  toJSON() {
362
- return this.declaration;
658
+ return this._declaration;
363
659
  }
364
660
  };
661
+ var PIVOT_ROW = "__pivot_row__";
662
+ function newGridRows(loaded, page) {
663
+ const ranks = new Set(loaded.map((row) => String(row[PIVOT_ROW])));
664
+ return page.filter((row) => !ranks.has(String(row[PIVOT_ROW])));
665
+ }
666
+
667
+ // src/app/changes.ts
668
+ function withChanges(base, changes, keys = Object.keys(changes)) {
669
+ const merged = { ...base };
670
+ keys.forEach((key) => {
671
+ if (!(key in changes)) return;
672
+ const value = changes[key];
673
+ if (value === void 0) delete merged[key];
674
+ else merged[key] = value;
675
+ });
676
+ return merged;
677
+ }
365
678
 
366
679
  // src/app/controls.ts
367
680
  var DATE_GRAINS = ["year", "quarter", "month", "week", "day", "hour", "minute"];
@@ -396,6 +709,8 @@ var Control = class extends Observable {
396
709
  __publicField(this, "pending");
397
710
  __publicField(this, "applied");
398
711
  __publicField(this, "initial");
712
+ /** Set once `remove()` took it out of its app; every method then throws. */
713
+ __publicField(this, "removed", false);
399
714
  this.name = name;
400
715
  this.app = app;
401
716
  this.initial = initial;
@@ -406,8 +721,44 @@ var Control = class extends Observable {
406
721
  * none is on the page yet; never throws.
407
722
  */
408
723
  locate() {
724
+ this.assertLive();
409
725
  return this.app.locate("control", this.name);
410
726
  }
727
+ /** False once `remove()` took it out of its app. */
728
+ get isRemoved() {
729
+ return this.removed;
730
+ }
731
+ /**
732
+ * Takes this control out of its app, with its mappings: the queries it was mapped to rerun
733
+ * without its condition at the next `app.execute()`. Its name is free again, and every method
734
+ * of it throws from then on.
735
+ */
736
+ remove() {
737
+ this.assertLive();
738
+ this.app.removeEntity(this);
739
+ }
740
+ /** @internal Throws once the control was removed. */
741
+ assertLive() {
742
+ if (this.removed) {
743
+ throw new ValidationError(`Control '${this.name}' was removed from its app; it can't be used any more.`, this.name);
744
+ }
745
+ }
746
+ /** @internal The app's half of `remove`: stop what is in flight. */
747
+ markRemoved() {
748
+ this.removed = true;
749
+ this.dropInFlight();
750
+ }
751
+ /** @internal Drops work in flight that the control's current declaration no longer wants. */
752
+ dropInFlight() {
753
+ }
754
+ /**
755
+ * @internal A new declaration's default: `reset()` goes back to it. `restart` also sets the
756
+ * reader's condition to it, for a control that now filters something else.
757
+ */
758
+ redefault(initial, restart) {
759
+ this.initial = initial;
760
+ if (restart) this.pending = initial;
761
+ }
411
762
  /** The reader's current value, which `execute()` will commit. */
412
763
  get condition() {
413
764
  return this.pending;
@@ -424,10 +775,12 @@ var Control = class extends Observable {
424
775
  return this.applied !== void 0 && !sameCondition(this.pending, this.applied);
425
776
  }
426
777
  setCondition(condition) {
778
+ this.assertLive();
427
779
  this.pending = condition;
428
780
  this.notify();
429
781
  }
430
782
  reset() {
783
+ this.assertLive();
431
784
  this.setCondition(this.initial);
432
785
  }
433
786
  /** @internal Called by the executor once the queries reading this control have been submitted. */
@@ -435,18 +788,23 @@ var Control = class extends Observable {
435
788
  this.applied = this.pending;
436
789
  }
437
790
  };
438
- var Filter = class extends Control {
791
+ var Filter = class _Filter extends Control {
439
792
  constructor(name, app, declaration, dataset, backend) {
440
793
  super(name, app, declaration.default ?? { operator: "is", values: [] });
441
794
  __publicField(this, "kind", "filter");
442
- __publicField(this, "declaration");
443
- __publicField(this, "type");
444
- __publicField(this, "resolved");
445
- __publicField(this, "datasetName");
795
+ __publicField(this, "_declaration");
796
+ __publicField(this, "resolution");
446
797
  __publicField(this, "backend");
447
798
  __publicField(this, "loadedOptions");
448
- this.declaration = declaration;
799
+ /** The `loadOptions` calls in flight, so a removal or a new field can drop them. */
800
+ __publicField(this, "loading", /* @__PURE__ */ new Set());
449
801
  this.backend = backend;
802
+ this.resolution = _Filter.resolve(name, declaration, dataset);
803
+ this._declaration = declaration;
804
+ this.assertValues(this.condition.values ?? []);
805
+ this.assertValues(declaration.options ?? []);
806
+ }
807
+ static resolve(name, declaration, dataset) {
450
808
  if (declaration.field) {
451
809
  if (!dataset) {
452
810
  throw new ValidationError(
@@ -454,32 +812,69 @@ var Filter = class extends Control {
454
812
  name
455
813
  );
456
814
  }
457
- this.resolved = dataset.resolve(declaration.field, name);
458
- this.datasetName = dataset.descriptor.name;
459
- this.type = declaration.type ?? inferType(this.resolved.type);
460
- } else {
461
- if (!declaration.type) {
462
- throw new ValidationError(
463
- `Filter '${name}' is a manual filter, so it needs a \`type\`.`,
464
- name
465
- );
466
- }
467
- this.type = declaration.type;
815
+ const resolved = dataset.resolve(declaration.field, name);
816
+ return { resolved, datasetName: dataset.descriptor.name, type: declaration.type ?? inferType(resolved.type) };
468
817
  }
469
- this.assertValues(this.condition.values ?? []);
470
- this.assertValues(declaration.options ?? []);
818
+ if (!declaration.type) {
819
+ throw new ValidationError(
820
+ `Filter '${name}' is a manual filter, so it needs a \`type\`.`,
821
+ name
822
+ );
823
+ }
824
+ return { type: declaration.type };
825
+ }
826
+ /** What it was declared with, or last updated to. */
827
+ get declaration() {
828
+ return this._declaration;
829
+ }
830
+ get type() {
831
+ return this.resolution.type;
471
832
  }
472
833
  setCondition(condition) {
834
+ this.assertLive();
473
835
  this.assertValues(condition.values ?? []);
474
836
  super.setCondition(condition);
475
837
  }
838
+ /**
839
+ * Edits this filter in place. A new label, options or default keep the reader's condition, and
840
+ * `reset()` goes to the new default. A new field, dataset or type is checked as `createFilter`
841
+ * checks it, and the condition goes back to the new default: the old values filtered something
842
+ * else. Its mappings stay as they are: each mapping's own field decides what its condition applies to.
843
+ */
844
+ update(changes) {
845
+ this.assertLive();
846
+ const declaration = withChanges(this._declaration, changes);
847
+ const previous = this._declaration;
848
+ const redefined = ["field", "dataset", "type"].some((key) => declaration[key] !== previous[key]);
849
+ const resolution = redefined ? _Filter.resolve(this.name, declaration, this.app.filterDataset(this.name, declaration)) : this.resolution;
850
+ const initial = declaration.default ?? { operator: "is", values: [] };
851
+ const values = (condition) => condition.values ?? [];
852
+ this.assertValuesOf(resolution.type, values(initial));
853
+ this.assertValuesOf(resolution.type, declaration.options ?? []);
854
+ if (!redefined) this.assertValuesOf(resolution.type, values(this.condition));
855
+ this._declaration = declaration;
856
+ this.resolution = resolution;
857
+ this.redefault(initial, redefined);
858
+ if (redefined) {
859
+ this.loadedOptions = void 0;
860
+ this.dropInFlight();
861
+ }
862
+ this.notify();
863
+ }
864
+ dropInFlight() {
865
+ this.loading.forEach((controller) => controller.abort());
866
+ this.loading.clear();
867
+ }
476
868
  /**
477
869
  * A number filter's values are strings, as query results give them, which keep every digit. A JS
478
870
  * number may already have lost some (`Number("9007199254740993")` is ...992), and nothing after
479
871
  * can tell, so the core API refuses one; this says so where the app hands it over.
480
872
  */
481
873
  assertValues(values) {
482
- if (this.type !== "number") return;
874
+ this.assertValuesOf(this.type, values);
875
+ }
876
+ assertValuesOf(type, values) {
877
+ if (type !== "number") return;
483
878
  const number = values.find((value) => typeof value === "number");
484
879
  if (number === void 0) return;
485
880
  throw new ValidationError(
@@ -489,68 +884,117 @@ var Filter = class extends Control {
489
884
  }
490
885
  /** True for a field-backed filter, false for a manual one. The two are separate axes from `type`. */
491
886
  get isFieldBacked() {
492
- return this.resolved !== void 0;
887
+ return this.resolution.resolved !== void 0;
493
888
  }
494
889
  /** A manual filter's static list, or whatever the last `loadOptions()` returned. */
495
890
  get options() {
496
- return this.loadedOptions ?? this.declaration.options ?? [];
891
+ return this.loadedOptions ?? this._declaration.options ?? [];
497
892
  }
498
893
  /**
499
894
  * Fetches option values for a field-backed filter.
500
895
  *
501
896
  * Lazy rather than fetched up front: building a distinct-values query for every filter is slow,
502
897
  * and readers often touch none of them. The backend decides which values this reader may see.
898
+ * Rejects with an `AbortError` when the filter is removed, or its field changes, before the list
899
+ * arrives: the list is dropped.
503
900
  */
504
901
  async loadOptions(search, signal = new AbortController().signal) {
505
- const model = this.resolved?.modelName;
506
- if (!this.resolved || !model || !this.backend || !this.datasetName) return this.options;
507
- const options = await this.backend.fieldSuggestions(
508
- {
509
- dataset: this.datasetName,
510
- model,
511
- field: this.resolved.fieldName,
512
- q: search ?? ""
513
- },
514
- signal
515
- ).catch((err) => {
516
- tagCall(err, "load_options");
517
- throw err;
518
- });
519
- this.loadedOptions = [...options ?? []];
520
- this.notify();
521
- return this.loadedOptions;
902
+ this.assertLive();
903
+ const { resolved, datasetName } = this.resolution;
904
+ const model = resolved?.modelName;
905
+ if (!resolved || !model || !this.backend || !datasetName) return this.options;
906
+ const controller = new AbortController();
907
+ const follow = () => controller.abort();
908
+ if (signal.aborted) controller.abort();
909
+ else signal.addEventListener("abort", follow, { once: true });
910
+ this.loading.add(controller);
911
+ try {
912
+ const options = await this.backend.fieldSuggestions(
913
+ {
914
+ dataset: datasetName,
915
+ model,
916
+ field: resolved.fieldName,
917
+ q: search ?? ""
918
+ },
919
+ controller.signal
920
+ ).catch((err) => {
921
+ tagCall(err, "load_options");
922
+ throw err;
923
+ });
924
+ if (controller.signal.aborted && !this.loading.has(controller)) throw abortError();
925
+ this.loadedOptions = [...options ?? []];
926
+ this.notify();
927
+ return this.loadedOptions;
928
+ } finally {
929
+ this.loading.delete(controller);
930
+ signal.removeEventListener("abort", follow);
931
+ }
522
932
  }
523
933
  toJSON() {
524
- return this.declaration;
934
+ return this._declaration;
525
935
  }
526
936
  };
527
937
  var DateDrillControl = class extends Control {
528
938
  constructor(name, app, declaration = {}) {
529
939
  super(name, app, drillCondition(name, declaration.default));
530
940
  __publicField(this, "kind", "dateDrill");
531
- __publicField(this, "declaration");
532
- this.declaration = declaration;
941
+ __publicField(this, "_declaration");
942
+ this._declaration = declaration;
943
+ }
944
+ /** What it was declared with, or last updated to. */
945
+ get declaration() {
946
+ return this._declaration;
947
+ }
948
+ /** Edits its label or default. The reader's grain stays; `reset()` goes to the new default. */
949
+ update(changes) {
950
+ this.assertLive();
951
+ const declaration = withChanges(this._declaration, changes);
952
+ const initial = drillCondition(this.name, declaration.default);
953
+ this._declaration = declaration;
954
+ this.redefault(initial, false);
955
+ this.notify();
533
956
  }
534
957
  setGrain(grain) {
958
+ this.assertLive();
535
959
  this.setCondition(drillCondition(this.name, grain));
536
960
  }
537
961
  toJSON() {
538
- return this.declaration;
962
+ return this._declaration;
539
963
  }
540
964
  };
541
965
 
542
966
  // src/app/mapping.ts
967
+ function assertLive(edge, removed) {
968
+ if (removed) {
969
+ throw new ValidationError(`Edge '${edge.id}' was removed from its app; map again to have it back.`, edge.from.name);
970
+ }
971
+ }
543
972
  var Mapping = class {
544
- constructor(from, to, field, aggregation) {
973
+ constructor(from, to, field, aggregation, owner) {
545
974
  __publicField(this, "kind", "control");
546
975
  __publicField(this, "from");
547
976
  __publicField(this, "to");
548
977
  __publicField(this, "field");
549
978
  __publicField(this, "aggregation");
979
+ __publicField(this, "owner");
980
+ __publicField(this, "removed", false);
550
981
  this.from = from;
551
982
  this.to = to;
552
983
  this.field = field;
553
984
  this.aggregation = aggregation;
985
+ this.owner = owner;
986
+ }
987
+ /**
988
+ * Takes this mapping out of its app: its query reruns without the control's condition at the
989
+ * next `app.execute()`. An edge never changes: to change one, remove it and map again.
990
+ */
991
+ remove() {
992
+ assertLive(this, this.removed);
993
+ this.owner?.removeEdge(this);
994
+ }
995
+ /** @internal */
996
+ markRemoved() {
997
+ this.removed = true;
554
998
  }
555
999
  /**
556
1000
  * Includes the field, unlike Dashboard as Code's `${from}.${to}` — that form collides the moment
@@ -571,12 +1015,27 @@ var Mapping = class {
571
1015
  }
572
1016
  };
573
1017
  var CrossFilter = class {
574
- constructor(from, to) {
1018
+ constructor(from, to, owner) {
575
1019
  __publicField(this, "kind", "crossFilter");
576
1020
  __publicField(this, "from");
577
1021
  __publicField(this, "to");
1022
+ __publicField(this, "owner");
1023
+ __publicField(this, "removed", false);
578
1024
  this.from = from;
579
1025
  this.to = to;
1026
+ this.owner = owner;
1027
+ }
1028
+ /**
1029
+ * Takes this cross-filter out of its app: a selection in `from` stops reaching `to`, which
1030
+ * reruns without it at the next `app.execute()`. To change one, remove it and map again.
1031
+ */
1032
+ remove() {
1033
+ assertLive(this, this.removed);
1034
+ this.owner?.removeEdge(this);
1035
+ }
1036
+ /** @internal */
1037
+ markRemoved() {
1038
+ this.removed = true;
580
1039
  }
581
1040
  /** No field to disambiguate, and one pair may only be declared once, so the pair is the id. */
582
1041
  get id() {
@@ -777,12 +1236,14 @@ function installContentUi(kernel) {
777
1236
  let hostKinds = /* @__PURE__ */ new Set();
778
1237
  let listening = false;
779
1238
  let current;
1239
+ let currentAbout;
780
1240
  const ui = () => kernel.body();
781
1241
  const root = () => layerRoot(doc, "anfra-ui");
782
1242
  const offered = (kind) => hostKinds.has(kind) || items.some((item) => item.target === kind);
783
1243
  const closeCurrent = () => {
784
1244
  const close = current;
785
1245
  current = void 0;
1246
+ currentAbout = void 0;
786
1247
  close?.();
787
1248
  };
788
1249
  function blockOf(target) {
@@ -854,7 +1315,7 @@ function installContentUi(kernel) {
854
1315
  }
855
1316
  return { entries, run };
856
1317
  }
857
- function open(event, targets) {
1318
+ function open(event, targets, about) {
858
1319
  const relevant = targets.map((target) => ({ target, own: frameEntries(target) })).filter(({ target, own }) => own.entries.length || hostKinds.has(target.kind));
859
1320
  if (!relevant.length) return false;
860
1321
  event.preventDefault();
@@ -882,6 +1343,7 @@ function installContentUi(kernel) {
882
1343
  }
883
1344
  });
884
1345
  current = close;
1346
+ currentAbout = about;
885
1347
  })().catch((err) => {
886
1348
  win.console?.error("anfra: the menu failed to open:", err);
887
1349
  reportError("plugin.uncaught", err);
@@ -903,8 +1365,11 @@ function installContentUi(kernel) {
903
1365
  const element = blockOf(event.target);
904
1366
  const node = element ? nodeTarget(element) : void 0;
905
1367
  const rows = node ? { ...target, node } : target;
906
- return open(event, node ? [rows, node] : [rows]);
1368
+ return open(event, node ? [rows, node] : [rows], { app: target.app, query: target.query });
907
1369
  };
1370
+ kernel.onApp((app) => app.onRemoved((entity) => {
1371
+ if (entity.kind === "query" && currentAbout?.app === app.index && currentAbout.query === entity.name) closeCurrent();
1372
+ }));
908
1373
  kernel.on("menu", (payload) => {
909
1374
  const kinds = payload?.kinds;
910
1375
  hostKinds = new Set((Array.isArray(kinds) ? kinds : []).filter((kind) => kind === "node" || kind === "rows"));
@@ -932,6 +1397,7 @@ function installContentUi(kernel) {
932
1397
  };
933
1398
  close = draw(body, onClose);
934
1399
  current = close;
1400
+ currentAbout = input.about ? { app: input.about.app, query: input.about.query } : void 0;
935
1401
  return { close };
936
1402
  }
937
1403
  return {
@@ -1078,119 +1544,6 @@ function scrollTo(element) {
1078
1544
  }
1079
1545
  }
1080
1546
 
1081
- // src/app/suggest.ts
1082
- function editDistance(a, b) {
1083
- const rows = a.length + 1;
1084
- const cols = b.length + 1;
1085
- let prev = Array.from({ length: cols }, (_, j) => j);
1086
- for (let i = 1; i < rows; i++) {
1087
- const curr = [i];
1088
- for (let j = 1; j < cols; j++) {
1089
- curr[j] = Math.min(
1090
- prev[j] + 1,
1091
- curr[j - 1] + 1,
1092
- prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
1093
- );
1094
- }
1095
- prev = curr;
1096
- }
1097
- return prev[cols - 1];
1098
- }
1099
- function suggest(value, candidates) {
1100
- let best;
1101
- let bestDistance = Infinity;
1102
- candidates.forEach((candidate) => {
1103
- const distance = editDistance(value.toLowerCase(), candidate.toLowerCase());
1104
- if (distance < bestDistance) {
1105
- bestDistance = distance;
1106
- best = candidate;
1107
- }
1108
- });
1109
- const threshold = Math.max(2, Math.floor(value.length / 3));
1110
- return bestDistance <= threshold ? best : void 0;
1111
- }
1112
- function withSuggestion(message, value, candidates) {
1113
- const hint = suggest(value, candidates);
1114
- return hint ? `${message} Did you mean '${hint}'?` : message;
1115
- }
1116
-
1117
- // src/app/validation.ts
1118
- var DatasetIndex = class {
1119
- constructor(descriptor) {
1120
- __publicField(this, "descriptor");
1121
- __publicField(this, "fields", /* @__PURE__ */ new Map());
1122
- __publicField(this, "references");
1123
- this.descriptor = descriptor;
1124
- descriptor.data_models.forEach((model) => {
1125
- model.fields.forEach((field) => {
1126
- const modelName = String(model.name);
1127
- this.fields.set(`${modelName}.${field.name}`, {
1128
- modelName,
1129
- fieldName: field.name,
1130
- isMetric: false,
1131
- type: field.type,
1132
- label: field.label ?? field.name
1133
- });
1134
- });
1135
- });
1136
- descriptor.metrics.forEach((metric) => {
1137
- this.fields.set(metric.name, {
1138
- fieldName: metric.name,
1139
- isMetric: true,
1140
- type: metric.type,
1141
- label: metric.label ?? metric.name
1142
- });
1143
- });
1144
- this.references = [...this.fields.keys()];
1145
- }
1146
- resolve(reference, entity) {
1147
- const field = this.fields.get(reference);
1148
- if (field) return field;
1149
- throw new ValidationError(
1150
- withSuggestion(
1151
- `Unknown field '${reference}' on dataset '${this.descriptor.name}'.`,
1152
- reference,
1153
- this.references
1154
- ),
1155
- entity
1156
- );
1157
- }
1158
- };
1159
- function resolveDataset(datasets, uname, entity) {
1160
- const dataset = datasets[uname];
1161
- if (dataset) return dataset;
1162
- throw new ValidationError(
1163
- withSuggestion(
1164
- `Unknown dataset '${uname}'.`,
1165
- uname,
1166
- Object.keys(datasets)
1167
- ),
1168
- entity
1169
- );
1170
- }
1171
- function assertValidFilterAggregation(aggregation, entity) {
1172
- if (!FILTER_AGGREGATIONS.includes(aggregation)) {
1173
- throw new ValidationError(
1174
- withSuggestion(
1175
- `Invalid filter aggregation '${aggregation}'.`,
1176
- aggregation,
1177
- [...FILTER_AGGREGATIONS]
1178
- ),
1179
- entity
1180
- );
1181
- }
1182
- }
1183
- function assertUniqueName(taken, name, kind) {
1184
- if (!name) {
1185
- throw new ValidationError(`A ${kind} needs a name.`);
1186
- }
1187
- for (const existing of taken) {
1188
- if (existing === name) {
1189
- throw new ValidationError(`'${name}' is already declared in this app.`, name);
1190
- }
1191
- }
1192
- }
1193
-
1194
1547
  // src/app/execution/submitQuery.ts
1195
1548
  function toFilter(mapping, condition) {
1196
1549
  if (!condition || condition.operator === "none" || condition.operator === "transform_date_drill") return void 0;
@@ -1229,7 +1582,8 @@ function toResult(query, data) {
1229
1582
  ...pageSize !== void 0 ? {
1230
1583
  page: data.meta?.page ?? query.page,
1231
1584
  pageSize: data.meta?.pageSize ?? pageSize,
1232
- ...data.meta?.hasMore !== void 0 ? { hasMore: data.meta.hasMore } : {}
1585
+ ...data.meta?.hasMore !== void 0 ? { hasMore: data.meta.hasMore } : {},
1586
+ ...data.meta?.pivot ? { pivot: data.meta.pivot } : {}
1233
1587
  } : {},
1234
1588
  numRows: data.meta?.numRows ?? rows.length
1235
1589
  },
@@ -1252,39 +1606,58 @@ function buildQuery(query, mappings, selection, context) {
1252
1606
  filters: [...mappedFilters, ...selectionFilters],
1253
1607
  conditions,
1254
1608
  sorts: query.sort.map((sort) => ({ field: sort.field, direction: sort.direction ?? "asc" })),
1255
- dateDrills
1609
+ dateDrills,
1610
+ // Omitted entirely when the app declares none, so the backend applies its own default rather
1611
+ // than the SDK guessing the browser's.
1612
+ ...context.timezone ? { timezone: context.timezone } : {},
1613
+ ...context.weekStartDay ? { weekStartDay: context.weekStartDay } : {}
1256
1614
  },
1257
- // Omitted entirely when the app declares none, so the backend applies its own default rather
1258
- // than the SDK guessing the browser's.
1259
- ...context.timezone ? { timezone: context.timezone } : {}
1615
+ ...query.cacheDuration ? { cacheDuration: query.cacheDuration } : {}
1260
1616
  };
1261
1617
  }
1262
1618
  function buildRequest(query, mappings, selection, context) {
1619
+ const { input, ...rest } = buildQuery(query, mappings, selection, context);
1263
1620
  return {
1264
- ...buildQuery(query, mappings, selection, context),
1265
- // Omitted for a query that declares no page size, so the backend returns every row.
1266
- ...query.pageSize !== void 0 ? { page: query.page, pageSize: query.pageSize } : {},
1621
+ ...rest,
1622
+ input: withPage(input, query),
1267
1623
  ...context.bustCache ? { bustCache: true } : {}
1268
1624
  };
1269
1625
  }
1626
+ function pageRequest(query, run) {
1627
+ return {
1628
+ dataset: query.dataset.descriptor.name,
1629
+ aql: query.declaration.aql,
1630
+ input: withPage(run.input, query),
1631
+ ...query.cacheDuration ? { cacheDuration: query.cacheDuration } : {},
1632
+ ...run.cachedAt ? { minCachedAt: run.cachedAt } : {}
1633
+ };
1634
+ }
1635
+ function withPage(input, query) {
1636
+ const { pagination: _, ...rest } = input;
1637
+ return query.pageSize !== void 0 ? { ...rest, pagination: { page: query.page, pageSize: query.pageSize } } : rest;
1638
+ }
1270
1639
  function defaultExportFilename(query, title) {
1271
1640
  const safeTitle = title?.replace(/[/\\]/g, "-").replace(/\p{Cc}/gu, "").trim();
1272
1641
  return safeTitle ? `${safeTitle} - ${query.name}` : query.name;
1273
1642
  }
1274
- function buildExportRequest(query, mappings, selection, context, options) {
1643
+ function buildExportRequest(query, mappings, selection, context, options, run) {
1275
1644
  const format2 = options.format ?? "csv";
1276
1645
  const formatOptions = format2 === "csv" ? { bom: true, ...options.formatOptions } : options.formatOptions;
1646
+ const built = buildQuery(query, mappings, selection, context);
1647
+ const { pagination: _, ...input } = run?.input ?? built.input;
1277
1648
  return {
1278
- ...buildQuery(query, mappings, selection, context),
1649
+ ...built,
1650
+ input,
1651
+ ...run?.cachedAt ? { minCachedAt: run.cachedAt } : {},
1279
1652
  format: format2,
1280
1653
  ...formatOptions ? { formatOptions } : {},
1281
1654
  filename: options.filename?.trim() || defaultExportFilename(query, context.title)
1282
1655
  };
1283
1656
  }
1284
- async function runQuery(query, mappings, selection, context, signal) {
1285
- const request = buildRequest(query, mappings, selection, context);
1286
- const data = await context.backend.submitQuery(request, signal);
1287
- return toResult(query, data);
1657
+ async function runQuery(query, request, backend, signal, stamp) {
1658
+ const data = await backend.submitQuery(request, signal, stamp);
1659
+ const cachedAt = data.debug?.cache?.cachedAt?.toISOString();
1660
+ return { result: toResult(query, data), run: { input: data.input ?? request.input, ...cachedAt ? { cachedAt } : {} } };
1288
1661
  }
1289
1662
 
1290
1663
  // src/app/aql.ts
@@ -1581,6 +1954,7 @@ function inspectError(error) {
1581
1954
  function inspectQuery(query) {
1582
1955
  const { result } = query;
1583
1956
  return {
1957
+ id: query.id,
1584
1958
  state: query.state,
1585
1959
  isDirty: query.isDirty,
1586
1960
  page: query.page,
@@ -1640,6 +2014,11 @@ var App = class extends Observable {
1640
2014
  __publicField(this, "extensions", extensions);
1641
2015
  __publicField(this, "title");
1642
2016
  __publicField(this, "_timezone");
2017
+ __publicField(this, "_weekStartDay");
2018
+ /** The app's `query.default.input`: what its queries use over its own timezone and week start day. */
2019
+ __publicField(this, "queryInput");
2020
+ /** The cache duration of each of the app's queries that declares none (`query.default.cache.duration`). */
2021
+ __publicField(this, "queryCacheDefaultDuration");
1643
2022
  __publicField(this, "datasets");
1644
2023
  __publicField(this, "backend");
1645
2024
  __publicField(this, "features");
@@ -1650,10 +2029,14 @@ var App = class extends Observable {
1650
2029
  __publicField(this, "_selection");
1651
2030
  __publicField(this, "_appliedSelection");
1652
2031
  /**
1653
- * Whether a run has ever committed the selection. Needed because `undefined` is a real applied
1654
- * value — "nothing selected" — unlike a control's condition, which is always present.
2032
+ * Whether a run has ever committed the selection, that is whether `execute()` has ever run. Needed
2033
+ * because `undefined` is a real applied value — "nothing selected" — unlike a control's condition,
2034
+ * which is always present.
1655
2035
  */
1656
2036
  __publicField(this, "selectionCommitted", false);
2037
+ /** The id the next query created gets. */
2038
+ __publicField(this, "nextQueryId", 1);
2039
+ __publicField(this, "removedListeners", /* @__PURE__ */ new Set());
1657
2040
  /**
1658
2041
  * @internal This app's index among the frame's apps, which is how a marked element names it
1659
2042
  * (`data-anfra-query="1/revenue"`); 0 unless set by the instance that created it.
@@ -1661,6 +2044,14 @@ var App = class extends Observable {
1661
2044
  __publicField(this, "index", 0);
1662
2045
  this.title = declaration.title;
1663
2046
  this._timezone = declaration.timezone;
2047
+ assertWeekStartDay(declaration.weekStartDay, "The app", "weekStartDay");
2048
+ this._weekStartDay = declaration.weekStartDay;
2049
+ const queryInput = declaration.query?.default?.input ?? {};
2050
+ assertWeekStartDay(queryInput.weekStartDay, "The app", "query.default.input.weekStartDay");
2051
+ this.queryInput = { ...queryInput };
2052
+ const duration = declaration.query?.default?.cache?.duration;
2053
+ assertCacheDuration(duration, "The app", "query.default.cache.duration");
2054
+ this.queryCacheDefaultDuration = duration;
1664
2055
  this.datasets = datasets;
1665
2056
  this.backend = backend;
1666
2057
  this.features = features;
@@ -1683,14 +2074,14 @@ var App = class extends Observable {
1683
2074
  }
1684
2075
  createQuery(name, declaration) {
1685
2076
  this.assertNameFree(name, "query");
1686
- const query = applyExtensions(new Query(name, this, declaration), this.extensions?.query);
2077
+ const query = applyExtensions(new Query(name, this, declaration, this.nextQueryId++), this.extensions?.query);
1687
2078
  this._queries.set(name, query);
1688
2079
  this.notify();
1689
2080
  return query;
1690
2081
  }
1691
2082
  createFilter(name, declaration) {
1692
2083
  this.assertNameFree(name, "filter");
1693
- const dataset = declaration.dataset ? this.datasetIndex(declaration.dataset, name) : this.soleDataset(name, declaration.field);
2084
+ const dataset = this.filterDataset(name, declaration);
1694
2085
  const filter = applyExtensions(new Filter(name, this, declaration, dataset, this.backend), this.extensions?.control);
1695
2086
  this._controls.set(name, filter);
1696
2087
  this.notify();
@@ -1714,7 +2105,7 @@ var App = class extends Observable {
1714
2105
  * because "the control happens to name a field this query also has" is exactly the coupling that
1715
2106
  * breaks silently when someone renames a dimension.
1716
2107
  *
1717
- * There is no `unmap`: a mapping you do not want is one you do not declare.
2108
+ * Edges never change: to change one, `remove()` it and map again.
1718
2109
  */
1719
2110
  mapControl(from, to, options) {
1720
2111
  if (!(from instanceof Control)) {
@@ -1722,6 +2113,8 @@ var App = class extends Observable {
1722
2113
  "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."
1723
2114
  );
1724
2115
  }
2116
+ from.assertLive();
2117
+ to.assertLive();
1725
2118
  if (this._controls.get(from.name) !== from) {
1726
2119
  throw new ValidationError(`Control '${from.name}' belongs to a different app.`, from.name);
1727
2120
  }
@@ -1731,7 +2124,7 @@ var App = class extends Observable {
1731
2124
  if (options.aggregation) {
1732
2125
  assertValidFilterAggregation(options.aggregation, from.name);
1733
2126
  }
1734
- const mapping = new Mapping(from, to, options.field, options.aggregation);
2127
+ const mapping = new Mapping(from, to, options.field, options.aggregation, this);
1735
2128
  if (this._mappings.some((existing) => existing.id === mapping.id)) {
1736
2129
  throw new ValidationError(`Mapping '${mapping.id}' is already declared.`, from.name);
1737
2130
  }
@@ -1756,6 +2149,8 @@ var App = class extends Observable {
1756
2149
  "mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field })."
1757
2150
  );
1758
2151
  }
2152
+ from.assertLive();
2153
+ to.assertLive();
1759
2154
  if (this._queries.get(from.name) !== from) {
1760
2155
  throw new ValidationError(`Query '${from.name}' belongs to a different app.`, from.name);
1761
2156
  }
@@ -1774,7 +2169,7 @@ var App = class extends Observable {
1774
2169
  from.name
1775
2170
  );
1776
2171
  }
1777
- const edge = new CrossFilter(from, to);
2172
+ const edge = new CrossFilter(from, to, this);
1778
2173
  if (this._crossFilters.some((existing) => existing.id === edge.id)) {
1779
2174
  throw new ValidationError(`Cross-filter '${edge.id}' is already declared.`, from.name);
1780
2175
  }
@@ -1782,6 +2177,86 @@ var App = class extends Observable {
1782
2177
  this.notify();
1783
2178
  return edge;
1784
2179
  }
2180
+ /** @internal Backs `query.update`: checks the change against the app, then swaps it in. */
2181
+ updateQuery(query, changes) {
2182
+ const previous = query.declaration;
2183
+ const declaration = withChanges(previous, changes, ["dataset", "aql", "pageSize", "cache"]);
2184
+ assertDeclaration(query.name, declaration, "sets");
2185
+ const dataset = this.datasetIndex(declaration.dataset, query.name);
2186
+ if (declaration.dataset !== previous.dataset) {
2187
+ const spanning = this._crossFilters.filter((edge) => {
2188
+ if (edge.from === query) return edge.to.declaration.dataset !== declaration.dataset;
2189
+ if (edge.to === query) return edge.from.declaration.dataset !== declaration.dataset;
2190
+ return false;
2191
+ });
2192
+ if (spanning.length) {
2193
+ throw new ValidationError(
2194
+ `Query '${query.name}' can't move to dataset '${declaration.dataset}': its cross-filters ${spanning.map((edge) => `'${edge.id}'`).join(", ")} would span two datasets. Remove them first.`,
2195
+ query.name
2196
+ );
2197
+ }
2198
+ }
2199
+ const reshaped = declaration.aql !== previous.aql || declaration.dataset !== previous.dataset;
2200
+ const sort = changes.sort ?? (reshaped ? [] : query.sort);
2201
+ if (reshaped) this.dropSelectionFrom(query.name);
2202
+ query.replaceDeclaration(declaration, dataset, sort);
2203
+ }
2204
+ /** @internal Backs `remove()` on a query or a control: takes it out, with its edges. */
2205
+ removeEntity(entity) {
2206
+ if (entity instanceof Query) {
2207
+ if (this._queries.get(entity.name) !== entity) {
2208
+ throw new ValidationError(`Query '${entity.name}' belongs to a different app.`, entity.name);
2209
+ }
2210
+ this._queries.delete(entity.name);
2211
+ this.dropEdges((edge) => edge.to === entity || edge.from === entity);
2212
+ this.dropSelectionFrom(entity.name);
2213
+ } else {
2214
+ if (this._controls.get(entity.name) !== entity) {
2215
+ throw new ValidationError(`Control '${entity.name}' belongs to a different app.`, entity.name);
2216
+ }
2217
+ this._controls.delete(entity.name);
2218
+ this.dropEdges((edge) => edge.from === entity);
2219
+ }
2220
+ entity.markRemoved();
2221
+ this.removedListeners.forEach((listener) => {
2222
+ try {
2223
+ listener(entity);
2224
+ } catch {
2225
+ }
2226
+ });
2227
+ this.notify();
2228
+ }
2229
+ /** @internal Backs `remove()` on an edge. */
2230
+ removeEdge(edge) {
2231
+ if (!this.dropEdges((candidate) => candidate === edge)) {
2232
+ throw new ValidationError(`Edge '${edge.id}' belongs to a different app.`, edge.from.name);
2233
+ }
2234
+ this.notify();
2235
+ }
2236
+ /** @internal Each query or control removed from this app, for what the kernel shows about one. */
2237
+ onRemoved(listener) {
2238
+ this.removedListeners.add(listener);
2239
+ return () => {
2240
+ this.removedListeners.delete(listener);
2241
+ };
2242
+ }
2243
+ /** Takes out the edges that match; whether any did. */
2244
+ dropEdges(matches) {
2245
+ const gone = this.mappings.filter(matches);
2246
+ gone.forEach((edge) => edge.markRemoved());
2247
+ const keep = (list) => {
2248
+ const kept = list.filter((edge) => !gone.includes(edge));
2249
+ list.splice(0, list.length, ...kept);
2250
+ };
2251
+ keep(this._mappings);
2252
+ keep(this._crossFilters);
2253
+ return gone.length > 0;
2254
+ }
2255
+ /** Clears the selection, the reader's and the applied one, when it was made in this query. */
2256
+ dropSelectionFrom(name) {
2257
+ if (this._selection?.source === name) this._selection = void 0;
2258
+ if (this._appliedSelection?.source === name) this._appliedSelection = void 0;
2259
+ }
1785
2260
  /* ----------------------------------------------------------------
1786
2261
  Selection
1787
2262
  ---------------------------------------------------------------- */
@@ -1812,12 +2287,37 @@ var App = class extends Observable {
1812
2287
  get timezone() {
1813
2288
  return this._timezone;
1814
2289
  }
2290
+ /**
2291
+ * The app's own, like `setTimezone`: for its UI, and for its queries unless
2292
+ * `query.default.input.weekStartDay` says otherwise. Changing it makes every query it reaches dirty.
2293
+ */
2294
+ setWeekStartDay(day) {
2295
+ assertWeekStartDay(day, "The app", "weekStartDay", "sets");
2296
+ this._weekStartDay = day;
2297
+ this.notify();
2298
+ }
2299
+ /** The app's own week start day, for its UI: undefined when it declares none. */
2300
+ get weekStartDay() {
2301
+ return this._weekStartDay;
2302
+ }
2303
+ /**
2304
+ * What the app's queries get in their input when they set none: its `query.default.input`, or else
2305
+ * its own timezone and week start day. A value absent from both is left to the backend's default.
2306
+ */
2307
+ get queryInputDefaults() {
2308
+ const timezone = this.queryInput.timezone ?? this._timezone;
2309
+ const weekStartDay = this.queryInput.weekStartDay ?? this._weekStartDay;
2310
+ return { ...timezone ? { timezone } : {}, ...weekStartDay ? { weekStartDay } : {} };
2311
+ }
1815
2312
  /* ----------------------------------------------------------------
1816
2313
  AppContext
1817
2314
  ---------------------------------------------------------------- */
1818
2315
  datasetIndex(uname, entity) {
1819
2316
  return resolveDataset(this.datasets, uname, entity);
1820
2317
  }
2318
+ filterDataset(entity, declaration) {
2319
+ return declaration.dataset ? this.datasetIndex(declaration.dataset, entity) : this.soleDataset(entity, declaration.field);
2320
+ }
1821
2321
  mappingsTo(queryName) {
1822
2322
  return this._mappings.filter((mapping) => mapping.to.name === queryName);
1823
2323
  }
@@ -1906,7 +2406,7 @@ var App = class extends Observable {
1906
2406
  conditions: this.selectionConditionsFor(query.name, "applied"),
1907
2407
  expression: this.selectionExpressionFor(query.name, "applied")
1908
2408
  },
1909
- { timezone: this._timezone }
2409
+ this.queryInputDefaults
1910
2410
  );
1911
2411
  }
1912
2412
  select(query, rows, fields) {
@@ -1925,9 +2425,15 @@ var App = class extends Observable {
1925
2425
  /* ----------------------------------------------------------------
1926
2426
  Execution
1927
2427
  ---------------------------------------------------------------- */
1928
- /** True when a control or the selection has changed since the queries reading it last ran. */
2428
+ /**
2429
+ * True when the next `execute()` would apply something: a control or the selection changed since
2430
+ * the queries reading them last ran, a query changed since its last run (edited, or an edge or a
2431
+ * control taken from it), or, once the app has run, a query was created and never run. A run in
2432
+ * flight with the current inputs is not a change, and nor is a failed run: retrying it is
2433
+ * `execute()`'s, unasked.
2434
+ */
1929
2435
  get hasChanges() {
1930
- return [...this._controls.values()].some((control) => control.isDirty) || this.isSelectionDirty;
2436
+ return [...this._controls.values()].some((control) => control.isDirty) || this.isSelectionDirty || [...this._queries.values()].some((query) => query.hasUnappliedChange(this.selectionCommitted));
1931
2437
  }
1932
2438
  /**
1933
2439
  * False before the first execution, matching `Control.isDirty`: with nothing applied there is
@@ -1953,43 +2459,73 @@ var App = class extends Observable {
1953
2459
  });
1954
2460
  const context = {
1955
2461
  backend: this.backend,
1956
- timezone: this._timezone,
2462
+ ...this.queryInputDefaults,
1957
2463
  bustCache: options.bustCache
1958
2464
  };
1959
2465
  const succeeded = [];
1960
2466
  const failed = [];
1961
2467
  await Promise.all(targets.map(async (query) => {
1962
- const controller = new AbortController();
1963
- query.controller = controller;
1964
- const signature = query.signature();
1965
- query.markExecuting();
1966
- try {
1967
- const result = await runQuery(
1968
- query,
1969
- this.mappingsTo(query.name),
1970
- {
1971
- conditions: this.selectionConditionsFor(query.name, "applied"),
1972
- expression: this.selectionExpressionFor(query.name, "applied")
1973
- },
1974
- context,
1975
- controller.signal
1976
- );
1977
- if (superseded(query, controller)) return;
1978
- query.markSuccess(result, signature, false);
1979
- succeeded.push(query.name);
1980
- } catch (err) {
1981
- if (superseded(query, controller)) return;
1982
- if (isAbort(err)) return;
1983
- const error = toDataAppError(err, query.name);
1984
- query.markError(error);
1985
- reportError("call.query", error);
1986
- failed.push(query.name);
1987
- } finally {
1988
- if (query.controller === controller) query.controller = void 0;
1989
- }
2468
+ const outcome = await this.run(query, query.signature(), context);
2469
+ if (outcome === "succeeded") succeeded.push(query.name);
2470
+ else if (outcome === "failed") failed.push(query.name);
1990
2471
  }));
1991
2472
  return { succeeded, failed };
1992
2473
  }
2474
+ /**
2475
+ * @internal Backs `query.execute()`: that query alone, with what is applied, committing nothing.
2476
+ * Its signature is the applied one, so a query the reader has pending changes for stays dirty.
2477
+ */
2478
+ async executeQuery(query, options = {}) {
2479
+ if (!query.shouldRunAlone(options.force)) return { succeeded: [], failed: [] };
2480
+ query.controller?.abort();
2481
+ query.resetPage();
2482
+ const outcome = await this.run(query, query.signature("applied"), {
2483
+ backend: this.backend,
2484
+ ...this.queryInputDefaults,
2485
+ bustCache: options.bustCache
2486
+ });
2487
+ return {
2488
+ succeeded: outcome === "succeeded" ? [query.name] : [],
2489
+ failed: outcome === "failed" ? [query.name] : []
2490
+ };
2491
+ }
2492
+ /**
2493
+ * One query's run from its first page, with the applied inputs, recorded under `signature`.
2494
+ * Undefined when a newer run took the query over, or it was aborted.
2495
+ */
2496
+ async run(query, signature, context) {
2497
+ const controller = new AbortController();
2498
+ query.controller = controller;
2499
+ query.runningSignature = signature;
2500
+ query.markExecuting();
2501
+ try {
2502
+ const request = buildRequest(
2503
+ query,
2504
+ this.mappingsTo(query.name),
2505
+ {
2506
+ conditions: this.selectionConditionsFor(query.name, "applied"),
2507
+ expression: this.selectionExpressionFor(query.name, "applied")
2508
+ },
2509
+ context
2510
+ );
2511
+ const { result, run } = await runQuery(query, request, context.backend, controller.signal, this.stampOf(query));
2512
+ if (superseded(query, controller)) return void 0;
2513
+ query.markSuccess(result, signature, false, run);
2514
+ return "succeeded";
2515
+ } catch (err) {
2516
+ if (superseded(query, controller)) return void 0;
2517
+ if (isAbort(err)) return void 0;
2518
+ const error = toDataAppError(err, query.name);
2519
+ query.markError(error, false, signature);
2520
+ reportError("call.query", error);
2521
+ return "failed";
2522
+ } finally {
2523
+ if (query.controller === controller) {
2524
+ query.controller = void 0;
2525
+ query.runningSignature = void 0;
2526
+ }
2527
+ }
2528
+ }
1993
2529
  /** Re-runs everything and asks the server to skip its result cache. */
1994
2530
  async refresh() {
1995
2531
  return this.execute({ force: true, bustCache: true });
@@ -2000,32 +2536,30 @@ var App = class extends Observable {
2000
2536
  /** @internal Backs `query.fetchMore()`. Rejects, so an explicit page request reports its failure. */
2001
2537
  async fetchPage(query) {
2002
2538
  const controller = new AbortController();
2539
+ const signature = query.signature("applied");
2003
2540
  query.controller = controller;
2004
- const signature = query.signature();
2541
+ query.runningSignature = signature;
2005
2542
  query.markExecuting();
2006
2543
  try {
2007
- const result = await runQuery(
2008
- query,
2009
- this.mappingsTo(query.name),
2010
- {
2011
- conditions: this.selectionConditionsFor(query.name, "applied"),
2012
- expression: this.selectionExpressionFor(query.name, "applied")
2013
- },
2014
- {
2015
- backend: this.backend,
2016
- timezone: this._timezone
2017
- },
2018
- controller.signal
2019
- );
2544
+ const request = query.run ? pageRequest(query, query.run) : buildRequest(query, this.mappingsTo(query.name), {
2545
+ conditions: this.selectionConditionsFor(query.name, "applied"),
2546
+ expression: this.selectionExpressionFor(query.name, "applied")
2547
+ }, { backend: this.backend, ...this.queryInputDefaults });
2548
+ const { result } = await runQuery(query, request, this.backend, controller.signal, this.stampOf(query));
2549
+ if (superseded(query, controller)) return;
2020
2550
  query.markSuccess(result, signature, true);
2021
2551
  } catch (err) {
2552
+ if (superseded(query, controller)) return;
2022
2553
  query.rewindPage();
2023
2554
  if (isAbort(err)) return;
2024
2555
  const error = toDataAppError(err, query.name);
2025
2556
  query.markError(error, true);
2026
2557
  throw error;
2027
2558
  } finally {
2028
- if (query.controller === controller) query.controller = void 0;
2559
+ if (query.controller === controller) {
2560
+ query.controller = void 0;
2561
+ query.runningSignature = void 0;
2562
+ }
2029
2563
  }
2030
2564
  }
2031
2565
  /**
@@ -2041,11 +2575,13 @@ var App = class extends Observable {
2041
2575
  conditions: this.selectionConditionsFor(query.name, "applied"),
2042
2576
  expression: this.selectionExpressionFor(query.name, "applied")
2043
2577
  },
2044
- { backend: this.backend, timezone: this._timezone, title: this.title },
2045
- options
2578
+ { ...this.queryInputDefaults, title: this.title },
2579
+ options,
2580
+ // As the result on screen ran, so the file holds what the reader sees.
2581
+ query.run
2046
2582
  );
2047
2583
  try {
2048
- return await send(request, options.signal ?? new AbortController().signal);
2584
+ return await send(request, options.signal ?? new AbortController().signal, { app: this.index, query: query.name });
2049
2585
  } catch (err) {
2050
2586
  if (isAbort(err)) throw err;
2051
2587
  throw toDataAppError(err, query.name, "The export failed.");
@@ -2065,6 +2601,7 @@ var App = class extends Observable {
2065
2601
  return {
2066
2602
  ...this.title ? { title: this.title } : {},
2067
2603
  ...this._timezone ? { timezone: this._timezone } : {},
2604
+ ...this._weekStartDay ? { weekStartDay: this._weekStartDay } : {},
2068
2605
  queries: Object.fromEntries([...this._queries.entries()].map(([name, q]) => [name, q.toJSON()])),
2069
2606
  filters: byKind("filter"),
2070
2607
  dateDrills: byKind("dateDrill"),
@@ -2087,6 +2624,8 @@ var App = class extends Observable {
2087
2624
  return {
2088
2625
  ...this.title ? { title: this.title } : {},
2089
2626
  ...this._timezone ? { timezone: this._timezone } : {},
2627
+ ...this._weekStartDay ? { weekStartDay: this._weekStartDay } : {},
2628
+ ...Object.keys(this.queryInput).length > 0 ? { queryInput: { ...this.queryInput } } : {},
2090
2629
  hasChanges: this.hasChanges,
2091
2630
  declaration: this.toJSON(),
2092
2631
  queries: Object.fromEntries(
@@ -2121,6 +2660,10 @@ var App = class extends Observable {
2121
2660
  /* ----------------------------------------------------------------
2122
2661
  Internals
2123
2662
  ---------------------------------------------------------------- */
2663
+ /** What a query's calls are stamped with, so the host can show each under its query. */
2664
+ stampOf(query) {
2665
+ return { app: this.index, query: query.name, id: query.id };
2666
+ }
2124
2667
  assertNameFree(name, kind) {
2125
2668
  assertUniqueName([...this._queries.keys(), ...this._controls.keys()], name, kind);
2126
2669
  }
@@ -2376,6 +2919,16 @@ function namedMember(member, api) {
2376
2919
  }
2377
2920
  });
2378
2921
  }
2922
+ function withQueryId(sdk, { app, query, variant }) {
2923
+ const queries = sdk.apps[app]?.queries ?? {};
2924
+ const id = Object.hasOwn(queries, query) ? queries[query]?.id : void 0;
2925
+ return {
2926
+ app,
2927
+ query,
2928
+ ...id !== void 0 && { id },
2929
+ ...variant !== void 0 && { variant }
2930
+ };
2931
+ }
2379
2932
  function createKernel(plugin, shared, entities) {
2380
2933
  const { window: win, sdk, endpoint } = shared;
2381
2934
  let loading;
@@ -2394,7 +2947,7 @@ function createKernel(plugin, shared, entities) {
2394
2947
  if (!app) throw new ValidationError(`Query '${String(query?.name)}' belongs to no app.`, query?.name);
2395
2948
  return app.requestFor(query);
2396
2949
  },
2397
- call: (name, request, signal) => endpoint.call(name, request ?? null, signal),
2950
+ call: (name, request, signal, stamp) => endpoint.call(name, request ?? null, signal, stamp && withQueryId(sdk, stamp)),
2398
2951
  emit: (name, payload) => endpoint.emit(`${plugin}.${name}`, payload ?? null),
2399
2952
  handle(name, handler) {
2400
2953
  shared.handlers.set(`${plugin}.${name}`, handler);
@@ -2440,6 +2993,17 @@ function createKernel(plugin, shared, entities) {
2440
2993
  };
2441
2994
  }
2442
2995
 
2996
+ // src/app/core.ts
2997
+ function installCore(kernel) {
2998
+ kernel.handle("execute", async () => {
2999
+ const summaries = await Promise.all(kernel.sdk.apps.map((app) => app.refresh()));
3000
+ return {
3001
+ succeeded: summaries.flatMap((summary) => summary.succeeded),
3002
+ failed: summaries.flatMap((summary) => summary.failed)
3003
+ };
3004
+ });
3005
+ }
3006
+
2443
3007
  // src/app/pick.ts
2444
3008
  function startPick(doc, handlers) {
2445
3009
  let current = null;
@@ -2620,7 +3184,7 @@ function bootstrap(win, setups = []) {
2620
3184
  endpoint.receive(event.data);
2621
3185
  });
2622
3186
  const backend = {
2623
- submitQuery: (request, signal) => endpoint.call("core.submitQuery", request, signal).then((result) => {
3187
+ submitQuery: (request, signal, stamp) => endpoint.call("core.submitQuery", request, signal, stamp).then((result) => {
2624
3188
  if (result.debug?.executedAt) result.debug.executedAt = new Date(result.debug.executedAt);
2625
3189
  return result;
2626
3190
  }),
@@ -2655,6 +3219,7 @@ function bootstrap(win, setups = []) {
2655
3219
  const own = createKernel("anfra", shared, { Query, Control });
2656
3220
  installReporting(own, win, provision.captureConsole === true);
2657
3221
  installInspection(own);
3222
+ installCore(createKernel("core", shared, { Query, Control }));
2658
3223
  shared.contentUi = installContentUi(own);
2659
3224
  own.on("theme", (theme) => {
2660
3225
  const resolved = resolveTheme(theme);