@altertable/data-app 0.75.0 → 0.77.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 (50) hide show
  1. package/README.md +56 -9
  2. package/REFERENCE.md +387 -333
  3. package/dist/chunks/{contract-B3s0ybE2.js → contract-BQsFReRp.js} +314 -237
  4. package/dist/chunks/contract-BQsFReRp.js.map +1 -0
  5. package/dist/chunks/{contract-DcPjfm0R.js → contract-VhY9V9wd.js} +184 -91
  6. package/dist/chunks/contract-VhY9V9wd.js.map +1 -0
  7. package/dist/chunks/{format-5hMYUWk3.js → date-time-range-value-CnlTr1U1.js} +8 -153
  8. package/dist/chunks/date-time-range-value-CnlTr1U1.js.map +1 -0
  9. package/dist/chunks/{diagnostics-DVwQ5PDK.js → diagnostics-Dyj-rUsY.js} +2 -2
  10. package/dist/chunks/{diagnostics-DVwQ5PDK.js.map → diagnostics-Dyj-rUsY.js.map} +1 -1
  11. package/dist/chunks/{operation-CGuN7Zcb.js → operation-BVRM-A5Y.js} +3 -3
  12. package/dist/chunks/{operation-CGuN7Zcb.js.map → operation-BVRM-A5Y.js.map} +1 -1
  13. package/dist/client/index.js +65 -50
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/core/config.js +1 -1
  16. package/dist/core/config.js.map +1 -1
  17. package/dist/core/contract.js +4 -4
  18. package/dist/core/format.js +149 -1
  19. package/dist/core/format.js.map +1 -0
  20. package/dist/internal.js +6 -308
  21. package/dist/internal.js.map +1 -1
  22. package/dist/server/index.js +3 -3
  23. package/dist/types/chunks/contract.d.ts +359 -599
  24. package/dist/types/chunks/contract2.d.ts +221 -0
  25. package/dist/types/chunks/date-time-range-value.d.ts +2 -28
  26. package/dist/types/chunks/date-time-range.d.ts +29 -0
  27. package/dist/types/chunks/index.d.ts +33 -5
  28. package/dist/types/client/index.d.ts +3 -3
  29. package/dist/types/core/config.d.ts +8 -4
  30. package/dist/types/core/contract.d.ts +5 -3
  31. package/dist/types/core/format.d.ts +2 -1
  32. package/dist/types/index.d.ts +2 -2
  33. package/dist/types/internal.d.ts +7 -5
  34. package/dist/types/server/index.d.ts +1 -1
  35. package/docs/app-authoring.md +15 -10
  36. package/docs/client.md +12 -7
  37. package/docs/contract.md +33 -50
  38. package/docs/data-context.md +9 -5
  39. package/docs/filters.md +295 -0
  40. package/docs/hosted-apps.md +4 -3
  41. package/docs/layout.md +24 -18
  42. package/docs/stories-and-export.md +19 -10
  43. package/docs/ui.md +7 -6
  44. package/docs/views.md +62 -26
  45. package/docs/widgets.md +38 -14
  46. package/package.json +16 -5
  47. package/dist/chunks/contract-B3s0ybE2.js.map +0 -1
  48. package/dist/chunks/contract-DcPjfm0R.js.map +0 -1
  49. package/dist/chunks/format-5hMYUWk3.js.map +0 -1
  50. package/docs/variables.md +0 -269
@@ -1,81 +1,14 @@
1
- import { _ as fixedUnitMilliseconds, g as serializeDateTimeRange, h as resolveDateTimeRange, m as parseDateTimeRange, n as formatDateRange, v as invariant } from "./format-5hMYUWk3.js";
2
- import { fromDate, parseDate, toCalendarDateTime, today } from "@internationalized/date";
3
- //#region src/core/date-time-range-contract.ts
4
- function createDateTimeRangeContract(options) {
5
- const { minDate, maxDate: sourceMaxDate, maxRangeDays, timeZone, completeDays } = options;
6
- function reference(now) {
7
- invariant(Number.isFinite(now.getTime()), "Invalid reference date.");
8
- return toCalendarDateTime(fromDate(now, timeZone)).toDate("UTC");
9
- }
10
- function bounds(now = /* @__PURE__ */ new Date()) {
11
- const date = reference(now).toISOString().slice(0, 10);
12
- const latest = parseDate(date).subtract({ days: completeDays === false ? 0 : 1 }).toString();
13
- const sourceMax = typeof sourceMaxDate === "function" ? sourceMaxDate() : sourceMaxDate;
14
- if (sourceMax) parseDate(sourceMax);
15
- return {
16
- minDate,
17
- maxDate: sourceMax && sourceMax < latest ? sourceMax : latest,
18
- maxRangeDays,
19
- timeZone
20
- };
21
- }
22
- function resolve(value, now = /* @__PURE__ */ new Date()) {
23
- const range = resolveDateTimeRange(parseDateTimeRange(value), reference(now));
24
- const limits = bounds(now);
25
- invariant(range.from, "Choose a bounded datetime range.");
26
- invariant(range.to.getTime() - range.from.getTime() <= maxRangeDays * fixedUnitMilliseconds.DAY, `Choose a range of at most ${maxRangeDays} days.`);
27
- invariant(!minDate || range.from >= parseDate(minDate).toDate("UTC"), "Range starts before available source coverage.");
28
- invariant(range.to <= parseDate(limits.maxDate).add({ days: 1 }).toDate("UTC"), "Range ends after available source coverage.");
29
- return {
30
- from: range.from,
31
- to: range.to
32
- };
33
- }
34
- function parse(value, now = /* @__PURE__ */ new Date()) {
35
- const range = parseDateTimeRange(value);
36
- resolve(range, now);
37
- return range;
38
- }
39
- function comparison(value, now = /* @__PURE__ */ new Date()) {
40
- const { from, to } = resolve(value, now);
41
- const previous = {
42
- from: /* @__PURE__ */ new Date(2 * from.getTime() - to.getTime()),
43
- to: from
44
- };
45
- try {
46
- return resolve(previous, now);
47
- } catch {
48
- return null;
49
- }
50
- }
51
- return {
52
- timeZone,
53
- bounds,
54
- /** Validate coverage and duration while preserving symbolic relative bounds. */
55
- parse,
56
- /** Resolve to UTC-rebased bounds using reporting-zone wall-clock fields, then validate policy. */
57
- resolve,
58
- /** Return the preceding equal-length interval, or null when source coverage excludes it. */
59
- comparison,
60
- /** Resolve both periods against one reference instant. Use these bounds for comparison queries. */
61
- request(value, compare = false, now = /* @__PURE__ */ new Date()) {
62
- const range = resolve(value, now);
63
- const previous = compare ? comparison(range, now) : null;
64
- invariant(!compare || previous, "Comparison is outside available source coverage.");
65
- return {
66
- range,
67
- comparison: previous
68
- };
69
- }
70
- };
71
- }
72
- //#endregion
1
+ import { i as parseDateTimeRange, l as invariant, o as serializeDateTimeRange } from "./date-time-range-value-CnlTr1U1.js";
73
2
  //#region src/core/keys.ts
