derive-dashboards 0.1.1 → 0.2.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 (167) hide show
  1. package/README.md +5 -3
  2. package/dist/cli/add.mjs +130 -0
  3. package/dist/cli/cli.mjs +14 -12
  4. package/dist/cli/config.mjs +12 -1
  5. package/dist/cli/doctor.mjs +147 -0
  6. package/dist/cli/init.mjs +3 -2
  7. package/dist/cli/json.mjs +21 -0
  8. package/dist/cli/layers.mjs +33 -0
  9. package/dist/core/document/layout.mjs +1 -1
  10. package/dist/core/document/view-layout.d.mts +14 -0
  11. package/dist/core/document/view-layout.mjs +157 -0
  12. package/dist/core/engine/filter.mjs +2 -2
  13. package/dist/core/engine/leaf.mjs +9 -4
  14. package/dist/core/engine/members.mjs +1 -1
  15. package/dist/core/engine/version.d.mts +1 -1
  16. package/dist/core/engine/version.mjs +1 -1
  17. package/dist/core/error/codes.d.mts +2 -1
  18. package/dist/core/error/codes.mjs +2 -1
  19. package/dist/core/index.d.mts +5 -3
  20. package/dist/core/index.mjs +5 -3
  21. package/dist/core/model/member.mjs +5 -2
  22. package/dist/core/model/types.d.mts +13 -13
  23. package/dist/core/model/validate/members.mjs +7 -4
  24. package/dist/core/policy/bind-query.d.mts +12 -0
  25. package/dist/core/policy/bind-query.mjs +53 -0
  26. package/dist/core/query/filter.d.mts +6 -0
  27. package/dist/core/query/picks.d.mts +8 -2
  28. package/dist/core/query/picks.mjs +11 -4
  29. package/dist/core/query/segments.mjs +2 -1
  30. package/dist/core/result/columns.mjs +6 -3
  31. package/dist/core/schema/aliases.d.mts +7 -0
  32. package/dist/core/schema/aliases.mjs +77 -0
  33. package/dist/core/schema/answers.d.mts +1 -0
  34. package/dist/core/schema/answers.mjs +1 -0
  35. package/dist/core/schema/index.d.mts +3 -2
  36. package/dist/core/schema/index.mjs +3 -2
  37. package/dist/core/schema/query.d.mts +81 -0
  38. package/dist/core/schema/query.mjs +9 -5
  39. package/dist/core/types/api.d.mts +7 -1
  40. package/dist/core/types/api.mjs +1 -1
  41. package/dist/dashboards.mjs +4 -0
  42. package/dist/editing.mjs +2 -2
  43. package/dist/endpoints/dashboards.mjs +17 -2
  44. package/dist/endpoints/index.d.mts +12 -2
  45. package/dist/endpoints/meta.mjs +10 -1
  46. package/dist/execute.mjs +20 -11
  47. package/dist/handler.mjs +5 -1
  48. package/dist/llms.txt +22 -0
  49. package/dist/mcp/format.mjs +42 -8
  50. package/dist/mcp/query.mjs +34 -4
  51. package/dist/postgres-store.mjs +1 -0
  52. package/dist/react/Canvas.mjs +28 -5
  53. package/dist/react/Cell.mjs +2 -1
  54. package/dist/react/Dashboard.mjs +15 -3
  55. package/dist/react/DashboardList.mjs +22 -22
  56. package/dist/react/DashboardListRow.mjs +49 -0
  57. package/dist/react/Discard.mjs +5 -2
  58. package/dist/react/Editing.mjs +19 -5
  59. package/dist/react/FilterBar.d.mts +7 -9
  60. package/dist/react/Grid.mjs +7 -19
  61. package/dist/react/Header.mjs +1 -1
  62. package/dist/react/History.mjs +5 -0
  63. package/dist/react/ReadFailed.mjs +23 -0
  64. package/dist/react/Spaces.mjs +15 -1
  65. package/dist/react/Tile.d.mts +2 -0
  66. package/dist/react/Tile.mjs +35 -7
  67. package/dist/react/_virtual/_rolldown/runtime.mjs +12 -0
  68. package/dist/react/arrange-steps.mjs +16 -13
  69. package/dist/react/arrange.mjs +10 -3
  70. package/dist/react/builder/Calcs.mjs +35 -11
  71. package/dist/react/builder/FilterEditor.mjs +196 -0
  72. package/dist/react/builder/Filters.mjs +172 -116
  73. package/dist/react/builder/Formula.mjs +82 -0
  74. package/dist/react/builder/Groups.mjs +1 -0
  75. package/dist/react/builder/Preview.mjs +1 -1
  76. package/dist/react/builder/RangeEditor.mjs +184 -0
  77. package/dist/react/builder/Sections.mjs +41 -6
  78. package/dist/react/builder/Time.mjs +138 -60
  79. package/dist/react/builder/Values.mjs +85 -0
  80. package/dist/react/builder/WidgetBuilder.mjs +50 -49
  81. package/dist/react/builder/base.d.mts +5 -0
  82. package/dist/react/builder/base.mjs +33 -8
  83. package/dist/react/builder/calc.mjs +15 -1
  84. package/dist/react/builder/escape.d.mts +1 -0
  85. package/dist/react/builder/escape.mjs +62 -0
  86. package/dist/react/builder/filter-tree.d.mts +9 -0
  87. package/dist/react/builder/filter-tree.mjs +186 -0
  88. package/dist/react/builder/formula-parse.d.mts +18 -0
  89. package/dist/react/builder/formula-parse.mjs +136 -0
  90. package/dist/react/builder/labels.d.mts +1 -1
  91. package/dist/react/builder/state.d.mts +2 -1
  92. package/dist/react/builder/state.mjs +23 -37
  93. package/dist/react/builder/useBuilder.d.mts +12 -1
  94. package/dist/react/builder/useBuilder.mjs +6 -3
  95. package/dist/react/builder/words.d.mts +59 -0
  96. package/dist/react/builder/words.mjs +73 -0
  97. package/dist/react/context.d.mts +13 -0
  98. package/dist/react/context.mjs +9 -3
  99. package/dist/react/drill/useDrill.d.mts +1 -1
  100. package/dist/react/drill/words.d.mts +3 -0
  101. package/dist/react/drill/words.mjs +2 -0
  102. package/dist/react/english.mjs +20 -5
  103. package/dist/react/filters/bar.d.mts +12 -0
  104. package/dist/react/filters/bar.mjs +135 -0
  105. package/dist/react/filters/calendar.mjs +193 -0
  106. package/dist/react/filters/chip.mjs +174 -0
  107. package/dist/react/filters/context.d.mts +22 -0
  108. package/dist/react/filters/context.mjs +78 -0
  109. package/dist/react/filters/dates.mjs +89 -0
  110. package/dist/react/filters/days.d.mts +36 -0
  111. package/dist/react/filters/days.mjs +87 -0
  112. package/dist/react/filters/field-step.mjs +81 -0
  113. package/dist/react/filters/hooks.d.mts +34 -0
  114. package/dist/react/filters/hooks.mjs +94 -0
  115. package/dist/react/filters/listbox.mjs +131 -0
  116. package/dist/react/filters/logic.d.mts +59 -0
  117. package/dist/react/filters/logic.mjs +109 -0
  118. package/dist/react/filters/menu-search.mjs +211 -0
  119. package/dist/react/filters/menu.mjs +85 -0
  120. package/dist/react/filters/number.mjs +127 -0
  121. package/dist/react/filters/numbers.d.mts +47 -0
  122. package/dist/react/filters/numbers.mjs +151 -0
  123. package/dist/react/filters/operator.mjs +104 -0
  124. package/dist/react/filters/phone.mjs +104 -0
  125. package/dist/react/filters/popover.d.mts +19 -0
  126. package/dist/react/filters/popover.mjs +153 -0
  127. package/dist/react/filters/rules.d.mts +8 -0
  128. package/dist/react/filters/rules.mjs +55 -0
  129. package/dist/react/filters/sheet.mjs +196 -0
  130. package/dist/react/filters/state.mjs +132 -0
  131. package/dist/react/filters/suggest.d.mts +47 -0
  132. package/dist/react/filters/suggest.mjs +97 -0
  133. package/dist/react/filters/values.mjs +166 -0
  134. package/dist/react/filters/words.d.mts +81 -0
  135. package/dist/react/filters/words.mjs +73 -0
  136. package/dist/react/format.mjs +11 -4
  137. package/dist/react/index.d.mts +11 -5
  138. package/dist/react/index.mjs +8 -4
  139. package/dist/react/messages.d.mts +34 -2
  140. package/dist/react/place.mjs +7 -3
  141. package/dist/react/renderers/index.mjs +65 -3
  142. package/dist/react/renderers/list.mjs +6 -6
  143. package/dist/react/series.d.mts +25 -8
  144. package/dist/react/series.mjs +135 -39
  145. package/dist/react/theme.css +930 -19
  146. package/dist/react/useBoard.d.mts +2 -0
  147. package/dist/react/useDashboard.d.mts +3 -0
  148. package/dist/react/useDashboard.mjs +6 -0
  149. package/dist/react/view-grid.mjs +16 -0
  150. package/dist/recharts/axes.mjs +28 -0
  151. package/dist/recharts/axis.mjs +84 -0
  152. package/dist/recharts/bar.d.mts +7 -0
  153. package/dist/recharts/bar.mjs +140 -0
  154. package/dist/recharts/charts.d.mts +4 -5
  155. package/dist/recharts/charts.mjs +2 -208
  156. package/dist/recharts/index.d.mts +3 -1
  157. package/dist/recharts/index.mjs +4 -1
  158. package/dist/recharts/line.d.mts +2 -0
  159. package/dist/recharts/line.mjs +111 -0
  160. package/dist/recharts/marks.mjs +47 -18
  161. package/dist/recharts/parts.mjs +88 -0
  162. package/dist/recharts/table.mjs +71 -0
  163. package/dist/records-read.mjs +1 -1
  164. package/dist/registry/filter-bar.json +26 -0
  165. package/dist/skills/derive-dashboards/SKILL.md +69 -0
  166. package/package.json +6 -2
  167. package/dist/react/FilterBar.mjs +0 -119
