@hypequery/datasets 0.32.0 → 0.35.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 (264) hide show
  1. package/dist/agent-catalog.d.ts +3 -3
  2. package/dist/agent-catalog.d.ts.map +1 -1
  3. package/dist/cache/protocol-cache-keys.d.ts.map +1 -1
  4. package/dist/cache/protocol-cache-keys.js +10 -48
  5. package/dist/cache/query-signature.d.ts.map +1 -1
  6. package/dist/cache/query-signature.js +16 -5
  7. package/dist/catalog.d.ts +5 -1
  8. package/dist/catalog.d.ts.map +1 -1
  9. package/dist/catalog.js +9 -0
  10. package/dist/client-contract/build-from-deployment.d.ts +2 -2
  11. package/dist/client-contract/build-from-deployment.d.ts.map +1 -1
  12. package/dist/client-contract/build-from-deployment.js +7 -0
  13. package/dist/client-contract/dataset-fields.d.ts.map +1 -1
  14. package/dist/client-contract/dataset-fields.js +2 -1
  15. package/dist/cloud-publication.d.ts +3 -3
  16. package/dist/cloud-publication.d.ts.map +1 -1
  17. package/dist/cloud-publishing.d.ts +2 -2
  18. package/dist/cloud-publishing.d.ts.map +1 -1
  19. package/dist/codegen/dataset-source.d.ts.map +1 -1
  20. package/dist/codegen/dataset-source.js +10 -1
  21. package/dist/contract-3-authoring.fixture.d.ts +103 -0
  22. package/dist/contract-3-authoring.fixture.d.ts.map +1 -0
  23. package/dist/contract-3-authoring.fixture.js +40 -0
  24. package/dist/contract.d.ts +5 -1
  25. package/dist/contract.d.ts.map +1 -1
  26. package/dist/contract.js +9 -0
  27. package/dist/dataset-compilation.d.ts +3 -0
  28. package/dist/dataset-compilation.d.ts.map +1 -1
  29. package/dist/dataset-query.d.ts +5 -0
  30. package/dist/dataset-query.d.ts.map +1 -1
  31. package/dist/dataset.d.ts.map +1 -1
  32. package/dist/dataset.js +12 -2
  33. package/dist/event-operations.d.ts +43 -0
  34. package/dist/event-operations.d.ts.map +1 -0
  35. package/dist/event-operations.js +137 -0
  36. package/dist/execution-capabilities.d.ts +16 -3
  37. package/dist/execution-capabilities.d.ts.map +1 -1
  38. package/dist/execution-capabilities.js +5 -3
  39. package/dist/execution-capabilities.json +7 -8
  40. package/dist/executor.d.ts +13 -0
  41. package/dist/executor.d.ts.map +1 -1
  42. package/dist/executor.js +42 -8
  43. package/dist/index.d.ts +7 -3
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +4 -1
  46. package/dist/portable-execution-errors.d.ts +11 -0
  47. package/dist/portable-execution-errors.d.ts.map +1 -1
  48. package/dist/portable-execution-errors.js +14 -0
  49. package/dist/portable-executor.d.ts +22 -5
  50. package/dist/portable-executor.d.ts.map +1 -1
  51. package/dist/portable-executor.js +64 -5
  52. package/dist/protocol-adapter.d.ts +12 -0
  53. package/dist/protocol-adapter.d.ts.map +1 -1
  54. package/dist/protocol-adapter.js +32 -10
  55. package/dist/protocol-deployment-adapter.d.ts +10 -3
  56. package/dist/protocol-deployment-adapter.d.ts.map +1 -1
  57. package/dist/protocol-deployment-adapter.js +60 -26
  58. package/dist/protocol-rehydrate.d.ts +3 -16
  59. package/dist/protocol-rehydrate.d.ts.map +1 -1
  60. package/dist/protocol-rehydrate.js +72 -14
  61. package/dist/query-builder-protocol.d.ts +10 -0
  62. package/dist/query-builder-protocol.d.ts.map +1 -1
  63. package/dist/query-planner.d.ts.map +1 -1
  64. package/dist/query-planner.js +3 -1
  65. package/dist/relationship-check.d.ts.map +1 -1
  66. package/dist/relationship-check.js +2 -0
  67. package/dist/semantic-planner.d.ts.map +1 -1
  68. package/dist/semantic-planner.js +17 -4
  69. package/dist/semantic-query-schema.d.ts +18 -0
  70. package/dist/semantic-query-schema.d.ts.map +1 -1
  71. package/dist/semantic-query-schema.js +79 -55
  72. package/dist/tools.d.ts +6 -0
  73. package/dist/tools.d.ts.map +1 -1
  74. package/dist/types.d.ts +121 -10
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/utils/agent-catalog-projection.d.ts +2 -12
  77. package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
  78. package/dist/utils/agent-catalog-projection.js +39 -2
  79. package/dist/utils/build-dataset-query-builder.d.ts.map +1 -1
  80. package/dist/utils/build-dataset-query-builder.js +4 -8
  81. package/dist/utils/calculation-stage-sql.d.ts +31 -0
  82. package/dist/utils/calculation-stage-sql.d.ts.map +1 -0
  83. package/dist/utils/calculation-stage-sql.js +98 -0
  84. package/dist/utils/compile-calculated-dataset-query.d.ts +24 -0
  85. package/dist/utils/compile-calculated-dataset-query.d.ts.map +1 -0
  86. package/dist/utils/compile-calculated-dataset-query.js +133 -0
  87. package/dist/utils/compile-dataset-query.d.ts.map +1 -1
  88. package/dist/utils/compile-dataset-query.js +11 -3
  89. package/dist/utils/dataset-definition-validation.d.ts.map +1 -1
  90. package/dist/utils/dataset-definition-validation.js +94 -7
  91. package/dist/utils/dataset-events.d.ts +19 -0
  92. package/dist/utils/dataset-events.d.ts.map +1 -0
  93. package/dist/utils/dataset-events.js +46 -0
  94. package/dist/utils/dataset-having.d.ts.map +1 -1
  95. package/dist/utils/dataset-having.js +6 -1
  96. package/dist/utils/dataset-query-result.d.ts.map +1 -1
  97. package/dist/utils/dataset-query-result.js +7 -1
  98. package/dist/utils/dataset-query-validation.d.ts +1 -1
  99. package/dist/utils/dataset-query-validation.d.ts.map +1 -1
  100. package/dist/utils/dataset-query-validation.js +25 -47
  101. package/dist/utils/dataset-source.d.ts +2 -2
  102. package/dist/utils/dataset-source.d.ts.map +1 -1
  103. package/dist/utils/dataset-source.js +8 -1
  104. package/dist/utils/dataset-validation.d.ts.map +1 -1
  105. package/dist/utils/dataset-validation.js +2 -1
  106. package/dist/utils/dimension-selection-overrides.d.ts +19 -0
  107. package/dist/utils/dimension-selection-overrides.d.ts.map +1 -0
  108. package/dist/utils/dimension-selection-overrides.js +22 -0
  109. package/dist/utils/event-breakdown-sql.d.ts +15 -0
  110. package/dist/utils/event-breakdown-sql.d.ts.map +1 -0
  111. package/dist/utils/event-breakdown-sql.js +17 -0
  112. package/dist/utils/event-condition-sql.d.ts +18 -0
  113. package/dist/utils/event-condition-sql.d.ts.map +1 -0
  114. package/dist/utils/event-condition-sql.js +63 -0
  115. package/dist/utils/event-operation-shape.d.ts +8 -0
  116. package/dist/utils/event-operation-shape.d.ts.map +1 -0
  117. package/dist/utils/event-operation-shape.js +66 -0
  118. package/dist/utils/event-operation-spec.d.ts +43 -0
  119. package/dist/utils/event-operation-spec.d.ts.map +1 -0
  120. package/dist/utils/event-operation-spec.js +68 -0
  121. package/dist/utils/event-range-span.d.ts +4 -0
  122. package/dist/utils/event-range-span.d.ts.map +1 -0
  123. package/dist/utils/event-range-span.js +22 -0
  124. package/dist/utils/event-result-values.d.ts +8 -0
  125. package/dist/utils/event-result-values.d.ts.map +1 -0
  126. package/dist/utils/event-result-values.js +21 -0
  127. package/dist/utils/event-source-sql.d.ts +38 -0
  128. package/dist/utils/event-source-sql.d.ts.map +1 -0
  129. package/dist/utils/event-source-sql.js +71 -0
  130. package/dist/utils/filter-predicate-tree.d.ts +28 -0
  131. package/dist/utils/filter-predicate-tree.d.ts.map +1 -0
  132. package/dist/utils/filter-predicate-tree.js +80 -0
  133. package/dist/utils/filter-tree.d.ts +42 -0
  134. package/dist/utils/filter-tree.d.ts.map +1 -0
  135. package/dist/utils/filter-tree.js +164 -0
  136. package/dist/utils/filtered-aggregation-sql.d.ts.map +1 -1
  137. package/dist/utils/filtered-aggregation-sql.js +22 -1
  138. package/dist/utils/funnel-rows.d.ts +10 -0
  139. package/dist/utils/funnel-rows.d.ts.map +1 -0
  140. package/dist/utils/funnel-rows.js +30 -0
  141. package/dist/utils/funnel-sql.d.ts +18 -0
  142. package/dist/utils/funnel-sql.d.ts.map +1 -0
  143. package/dist/utils/funnel-sql.js +104 -0
  144. package/dist/utils/metric-derived-query.d.ts.map +1 -1
  145. package/dist/utils/metric-derived-query.js +4 -5
  146. package/dist/utils/metric-query-builder.d.ts.map +1 -1
  147. package/dist/utils/metric-query-builder.js +4 -5
  148. package/dist/utils/metric-query-validation.d.ts.map +1 -1
  149. package/dist/utils/metric-query-validation.js +18 -7
  150. package/dist/utils/other-bucket-sql.d.ts +23 -0
  151. package/dist/utils/other-bucket-sql.d.ts.map +1 -0
  152. package/dist/utils/other-bucket-sql.js +51 -0
  153. package/dist/utils/portable-aggregations.d.ts +10 -6
  154. package/dist/utils/portable-aggregations.d.ts.map +1 -1
  155. package/dist/utils/portable-aggregations.js +13 -8
  156. package/dist/utils/portable-grains.d.ts +17 -8
  157. package/dist/utils/portable-grains.d.ts.map +1 -1
  158. package/dist/utils/portable-grains.js +26 -11
  159. package/dist/utils/portable-query-calculations.d.ts +14 -0
  160. package/dist/utils/portable-query-calculations.d.ts.map +1 -0
  161. package/dist/utils/portable-query-calculations.js +31 -0
  162. package/dist/utils/portable-semantic-query.d.ts.map +1 -1
  163. package/dist/utils/portable-semantic-query.js +27 -1
  164. package/dist/utils/protocol-contract-3.d.ts +30 -0
  165. package/dist/utils/protocol-contract-3.d.ts.map +1 -0
  166. package/dist/utils/protocol-contract-3.js +93 -0
  167. package/dist/utils/protocol-dataset-query.d.ts +19 -0
  168. package/dist/utils/protocol-dataset-query.d.ts.map +1 -0
  169. package/dist/utils/protocol-dataset-query.js +50 -0
  170. package/dist/utils/protocol-filter-nodes.d.ts +9 -0
  171. package/dist/utils/protocol-filter-nodes.d.ts.map +1 -0
  172. package/dist/utils/protocol-filter-nodes.js +68 -0
  173. package/dist/utils/protocol-metric-capabilities.d.ts.map +1 -1
  174. package/dist/utils/protocol-metric-capabilities.js +2 -1
  175. package/dist/utils/protocol-metric-expressions.d.ts +9 -1
  176. package/dist/utils/protocol-metric-expressions.d.ts.map +1 -1
  177. package/dist/utils/protocol-metric-expressions.js +27 -2
  178. package/dist/utils/protocol-rehydrate-filters.d.ts +8 -1
  179. package/dist/utils/protocol-rehydrate-filters.d.ts.map +1 -1
  180. package/dist/utils/protocol-rehydrate-filters.js +20 -1
  181. package/dist/utils/protocol-rehydrate-time-keys.d.ts +6 -0
  182. package/dist/utils/protocol-rehydrate-time-keys.d.ts.map +1 -0
  183. package/dist/utils/protocol-rehydrate-time-keys.js +7 -0
  184. package/dist/utils/query-calculation-errors.d.ts +6 -0
  185. package/dist/utils/query-calculation-errors.d.ts.map +1 -0
  186. package/dist/utils/query-calculation-errors.js +9 -0
  187. package/dist/utils/query-calculation-formula.d.ts +19 -0
  188. package/dist/utils/query-calculation-formula.d.ts.map +1 -0
  189. package/dist/utils/query-calculation-formula.js +77 -0
  190. package/dist/utils/query-calculation-outputs.d.ts +24 -0
  191. package/dist/utils/query-calculation-outputs.d.ts.map +1 -0
  192. package/dist/utils/query-calculation-outputs.js +72 -0
  193. package/dist/utils/query-calculation-plan.d.ts +67 -0
  194. package/dist/utils/query-calculation-plan.d.ts.map +1 -0
  195. package/dist/utils/query-calculation-plan.js +416 -0
  196. package/dist/utils/query-calculation-types.d.ts +97 -0
  197. package/dist/utils/query-calculation-types.d.ts.map +1 -0
  198. package/dist/utils/query-calculation-types.js +8 -0
  199. package/dist/utils/query-field-references.d.ts.map +1 -1
  200. package/dist/utils/query-field-references.js +3 -2
  201. package/dist/utils/query-filter-errors.d.ts +11 -0
  202. package/dist/utils/query-filter-errors.d.ts.map +1 -0
  203. package/dist/utils/query-filter-errors.js +65 -0
  204. package/dist/utils/query-schema-calculations.d.ts +55 -0
  205. package/dist/utils/query-schema-calculations.d.ts.map +1 -0
  206. package/dist/utils/query-schema-calculations.js +150 -0
  207. package/dist/utils/query-schema-filters.d.ts +47 -0
  208. package/dist/utils/query-schema-filters.d.ts.map +1 -0
  209. package/dist/utils/query-schema-filters.js +132 -0
  210. package/dist/utils/query-timezone.d.ts +6 -3
  211. package/dist/utils/query-timezone.d.ts.map +1 -1
  212. package/dist/utils/query-timezone.js +5 -1
  213. package/dist/utils/relationship-builder-plan.d.ts.map +1 -1
  214. package/dist/utils/relationship-builder-plan.js +2 -1
  215. package/dist/utils/relationship-fields.d.ts.map +1 -1
  216. package/dist/utils/relationship-fields.js +5 -0
  217. package/dist/utils/relationship-measure-sql.d.ts.map +1 -1
  218. package/dist/utils/relationship-measure-sql.js +4 -1
  219. package/dist/utils/relationship-measures.d.ts.map +1 -1
  220. package/dist/utils/relationship-measures.js +2 -1
  221. package/dist/utils/relationship-validation.d.ts +3 -1
  222. package/dist/utils/relationship-validation.d.ts.map +1 -1
  223. package/dist/utils/relationship-validation.js +8 -4
  224. package/dist/utils/relative-date-filters.d.ts +21 -0
  225. package/dist/utils/relative-date-filters.d.ts.map +1 -0
  226. package/dist/utils/relative-date-filters.js +86 -0
  227. package/dist/utils/relative-date-range.d.ts +20 -0
  228. package/dist/utils/relative-date-range.d.ts.map +1 -0
  229. package/dist/utils/relative-date-range.js +75 -0
  230. package/dist/utils/retention-rows.d.ts +9 -0
  231. package/dist/utils/retention-rows.d.ts.map +1 -0
  232. package/dist/utils/retention-rows.js +30 -0
  233. package/dist/utils/retention-sql.d.ts +16 -0
  234. package/dist/utils/retention-sql.d.ts.map +1 -0
  235. package/dist/utils/retention-sql.js +68 -0
  236. package/dist/utils/scoped-dataset-source.d.ts.map +1 -1
  237. package/dist/utils/scoped-dataset-source.js +4 -0
  238. package/dist/utils/segments.d.ts +3 -2
  239. package/dist/utils/segments.d.ts.map +1 -1
  240. package/dist/utils/segments.js +5 -4
  241. package/dist/utils/semantic-query-syntax.d.ts.map +1 -1
  242. package/dist/utils/semantic-query-syntax.js +8 -2
  243. package/dist/utils/sql-dataset-source.d.ts +36 -0
  244. package/dist/utils/sql-dataset-source.d.ts.map +1 -0
  245. package/dist/utils/sql-dataset-source.js +126 -0
  246. package/dist/utils/time-axis-bounds.d.ts +11 -4
  247. package/dist/utils/time-axis-bounds.d.ts.map +1 -1
  248. package/dist/utils/time-axis-bounds.js +14 -6
  249. package/dist/utils/time-measure-axis.d.ts +2 -2
  250. package/dist/utils/time-measure-axis.d.ts.map +1 -1
  251. package/dist/utils/time-measure-axis.js +13 -3
  252. package/dist/utils/time-measure-dataset-sql.d.ts +1 -1
  253. package/dist/utils/time-measure-dataset-sql.d.ts.map +1 -1
  254. package/dist/utils/time-measure-dataset-sql.js +15 -5
  255. package/dist/utils/time-measure-source-sql.d.ts +2 -2
  256. package/dist/utils/time-measure-source-sql.d.ts.map +1 -1
  257. package/dist/utils/time-measure-source-sql.js +7 -8
  258. package/dist/utils/time-query-measures.d.ts +5 -0
  259. package/dist/utils/time-query-measures.d.ts.map +1 -1
  260. package/dist/utils/time-query-measures.js +7 -0
  261. package/dist/utils/unsupported-contract-reasons.d.ts +5 -1
  262. package/dist/utils/unsupported-contract-reasons.d.ts.map +1 -1
  263. package/dist/utils/unsupported-contract-reasons.js +5 -1
  264. package/package.json +3 -3
