@ahoo-wang/wow-client 10.0.0-beta.2 → 10.0.0-beta.4

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 (59) hide show
  1. package/dist/commands.cjs +1 -1
  2. package/dist/commands.cjs.map +1 -1
  3. package/dist/commands.d.cts +15 -3
  4. package/dist/commands.d.ts +15 -3
  5. package/dist/commands.es.js +46 -46
  6. package/dist/commands.es.js.map +1 -1
  7. package/dist/dsl/aggregation/admit.cjs +1 -1
  8. package/dist/dsl/aggregation/admit.cjs.map +1 -1
  9. package/dist/dsl/aggregation/admit.es.js +96 -96
  10. package/dist/dsl/aggregation/builders.cjs +1 -1
  11. package/dist/dsl/aggregation/builders.cjs.map +1 -1
  12. package/dist/dsl/aggregation/builders.es.js +32 -32
  13. package/dist/dsl/aggregation/derived.cjs +1 -1
  14. package/dist/dsl/aggregation/derived.cjs.map +1 -1
  15. package/dist/dsl/aggregation/derived.es.js +11 -11
  16. package/dist/dsl/aggregation/groups.cjs +1 -1
  17. package/dist/dsl/aggregation/groups.cjs.map +1 -1
  18. package/dist/dsl/aggregation/groups.es.js +22 -22
  19. package/dist/dsl/aggregation/having.cjs +1 -1
  20. package/dist/dsl/aggregation/having.cjs.map +1 -1
  21. package/dist/dsl/aggregation/having.es.js +11 -11
  22. package/dist/dsl/filter/expressionFilter.cjs +1 -1
  23. package/dist/dsl/filter/expressionFilter.cjs.map +1 -1
  24. package/dist/dsl/filter/expressionFilter.es.js +7 -7
  25. package/dist/dsl/filter/fieldFilters.cjs +1 -1
  26. package/dist/dsl/filter/fieldFilters.cjs.map +1 -1
  27. package/dist/dsl/filter/fieldFilters.es.js +61 -61
  28. package/dist/dsl/filter/logicalFilters.cjs +1 -1
  29. package/dist/dsl/filter/logicalFilters.cjs.map +1 -1
  30. package/dist/dsl/filter/logicalFilters.es.js +19 -19
  31. package/dist/dsl/filter/metadataFilters.cjs +1 -1
  32. package/dist/dsl/filter/metadataFilters.cjs.map +1 -1
  33. package/dist/dsl/filter/metadataFilters.es.js +31 -31
  34. package/dist/dsl/filter/scope.cjs +1 -1
  35. package/dist/dsl/filter/scope.cjs.map +1 -1
  36. package/dist/dsl/filter/scope.es.js +18 -18
  37. package/dist/dsl/filter/searchFilter.cjs +1 -1
  38. package/dist/dsl/filter/searchFilter.cjs.map +1 -1
  39. package/dist/dsl/filter/searchFilter.es.js +6 -6
  40. package/dist/dsl/filter/timeFilters.cjs +1 -1
  41. package/dist/dsl/filter/timeFilters.cjs.map +1 -1
  42. package/dist/dsl/filter/timeFilters.es.js +47 -47
  43. package/dist/dsl/filter/validate.cjs +1 -1
  44. package/dist/dsl/filter/validate.cjs.map +1 -1
  45. package/dist/dsl/filter/validate.es.js +8 -8
  46. package/dist/dsl/queryable.cjs +1 -1
  47. package/dist/dsl/queryable.cjs.map +1 -1
  48. package/dist/dsl/queryable.es.js +8 -8
  49. package/dist/dsl.cjs +1 -1
  50. package/dist/dsl.es.js +12 -12
  51. package/dist/index.cjs +1 -1
  52. package/dist/index.es.js +12 -12
  53. package/dist/manifest.cjs +1 -1
  54. package/dist/manifest.cjs.map +1 -1
  55. package/dist/manifest.es.js +11 -11
  56. package/dist/state.cjs +1 -1
  57. package/dist/state.cjs.map +1 -1
  58. package/dist/state.es.js +22 -22
  59. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"admit.cjs","names":["FilterOperator","AggregationMetricType","AggregationGroupType","constantName","AggregationGroupScope","AGGREGATION_LIMITS","DerivedExpressionType","HavingExpressionType","effectiveSort","require_operator","require_types","require_expressionTrees","require_constantName","require_groups","require_metrics","require_derived","require_having","require_sort","requireAtMost","items","max","name","noun","validateMetricFilter","filter","validateExpressions","metrics","metric","groupBy","group","NON_NUMERIC","validateDerivedMetrics","declared","derived","counter","validateDerivedExpression","pending","depth","expression","reference","nonNumeric","requireWindowMetric","target","window","alias","requireValidHavingMetric","metricAliases","anyAliases","edgeAliases","validateHaving","having","operand","validateSort","sort","fields","entry","aliases","field","requireRootGroupsFirst","root","query","order","firstElement","admitAggregationQuery","elements"],"sources":["../../../src/dsl/aggregation/admit.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { constantName } from '../constantName.js';\nimport { FilterOperator, type FilterExpression } from '../filter/index.js';\nimport type { FieldSort } from '../sort.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { effectiveSort } from './sort.js';\nimport {\n DerivedExpressionType,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type DerivedWindow,\n} from './derived.js';\nimport {\n AggregationGroupScope,\n AggregationGroupType,\n type AggregationGroup,\n} from './groups.js';\nimport { HavingExpressionType, type HavingExpression } from './having.js';\nimport { AggregationMetricType, type AggregationMetric } from './metrics.js';\nimport { AGGREGATION_LIMITS, type AggregationQuery } from './types.js';\n\n// Internal: the rules `aggregation.query()` checks across the parts of a\n// query. index.ts does not re-export this file.\n\nfunction requireAtMost(\n name: string,\n noun: string,\n items: readonly unknown[],\n max: number,\n): void {\n if (items.length > max) {\n throw new TypeError(`${name} must contain at most ${max} ${noun}.`);\n }\n}\n\n/**\n * Refuses the filters a metric cannot carry, whatever the aggregate holds.\n *\n * A metric filter is a whole-value predicate on one record — MongoDB turns it\n * into a `$cond` guard and Elasticsearch into a filter aggregation — and\n * element matching and full text have no whole-value reading. Both backends\n * refuse them before touching a schema, so the shape alone settles it. What a\n * schema would add, refusing an array-valued field, stays on the server.\n */\nfunction validateMetricFilter(filter: FilterExpression): void {\n switch (filter.op) {\n case FilterOperator.SEARCH:\n throw new TypeError(\n 'Aggregation metric filters do not support search filters.',\n );\n case FilterOperator.ELEMENT_MATCH:\n throw new TypeError(\n 'Aggregation metric filters do not support [ELEMENT_MATCH].',\n );\n case FilterOperator.AND:\n case FilterOperator.OR:\n case FilterOperator.NOR:\n filter.operands.forEach(validateMetricFilter);\n break;\n }\n}\n\n/**\n * Walks the arithmetic of every metric that carries an expression, as one\n * budget, and of each expression group on its own, as Wow does.\n */\nfunction validateExpressions(\n metrics: readonly AggregationMetric[],\n groupBy: readonly AggregationGroup[],\n): void {\n requireValidExpressionTrees(\n metrics.flatMap(metric =>\n metric.type === AggregationMetricType.NUMERIC ||\n metric.type === AggregationMetricType.DISTINCT_COUNT ||\n metric.type === AggregationMetricType.PERCENTILE\n ? [metric.expression]\n : [],\n ),\n );\n groupBy.forEach(group => {\n if (\n group.type !== AggregationGroupType.TERMS &&\n group.type !== AggregationGroupType.HISTOGRAM\n )\n return;\n if ((group.field === undefined) === (group.expression === undefined)) {\n throw new TypeError(\n `${constantName(group.type)} group requires exactly one of field and expression.`,\n );\n }\n if (group.expression) requireValidExpressionTrees([group.expression]);\n if (\n group.type === AggregationGroupType.TERMS &&\n group.missingKey !== undefined &&\n group.expression\n ) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n if (group.scope === AggregationGroupScope.ROOT && group.expression) {\n throw new TypeError(\n `${constantName(group.type)} with a ROOT scope requires a field input.`,\n );\n }\n });\n}\n\n/** The metric types whose value is not a number: derived and having refuse them. */\nconst NON_NUMERIC: ReadonlySet<string> = new Set([\n AggregationMetricType.ANY,\n AggregationMetricType.FIRST,\n AggregationMetricType.LAST,\n]);\n\n/**\n * Admits the derived metrics against what was declared before each of them.\n *\n * Derived arithmetic runs after the aggregation, over values the query has\n * already produced, so a reference may only name a metric declared earlier —\n * that is what makes the list evaluable in one pass — and never an `ANY`,\n * `FIRST` or `LAST` metric, whose value is a field's value rather than a\n * number.\n */\nfunction validateDerivedMetrics(metrics: readonly AggregationMetric[]): void {\n // Each earlier alias, with its type when that is not a number.\n const declared = new Map<string, string | undefined>();\n const derived = new Set<string>();\n const counter = { nodes: 0, windows: 0 };\n metrics.forEach(metric => {\n if (metric.type === AggregationMetricType.DERIVED) {\n validateDerivedExpression(metric, declared, derived, counter);\n derived.add(metric.alias);\n }\n declared.set(\n metric.alias,\n NON_NUMERIC.has(metric.type) ? metric.type : undefined,\n );\n });\n}\n\nfunction validateDerivedExpression(\n metric: DerivedAggregationMetric,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n counter: { nodes: number; windows: number },\n): void {\n const pending: { expression: DerivedExpression; depth: number }[] = [\n { expression: metric.expression, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `derived expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n counter.nodes++;\n if (counter.nodes > AGGREGATION_LIMITS.MAX_EXPRESSION_NODES) {\n throw new TypeError(\n `derived expressions must contain at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`,\n );\n }\n switch (expression.type) {\n case DerivedExpressionType.METRIC_REF: {\n const reference = expression.metric;\n if (!declared.has(reference)) {\n throw new TypeError(\n `derived metric [${metric.alias}] must reference a metric declared before it, but was [${reference}].`,\n );\n }\n const nonNumeric = declared.get(reference);\n if (nonNumeric !== undefined) {\n throw new TypeError(\n `derived metric [${metric.alias}] cannot reference ${constantName(nonNumeric)} metric [${reference}].`,\n );\n }\n break;\n }\n case DerivedExpressionType.CONSTANT:\n if (!Number.isFinite(expression.value)) {\n throw new TypeError('derived constant must be finite.');\n }\n break;\n case DerivedExpressionType.BINARY:\n pending.push({ expression: expression.left, depth: depth + 1 });\n pending.push({ expression: expression.right, depth: depth + 1 });\n break;\n case DerivedExpressionType.TOTAL:\n case DerivedExpressionType.RUNNING:\n case DerivedExpressionType.PREVIOUS:\n case DerivedExpressionType.RANK:\n counter.windows++;\n if (counter.windows > AGGREGATION_LIMITS.MAX_WINDOWS) {\n throw new TypeError(\n `an aggregation must compute at most ${AGGREGATION_LIMITS.MAX_WINDOWS} windows.`,\n );\n }\n requireWindowMetric(metric.alias, expression, declared, derived);\n break;\n default:\n throw new TypeError(\n `Unsupported derived expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\n/**\n * A window reads a non-derived numeric metric declared before the derived\n * one; the rest of its rules (which metrics add up, which groups it names)\n * the server checks against the whole query.\n */\nfunction requireWindowMetric(\n alias: string,\n window: DerivedWindow,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n): void {\n const target = window.metric;\n if (!declared.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a metric declared before it, but was [${target}].`,\n );\n }\n if (declared.get(target) !== undefined || derived.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a non-derived numeric metric, but was [${target}].`,\n );\n }\n}\n\nfunction requireValidHavingMetric(\n metric: string,\n metricAliases: ReadonlySet<string>,\n anyAliases: ReadonlySet<string>,\n edgeAliases: ReadonlySet<string>,\n): void {\n if (!metricAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] must reference a declared metric alias.`,\n );\n }\n if (anyAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference ANY metric.`,\n );\n }\n if (edgeAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference FIRST or LAST metric.`,\n );\n }\n}\n\n/**\n * `having` filters the grouped rows, so it needs rows to filter: a query with\n * no `groupBy` produces one row and has nothing to select from.\n */\nfunction validateHaving(\n having: HavingExpression | undefined,\n groupBy: readonly AggregationGroup[],\n metrics: readonly AggregationMetric[],\n): void {\n if (having === undefined) return;\n if (groupBy.length === 0) {\n throw new TypeError('having requires at least one groupBy.');\n }\n const metricAliases = new Set(metrics.map(metric => metric.alias));\n const anyAliases = new Set(\n metrics\n .filter(metric => metric.type === AggregationMetricType.ANY)\n .map(metric => metric.alias),\n );\n const edgeAliases = new Set(\n metrics\n .filter(\n metric =>\n metric.type === AggregationMetricType.FIRST ||\n metric.type === AggregationMetricType.LAST,\n )\n .map(metric => metric.alias),\n );\n\n const pending: { expression: HavingExpression; depth: number }[] = [\n { expression: having, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `having expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n switch (expression.type) {\n case HavingExpressionType.CONDITION:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (!Number.isFinite(expression.value)) {\n throw new TypeError(\n `having condition [${expression.metric}] value must be finite.`,\n );\n }\n break;\n case HavingExpressionType.BETWEEN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (\n !Number.isFinite(expression.lower) ||\n !Number.isFinite(expression.upper)\n ) {\n throw new TypeError(\n `having between [${expression.metric}] bounds must be finite.`,\n );\n }\n if (expression.lower > expression.upper) {\n throw new TypeError(\n `having between [${expression.metric}] lower bound must not exceed upper bound.`,\n );\n }\n break;\n case HavingExpressionType.IN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (expression.values.length === 0) {\n throw new TypeError(\n `having in [${expression.metric}] values must not be empty.`,\n );\n }\n if (!expression.values.every(Number.isFinite)) {\n throw new TypeError(\n `having in [${expression.metric}] values must be finite.`,\n );\n }\n break;\n case HavingExpressionType.IS_NULL:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n break;\n case HavingExpressionType.AND:\n case HavingExpressionType.OR:\n if (expression.operands.length === 0) {\n throw new TypeError(\n `having ${constantName(expression.type)} operands must not be empty.`,\n );\n }\n expression.operands.forEach(operand =>\n pending.push({ expression: operand, depth: depth + 1 }),\n );\n break;\n default:\n throw new TypeError(\n `Unsupported having expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\nfunction validateSort(\n sort: readonly FieldSort[],\n groupBy: readonly AggregationGroup[],\n aliases: readonly string[],\n): void {\n requireAtMost('sort', 'fields', sort, AGGREGATION_LIMITS.MAX_SORT_FIELDS);\n if (groupBy.length === 0 && sort.length > 0) {\n throw new TypeError('sort requires at least one groupBy.');\n }\n const fields = sort.map(entry => entry.field);\n if (new Set(fields).size !== fields.length) {\n throw new TypeError('sort fields must be unique.');\n }\n if (!fields.every(field => aliases.includes(field))) {\n throw new TypeError('sort fields must reference aggregation aliases.');\n }\n requireAtMost(\n 'effective sort',\n 'fields',\n effectiveSort({ groupBy: [...groupBy], sort: [...sort] }),\n AGGREGATION_LIMITS.MAX_SORT_FIELDS,\n );\n}\n\n/**\n * With elements, the groups of a ROOT scope lead the effective sort: a storage\n * reads the root records' keys before the keys of their elements.\n */\nfunction requireRootGroupsFirst(\n query: Pick<AggregationQuery<string, string>, 'groupBy' | 'sort'>,\n): void {\n const root = new Map(\n (query.groupBy ?? []).map(group => [\n group.alias,\n group.scope === AggregationGroupScope.ROOT,\n ]),\n );\n const order = effectiveSort(query).flatMap(entry =>\n root.has(entry.field) ? [root.get(entry.field)] : [],\n );\n const firstElement = order.indexOf(false);\n if (firstElement >= 0 && order.slice(firstElement).includes(true)) {\n throw new TypeError(\n 'groups with a ROOT scope must sort before the element groups.',\n );\n }\n}\n\n/**\n * Admits a whole aggregation query against the rules Wow enforces on arrival;\n * {@link aggregation.query} is its public face.\n */\nexport function admitAggregationQuery<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n>(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n const elements = query.elements ?? [];\n const groupBy = query.groupBy ?? [];\n const metrics = query.metrics;\n const sort = query.sort ?? [];\n\n requireAtMost('elements', 'paths', elements, AGGREGATION_LIMITS.MAX_ELEMENTS);\n requireAtMost(\n 'groupBy',\n 'dimensions',\n groupBy,\n AGGREGATION_LIMITS.MAX_GROUPS,\n );\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new TypeError('metrics must not be empty.');\n }\n requireAtMost('metrics', 'entries', metrics, AGGREGATION_LIMITS.MAX_METRICS);\n if (query.limit !== undefined) {\n if (\n !Number.isInteger(query.limit) ||\n query.limit < 1 ||\n query.limit > AGGREGATION_LIMITS.MAX_LIMIT\n ) {\n throw new TypeError(\n `limit must be between 1 and ${AGGREGATION_LIMITS.MAX_LIMIT}.`,\n );\n }\n }\n\n validateExpressions(metrics, groupBy);\n validateDerivedMetrics(metrics);\n validateHaving(query.having, groupBy, metrics);\n metrics.forEach(metric => {\n if ('filter' in metric && metric.filter)\n validateMetricFilter(metric.filter);\n });\n\n // A dense DATE_HISTOGRAM fills in the buckets its range implies, and a\n // dense DATE_PART every key of its part's domain, rather than only the ones\n // with rows; a second dimension would multiply that filling out across\n // every one of its own keys.\n groupBy.forEach(group => {\n if (\n (group.type === AggregationGroupType.DATE_HISTOGRAM ||\n group.type === AggregationGroupType.DATE_PART) &&\n group.dense === true &&\n groupBy.length !== 1\n ) {\n throw new TypeError(\n `dense requires ${constantName(group.type)} to be the only groupBy.`,\n );\n }\n });\n\n const aliases = [\n ...groupBy.map(group => group.alias),\n ...metrics.map(metric => metric.alias),\n ];\n if (new Set(aliases).size !== aliases.length) {\n throw new TypeError('aggregation aliases must be unique.');\n }\n validateSort(sort, groupBy, aliases);\n if (elements.length > 0) requireRootGroupsFirst(query);\n\n return {\n ...query,\n metrics: [...metrics] as typeof query.metrics,\n };\n}\n"],"mappings":"A,yQAoCA,SAASkB,EACP,EACA,EACA,EACA,EACM,CACN,GAAIC,EAAM,OAASC,EACjB,MAAU,UAAU,GAAGC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C2B,EAAM,QAAU,IAChBD,EAAQ,SAAW,EAEnB,MAAU,UACR,kBAAkBzB,EAAAA,aAAa0B,EAAM,IAAI,EAAE,yBAC7C,CAEJ,CAAC,EAED,IAAM2B,EAAU,CACd,GAAG5B,EAAQ,IAAI,GAASC,EAAM,KAAK,EACnC,GAAGH,EAAQ,IAAI,GAAUC,EAAO,KAAK,CACvC,EACA,GAAI,IAAI,IAAI6B,CAAO,CAAC,CAAC,OAASA,EAAQ,OACpC,MAAU,UAAU,qCAAqC,EAK3D,OAHAJ,EAAaC,EAAMzB,EAAS4B,CAAO,EAC/BQ,EAAS,OAAS,GAAGN,EAAuBE,CAAK,EAE9C,CACL,GAAGA,EACH,QAAS,CAAC,GAAGlC,CAAO,CACtB,CACF,C"}