@@ -28,7 +28,7 @@ function filterSql(b, scope, filter) {
28
28
  if ("not" in filter) return sql`NOT ${filterSql(b, scope, filter.not)}`;
29
29
  if ("some" in filter) return childSql(b, scope, filter.some, false);
30
30
  if ("none" in filter) return childSql(b, scope, filter.none, true);
31
- return leafSql(b, memberSql(b, scope, filter.member), filter.op, filter.values);
31
+ return leafSql(b, memberSql(b, scope, filter.member), filter);
32
32
  }
33
33
  /** A bound row policy speaks about physical columns. */
34
34
  function policySql(b, alias, filter) {
@@ -40,7 +40,7 @@ function policySql(b, alias, filter) {
40
40
  type: typeOfValues(filter.values),
41
41
  collation: "binary"
42
42
  };
43
- return leafSql(b, operand, filter.op, filter.values);
43
+ return leafSql(b, operand, filter);
44
44
  }
45
45
  /** Through a via: the parent row exists and carries the via's terms. */
46
46
  function viaSql(b, alias, via) {
@@ -74,7 +74,7 @@ function eq(c, x, y, value) {
74
74
  if (c.operand.type !== "string") return beside(c, [...bound(c, value, "over"), ...bound(c, value, "under")], sql`${x} = ${y}`);
75
75
  if (!c.side.plain) {
76
76
  const part = sql`${c.b.dialect.binary(x)} = ${y}`;
77
- if (value === void 0) return part;
77
+ if (value === void 0 || c.broad) return part;
78
78
  return sql`(${part} AND ${c.b.dialect.fold(c.operand.sql)} = ${param(c.b, value, c.operand)})`;
79
79
  }
80
80
  const native = c.operand.native;
@@ -120,16 +120,21 @@ const isNegative = (op) => op in NEGATION_OF;
120
120
  * or of another type is FALSE before any SQL), so it is never unknown; it stands bare, where
121
121
  * an index on the column can answer it.
122
122
  */
123
- function leafSql(b, operand, op, values) {
123
+ function leafSql(b, operand, leaf) {
124
+ const { op, values } = leaf;
124
125
  if (op === "set") return sql`(${operand.sql} IS NOT NULL)`;
125
126
  if (op === "notSet") return sql`(${operand.sql} IS NULL)`;
126
- if (isNegative(op)) return sql`NOT ${leafSql(b, operand, NEGATION_OF[op], values)}`;
127
+ if (isNegative(op)) return sql`NOT ${leafSql(b, operand, {
128
+ ...leaf,
129
+ op: NEGATION_OF[op]
130
+ })}`;
127
131
  const side = columnSide(b, operand, op, values);
128
132
  const test = POSITIVE[op]({
129
133
  b,
130
134
  operand,
131
135
  side,
132
- values
136
+ values,
137
+ broad: leaf.broad === true
133
138
  });
134
139
  return sql`(${operand.sql} IS NOT NULL AND ${test})`;
135
140
  }
@@ -57,7 +57,7 @@ function caseSql(ctx, expr) {
57
57
  sql: left,
58
58
  type: typeOfValues(branch.when.values),
59
59
  collation: "binary"
60
- }, branch.when.op, branch.when.values);
60
+ }, branch.when);
61
61
  return sql`WHEN ${test} THEN ${exprSql(ctx, branch.then)}`;
62
62
  });
63
63
  const otherwise = expr.else === void 0 ? sql`NULL` : exprSql(ctx, expr.else);
@@ -4,4 +4,4 @@
4
4
  * so an answer cached by older code is never read. `test/engine-version.test.ts` checks it
5
5
  * against the files and prints the new value when they change.
6
6
  */
7
- export declare const ENGINE_VERSION = "c50d674f90366532";
7
+ export declare const ENGINE_VERSION = "dc606144b73c8623";
@@ -5,5 +5,5 @@
5
5
  * so an answer cached by older code is never read. `test/engine-version.test.ts` checks it
6
6
  * against the files and prints the new value when they change.
7
7
  */
8
- const ENGINE_VERSION = "c50d674f90366532";
8
+ const ENGINE_VERSION = "dc606144b73c8623";
9
9
  export { ENGINE_VERSION };