@@ -3,20 +3,25 @@ import { resolveRelationshipMeasure } from './relationship-measures.js';
3
3
  import { semanticQuerySyntaxErrors } from './semantic-query-syntax.js';
4
4
  import { queryTimezoneErrors } from './query-timezone.js';
5
5
  import { baseMeasureNames } from './dataset-measures.js';
6
- import { validateFilterValue } from '../validation.js';
7
6
  import { unsupportedTimeGrainError } from './dataset-time-grains.js';
8
- import { getRuntimeTenantPredicate, validateTenantRuntime, } from './tenant-runtime.js';
7
+ import { validateTenantRuntime } from './tenant-runtime.js';
9
8
  import { isQualifiedField, resolveQualifiedField, } from './relationship-fields.js';
10
- import { validateQualifiedFilter, validateRelationshipTenantRuntime, } from './relationship-validation.js';
9
+ import { validateRelationshipTenantRuntime } from './relationship-validation.js';
11
10
  import { segmentSelectionErrors } from './segments.js';
12
- import { filterAllowsOperator } from './filter-operator-policy.js';
13
- import { SEMANTIC_FILTER_OPERATORS } from '../constants.js';
14
11
  import { enforcedConstraintErrors } from './enforced-constraints.js';
15
12
  import { analyzeTimeMeasureAxis } from './time-measure-axis.js';
