measurr 0.3.0 → 0.5.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.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { type Analytics, AnalyticsError, type AnalyticsErrorCode, type AnalyticsErrorDetails, type AnalyticsErrorOf, type AnalyticsOptions, type AnalyticsQuery, type AnalyticsQueryEvent, type AnalyticsResult, type AnalyticsSource, createAnalytics, type DatasetCatalogEntry, isAnalyticsError } from './analytics.js';
1
+ export { type AccessKey, type Analytics, type AnalyticsCache, AnalyticsError, type AnalyticsErrorCode, type AnalyticsErrorDetails, type AnalyticsErrorOf, type AnalyticsOptions, type AnalyticsQuery, type AnalyticsQueryEvent, type AnalyticsResult, type AnalyticsSource, createAnalytics, type DatasetCatalogEntry, type FieldKey, isAnalyticsError } from './analytics.js';
2
2
  export { CompileError, type CompiledStatement, type Dialect, type JoinClause, type SelectItem, type SelectStatement, type SqlRenderer, decodeNumber, renderStatement } from './compile.js';
3
3
  export { type AnyDataset, type AnyDimension, type AnyMeasure, type Dataset, type DimensionValue, defineDataset, dimension, type MeasureValue, measure, type Ratio } from './dataset.js';
4
4
  export { and, caseWhen, coalesce, type ColumnKey, eq, Expr, type ExprNode, exists, gt, gte, inList, isNotNull, isNull, literal, lt, lte, minutesAgo, ne, not, or, type SqlType, Table, type TableRef, table, toText } from './expr.js';
package/dist/index.js CHANGED
@@ -3,16 +3,18 @@ import {
3
3
  allTenants2,
4
4
  AnalyticsError2,
5
5
  isAnalyticsError2,
6
- createAnalytics2,
7
- measure2,
8
- dimension2,
9
- defineDataset2
10
- } from "./index-wrr67sxq.js";
6
+ createAnalytics2
7
+ } from "./index-zgb1e89d.js";
11
8
  import {
12
9
  CompileError2,
13
10
  decodeNumber2,
14
11
  renderStatement2
15
12
  } from "./index-nrjdssft.js";