1
+ {"version":3,"file":"admit.cjs","names":["FilterOperator","AggregationMetricType","AggregationGroupType","constantName","AggregationGroupScope","AGGREGATION_LIMITS","DerivedExpressionType","HavingExpressionType","effectiveSort","require_constantName","require_operator","require_expressionTrees","require_sort","require_derived","require_groups","require_having","require_metrics","require_types","requireAtMost","items","max","name","noun","validateMetricFilter","filter","validateExpressions","metrics","metric","groupBy","group","NON_NUMERIC","validateDerivedMetrics","declared","derived","counter","validateDerivedExpression","pending","depth","expression","reference","nonNumeric","requireWindowMetric","target","window","alias","requireValidHavingMetric","metricAliases","anyAliases","edgeAliases","validateHaving","having","operand","validateSort","sort","fields","entry","aliases","field","requireRootGroupsFirst","root","query","order","firstElement","admitAggregationQuery","elements"],"sources":["../../../src/dsl/aggregation/admit.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { constantName } from '../constantName.js';\nimport { FilterOperator, type FilterExpression } from '../filter/index.js';\nimport type { FieldSort } from '../sort.js';\nimport { requireValidExpressionTrees } from './expressionTrees.js';\nimport { effectiveSort } from './sort.js';\nimport {\n DerivedExpressionType,\n type DerivedAggregationMetric,\n type DerivedExpression,\n type DerivedWindow,\n} from './derived.js';\nimport {\n AggregationGroupScope,\n AggregationGroupType,\n type AggregationGroup,\n} from './groups.js';\nimport { HavingExpressionType, type HavingExpression } from './having.js';\nimport { AggregationMetricType, type AggregationMetric } from './metrics.js';\nimport { AGGREGATION_LIMITS, type AggregationQuery } from './types.js';\n\n// Internal: the rules `aggregation.query()` checks across the parts of a\n// query. index.ts does not re-export this file.\n\nfunction requireAtMost(\n name: string,\n noun: string,\n items: readonly unknown[],\n max: number,\n): void {\n if (items.length > max) {\n throw new TypeError(`${name} must contain at most ${max} ${noun}.`);\n }\n}\n\n/**\n * Refuses the filters a metric cannot carry, whatever the aggregate holds.\n *\n * A metric filter is a whole-value predicate on one record — MongoDB turns it\n * into a `$cond` guard and Elasticsearch into a filter aggregation — and\n * element matching and full text have no whole-value reading. Both backends\n * refuse them before touching a schema, so the shape alone settles it. What a\n * schema would add, refusing an array-valued field, stays on the server.\n */\nfunction validateMetricFilter(filter: FilterExpression): void {\n switch (filter.op) {\n case FilterOperator.SEARCH:\n throw new TypeError(\n 'Aggregation metric filters do not support search filters.',\n );\n case FilterOperator.ELEMENT_MATCH:\n throw new TypeError(\n 'Aggregation metric filters do not support [ELEMENT_MATCH].',\n );\n case FilterOperator.AND:\n case FilterOperator.OR:\n case FilterOperator.NOR:\n filter.operands.forEach(validateMetricFilter);\n break;\n }\n}\n\n/**\n * Walks the arithmetic of every metric that carries an expression, as one\n * budget, and of each expression group on its own, as Wow does.\n */\nfunction validateExpressions(\n metrics: readonly AggregationMetric[],\n groupBy: readonly AggregationGroup[],\n): void {\n requireValidExpressionTrees(\n metrics.flatMap(metric =>\n metric.type === AggregationMetricType.NUMERIC ||\n metric.type === AggregationMetricType.DISTINCT_COUNT ||\n metric.type === AggregationMetricType.PERCENTILE\n ? [metric.expression]\n : [],\n ),\n );\n groupBy.forEach(group => {\n if (\n group.type !== AggregationGroupType.TERMS &&\n group.type !== AggregationGroupType.HISTOGRAM\n )\n return;\n if ((group.field === undefined) === (group.expression === undefined)) {\n throw new TypeError(\n `${constantName(group.type)} group requires exactly one of field and expression.`,\n );\n }\n if (group.expression) requireValidExpressionTrees([group.expression]);\n if (\n group.type === AggregationGroupType.TERMS &&\n group.missingKey !== undefined &&\n group.expression\n ) {\n throw new TypeError('terms missingKey requires a field input.');\n }\n if (group.scope === AggregationGroupScope.ROOT && group.expression) {\n throw new TypeError(\n `${constantName(group.type)} with a ROOT scope requires a field input.`,\n );\n }\n });\n}\n\n/** The metric types whose value is not a number: derived and having refuse them. */\nconst NON_NUMERIC: ReadonlySet<string> = new Set([\n AggregationMetricType.ANY,\n AggregationMetricType.FIRST,\n AggregationMetricType.LAST,\n]);\n\n/**\n * Admits the derived metrics against what was declared before each of them.\n *\n * Derived arithmetic runs after the aggregation, over values the query has\n * already produced, so a reference may only name a metric declared earlier —\n * that is what makes the list evaluable in one pass — and never an `ANY`,\n * `FIRST` or `LAST` metric, whose value is a field's value rather than a\n * number.\n */\nfunction validateDerivedMetrics(metrics: readonly AggregationMetric[]): void {\n // Each earlier alias, with its type when that is not a number.\n const declared = new Map<string, string | undefined>();\n const derived = new Set<string>();\n const counter = { nodes: 0, windows: 0 };\n metrics.forEach(metric => {\n if (metric.type === AggregationMetricType.DERIVED) {\n validateDerivedExpression(metric, declared, derived, counter);\n derived.add(metric.alias);\n }\n declared.set(\n metric.alias,\n NON_NUMERIC.has(metric.type) ? metric.type : undefined,\n );\n });\n}\n\nfunction validateDerivedExpression(\n metric: DerivedAggregationMetric,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n counter: { nodes: number; windows: number },\n): void {\n const pending: { expression: DerivedExpression; depth: number }[] = [\n { expression: metric.expression, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `derived expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n counter.nodes++;\n if (counter.nodes > AGGREGATION_LIMITS.MAX_EXPRESSION_NODES) {\n throw new TypeError(\n `derived expressions must contain at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_NODES} nodes.`,\n );\n }\n switch (expression.type) {\n case DerivedExpressionType.METRIC_REF: {\n const reference = expression.metric;\n if (!declared.has(reference)) {\n throw new TypeError(\n `derived metric [${metric.alias}] must reference a metric declared before it, but was [${reference}].`,\n );\n }\n const nonNumeric = declared.get(reference);\n if (nonNumeric !== undefined) {\n throw new TypeError(\n `derived metric [${metric.alias}] cannot reference ${constantName(nonNumeric)} metric [${reference}].`,\n );\n }\n break;\n }\n case DerivedExpressionType.CONSTANT:\n if (!Number.isFinite(expression.value)) {\n throw new TypeError('derived constant must be finite.');\n }\n break;\n case DerivedExpressionType.BINARY:\n pending.push({ expression: expression.left, depth: depth + 1 });\n pending.push({ expression: expression.right, depth: depth + 1 });\n break;\n case DerivedExpressionType.TOTAL:\n case DerivedExpressionType.RUNNING:\n case DerivedExpressionType.PREVIOUS:\n case DerivedExpressionType.RANK:\n counter.windows++;\n if (counter.windows > AGGREGATION_LIMITS.MAX_WINDOWS) {\n throw new TypeError(\n `an aggregation must compute at most ${AGGREGATION_LIMITS.MAX_WINDOWS} windows.`,\n );\n }\n requireWindowMetric(metric.alias, expression, declared, derived);\n break;\n default:\n throw new TypeError(\n `Unsupported derived expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\n/**\n * A window reads a non-derived numeric metric declared before the derived\n * one; the rest of its rules (which metrics add up, which groups it names)\n * the server checks against the whole query.\n */\nfunction requireWindowMetric(\n alias: string,\n window: DerivedWindow,\n declared: ReadonlyMap<string, string | undefined>,\n derived: ReadonlySet<string>,\n): void {\n const target = window.metric;\n if (!declared.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a metric declared before it, but was [${target}].`,\n );\n }\n if (declared.get(target) !== undefined || derived.has(target)) {\n throw new TypeError(\n `${constantName(window.type)} window of derived metric [${alias}] must read a non-derived numeric metric, but was [${target}].`,\n );\n }\n}\n\nfunction requireValidHavingMetric(\n metric: string,\n metricAliases: ReadonlySet<string>,\n anyAliases: ReadonlySet<string>,\n edgeAliases: ReadonlySet<string>,\n): void {\n if (!metricAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] must reference a declared metric alias.`,\n );\n }\n if (anyAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference ANY metric.`,\n );\n }\n if (edgeAliases.has(metric)) {\n throw new TypeError(\n `having condition [${metric}] cannot reference FIRST or LAST metric.`,\n );\n }\n}\n\n/**\n * `having` filters the grouped rows, so it needs rows to filter: a query with\n * no `groupBy` produces one row and has nothing to select from.\n */\nfunction validateHaving(\n having: HavingExpression | undefined,\n groupBy: readonly AggregationGroup[],\n metrics: readonly AggregationMetric[],\n): void {\n if (having === undefined) return;\n if (groupBy.length === 0) {\n throw new TypeError('having requires at least one groupBy.');\n }\n const metricAliases = new Set(metrics.map(metric => metric.alias));\n const anyAliases = new Set(\n metrics\n .filter(metric => metric.type === AggregationMetricType.ANY)\n .map(metric => metric.alias),\n );\n const edgeAliases = new Set(\n metrics\n .filter(\n metric =>\n metric.type === AggregationMetricType.FIRST ||\n metric.type === AggregationMetricType.LAST,\n )\n .map(metric => metric.alias),\n );\n\n const pending: { expression: HavingExpression; depth: number }[] = [\n { expression: having, depth: 1 },\n ];\n while (pending.length > 0) {\n const { expression, depth } = pending.pop()!;\n if (depth > AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH) {\n throw new TypeError(\n `having expression depth must be at most ${AGGREGATION_LIMITS.MAX_EXPRESSION_DEPTH}.`,\n );\n }\n switch (expression.type) {\n case HavingExpressionType.CONDITION:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (!Number.isFinite(expression.value)) {\n throw new TypeError(\n `having condition [${expression.metric}] value must be finite.`,\n );\n }\n break;\n case HavingExpressionType.BETWEEN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (\n !Number.isFinite(expression.lower) ||\n !Number.isFinite(expression.upper)\n ) {\n throw new TypeError(\n `having between [${expression.metric}] bounds must be finite.`,\n );\n }\n if (expression.lower > expression.upper) {\n throw new TypeError(\n `having between [${expression.metric}] lower bound must not exceed upper bound.`,\n );\n }\n break;\n case HavingExpressionType.IN:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n if (expression.values.length === 0) {\n throw new TypeError(\n `having in [${expression.metric}] values must not be empty.`,\n );\n }\n if (!expression.values.every(Number.isFinite)) {\n throw new TypeError(\n `having in [${expression.metric}] values must be finite.`,\n );\n }\n break;\n case HavingExpressionType.IS_NULL:\n requireValidHavingMetric(\n expression.metric,\n metricAliases,\n anyAliases,\n edgeAliases,\n );\n break;\n case HavingExpressionType.AND:\n case HavingExpressionType.OR:\n if (expression.operands.length === 0) {\n throw new TypeError(\n `having ${constantName(expression.type)} operands must not be empty.`,\n );\n }\n expression.operands.forEach(operand =>\n pending.push({ expression: operand, depth: depth + 1 }),\n );\n break;\n default:\n throw new TypeError(\n `Unsupported having expression: ${String((expression as { type: unknown }).type)}.`,\n );\n }\n }\n}\n\nfunction validateSort(\n sort: readonly FieldSort[],\n groupBy: readonly AggregationGroup[],\n aliases: readonly string[],\n): void {\n requireAtMost('sort', 'fields', sort, AGGREGATION_LIMITS.MAX_SORT_FIELDS);\n if (groupBy.length === 0 && sort.length > 0) {\n throw new TypeError('sort requires at least one groupBy.');\n }\n const fields = sort.map(entry => entry.field);\n if (new Set(fields).size !== fields.length) {\n throw new TypeError('sort fields must be unique.');\n }\n if (!fields.every(field => aliases.includes(field))) {\n throw new TypeError('sort fields must reference aggregation aliases.');\n }\n requireAtMost(\n 'effective sort',\n 'fields',\n effectiveSort({ groupBy: [...groupBy], sort: [...sort] }),\n AGGREGATION_LIMITS.MAX_SORT_FIELDS,\n );\n}\n\n/**\n * With elements, the groups of a ROOT scope lead the effective sort: a storage\n * reads the root records' keys before the keys of their elements.\n */\nfunction requireRootGroupsFirst(\n query: Pick<AggregationQuery<string, string>, 'groupBy' | 'sort'>,\n): void {\n const root = new Map(\n (query.groupBy ?? []).map(group => [\n group.alias,\n group.scope === AggregationGroupScope.ROOT,\n ]),\n );\n const order = effectiveSort(query).flatMap(entry =>\n root.has(entry.field) ? [root.get(entry.field)] : [],\n );\n const firstElement = order.indexOf(false);\n if (firstElement >= 0 && order.slice(firstElement).includes(true)) {\n throw new TypeError(\n 'groups with a ROOT scope must sort before the element groups.',\n );\n }\n}\n\n/**\n * Admits a whole aggregation query against the rules Wow enforces on arrival;\n * {@link aggregation.query} is its public face.\n */\nexport function admitAggregationQuery<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n>(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n const elements = query.elements ?? [];\n const groupBy = query.groupBy ?? [];\n const metrics = query.metrics;\n const sort = query.sort ?? [];\n\n requireAtMost('elements', 'paths', elements, AGGREGATION_LIMITS.MAX_ELEMENTS);\n requireAtMost(\n 'groupBy',\n 'dimensions',\n groupBy,\n AGGREGATION_LIMITS.MAX_GROUPS,\n );\n if (!Array.isArray(metrics) || metrics.length === 0) {\n throw new TypeError('metrics must not be empty.');\n }\n requireAtMost('metrics', 'entries', metrics, AGGREGATION_LIMITS.MAX_METRICS);\n if (query.limit !== undefined) {\n if (\n !Number.isInteger(query.limit) ||\n query.limit < 1 ||\n query.limit > AGGREGATION_LIMITS.MAX_LIMIT\n ) {\n throw new TypeError(\n `limit must be between 1 and ${AGGREGATION_LIMITS.MAX_LIMIT}.`,\n );\n }\n }\n\n validateExpressions(metrics, groupBy);\n validateDerivedMetrics(metrics);\n validateHaving(query.having, groupBy, metrics);\n metrics.forEach(metric => {\n if ('filter' in metric && metric.filter)\n validateMetricFilter(metric.filter);\n });\n\n // A dense DATE_HISTOGRAM fills in the buckets its range implies, and a\n // dense DATE_PART every key of its part's domain, rather than only the ones\n // with rows; a second dimension would multiply that filling out across\n // every one of its own keys.\n groupBy.forEach(group => {\n if (\n (group.type === AggregationGroupType.DATE_HISTOGRAM ||\n group.type === AggregationGroupType.DATE_PART) &&\n group.dense === true &&\n groupBy.length !== 1\n ) {\n throw new TypeError(\n `dense requires ${constantName(group.type)} to be the only groupBy.`,\n );\n }\n });\n\n const aliases = [\n ...groupBy.map(group => group.alias),\n ...metrics.map(metric => metric.alias),\n ];\n if (new Set(aliases).size !== aliases.length) {\n throw new TypeError('aggregation aliases must be unique.');\n }\n validateSort(sort, groupBy, aliases);\n if (elements.length > 0) requireRootGroupsFirst(query);\n\n return {\n ...query,\n metrics: [...metrics] as typeof query.metrics,\n };\n}\n"],"mappings":"A,yQAoCA,SAASkB,EACP,EACA,EACA,EACA,EACM,CACN,GAAIC,EAAM,OAASC,EACjB,MAAU,UAAU,GAAGC,EAAK,wBAAwBD,EAAI,GAAGE,EAAK,EAAE,CAEtE,CAWA,SAASC,EAAqB,EAAgC,CAC5D,OAAQC,EAAO,GAAf,CACE,KAAKxB,EAAAA,eAAe,OAClB,MAAU,UACR,2DACF,EACF,KAAKA,EAAAA,eAAe,cAClB,MAAU,UACR,4DACF,EACF,KAAKA,EAAAA,eAAe,IACpB,KAAKA,EAAAA,eAAe,GACpB,KAAKA,EAAAA,eAAe,IAClBwB,EAAO,SAAS,QAAQD,CAAoB,CAEhD,CACF,CAMA,SAASE,EACP,EACA,EACM,CACNd,EAAA,4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,EAC/BQ,EAAS,OAAS,GAAGN,EAAuBE,CAAK,EAE9C,CACL,GAAGA,EACH,QAAS,CAAC,GAAGlC,CAAO,CACtB,CACF,C"}
@@ -1,38 +1,38 @@
1
- import { FilterOperator as e } from "../filter/operator.es.js";
2
- import { AGGREGATION_LIMITS as t } from "./types.es.js";
1
+ import { constantName as e } from "../constantName.es.js";
2
+ import { FilterOperator as t } from "../filter/operator.es.js";
3
3
  import { requireValidExpressionTrees as n } from "./expressionTrees.es.js";