@@ -36,7 +36,7 @@ export declare const MODEL_ISSUES: {
36
36
  readonly NAME_INVALID: "A name is not a letter followed by letters, digits or underscores.";
37
37
  readonly NUMERIC_SCALE: "An exact number's scale is not a whole number from 0 to 38.";
38
38
  readonly OPEN_POLICY_UNACKNOWLEDGED: "A source that allows every row joins a guarded one without acknowledgeOpenPolicy.";
39
- readonly PARTITION_UNKNOWN: "A partition names a dimension that does not exist.";
39
+ readonly PARTITION_UNSUPPORTED: "A snapshot measure (partitionBy) is not computed yet; the model refuses it.";
40
40
  readonly PERCENTILE_MERGE: "A percentile has a merge other than \"none\".";
41
41
  readonly POLICY_COLUMN_MISSING: "A policy leaf has no column.";
42
42
  readonly POLICY_EXISTS_RESERVED: "A policy uses a grant table (exists), which is reserved.";
@@ -168,6 +168,7 @@ export declare const BASE_ERROR_CODES: {
168
168
  QUERY_TIMEOUT: RawError<"QUERY_TIMEOUT">;
169
169
  RETRYABLE: RawError<"RETRYABLE">;
170
170
  INTERNAL: RawError<"INTERNAL">;
171
+ CANCELLED: RawError<"CANCELLED">;
171
172
  NO_HANDLER: RawError<"NO_HANDLER">;
172
173
  DRILL_DENIED: RawError<"DRILL_DENIED">;
173
174
  DRILL_STALE: RawError<"DRILL_STALE">;
@@ -39,7 +39,7 @@ const MODEL_ISSUES = {
39
39
  NAME_INVALID: "A name is not a letter followed by letters, digits or underscores.",
40
40
  NUMERIC_SCALE: "An exact number's scale is not a whole number from 0 to 38.",
41
41
  OPEN_POLICY_UNACKNOWLEDGED: "A source that allows every row joins a guarded one without acknowledgeOpenPolicy.",
42
- PARTITION_UNKNOWN: "A partition names a dimension that does not exist.",
42
+ PARTITION_UNSUPPORTED: "A snapshot measure (partitionBy) is not computed yet; the model refuses it.",
43
43
  PERCENTILE_MERGE: "A percentile has a merge other than \"none\".",
44
44
  POLICY_COLUMN_MISSING: "A policy leaf has no column.",
45
45
  POLICY_EXISTS_RESERVED: "A policy uses a grant table (exists), which is reserved.",
@@ -146,6 +146,7 @@ const BASE_ERROR_CODES = defineErrorCodes({
146
146
  QUERY_TIMEOUT: "The query ran past its deadline.",
147
147
  RETRYABLE: "The request could not complete. Try again.",
148
148
  INTERNAL: "Something went wrong on the server. Its cause is in the host's logs.",
149
+ CANCELLED: "The request was abandoned (the viewer left, or its deadline passed) before it was answered. Its statements were cancelled; nothing is logged.",
149
150
  NO_HANDLER: "No dashboards handler answered at the client's path: mount the handler there or set baseURL.",
150
151
  DRILL_DENIED: "No drill here: the server sets drill: false, the model keeps the source out, the viewer is on a public link, or the host keeps its records back.",
151
152
  DRILL_STALE: "The dashboard changed since the drill was opened. Open it again from the chart.",
@@ -17,7 +17,7 @@ import { viaJoins } from "./model/validate/via.mjs";
17
17
  import { Span, inSpan, resolveRange } from "./time/range.mjs";
18
18
  import { NaiveRule, OffsetSegment, offsetSegments, resolveNaive, startOfDate } from "./time/zone.mjs";
19
19
  import { BoundRule, bindFilter, bindPolicy, namedPolicy, viewerValues } from "./policy/bind.mjs";
20
- import { ruleMatches, selectRule } from "./policy/match.mjs";
20
+ import { bindQueryViewer, bindViewer } from "./policy/bind-query.mjs";
21
21
  import { Command, CommandBody, CommandId, Display, Doc, LayoutItem, Scope, Tab, TabId, Widget, WidgetId, emptyDoc } from "./document/types.mjs";
22
22
  import { Change, Placement, WidgetPart, changedWidget, diffDocs, markShifted, placementOf, widgetDiff } from "./document/diff.mjs";
23
23
  import { GRID_COLUMNS, Gap, closeGaps, closeGapsCommands, freeSpot, layoutGaps, placeItem, repairLayout } from "./document/layout.mjs";
@@ -26,15 +26,17 @@ import { lockChanged, reduce, reduceAll } from "./document/reduce.mjs";
26
26
  import { Recorded, Replayed, commandWidget, replay } from "./document/replay.mjs";
27
27
  import { readingOrder, stepCommands, stepMoves } from "./document/stacked.mjs";
28
28
  import { EncodeOptions, VIEW_PREFIX, ViewState, encodeView, viewFor, withView } from "./document/view.mjs";
29
+ import { smallestFor, viewLayout } from "./document/view-layout.mjs";
29
30
  import { EXACT_LIMIT, Exact, divideExact, formatExact, parseExact, storedExact } from "./exact/decimal.mjs";
30
31
  import { ExactSum, Operands, rowValue, sumLinear } from "./exact/sum.mjs";
32
+ import { ruleMatches, selectRule } from "./policy/match.mjs";
31
33
  import { Closure, queryClosure } from "./query/closure.mjs";
32
34
  import { AssertionContext, BoundPolicy, BoundPolicyFilter, ComposeCtx, ComposeDelta, ComposedQuery, CompositionPolicy, DEFAULT_COMPOSITION_POLICY, LockEntry, RequiredEntry, StoredLockEntry } from "./query/compose.mjs";
33
35
  import { ComposedTile, TileInput, composeTile, documentLock, tileInputs } from "./query/compose-tile.mjs";
34
36
  import { AccessParts, effectiveFilter } from "./query/effective.mjs";
35
37
  import { BoundFilter, Leaf, NEGATION_OF, NEGATIVE_OPS, NULL_OPS, NegativeOp, NodeId, NullOp, Op, POSITIVE_OPS, PositiveOp, StoredFilter, ValueLeaf, VariableLeaf, ViewerLeaf, ViewerRef, WireFilter, isBound, isLeaf, stripIds } from "./query/filter.mjs";
36
38
  import { FormulaRef, changeOf, formulaRefs, shareOf } from "./query/formulas.mjs";
37
- import { isDateRange, pickProblem } from "./query/picks.mjs";
39
+ import { isDateRange, isValuePick, pickProblem } from "./query/picks.mjs";
38
40
  import { Alias, QueryReferenceError, toWire } from "./query/to-wire.mjs";
39
41
  import { CalcAlias, Calendar, Cell, Control, ControlId, DateRange, DimensionAlias, DimensionCut, EntryId, ExplicitRange, Format, Formula, FormulaNode, Grain, MeasureAlias, Picks, RefOf, RelativeRange, ResolvedRange, ScopeCoverage, StoredFormulaNode, StoredQuery, TileRef, TypedFilter, TypedQuery, WireQuery } from "./query/types.mjs";
40
42
  import { memberLabel, recordColumns, resultColumns } from "./result/columns.mjs";
@@ -57,4 +59,4 @@ import { Author, DashAdapter, DashboardHead, DashboardReader, DashboardStore, Da
57
59
  import { CanFn, Channel, Principal, Resource, TenantKeysOf, Verb, Viewer, ViewerFor, principalTenant } from "./types/viewer.mjs";
58
60
  import { canonical } from "./value/canonical.mjs";
59
61
  import { fold, foldingPairs } from "./value/casefold.mjs";
60
- export { type AccessParts, type Alias, type AnswerDrill, type ApiError, type AssertionContext, type Author, type Awaitable, BASE_ERROR_CODES, type BoundFilter, type BoundPolicy, type BoundPolicyFilter, type BoundRule, CATALOG, CONTRACT_VERSION, type CalcAlias, type Calendar, type CanFn, type Catalog, type CatalogIssueCode, type Cell, type Change, type Channel, type ClosedRow, type Closure, type CodeDashboard, type Column, type ColumnType, type Command, type CommandBody, type CommandId, type ComposeCtx, type ComposeDelta, type ComposedQuery, type ComposedTile, type CompositionPolicy, type ConnectionId, type Control, type ControlId, type CoreApi, type CoreContract, type CreateDash, type CustomSource, type Cuts, DEFAULT_COMPOSITION_POLICY, DRILL_REASONS, type Dash, type DashAdapter, type DashEndpoint, type DashHook, type DashOptions, type DashPlugin, type DashboardHead, type DashboardListResponse, type DashboardReader, type DashboardResponse, type DashboardStore, type DashboardSummary, type DatePart, type DateRange, type DbSchema, type DimensionAlias, type DimensionCut, type DimensionDef, type DimensionHints, type DimensionId, type DimensionName, type Display, type Doc, type DocumentRefusalCode, type DocumentSlice, type Draft, type DraftResponse, type DraftTarget, type Drill, type DrillAbilities, type DrillAnswer, type DrillBody, type DrillCan, type DrillCrumb, type DrillExplanationView, type DrillField, type DrillGroupedView, type DrillItem, type DrillItemsView, type DrillOperand, type DrillOrigin, type DrillReason, type DrillSemantics, type DrillState, type DrillStep, type DrillSummary, type DrillView, EXACT_LIMIT, EXPR_FUNCTIONS, type EncodeOptions, type EndpointAccess, type EndpointContext, type EndpointsByPath, type EntryId, type Exact, type ExactSum, type Explanation, type ExplicitRange, type Expr, type ExprCondition, type ExprFunction, type Field, type FieldType, type Format, type Formula, type FormulaNode, type FormulaRef, GRID_COLUMNS, type Gap, type Grain, type GroupedRead, type HeadersLike, type HookContext, type HostCell, type HostRows, type IanaZone, type IntrospectingConnection, type IsoInstant, type Issue, type IssueCode, type ItemColumn, type ItemLinks, type ItemLinksFor, type JoinDef, type JoinName, type JoinedDimensionId, LINK_PART, type LayoutItem, type Leaf, type LinearTerm, type LockEntry, MAX_DRILL_STEPS, MICROS_PER_DAY, MICROS_PER_HOUR, MICROS_PER_SECOND, type Mark, type MeasureAlias, type MeasureDef, type MeasureId, type MeasureName, type MemberId, type MemberMeta, type MemberRef, type MetaJoin, type MetaMember, type MetaResponse, type Micros, type Model, ModelError, type ModelIssueCode, type Moment, NEGATION_OF, NEGATIVE_OPS, NULL_OPS, type NaiveRule, type NegativeOp, type NodeId, type Noun, type NullOp, type NumberFormat, type Numeric, type OffsetSegment, type Op, type Operands, type Outcome, type OverlapPart, type OwnDimensionId, POSITIVE_OPS, type PageRequest, type Param, type Picks, type PinnedExecution, type Placement, type PluginEndpoints, type PluginErrorCodes, type PolicyBinding, type PolicyFilter, type PolicyName, type PolicyRule, type PositiveOp, type Preview, type Primitive, type Principal, type PublishResponse, type Published, type QueryAnswer, type QueryConnection, type QueryCtx, type QueryLine, QueryReferenceError, type QueryRefusalCode, type RawError, type RawLevels, type RawResult, type ReadContext, type ReadField, type ReadFilter, type ReadMeasure, type ReadSession, type Receipt, type RecordColumn, type RecordPage, type Recorded, type RecordsHint, type RecordsRead, type RecordsResponse, type RefOf, type Refusal, type Relationship, type RelativeRange, type Replayed, type RequiredEntry, type ResolvedDimension, type ResolvedRange, type Resource, type Result, type ResultCell, type ResultColumn, type ResultRows, type ResultWarningCode, type Row, type RowPolicy, type RunOptions, type RuntimeErrorCode, type SchemaDriver, type Scope, type ScopeCoverage, type SealedAnswer, type SecondaryStorage, type Selection, type SemanticProvider, type ServerCall, type ServerCallInput, type ServerCalls, type SourceDef, type SourceName, type SourceNameOf, type Span, type Sql, type StoreDialect, type StoredFilter, type StoredFormulaNode, type StoredLockEntry, type StoredQuery, type StoredVersion, TABLES, type Tab, type TabId, type TableCheck, type TableDef, type TableName, type Tenant, type TenantBinding, type TenantKey, type TenantKeysOf, type TileAnswer, type TileInput, type TileLine, type TileRef, type TileRequest, type TileResult, type TilesRequest, type TimeStorage, type Token, type Tone, type TypedFilter, type TypedQuery, type UniqueIds, type Unit, type UnpublishedDraft, VIEW_PREFIX, type ValidateResponse, type ValueLeaf, type ValuesResponse, type VariableLeaf, type Verb, type VersionEntry, type ViewState, type Viewer, type ViewerFor, type ViewerLeaf, type ViewerMatch, type ViewerRef, type WeekStart, type Where, type Widget, type WidgetId, type WidgetPart, type WireFilter, type WireQuery, bindFilter, bindPolicy, bucketLabel, bucketLabels, bucketStart, canonical, changeOf, changedWidget, checkCatalog, closeGaps, closeGapsCommands, commandWidget, comparisonQuery, comparisonSpan, composeTile, createDashEndpoint, createTable, defineErrorCodes, defineModel, describeQueries, diffDocs, divideExact, documentLock, effectiveFilter, emptyDoc, encodeView, fold, foldingPairs, formatExact, formatTextTime, formulaRefs, freeSpot, inSpan, isBound, isDateRange, isLeaf, isMark, isZone, itemLink, layoutGaps, linearTerms, linkTemplateIssues, lockChanged, markShifted, markedRows, memberLabel, momentMicros, namedPolicy, nextBucketStart, offsetSegments, parseDate, parseExact, parseMemberId, parseNaiveTime, parseTextTime, pickProblem, placeItem, placementOf, policyBinding, principalTenant, queryClosure, readingOrder, recordColumns, recordDimensions, reduce, reduceAll, repairLayout, replay, resolveDimension, resolveMeasure, resolveNaive, resolveRange, resultColumns, rowValue, ruleMatches, schemaChecks, schemaStatements, selectRule, shareOf, shiftBucket, shiftInstant, startOfDate, stepCommands, stepMoves, storedExact, stripIds, sumLinear, tileInputs, toWire, validateModel, viaJoins, viewFor, viewerValues, widgetDiff, withView };
62
+ export { type AccessParts, type Alias, type AnswerDrill, type ApiError, type AssertionContext, type Author, type Awaitable, BASE_ERROR_CODES, type BoundFilter, type BoundPolicy, type BoundPolicyFilter, type BoundRule, CATALOG, CONTRACT_VERSION, type CalcAlias, type Calendar, type CanFn, type Catalog, type CatalogIssueCode, type Cell, type Change, type Channel, type ClosedRow, type Closure, type CodeDashboard, type Column, type ColumnType, type Command, type CommandBody, type CommandId, type ComposeCtx, type ComposeDelta, type ComposedQuery, type ComposedTile, type CompositionPolicy, type ConnectionId, type Control, type ControlId, type CoreApi, type CoreContract, type CreateDash, type CustomSource, type Cuts, DEFAULT_COMPOSITION_POLICY, DRILL_REASONS, type Dash, type DashAdapter, type DashEndpoint, type DashHook, type DashOptions, type DashPlugin, type DashboardHead, type DashboardListResponse, type DashboardReader, type DashboardResponse, type DashboardStore, type DashboardSummary, type DatePart, type DateRange, type DbSchema, type DimensionAlias, type DimensionCut, type DimensionDef, type DimensionHints, type DimensionId, type DimensionName, type Display, type Doc, type DocumentRefusalCode, type DocumentSlice, type Draft, type DraftResponse, type DraftTarget, type Drill, type DrillAbilities, type DrillAnswer, type DrillBody, type DrillCan, type DrillCrumb, type DrillExplanationView, type DrillField, type DrillGroupedView, type DrillItem, type DrillItemsView, type DrillOperand, type DrillOrigin, type DrillReason, type DrillSemantics, type DrillState, type DrillStep, type DrillSummary, type DrillView, EXACT_LIMIT, EXPR_FUNCTIONS, type EncodeOptions, type EndpointAccess, type EndpointContext, type EndpointsByPath, type EntryId, type Exact, type ExactSum, type Explanation, type ExplicitRange, type Expr, type ExprCondition, type ExprFunction, type Field, type FieldType, type Format, type Formula, type FormulaNode, type FormulaRef, GRID_COLUMNS, type Gap, type Grain, type GroupedRead, type HeadersLike, type HookContext, type HostCell, type HostRows, type IanaZone, type IntrospectingConnection, type IsoInstant, type Issue, type IssueCode, type ItemColumn, type ItemLinks, type ItemLinksFor, type JoinDef, type JoinName, type JoinedDimensionId, LINK_PART, type LayoutItem, type Leaf, type LinearTerm, type LockEntry, MAX_DRILL_STEPS, MICROS_PER_DAY, MICROS_PER_HOUR, MICROS_PER_SECOND, type Mark, type MeasureAlias, type MeasureDef, type MeasureId, type MeasureName, type MemberId, type MemberMeta, type MemberRef, type MetaJoin, type MetaMember, type MetaResponse, type Micros, type Model, ModelError, type ModelIssueCode, type Moment, NEGATION_OF, NEGATIVE_OPS, NULL_OPS, type NaiveRule, type NegativeOp, type NodeId, type Noun, type NullOp, type NumberFormat, type Numeric, type OffsetSegment, type Op, type Operands, type Outcome, type OverlapPart, type OwnDimensionId, POSITIVE_OPS, type PageRequest, type Param, type Picks, type PinnedExecution, type Placement, type PluginEndpoints, type PluginErrorCodes, type PolicyBinding, type PolicyFilter, type PolicyName, type PolicyRule, type PositiveOp, type Preview, type Primitive, type Principal, type PublishResponse, type Published, type QueryAnswer, type QueryConnection, type QueryCtx, type QueryLine, QueryReferenceError, type QueryRefusalCode, type RawError, type RawLevels, type RawResult, type ReadContext, type ReadField, type ReadFilter, type ReadMeasure, type ReadSession, type Receipt, type RecordColumn, type RecordPage, type Recorded, type RecordsHint, type RecordsRead, type RecordsResponse, type RefOf, type Refusal, type Relationship, type RelativeRange, type Replayed, type RequiredEntry, type ResolvedDimension, type ResolvedRange, type Resource, type Result, type ResultCell, type ResultColumn, type ResultRows, type ResultWarningCode, type Row, type RowPolicy, type RunOptions, type RuntimeErrorCode, type SchemaDriver, type Scope, type ScopeCoverage, type SealedAnswer, type SecondaryStorage, type Selection, type SemanticProvider, type ServerCall, type ServerCallInput, type ServerCalls, type SourceDef, type SourceName, type SourceNameOf, type Span, type Sql, type StoreDialect, type StoredFilter, type StoredFormulaNode, type StoredLockEntry, type StoredQuery, type StoredVersion, TABLES, type Tab, type TabId, type TableCheck, type TableDef, type TableName, type Tenant, type TenantBinding, type TenantKey, type TenantKeysOf, type TileAnswer, type TileInput, type TileLine, type TileRef, type TileRequest, type TileResult, type TilesRequest, type TimeStorage, type Token, type Tone, type TypedFilter, type TypedQuery, type UniqueIds, type Unit, type UnpublishedDraft, VIEW_PREFIX, type ValidateResponse, type ValueLeaf, type ValuesResponse, type VariableLeaf, type Verb, type VersionEntry, type ViewState, type Viewer, type ViewerFor, type ViewerLeaf, type ViewerMatch, type ViewerRef, type WeekStart, type Where, type Widget, type WidgetId, type WidgetPart, type WireFilter, type WireQuery, bindFilter, bindPolicy, bindQueryViewer, bindViewer, bucketLabel, bucketLabels, bucketStart, canonical, changeOf, changedWidget, checkCatalog, closeGaps, closeGapsCommands, commandWidget, comparisonQuery, comparisonSpan, composeTile, createDashEndpoint, createTable, defineErrorCodes, defineModel, describeQueries, diffDocs, divideExact, documentLock, effectiveFilter, emptyDoc, encodeView, fold, foldingPairs, formatExact, formatTextTime, formulaRefs, freeSpot, inSpan, isBound, isDateRange, isLeaf, isMark, isValuePick, isZone, itemLink, layoutGaps, linearTerms, linkTemplateIssues, lockChanged, markShifted, markedRows, memberLabel, momentMicros, namedPolicy, nextBucketStart, offsetSegments, parseDate, parseExact, parseMemberId, parseNaiveTime, parseTextTime, pickProblem, placeItem, placementOf, policyBinding, principalTenant, queryClosure, readingOrder, recordColumns, recordDimensions, reduce, reduceAll, repairLayout, replay, resolveDimension, resolveMeasure, resolveNaive, resolveRange, resultColumns, rowValue, ruleMatches, schemaChecks, schemaStatements, selectRule, shareOf, shiftBucket, shiftInstant, smallestFor, startOfDate, stepCommands, stepMoves, storedExact, stripIds, sumLinear, tileInputs, toWire, validateModel, viaJoins, viewFor, viewLayout, viewerValues, widgetDiff, withView };
@@ -7,6 +7,7 @@ import { readingOrder, stepCommands, stepMoves } from "./document/stacked.mjs";
7
7
  import { emptyDoc } from "./document/types.mjs";
8
8
  import { checkCatalog } from "./model/catalog/check.mjs";
9
9
  import { VIEW_PREFIX, encodeView, viewFor, withView } from "./document/view.mjs";
10
+ import { smallestFor, viewLayout } from "./document/view-layout.mjs";
10
11
  import { describeQueries } from "./model/catalog/queries.mjs";
11
12
  import { EXACT_LIMIT, divideExact, formatExact, parseExact, storedExact } from "./exact/decimal.mjs";
12
13
  import { rowValue, sumLinear } from "./exact/sum.mjs";
@@ -18,15 +19,16 @@ import { linearTerms } from "./model/validate/expr.mjs";
18
19
  import { validateModel } from "./model/validate/index.mjs";
19
20
  import { viaJoins } from "./model/validate/via.mjs";
20
21
  import { bindFilter, bindPolicy, namedPolicy, viewerValues } from "./policy/bind.mjs";
21
- import { ruleMatches, selectRule } from "./policy/match.mjs";
22
+ import { bindQueryViewer, bindViewer } from "./policy/bind-query.mjs";
22
23
  import { isZone, momentMicros } from "./time/temporal.mjs";
24
+ import { ruleMatches, selectRule } from "./policy/match.mjs";
23
25
  import { queryClosure } from "./query/closure.mjs";
24
26
  import { DEFAULT_COMPOSITION_POLICY } from "./query/compose.mjs";
25
27
  import { composeTile, documentLock, tileInputs } from "./query/compose-tile.mjs";
26
28
  import { effectiveFilter } from "./query/effective.mjs";
27
29
  import { NEGATION_OF, NEGATIVE_OPS, NULL_OPS, POSITIVE_OPS, isBound, isLeaf, stripIds } from "./query/filter.mjs";
28
30
  import { changeOf, formulaRefs, shareOf } from "./query/formulas.mjs";
29
- import { isDateRange, pickProblem } from "./query/picks.mjs";
31
+ import { isDateRange, isValuePick, pickProblem } from "./query/picks.mjs";
30
32
  import { QueryReferenceError, toWire } from "./query/to-wire.mjs";
31
33
  import { LINK_PART, itemLink, linkTemplateIssues } from "./query/drill/links.mjs";
32
34
  import { MAX_DRILL_STEPS } from "./query/drill/types.mjs";
@@ -44,4 +46,4 @@ import { createDashEndpoint } from "./types/plugin.mjs";
44
46
  import { principalTenant } from "./types/viewer.mjs";
45
47
  import { canonical } from "./value/canonical.mjs";
46
48
  import { fold, foldingPairs } from "./value/casefold.mjs";
47
- export { BASE_ERROR_CODES, CATALOG, CONTRACT_VERSION, DEFAULT_COMPOSITION_POLICY, DRILL_REASONS, EXACT_LIMIT, EXPR_FUNCTIONS, GRID_COLUMNS, LINK_PART, MAX_DRILL_STEPS, MICROS_PER_DAY, MICROS_PER_HOUR, MICROS_PER_SECOND, ModelError, NEGATION_OF, NEGATIVE_OPS, NULL_OPS, POSITIVE_OPS, QueryReferenceError, TABLES, VIEW_PREFIX, bindFilter, bindPolicy, bucketLabel, bucketLabels, bucketStart, canonical, changeOf, changedWidget, checkCatalog, closeGaps, closeGapsCommands, commandWidget, comparisonQuery, comparisonSpan, composeTile, createDashEndpoint, createTable, defineErrorCodes, defineModel, describeQueries, diffDocs, divideExact, documentLock, effectiveFilter, emptyDoc, encodeView, fold, foldingPairs, formatExact, formatTextTime, formulaRefs, freeSpot, inSpan, isBound, isDateRange, isLeaf, isMark, isZone, itemLink, layoutGaps, linearTerms, linkTemplateIssues, lockChanged, markShifted, markedRows, memberLabel, momentMicros, namedPolicy, nextBucketStart, offsetSegments, parseDate, parseExact, parseMemberId, parseNaiveTime, parseTextTime, pickProblem, placeItem, placementOf, policyBinding, principalTenant, queryClosure, readingOrder, recordColumns, recordDimensions, reduce, reduceAll, repairLayout, replay, resolveDimension, resolveMeasure, resolveNaive, resolveRange, resultColumns, rowValue, ruleMatches, schemaChecks, schemaStatements, selectRule, shareOf, shiftBucket, shiftInstant, startOfDate, stepCommands, stepMoves, storedExact, stripIds, sumLinear, tileInputs, toWire, validateModel, viaJoins, viewFor, viewerValues, widgetDiff, withView };
49
+ export { BASE_ERROR_CODES, CATALOG, CONTRACT_VERSION, DEFAULT_COMPOSITION_POLICY, DRILL_REASONS, EXACT_LIMIT, EXPR_FUNCTIONS, GRID_COLUMNS, LINK_PART, MAX_DRILL_STEPS, MICROS_PER_DAY, MICROS_PER_HOUR, MICROS_PER_SECOND, ModelError, NEGATION_OF, NEGATIVE_OPS, NULL_OPS, POSITIVE_OPS, QueryReferenceError, TABLES, VIEW_PREFIX, bindFilter, bindPolicy, bindQueryViewer, bindViewer, bucketLabel, bucketLabels, bucketStart, canonical, changeOf, changedWidget, checkCatalog, closeGaps, closeGapsCommands, commandWidget, comparisonQuery, comparisonSpan, composeTile, createDashEndpoint, createTable, defineErrorCodes, defineModel, describeQueries, diffDocs, divideExact, documentLock, effectiveFilter, emptyDoc, encodeView, fold, foldingPairs, formatExact, formatTextTime, formulaRefs, freeSpot, inSpan, isBound, isDateRange, isLeaf, isMark, isValuePick, isZone, itemLink, layoutGaps, linearTerms, linkTemplateIssues, lockChanged, markShifted, markedRows, memberLabel, momentMicros, namedPolicy, nextBucketStart, offsetSegments, parseDate, parseExact, parseMemberId, parseNaiveTime, parseTextTime, pickProblem, placeItem, placementOf, policyBinding, principalTenant, queryClosure, readingOrder, recordColumns, recordDimensions, reduce, reduceAll, repairLayout, replay, resolveDimension, resolveMeasure, resolveNaive, resolveRange, resultColumns, rowValue, ruleMatches, schemaChecks, schemaStatements, selectRule, shareOf, shiftBucket, shiftInstant, smallestFor, startOfDate, stepCommands, stepMoves, storedExact, stripIds, sumLinear, tileInputs, toWire, validateModel, viaJoins, viewFor, viewLayout, viewerValues, widgetDiff, withView };
@@ -63,9 +63,12 @@ const DEFAULT_RECORD_COLUMNS = 12;
63
63
  function recordDimensions(model, sourceName) {
64
64
  const def = model.sources[sourceName];
65
65
  if (def === void 0) return [];
66
- if (def.records?.columns !== void 0) return def.records.columns.filter((n) => def.dimensions[n] !== void 0);
66
+ const title = def.records?.title;
67
+ const named = title !== void 0 && def.dimensions[title] !== void 0 ? title : void 0;
68
+ const lead = (names) => named === void 0 || names.includes(named) ? names : [named, ...names];
69
+ if (def.records?.columns !== void 0) return lead(def.records.columns.filter((n) => def.dimensions[n] !== void 0));
67
70
  const time = def.time ?? Object.entries(def.dimensions).find(([, d]) => d.kind === "time")?.[0];
68
71
  const rank = ([n, d]) => shownRank(d, n === time);
69
- return Object.entries(def.dimensions).filter(([n]) => !n.startsWith("dd_")).filter(([, d]) => d.hidden !== true && d.sensitive !== true && d.drill !== false).filter(([n, d]) => d.kind !== "time" || n === time).toSorted((a, b) => rank(a) - rank(b)).slice(0, DEFAULT_RECORD_COLUMNS).map(([n]) => n);
72
+ return lead(Object.entries(def.dimensions).filter(([n]) => !n.startsWith("dd_") && n !== named).filter(([, d]) => d.hidden !== true && d.sensitive !== true && d.drill !== false).filter(([n, d]) => d.kind !== "time" || n === time).toSorted((a, b) => rank(a) - rank(b)).map(([n]) => n).slice(0, DEFAULT_RECORD_COLUMNS - (named === void 0 ? 0 : 1)));
70
73
  }
71
74
  export { parseMemberId, recordDimensions, resolveDimension, resolveMeasure };
@@ -157,6 +157,15 @@ export type Numeric = "float" | {
157
157
  scale: number;
158
158
  stored: "decimal" | "minor_units";
159
159
  };
160
+ /** What every measure over a column may add: rows it reads, a duration format, a partition. */
161
+ type OverColumn = {
162
+ of: Column | Expr;
163
+ where?: WireFilter;
164
+ /** `duration`: the values are seconds, shown as "3.7 days", "2 h". */
165
+ format?: "duration";
166
+ /** Reserved for snapshot measures (the last value per partition). Refused by the model check until computed. */
167
+ partitionBy?: DimensionName;
168
+ };
160
169
  /** One aggregate per measure, so each has one result type and one merge rule. */
161
170
  export type MeasureDef = MemberMeta & {
162
171
  /** How partial results combine. `none` means they cannot be combined. */
@@ -165,26 +174,17 @@ export type MeasureDef = MemberMeta & {
165
174
  kind: "count";
166
175
  distinct?: Column;
167
176
  where?: WireFilter;
168
- } | {
177
+ } | ({
169
178
  kind: "sum" | "min" | "max";
170
- of: Column | Expr;
171
179
  numeric: Numeric;
172
- where?: WireFilter;
173
180
  unit?: Unit;
174
- partitionBy?: DimensionName;
175
- } | {
181
+ } & OverColumn) | ({
176
182
  kind: "avg";
177
- of: Column | Expr;
178
183
  numeric: Numeric;
179
- where?: WireFilter;
180
- partitionBy?: DimensionName;
181
- } | {
184
+ } & OverColumn) | ({
182
185
  kind: "percentile";
183
- of: Column | Expr;
184
186
  p: 50 | 75 | 90 | 95 | 99;
185
- where?: WireFilter;
186
- partitionBy?: DimensionName;
187
- } | {
187
+ } & OverColumn) | {
188
188
  kind: "ratio";
189
189
  numerator: MeasureName;
190
190
  denominator: MeasureName;
@@ -64,10 +64,13 @@ function numericIssues(numeric, path) {
64
64
  const ok = Number.isInteger(numeric.scale) && numeric.scale >= 0 && numeric.scale <= 38;
65
65
  return when(!ok, "NUMERIC_SCALE", [...path, "scale"], "The scale must be a whole number, 0 to 38.");
66
66
  }
67
- function partitionIssues(source, measure, path) {
68
- const partition = measure.partitionBy;
69
- const unknown = partition !== void 0 && source.dimensions[partition] === void 0;
70
- return when(unknown, "PARTITION_UNKNOWN", path, `There is no dimension named "${partition}".`);
67
+ /**
68
+ * A snapshot measure (`partitionBy`) is refused until the engines compute its meaning, the last
69
+ * value per partition in a bucket: accepting it now would answer an ordinary aggregate where the
70
+ * model's author asked for a snapshot.
71
+ */
72
+ function partitionIssues(_source, measure, path) {
73
+ return when(measure.partitionBy !== void 0, "PARTITION_UNSUPPORTED", path, "Snapshot measures (partitionBy) are not computed yet: remove it, or model the snapshot as a source of last rows.");
71
74
  }
72
75
  function percentileIssues(measure, path) {
73
76
  const bad = measure.kind === "percentile" && measure.merge !== "none";
@@ -0,0 +1,12 @@
1
+ import { WireFilter } from "../query/filter.mjs";
2
+ import { WireQuery } from "../query/types.mjs";
3
+ import { Principal } from "../types/viewer.mjs";
4
+ /**
5
+ * The filter with every viewer reference (`{ viewer: "id" }`) replaced by the signed-in viewer's
6
+ * values, as a row policy binds them. When a value is missing (a public link, a viewer without
7
+ * that attribute), the whole filter matches no rows: a missing value never makes a negated leaf
8
+ * true. Variables are left as they are.
9
+ */
10
+ export declare function bindViewer(filter: WireFilter, principal: Principal): WireFilter;
11
+ /** The query with the viewer bound in its filters and in each measure's own filter. */
12
+ export declare function bindQueryViewer(query: WireQuery, principal: Principal): WireQuery;
@@ -0,0 +1,53 @@
1
+ import { viewerValues } from "./bind.mjs";
2
+ // src/policy/bind-query.ts
3
+ /** No rows: what a filter is when a viewer value it needs is missing. */
4
+ const NOTHING = { any: [] };
5
+ var Missing = class extends Error {};
6
+ function walk(filter, viewer) {
7
+ if ("all" in filter) return { all: filter.all.map((f) => walk(f, viewer)) };
8
+ if ("any" in filter) return { any: filter.any.map((f) => walk(f, viewer)) };
9
+ if ("not" in filter) return { not: walk(filter.not, viewer) };
10
+ if ("some" in filter) return { some: {
11
+ ...filter.some,
12
+ where: walk(filter.some.where, viewer)
13
+ } };
14
+ if ("none" in filter) return { none: {
15
+ ...filter.none,
16
+ where: walk(filter.none.where, viewer)
17
+ } };
18
+ if (!("viewer" in filter)) return filter;
19
+ const values = viewer === void 0 ? [] : viewerValues(viewer, filter.viewer);
20
+ if (values.length === 0) throw new Missing();
21
+ return {
22
+ member: filter.member,
23
+ op: filter.op,
24
+ values
25
+ };
26
+ }
27
+ /**
28
+ * The filter with every viewer reference (`{ viewer: "id" }`) replaced by the signed-in viewer's
29
+ * values, as a row policy binds them. When a value is missing (a public link, a viewer without
30
+ * that attribute), the whole filter matches no rows: a missing value never makes a negated leaf
31
+ * true. Variables are left as they are.
32
+ */
33
+ function bindViewer(filter, principal) {
34
+ const viewer = principal.channel === "user" ? principal.viewer : void 0;
35
+ try {
36
+ return walk(filter, viewer);
37
+ } catch (error) {
38
+ if (error instanceof Missing) return NOTHING;
39
+ throw error;
40
+ }
41
+ }
42
+ /** The query with the viewer bound in its filters and in each measure's own filter. */
43
+ function bindQueryViewer(query, principal) {
44
+ return {
45
+ ...query,
46
+ ...query.filters === void 0 ? {} : { filters: bindViewer(query.filters, principal) },
47
+ measures: query.measures.map((m) => m.filter === void 0 ? m : {
48
+ ...m,
49
+ filter: bindViewer(m.filter, principal)
50
+ })
51
+ };
52
+ }
53
+ export { bindQueryViewer, bindViewer };
@@ -15,6 +15,12 @@ export type ValueLeaf<Member extends string = string> = {
15
15
  member: Member;
16
16
  op: Op;
17
17
  values: readonly Primitive[];
18
+ /**
19
+ * Set only by the engine, on a limited dimension's kept values: a test that keeps most rows,
20
+ * which no index would answer, so its SQL leaves out the tests that are there for an index.
21
+ * The wire schema refuses it, and it changes no answer.
22
+ */
23
+ broad?: true;
18
24
  };
19
25
  export type ViewerLeaf<Member extends string = string> = {
20
26
  member: Member;
@@ -1,10 +1,16 @@
1
+ import { Primitive } from "../types/primitives.mjs";
1
2
  import { Control, DateRange, Picks } from "./types.mjs";
2
3
  /** Whether a pick is a date range: the last N units, or from and to. */
3
4
  export declare function isDateRange(pick: Picks[string]): pick is DateRange;
5
+ /** Whether a pick is a filter's: an operator and its values. */
6
+ export declare function isValuePick(pick: Picks[string] | undefined): pick is Extract<Picks[string], {
7
+ values: readonly Primitive[];
8
+ }>;
4
9
  /**
5
10
  * Why a viewer's pick does not fit its control, or undefined when it does: the one rule the
6
11
  * tiles and a shared link both apply. A filter takes values with one of its operators, from
7
- * its own list when it has one, at least one value, and only one unless it is multi; a date
8
- * range control takes a range; any other control takes no pick yet.
12
+ * its own list when it has one, at least one value (none for set and notSet, which test null),
13
+ * and only one unless it is multi; a date range control takes a range; any other control takes
14
+ * no pick yet.
9
15
  */
10
16
  export declare function pickProblem(control: Control, pick: Picks[string]): string | undefined;
@@ -3,18 +3,25 @@
3
3
  function isDateRange(pick) {
4
4
  return typeof pick === "object" && pick !== null && ("last" in pick || "from" in pick);
5
5
  }
6
+ /** Whether a pick is a filter's: an operator and its values. */
7
+ function isValuePick(pick) {
8
+ return typeof pick === "object" && pick !== null && "values" in pick;
9
+ }
6
10
  /** Whether a filter pick fits its filter: one of its operators, its own values, one unless multi. */
7
11
  function filterFits(control, pick) {
12
+ if (!control.ops.some((op) => op === pick.op)) return false;
13
+ if (pick.op === "set" || pick.op === "notSet") return pick.values.length === 0;
8
14
  const allowed = Array.isArray(control.values) ? control.values : void 0;
9
15
  const inList = allowed === void 0 || pick.values.every((v) => allowed.includes(v));
10
16
  const count = pick.values.length > 0 && (control.multi || pick.values.length === 1);
11
- return control.ops.some((op) => op === pick.op) && inList && count;
17
+ return inList && count;
12
18
  }
13
19
  /**
14
20
  * Why a viewer's pick does not fit its control, or undefined when it does: the one rule the
15
21
  * tiles and a shared link both apply. A filter takes values with one of its operators, from
16
- * its own list when it has one, at least one value, and only one unless it is multi; a date
17
- * range control takes a range; any other control takes no pick yet.
22
+ * its own list when it has one, at least one value (none for set and notSet, which test null),
23
+ * and only one unless it is multi; a date range control takes a range; any other control takes
24
+ * no pick yet.
18
25
  */
19
26
  function pickProblem(control, pick) {
20
27
  if (control.kind === "date_range") return isDateRange(pick) ? void 0 : `The pick for "${control.id}" is not a date range.`;
@@ -22,4 +29,4 @@ function pickProblem(control, pick) {
22
29
  if (typeof pick !== "object" || pick === null || !("op" in pick)) return `The pick for "${control.id}" is not a filter.`;
23
30
  return filterFits(control, pick) ? void 0 : `The pick for "${control.id}" is not one the control allows.`;
24
31
  }
25
- export { isDateRange, pickProblem };
32
+ export { isDateRange, isValuePick, pickProblem };
@@ -64,7 +64,8 @@ function keptFilter(member, values) {
64
64
  const leaves = [{
65
65
  member,
66
66
  op: "in",
67
- values: values.filter((v) => v !== null && typeof v !== "object")
67
+ values: values.filter((v) => v !== null && typeof v !== "object"),
68
+ broad: true
68
69
  }];
69
70
  if (values.includes(null)) leaves.push({
70
71
  member,
@@ -11,16 +11,19 @@ const lastPart = (id) => id.split(".").at(-1) ?? id;
11
11
  function memberLabel(id, label) {
12
12
  return label ?? words(lastPart(id));
13
13
  }
14
- /** How a measure's values read: its unit, and a ratio the model reads as a percent of one. */
14
+ /** How a measure's values read: its unit, a ratio the model reads as a percent of one, a duration in seconds. */
15
15
  function readsAs(def) {
16
16
  const unit = def !== void 0 && "unit" in def ? def.unit : void 0;
17
- const percent = def?.kind === "ratio" && def.format === "percent";
17
+ const format = def !== void 0 && "format" in def ? def.format : void 0;
18
+ const percent = def?.kind === "ratio" && format === "percent";
19
+ const duration = format === "duration";
18
20
  return {
19
21
  ...unit === void 0 ? {} : { unit },
20
22
  ...percent ? {
21
23
  format: "percent",
22
24
  fraction: true
23
- } : {}
25
+ } : {},
26
+ ...duration ? { format: "duration" } : {}
24
27
  };
25
28
  }
26
29
  /** A measure's cell type: counts are integers, percentiles float, the rest as declared. */
@@ -0,0 +1,7 @@
1
+ import { WireQuery } from "../query/types.mjs";
2
+ import { z } from "zod";
3
+ /**
4
+ * The query with each id renumbered to its position and every reference following it: for an
5
+ * agent's tool, which takes any ids and answers in text, so the ids never show.
6
+ */
7
+ export declare function positional<Q extends WireQuery>(query: Q): Q;
@@ -0,0 +1,77 @@
1
+ // src/schema/aliases.ts
2
+ const LISTS = [
3
+ ["measures", "m"],
4
+ ["dimensions", "d"],
5
+ ["calc", "c"]
6
+ ];
7
+ /**
8
+ * Each entry's id is its position from 1 (the second dimension is d2): the engine, a drill and
9
+ * an answer's columns all read entries by it, so a query has one id space. References to the
10
+ * ids are checked with the rest of the query's closure.
11
+ */
12
+ function checkPositions(query, ctx) {
13
+ for (const [key, prefix] of LISTS) for (const [i, entry] of (query[key] ?? []).entries()) {
14
+ const want = `${prefix}${i + 1}`;
15
+ if (entry.id !== want) ctx.addIssue({
16
+ code: "custom",
17
+ path: [
18
+ key,
19
+ i,
20
+ "id"
21
+ ],
22
+ message: `Entry ${i + 1} of ${key} is "${want}", not "${entry.id}": an id is its entry's position from 1.`
23
+ });
24
+ }
25
+ }
26
+ /**
27
+ * The query with each id renumbered to its position and every reference following it: for an
28
+ * agent's tool, which takes any ids and answers in text, so the ids never show.
29
+ */
30
+ function positional(query) {
31
+ const to = /* @__PURE__ */ new Map();
32
+ for (const [key, prefix] of LISTS) for (const [i, entry] of (query[key] ?? []).entries()) to.set(entry.id, `${prefix}${i + 1}`);
33
+ const alias = (id) => to.get(id) ?? id;
34
+ const formula = (node) => {
35
+ if ("ref" in node) return {
36
+ ...node,
37
+ ref: alias(node.ref)
38
+ };
39
+ if (!("args" in node)) return node;
40
+ if (node.op === "abs") return {
41
+ op: "abs",
42
+ args: [formula(node.args[0])]
43
+ };
44
+ return {
45
+ op: node.op,
46
+ args: [formula(node.args[0]), formula(node.args[1])]
47
+ };
48
+ };
49
+ const dimensions = query.dimensions?.map((d) => ({
50
+ ...d,
51
+ id: alias(d.id),
52
+ ...d.rankBy === void 0 ? {} : { rankBy: {
53
+ ...d.rankBy,
54
+ by: alias(d.rankBy.by)
55
+ } }
56
+ }));
57
+ const calc = query.calc?.map((c) => ({
58
+ ...c,
59
+ id: alias(c.id),
60
+ formula: formula(c.formula)
61
+ }));
62
+ const order = query.order?.map((o) => ({
63
+ ...o,
64
+ by: alias(o.by)
65
+ }));
66
+ return {
67
+ ...query,
68
+ measures: query.measures.map((m) => ({
69
+ ...m,
70
+ id: alias(m.id)
71
+ })),
72
+ ...dimensions === void 0 ? {} : { dimensions },
73
+ ...calc === void 0 ? {} : { calc },
74
+ ...order === void 0 ? {} : { order }
75
+ };
76
+ }
77
+ export { checkPositions, positional };
@@ -1851,6 +1851,7 @@ export declare const answerSchemas: {
1851
1851
  dashboards: z.ZodArray<z.ZodObject<{
1852
1852
  id: z.ZodString;
1853
1853
  title: z.ZodString;
1854
+ description: z.ZodExactOptional<z.ZodString>;
1854
1855
  version: z.ZodNumber;
1855
1856
  unpublished: z.ZodExactOptional<z.ZodLiteral<true>>;
1856
1857
  }, z.core.$loose>>;
@@ -60,6 +60,7 @@ const list = z.looseObject({
60
60
  dashboards: z.array(z.looseObject({
61
61
  id: z.string(),
62
62
  title: z.string(),
63
+ description: z.string().exactOptional(),
63
64
  version: z.number(),
64
65
  unpublished: z.literal(true).exactOptional()
65
66
  })),
@@ -1,11 +1,12 @@
1
1
  import { DOCUMENT_UPGRADES, Loaded, SPEC_VERSION, Upgrade, loadDocument } from "../document/upgrade.mjs";
2
+ import { positional } from "./aliases.mjs";
2
3
  import { AnswerSchemas, answerSchemas, tileLineSchema } from "./answers.mjs";
3
4
  import { ParsedCommands, commandSchema, parseCommands } from "./commands.mjs";
4
5
  import { customReadSchemas, groupedReadSchema, recordsReadSchema } from "./custom.mjs";
5
6
  import { ParsedDocument, documentSchema, parseDocument } from "./document.mjs";
6
7
  import { drillStateSchema, drillViewSchema, pinnedSchema, selectionSchema } from "./drill.mjs";
7
8
  import { picksSchema } from "./picks.mjs";
8
- import { ParsedQuery, parseWireQuery, wireQuerySchema } from "./query.mjs";
9
+ import { ParsedQuery, parseWireQuery, wireQuerySchema, wireQueryShape } from "./query.mjs";
9
10
  import { JsonSchema, jsonSchema, toolSchemas } from "./tools.mjs";
10
11
  import { decodeView } from "./view.mjs";
11
- export { type AnswerSchemas, DOCUMENT_UPGRADES, type JsonSchema, type Loaded, type ParsedCommands, type ParsedDocument, type ParsedQuery, SPEC_VERSION, type Upgrade, answerSchemas, commandSchema, customReadSchemas, decodeView, documentSchema, drillStateSchema, drillViewSchema, groupedReadSchema, jsonSchema, loadDocument, parseCommands, parseDocument, parseWireQuery, picksSchema, pinnedSchema, recordsReadSchema, selectionSchema, tileLineSchema, toolSchemas, wireQuerySchema };
12
+ export { type AnswerSchemas, DOCUMENT_UPGRADES, type JsonSchema, type Loaded, type ParsedCommands, type ParsedDocument, type ParsedQuery, SPEC_VERSION, type Upgrade, answerSchemas, commandSchema, customReadSchemas, decodeView, documentSchema, drillStateSchema, drillViewSchema, groupedReadSchema, jsonSchema, loadDocument, parseCommands, parseDocument, parseWireQuery, picksSchema, pinnedSchema, positional, recordsReadSchema, selectionSchema, tileLineSchema, toolSchemas, wireQuerySchema, wireQueryShape };
@@ -1,11 +1,12 @@
1
1
  import { DOCUMENT_UPGRADES, SPEC_VERSION, loadDocument } from "../document/upgrade.mjs";
2
+ import { positional } from "./aliases.mjs";
2
3
  import { answerSchemas, tileLineSchema } from "./answers.mjs";
3
4
  import { commandSchema, parseCommands } from "./commands.mjs";
4
5
  import { customReadSchemas, groupedReadSchema, recordsReadSchema } from "./custom.mjs";
5
6
  import { documentSchema, parseDocument } from "./document.mjs";
6
7
  import { drillStateSchema, drillViewSchema, pinnedSchema, selectionSchema } from "./drill.mjs";
7
8
  import { picksSchema } from "./picks.mjs";
8
- import { parseWireQuery, wireQuerySchema } from "./query.mjs";
9
+ import { parseWireQuery, wireQuerySchema, wireQueryShape } from "./query.mjs";
9
10
  import { jsonSchema, toolSchemas } from "./tools.mjs";
10
11
  import { decodeView } from "./view.mjs";
11
- export { DOCUMENT_UPGRADES, SPEC_VERSION, answerSchemas, commandSchema, customReadSchemas, decodeView, documentSchema, drillStateSchema, drillViewSchema, groupedReadSchema, jsonSchema, loadDocument, parseCommands, parseDocument, parseWireQuery, picksSchema, pinnedSchema, recordsReadSchema, selectionSchema, tileLineSchema, toolSchemas, wireQuerySchema };
12
+ export { DOCUMENT_UPGRADES, SPEC_VERSION, answerSchemas, commandSchema, customReadSchemas, decodeView, documentSchema, drillStateSchema, drillViewSchema, groupedReadSchema, jsonSchema, loadDocument, parseCommands, parseDocument, parseWireQuery, picksSchema, pinnedSchema, positional, recordsReadSchema, selectionSchema, tileLineSchema, toolSchemas, wireQuerySchema, wireQueryShape };