13
+ import {
14
+ measure2,
15
+ dimension2,
16
+ defineDataset2
17
+ } from "./index-g2mjqx4f.js";
16
18
  import {
17
19
  Expr2,
18
20
  Table2,
package/dist/period.d.ts CHANGED
@@ -51,3 +51,8 @@ export declare class PeriodError extends Error {
51
51
  export declare function resolvePeriod(input: PeriodRange, timezone: string, now: Date): ResolvedPeriod;
52
52
  /** The period of equal length that ends the day before `period` starts. */
53
53
  export declare function previousPeriod(period: ResolvedPeriod): ResolvedPeriod;
54
+ /**
55
+ * The start date of every `unit` bucket that overlaps the days `from` to `to` (inclusive), as
56
+ * the time-bucket dimensions key them: the day, the ISO week's Monday, the month's first day.
57
+ */
58
+ export declare function bucketStarts(from: string, to: string, unit: 'day' | 'week' | 'month'): string[];
@@ -0,0 +1,111 @@
1
+ import type { ResultPeriod } from './query.js';
2
+ type DimensionValue = {
3
+ key: string | number | null;
4
+ label: string;
5
+ };
6
+ type Measures = Record<string, number | null>;
7
+ /** Any `analytics.query` result. */
8
+ type AnyResult = {
9
+ period: ResultPeriod;
10
+ rows: readonly Record<string, unknown>[];
11
+ totals: Measures;
12
+ previous?: {
13
+ period: ResultPeriod;
14
+ rows: readonly Record<string, unknown>[];
15
+ totals: Measures;
16
+ };
17
+ truncated: boolean;
18
+ };
19
+ type MeasureOf<R extends AnyResult> = keyof R['totals'] & string;
20
+ type DimensionOf<R extends AnyResult> = Exclude<keyof R['rows'][number] & string, MeasureOf<R>>;
21
+ export type KpiShape = {
22
+ kind: 'kpi';
23
+ value: number | null;
24
+ /** Only when the query compared with the previous period. */
25
+ previous?: number | null;
26
+ /** `(value - previous) / |previous|`; null when either is null or previous is 0. */
27
+ change?: number | null;
28
+ };
29
+ export type SeriesPoint = {
30
+ /** The bucket's start date, `YYYY-MM-DD`. */
31
+ bucket: string;
32
+ value: number | null;
33
+ };
34
+ export type TimeseriesShape = {
35
+ kind: 'timeseries';
36
+ unit: 'day' | 'week' | 'month';
37
+ series: {
38
+ key: string | number | null;
39
+ label: string;
40
+ points: SeriesPoint[];
41
+ /** The previous period's points, its own buckets; compare them by position. */
42
+ previous?: SeriesPoint[];
43
+ }[];
44
+ truncated: boolean;
45
+ };
46
+ export type DistributionShape = {
47
+ kind: 'distribution';
48
+ /** The measure over every row, so a many-to-many split can add up to more. */
49
+ total: number | null;
50
+ segments: (DimensionValue & {
51
+ value: number | null;
52
+ /** `value / total`, 0-1. */
53
+ share: number | null;
54
+ previous?: number | null;
55
+ })[];
56
+ truncated: boolean;
57
+ };
58
+ export type PivotShape = {
59
+ kind: 'pivot';
60
+ rows: DimensionValue[];
61
+ columns: DimensionValue[];
62
+ /** `values[row][column]`. */
63
+ values: (number | null)[][];
64
+ total: number | null;
65
+ truncated: boolean;
66
+ };
67
+ export type LeaderboardShape = {
68
+ kind: 'leaderboard';
69
+ items: (DimensionValue & {
70
+ rank: number;
71
+ value: number | null;
72
+ /** Every measure the query asked for. */
73
+ values: Measures;
74
+ })[];
75
+ truncated: boolean;
76
+ };
77
+ export declare function toKpi<R extends AnyResult>(result: R, measure: MeasureOf<R>): KpiShape;
78
+ /**
79
+ * One series per value of `series` (or one series named after the measure), with a point for
80
+ * every bucket of the period: buckets without rows get `fill` (0 by default; pass null for
81
+ * averages). Series come in the order they first appear in the rows. Group by the bucket
82
+ * dimension and set a `limit` that covers every bucket and series, or the result is truncated.
83
+ */
84
+ export declare function toTimeseries<R extends AnyResult>(result: R, options: {
85
+ bucket: DimensionOf<R>;
86
+ unit: 'day' | 'week' | 'month';
87
+ measure: MeasureOf<R>;
88
+ series?: DimensionOf<R>;
89
+ fill?: number | null;
90
+ }): TimeseriesShape;
91
+ export declare function toDistribution<R extends AnyResult>(result: R, options: {
92
+ by: DimensionOf<R>;
93
+ measure: MeasureOf<R>;
94
+ }): DistributionShape;
95
+ /**
96
+ * A grid of `measure` by two grouped dimensions. Numeric keys (weekdays, hours) are sorted;
97
+ * other keys keep the order they first appear in. Cells without a row get `fill` (0 by
98
+ * default; pass null for averages).
99
+ */
100
+ export declare function toPivot<R extends AnyResult>(result: R, options: {
101
+ rows: DimensionOf<R>;
102
+ columns: DimensionOf<R>;
103
+ measure: MeasureOf<R>;
104
+ fill?: number | null;
105
+ }): PivotShape;
106
+ /** The rows in query order (sort the query by `measure`), ranked from 1. */
107
+ export declare function toLeaderboard<R extends AnyResult>(result: R, options: {
108
+ by: DimensionOf<R>;
109
+ measure: MeasureOf<R>;
110
+ }): LeaderboardShape;
111
+ export {};
package/dist/shapes.js ADDED
@@ -0,0 +1,134 @@
1
+ import {
2
+ bucketStarts
3
+ } from "./index-g255jb1s.js";
4
+
5
+ // src/shapes.ts
6
+ function toKpi(result, measure) {
7
+ const value = result.totals[measure] ?? null;
8
+ if (!result.previous)
9
+ return { kind: "kpi", value };
10
+ const previous = result.previous.totals[measure] ?? null;
11
+ const change = value === null || previous === null || previous === 0 ? null : (value - previous) / Math.abs(previous);
12
+ return { kind: "kpi", value, previous, change };
13
+ }
14
+ function toTimeseries(result, options) {
15
+ const { bucket, unit, measure, series } = options;
16
+ const fill = options.fill === undefined ? 0 : options.fill;
17
+ const seriesOf = (row) => series ? dimensionValue(row, series) : { key: measure, label: measure };
18
+ const pointsOf = (period, rows, key) => {
19
+ const values = new Map;
20
+ for (const row of rows) {
21
+ const start = dimensionValue(row, bucket).key;
22
+ if (start === null || seriesOf(row).key !== key)
23
+ continue;
24
+ values.set(String(start), measureValue(row, measure));
25
+ }
26
+ const starts = "all" in period ? [...values.keys()].sort() : bucketStarts(period.from, period.to, unit);
27
+ return starts.map((start) => ({
28
+ bucket: start,
29
+ value: values.has(start) ? values.get(start) ?? null : fill
30
+ }));
31
+ };
32
+ const { previous } = result;
33
+ return {
34
+ kind: "timeseries",
35
+ unit,
36
+ series: distinct(result.rows.map(seriesOf)).map(({ key, label }) => ({
37
+ key,
38
+ label,
39
+ points: pointsOf(result.period, result.rows, key),
40
+ ...previous && {
41
+ previous: pointsOf(previous.period, previous.rows, key)
42
+ }
43
+ })),
44
+ truncated: result.truncated
45
+ };
46
+ }
47
+ function toDistribution(result, options) {
48
+ const { by, measure } = options;
49
+ const total = result.totals[measure] ?? null;
50
+ const previous = result.previous && new Map(result.previous.rows.map((row) => [
51
+ dimensionValue(row, by).key,
52
+ measureValue(row, measure)
53
+ ]));
54
+ return {
55
+ kind: "distribution",
56
+ total,
57
+ segments: result.rows.map((row) => {
58
+ const { key, label } = dimensionValue(row, by);
59
+ const value = measureValue(row, measure);
60
+ return {
61
+ key,
62
+ label,
63
+ value,
64
+ share: value === null || !total ? null : value / total,
65
+ ...previous && { previous: previous.get(key) ?? null }
66
+ };
67
+ }),
68
+ truncated: result.truncated
69
+ };
70
+ }
71
+ function toPivot(result, options) {
72
+ const fill = options.fill === undefined ? 0 : options.fill;
73
+ const rowsOf = (dimension) => sortNumeric(distinct(result.rows.map((row) => dimensionValue(row, dimension))));
74
+ const rows = rowsOf(options.rows);
75
+ const columns = rowsOf(options.columns);
76
+ const values = rows.map(() => columns.map(() => fill));
77
+ for (const row of result.rows) {
78
+ const r = rows.findIndex((entry) => entry.key === dimensionValue(row, options.rows).key);
79
+ const c = columns.findIndex((entry) => entry.key === dimensionValue(row, options.columns).key);
80
+ const cells = values[r];
81
+ if (cells)
82
+ cells[c] = measureValue(row, options.measure);
83
+ }
84
+ return {
85
+ kind: "pivot",
86
+ rows,
87
+ columns,
88
+ values,
89
+ total: result.totals[options.measure] ?? null,
90
+ truncated: result.truncated
91
+ };
92
+ }
93
+ function toLeaderboard(result, options) {
94
+ const measures = Object.keys(result.totals);
95
+ return {
96
+ kind: "leaderboard",
97
+ items: result.rows.map((row, index) => ({
98
+ ...dimensionValue(row, options.by),
99
+ rank: index + 1,
100
+ value: measureValue(row, options.measure),
101
+ values: Object.fromEntries(measures.map((key) => [key, measureValue(row, key)]))
102
+ })),
103
+ truncated: result.truncated
104
+ };
105
+ }
106
+ function dimensionValue(row, key) {
107
+ const value = row[key];
108
+ if (typeof value === "object" && value !== null && "label" in value) {
109
+ return value;
110
+ }
111
+ throw new Error(`The rows are not grouped by ${key}`);
112
+ }
113
+ function measureValue(row, key) {
114
+ const value = row[key];
115
+ return typeof value === "number" ? value : null;
116
+ }
117
+ function distinct(values) {
118
+ const byKey = new Map;
119
+ for (const value of values) {
120
+ if (!byKey.has(value.key))
121
+ byKey.set(value.key, { key: value.key, label: value.label });
122
+ }
123
+ return [...byKey.values()];
124
+ }
125
+ function sortNumeric(values) {
126
+ return values.every((value) => typeof value.key === "number") ? [...values].sort((a, b) => Number(a.key) - Number(b.key)) : values;
127
+ }
128
+ export {
129
+ toDistribution,
130
+ toKpi,
131
+ toLeaderboard,
132
+ toPivot,
133
+ toTimeseries
134
+ };
package/dist/testing.d.ts CHANGED
@@ -6,6 +6,7 @@
6
6
  import { type AnalyticsSource } from './analytics.js';
7
7
  import { type AnyDataset } from './dataset.js';
8
8
  import type { PeriodInput } from './period.js';
9
+ import { type TenantId, allTenants } from './plan.js';
9
10
  export type ContractCheck = {
10
11
  name: string;
11
12
  ok: boolean;
@@ -18,8 +19,11 @@ export type ContractReport = {
18
19
  export type ContractOptions = {
19
20
  dataset: AnyDataset;
20
21
  source: AnalyticsSource;
21
- /** A tenant with seeded rows in the period. */
22
- tenant: string | number;
22
+ /**
23
+ * A tenant with seeded rows in the period. `allTenants` for a dataset without a tenant
24
+ * column, which no single tenant may query.
25
+ */
26
+ tenant: TenantId | typeof allTenants;
23
27
  /** A tenant with no rows; defaults to a sentinel that no real tenant uses. */
24
28
  emptyTenant?: string | number;
25
29
  /** A timezone far from UTC makes bucketing mistakes visible. Defaults to Pacific/Auckland. */
@@ -30,8 +34,9 @@ export type ContractOptions = {
30
34
  };
31
35
  /**
32
36
  * Checks that every measure, grouping and filter compiles and runs, that groups add up to the
33
- * total, that labels resolve, that another tenant's rows never count, and that day buckets
34
- * agree with periods in the timezone.
37
+ * total, that labels resolve, that another tenant's rows never count (or, for a dataset
38
+ * without a tenant column, that a scoped caller is refused), and that day buckets agree with
39
+ * periods in the timezone. Fields marked with `access` are checked like any other.
35
40
  */
36
41
  export declare function checkDatasetContract(options: ContractOptions): Promise<ContractReport>;
37
42
  /** Runs `checkDatasetContract` and throws with every failed check listed. */
package/dist/testing.js CHANGED
@@ -1,9 +1,13 @@
1
1
  import {
2
2
  MAX_MEASURES,
3
- createAnalytics2,
3
+ allTenants2,
4
+ isAnalyticsError2,
5
+ createAnalytics2
6
+ } from "./index-zgb1e89d.js";
7
+ import {
4
8
  measure2,
5
9
  dimension2
6
- } from "./index-wrr67sxq.js";
10
+ } from "./index-g2mjqx4f.js";
7
11
 
8
12
  // src/testing.ts
9
13
  var COUNT = "__contractCount";
@@ -31,6 +35,7 @@ async function checkDatasetContract(options) {
31
35
  datasets: [probe],
32
36
  sources: { main: options.source },
33
37
  tenant: (ctx) => ctx.tenant,
38
+ authorizeField: () => true,
34
39
  timezone: () => timezone,
35
40
  ...options.now && { now: options.now }
36
41
  });
@@ -55,10 +60,11 @@ async function checkDatasetContract(options) {
55
60
  };
56
61
  const total = (await run({ measures: [COUNT] })).totals[COUNT] ?? 0;
57
62
  if (total === 0) {
63
+ const scope = options.tenant === allTenants2 ? "The dataset" : `Tenant ${options.tenant}`;
58
64
  checks.push({
59
65
  name: "seeded rows",
60
66
  ok: false,
61
- message: `Tenant ${options.tenant} has no rows in the period; the checks below prove little`
67
+ message: `${scope} has no rows in the period; the checks below prove little`
62
68
  });
63
69
  }
64
70
  for (const key of Object.keys(dataset.measures)) {
@@ -133,6 +139,10 @@ async function checkDatasetContract(options) {
133
139
  ["an empty tenant list", []]
134
140
  ]) {
135
141
  await check(`tenant isolation: ${name}`, async () => {
142
+ if (!dataset.tenantColumn) {
143
+ const refused = await run({ measures: [COUNT] }, tenant).then(() => false, (error) => isAnalyticsError2(error, "forbidden"));
144
+ return refused ? undefined : `${name} may query a dataset without a tenant column`;
145
+ }
136
146
  const measures = Object.keys(probe.measures);
137
147
  const leaked = [];
138
148
  for (let start = 0;start < measures.length; start += MAX_MEASURES) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "measurr",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "A small typed semantic layer: datasets of measures and dimensions compiled to one SQL statement per dialect.",
5
5
  "type": "module",
6
6
  "module": "./dist/index.js",
@@ -45,6 +45,18 @@
45
45
  "import": "./dist/dialects/postgres.js",
46
46
  "default": "./dist/dialects/postgres.js"
47
47
  },
48
+ "./shapes": {
49
+ "types": "./dist/shapes.d.ts",
50
+ "bun": "./src/shapes.ts",
51
+ "import": "./dist/shapes.js",
52
+ "default": "./dist/shapes.js"
53
+ },
54
+ "./handler": {
55
+ "types": "./dist/handler.d.ts",
56
+ "bun": "./src/handler.ts",
57
+ "import": "./dist/handler.js",
58
+ "default": "./dist/handler.js"
59
+ },
48
60
  "./testing": {
49
61
  "types": "./dist/testing.d.ts",
50
62
  "bun": "./src/testing.ts",
@@ -54,7 +66,7 @@
54
66
  },
55
67
  "scripts": {
56
68
  "build": "rm -rf dist && bun run build:js && bun run build:types",
57
- "build:js": "bun build ./src/index.ts ./src/dialects/postgres.ts ./src/testing.ts --root ./src --outdir ./dist --target node --packages external --splitting",
69
+ "build:js": "bun build ./src/index.ts ./src/dialects/postgres.ts ./src/shapes.ts ./src/handler.ts ./src/testing.ts --root ./src --outdir ./dist --target node --packages external --splitting",
58
70
  "build:types": "tsgo -p tsconfig.build.json",
59
71
  "prepublishOnly": "bun run build",
60
72
  "test": "bun test",