16
13
  import { datasetHavingErrors } from './dataset-having.js';
17
14
  import { datasetOnTimeKey, selectedTimeKeyError } from './dataset-time-keys.js';
18
- import { effectiveFilters } from './effective-filters.js';
15
+ import { queryFilterErrors } from './query-filter-errors.js';
16
+ import { hasQueryCalculations } from './query-calculation-outputs.js';
17
+ import { calculatedDatasetQueryErrors } from './compile-calculated-dataset-query.js';
18
+ import { filterLeafCount, filterTreeErrors } from './filter-tree.js';
19
19
  export function validateDatasetQueryInput(dataset, query, context) {
20
+ // RFC 0026: a calculated query validates as the view and inner query it plans to.
21
+ if (hasQueryCalculations(query)) {
22
+ const { errors } = calculatedDatasetQueryErrors(dataset, query, context);
23
+ return { valid: errors.length === 0, errors };
24
+ }
20
25
  // Validate against the selected time axis, so grain and window checks see it.
21
26
  const timeKeyError = selectedTimeKeyError(dataset, query.timeKey);
22
27
  const ds = timeKeyError ? dataset : datasetOnTimeKey(dataset, query.timeKey);
@@ -34,8 +39,6 @@ export function validateDatasetQueryInput(dataset, query, context) {
34
39
  errors.push(`Output "${name}" cannot be selected as both a dimension and a measure. Select one or give the definitions distinct names.`);
35
40
  }
36
41
  }