4
- import { constantName as r } from "../constantName.es.js";
5
- import { AggregationGroupScope as i, AggregationGroupType as a } from "./groups.es.js";
6
- import { AggregationMetricType as o } from "./metrics.es.js";
7
- import { DerivedExpressionType as s } from "./derived.es.js";
8
- import { HavingExpressionType as c } from "./having.es.js";
9
- import { effectiveSort as l } from "./sort.es.js";
4
+ import { effectiveSort as r } from "./sort.es.js";
5
+ import { DerivedExpressionType as i } from "./derived.es.js";
6
+ import { AggregationGroupScope as a, AggregationGroupType as o } from "./groups.es.js";
7
+ import { HavingExpressionType as s } from "./having.es.js";
8
+ import { AggregationMetricType as c } from "./metrics.es.js";
9
+ import { AGGREGATION_LIMITS as l } from "./types.es.js";
10
10
  // src/dsl/aggregation/admit.ts
11
11
  function u(e, t, n, r) {
12
12
  if (n.length > r) throw TypeError(`${e} must contain at most ${r} ${t}.`);
13
13
  }
14
- function d(t) {
15
- switch (t.op) {
16
- case e.SEARCH: throw TypeError("Aggregation metric filters do not support search filters.");
17
- case e.ELEMENT_MATCH: throw TypeError("Aggregation metric filters do not support [ELEMENT_MATCH].");
18
- case e.AND:
19
- case e.OR:
20
- case e.NOR: t.operands.forEach(d);
14
+ function d(e) {
15
+ switch (e.op) {
16
+ case t.SEARCH: throw TypeError("Aggregation metric filters do not support search filters.");
17
+ case t.ELEMENT_MATCH: throw TypeError("Aggregation metric filters do not support [ELEMENT_MATCH].");
18
+ case t.AND:
19
+ case t.OR:
20
+ case t.NOR: e.operands.forEach(d);
21
21
  }
22
22
  }
23
- function f(e, t) {
24
- n(e.flatMap((e) => e.type === o.NUMERIC || e.type === o.DISTINCT_COUNT || e.type === o.PERCENTILE ? [e.expression] : [])), t.forEach((e) => {
25
- if (e.type === a.TERMS || e.type === a.HISTOGRAM) {
26
- if (e.field === void 0 == (e.expression === void 0)) throw TypeError(`${r(e.type)} group requires exactly one of field and expression.`);
27
- if (e.expression && n([e.expression]), e.type === a.TERMS && e.missingKey !== void 0 && e.expression) throw TypeError("terms missingKey requires a field input.");
28
- if (e.scope === i.ROOT && e.expression) throw TypeError(`${r(e.type)} with a ROOT scope requires a field input.`);
23
+ function f(t, r) {
24
+ n(t.flatMap((e) => e.type === c.NUMERIC || e.type === c.DISTINCT_COUNT || e.type === c.PERCENTILE ? [e.expression] : [])), r.forEach((t) => {
25
+ if (t.type === o.TERMS || t.type === o.HISTOGRAM) {
26
+ if (t.field === void 0 == (t.expression === void 0)) throw TypeError(`${e(t.type)} group requires exactly one of field and expression.`);
27
+ if (t.expression && n([t.expression]), t.type === o.TERMS && t.missingKey !== void 0 && t.expression) throw TypeError("terms missingKey requires a field input.");
28
+ if (t.scope === a.ROOT && t.expression) throw TypeError(`${e(t.type)} with a ROOT scope requires a field input.`);
29
29
  }
30
30
  });
31
31
  }
32
32
  var p = /* @__PURE__ */ new Set([
33
- o.ANY,
34
- o.FIRST,
35
- o.LAST
33
+ c.ANY,
34
+ c.FIRST,
35
+ c.LAST
36
36
  ]);
37
37
  function m(e) {
38
38
  let t = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Set(), r = {
@@ -40,124 +40,124 @@ function m(e) {
40
40
  windows: 0
41
41
  };
42
42
  e.forEach((e) => {
43
- e.type === o.DERIVED && (h(e, t, n, r), n.add(e.alias)), t.set(e.alias, p.has(e.type) ? e.type : void 0);
43
+ e.type === c.DERIVED && (h(e, t, n, r), n.add(e.alias)), t.set(e.alias, p.has(e.type) ? e.type : void 0);
44
44
  });
45
45
  }
46
- function h(e, n, i, a) {
46
+ function h(t, n, r, a) {
47
47
  let o = [{
48
- expression: e.expression,
48
+ expression: t.expression,
49
49
  depth: 1
50
50
  }];
51
51
  for (; o.length > 0;) {
52
- let { expression: c, depth: l } = o.pop();
53
- if (l > t.MAX_EXPRESSION_DEPTH) throw TypeError(`derived expression depth must be at most ${t.MAX_EXPRESSION_DEPTH}.`);
54
- if (a.nodes++, a.nodes > t.MAX_EXPRESSION_NODES) throw TypeError(`derived expressions must contain at most ${t.MAX_EXPRESSION_NODES} nodes.`);
55
- switch (c.type) {
56
- case s.METRIC_REF: {
57
- let t = c.metric;
58
- if (!n.has(t)) throw TypeError(`derived metric [${e.alias}] must reference a metric declared before it, but was [${t}].`);
59
- let i = n.get(t);
60
- if (i !== void 0) throw TypeError(`derived metric [${e.alias}] cannot reference ${r(i)} metric [${t}].`);
52
+ let { expression: s, depth: c } = o.pop();
53
+ if (c > l.MAX_EXPRESSION_DEPTH) throw TypeError(`derived expression depth must be at most ${l.MAX_EXPRESSION_DEPTH}.`);
54
+ if (a.nodes++, a.nodes > l.MAX_EXPRESSION_NODES) throw TypeError(`derived expressions must contain at most ${l.MAX_EXPRESSION_NODES} nodes.`);
55
+ switch (s.type) {
56
+ case i.METRIC_REF: {
57
+ let r = s.metric;
58
+ if (!n.has(r)) throw TypeError(`derived metric [${t.alias}] must reference a metric declared before it, but was [${r}].`);
59
+ let i = n.get(r);
60
+ if (i !== void 0) throw TypeError(`derived metric [${t.alias}] cannot reference ${e(i)} metric [${r}].`);
61
61
  break;
62
62
  }
63
- case s.CONSTANT:
64
- if (!Number.isFinite(c.value)) throw TypeError("derived constant must be finite.");
63
+ case i.CONSTANT:
64
+ if (!Number.isFinite(s.value)) throw TypeError("derived constant must be finite.");
65
65
  break;
66
- case s.BINARY:
66
+ case i.BINARY:
67
67
  o.push({
68
- expression: c.left,
69
- depth: l + 1
68
+ expression: s.left,
69
+ depth: c + 1
70
70
  }), o.push({
71
- expression: c.right,
72
- depth: l + 1
71
+ expression: s.right,
72
+ depth: c + 1
73
73
  });
74
74
  break;
75
- case s.TOTAL:
76
- case s.RUNNING:
77
- case s.PREVIOUS:
78
- case s.RANK:
79
- if (a.windows++, a.windows > t.MAX_WINDOWS) throw TypeError(`an aggregation must compute at most ${t.MAX_WINDOWS} windows.`);
80
- g(e.alias, c, n, i);
75
+ case i.TOTAL:
76
+ case i.RUNNING:
77
+ case i.PREVIOUS:
78
+ case i.RANK:
79
+ if (a.windows++, a.windows > l.MAX_WINDOWS) throw TypeError(`an aggregation must compute at most ${l.MAX_WINDOWS} windows.`);
80
+ g(t.alias, s, n, r);
81
81
  break;
82
- default: throw TypeError(`Unsupported derived expression: ${String(c.type)}.`);
82
+ default: throw TypeError(`Unsupported derived expression: ${String(s.type)}.`);
83
83
  }
84
84
  }
85
85
  }
86
- function g(e, t, n, i) {
87
- let a = t.metric;
88
- if (!n.has(a)) throw TypeError(`${r(t.type)} window of derived metric [${e}] must read a metric declared before it, but was [${a}].`);
89
- if (n.get(a) !== void 0 || i.has(a)) throw TypeError(`${r(t.type)} window of derived metric [${e}] must read a non-derived numeric metric, but was [${a}].`);
86
+ function g(t, n, r, i) {
87
+ let a = n.metric;
88
+ if (!r.has(a)) throw TypeError(`${e(n.type)} window of derived metric [${t}] must read a metric declared before it, but was [${a}].`);
89
+ if (r.get(a) !== void 0 || i.has(a)) throw TypeError(`${e(n.type)} window of derived metric [${t}] must read a non-derived numeric metric, but was [${a}].`);
90
90
  }
91
91
  function _(e, t, n, r) {
92
92
  if (!t.has(e)) throw TypeError(`having condition [${e}] must reference a declared metric alias.`);
93
93
  if (n.has(e)) throw TypeError(`having condition [${e}] cannot reference ANY metric.`);
94
94
  if (r.has(e)) throw TypeError(`having condition [${e}] cannot reference FIRST or LAST metric.`);
95
95
  }
96
- function v(e, n, i) {
97
- if (e === void 0) return;
96
+ function v(t, n, r) {
97
+ if (t === void 0) return;
98
98
  if (n.length === 0) throw TypeError("having requires at least one groupBy.");
99
- let a = new Set(i.map((e) => e.alias)), s = new Set(i.filter((e) => e.type === o.ANY).map((e) => e.alias)), l = new Set(i.filter((e) => e.type === o.FIRST || e.type === o.LAST).map((e) => e.alias)), u = [{
100
- expression: e,
99
+ let i = new Set(r.map((e) => e.alias)), a = new Set(r.filter((e) => e.type === c.ANY).map((e) => e.alias)), o = new Set(r.filter((e) => e.type === c.FIRST || e.type === c.LAST).map((e) => e.alias)), u = [{
100
+ expression: t,
101
101
  depth: 1
102
102
  }];
103
103
  for (; u.length > 0;) {
104
- let { expression: e, depth: n } = u.pop();
105
- if (n > t.MAX_EXPRESSION_DEPTH) throw TypeError(`having expression depth must be at most ${t.MAX_EXPRESSION_DEPTH}.`);
106
- switch (e.type) {
107
- case c.CONDITION:
108
- if (_(e.metric, a, s, l), !Number.isFinite(e.value)) throw TypeError(`having condition [${e.metric}] value must be finite.`);
104
+ let { expression: t, depth: n } = u.pop();
105
+ if (n > l.MAX_EXPRESSION_DEPTH) throw TypeError(`having expression depth must be at most ${l.MAX_EXPRESSION_DEPTH}.`);
106
+ switch (t.type) {
107
+ case s.CONDITION:
108
+ if (_(t.metric, i, a, o), !Number.isFinite(t.value)) throw TypeError(`having condition [${t.metric}] value must be finite.`);
109
109
  break;
110
- case c.BETWEEN:
111
- if (_(e.metric, a, s, l), !Number.isFinite(e.lower) || !Number.isFinite(e.upper)) throw TypeError(`having between [${e.metric}] bounds must be finite.`);
112
- if (e.lower > e.upper) throw TypeError(`having between [${e.metric}] lower bound must not exceed upper bound.`);
110
+ case s.BETWEEN:
111
+ if (_(t.metric, i, a, o), !Number.isFinite(t.lower) || !Number.isFinite(t.upper)) throw TypeError(`having between [${t.metric}] bounds must be finite.`);
112
+ if (t.lower > t.upper) throw TypeError(`having between [${t.metric}] lower bound must not exceed upper bound.`);
113
113
  break;
114
- case c.IN:
115
- if (_(e.metric, a, s, l), e.values.length === 0) throw TypeError(`having in [${e.metric}] values must not be empty.`);
116
- if (!e.values.every(Number.isFinite)) throw TypeError(`having in [${e.metric}] values must be finite.`);
114
+ case s.IN:
115
+ if (_(t.metric, i, a, o), t.values.length === 0) throw TypeError(`having in [${t.metric}] values must not be empty.`);
116
+ if (!t.values.every(Number.isFinite)) throw TypeError(`having in [${t.metric}] values must be finite.`);
117
117
  break;
118
- case c.IS_NULL:
119
- _(e.metric, a, s, l);
118
+ case s.IS_NULL:
119
+ _(t.metric, i, a, o);
120
120
  break;
121
- case c.AND:
122
- case c.OR:
123
- if (e.operands.length === 0) throw TypeError(`having ${r(e.type)} operands must not be empty.`);
124
- e.operands.forEach((e) => u.push({
121
+ case s.AND:
122
+ case s.OR:
123
+ if (t.operands.length === 0) throw TypeError(`having ${e(t.type)} operands must not be empty.`);
124
+ t.operands.forEach((e) => u.push({
125
125
  expression: e,
126
126
  depth: n + 1
127
127
  }));
128
128
  break;
129
- default: throw TypeError(`Unsupported having expression: ${String(e.type)}.`);
129
+ default: throw TypeError(`Unsupported having expression: ${String(t.type)}.`);
130
130
  }
131
131
  }
132
132
  }
133
- function y(e, n, r) {
134
- if (u("sort", "fields", e, t.MAX_SORT_FIELDS), n.length === 0 && e.length > 0) throw TypeError("sort requires at least one groupBy.");
133
+ function y(e, t, n) {
134
+ if (u("sort", "fields", e, l.MAX_SORT_FIELDS), t.length === 0 && e.length > 0) throw TypeError("sort requires at least one groupBy.");
135
135
  let i = e.map((e) => e.field);
136
136
  if (new Set(i).size !== i.length) throw TypeError("sort fields must be unique.");
137
- if (!i.every((e) => r.includes(e))) throw TypeError("sort fields must reference aggregation aliases.");
138
- u("effective sort", "fields", l({
139
- groupBy: [...n],
137
+ if (!i.every((e) => n.includes(e))) throw TypeError("sort fields must reference aggregation aliases.");
138
+ u("effective sort", "fields", r({
139
+ groupBy: [...t],
140
140
  sort: [...e]
141
- }), t.MAX_SORT_FIELDS);
141
+ }), l.MAX_SORT_FIELDS);
142
142
  }
143
143
  function b(e) {
144
- let t = new Map((e.groupBy ?? []).map((e) => [e.alias, e.scope === i.ROOT])), n = l(e).flatMap((e) => t.has(e.field) ? [t.get(e.field)] : []), r = n.indexOf(!1);
145
- if (r >= 0 && n.slice(r).includes(!0)) throw TypeError("groups with a ROOT scope must sort before the element groups.");
144
+ let t = new Map((e.groupBy ?? []).map((e) => [e.alias, e.scope === a.ROOT])), n = r(e).flatMap((e) => t.has(e.field) ? [t.get(e.field)] : []), i = n.indexOf(!1);
145
+ if (i >= 0 && n.slice(i).includes(!0)) throw TypeError("groups with a ROOT scope must sort before the element groups.");
146
146
  }
147
- function x(e) {
148
- let n = e.elements ?? [], i = e.groupBy ?? [], o = e.metrics, s = e.sort ?? [];
149
- if (u("elements", "paths", n, t.MAX_ELEMENTS), u("groupBy", "dimensions", i, t.MAX_GROUPS), !Array.isArray(o) || o.length === 0) throw TypeError("metrics must not be empty.");
150
- if (u("metrics", "entries", o, t.MAX_METRICS), e.limit !== void 0 && (!Number.isInteger(e.limit) || e.limit < 1 || e.limit > t.MAX_LIMIT)) throw TypeError(`limit must be between 1 and ${t.MAX_LIMIT}.`);
151
- f(o, i), m(o), v(e.having, i, o), o.forEach((e) => {
147
+ function x(t) {
148
+ let n = t.elements ?? [], r = t.groupBy ?? [], i = t.metrics, a = t.sort ?? [];
149
+ if (u("elements", "paths", n, l.MAX_ELEMENTS), u("groupBy", "dimensions", r, l.MAX_GROUPS), !Array.isArray(i) || i.length === 0) throw TypeError("metrics must not be empty.");
150
+ if (u("metrics", "entries", i, l.MAX_METRICS), t.limit !== void 0 && (!Number.isInteger(t.limit) || t.limit < 1 || t.limit > l.MAX_LIMIT)) throw TypeError(`limit must be between 1 and ${l.MAX_LIMIT}.`);
151
+ f(i, r), m(i), v(t.having, r, i), i.forEach((e) => {
152
152
  "filter" in e && e.filter && d(e.filter);
153
- }), i.forEach((e) => {
154
- if ((e.type === a.DATE_HISTOGRAM || e.type === a.DATE_PART) && e.dense === !0 && i.length !== 1) throw TypeError(`dense requires ${r(e.type)} to be the only groupBy.`);
153
+ }), r.forEach((t) => {
154
+ if ((t.type === o.DATE_HISTOGRAM || t.type === o.DATE_PART) && t.dense === !0 && r.length !== 1) throw TypeError(`dense requires ${e(t.type)} to be the only groupBy.`);
155
155
  });
156
- let c = [...i.map((e) => e.alias), ...o.map((e) => e.alias)];
157
- if (new Set(c).size !== c.length) throw TypeError("aggregation aliases must be unique.");
158
- return y(s, i, c), n.length > 0 && b(e), {
159
- ...e,
160
- metrics: [...o]
156
+ let s = [...r.map((e) => e.alias), ...i.map((e) => e.alias)];
157
+ if (new Set(s).size !== s.length) throw TypeError("aggregation aliases must be unique.");
158
+ return y(a, r, s), n.length > 0 && b(t), {
159
+ ...t,
160
+ metrics: [...i]
161
161
  };
162
162
  }
163
163
  export { x as admitAggregationQuery };
@@ -1,2 +1,2 @@
1
- const e=require("./types.cjs"),t=require("../filter/scope.cjs"),n=require("./aliases.cjs"),r=require("./groups.cjs"),i=require("./metrics.cjs"),a=require("./derived.cjs"),o=require("./having.cjs"),s=require("./admit.cjs");function c(t,n,r){return{type:e.AggregationExpressionType.BINARY,operator:t,left:n,right:r}}var l={element(e,r){let i=n.aggregationField(e);return r===void 0?{path:i}:(t.requireElementScopedFilter(r,`Aggregation element filter`,!1),{path:i,filter:r})},field(t){return{type:e.AggregationExpressionType.FIELD,field:n.aggregationField(t)}},constant(t){if(!Number.isFinite(t))throw TypeError(`aggregation constant must be finite.`);return{type:e.AggregationExpressionType.CONSTANT,value:t}},dateDiff(t,r,i){if(!Object.values(e.DateDiffUnit).includes(i))throw TypeError(`date diff unit is invalid.`);return{type:e.AggregationExpressionType.DATE_DIFF,from:n.aggregationField(t),to:n.aggregationField(r),unit:i}},add:(t,n)=>c(e.AggregationExpressionOperator.ADD,t,n),subtract:(t,n)=>c(e.AggregationExpressionOperator.SUBTRACT,t,n),multiply:(t,n)=>c(e.AggregationExpressionOperator.MULTIPLY,t,n),divide:(t,n)=>c(e.AggregationExpressionOperator.DIVIDE,t,n),query(e){return s.admitAggregationQuery(e)}},u={...l,...r.groupBuilders,...i.metricBuilders,...a.derivedBuilders,...o.havingBuilders};exports.aggregation=u,exports.queryBuilders=l;
1
+ const e=require("../filter/scope.cjs"),t=require("./admit.cjs"),n=require("./aliases.cjs"),r=require("./types.cjs"),i=require("./derived.cjs"),a=require("./groups.cjs"),o=require("./having.cjs"),s=require("./metrics.cjs");function c(e,t,n){return{type:r.AggregationExpressionType.BINARY,operator:e,left:t,right:n}}var l={element(t,r){let i=n.aggregationField(t);return r===void 0?{path:i}:(e.requireElementScopedFilter(r,`Aggregation element filter`,!1),{path:i,filter:r})},field(e){return{type:r.AggregationExpressionType.FIELD,field:n.aggregationField(e)}},constant(e){if(!Number.isFinite(e))throw TypeError(`aggregation constant must be finite.`);return{type:r.AggregationExpressionType.CONSTANT,value:e}},dateDiff(e,t,i){if(!Object.values(r.DateDiffUnit).includes(i))throw TypeError(`date diff unit is invalid.`);return{type:r.AggregationExpressionType.DATE_DIFF,from:n.aggregationField(e),to:n.aggregationField(t),unit:i}},add:(e,t)=>c(r.AggregationExpressionOperator.ADD,e,t),subtract:(e,t)=>c(r.AggregationExpressionOperator.SUBTRACT,e,t),multiply:(e,t)=>c(r.AggregationExpressionOperator.MULTIPLY,e,t),divide:(e,t)=>c(r.AggregationExpressionOperator.DIVIDE,e,t),query(e){return t.admitAggregationQuery(e)}},u={...l,...a.groupBuilders,...s.metricBuilders,...i.derivedBuilders,...o.havingBuilders};exports.aggregation=u,exports.queryBuilders=l;
2
2
  //# sourceMappingURL=builders.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"builders.cjs","names":["AggregationExpressionType","aggregationField","DateDiffUnit","AggregationExpressionOperator","admitAggregationQuery","groupBuilders","metricBuilders","derivedBuilders","havingBuilders","require_types","require_scope","require_aliases","require_groups","require_metrics","require_derived","require_having","require_admit","binary","queryBuilders","validPath","path","predicate","field","value","unit","from","to","left","right","query","aggregation"],"sources":["../../../src/dsl/aggregation/builders.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ElementFilterExpression,\n ExpressionFilter,\n} from '../filter/index.js';\nimport { requireElementScopedFilter } from '../filter/scope.js';\nimport { admitAggregationQuery } from './admit.js';\nimport { aggregationField } from './aliases.js';\nimport {\n DateDiffUnit,\n AggregationExpressionOperator,\n AggregationExpressionType,\n type AggregationElement,\n type AggregationExpression,\n type DateDiffAggregationExpression,\n type AggregationQuery,\n type BinaryAggregationExpression,\n type ConstantAggregationExpression,\n type FieldAggregationExpression,\n} from './types.js';\nimport { derivedBuilders } from './derived.js';\nimport { groupBuilders } from './groups.js';\nimport { havingBuilders } from './having.js';\nimport { metricBuilders } from './metrics.js';\n\nfunction binary<FIELDS extends string>(\n operator: AggregationExpressionOperator,\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n): BinaryAggregationExpression<FIELDS> {\n return { type: AggregationExpressionType.BINARY, operator, left, right };\n}\n\n/** The builders of an aggregation query's elements and expressions, and of the query itself. */\nexport const queryBuilders = {\n /**\n * Aggregates over the elements of an array field instead of the root\n * documents. `{ path, filter? }`.\n *\n * @param path - The array field, a query field path.\n * @param predicate - Keeps only the elements that match; may not contain\n * root filters (id, owner, tenant, space, deletion) or any search, even\n * one that names its fields. An `EXPRESSION` filter is allowed.\n * @throws TypeError when `path` is not a valid field path or `predicate`\n * contains a root filter.\n * @example\n * ```typescript\n * aggregation.element('items', filter.gt('quantity', 0));\n * ```\n */\n element(\n path: string,\n predicate?: ElementFilterExpression | ExpressionFilter,\n ): AggregationElement {\n const validPath = aggregationField(path);\n if (predicate === undefined) return { path: validPath };\n requireElementScopedFilter(predicate, 'Aggregation element filter', false);\n return { path: validPath, filter: predicate };\n },\n /**\n * The value of a field, as an operand. `{ type: 'field', field }`.\n *\n * @throws TypeError when `field` is not a valid field path.\n * @example\n * ```typescript\n * aggregation.sum(aggregation.field('state.amount'), 'amount');\n * ```\n */\n field<FIELDS extends string>(\n field: FIELDS,\n ): FieldAggregationExpression<FIELDS> {\n return {\n type: AggregationExpressionType.FIELD,\n field: aggregationField(field),\n };\n },\n /**\n * A number, as an operand. `{ type: 'constant', value }`.\n *\n * @throws TypeError when `value` is not finite.\n * @example\n * ```typescript\n * aggregation.multiply(aggregation.field('price'), aggregation.constant(100));\n * ```\n */\n constant(value: number): ConstantAggregationExpression {\n if (!Number.isFinite(value)) {\n throw new TypeError('aggregation constant must be finite.');\n }\n return { type: AggregationExpressionType.CONSTANT, value };\n },\n /**\n * The time from the instant in `from` to the instant in `to`, `to − from`,\n * in `unit`, as a signed decimal: negative when `to` is earlier, and no\n * value when either instant is absent. A `DAY` is exactly 24 hours.\n * `{ type: 'date-diff', from, to, unit }`. Both fields must be\n * single-valued time fields, those whose `aggregate.groups` list\n * `DATE_HISTOGRAM` in the descriptor, and `unit` one of its\n * `analysis.dateDiffUnits`. Wow 9.2 and later.\n *\n * @throws TypeError when `from` or `to` is not a valid field path, or\n * `unit` is not a {@link DateDiffUnit}.\n * @example\n * ```typescript\n * // Hours from payment to shipping, averaged per warehouse.\n * aggregation.avg(\n * aggregation.dateDiff('state.paidAt', 'state.shippedAt', DateDiffUnit.HOUR),\n * 'hoursToShip',\n * );\n * ```\n */\n dateDiff<FIELDS extends string>(\n from: FIELDS,\n to: FIELDS,\n unit: DateDiffUnit,\n ): DateDiffAggregationExpression<FIELDS> {\n if (!Object.values(DateDiffUnit).includes(unit)) {\n throw new TypeError('date diff unit is invalid.');\n }\n return {\n type: AggregationExpressionType.DATE_DIFF,\n from: aggregationField(from),\n to: aggregationField(to),\n unit,\n };\n },\n /** `left + right`. `{ type: 'binary', operator: 'add', left, right }`. */\n add: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.ADD, left, right),\n /** `left - right`. `{ type: 'binary', operator: 'subtract', left, right }`. */\n subtract: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.SUBTRACT, left, right),\n /** `left * right`. `{ type: 'binary', operator: 'multiply', left, right }`. */\n multiply: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.MULTIPLY, left, right),\n /** `left / right`. `{ type: 'binary', operator: 'divide', left, right }`. */\n divide: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.DIVIDE, left, right),\n /**\n * Admits a whole aggregation query against the rules Wow enforces on arrival.\n *\n * The factories above each check their own part; only the assembled query\n * can answer the questions that span parts — whether two aliases collide,\n * whether a sort names one of them, whether `having` has rows to filter.\n * Wow checks all of it in `AggregationQuery`'s constructor and answers a\n * query that fails with a 400, so the same rules run here against the object\n * about to be sent.\n */\n query<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n >(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n ): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n return admitAggregationQuery(query);\n },\n};\n\n/**\n * Builders of an `AggregationQuery`: its elements, groups, metrics and the\n * arithmetic expressions metrics compute over. Each builder checks its own\n * part and throws a `TypeError` naming what is wrong; {@link aggregation.query}\n * checks the parts against each other.\n *\n * Every group and metric takes its target first, its alias second, and any\n * further options as a trailing object.\n */\nexport const aggregation: typeof queryBuilders &\n typeof groupBuilders &\n typeof metricBuilders &\n typeof derivedBuilders &\n typeof havingBuilders = {\n ...queryBuilders,\n ...groupBuilders,\n ...metricBuilders,\n ...derivedBuilders,\n ...havingBuilders,\n};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,GAAGb,EAAAA,cACH,GAAGC,EAAAA,eACH,GAAGC,EAAAA,gBACH,GAAGC,EAAAA,cACL,E"}
1
+ {"version":3,"file":"builders.cjs","names":["AggregationExpressionType","aggregationField","DateDiffUnit","AggregationExpressionOperator","admitAggregationQuery","groupBuilders","metricBuilders","derivedBuilders","havingBuilders","require_scope","require_admit","require_aliases","require_types","require_derived","require_groups","require_having","require_metrics","binary","queryBuilders","validPath","path","predicate","field","value","unit","from","to","left","right","query","aggregation"],"sources":["../../../src/dsl/aggregation/builders.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ElementFilterExpression,\n ExpressionFilter,\n} from '../filter/index.js';\nimport { requireElementScopedFilter } from '../filter/scope.js';\nimport { admitAggregationQuery } from './admit.js';\nimport { aggregationField } from './aliases.js';\nimport {\n DateDiffUnit,\n AggregationExpressionOperator,\n AggregationExpressionType,\n type AggregationElement,\n type AggregationExpression,\n type DateDiffAggregationExpression,\n type AggregationQuery,\n type BinaryAggregationExpression,\n type ConstantAggregationExpression,\n type FieldAggregationExpression,\n} from './types.js';\nimport { derivedBuilders } from './derived.js';\nimport { groupBuilders } from './groups.js';\nimport { havingBuilders } from './having.js';\nimport { metricBuilders } from './metrics.js';\n\nfunction binary<FIELDS extends string>(\n operator: AggregationExpressionOperator,\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n): BinaryAggregationExpression<FIELDS> {\n return { type: AggregationExpressionType.BINARY, operator, left, right };\n}\n\n/** The builders of an aggregation query's elements and expressions, and of the query itself. */\nexport const queryBuilders = {\n /**\n * Aggregates over the elements of an array field instead of the root\n * documents. `{ path, filter? }`.\n *\n * @param path - The array field, a query field path.\n * @param predicate - Keeps only the elements that match; may not contain\n * root filters (id, owner, tenant, space, deletion) or any search, even\n * one that names its fields. An `EXPRESSION` filter is allowed.\n * @throws TypeError when `path` is not a valid field path or `predicate`\n * contains a root filter.\n * @example\n * ```typescript\n * aggregation.element('items', filter.gt('quantity', 0));\n * ```\n */\n element(\n path: string,\n predicate?: ElementFilterExpression | ExpressionFilter,\n ): AggregationElement {\n const validPath = aggregationField(path);\n if (predicate === undefined) return { path: validPath };\n requireElementScopedFilter(predicate, 'Aggregation element filter', false);\n return { path: validPath, filter: predicate };\n },\n /**\n * The value of a field, as an operand. `{ type: 'field', field }`.\n *\n * @throws TypeError when `field` is not a valid field path.\n * @example\n * ```typescript\n * aggregation.sum(aggregation.field('state.amount'), 'amount');\n * ```\n */\n field<FIELDS extends string>(\n field: FIELDS,\n ): FieldAggregationExpression<FIELDS> {\n return {\n type: AggregationExpressionType.FIELD,\n field: aggregationField(field),\n };\n },\n /**\n * A number, as an operand. `{ type: 'constant', value }`.\n *\n * @throws TypeError when `value` is not finite.\n * @example\n * ```typescript\n * aggregation.multiply(aggregation.field('price'), aggregation.constant(100));\n * ```\n */\n constant(value: number): ConstantAggregationExpression {\n if (!Number.isFinite(value)) {\n throw new TypeError('aggregation constant must be finite.');\n }\n return { type: AggregationExpressionType.CONSTANT, value };\n },\n /**\n * The time from the instant in `from` to the instant in `to`, `to − from`,\n * in `unit`, as a signed decimal: negative when `to` is earlier, and no\n * value when either instant is absent. A `DAY` is exactly 24 hours.\n * `{ type: 'date-diff', from, to, unit }`. Both fields must be\n * single-valued time fields, those whose `aggregate.groups` list\n * `DATE_HISTOGRAM` in the descriptor, and `unit` one of its\n * `analysis.dateDiffUnits`. Wow 9.2 and later.\n *\n * @throws TypeError when `from` or `to` is not a valid field path, or\n * `unit` is not a {@link DateDiffUnit}.\n * @example\n * ```typescript\n * // Hours from payment to shipping, averaged per warehouse.\n * aggregation.avg(\n * aggregation.dateDiff('state.paidAt', 'state.shippedAt', DateDiffUnit.HOUR),\n * 'hoursToShip',\n * );\n * ```\n */\n dateDiff<FIELDS extends string>(\n from: FIELDS,\n to: FIELDS,\n unit: DateDiffUnit,\n ): DateDiffAggregationExpression<FIELDS> {\n if (!Object.values(DateDiffUnit).includes(unit)) {\n throw new TypeError('date diff unit is invalid.');\n }\n return {\n type: AggregationExpressionType.DATE_DIFF,\n from: aggregationField(from),\n to: aggregationField(to),\n unit,\n };\n },\n /** `left + right`. `{ type: 'binary', operator: 'add', left, right }`. */\n add: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.ADD, left, right),\n /** `left - right`. `{ type: 'binary', operator: 'subtract', left, right }`. */\n subtract: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.SUBTRACT, left, right),\n /** `left * right`. `{ type: 'binary', operator: 'multiply', left, right }`. */\n multiply: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.MULTIPLY, left, right),\n /** `left / right`. `{ type: 'binary', operator: 'divide', left, right }`. */\n divide: <FIELDS extends string>(\n left: AggregationExpression<FIELDS>,\n right: AggregationExpression<FIELDS>,\n ) => binary(AggregationExpressionOperator.DIVIDE, left, right),\n /**\n * Admits a whole aggregation query against the rules Wow enforces on arrival.\n *\n * The factories above each check their own part; only the assembled query\n * can answer the questions that span parts — whether two aliases collide,\n * whether a sort names one of them, whether `having` has rows to filter.\n * Wow checks all of it in `AggregationQuery`'s constructor and answers a\n * query that fails with a 400, so the same rules run here against the object\n * about to be sent.\n */\n query<\n ROOT_FIELDS extends string = string,\n AGGREGATION_FIELDS extends string = ROOT_FIELDS,\n >(\n query: AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS>,\n ): AggregationQuery<ROOT_FIELDS, AGGREGATION_FIELDS> {\n return admitAggregationQuery(query);\n },\n};\n\n/**\n * Builders of an `AggregationQuery`: its elements, groups, metrics and the\n * arithmetic expressions metrics compute over. Each builder checks its own\n * part and throws a `TypeError` naming what is wrong; {@link aggregation.query}\n * checks the parts against each other.\n *\n * Every group and metric takes its target first, its alias second, and any\n * further options as a trailing object.\n */\nexport const aggregation: typeof queryBuilders &\n typeof groupBuilders &\n typeof metricBuilders &\n typeof derivedBuilders &\n typeof havingBuilders = {\n ...queryBuilders,\n ...groupBuilders,\n ...metricBuilders,\n ...derivedBuilders,\n ...havingBuilders,\n};\n"],"mappings":"A,8NAqCA,SAASiB,EACP,EACA,EACA,EACqC,CACrC,MAAO,CAAE,KAAMjB,EAAAA,0BAA0B,OAAQ,WAAU,OAAM,OAAM,CACzE,CAGA,IAAakB,EAAgB,CAgB3B,QACE,EACA,EACoB,CACpB,IAAMC,EAAYlB,EAAAA,iBAAiBmB,CAAI,EAGvC,OAFIC,IAAc,IAAA,GAAkB,CAAE,KAAMF,CAAU,GACtDV,EAAA,2BAA2BY,EAAW,6BAA8B,EAAK,EAClE,CAAE,KAAMF,EAAW,OAAQE,CAAU,EAC9C,EAUA,MACE,EACoC,CACpC,MAAO,CACL,KAAMrB,EAAAA,0BAA0B,MAChC,MAAOC,EAAAA,iBAAiBqB,CAAK,CAC/B,CACF,EAUA,SAAS,EAA8C,CACrD,GAAI,CAAC,OAAO,SAASC,CAAK,EACxB,MAAU,UAAU,sCAAsC,EAE5D,MAAO,CAAE,KAAMvB,EAAAA,0BAA0B,SAAU,OAAM,CAC3D,EAqBA,SACE,EACA,EACA,EACuC,CACvC,GAAI,CAAC,OAAO,OAAOE,EAAAA,YAAY,CAAC,CAAC,SAASsB,CAAI,EAC5C,MAAU,UAAU,4BAA4B,EAElD,MAAO,CACL,KAAMxB,EAAAA,0BAA0B,UAChC,KAAMC,EAAAA,iBAAiBwB,CAAI,EAC3B,GAAIxB,EAAAA,iBAAiByB,CAAE,EACvB,MACF,CACF,EAEA,KACE,EACA,IACGT,EAAOd,EAAAA,8BAA8B,IAAKwB,EAAMC,CAAK,EAE1D,UACE,EACA,IACGX,EAAOd,EAAAA,8BAA8B,SAAUwB,EAAMC,CAAK,EAE/D,UACE,EACA,IACGX,EAAOd,EAAAA,8BAA8B,SAAUwB,EAAMC,CAAK,EAE/D,QACE,EACA,IACGX,EAAOd,EAAAA,8BAA8B,OAAQwB,EAAMC,CAAK,EAW7D,MAIE,EACmD,CACnD,OAAOxB,EAAAA,sBAAsByB,CAAK,CACpC,CACF,EAWaC,EAIa,CACxB,GAAGZ,EACH,GAAGb,EAAAA,cACH,GAAGC,EAAAA,eACH,GAAGC,EAAAA,gBACH,GAAGC,EAAAA,cACL,E"}
@@ -1,62 +1,62 @@
1
- import { AggregationExpressionOperator as e, AggregationExpressionType as t, DateDiffUnit as n } from "./types.es.js";
2
- import { requireElementScopedFilter as r } from "../filter/scope.es.js";
3
- import { aggregationField as i } from "./aliases.es.js";
4
- import { groupBuilders as a } from "./groups.es.js";
5
- import { metricBuilders as o } from "./metrics.es.js";
6
- import { derivedBuilders as s } from "./derived.es.js";
1
+ import { requireElementScopedFilter as e } from "../filter/scope.es.js";
2
+ import { admitAggregationQuery as t } from "./admit.es.js";
3
+ import { aggregationField as n } from "./aliases.es.js";
4
+ import { AggregationExpressionOperator as r, AggregationExpressionType as i, DateDiffUnit as a } from "./types.es.js";
5
+ import { derivedBuilders as o } from "./derived.es.js";
6
+ import { groupBuilders as s } from "./groups.es.js";
7
7
  import { havingBuilders as c } from "./having.es.js";
8
- import { admitAggregationQuery as l } from "./admit.es.js";
8
+ import { metricBuilders as l } from "./metrics.es.js";
9
9
  // src/dsl/aggregation/builders.ts
10
- function u(e, n, r) {
10
+ function u(e, t, n) {
11
11
  return {
12
- type: t.BINARY,
12
+ type: i.BINARY,
13
13
  operator: e,
14
- left: n,
15
- right: r
14
+ left: t,
15
+ right: n
16
16
  };
17
17
  }
18
18
  var d = {
19
- element(e, t) {
20
- let n = i(e);
21
- return t === void 0 ? { path: n } : (r(t, "Aggregation element filter", !1), {
22
- path: n,
23
- filter: t
19
+ element(t, r) {
20
+ let i = n(t);
21
+ return r === void 0 ? { path: i } : (e(r, "Aggregation element filter", !1), {
22
+ path: i,
23
+ filter: r
24
24
  });
25
25
  },
26
26
  field(e) {
27
27
  return {
28
- type: t.FIELD,
29
- field: i(e)
28
+ type: i.FIELD,
29
+ field: n(e)
30
30
  };
31
31
  },
32
32
  constant(e) {
33
33
  if (!Number.isFinite(e)) throw TypeError("aggregation constant must be finite.");
34
34
  return {
35
- type: t.CONSTANT,
35
+ type: i.CONSTANT,
36
36
  value: e
37
37
  };
38
38
  },
39
- dateDiff(e, r, a) {
40
- if (!Object.values(n).includes(a)) throw TypeError("date diff unit is invalid.");
39
+ dateDiff(e, t, r) {
40
+ if (!Object.values(a).includes(r)) throw TypeError("date diff unit is invalid.");
41
41
  return {
42
- type: t.DATE_DIFF,
43
- from: i(e),
44
- to: i(r),
45
- unit: a
42
+ type: i.DATE_DIFF,
43
+ from: n(e),
44
+ to: n(t),
45
+ unit: r
46
46
  };
47
47
  },
48
- add: (t, n) => u(e.ADD, t, n),
49
- subtract: (t, n) => u(e.SUBTRACT, t, n),
50
- multiply: (t, n) => u(e.MULTIPLY, t, n),
51
- divide: (t, n) => u(e.DIVIDE, t, n),
48
+ add: (e, t) => u(r.ADD, e, t),
49
+ subtract: (e, t) => u(r.SUBTRACT, e, t),
50
+ multiply: (e, t) => u(r.MULTIPLY, e, t),
51
+ divide: (e, t) => u(r.DIVIDE, e, t),
52
52
  query(e) {
53
- return l(e);
53
+ return t(e);
54
54
  }
55
55
  }, f = {
56
56
  ...d,
57
- ...a,
58
- ...o,
59
57
  ...s,
58
+ ...l,
59
+ ...o,
60
60
  ...c
61
61
  };
62
62
  export { f as aggregation, d as queryBuilders };
@@ -1,2 +1,2 @@
1
- const e=require("./types.cjs"),t=require("./aliases.cjs"),n=require("./metrics.cjs");var r=function(e){return e.METRIC_REF=`metric-ref`,e.CONSTANT=`constant`,e.BINARY=`binary`,e.TOTAL=`total`,e.RUNNING=`running`,e.PREVIOUS=`previous`,e.RANK=`rank`,e}({}),i=function(e){return e.TOTAL=`total`,e.RUNNING=`running`,e.PREVIOUS=`previous`,e.RANK=`rank`,e}({}),a=function(e){return e.SUM=`sum`,e.AVG=`avg`,e}({});function o(e,t,n){return{type:`binary`,operator:e,left:t,right:n}}var s={ref:e=>({type:`metric-ref`,metric:e}),constant(e){if(!Number.isFinite(e))throw TypeError(`derived constant must be finite.`);return{type:`constant`,value:e}},add:(t,n)=>o(e.AggregationExpressionOperator.ADD,t,n),subtract:(t,n)=>o(e.AggregationExpressionOperator.SUBTRACT,t,n),multiply:(t,n)=>o(e.AggregationExpressionOperator.MULTIPLY,t,n),divide:(t,n)=>o(e.AggregationExpressionOperator.DIVIDE,t,n),total:(e,...t)=>({type:`total`,metric:e,...t.length>0&&{within:t}}),running:(e,t,n={})=>({type:`running`,metric:e,order:t,...n}),previous:(e,t,n={})=>({type:`previous`,metric:e,along:t,...n}),rank:(e,t={})=>({type:`rank`,metric:e,...t})},c={derived(e,r){return{type:n.AggregationMetricType.DERIVED,expression:typeof e==`function`?e(s):e,alias:t.aggregationAlias(r)}}};exports.DerivedExpressionType=r,exports.RunningFunction=a,exports.WindowFunction=i,exports.derivedBuilders=c,exports.derivedExpressionDsl=s;
1
+ const e=require("./metrics.cjs"),t=require("./types.cjs"),n=require("./aliases.cjs");var r=function(e){return e.METRIC_REF=`metric-ref`,e.CONSTANT=`constant`,e.BINARY=`binary`,e.TOTAL=`total`,e.RUNNING=`running`,e.PREVIOUS=`previous`,e.RANK=`rank`,e}({}),i=function(e){return e.TOTAL=`total`,e.RUNNING=`running`,e.PREVIOUS=`previous`,e.RANK=`rank`,e}({}),a=function(e){return e.SUM=`sum`,e.AVG=`avg`,e}({});function o(e,t,n){return{type:`binary`,operator:e,left:t,right:n}}var s={ref:e=>({type:`metric-ref`,metric:e}),constant(e){if(!Number.isFinite(e))throw TypeError(`derived constant must be finite.`);return{type:`constant`,value:e}},add:(e,n)=>o(t.AggregationExpressionOperator.ADD,e,n),subtract:(e,n)=>o(t.AggregationExpressionOperator.SUBTRACT,e,n),multiply:(e,n)=>o(t.AggregationExpressionOperator.MULTIPLY,e,n),divide:(e,n)=>o(t.AggregationExpressionOperator.DIVIDE,e,n),total:(e,...t)=>({type:`total`,metric:e,...t.length>0&&{within:t}}),running:(e,t,n={})=>({type:`running`,metric:e,order:t,...n}),previous:(e,t,n={})=>({type:`previous`,metric:e,along:t,...n}),rank:(e,t={})=>({type:`rank`,metric:e,...t})},c={derived(t,r){return{type:e.AggregationMetricType.DERIVED,expression:typeof t==`function`?t(s):t,alias:n.aggregationAlias(r)}}};exports.DerivedExpressionType=r,exports.RunningFunction=a,exports.WindowFunction=i,exports.derivedBuilders=c,exports.derivedExpressionDsl=s;
2
2
  //# sourceMappingURL=derived.cjs.map