@altertable/data-app 0.76.0 → 0.78.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 (69) hide show
  1. package/CONTRIBUTING.md +3 -0
  2. package/REFERENCE.md +392 -276
  3. package/dist/chunks/contract-gu1rDsV0.js +1588 -0
  4. package/dist/chunks/contract-gu1rDsV0.js.map +1 -0
  5. package/dist/chunks/data-client-BMdL73Ab.js +122 -0
  6. package/dist/chunks/data-client-BMdL73Ab.js.map +1 -0
  7. package/dist/chunks/{date-time-range-value-TE8KCsfV.js → date-time-range-value-D-XfqVTT.js} +28 -31
  8. package/dist/chunks/date-time-range-value-D-XfqVTT.js.map +1 -0
  9. package/dist/chunks/{diagnostics-DhCqGklq.js → diagnostics-CX9SsU79.js} +240 -63
  10. package/dist/chunks/diagnostics-CX9SsU79.js.map +1 -0
  11. package/dist/chunks/record-Cr4Uk1K3.js +9 -0
  12. package/dist/chunks/record-Cr4Uk1K3.js.map +1 -0
  13. package/dist/client/index.js +4 -86
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/core/appearance.js +3 -5
  16. package/dist/core/appearance.js.map +1 -1
  17. package/dist/core/config.js +11 -3
  18. package/dist/core/config.js.map +1 -1
  19. package/dist/core/contract.js +3 -4
  20. package/dist/core/format.js +1 -1
  21. package/dist/internal.js +58 -124
  22. package/dist/internal.js.map +1 -1
  23. package/dist/types/chunks/contract.d.ts +592 -308
  24. package/dist/types/chunks/data-client.d.ts +46 -0
  25. package/dist/types/chunks/date-time-range-value.d.ts +28 -2
  26. package/dist/types/chunks/index.d.ts +65 -53
  27. package/dist/types/client/index.d.ts +4 -3
  28. package/dist/types/core/config.d.ts +16 -6
  29. package/dist/types/core/contract.d.ts +3 -5
  30. package/dist/types/core/format.d.ts +1 -2
  31. package/dist/types/index.d.ts +4 -4
  32. package/dist/types/internal.d.ts +26 -7
  33. package/docs/app-authoring.md +23 -14
  34. package/docs/client.md +14 -48
  35. package/docs/contract.md +58 -56
  36. package/docs/data-context.md +13 -6
  37. package/docs/diagnostics.md +16 -23
  38. package/docs/embed.md +60 -25
  39. package/docs/filters.md +271 -0
  40. package/docs/hosted-apps.md +11 -10
  41. package/docs/layout.md +45 -18
  42. package/docs/local-data-apps.md +5 -6
  43. package/docs/react-embed.md +44 -2
  44. package/docs/react.md +1 -2
  45. package/docs/server-bun.md +8 -5
  46. package/docs/stories-and-export.md +23 -14
  47. package/docs/styling.md +2 -1
  48. package/docs/ui.md +18 -8
  49. package/docs/views.md +63 -26
  50. package/docs/widgets.md +40 -16
  51. package/docs/worker.md +1 -1
  52. package/package.json +1 -5
  53. package/dist/chunks/contract-DsyRYgN_.js +0 -626
  54. package/dist/chunks/contract-DsyRYgN_.js.map +0 -1
  55. package/dist/chunks/contract-kNFYPHRK.js +0 -713
  56. package/dist/chunks/contract-kNFYPHRK.js.map +0 -1
  57. package/dist/chunks/date-time-range-value-TE8KCsfV.js.map +0 -1
  58. package/dist/chunks/diagnostics-DhCqGklq.js.map +0 -1
  59. package/dist/chunks/operation-7tiT4cpJ.js +0 -134
  60. package/dist/chunks/operation-7tiT4cpJ.js.map +0 -1
  61. package/dist/chunks/request-body-H1qPmmTN.js +0 -50
  62. package/dist/chunks/request-body-H1qPmmTN.js.map +0 -1
  63. package/dist/server/index.js +0 -90
  64. package/dist/server/index.js.map +0 -1
  65. package/dist/types/chunks/contract2.d.ts +0 -207
  66. package/dist/types/chunks/date-time-range.d.ts +0 -29
  67. package/dist/types/server/index.d.ts +0 -17
  68. package/docs/server.md +0 -41
  69. package/docs/variables.md +0 -280