37
- const filters = effectiveFilters(ds);
38
- const filterNames = Object.keys(filters);
39
42
  const orderableFields = new Set([
40
43
  ...selectedDimensions,
41
44
  ...selectedMeasures,
@@ -49,7 +52,7 @@ export function validateDatasetQueryInput(dataset, query, context) {
49
52
  if (relationshipTenantError) {
50
53
  errors.push(relationshipTenantError);
51
54
  }
52
- errors.push(...enforcedConstraintErrors(ds, context, query.filters?.length ?? 0));
55
+ errors.push(...enforcedConstraintErrors(ds, context, filterLeafCount(query.filters)));
53
56
  if (selectedDimensions.length === 0 && selectedMeasures.length === 0) {
54
57
  errors.push(`Dataset "${ds.name}" query must select at least one dimension or measure.`);
55
58
  }
@@ -89,42 +92,9 @@ export function validateDatasetQueryInput(dataset, query, context) {
89
92
  }
90
93
  }
91
94
  }
92
- if (query.filters) {
93
- for (const filter of query.filters) {
94
- if (isQualifiedField(filter.field)) {
95
- const filterError = validateQualifiedFilter(ds, filter, context);
96
- if (filterError) {
97
- errors.push(filterError);
98
- }
99
- continue;
100
- }
101
- if (!filterNames.includes(filter.field)) {
102
- errors.push(`Unknown filter fields: ${filter.field}. Available: ${filterNames.join(', ')}`);
103
- continue;
104
- }
105
- const filterDefinition = filters[filter.field];
106
- if (!filterAllowsOperator(filterDefinition, filter.operator)) {
107
- errors.push(`Filter "${filter.field}" does not allow operator "${filter.operator}". Allowed: ${(filterDefinition?.operators ?? SEMANTIC_FILTER_OPERATORS).join(', ')}`);
108
- continue;
109
- }
110
- const resolvedField = filterDefinition.field;
111
- const resolvedDimension = ds.dimensions[resolvedField];
112
- const resolvedColumn = resolvedDimension?.sql
113
- ? undefined
114
- : resolvedDimension?.column ?? resolvedField;
115
- if (getRuntimeTenantPredicate(context) && ds.tenantKey && resolvedColumn === ds.tenantKey) {
116
- errors.push(`Cannot filter on tenant field "${filter.field}" when runtime tenancy enforcement is active.`);
117
- continue;
118
- }
119
- const fieldType = resolvedDimension?.fieldType;
120
- if (!fieldType) {
121
- continue;
122
- }
123
- const filterError = validateFilterValue(filter, fieldType);
124
- if (filterError) {
125
- errors.push(filterError);
126
- }
127
- }
95
+ // A malformed tree is reported once, by the syntax check; its leaves are not read.
96
+ if (query.filters && filterTreeErrors(query.filters).length === 0) {
97
+ errors.push(...queryFilterErrors(ds, query.filters, context));
128
98
  }
129
99
  if (query.orderBy) {
130
100
  const invalid = [];
@@ -148,6 +118,12 @@ export function validateDatasetQueryInput(dataset, query, context) {
148
118
  errors.push(`Unknown orderBy fields: ${invalid.join(', ')}. Available: ${Array.from(orderableFields).join(', ')}`);
149
119
  }
150
120
  }
121
+ if (query.fill !== undefined && typeof query.fill !== 'boolean') {
122
+ errors.push('Invalid fill: expected true or false.');
123
+ }
124
+ else if (query.fill === true && !query.by) {
125
+ errors.push('"fill" needs a "by" grain: it fills the periods of the time series.');
126
+ }
151
127
  if (query.by && !ds.timeKey) {
152
128
  errors.push(`Cannot use "by" grain — dataset "${ds.name}" has no timeKey.`);
153
129
  }
@@ -170,8 +146,10 @@ export function validateDatasetQueryInput(dataset, query, context) {
170
146
  errors.push(`Too many measures: ${query.measures.length} (max ${ds.limits.maxMeasures})`);
171
147
  }
172
148
  errors.push(...datasetHavingErrors(ds, query, selectedMeasures));
173
- if (ds.limits?.maxFilters && query.filters && query.filters.length > ds.limits.maxFilters) {
174
- errors.push(`Too many filters: ${query.filters.length} (max ${ds.limits.maxFilters})`);
149
+ // RFC 0029: the budget counts comparisons; and/or/not groups cost nothing.
150
+ const filterCount = filterLeafCount(query.filters);
151
+ if (ds.limits?.maxFilters && filterCount > ds.limits.maxFilters) {
152
+ errors.push(`Too many filters: ${filterCount} (max ${ds.limits.maxFilters})`);
175
153
  }
176
154
  if (ds.limits?.maxResultSize && query.limit != null && query.limit > ds.limits.maxResultSize) {
177
155
  errors.push(`Too many results requested: ${query.limit} (max ${ds.limits.maxResultSize})`);
@@ -6,7 +6,7 @@ import type { RelationshipBuilderContext } from './relationship-builder-plan.js'
6
6
  * declares `rowResolution`. Every builder-path read of a dataset source goes
7
7
  * through here so no query can skip row-version resolution.
8
8
  */
9
- export declare function datasetSourceBuilder(builderFactory: Pick<QueryBuilderFactoryLike, 'table'>, ds: Pick<AnyDatasetInstance, 'name' | 'source' | 'rowResolution'>): QueryBuilderLike;
9
+ export declare function datasetSourceBuilder(builderFactory: Pick<QueryBuilderFactoryLike, 'table'>, ds: Pick<AnyDatasetInstance, 'name' | 'source' | 'rowResolution' | 'sqlSource'>): QueryBuilderLike;
10
10
  /**
11
11
  * A filter moved to PREWHERE runs before `FINAL` and can match an older version
12
12
  * of a row. The server default forbids that; pinning it also covers profiles
@@ -21,7 +21,7 @@ export declare const FINAL_SAFETY_SETTINGS: {
21
21
  * relationship target it actually joins. Unused relationships don't count, so
22
22
  * a plain query never carries the pin.
23
23
  */
24
- export declare function queryReadsFinal(ds: Pick<AnyDatasetInstance, 'rowResolution'>, joinCtx: Pick<RelationshipBuilderContext, 'joins'> | undefined): boolean;
24
+ export declare function queryReadsFinal(ds: Pick<AnyDatasetInstance, 'rowResolution' | 'sqlSource'>, joinCtx: Pick<RelationshipBuilderContext, 'joins'> | undefined): boolean;
25
25
  /**
26
26
  * The statement with `FINAL_SAFETY_SETTINGS` in its own SQL, for paths that run
27
27
  * rendered SQL (`rawQuery`), where builder settings don't travel.
@@ -1 +1 @@
1
- {"version":3,"file":"dataset-source.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAC9F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAEjF;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,cAAc,EAAE,IAAI,CAAC,uBAAuB,EAAE,OAAO,CAAC,EACtD,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,MAAM,GAAG,QAAQ,GAAG,eAAe,CAAC,GAChE,gBAAgB,CAgBlB;AAED;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB;;CAAqD,CAAC;AAExF;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,CAAC,EAC7C,OAAO,EAAE,IAAI,CAAC,0BAA0B,EAAE,OAAO,CAAC,GAAG,SAAS,GAC7D,OAAO,CAET;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,GAAG,CAAC,CAI/F;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,CAAC,GAC5C;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAA;CAAE,GAAG,SAAS,CAM9C"}
1
+ {"version":3,"file":"dataset-source.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-source.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAC9F,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAGjF;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,cAAc,EAAE,IAAI,CAAC,uBAAuB,EAAE,OAAO,CAAC,EACtD,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,MAAM,GAAG,QAAQ,GAAG,eAAe,GAAG,WAAW,CAAC,GAC9E,gBAAgB,CAqBlB;AAED;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB;;CAAqD,CAAC;AAExF;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,GAAG,WAAW,CAAC,EAC3D,OAAO,EAAE,IAAI,CAAC,0BAA0B,EAAE,OAAO,CAAC,GAAG,SAAS,GAC7D,OAAO,CAGT;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,GAAG,CAAC,CAI/F;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,EAAE,EAAE,IAAI,CAAC,kBAAkB,EAAE,eAAe,CAAC,GAC5C;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAA;CAAE,GAAG,SAAS,CAM9C"}
@@ -1,9 +1,15 @@
1
+ import { sqlSourceRelation } from './sql-dataset-source.js';
1
2
  /**
2
3
  * The dataset's source table as a builder, read with `FINAL` when the dataset
3
4
  * declares `rowResolution`. Every builder-path read of a dataset source goes
4
5
  * through here so no query can skip row-version resolution.
5
6
  */
6
7
  export function datasetSourceBuilder(builderFactory, ds) {
8
+ // RFC 0028: a SQL source is a derived table; FINAL, if any, is inside it.
9
+ if (ds.sqlSource) {
10
+ const derived = builderFactory.table(sqlSourceRelation(ds));
11
+ return ds.sqlSource.readsFinal && derived.settings ? derived.settings(FINAL_SAFETY_SETTINGS) : derived;
12
+ }
7
13
  const qb = builderFactory.table(ds.source);
8
14
  if (!ds.rowResolution) {
9
15
  return qb;
@@ -31,7 +37,8 @@ export const FINAL_SAFETY_SETTINGS = { optimize_move_to_prewhere_if_final: 0 };
31
37
  * a plain query never carries the pin.
32
38
  */
33
39
  export function queryReadsFinal(ds, joinCtx) {
34
- return Boolean(ds.rowResolution) || Boolean(joinCtx?.joins.some(join => join.final));
40
+ return Boolean(ds.rowResolution) || Boolean(ds.sqlSource?.readsFinal)
41
+ || Boolean(joinCtx?.joins.some(join => join.final));
35
42
  }
36
43
  /**
37
44
  * The statement with `FINAL_SAFETY_SETTINGS` in its own SQL, for paths that run
@@ -1 +1 @@
1
- {"version":3,"file":"dataset-validation.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACpB,MAAM,aAAa,CAAC;AAarB,wBAAgB,kBAAkB,CAChC,EAAE,EAAE,kBAAkB,EACtB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,eAAe,EACrB,OAAO,CAAC,EAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAE,GACvC,IAAI,CAiEN;AAED,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,kBAAkB,EACtB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,mBAAmB,CAAC,MAAM,CAAC,GAClC,IAAI,CAmBN"}
1
+ {"version":3,"file":"dataset-validation.d.ts","sourceRoot":"","sources":["../../src/utils/dataset-validation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EAClB,mBAAmB,EACpB,MAAM,aAAa,CAAC;AAarB,wBAAgB,kBAAkB,CAChC,EAAE,EAAE,kBAAkB,EACtB,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,eAAe,EACrB,OAAO,CAAC,EAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAE,GACvC,IAAI,CAiEN;AAED,wBAAgB,qBAAqB,CACnC,EAAE,EAAE,kBAAkB,EACtB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,mBAAmB,CAAC,MAAM,CAAC,GAClC,IAAI,CAmBN"}
@@ -1,3 +1,4 @@
1
+ import { filterLeaves } from './filter-tree.js';
1
2
  import { validateFilterValue } from '../validation.js';
2
3
  import { validatePercentileLevel } from '../measure.js';
3
4
  import { assertAggregateStateFunction } from './aggregate-state-functions.js';
@@ -37,7 +38,7 @@ export function validateBaseMetric(ds, metricName, spec, options) {
37
38
  !NUMERIC_FIELD_TYPES.has(dimension.fieldType)) {
38
39
  throw new Error(`Invalid metric "${metricName}": ${spec.aggregation}() requires a numeric dimension, but "${spec.field}" is ${dimension.fieldType}.`);
39
40
  }
40
- for (const filter of spec.filters ?? []) {
41
+ for (const filter of filterLeaves(spec.filters)) {
41
42
  const filterDefinition = ds.filters[filter.field];
42
43
  const resolvedField = filterDefinition?.field ?? filter.field;
43
44
  const fieldType = ds.dimensions[resolvedField]?.fieldType;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Selection-only dimension rewrites for RFC 0026 `other`.
3
+ *
4
+ * `other` regroups one dimension as itself or a remainder label. Only the
5
+ * grouped output reads the rewritten expression: filters, segments, measure
6
+ * filters and measures over the same column keep reading source values,
7
+ * because they resolve the dimension through `resolveDimensionExpression`.
8
+ *
9
+ * The rewrite travels on the dataset view under a symbol key, which object
10
+ * spread copies, so views derived from it (a time-key rebase) keep it.
11
+ */
12
+ import type { AnyDatasetInstance } from '../types.js';
13
+ type SelectionRewrite = (expression: string) => string;
14
+ /** A view of `ds` whose `dimension`, when selected, reads `rewrite(expression)`. */
15
+ export declare function withDimensionSelectionRewrite<TDataset extends AnyDatasetInstance>(ds: TDataset, dimension: string, rewrite: SelectionRewrite): TDataset;
16
+ /** The expression a selected (grouped) dimension reads, given its source expression. */
17
+ export declare function rewriteSelectedDimension(ds: AnyDatasetInstance, dimension: string, expression: string): string;
18
+ export {};
19
+ //# sourceMappingURL=dimension-selection-overrides.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dimension-selection-overrides.d.ts","sourceRoot":"","sources":["../../src/utils/dimension-selection-overrides.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAItD,KAAK,gBAAgB,GAAG,CAAC,UAAU,EAAE,MAAM,KAAK,MAAM,CAAC;AAGvD,oFAAoF;AACpF,wBAAgB,6BAA6B,CAAC,QAAQ,SAAS,kBAAkB,EAC/E,EAAE,EAAE,QAAQ,EACZ,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,gBAAgB,GACxB,QAAQ,CAGV;AAED,wFAAwF;AACxF,wBAAgB,wBAAwB,CAAC,EAAE,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,MAAM,CAG9G"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Selection-only dimension rewrites for RFC 0026 `other`.
3
+ *
4
+ * `other` regroups one dimension as itself or a remainder label. Only the
5
+ * grouped output reads the rewritten expression: filters, segments, measure
6
+ * filters and measures over the same column keep reading source values,
7
+ * because they resolve the dimension through `resolveDimensionExpression`.
8
+ *
9
+ * The rewrite travels on the dataset view under a symbol key, which object
10
+ * spread copies, so views derived from it (a time-key rebase) keep it.
11
+ */
12
+ const SELECTION_OVERRIDES = Symbol('hypequery.datasets.selectionOverrides');
13
+ /** A view of `ds` whose `dimension`, when selected, reads `rewrite(expression)`. */
14
+ export function withDimensionSelectionRewrite(ds, dimension, rewrite) {
15
+ const current = ds[SELECTION_OVERRIDES] ?? {};
16
+ return { ...ds, [SELECTION_OVERRIDES]: Object.freeze({ ...current, [dimension]: rewrite }) };
17
+ }
18
+ /** The expression a selected (grouped) dimension reads, given its source expression. */
19
+ export function rewriteSelectedDimension(ds, dimension, expression) {
20
+ const rewrite = ds[SELECTION_OVERRIDES]?.[dimension];
21
+ return rewrite === undefined ? expression : rewrite(expression);
22
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Keep the first `limit` breakdown groups of an aggregated relation (RFC
3
+ * 0027): ranked by `sizeColumn` summed over the group's rows (descending),
4
+ * then by the breakdown values (ascending, nulls last). Without a breakdown
5
+ * the relation is returned in `orderBy` order.
6
+ */
7
+ export declare function rankedBreakdownSql(options: {
8
+ readonly relation: string;
9
+ readonly breakdown: readonly string[];
10
+ readonly sizeColumn: string;
11
+ readonly limit: number;
12
+ /** Final ordering terms; `_hq_rank` is available to them. */
13
+ readonly orderBy: readonly string[];
14
+ }): string;
15
+ //# sourceMappingURL=event-breakdown-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-breakdown-sql.d.ts","sourceRoot":"","sources":["../../src/utils/event-breakdown-sql.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE;IAC1C,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,6DAA6D;IAC7D,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;CACrC,GAAG,MAAM,CAUT"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Keep the first `limit` breakdown groups of an aggregated relation (RFC
3
+ * 0027): ranked by `sizeColumn` summed over the group's rows (descending),
4
+ * then by the breakdown values (ascending, nulls last). Without a breakdown
5
+ * the relation is returned in `orderBy` order.
6
+ */
7
+ export function rankedBreakdownSql(options) {
8
+ const { relation, breakdown, sizeColumn, limit, orderBy } = options;
9
+ if (breakdown.length === 0) {
10
+ return `SELECT * FROM ${relation}${orderBy.length ? ` ORDER BY ${orderBy.join(', ')}` : ''}`;
11
+ }
12
+ const partition = breakdown.join(', ');
13
+ const valueOrder = breakdown.map(alias => `${alias} ASC NULLS LAST`).join(', ');
14
+ const sized = `SELECT *, sum(${sizeColumn}) OVER (PARTITION BY ${partition}) AS _hq_group_size FROM ${relation}`;
15
+ const ranked = `SELECT *, dense_rank() OVER (ORDER BY _hq_group_size DESC, ${valueOrder}) AS _hq_rank FROM (${sized})`;
16
+ return `SELECT * FROM (${ranked}) WHERE _hq_rank <= ${limit} ORDER BY ${orderBy.join(', ')}`;
17
+ }
@@ -0,0 +1,18 @@
1
+ import type { DatasetFilterNode, MetricFilter } from '../types.js';
2
+ import type { QueryTimePredicate } from './query-timezone.js';
3
+ import type { StatementParameters } from './statement-parameters.js';
4
+ /**
5
+ * One RFC 0027 condition as a SQL boolean over an already-projected column.
6
+ * Every caller value is bound as a parameter, never inlined.
7
+ */
8
+ export declare function eventConditionSql(column: string, filter: MetricFilter, statement: StatementParameters): string;
9
+ /**
10
+ * AND-combined conditions as a non-null 0/1 flag: a NULL comparison is a
11
+ * non-match, so array and aggregate functions never see a Nullable flag.
12
+ *
13
+ * `predicatesFor` turns one condition into the predicates that test it, the
14
+ * way a caller filter on the same field is applied: a timestamp instant is
15
+ * compared in UTC, and a mixed range splits into one predicate per kind.
16
+ */
17
+ export declare function eventConditionFlagSql(conditions: readonly DatasetFilterNode[], predicatesFor: (condition: MetricFilter) => readonly QueryTimePredicate[], statement: StatementParameters): string;
18
+ //# sourceMappingURL=event-condition-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-condition-sql.d.ts","sourceRoot":"","sources":["../../src/utils/event-condition-sql.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEnE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAErE;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,SAAS,EAAE,mBAAmB,GAAG,MAAM,CA8B9G;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,UAAU,EAAE,SAAS,iBAAiB,EAAE,EACxC,aAAa,EAAE,CAAC,SAAS,EAAE,YAAY,KAAK,SAAS,kBAAkB,EAAE,EACzE,SAAS,EAAE,mBAAmB,GAC7B,MAAM,CAgBR"}
@@ -0,0 +1,63 @@
1
+ import { isFilterGroup } from './filter-tree.js';
2
+ /**
3
+ * One RFC 0027 condition as a SQL boolean over an already-projected column.
4
+ * Every caller value is bound as a parameter, never inlined.
5
+ */
6
+ export function eventConditionSql(column, filter, statement) {
7
+ const bind = (value) => statement.bind(value);
8
+ switch (filter.operator) {
9
+ case 'eq': return `${column} = ${bind(filter.value)}`;
10
+ case 'neq': return `${column} != ${bind(filter.value)}`;
11
+ case 'gt': return `${column} > ${bind(filter.value)}`;
12
+ case 'gte': return `${column} >= ${bind(filter.value)}`;
13
+ case 'lt': return `${column} < ${bind(filter.value)}`;
14
+ case 'lte': return `${column} <= ${bind(filter.value)}`;
15
+ case 'like': return `${column} LIKE ${bind(filter.value)}`;
16
+ case 'isNull': return `${column} IS NULL`;
17
+ case 'isNotNull': return `${column} IS NOT NULL`;
18
+ case 'in':
19
+ case 'notIn': {
20
+ if (!Array.isArray(filter.value) || filter.value.length === 0) {
21
+ throw new Error(`"${filter.operator}" conditions require a non-empty array.`);
22
+ }
23
+ const values = filter.value.map(bind).join(', ');
24
+ return `${column} ${filter.operator === 'in' ? 'IN' : 'NOT IN'} (${values})`;
25
+ }
26
+ case 'between': {
27
+ if (!Array.isArray(filter.value) || filter.value.length !== 2) {
28
+ throw new Error('"between" conditions require a two-item array.');
29
+ }
30
+ return `${column} BETWEEN ${bind(filter.value[0])} AND ${bind(filter.value[1])}`;
31
+ }
32
+ default:
33
+ // `inDateRange` applies only to the time axis, which conditions can't use.
34
+ throw new Error(`Operator "${filter.operator}" can't be used in an event condition.`);
35
+ }
36
+ }
37
+ /**
38
+ * AND-combined conditions as a non-null 0/1 flag: a NULL comparison is a
39
+ * non-match, so array and aggregate functions never see a Nullable flag.
40
+ *
41
+ * `predicatesFor` turns one condition into the predicates that test it, the
42
+ * way a caller filter on the same field is applied: a timestamp instant is
43
+ * compared in UTC, and a mixed range splits into one predicate per kind.
44
+ */
45
+ export function eventConditionFlagSql(conditions, predicatesFor, statement) {
46
+ const leaf = (condition) => predicatesFor(condition).map(predicate => {
47
+ const filter = { field: condition.field, operator: predicate.operator, value: predicate.value };
48
+ return `(${eventConditionSql(predicate.expression, filter, statement)})`;
49
+ }).join(' AND ');
50
+ // RFC 0029 groups render as written. SQL three-valued logic makes a NULL
51
+ // field fail a comparison and its negation alike, and the outer ifNull
52
+ // reads what is left NULL as "no match".
53
+ const node = (item) => {
54
+ if (!isFilterGroup(item))
55
+ return `(${leaf(item)})`;
56
+ const group = item;
57
+ if (group.not !== undefined)
58
+ return `(NOT ${node(group.not)})`;
59
+ const items = (group.and ?? group.or ?? []).map(node);
60
+ return `(${items.join(group.and ? ' AND ' : ' OR ')})`;
61
+ };
62
+ return `toUInt8(ifNull(${conditions.map(node).join(' AND ')}, 0))`;
63
+ }
@@ -0,0 +1,8 @@
1
+ import type { EventOperationSpec } from './event-operation-spec.js';
2
+ /**
3
+ * The RFC 0027 shape rules the protocol validator applies, for specs built
4
+ * directly in code: bounds, unique names, and breakdown names that can't
5
+ * collide with an output column (which would overwrite the breakdown value).
6
+ */
7
+ export declare function eventOperationShapeErrors(spec: EventOperationSpec): string[];
8
+ //# sourceMappingURL=event-operation-shape.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-operation-shape.d.ts","sourceRoot":"","sources":["../../src/utils/event-operation-shape.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,kBAAkB,EAA6B,MAAM,2BAA2B,CAAC;AAI/F;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,kBAAkB,GAAG,MAAM,EAAE,CAuB5E"}
@@ -0,0 +1,66 @@
1
+ import { PROTOCOL_EVENT_OPERATION_LIMITS as LIMITS, PROTOCOL_FUNNEL_COLUMNS, PROTOCOL_RETENTION_COLUMNS, } from '@hypequery/protocol';
2
+ const COHORT_GRAINS = new Set(['day', 'week', 'month']);
3
+ /**
4
+ * The RFC 0027 shape rules the protocol validator applies, for specs built
5
+ * directly in code: bounds, unique names, and breakdown names that can't
6
+ * collide with an output column (which would overwrite the breakdown value).
7
+ */
8
+ export function eventOperationShapeErrors(spec) {
9
+ const errors = [];
10
+ const reserved = spec.kind === 'retention' ? PROTOCOL_RETENTION_COLUMNS : PROTOCOL_FUNNEL_COLUMNS;
11
+ if (spec.breakdown.length > LIMITS.maxBreakdown) {
12
+ errors.push(`At most ${LIMITS.maxBreakdown} breakdown dimensions may be used.`);
13
+ }
14
+ if (new Set(spec.breakdown).size !== spec.breakdown.length)
15
+ errors.push('Breakdown dimensions must be unique.');
16
+ for (const name of spec.breakdown) {
17
+ if (reserved.has(name))
18
+ errors.push(`Breakdown dimension "${name}" collides with the "${name}" output column.`);
19
+ }
20
+ if (!Number.isSafeInteger(spec.breakdownLimit) || spec.breakdownLimit < 1 || spec.breakdownLimit > LIMITS.maxBreakdownLimit) {
21
+ errors.push(`breakdownLimit must be an integer from 1 to ${LIMITS.maxBreakdownLimit}.`);
22
+ }
23
+ // Each kind checks only its own fields, so a new kind can't read another's.
24
+ switch (spec.kind) {
25
+ case 'funnel':
26
+ errors.push(...funnelShapeErrors(spec));
27
+ break;
28
+ case 'retention':
29
+ errors.push(...retentionShapeErrors(spec));
30
+ break;
31
+ }
32
+ return errors;
33
+ }
34
+ function conditionErrors(name, where) {
35
+ return where.length < 1 || where.length > LIMITS.maxConditions
36
+ ? [`${name} needs 1 to ${LIMITS.maxConditions} conditions.`]
37
+ : [];
38
+ }
39
+ function funnelShapeErrors(spec) {
40
+ const errors = [];
41
+ if (spec.steps.length < LIMITS.minSteps || spec.steps.length > LIMITS.maxSteps) {
42
+ errors.push(`A funnel has ${LIMITS.minSteps} to ${LIMITS.maxSteps} steps.`);
43
+ }
44
+ if (new Set(spec.steps.map(step => step.name)).size !== spec.steps.length)
45
+ errors.push('Step names must be unique.');
46
+ for (const step of spec.steps)
47
+ errors.push(...conditionErrors(`Step "${step.name}"`, step.where));
48
+ if (!Number.isSafeInteger(spec.windowMs) || spec.windowMs < 1 || spec.windowMs > LIMITS.maxWindowMilliseconds) {
49
+ errors.push('The funnel window must be a whole number of milliseconds, at most 365 days.');
50
+ }
51
+ if (spec.by !== undefined && !COHORT_GRAINS.has(spec.by))
52
+ errors.push(`Cohort grain "${spec.by}" is not day, week or month.`);
53
+ return errors;
54
+ }
55
+ function retentionShapeErrors(spec) {
56
+ const errors = [
57
+ ...conditionErrors('The start condition', spec.start),
58
+ ...conditionErrors('The return condition', spec.return),
59
+ ];
60
+ if (!Number.isSafeInteger(spec.periods) || spec.periods < 1 || spec.periods > LIMITS.maxPeriods) {
61
+ errors.push(`periods must be an integer from 1 to ${LIMITS.maxPeriods}.`);
62
+ }
63
+ if (!COHORT_GRAINS.has(spec.grain))
64
+ errors.push(`Cohort grain "${spec.grain}" is not day, week or month.`);
65
+ return errors;
66
+ }
@@ -0,0 +1,43 @@
1
+ import type { ProtocolEventOperation, ProtocolExpression } from '@hypequery/protocol';
2
+ import type { AnyDatasetInstance, DatasetFilterNode, MetricFilter } from '../types.js';
3
+ export type EventCohortGrain = 'day' | 'week' | 'month';
4
+ /** An RFC 0027 funnel in the dataset layer's vocabulary. */
5
+ export interface FunnelSpec {
6
+ readonly kind: 'funnel';
7
+ readonly entity: string;
8
+ /** Each step's conditions: comparisons or and/or/not groups (RFC 0029), ANDed. */
9
+ readonly steps: readonly {
10
+ readonly name: string;
11
+ readonly where: readonly DatasetFilterNode[];
12
+ }[];
13
+ readonly windowMs: number;
14
+ readonly order: 'strict' | 'any';
15
+ /** Caller filters, ANDed; groups and `inDateRange` as a dataset query takes them. */
16
+ readonly filters: readonly DatasetFilterNode[];
17
+ readonly breakdown: readonly string[];
18
+ readonly breakdownLimit: number;
19
+ readonly by?: EventCohortGrain;
20
+ readonly timezone?: string;
21
+ }
22
+ /** An RFC 0027 retention operation in the dataset layer's vocabulary. */
23
+ export interface RetentionSpec {
24
+ readonly kind: 'retention';
25
+ readonly entity: string;
26
+ /** What starts a cohort and what counts as a return: comparisons or groups (RFC 0029), ANDed. */
27
+ readonly start: readonly DatasetFilterNode[];
28
+ readonly return: readonly DatasetFilterNode[];
29
+ readonly grain: EventCohortGrain;
30
+ readonly periods: number;
31
+ readonly filters: readonly DatasetFilterNode[];
32
+ readonly breakdown: readonly string[];
33
+ readonly breakdownLimit: number;
34
+ readonly timezone?: string;
35
+ }
36
+ export type EventOperationSpec = FunnelSpec | RetentionSpec;
37
+ /** Every condition list the operation tests events against. */
38
+ export declare function eventOperationConditions(spec: EventOperationSpec): readonly DatasetFilterNode[];
39
+ /** Enforced constraints (RFC 0019) as the dataset layer's trusted filters: comparisons only. */
40
+ export declare function eventConstraintFilters(expressions: readonly ProtocolExpression[]): MetricFilter[];
41
+ /** Resolve a validated protocol operation against the dataset that serves it. */
42
+ export declare function eventOperationSpec(operation: ProtocolEventOperation, dataset: AnyDatasetInstance): EventOperationSpec;
43
+ //# sourceMappingURL=event-operation-spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-operation-spec.d.ts","sourceRoot":"","sources":["../../src/utils/event-operation-spec.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAEtF,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAKvF,MAAM,MAAM,gBAAgB,GAAG,KAAK,GAAG,MAAM,GAAG,OAAO,CAAC;AAExD,4DAA4D;AAC5D,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,kFAAkF;IAClF,QAAQ,CAAC,KAAK,EAAE,SAAS;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,CAAA;KAAE,EAAE,CAAC;IACnG,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,QAAQ,GAAG,KAAK,CAAC;IACjC,qFAAqF;IACrF,QAAQ,CAAC,OAAO,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC/C,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,EAAE,CAAC,EAAE,gBAAgB,CAAC;IAC/B,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,yEAAyE;AACzE,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,iGAAiG;IACjG,QAAQ,CAAC,KAAK,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC7C,QAAQ,CAAC,MAAM,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC9C,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC/C,QAAQ,CAAC,SAAS,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,aAAa,CAAC;AAE5D,+DAA+D;AAC/D,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,kBAAkB,GAAG,SAAS,iBAAiB,EAAE,CAE/F;AAwBD,gGAAgG;AAChG,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,SAAS,kBAAkB,EAAE,GAAG,YAAY,EAAE,CAEjG;AAED,iFAAiF;AACjF,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,sBAAsB,EAAE,OAAO,EAAE,kBAAkB,GAAG,kBAAkB,CAsCrH"}
@@ -0,0 +1,68 @@
1
+ import { PROTOCOL_EVENT_OPERATION_LIMITS, parseProtocolEventWindow } from '@hypequery/protocol';
2
+ import { PortableExecutionUnsupportedError } from '../portable-execution-errors.js';
3
+ import { rehydrateMeasureFilter } from './protocol-rehydrate-filters.js';
4
+ import { UNSUPPORTED_CONTRACT_REASONS } from './unsupported-contract-reasons.js';
5
+ /** Every condition list the operation tests events against. */
6
+ export function eventOperationConditions(spec) {
7
+ return spec.kind === 'retention' ? [...spec.start, ...spec.return] : spec.steps.flatMap(step => step.where);
8
+ }
9
+ function comparison(expression, path) {
10
+ return rehydrateMeasureFilter(expression, () => new PortableExecutionUnsupportedError(`${path} is not a field/operator/value comparison, so it cannot be planned.`, { reason: UNSUPPORTED_CONTRACT_REASONS.queryFilterNotComparison }));
11
+ }
12
+ /** A predicate as a filter node: `logical` becomes an and/or/not group (RFC 0029). */
13
+ function filterNode(expression, path) {
14
+ if (expression.kind !== 'logical')
15
+ return comparison(expression, path);
16
+ if (expression.operator === 'not')
17
+ return { not: filterNode(expression.operand, `${path}.operand`) };
18
+ const items = expression.operands.map((operand, index) => filterNode(operand, `${path}.operands[${index}]`));
19
+ return expression.operator === 'and' ? { and: items } : { or: items };
20
+ }
21
+ function filters(expressions, path) {
22
+ return expressions.map((expression, index) => filterNode(expression, `${path}[${index}]`));
23
+ }
24
+ /** Enforced constraints (RFC 0019) as the dataset layer's trusted filters: comparisons only. */
25
+ export function eventConstraintFilters(expressions) {
26
+ return expressions.map((expression, index) => comparison(expression, `constraints[${index}]`));
27
+ }
28
+ /** Resolve a validated protocol operation against the dataset that serves it. */
29
+ export function eventOperationSpec(operation, dataset) {
30
+ if (!dataset.events) {
31
+ throw new Error(`Dataset "${dataset.name}" does not declare events, so it has no ${operation.kind}.`);
32
+ }
33
+ const common = {
34
+ entity: String(operation.entity ?? dataset.events.entity),
35
+ filters: filters(operation.filters, 'filters'),
36
+ breakdown: (operation.breakdown ?? []).map(String),
37
+ breakdownLimit: operation.breakdownLimit ?? PROTOCOL_EVENT_OPERATION_LIMITS.defaultBreakdownLimit,
38
+ ...(operation.timezone === undefined ? {} : { timezone: operation.timezone }),
39
+ };
40
+ if (operation.kind === 'retention') {
41
+ return {
42
+ kind: 'retention',
43
+ ...common,
44
+ start: filters(operation.start.where, 'start.where'),
45
+ return: filters(operation.return.where, 'return.where'),
46
+ grain: operation.grain,
47
+ periods: operation.periods,
48
+ };
49
+ }
50
+ const window = parseProtocolEventWindow(operation.window);
51
+ if (!window)
52
+ throw new Error(`Invalid funnel window "${operation.window}".`);
53
+ return {
54
+ kind: 'funnel',
55
+ entity: String(operation.entity ?? dataset.events.entity),
56
+ steps: operation.steps.map((step, index) => ({
57
+ name: String(step.name),
58
+ where: filters(step.where, `steps[${index}].where`),
59
+ })),
60
+ windowMs: window.milliseconds,
61
+ order: operation.order ?? 'strict',
62
+ filters: filters(operation.filters, 'filters'),
63
+ breakdown: (operation.breakdown ?? []).map(String),
64
+ breakdownLimit: operation.breakdownLimit ?? PROTOCOL_EVENT_OPERATION_LIMITS.defaultBreakdownLimit,
65
+ ...(operation.by === undefined ? {} : { by: operation.by }),
66
+ ...(operation.timezone === undefined ? {} : { timezone: operation.timezone }),
67
+ };
68
+ }
@@ -0,0 +1,4 @@
1
+ import type { TimeAxisRange } from './time-axis-bounds.js';
2
+ /** The range's span in days, with both bounds read in the operation's zone (RFC 0025). */
3
+ export declare function eventRangeSpanDays(range: TimeAxisRange, timezone: string | undefined): number;
4
+ //# sourceMappingURL=event-range-span.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-range-span.d.ts","sourceRoot":"","sources":["../../src/utils/event-range-span.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAqB3D,0FAA0F;AAC1F,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAG7F"}
@@ -0,0 +1,22 @@
1
+ const DAY_MS = 86_400_000;
2
+ /** How far `timezone`'s wall clock is ahead of UTC at instant `at`. */
3
+ function zoneOffset(at, timezone) {
4
+ const parts = Object.fromEntries(new Intl.DateTimeFormat('en-GB', {
5
+ timeZone: timezone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit',
6
+ hour: '2-digit', minute: '2-digit', second: '2-digit',
7
+ }).formatToParts(new Date(at)).filter(part => part.type !== 'literal').map(part => [part.type, Number(part.value)]));
8
+ const wall = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
9
+ return wall - Math.floor(at / 1000) * 1000;
10
+ }
11
+ /** A bound as an instant: an offset-free bound is a wall clock in the query zone, as the scan reads it. */
12
+ function boundInstant(bound, timezone) {
13
+ if (bound.hasOffset || timezone === 'UTC')
14
+ return bound.milliseconds;
15
+ // Two passes settle a wall clock next to a DST change.
16
+ return bound.milliseconds - zoneOffset(bound.milliseconds - zoneOffset(bound.milliseconds, timezone), timezone);
17
+ }
18
+ /** The range's span in days, with both bounds read in the operation's zone (RFC 0025). */
19
+ export function eventRangeSpanDays(range, timezone) {
20
+ const zone = timezone ?? 'UTC';
21
+ return (boundInstant(range.end, zone) - boundInstant(range.start, zone)) / DAY_MS;
22
+ }
@@ -0,0 +1,8 @@
1
+ export type EventResultValue = string | number | boolean | null;
2
+ export type EventResultRow = Readonly<Record<string, EventResultValue>>;
3
+ /** A ClickHouse count arrives as a number or, for 64-bit types, a quoted string. */
4
+ export declare function countValue(value: unknown): number;
5
+ export declare function ratio(numerator: number, denominator: number): number | null;
6
+ /** A result cell: scalars pass through; anything else becomes its string form. */
7
+ export declare function scalar(value: unknown): EventResultValue;
8
+ //# sourceMappingURL=event-result-values.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-result-values.d.ts","sourceRoot":"","sources":["../../src/utils/event-result-values.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;AAChE,MAAM,MAAM,cAAc,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAExE,oFAAoF;AACpF,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAMjD;AAED,wBAAgB,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE3E;AAED,kFAAkF;AAClF,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,gBAAgB,CAKvD"}