74
3
  /** Separator for opaque composite keys, independent of URL and DOM ID formats. */
75
4
  const KEY_SEPARATOR = ":";
76
5
  //#endregion
77
6
  //#region src/core/dimension.ts
78
7
  const allSelection = { kind: "all" };
8
+ /** Selections are equal when they keep the same members, in any order. */
9
+ function selectionKey(value) {
10
+ return value.kind === "all" ? "all" : [value.kind, ...value.members.map(dimensionMemberKey).sort()].join(":");
11
+ }
79
12
  function dimensionMemberKey(member) {
80
13
  return member.kind === "missing" ? "missing" : [
81
14
  "value",
@@ -103,7 +36,7 @@ function createDimensionFilter(config, dynamic = false) {
103
36
  const maxSelected = config.maxSelected ?? (selectionMode === "single" ? 1 : 20);
104
37
  invariant(Number.isInteger(maxSelected) && maxSelected >= 1 && maxSelected <= 50 && (selectionMode !== "single" || maxSelected === 1), "Dimension selection limit is invalid.");
105
38
  const allowMissing = config.allowMissing ?? false;
106
- const defaultValue = allSelection;
39
+ const defaultValue = config.defaultValue ?? allSelection;
107
40
  function validMember(member) {
108
41
  if (!member || typeof member !== "object") return false;
109
42
  if (member.kind === "missing") return allowMissing;
@@ -119,12 +52,18 @@ function createDimensionFilter(config, dynamic = false) {
119
52
  const ids = value.members.map(dimensionMemberKey);
120
53
  return new Set(ids).size === ids.length;
121
54
  }
55
+ invariant(valid(defaultValue), `Invalid default selection for ${label}.`);
56
+ /** The default selection has no URL value; every member is explicit when it differs. */
122
57
  function encode(value) {
123
- return value.kind === "all" ? null : JSON.stringify({
58
+ if (same(value, defaultValue)) return null;
59
+ return value.kind === "all" ? JSON.stringify({ kind: "all" }) : JSON.stringify({
124
60
  kind: value.kind,
125
61
  members: value.members.map((member) => member.kind === "missing" ? ["m"] : ["v", member.value])
126
62
  });
127
63
  }
64
+ function same(left, right) {
65
+ return selectionKey(left) === selectionKey(right);
66
+ }
128
67
  function parse(raw) {
129
68
  if (raw === null) return defaultValue;
130
69
  if (raw.length > 4096) return defaultValue;
@@ -134,6 +73,7 @@ function createDimensionFilter(config, dynamic = false) {
134
73
  kind: "include",
135
74
  members: parsed
136
75
  } : parsed;
76
+ if (tokens?.kind === "all") return allSelection;
137
77
  if (!tokens || !Array.isArray(tokens.members)) return defaultValue;
138
78
  const value = {
139
79
  kind: tokens.kind,
@@ -163,9 +103,7 @@ function createDimensionFilter(config, dynamic = false) {
163
103
  clearValue: allSelection,
164
104
  history: config.history ?? "push",
165
105
  valid,
166
- same(left, right) {
167
- return encode(left) === encode(right);
168
- },
106
+ same,
169
107
  read(params) {
170
108
  return parse(params.get(key));
171
109
  },
@@ -268,14 +206,31 @@ function boundExpression(parameter, bound) {
268
206
  WHERE i < COALESCE(json_array_length(${json}, '${path}.offset'), 0)
269
207
  ) SELECT value FROM bounds ORDER BY i DESC LIMIT 1)`;
270
208
  }
271
- /** Expand bound references only in SQL code, leaving quoted text and comments untouched. */
272
- function expandDateTimeRangeParameters(statement, names) {
273
- const token = /[eE]'(?:\\.|''|[^'\\])*'|'(?:''|[^'])*'|"(?:""|[^"])*"|\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$|--[^\n]*(?:\n|$)|\/\*|\$([A-Za-z_][A-Za-z0-9_]*)(?:\.(from|to)\b)?/g;
209
+ //#endregion
210
+ //#region src/core/parameter-sql.ts
211
+ /** True for rows the selection keeps. Excluding values keeps missing values unless
212
+ * missing itself is excluded, matching the picker's semantics. */
213
+ function selectionExpression(parameter, valueType, column) {
214
+ const json = `$${parameter}`;
215
+ const values = `CAST(json_extract(${json}, '$.values') AS ${valueType === "number" ? "DOUBLE" : "VARCHAR"}[])`;
216
+ const missing = `CAST(json_extract(${json}, '$.missing') AS BOOLEAN)`;
217
+ const listed = `list_contains(${values}, ${column})`;
218
+ return `(CASE json_extract_string(${json}, '$.kind')
219
+ WHEN 'all' THEN TRUE
220
+ WHEN 'include' THEN CASE WHEN ${column} IS NULL THEN ${missing} ELSE ${listed} END
221
+ WHEN 'exclude' THEN CASE WHEN ${column} IS NULL THEN NOT ${missing} ELSE NOT ${listed} END
222
+ END)`;
223
+ }
224
+ /** Expand `$period.from`, `$period.to`, and `$country.matches(column)` references only
225
+ * in SQL code, leaving quoted text and comments untouched. */
226
+ function expandParameterReferences(statement, parameters) {
227
+ const token = /[eE]'(?:\\.|''|[^'\\])*'|'(?:''|[^'])*'|"(?:""|[^"])*"|\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$|--[^\n]*(?:\n|$)|\/\*|\$([A-Za-z_][A-Za-z0-9_]*)(?:\.(from|to)\b|\.matches\(\s*([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\s*\))?/g;
274
228
  let output = "";
275
229
  let position = 0;
276
230
  for (let match = token.exec(statement); match; match = token.exec(statement)) {
277
231
  output += statement.slice(position, match.index);
278
232
  const text = match[0];
233
+ const parameter = match[1] ? parameters.get(match[1]) : void 0;
279
234
  if (text === "/*") {
280
235
  let depth = 1;
281
236
  let end = token.lastIndex;
@@ -293,7 +248,8 @@ function expandDateTimeRangeParameters(statement, names) {
293
248
  const end = closing < 0 ? statement.length : closing + text.length;
294
249
  output += statement.slice(match.index, end);
295
250
  token.lastIndex = end;
296
- } else if (match[1] && names.has(match[1]) && match[2]) output += boundExpression(match[1], match[2]);
251
+ } else if (parameter?.type === "dateTimeRange" && match[2]) output += boundExpression(match[1], match[2]);
252
+ else if (parameter?.type === "dimension" && match[3]) output += selectionExpression(match[1], parameter.valueType, match[3]);
297
253
  else output += text;
298
254
  position = token.lastIndex;
299
255
  }
@@ -303,6 +259,18 @@ function expandDateTimeRangeParameters(statement, names) {
303
259
  //#region src/core/queries.ts
304
260
  const MAX_QUERY_ROWS = 1e4;
305
261
  const QUERY_CAST_ERROR = "##ERROR##";
262
+ /** Bind a selection as JSON the expanded predicate reads: kind, listed values, and
263
+ * whether missing values are listed. */
264
+ function serializeSelection(key, valueType, value) {
265
+ const selection = typeof value === "string" ? JSON.parse(value) : value;
266
+ if (!(!!selection && typeof selection === "object" && (selection.kind === "all" || (selection.kind === "include" || selection.kind === "exclude") && Array.isArray(selection.members) && selection.members.length > 0 && selection.members.every((member) => member?.kind === "missing" || member?.kind === "value" && (valueType === "number" ? typeof member.value === "number" && Number.isFinite(member.value) : typeof member.value === "string"))))) throw new Error(`Parameter ${key} is not a ${valueType} dimension selection.`);
267
+ if (selection.kind === "all") return JSON.stringify({ kind: "all" });
268
+ return JSON.stringify({
269
+ kind: selection.kind,
270
+ values: selection.members.flatMap((member) => member.kind === "value" ? [member.value] : []),
271
+ missing: selection.members.some((member) => member.kind === "missing")
272
+ });
273
+ }
306
274
  function isQueryParameterValue(value) {
307
275
  return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
308
276
  }
@@ -318,7 +286,11 @@ function snapshotQueries(definitions) {
318
286
  return Object.freeze(Object.fromEntries(Object.entries(definitions).map(([name, query]) => {
319
287
  invariant(!!name.trim() && !!query.statement.trim(), "Queries need a name and SQL statement.");
320
288
  const params = Object.freeze(Object.fromEntries(Object.entries(query.params).map(([key, declaration]) => {
321
- if (declaration.type === "dateTimeRange") invariant(/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && declaration.nullable !== true, "Datetime ranges require a SQL parameter name and cannot be nullable.");
289
+ if (declaration.type === "dateTimeRange" || declaration.type === "dimension") invariant(/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && declaration.nullable !== true, "Range and dimension parameters require a SQL parameter name and cannot be nullable.");
290
+ if (declaration.type === "dimension") {
291
+ invariant((declaration.valueType === "string" || declaration.valueType === "number") && !Object.hasOwn(declaration, "defaultValue"), `Dimension parameter ${key} in query ${name} needs a string or number valueType and no default.`);
292
+ return [key, Object.freeze({ ...declaration })];
293
+ }
322
294
  invariant(!Object.hasOwn(declaration, "defaultValue") || (declaration.type === "dateTimeRange" ? !!parseDateTimeRange(declaration.defaultValue) : isQueryParameterValue(declaration.defaultValue)), `Invalid default for parameter ${key} in query ${name}.`);
323
295
  return [key, declaration.type === "dateTimeRange" ? Object.freeze({
324
296
  ...declaration,
@@ -328,7 +300,7 @@ function snapshotQueries(definitions) {
328
300
  const projectionEntries = Object.entries(query.projections);
329
301
  invariant(projectionEntries.length > 0 && projectionEntries.every(([alias]) => !!alias.trim()), "Queries need at least one named projection.");
330
302
  return [name, Object.freeze({
331
- statement: expandDateTimeRangeParameters(query.statement, new Set(Object.entries(query.params).filter(([, p]) => p.type === "dateTimeRange").map(([key]) => key))),
303
+ statement: expandParameterReferences(query.statement, new Map(Object.entries(query.params).flatMap(([key, p]) => p.type === "dateTimeRange" || p.type === "dimension" ? [[key, p]] : []))),
332
304
  params,
333
305
  projections: Object.freeze(Object.fromEntries(projectionEntries.map(([alias, field]) => [alias, snapshotField(field)])))
334
306
  })];
@@ -381,6 +353,7 @@ function resolveQueryParameters(declarations, values, context) {
381
353
  return Object.fromEntries(Object.entries(declarations).map(([key, declaration]) => {
382
354
  const value = Object.hasOwn(context, key) ? context[key] : Object.hasOwn(values, key) && values[key] !== void 0 ? values[key] : declaration.defaultValue;
383
355
  if (value === void 0) throw new Error(`Missing parameter ${key}.`);
356
+ if (declaration.type === "dimension") return [key, serializeSelection(key, declaration.valueType, value)];
384
357
  if (declaration.type === "dateTimeRange") return [key, serializeDateTimeRange(parseDateTimeRange(typeof value === "string" ? JSON.parse(value) : value))];
385
358
  const nullable = declaration.type === "null" || declaration.nullable === true;
386
359
  if (!(value === null ? nullable : typeof value === declaration.type && isQueryParameterValue(value))) throw new Error(`Parameter ${key} does not match ${declaration.type}.`);
@@ -391,7 +364,6 @@ function resolveQueryParameters(declarations, values, context) {
391
364
  //#region src/core/dimension-source.ts
392
365
  const dimensionSource = Symbol("data-app.dimensionSource");
393
366
  const sources = /* @__PURE__ */ new WeakMap();
394
- const parserVariables = /* @__PURE__ */ new WeakMap();
395
367
  const selectorsKey = Symbol.for("@altertable/data-app/dimension-selectors");
396
368
  const ownerKey = Symbol.for("@altertable/data-app/dimension-selector-owner");
397
369
  const invalidMemberKey = Symbol.for("@altertable/data-app/dimension-member-error");
@@ -401,36 +373,6 @@ var DimensionMembershipError = class extends Error {
401
373
  return value instanceof Error && value[invalidMemberKey] === true;
402
374
  }
403
375
  };
404
- /** Validate named variable values at the operation boundary. Date inputs belong to the base parser. */
405
- function variableInput(parse, variables) {
406
- const previous = parserVariables.get(parse) ?? {};
407
- const definitions = { ...variables };
408
- for (const [name, variable] of Object.entries(definitions)) invariant(!previous[name] || previous[name] === variable, `Variable input ${name} is already declared.`);
409
- function parser(value) {
410
- invariant(value && typeof value === "object" && !Array.isArray(value), "Expected variable input.");
411
- const input = parse(value);
412
- invariant(input && typeof input === "object" && !Array.isArray(input), "Expected parsed input object.");
413
- const values = {};
414
- for (const [name, variable] of Object.entries(definitions)) {
415
- const selected = value[name];
416
- if (variable.kind === "dateTimeRangeComparison") {
417
- values[name] = variable.parseInput(selected);
418
- continue;
419
- }
420
- invariant(variable.valid(selected), `Invalid ${variable.label ?? name}.`);
421
- values[name] = variable.kind === "dateTimeRange" ? variable.parse(selected) : selected;
422
- }
423
- return {
424
- ...input,
425
- ...values
426
- };
427
- }
428
- parserVariables.set(parser, {
429
- ...previous,
430
- ...definitions
431
- });
432
- return parser;
433
- }
434
376
  /** A query supplies independent options and exact member lookup; it declares a nullable `member` parameter. */
435
377
  function bindDimensionSource(config, queries) {
436
378
  invariant(!config.allowMissing, "Source dimensions require concrete members.");
@@ -440,7 +382,7 @@ function bindDimensionSource(config, queries) {
440
382
  const { value, label, count } = query.projections;
441
383
  invariant(member.type === config.valueType && member.nullable === true && value?.type === config.valueType && value.nullable !== true && label?.type === "string" && label.nullable !== true && (!count || count.type === "number" && count.nullable !== true), "Dimension sources require a matching nullable member and concrete value, label, and count projections.");
442
384
  const operation = `__dimension:${config.key}`;
443
- const variable = Object.assign(createDimensionFilter({
385
+ const filter = Object.assign(createDimensionFilter({
444
386
  ...config,
445
387
  valueType: config.valueType,
446
388
  options: []
@@ -448,42 +390,43 @@ function bindDimensionSource(config, queries) {
448
390
  optionsSource: "query",
449
391
  [dimensionSource]: Object.freeze({ operation })
450
392
  });
451
- sources.set(variable, {
393
+ sources.set(filter, {
452
394
  query: config.source.query,
453
395
  queries
454
396
  });
455
- return variable;
397
+ return filter;
456
398
  }
457
- async function loadOptions(variable, member, query) {
458
- const result = await query(sources.get(variable).query, { member }, { limit: member === null ? 200 : 2 });
399
+ async function loadOptions(filter, member, query) {
400
+ const result = await query(sources.get(filter).query, { member }, { limit: member === null ? 200 : 2 });
459
401
  const names = result.columns.map((column) => column.name);
460
402
  invariant(new Set(names).size === names.length && names.includes("value") && names.includes("label"), "Dimension source must return value and label.");
461
- const options = parseFacetOptions(result.rows, variable);
462
- if (member !== null && (options.length !== 1 || options[0].value !== member)) throw new DimensionMembershipError(`Invalid ${variable.label} member.`);
403
+ const options = parseFacetOptions(result.rows, filter);
404
+ if (member !== null && (options.length !== 1 || options[0].value !== member)) throw new DimensionMembershipError(`Invalid ${filter.label} member.`);
463
405
  return options;
464
406
  }
465
- async function validateVariableInput(parser, input, query) {
466
- for (const [name, variable] of Object.entries(parserVariables.get(parser) ?? {})) {
467
- if (variable.kind !== "dimension" || !sources.has(variable)) continue;
407
+ /** Source dimension selections must name members the source query returns. */
408
+ async function validateSourceMembers(filters, input, query) {
409
+ for (const [name, filter] of Object.entries(filters)) {
410
+ if (filter.kind !== "dimension" || !sources.has(filter)) continue;
468
411
  const selection = input[name];
469
412
  if (selection.kind === "all") continue;
470
- for (const member of selection.members) if (member.kind === "value") await loadOptions(variable, member.value, query);
413
+ for (const member of selection.members) if (member.kind === "value") await loadOptions(filter, member.value, query);
471
414
  }
472
415
  }
473
416
  function attachDimensionSelectors(operation, queries) {
474
417
  const selectors = {};
475
- for (const variable of Object.values(parserVariables.get(operation.input) ?? {})) {
476
- if (variable.kind !== "dimension" || !(dimensionSource in variable)) continue;
477
- const source = sources.get(variable);
418
+ for (const filter of Object.values(operation.filters ?? {})) {
419
+ if (filter.kind !== "dimension" || !(dimensionSource in filter)) continue;
420
+ const source = sources.get(filter);
478
421
  if (!source) continue;
479
422
  invariant(JSON.stringify(source.queries[source.query]) === JSON.stringify(queries[source.query]), "Dimension sources must belong to the operation query registry.");
480
- const name = variable[dimensionSource].operation;
481
- invariant(!selectors[name] || selectors[name][ownerKey] === variable, "Dimension source keys must be unique across the app.");
423
+ const name = filter[dimensionSource].operation;
424
+ invariant(!selectors[name] || selectors[name][ownerKey] === filter, "Dimension source keys must be unique across the app.");
482
425
  selectors[name] = {
483
426
  input(value) {
484
427
  invariant(value && typeof value === "object", "Invalid dimension request.");
485
428
  const member = value.member;
486
- invariant(member === null || variable.valid({
429
+ invariant(member === null || filter.valid({
487
430
  kind: "include",
488
431
  members: [{
489
432
  kind: "value",
@@ -500,7 +443,7 @@ function attachDimensionSelectors(operation, queries) {
500
443
  },
501
444
  queryNames: { [source.query]: source.query },
502
445
  async run(context, input) {
503
- return loadOptions(variable, input.member, async (name, params, options) => {
446
+ return loadOptions(filter, input.member, async (name, params, options) => {
504
447
  const definition = queries[name];
505
448
  return decodeQueryResult(await context.lakehouse.queryAll(definition.statement, {
506
449
  name,
@@ -511,7 +454,7 @@ function attachDimensionSelectors(operation, queries) {
511
454
  });
512
455
  }
513
456
  };
514
- Object.defineProperty(selectors[name], ownerKey, { value: variable });
457
+ Object.defineProperty(selectors[name], ownerKey, { value: filter });
515
458
  }
516
459
  Object.defineProperty(operation, selectorsKey, { value: selectors });
517
460
  }
@@ -525,115 +468,207 @@ function withDimensionSelectors(operations) {
525
468
  return expanded;
526
469
  }
527
470
  //#endregion
528
- //#region src/authoring/contract.ts
529
- /**
530
- * Shared operation contracts and input validation for browser and server.
531
- * @module @altertable/data-app/contract
532
- * @see https://github.com/altertable-ai/data-app/blob/main/docs/contract.md
533
- */
534
- function parseEmptyInput(value) {
535
- invariant(typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0, "This operation takes no inputs.");
536
- return {};
471
+ //#region src/core/app-filters.ts
472
+ /** Name filters once in the app. URL keys must be unique across its controls. */
473
+ function defineAppFilters(filters) {
474
+ const owners = /* @__PURE__ */ new Map();
475
+ for (const [name, filter] of Object.entries(filters)) {
476
+ const presentation = filter.presentation;
477
+ invariant(presentation === void 0 || presentation !== null && typeof presentation === "object" && !Array.isArray(presentation) && (presentation.control === void 0 || presentation.control === "toolbar" || presentation.control === "widget") && (presentation.group === void 0 || presentation.group === "scope" || presentation.group === "display") && (presentation.prominence === void 0 || presentation.prominence === "primary" || presentation.prominence === "secondary"), `Filter ${name} has invalid presentation.`);
478
+ for (const key of filter.urlKeys) {
479
+ invariant(![
480
+ "view",
481
+ "about",
482
+ "tab",
483
+ "present",
484
+ "step",
485
+ "details"
486
+ ].includes(key), `Filter ${name} uses reserved URL key: ${key}.`);
487
+ invariant(!!key && !owners.has(key), `Filter ${name} has an empty or duplicate URL key: ${key}.`);
488
+ owners.set(key, name);
489
+ }
490
+ }
491
+ return filters;
537
492
  }
538
- function parseTrue(value) {
539
- invariant(value === true, "Expected a successful check.");
540
- return true;
493
+ /** Search query state; typing replaces history by default. Operations reject text
494
+ * longer than `maxLength` (200 by default). */
495
+ function searchFilter({ key, label, defaultValue = "", history = "replace", maxLength = 200 }) {
496
+ invariant(Number.isSafeInteger(maxLength) && maxLength > 0, `Search ${key} needs a positive maxLength.`);
497
+ function valid(value) {
498
+ return typeof value === "string" && value.length <= maxLength;
499
+ }
500
+ invariant(valid(defaultValue), `Search ${key} default exceeds maxLength.`);
501
+ return {
502
+ kind: "search",
503
+ label: label ?? key,
504
+ urlKeys: [key],
505
+ defaultValue,
506
+ clearValue: "",
507
+ describe: (value) => value,
508
+ history,
509
+ read(params) {
510
+ const value = params.get(key);
511
+ return value !== null && valid(value) ? value : defaultValue;
512
+ },
513
+ write(value) {
514
+ return { [key]: value === defaultValue ? null : value };
515
+ },
516
+ valid,
517
+ same(left, right) {
518
+ return left === right;
519
+ }
520
+ };
541
521
  }
542
- /** The immediately preceding, equally long set of calendar days. */
543
- function previousDateRange({ start, end }) {
544
- const first = parseDate(start);
545
- const days = (parseDate(end).toDate("UTC").getTime() - first.toDate("UTC").getTime()) / fixedUnitMilliseconds.DAY + 1;
546
- invariant(days >= 1, "Date range must start before it ends.");
547
- const previousEnd = first.subtract({ days: 1 });
522
+ /** Validate labeled choices before controls or URL state consume them. */
523
+ function validateChoiceOptions(options) {
524
+ invariant(options.length > 0 && options.every((option) => !!option.id.trim() && !!option.label.trim()) && new Set(options.map((option) => option.id)).size === options.length, "Choices require nonempty, unique IDs and labels.");
525
+ }
526
+ /** One choice that narrows the included data. */
527
+ function choiceFilter(options) {
528
+ return createChoice(options);
529
+ }
530
+ /** One choice that changes how results are shown, such as a chart breakdown or sort order.
531
+ * Clearing filters keeps it; pass `view.breakdown(name)` to render it beside its chart. */
532
+ function displayChoice(options) {
533
+ const presentation = {
534
+ ...options.presentation,
535
+ group: "display"
536
+ };
548
537
  return {
549
- start: previousEnd.subtract({ days: days - 1 }).toString(),
550
- end: previousEnd.toString()
538
+ ...createChoice(options),
539
+ presentation
551
540
  };
552
541
  }
553
- /** One source policy for the server parser, URL variable, and displayed reporting period. */
554
- function defineDateRangeContract({ minDate, maxDate, maxRangeDays, timeZone, completeDays }) {
555
- invariant(Number.isInteger(maxRangeDays) && maxRangeDays > 0, "Date range needs a positive maxRangeDays.");
556
- if (minDate) parseDate(minDate);
557
- if (typeof maxDate === "string") parseDate(maxDate);
558
- today(timeZone);
559
- const datetime = createDateTimeRangeContract({
560
- minDate,
561
- maxDate,
562
- maxRangeDays,
563
- timeZone,
564
- completeDays
565
- });
566
- const bounds = datetime.bounds;
567
- function period({ start, end }) {
568
- return {
569
- kind: "calendar",
570
- start,
571
- end,
572
- timeZone
573
- };
574
- }
575
- function describeInput(input) {
576
- return `${formatDateRange(input)} ${timeZone}`;
577
- }
578
- function comparison(input) {
579
- const previous = previousDateRange(input);
580
- return minDate && previous.start < minDate ? null : previous;
581
- }
582
- function request(value, compare = false) {
583
- const range = parseDateRangeInput(value, bounds());
584
- const previous = compare ? comparison(range) : null;
585
- invariant(!compare || previous, "Comparison is outside available source coverage.");
586
- return {
587
- range,
588
- comparison: previous
589
- };
590
- }
591
- function parseRequest(value) {
592
- invariant(value && typeof value === "object", "Choose a date range.");
593
- const input = value;
594
- const parsed = request(input.range, input.comparison != null);
595
- if (input.comparison != null) {
596
- const supplied = parseDateRangeInput(input.comparison, bounds());
597
- invariant(supplied.start === parsed.comparison?.start && supplied.end === parsed.comparison?.end, "Comparison must be the preceding equal-length range.");
598
- }
599
- return parsed;
542
+ function createChoice({ key, label, defaultValue, options, history = "push", presentation }) {
543
+ validateChoiceOptions(options);
544
+ function valid(value) {
545
+ return typeof value === "string" && options.some((option) => option.id === value);
600
546
  }
547
+ invariant(valid(defaultValue), `Choice ${key} must include its default value.`);
601
548
  return {
602
- datetime,
603
- request,
604
- parseRequest,
605
- bounds,
606
- parse(value) {
607
- return parseDateRangeInput(value, bounds());
549
+ kind: "choice",
550
+ presentation,
551
+ label: label ?? key,
552
+ options,
553
+ urlKeys: [key],
554
+ defaultValue,
555
+ history,
556
+ describe: (value) => options.find((option) => option.id === value).label,
557
+ read(params) {
558
+ const value = params.get(key);
559
+ return value !== null && valid(value) ? value : defaultValue;
608
560
  },
609
- period,
610
- comparison,
611
- describeInput,
612
- view: {
613
- period,
614
- describeInput
615
- }
561
+ write(value) {
562
+ return { [key]: value === defaultValue ? null : value };
563
+ },
564
+ valid,
565
+ same: (left, right) => left === right
616
566
  };
617
567
  }
618
- /** Validate calendar dates and a bounded inclusive range on the server. */
619
- function parseDateRangeInput(value, { minDate, maxDate, maxRangeDays }) {
620
- invariant(value && typeof value === "object" && !Array.isArray(value), "Choose a date range.");
621
- const { start, end } = value;
622
- function day(input) {
623
- invariant(typeof input === "string" && /^\d{4}-\d{2}-\d{2}$/.test(input), "Dates must be YYYY-MM-DD.");
624
- const timestamp = Date.parse(`${input}T00:00:00Z`);
625
- invariant(Number.isFinite(timestamp) && new Date(timestamp).toISOString().slice(0, 10) === input, "Choose valid calendar dates.");
626
- return timestamp;
568
+ function multiChoiceFilter({ key, label, defaultValue = [], options, maxSelected = options.length, history = "push", presentation }) {
569
+ validateChoiceOptions(options);
570
+ invariant(Number.isSafeInteger(maxSelected) && maxSelected >= 1 && maxSelected <= options.length, "Invalid choice selection limit.");
571
+ function valid(value) {
572
+ return Array.isArray(value) && value.length <= maxSelected && new Set(value).size === value.length && value.every((id) => options.some((option) => option.id === id));
573
+ }
574
+ function same(left, right) {
575
+ return left.length === right.length && left.every((id) => right.includes(id));
627
576
  }
628
- const first = day(start);
629
- const last = day(end);
630
- invariant(Number.isInteger(maxRangeDays) && maxRangeDays > 0, "Maximum range days must be positive.");
631
- invariant(first <= last && (last - first) / fixedUnitMilliseconds.DAY < maxRangeDays && (minDate === void 0 || first >= day(minDate)) && (maxDate === void 0 || last <= day(maxDate)), `Choose up to ${maxRangeDays} days within the available range.`);
577
+ invariant(valid(defaultValue), `Invalid default choices for ${key}.`);
632
578
  return {
633
- start,
634
- end
579
+ kind: "multiChoice",
580
+ presentation,
581
+ label: label ?? key,
582
+ options,
583
+ maxSelected,
584
+ urlKeys: [key],
585
+ defaultValue,
586
+ history,
587
+ describe: (values) => values.map((id) => options.find((option) => option.id === id).label).join(", ") || "None",
588
+ read(params) {
589
+ const raw = params.get(key);
590
+ if (raw === null || raw.length > 4096) return defaultValue;
591
+ try {
592
+ const values = JSON.parse(raw);
593
+ return valid(values) ? values : defaultValue;
594
+ } catch {
595
+ return defaultValue;
596
+ }
597
+ },
598
+ write(value) {
599
+ return { [key]: same(value, defaultValue) ? null : JSON.stringify(options.filter((option) => value.includes(option.id)).map((option) => option.id)) };
600
+ },
601
+ valid,
602
+ same
635
603
  };
636
604
  }
605
+ //#endregion
606
+ //#region src/core/operation-filters.ts
607
+ function isDateFilter(filter) {
608
+ return filter.kind === "dateTimeRange";
609
+ }
610
+ /** Validate an operation's filters once: unique URL keys and at most one date filter. */
611
+ function defineOperationFilters(filters) {
612
+ defineAppFilters(filters);
613
+ invariant(Object.values(filters).filter(isDateFilter).length <= 1, "An operation reads at most one date filter.");
614
+ return Object.freeze({ ...filters });
615
+ }
616
+ /** The name of the operation's date filter, which sets its reporting period. */
617
+ function dateFilterName(filters) {
618
+ return Object.keys(filters).find((name) => isDateFilter(filters[name]));
619
+ }
620
+ /** Resolve URL selections to the request the browser sends. Relative date ranges
621
+ * resolve against one reference time so the range and its comparison agree. */
622
+ function resolveFilterInput(filters, values, reference = /* @__PURE__ */ new Date()) {
623
+ const input = {};
624
+ for (const [name, filter] of Object.entries(filters)) {
625
+ const value = values[name];
626
+ input[name] = filter.kind === "dateTimeRange" ? filter.request(value, reference) : value;
627
+ }
628
+ return input;
629
+ }
630
+ /** Validate untrusted operation input against the declared filters. */
631
+ function parseFilterInput(filters, value) {
632
+ invariant(value && typeof value === "object" && !Array.isArray(value), "Expected filter input.");
633
+ const fields = value;
634
+ for (const name of Object.keys(fields)) invariant(Object.hasOwn(filters, name), `Unknown filter input: ${name}.`);
635
+ const input = {};
636
+ for (const [name, filter] of Object.entries(filters)) {
637
+ const selected = fields[name];
638
+ if (filter.kind === "dateTimeRange") input[name] = filter.parseInput(selected);
639
+ else {
640
+ invariant(filter.valid(selected), `Invalid ${filter.label ?? name}.`);
641
+ input[name] = selected;
642
+ }
643
+ }
644
+ return input;
645
+ }
646
+ /** The default selections, resolved: every filter operation can run with them. */
647
+ function defaultFilterInput(filters) {
648
+ return Object.fromEntries(Object.entries(filters).map(([name, filter]) => {
649
+ if (filter.kind !== "dateTimeRange") return [name, filter.defaultValue];
650
+ const { range, comparison } = filter.request(filter.defaultValue);
651
+ return [name, {
652
+ range,
653
+ comparison
654
+ }];
655
+ }));
656
+ }
657
+ /** Every operation in an app shares one filter per name and one owner per URL key. */
658
+ function combineOperationFilters(operations) {
659
+ const combined = {};
660
+ for (const [operation, filters] of Object.entries(operations)) for (const [name, filter] of Object.entries(filters)) {
661
+ invariant(!combined[name] || combined[name] === filter, `Operations read different filters named ${name}; declare it once and share it (${operation}).`);
662
+ combined[name] = filter;
663
+ }
664
+ return defineAppFilters(combined);
665
+ }
666
+ //#endregion
667
+ //#region src/authoring/contract.ts
668
+ function parseTrue(value) {
669
+ invariant(value === true, "Expected a successful check.");
670
+ return true;
671
+ }
637
672
  /** Accepts numeric strings from DuckDB; rejects negative, fractional, and unsafe integers. */
638
673
  function parseCount(value) {
639
674
  const number = typeof value === "number" || typeof value === "string" ? Number(value) : NaN;
@@ -650,12 +685,14 @@ function defineQueryNames(names) {
650
685
  return names;
651
686
  }
652
687
  function defineOperation(operation) {
653
- invariant(Array.isArray(operation.checks) && operation.checks.length > 0 && Number.isInteger(operation.policy.maxQueryRows) && operation.policy.maxQueryRows > 0 && operation.policy.maxQueryRows <= 1e4 && Number.isInteger(operation.policy.maxDurationMs) && operation.policy.maxDurationMs > 0 && (operation.policy.maxResponseBytes === void 0 || Number.isInteger(operation.policy.maxResponseBytes) && operation.policy.maxResponseBytes > 0), `Each data operation needs check inputs and positive row and duration limits, with at most ${MAX_QUERY_ROWS.toLocaleString("en-US")} rows.`);
688
+ const { policy } = operation;
689
+ invariant(Number.isInteger(policy.maxQueryRows) && policy.maxQueryRows > 0 && policy.maxQueryRows <= 1e4 && Number.isInteger(policy.maxDurationMs) && policy.maxDurationMs > 0 && (policy.maxResponseBytes === void 0 || Number.isInteger(policy.maxResponseBytes) && policy.maxResponseBytes > 0), `Each data operation needs positive row and duration limits, with at most ${MAX_QUERY_ROWS.toLocaleString("en-US")} rows.`);
690
+ const contract = operationInputContract(operation);
654
691
  const queries = snapshotQueries(operation.queries);
655
692
  const queryNames = Object.fromEntries(Object.keys(queries).map((name) => [name, name]));
656
- for (const input of operation.checks) operation.input(input);
657
693
  const defined = {
658
- ...operation,
694
+ ...contract,
695
+ policy,
659
696
  queryNames,
660
697
  async run(context, input) {
661
698
  async function query(name, values = {}, options) {
@@ -665,11 +702,11 @@ function defineOperation(operation) {
665
702
  return decodeQueryResult(await context.lakehouse.queryAll(definition.statement, {
666
703
  name,
667
704
  params,
668
- limit: options?.limit ?? operation.policy.maxQueryRows,
705
+ limit: options?.limit ?? policy.maxQueryRows,
669
706
  signal: context.signal
670
707
  }), definition.projections);
671
708
  }
672
- await validateVariableInput(operation.input, input, query);
709
+ if (contract.filters) await validateSourceMembers(contract.filters, input, query);
673
710
  context.signal.throwIfAborted();
674
711
  return operation.run({
675
712
  signal: context.signal,
@@ -680,13 +717,53 @@ function defineOperation(operation) {
680
717
  attachDimensionSelectors(defined, queries);
681
718
  return defined;
682
719
  }
720
+ /** Filters parse themselves; an operation's own `input` parses only its other fields. */
721
+ function operationInputContract(operation) {
722
+ const filters = defineOperationFilters(operation.filters ?? {});
723
+ const defaults = defaultFilterInput(filters);
724
+ if (!operation.input) return {
725
+ filters,
726
+ input: (value) => parseFilterInput(filters, value),
727
+ checks: [defaults]
728
+ };
729
+ const parseOwn = operation.input;
730
+ invariant(Array.isArray(operation.checks) && operation.checks.length > 0, "An operation with its own input needs check inputs.");
731
+ if (!Object.keys(filters).length) {
732
+ for (const check of operation.checks) parseOwn(check);
733
+ return {
734
+ input: parseOwn,
735
+ checks: operation.checks
736
+ };
737
+ }
738
+ function input(value) {
739
+ invariant(value && typeof value === "object" && !Array.isArray(value), "Expected operation input.");
740
+ const own = {};
741
+ const selected = {};
742
+ for (const [name, field] of Object.entries(value)) (Object.hasOwn(filters, name) ? selected : own)[name] = field;
743
+ const parsed = parseOwn(own);
744
+ invariant(!!parsed && typeof parsed === "object", "Expected parsed input object.");
745
+ for (const name of Object.keys(parsed)) invariant(!Object.hasOwn(filters, name), `Input field ${name} is also a filter; the filter parses it.`);
746
+ return {
747
+ ...parseFilterInput(filters, selected),
748
+ ...parsed
749
+ };
750
+ }
751
+ const checks = operation.checks.map((check) => ({
752
+ ...defaults,
753
+ ...check
754
+ }));
755
+ for (const check of checks) input(check);
756
+ return {
757
+ filters,
758
+ input,
759
+ checks
760
+ };
761
+ }
683
762
  /** A connectivity probe uses the app's registered connection query. */
684
763
  function connectionCheck(queries) {
685
764
  const connection = queries.connection;
686
765
  return defineOperation({
687
766
  queries: { connection },
688
- input: parseEmptyInput,
689
- checks: [{}],
690
767
  policy: {
691
768
  maxQueryRows: 1,
692
769
  maxDurationMs: 15e3
@@ -698,6 +775,6 @@ function connectionCheck(queries) {
698
775
  });
699
776
  }
700
777
  //#endregion
701
- export { dimensionPredicate as C, KEY_SEPARATOR as E, dimensionMemberKey as S, parseFacetOptions as T, isQueryParameters as _, parseCount as a, createDimensionFilter as b, parseLabel as c, DimensionMembershipError as d, bindDimensionSource as f, MAX_QUERY_ROWS as g, withDimensionSelectors as h, defineQueryNames as i, parseTrue as l, variableInput as m, defineDateRangeContract as n, parseDateRangeInput as o, dimensionSource as p, defineOperation as r, parseEmptyInput as s, connectionCheck as t, previousDateRange as u, snapshotQueries as v, parseDimensionSelection as w, dimensionFilter as x, dateTimeRangeSql as y };
778
+ export { KEY_SEPARATOR as A, dateTimeRangeSql as C, dimensionPredicate as D, dimensionMemberKey as E, parseDimensionSelection as O, snapshotQueries as S, dimensionFilter as T, bindDimensionSource as _, parseLabel as a, MAX_QUERY_ROWS as b, dateFilterName as c, defineAppFilters as d, displayChoice as f, DimensionMembershipError as g, validateChoiceOptions as h, parseCount as i, parseFacetOptions as k, resolveFilterInput as l, searchFilter as m, defineOperation as n, parseTrue as o, multiChoiceFilter as p, defineQueryNames as r, combineOperationFilters as s, connectionCheck as t, choiceFilter as u, dimensionSource as v, createDimensionFilter as w, isQueryParameters as x, withDimensionSelectors as y };
702
779
 
703
- //# sourceMappingURL=contract-B3s0ybE2.js.map
780
+ //# sourceMappingURL=contract-BQsFReRp.js.map