@@ -1,626 +0,0 @@
1
- import { a as resolveDateTimeRange, c as invariant, i as parseDateTimeRange, o as serializeDateTimeRange, s as fixedUnitMilliseconds } from "./date-time-range-value-TE8KCsfV.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
73
- //#region src/core/keys.ts
74
- /** Separator for opaque composite keys, independent of URL and DOM ID formats. */
75
- const KEY_SEPARATOR = ":";
76
- //#endregion
77
- //#region src/core/dimension.ts
78
- const allSelection = { kind: "all" };
79
- function dimensionMemberKey(member) {
80
- return member.kind === "missing" ? "missing" : [
81
- "value",
82
- typeof member.value,
83
- member.value
84
- ].join(":");
85
- }
86
- function dimensionFilter(config) {
87
- return {
88
- ...createDimensionFilter(config),
89
- optionsSource: "fixed"
90
- };
91
- }
92
- /** Shared fixed-option and query-backed selection behavior. */
93
- function createDimensionFilter(config, dynamic = false) {
94
- const { key, label, selectionMode, valueType } = config;
95
- const options = config.options ?? [];
96
- const optionKeys = options.map((option) => dimensionMemberKey({
97
- kind: "value",
98
- value: option.value
99
- }));
100
- invariant(!!key && options.length <= 200 && new Set(optionKeys).size === options.length, "Dimension options need a key, at most 200 distinct values.");
101
- invariant(options.every((option) => typeof option.value === valueType && !!option.label.trim() && (option.count === void 0 || Number.isSafeInteger(option.count) && option.count >= 0)), "Dimension options need typed values, labels, and nonnegative counts.");
102
- const allowed = new Set(optionKeys);
103
- const maxSelected = config.maxSelected ?? (selectionMode === "single" ? 1 : 20);
104
- invariant(Number.isInteger(maxSelected) && maxSelected >= 1 && maxSelected <= 50 && (selectionMode !== "single" || maxSelected === 1), "Dimension selection limit is invalid.");
105
- const allowMissing = config.allowMissing ?? false;
106
- const defaultValue = allSelection;
107
- function validMember(member) {
108
- if (!member || typeof member !== "object") return false;
109
- if (member.kind === "missing") return allowMissing;
110
- if (member.kind !== "value" || typeof member.value !== valueType) return false;
111
- if (!dynamic) return allowed.has(dimensionMemberKey(member));
112
- return typeof member.value === "number" ? Number.isFinite(member.value) : member.value.length <= 100;
113
- }
114
- function valid(value) {
115
- if (!value || typeof value !== "object") return false;
116
- if (value.kind === "all") return true;
117
- if (value.kind !== "include" && !(config.allowExclusion && value.kind === "exclude") || !Array.isArray(value.members) || !value.members.length || value.members.length > maxSelected) return false;
118
- if (!value.members.every(validMember)) return false;
119
- const ids = value.members.map(dimensionMemberKey);
120
- return new Set(ids).size === ids.length;
121
- }
122
- function encode(value) {
123
- return value.kind === "all" ? null : JSON.stringify({
124
- kind: value.kind,
125
- members: value.members.map((member) => member.kind === "missing" ? ["m"] : ["v", member.value])
126
- });
127
- }
128
- function parse(raw) {
129
- if (raw === null) return defaultValue;
130
- if (raw.length > 4096) return defaultValue;
131
- try {
132
- const parsed = JSON.parse(raw);
133
- const tokens = Array.isArray(parsed) ? {
134
- kind: "include",
135
- members: parsed
136
- } : parsed;
137
- if (!tokens || !Array.isArray(tokens.members)) return defaultValue;
138
- const value = {
139
- kind: tokens.kind,
140
- members: tokens.members.map((token) => Array.isArray(token) && token.length === 1 && token[0] === "m" ? { kind: "missing" } : Array.isArray(token) && token.length === 2 && token[0] === "v" ? {
141
- kind: "value",
142
- value: token[1]
143
- } : { kind: "invalid" })
144
- };
145
- return valid(value) ? value : defaultValue;
146
- } catch {
147
- return defaultValue;
148
- }
149
- }
150
- return {
151
- kind: "dimension",
152
- optionsSource: dynamic ? "query" : "fixed",
153
- presentation: config.presentation,
154
- label,
155
- valueType,
156
- selectionMode,
157
- options,
158
- allowMissing,
159
- allowExclusion: config.allowExclusion ?? false,
160
- maxSelected,
161
- urlKeys: [key],
162
- defaultValue,
163
- clearValue: allSelection,
164
- history: config.history ?? "push",
165
- valid,
166
- same(left, right) {
167
- return encode(left) === encode(right);
168
- },
169
- read(params) {
170
- return parse(params.get(key));
171
- },
172
- write(value) {
173
- return { [key]: encode(value) };
174
- },
175
- describe(value, suppliedOptions = options) {
176
- return value.kind === "all" ? `All ${label.toLocaleLowerCase()}` : `${value.kind === "exclude" ? "Exclude: " : ""}${value.members.map((member) => member.kind === "missing" ? "Missing" : suppliedOptions.find((option) => option.value === member.value)?.label ?? String(member.value)).join(", ")}`;
177
- }
178
- };
179
- }
180
- /** Server-side parser; call from the operation input parser before building SQL. */
181
- function parseDimensionSelection(value, filter) {
182
- invariant(filter.valid(value), `Invalid ${filter.label} selection.`);
183
- return value;
184
- }
185
- /** Validate bounded facet results before showing them in a picker. */
186
- function parseFacetOptions(value, filter) {
187
- invariant(Array.isArray(value) && value.length <= 200, "Facet options exceed their bound.");
188
- const options = [];
189
- const seen = /* @__PURE__ */ new Set();
190
- for (const item of value) {
191
- invariant(item && typeof item === "object", "Invalid facet option.");
192
- const option = item;
193
- invariant(typeof option.value === filter.valueType && filter.valid({
194
- kind: "include",
195
- members: [{
196
- kind: "value",
197
- value: option.value
198
- }]
199
- }) && typeof option.label === "string" && !!option.label.trim() && option.label.length <= 100 && (option.count === void 0 || Number.isSafeInteger(option.count) && option.count >= 0), "Invalid facet option.");
200
- const id = dimensionMemberKey({
201
- kind: "value",
202
- value: option.value
203
- });
204
- invariant(!seen.has(id), "Duplicate facet option.");
205
- seen.add(id);
206
- options.push(option);
207
- }
208
- return options;
209
- }
210
- /** Central SQL literal encoding for transports without bound parameters. Column is an allowlisted identifier. */
211
- function dimensionPredicate(column, selection, allowedColumns) {
212
- invariant(allowedColumns.includes(column) && /^[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*$/.test(column), "Invalid dimension column.");
213
- if (selection.kind === "all") return "";
214
- invariant(selection.members.length > 0, "Empty dimension inclusion is invalid.");
215
- const values = selection.members.filter((member) => member.kind === "value");
216
- const missing = selection.members.some((member) => member.kind === "missing");
217
- const literals = values.map(({ value }) => {
218
- if (typeof value === "number") {
219
- invariant(Number.isFinite(value), "Invalid numeric dimension value.");
220
- return String(value);
221
- }
222
- const text = value;
223
- for (let index = 0; index < text.length; index++) invariant(text.charCodeAt(index) >= 32 && text.charCodeAt(index) !== 127, "Invalid control character in dimension value.");
224
- return `'${text.replaceAll("'", "''")}'`;
225
- });
226
- const predicate = `(${[...literals.length ? [`${column} IN (${literals.join(", ")})`] : [], ...missing ? [`${column} IS NULL`] : []].join(" OR ")})`;
227
- return selection.kind === "exclude" ? missing ? `NOT ${predicate}` : `(${column} IS NULL OR NOT ${predicate})` : predicate;
228
- }
229
- //#endregion
230
- //#region src/core/date-time-range-sql.ts
231
- /** DuckDB timestamp expressions using the query session's timezone for relative anchors.
232
- * Absolute fields remain UTC-rebased TIMESTAMP values. Start is inclusive, end exclusive.
233
- */
234
- function dateTimeRangeSql(range, parameter = "period") {
235
- invariant(/^[A-Za-z_][A-Za-z0-9_]*$/.test(parameter), "Use a SQL parameter name.");
236
- return {
237
- from: boundExpression(parameter, "from"),
238
- to: boundExpression(parameter, "to"),
239
- params: { [parameter]: serializeDateTimeRange(range) }
240
- };
241
- }
242
- function boundExpression(parameter, bound) {
243
- const json = `$${parameter}`;
244
- const path = `$.${bound}`;
245
- const anchor = `json_extract_string(${json}, '${path}.anchor')`;
246
- const base = `CASE WHEN json_type(${json}, '${path}') = 'VARCHAR' THEN CAST(json_extract_string(${json}, '${path}') AS TIMESTAMP)
247
- WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_TODAY' THEN date_trunc('day', localtimestamp)
248
- WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_YESTERDAY' THEN date_trunc('day', localtimestamp) - INTERVAL '1 day'
249
- WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_TOMORROW' THEN date_trunc('day', localtimestamp) + INTERVAL '1 day'
250
- WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_WEEK' THEN date_trunc('week', localtimestamp)
251
- WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_MONTH' THEN date_trunc('month', localtimestamp)
252
- WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_YEAR' THEN date_trunc('year', localtimestamp)
253
- WHEN ${anchor} = 'RELATIVE_ANCHOR_NOW' THEN localtimestamp
254
- ELSE ${bound === "from" ? "TIMESTAMP '-infinity'" : "localtimestamp"} END`;
255
- const item = `json_extract(${json}, '${path}.offset[' || i::VARCHAR || ']')`;
256
- const amount = `CAST(json_extract_string(${item}, '$.amount') AS INTEGER)`;
257
- return `(WITH RECURSIVE bounds(i, value) AS (
258
- SELECT 0, ${base}
259
- UNION ALL SELECT i + 1, value + ${`CASE json_extract_string(${item}, '$.unit') ${[
260
- "SECOND",
261
- "MINUTE",
262
- "HOUR",
263
- "DAY",
264
- "WEEK",
265
- "MONTH",
266
- "YEAR"
267
- ].map((unit) => `WHEN '${unit}' THEN ${amount} * INTERVAL '1 ${unit}'`).join(" ")} ELSE INTERVAL '0 seconds' END`} FROM bounds
268
- WHERE i < COALESCE(json_array_length(${json}, '${path}.offset'), 0)
269
- ) SELECT value FROM bounds ORDER BY i DESC LIMIT 1)`;
270
- }
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;
274
- let output = "";
275
- let position = 0;
276
- for (let match = token.exec(statement); match; match = token.exec(statement)) {
277
- output += statement.slice(position, match.index);
278
- const text = match[0];
279
- if (text === "/*") {
280
- let depth = 1;
281
- let end = token.lastIndex;
282
- while (depth && end < statement.length) if (statement.slice(end, end + 2) === "/*") {
283
- depth++;
284
- end += 2;
285
- } else if (statement.slice(end, end + 2) === "*/") {
286
- depth--;
287
- end += 2;
288
- } else end++;
289
- output += statement.slice(match.index, end);
290
- token.lastIndex = end;
291
- } else if (/^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$$/.test(text)) {
292
- const closing = statement.indexOf(text, token.lastIndex);
293
- const end = closing < 0 ? statement.length : closing + text.length;
294
- output += statement.slice(match.index, end);
295
- token.lastIndex = end;
296
- } else if (match[1] && names.has(match[1]) && match[2]) output += boundExpression(match[1], match[2]);
297
- else output += text;
298
- position = token.lastIndex;
299
- }
300
- return output + statement.slice(position);
301
- }
302
- //#endregion
303
- //#region src/core/queries.ts
304
- const MAX_QUERY_ROWS = 1e4;
305
- const QUERY_CAST_ERROR = "##ERROR##";
306
- function isQueryParameterValue(value) {
307
- return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
308
- }
309
- function isQueryParameters(value) {
310
- return !!value && typeof value === "object" && !Array.isArray(value) && Object.values(value).every(isQueryParameterValue);
311
- }
312
- function snapshotField(field) {
313
- invariant(field && typeof field === "object" && !Array.isArray(field) && (field.type === "string" || field.type === "number" || field.type === "boolean" || field.type === "null") && (field.nullable === void 0 || typeof field.nullable === "boolean"), "Query fields need a supported type and a boolean nullable flag.");
314
- return Object.freeze({ ...field });
315
- }
316
- /** Snapshot the query's SQL, parameter defaults, and decoded result contract. */
317
- function snapshotQueries(definitions) {
318
- return Object.freeze(Object.fromEntries(Object.entries(definitions).map(([name, query]) => {
319
- invariant(!!name.trim() && !!query.statement.trim(), "Queries need a name and SQL statement.");
320
- 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.");
322
- invariant(!Object.hasOwn(declaration, "defaultValue") || (declaration.type === "dateTimeRange" ? !!parseDateTimeRange(declaration.defaultValue) : isQueryParameterValue(declaration.defaultValue)), `Invalid default for parameter ${key} in query ${name}.`);
323
- return [key, declaration.type === "dateTimeRange" ? Object.freeze({
324
- ...declaration,
325
- ...declaration.defaultValue === void 0 ? {} : { defaultValue: parseDateTimeRange(declaration.defaultValue) }
326
- }) : snapshotField(declaration)];
327
- })));
328
- const projectionEntries = Object.entries(query.projections);
329
- invariant(projectionEntries.length > 0 && projectionEntries.every(([alias]) => !!alias.trim()), "Queries need at least one named projection.");
330
- return [name, Object.freeze({
331
- statement: expandDateTimeRangeParameters(query.statement, new Set(Object.entries(query.params).filter(([, p]) => p.type === "dateTimeRange").map(([key]) => key))),
332
- params,
333
- projections: Object.freeze(Object.fromEntries(projectionEntries.map(([alias, field]) => [alias, snapshotField(field)])))
334
- })];
335
- })));
336
- }
337
- /** Decode each returned cell once, matching aliases independently of result order. */
338
- function decodeQueryResult(result, projections) {
339
- if (!result || !Array.isArray(result.columns) || !Array.isArray(result.rows) || result.queryId !== void 0 && typeof result.queryId !== "string") throw new Error("Query result must contain columns and rows.");
340
- const returnedColumns = Array.from(result.columns, (column) => {
341
- if (!column || typeof column !== "object" || Array.isArray(column) || typeof column.name !== "string" || column.type !== void 0 && typeof column.type !== "string") throw new Error("Query result columns must have names and optional type strings.");
342
- return {
343
- name: column.name,
344
- ...column.type === void 0 ? {} : { type: column.type }
345
- };
346
- });
347
- const names = returnedColumns.map((column) => column.name);
348
- return {
349
- columns: returnedColumns,
350
- rows: Array.from(result.rows, (row) => {
351
- if (!Array.isArray(row) || row.length !== names.length) throw new Error("Query result row has the wrong width.");
352
- return Object.fromEntries(names.map((name, index) => [name, castQueryCell(row[index], projections[name])]));
353
- }),
354
- ...result.queryId === void 0 ? {} : { queryId: result.queryId }
355
- };
356
- }
357
- function castQueryCell(value, field) {
358
- if (field === void 0) {
359
- if (typeof value === "string" || typeof value === "boolean" || typeof value === "number") return value;
360
- if (value === null) return null;
361
- return JSON.stringify(value);
362
- }
363
- if (value === null && field.nullable !== false) return null;
364
- switch (field.type) {
365
- case "string": return String(value);
366
- case "number": {
367
- const number = Number(value);
368
- return Number.isFinite(number) ? number : QUERY_CAST_ERROR;
369
- }
370
- case "boolean": return Boolean(value);
371
- case "null": return null;
372
- }
373
- }
374
- /** Host context supplies protected values; callers and defaults fill the remaining parameters. */
375
- function resolveQueryParameters(declarations, values, context) {
376
- if (!values || typeof values !== "object" || Array.isArray(values)) throw new Error("Supply query parameter values as an object.");
377
- for (const key of Object.keys(values)) {
378
- if (!Object.hasOwn(declarations, key)) throw new Error(`Unknown parameter ${key}.`);
379
- if (Object.hasOwn(context, key)) throw new Error(`Cannot override context parameter ${key}.`);
380
- }
381
- return Object.fromEntries(Object.entries(declarations).map(([key, declaration]) => {
382
- const value = Object.hasOwn(context, key) ? context[key] : Object.hasOwn(values, key) && values[key] !== void 0 ? values[key] : declaration.defaultValue;
383
- if (value === void 0) throw new Error(`Missing parameter ${key}.`);
384
- if (declaration.type === "dateTimeRange") return [key, serializeDateTimeRange(parseDateTimeRange(typeof value === "string" ? JSON.parse(value) : value))];
385
- const nullable = declaration.type === "null" || declaration.nullable === true;
386
- if (!(value === null ? nullable : typeof value === declaration.type && isQueryParameterValue(value))) throw new Error(`Parameter ${key} does not match ${declaration.type}.`);
387
- return [key, value];
388
- }));
389
- }
390
- //#endregion
391
- //#region src/core/dimension-source.ts
392
- const dimensionSource = Symbol("data-app.dimensionSource");
393
- const sources = /* @__PURE__ */ new WeakMap();
394
- const parserVariables = /* @__PURE__ */ new WeakMap();
395
- const selectorsKey = Symbol.for("@altertable/data-app/dimension-selectors");
396
- const ownerKey = Symbol.for("@altertable/data-app/dimension-selector-owner");
397
- const invalidMemberKey = Symbol.for("@altertable/data-app/dimension-member-error");
398
- var DimensionMembershipError = class extends Error {
399
- [invalidMemberKey] = true;
400
- static [Symbol.hasInstance](value) {
401
- return value instanceof Error && value[invalidMemberKey] === true;
402
- }
403
- };
404
- /** Validate named variable values at the operation boundary. */
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
- /** A query supplies independent options and exact member lookup; it declares a nullable `member` parameter. */
435
- function bindDimensionSource(config, queries) {
436
- invariant(!config.allowMissing, "Source dimensions require concrete members.");
437
- const query = queries[config.source.query];
438
- invariant(query && Object.hasOwn(query.params, "member"), "Dimension sources must declare member.");
439
- const member = query.params.member;
440
- const { value, label, count } = query.projections;
441
- 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
- const operation = `__dimension:${config.key}`;
443
- const variable = Object.assign(createDimensionFilter({
444
- ...config,
445
- valueType: config.valueType,
446
- options: []
447
- }, true), {
448
- optionsSource: "query",
449
- [dimensionSource]: Object.freeze({ operation })
450
- });
451
- sources.set(variable, {
452
- query: config.source.query,
453
- queries
454
- });
455
- return variable;
456
- }
457
- async function loadOptions(variable, member, query) {
458
- const result = await query(sources.get(variable).query, { member }, { limit: member === null ? 200 : 2 });
459
- const names = result.columns.map((column) => column.name);
460
- 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.`);
463
- return options;
464
- }
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;
468
- const selection = input[name];
469
- if (selection.kind === "all") continue;
470
- for (const member of selection.members) if (member.kind === "value") await loadOptions(variable, member.value, query);
471
- }
472
- }
473
- function attachDimensionSelectors(operation, queries) {
474
- 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);
478
- if (!source) continue;
479
- 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.");
482
- selectors[name] = {
483
- input(value) {
484
- invariant(value && typeof value === "object", "Invalid dimension request.");
485
- const member = value.member;
486
- invariant(member === null || variable.valid({
487
- kind: "include",
488
- members: [{
489
- kind: "value",
490
- value: member
491
- }]
492
- }), "Invalid requested member.");
493
- return { member };
494
- },
495
- checks: [{ member: null }],
496
- policy: {
497
- maxDurationMs: 15e3,
498
- maxQueryRows: 200,
499
- maxResponseBytes: 1e6
500
- },
501
- queryNames: { [source.query]: source.query },
502
- async run(context, input) {
503
- return loadOptions(variable, input.member, async (name, params, options) => {
504
- const definition = queries[name];
505
- return decodeQueryResult(await context.lakehouse.queryAll(definition.statement, {
506
- name,
507
- params: resolveQueryParameters(definition.params, params, context.queryParams ?? {}),
508
- limit: options.limit,
509
- signal: context.signal
510
- }), definition.projections);
511
- });
512
- }
513
- };
514
- Object.defineProperty(selectors[name], ownerKey, { value: variable });
515
- }
516
- Object.defineProperty(operation, selectorsKey, { value: selectors });
517
- }
518
- function withDimensionSelectors(operations) {
519
- const expanded = { ...operations };
520
- for (const operation of Object.values(operations)) for (const [name, selector] of Object.entries(operation[selectorsKey] ?? {})) {
521
- invariant(!Object.hasOwn(operations, name), "Reserved dimension operation name.");
522
- invariant(!expanded[name] || expanded[name][ownerKey] === selector[ownerKey], "Dimension source keys must be unique across the app.");
523
- expanded[name] ??= selector;
524
- }
525
- return expanded;
526
- }
527
- //#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 {};
537
- }
538
- function parseTrue(value) {
539
- invariant(value === true, "Expected a successful check.");
540
- return true;
541
- }
542
- /** One source policy for datetime picker validation and operation requests. */
543
- function defineDateRangeContract({ minDate, maxDate, maxRangeDays, timeZone, completeDays }) {
544
- invariant(Number.isInteger(maxRangeDays) && maxRangeDays > 0, "Date range needs a positive maxRangeDays.");
545
- if (minDate) parseDate(minDate);
546
- if (typeof maxDate === "string") parseDate(maxDate);
547
- today(timeZone);
548
- const datetime = createDateTimeRangeContract({
549
- minDate,
550
- maxDate,
551
- maxRangeDays,
552
- timeZone,
553
- completeDays
554
- });
555
- return {
556
- datetime,
557
- bounds: datetime.bounds
558
- };
559
- }
560
- /** Accepts numeric strings from DuckDB; rejects negative, fractional, and unsafe integers. */
561
- function parseCount(value) {
562
- const number = typeof value === "number" || typeof value === "string" ? Number(value) : NaN;
563
- invariant(Number.isSafeInteger(number) && number >= 0 && (typeof value !== "string" || !!value.trim()), "Invalid count in query result.");
564
- return number;
565
- }
566
- function parseLabel(value, maxLength = 100) {
567
- invariant(typeof value === "string" && !!value && value.length <= maxLength, "Invalid label in query result.");
568
- return value;
569
- }
570
- function defineQueryNames(names) {
571
- const values = Object.values(names);
572
- invariant(values.every((name) => !!name.trim()) && new Set(values).size === values.length, "Query names must be nonempty and unique.");
573
- return names;
574
- }
575
- function defineOperation(operation) {
576
- 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.`);
577
- const queries = snapshotQueries(operation.queries);
578
- const queryNames = Object.fromEntries(Object.keys(queries).map((name) => [name, name]));
579
- for (const input of operation.checks) operation.input(input);
580
- const defined = {
581
- ...operation,
582
- queryNames,
583
- async run(context, input) {
584
- async function query(name, values = {}, options) {
585
- invariant(Object.hasOwn(queries, name), `Unknown query name: ${name}.`);
586
- const definition = queries[name];
587
- const params = resolveQueryParameters(definition.params, values, context.queryParams ?? {});
588
- return decodeQueryResult(await context.lakehouse.queryAll(definition.statement, {
589
- name,
590
- params,
591
- limit: options?.limit ?? operation.policy.maxQueryRows,
592
- signal: context.signal
593
- }), definition.projections);
594
- }
595
- await validateVariableInput(operation.input, input, query);
596
- context.signal.throwIfAborted();
597
- return operation.run({
598
- signal: context.signal,
599
- query
600
- }, input);
601
- }
602
- };
603
- attachDimensionSelectors(defined, queries);
604
- return defined;
605
- }
606
- /** A connectivity probe uses the app's registered connection query. */
607
- function connectionCheck(queries) {
608
- const connection = queries.connection;
609
- return defineOperation({
610
- queries: { connection },
611
- input: parseEmptyInput,
612
- checks: [{}],
613
- policy: {
614
- maxQueryRows: 1,
615
- maxDurationMs: 15e3
616
- },
617
- async run({ query }) {
618
- await query("connection");
619
- return true;
620
- }
621
- });
622
- }
623
- //#endregion
624
- export { parseFacetOptions as C, parseDimensionSelection as S, dateTimeRangeSql as _, parseCount as a, dimensionMemberKey as b, parseTrue as c, dimensionSource as d, variableInput as f, snapshotQueries as g, isQueryParameters as h, defineQueryNames as i, DimensionMembershipError as l, MAX_QUERY_ROWS as m, defineDateRangeContract as n, parseEmptyInput as o, withDimensionSelectors as p, defineOperation as r, parseLabel as s, connectionCheck as t, bindDimensionSource as u, createDimensionFilter as v, KEY_SEPARATOR as w, dimensionPredicate as x, dimensionFilter as y };
625
-
626
- //# sourceMappingURL=contract-DsyRYgN_.js.map