@contractspec/example.analytics-dashboard 3.9.8 → 3.9.10
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/browser/dashboard/dashboard.enum.js +1 -34
- package/dist/browser/dashboard/dashboard.operation.js +1 -289
- package/dist/browser/dashboard/dashboard.presentation.js +1 -200
- package/dist/browser/dashboard/dashboard.schema.js +1 -126
- package/dist/browser/dashboard/dashboard.test-spec.js +1 -213
- package/dist/browser/dashboard/index.js +1 -299
- package/dist/browser/dashboard.feature.js +1 -683
- package/dist/browser/datasource/posthog-datasource.js +4 -289
- package/dist/browser/docs/analytics-dashboard.docblock.js +5 -49
- package/dist/browser/docs/index.js +5 -49
- package/dist/browser/events.js +1 -81
- package/dist/browser/example.js +1 -42
- package/dist/browser/handlers/analytics.handlers.js +4 -278
- package/dist/browser/handlers/index.js +7 -571
- package/dist/browser/handlers/query.handlers.js +4 -294
- package/dist/browser/index.js +12 -2317
- package/dist/browser/query/index.js +1 -159
- package/dist/browser/query/query.enum.js +1 -11
- package/dist/browser/query/query.operation.js +1 -154
- package/dist/browser/query/query.presentation.js +1 -122
- package/dist/browser/query/query.schema.js +1 -70
- package/dist/browser/query/query.test-spec.js +1 -113
- package/dist/browser/query-engine/index.js +4 -491
- package/dist/browser/seeders/index.js +2 -20
- package/dist/browser/ui/AnalyticsDashboard.js +1 -1115
- package/dist/browser/ui/AnalyticsDashboard.widgets.js +1 -94
- package/dist/browser/ui/AnalyticsQueriesTable.js +1 -188
- package/dist/browser/ui/hooks/index.js +1 -660
- package/dist/browser/ui/hooks/useAnalyticsData.js +1 -657
- package/dist/browser/ui/index.js +5 -1283
- package/dist/browser/ui/renderers/analytics.markdown.js +5 -756
- package/dist/browser/ui/renderers/index.js +5 -756
- package/dist/browser/visualizations/catalog.js +1 -457
- package/dist/browser/visualizations/index.js +1 -611
- package/dist/browser/visualizations/specs.breakdown.js +1 -140
- package/dist/browser/visualizations/specs.performance.js +1 -198
- package/dist/browser/visualizations/widgets.js +1 -595
- package/dist/dashboard/dashboard.enum.js +1 -34
- package/dist/dashboard/dashboard.operation.js +1 -289
- package/dist/dashboard/dashboard.presentation.js +1 -200
- package/dist/dashboard/dashboard.schema.js +1 -126
- package/dist/dashboard/dashboard.test-spec.js +1 -213
- package/dist/dashboard/index.js +1 -299
- package/dist/dashboard.feature.js +1 -683
- package/dist/datasource/posthog-datasource.js +4 -289
- package/dist/docs/analytics-dashboard.docblock.js +5 -49
- package/dist/docs/index.js +5 -49
- package/dist/events.js +1 -81
- package/dist/example.js +1 -42
- package/dist/handlers/analytics.handlers.js +4 -278
- package/dist/handlers/index.js +7 -571
- package/dist/handlers/query.handlers.js +4 -294
- package/dist/index.js +12 -2317
- package/dist/node/dashboard/dashboard.enum.js +1 -34
- package/dist/node/dashboard/dashboard.operation.js +1 -289
- package/dist/node/dashboard/dashboard.presentation.js +1 -200
- package/dist/node/dashboard/dashboard.schema.js +1 -126
- package/dist/node/dashboard/dashboard.test-spec.js +1 -213
- package/dist/node/dashboard/index.js +1 -299
- package/dist/node/dashboard.feature.js +1 -683
- package/dist/node/datasource/posthog-datasource.js +4 -289
- package/dist/node/docs/analytics-dashboard.docblock.js +5 -49
- package/dist/node/docs/index.js +5 -49
- package/dist/node/events.js +1 -81
- package/dist/node/example.js +1 -42
- package/dist/node/handlers/analytics.handlers.js +4 -278
- package/dist/node/handlers/index.js +7 -571
- package/dist/node/handlers/query.handlers.js +4 -294
- package/dist/node/index.js +12 -2317
- package/dist/node/query/index.js +1 -159
- package/dist/node/query/query.enum.js +1 -11
- package/dist/node/query/query.operation.js +1 -154
- package/dist/node/query/query.presentation.js +1 -122
- package/dist/node/query/query.schema.js +1 -70
- package/dist/node/query/query.test-spec.js +1 -113
- package/dist/node/query-engine/index.js +4 -491
- package/dist/node/seeders/index.js +2 -20
- package/dist/node/ui/AnalyticsDashboard.js +1 -1115
- package/dist/node/ui/AnalyticsDashboard.widgets.js +1 -94
- package/dist/node/ui/AnalyticsQueriesTable.js +1 -188
- package/dist/node/ui/hooks/index.js +1 -660
- package/dist/node/ui/hooks/useAnalyticsData.js +1 -657
- package/dist/node/ui/index.js +5 -1283
- package/dist/node/ui/renderers/analytics.markdown.js +5 -756
- package/dist/node/ui/renderers/index.js +5 -756
- package/dist/node/visualizations/catalog.js +1 -457
- package/dist/node/visualizations/index.js +1 -611
- package/dist/node/visualizations/specs.breakdown.js +1 -140
- package/dist/node/visualizations/specs.performance.js +1 -198
- package/dist/node/visualizations/widgets.js +1 -595
- package/dist/query/index.js +1 -159
- package/dist/query/query.enum.js +1 -11
- package/dist/query/query.operation.js +1 -154
- package/dist/query/query.presentation.js +1 -122
- package/dist/query/query.schema.js +1 -70
- package/dist/query/query.test-spec.js +1 -113
- package/dist/query-engine/index.js +4 -491
- package/dist/seeders/index.js +2 -20
- package/dist/ui/AnalyticsDashboard.js +1 -1115
- package/dist/ui/AnalyticsDashboard.widgets.js +1 -94
- package/dist/ui/AnalyticsQueriesTable.js +1 -188
- package/dist/ui/hooks/index.js +1 -660
- package/dist/ui/hooks/useAnalyticsData.js +1 -657
- package/dist/ui/index.js +5 -1283
- package/dist/ui/renderers/analytics.markdown.js +5 -756
- package/dist/ui/renderers/index.js +5 -756
- package/dist/visualizations/catalog.js +1 -457
- package/dist/visualizations/index.js +1 -611
- package/dist/visualizations/specs.breakdown.js +1 -140
- package/dist/visualizations/specs.performance.js +1 -198
- package/dist/visualizations/widgets.js +1 -595
- package/package.json +13 -13
package/dist/index.js
CHANGED
|
@@ -1,2318 +1,13 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
// src/visualizations/specs.breakdown.ts
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
var
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
stability: "experimental",
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
...META,
|
|
15
|
-
key: "analytics.visualization.channel-mix",
|
|
16
|
-
title: "Channel Mix",
|
|
17
|
-
description: "Session distribution across acquisition channels.",
|
|
18
|
-
goal: "Explain which channels currently drive the largest share of traffic.",
|
|
19
|
-
context: "Marketing attribution dashboard."
|
|
20
|
-
},
|
|
21
|
-
source: { primary: QUERY_REF, resultPath: "data" },
|
|
22
|
-
visualization: {
|
|
23
|
-
kind: "pie",
|
|
24
|
-
nameDimension: "channel",
|
|
25
|
-
valueMeasure: "sessions",
|
|
26
|
-
dimensions: [
|
|
27
|
-
{
|
|
28
|
-
key: "channel",
|
|
29
|
-
label: "Channel",
|
|
30
|
-
dataPath: "channel",
|
|
31
|
-
type: "category"
|
|
32
|
-
}
|
|
33
|
-
],
|
|
34
|
-
measures: [{ key: "sessions", label: "Sessions", dataPath: "sessions" }],
|
|
35
|
-
table: { caption: "Sessions by acquisition channel." }
|
|
36
|
-
}
|
|
37
|
-
});
|
|
38
|
-
var EngagementHeatmapVisualization = defineVisualization({
|
|
39
|
-
meta: {
|
|
40
|
-
...META,
|
|
41
|
-
key: "analytics.visualization.engagement-heatmap",
|
|
42
|
-
title: "Engagement Heatmap",
|
|
43
|
-
description: "Average engagement score by weekday and time band.",
|
|
44
|
-
goal: "Reveal the highest-engagement time windows for product activity.",
|
|
45
|
-
context: "Usage analytics dashboard."
|
|
46
|
-
},
|
|
47
|
-
source: { primary: QUERY_REF, resultPath: "data" },
|
|
48
|
-
visualization: {
|
|
49
|
-
kind: "heatmap",
|
|
50
|
-
xDimension: "timeBand",
|
|
51
|
-
yDimension: "weekday",
|
|
52
|
-
valueMeasure: "engagementScore",
|
|
53
|
-
dimensions: [
|
|
54
|
-
{
|
|
55
|
-
key: "timeBand",
|
|
56
|
-
label: "Time Band",
|
|
57
|
-
dataPath: "timeBand",
|
|
58
|
-
type: "category"
|
|
59
|
-
},
|
|
60
|
-
{
|
|
61
|
-
key: "weekday",
|
|
62
|
-
label: "Weekday",
|
|
63
|
-
dataPath: "weekday",
|
|
64
|
-
type: "category"
|
|
65
|
-
}
|
|
66
|
-
],
|
|
67
|
-
measures: [
|
|
68
|
-
{
|
|
69
|
-
key: "engagementScore",
|
|
70
|
-
label: "Engagement",
|
|
71
|
-
dataPath: "engagementScore"
|
|
72
|
-
}
|
|
73
|
-
],
|
|
74
|
-
table: { caption: "Engagement score by weekday and time band." }
|
|
75
|
-
}
|
|
76
|
-
});
|
|
77
|
-
var ConversionFunnelVisualization = defineVisualization({
|
|
78
|
-
meta: {
|
|
79
|
-
...META,
|
|
80
|
-
key: "analytics.visualization.conversion-funnel",
|
|
81
|
-
title: "Conversion Funnel",
|
|
82
|
-
description: "Progression through the main acquisition funnel.",
|
|
83
|
-
goal: "Show where the product is losing the largest share of prospects.",
|
|
84
|
-
context: "Growth dashboard."
|
|
85
|
-
},
|
|
86
|
-
source: { primary: QUERY_REF, resultPath: "data" },
|
|
87
|
-
visualization: {
|
|
88
|
-
kind: "funnel",
|
|
89
|
-
nameDimension: "stage",
|
|
90
|
-
valueMeasure: "users",
|
|
91
|
-
sort: "descending",
|
|
92
|
-
dimensions: [
|
|
93
|
-
{ key: "stage", label: "Stage", dataPath: "stage", type: "category" }
|
|
94
|
-
],
|
|
95
|
-
measures: [{ key: "users", label: "Users", dataPath: "users" }],
|
|
96
|
-
table: { caption: "Users per conversion stage." }
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
var AccountCoverageGeoVisualization = defineVisualization({
|
|
100
|
-
meta: {
|
|
101
|
-
...META,
|
|
102
|
-
key: "analytics.visualization.account-coverage-geo",
|
|
103
|
-
title: "Account Coverage",
|
|
104
|
-
description: "High-value accounts plotted on a slippy-map surface.",
|
|
105
|
-
goal: "Locate where active commercial concentration is strongest.",
|
|
106
|
-
context: "Territory coverage dashboard."
|
|
107
|
-
},
|
|
108
|
-
source: { primary: QUERY_REF, resultPath: "data" },
|
|
109
|
-
visualization: {
|
|
110
|
-
kind: "geo",
|
|
111
|
-
mode: "slippy-map",
|
|
112
|
-
variant: "scatter",
|
|
113
|
-
nameDimension: "city",
|
|
114
|
-
latitudeDimension: "latitude",
|
|
115
|
-
longitudeDimension: "longitude",
|
|
116
|
-
valueMeasure: "accounts",
|
|
117
|
-
dimensions: [
|
|
118
|
-
{ key: "city", label: "City", dataPath: "city", type: "category" },
|
|
119
|
-
{
|
|
120
|
-
key: "latitude",
|
|
121
|
-
label: "Latitude",
|
|
122
|
-
dataPath: "latitude",
|
|
123
|
-
type: "latitude"
|
|
124
|
-
},
|
|
125
|
-
{
|
|
126
|
-
key: "longitude",
|
|
127
|
-
label: "Longitude",
|
|
128
|
-
dataPath: "longitude",
|
|
129
|
-
type: "longitude"
|
|
130
|
-
}
|
|
131
|
-
],
|
|
132
|
-
measures: [{ key: "accounts", label: "Accounts", dataPath: "accounts" }],
|
|
133
|
-
table: { caption: "Account concentration by city." }
|
|
134
|
-
}
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
// src/visualizations/specs.performance.ts
|
|
138
|
-
import { defineVisualization as defineVisualization2 } from "@contractspec/lib.contracts-spec/visualizations";
|
|
139
|
-
var QUERY_REF2 = { key: "analytics.query.execute", version: "1.0.0" };
|
|
140
|
-
var META2 = {
|
|
141
|
-
version: "1.0.0",
|
|
142
|
-
domain: "analytics",
|
|
143
|
-
stability: "experimental",
|
|
144
|
-
owners: ["@example.analytics-dashboard"],
|
|
145
|
-
tags: ["analytics", "dashboard", "visualization"]
|
|
146
|
-
};
|
|
147
|
-
var RevenueMetricVisualization = defineVisualization2({
|
|
148
|
-
meta: {
|
|
149
|
-
...META2,
|
|
150
|
-
key: "analytics.visualization.revenue-metric",
|
|
151
|
-
title: "Revenue Snapshot",
|
|
152
|
-
description: "Current recurring revenue with prior-period comparison.",
|
|
153
|
-
goal: "Highlight the headline commercial metric for the dashboard.",
|
|
154
|
-
context: "Executive revenue overview."
|
|
155
|
-
},
|
|
156
|
-
source: { primary: QUERY_REF2, resultPath: "data" },
|
|
157
|
-
visualization: {
|
|
158
|
-
kind: "metric",
|
|
159
|
-
measure: "totalRevenue",
|
|
160
|
-
comparisonMeasure: "priorRevenue",
|
|
161
|
-
dimensions: [
|
|
162
|
-
{ key: "period", label: "Period", dataPath: "period", type: "time" }
|
|
163
|
-
],
|
|
164
|
-
measures: [
|
|
165
|
-
{
|
|
166
|
-
key: "totalRevenue",
|
|
167
|
-
label: "Revenue",
|
|
168
|
-
dataPath: "totalRevenue",
|
|
169
|
-
format: "currency"
|
|
170
|
-
},
|
|
171
|
-
{
|
|
172
|
-
key: "priorRevenue",
|
|
173
|
-
label: "Prior Revenue",
|
|
174
|
-
dataPath: "priorRevenue",
|
|
175
|
-
format: "currency"
|
|
176
|
-
}
|
|
177
|
-
],
|
|
178
|
-
sparkline: { dimension: "period", measure: "totalRevenue" },
|
|
179
|
-
table: { caption: "Revenue trend and prior period values." }
|
|
180
|
-
}
|
|
181
|
-
});
|
|
182
|
-
var RevenueTrendVisualization = defineVisualization2({
|
|
183
|
-
meta: {
|
|
184
|
-
...META2,
|
|
185
|
-
key: "analytics.visualization.revenue-trend",
|
|
186
|
-
title: "Revenue Trend",
|
|
187
|
-
description: "Monthly revenue progression for the current quarter.",
|
|
188
|
-
goal: "Track whether revenue growth is accelerating or stalling.",
|
|
189
|
-
context: "Quarterly commercial dashboard."
|
|
190
|
-
},
|
|
191
|
-
source: { primary: QUERY_REF2, resultPath: "data" },
|
|
192
|
-
visualization: {
|
|
193
|
-
kind: "cartesian",
|
|
194
|
-
variant: "line",
|
|
195
|
-
xDimension: "date",
|
|
196
|
-
yMeasures: ["revenue"],
|
|
197
|
-
dimensions: [
|
|
198
|
-
{ key: "date", label: "Month", dataPath: "date", type: "time" }
|
|
199
|
-
],
|
|
200
|
-
measures: [
|
|
201
|
-
{
|
|
202
|
-
key: "revenue",
|
|
203
|
-
label: "Revenue",
|
|
204
|
-
dataPath: "revenue",
|
|
205
|
-
format: "currency",
|
|
206
|
-
color: "#0f766e"
|
|
207
|
-
}
|
|
208
|
-
],
|
|
209
|
-
thresholds: [
|
|
210
|
-
{ key: "target", value: 140000, label: "Target", color: "#dc2626" }
|
|
211
|
-
],
|
|
212
|
-
table: { caption: "Monthly revenue values." }
|
|
213
|
-
}
|
|
214
|
-
});
|
|
215
|
-
var RegionalRevenueVisualization = defineVisualization2({
|
|
216
|
-
meta: {
|
|
217
|
-
...META2,
|
|
218
|
-
key: "analytics.visualization.regional-revenue",
|
|
219
|
-
title: "Regional Revenue",
|
|
220
|
-
description: "Revenue split by sales territory.",
|
|
221
|
-
goal: "Compare the strongest and weakest performing territories.",
|
|
222
|
-
context: "Territory planning and commercial comparison."
|
|
223
|
-
},
|
|
224
|
-
source: { primary: QUERY_REF2, resultPath: "data" },
|
|
225
|
-
visualization: {
|
|
226
|
-
kind: "cartesian",
|
|
227
|
-
variant: "bar",
|
|
228
|
-
xDimension: "region",
|
|
229
|
-
yMeasures: ["revenue"],
|
|
230
|
-
dimensions: [
|
|
231
|
-
{ key: "region", label: "Region", dataPath: "region", type: "category" }
|
|
232
|
-
],
|
|
233
|
-
measures: [
|
|
234
|
-
{
|
|
235
|
-
key: "revenue",
|
|
236
|
-
label: "Revenue",
|
|
237
|
-
dataPath: "revenue",
|
|
238
|
-
format: "currency",
|
|
239
|
-
color: "#1d4ed8"
|
|
240
|
-
}
|
|
241
|
-
],
|
|
242
|
-
table: { caption: "Revenue by region." }
|
|
243
|
-
}
|
|
244
|
-
});
|
|
245
|
-
var RetentionAreaVisualization = defineVisualization2({
|
|
246
|
-
meta: {
|
|
247
|
-
...META2,
|
|
248
|
-
key: "analytics.visualization.retention-area",
|
|
249
|
-
title: "Retention Curve",
|
|
250
|
-
description: "Weekly retention progression across the active cohort.",
|
|
251
|
-
goal: "Show whether user retention remains above the desired floor.",
|
|
252
|
-
context: "Product health dashboard."
|
|
253
|
-
},
|
|
254
|
-
source: { primary: QUERY_REF2, resultPath: "data" },
|
|
255
|
-
visualization: {
|
|
256
|
-
kind: "cartesian",
|
|
257
|
-
variant: "area",
|
|
258
|
-
xDimension: "week",
|
|
259
|
-
yMeasures: ["retentionRate"],
|
|
260
|
-
dimensions: [
|
|
261
|
-
{ key: "week", label: "Week", dataPath: "week", type: "category" }
|
|
262
|
-
],
|
|
263
|
-
measures: [
|
|
264
|
-
{
|
|
265
|
-
key: "retentionRate",
|
|
266
|
-
label: "Retention",
|
|
267
|
-
dataPath: "retentionRate",
|
|
268
|
-
format: "percentage",
|
|
269
|
-
color: "#16a34a"
|
|
270
|
-
}
|
|
271
|
-
],
|
|
272
|
-
thresholds: [
|
|
273
|
-
{ key: "floor", value: 0.5, label: "Floor", color: "#f59e0b" }
|
|
274
|
-
],
|
|
275
|
-
table: { caption: "Weekly retention rate." }
|
|
276
|
-
}
|
|
277
|
-
});
|
|
278
|
-
var PipelineScatterVisualization = defineVisualization2({
|
|
279
|
-
meta: {
|
|
280
|
-
...META2,
|
|
281
|
-
key: "analytics.visualization.pipeline-scatter",
|
|
282
|
-
title: "Pipeline Velocity",
|
|
283
|
-
description: "Deal-cycle length against win rate for active accounts.",
|
|
284
|
-
goal: "Spot outliers where the sales cycle is long but conversion remains weak.",
|
|
285
|
-
context: "Commercial operations dashboard."
|
|
286
|
-
},
|
|
287
|
-
source: { primary: QUERY_REF2, resultPath: "data" },
|
|
288
|
-
visualization: {
|
|
289
|
-
kind: "cartesian",
|
|
290
|
-
variant: "scatter",
|
|
291
|
-
xDimension: "cycleDays",
|
|
292
|
-
yMeasures: ["winRate"],
|
|
293
|
-
dimensions: [
|
|
294
|
-
{
|
|
295
|
-
key: "cycleDays",
|
|
296
|
-
label: "Cycle Days",
|
|
297
|
-
dataPath: "cycleDays",
|
|
298
|
-
type: "number"
|
|
299
|
-
}
|
|
300
|
-
],
|
|
301
|
-
measures: [
|
|
302
|
-
{
|
|
303
|
-
key: "winRate",
|
|
304
|
-
label: "Win Rate",
|
|
305
|
-
dataPath: "winRate",
|
|
306
|
-
format: "percentage",
|
|
307
|
-
color: "#7c3aed"
|
|
308
|
-
},
|
|
309
|
-
{
|
|
310
|
-
key: "arr",
|
|
311
|
-
label: "ARR",
|
|
312
|
-
dataPath: "arr",
|
|
313
|
-
format: "currency"
|
|
314
|
-
}
|
|
315
|
-
],
|
|
316
|
-
series: [
|
|
317
|
-
{
|
|
318
|
-
key: "pipeline",
|
|
319
|
-
label: "Accounts",
|
|
320
|
-
measure: "winRate",
|
|
321
|
-
type: "scatter",
|
|
322
|
-
color: "#7c3aed"
|
|
323
|
-
}
|
|
324
|
-
],
|
|
325
|
-
table: { caption: "Sales cycle and win rate per account." }
|
|
326
|
-
}
|
|
327
|
-
});
|
|
328
|
-
|
|
329
|
-
// src/visualizations/catalog.ts
|
|
330
|
-
import { VisualizationRegistry } from "@contractspec/lib.contracts-spec/visualizations";
|
|
331
|
-
var AnalyticsVisualizationSpecs = [
|
|
332
|
-
RevenueMetricVisualization,
|
|
333
|
-
RevenueTrendVisualization,
|
|
334
|
-
RegionalRevenueVisualization,
|
|
335
|
-
RetentionAreaVisualization,
|
|
336
|
-
PipelineScatterVisualization,
|
|
337
|
-
ChannelMixVisualization,
|
|
338
|
-
EngagementHeatmapVisualization,
|
|
339
|
-
ConversionFunnelVisualization,
|
|
340
|
-
AccountCoverageGeoVisualization
|
|
341
|
-
];
|
|
342
|
-
var AnalyticsVisualizationRegistry = new VisualizationRegistry([
|
|
343
|
-
...AnalyticsVisualizationSpecs
|
|
344
|
-
]);
|
|
345
|
-
var AnalyticsVisualizationRefs = AnalyticsVisualizationSpecs.map((spec) => refOf(spec));
|
|
346
|
-
var AnalyticsVisualizationSpecMap = new Map(AnalyticsVisualizationSpecs.map((spec) => [
|
|
347
|
-
visualizationRefKey(spec.meta),
|
|
348
|
-
spec
|
|
349
|
-
]));
|
|
350
|
-
var AnalyticsVisualizationSampleData = {
|
|
351
|
-
[visualizationRefKey(RevenueMetricVisualization.meta)]: {
|
|
352
|
-
data: [
|
|
353
|
-
{ period: "2025-11-01", totalRevenue: 112000, priorRevenue: 103000 },
|
|
354
|
-
{ period: "2025-12-01", totalRevenue: 119000, priorRevenue: 110000 },
|
|
355
|
-
{ period: "2026-01-01", totalRevenue: 126500, priorRevenue: 116000 },
|
|
356
|
-
{ period: "2026-02-01", totalRevenue: 133000, priorRevenue: 124000 },
|
|
357
|
-
{ period: "2026-03-01", totalRevenue: 145500, priorRevenue: 133000 }
|
|
358
|
-
]
|
|
359
|
-
},
|
|
360
|
-
[visualizationRefKey(RevenueTrendVisualization.meta)]: {
|
|
361
|
-
data: [
|
|
362
|
-
{ date: "2025-11-01", revenue: 112000 },
|
|
363
|
-
{ date: "2025-12-01", revenue: 119000 },
|
|
364
|
-
{ date: "2026-01-01", revenue: 126500 },
|
|
365
|
-
{ date: "2026-02-01", revenue: 133000 },
|
|
366
|
-
{ date: "2026-03-01", revenue: 145500 }
|
|
367
|
-
]
|
|
368
|
-
},
|
|
369
|
-
[visualizationRefKey(RegionalRevenueVisualization.meta)]: {
|
|
370
|
-
data: [
|
|
371
|
-
{ region: "North America", revenue: 210000 },
|
|
372
|
-
{ region: "EMEA", revenue: 174000 },
|
|
373
|
-
{ region: "APAC", revenue: 132000 },
|
|
374
|
-
{ region: "LATAM", revenue: 88000 }
|
|
375
|
-
]
|
|
376
|
-
},
|
|
377
|
-
[visualizationRefKey(RetentionAreaVisualization.meta)]: {
|
|
378
|
-
data: [
|
|
379
|
-
{ week: "Week 1", retentionRate: 0.71 },
|
|
380
|
-
{ week: "Week 2", retentionRate: 0.66 },
|
|
381
|
-
{ week: "Week 3", retentionRate: 0.62 },
|
|
382
|
-
{ week: "Week 4", retentionRate: 0.58 },
|
|
383
|
-
{ week: "Week 5", retentionRate: 0.55 },
|
|
384
|
-
{ week: "Week 6", retentionRate: 0.53 }
|
|
385
|
-
]
|
|
386
|
-
},
|
|
387
|
-
[visualizationRefKey(PipelineScatterVisualization.meta)]: {
|
|
388
|
-
data: [
|
|
389
|
-
{ cycleDays: 18, winRate: 0.31, arr: 82000 },
|
|
390
|
-
{ cycleDays: 26, winRate: 0.44, arr: 65000 },
|
|
391
|
-
{ cycleDays: 33, winRate: 0.27, arr: 91000 },
|
|
392
|
-
{ cycleDays: 14, winRate: 0.56, arr: 47000 },
|
|
393
|
-
{ cycleDays: 21, winRate: 0.48, arr: 59000 },
|
|
394
|
-
{ cycleDays: 39, winRate: 0.22, arr: 114000 }
|
|
395
|
-
]
|
|
396
|
-
},
|
|
397
|
-
[visualizationRefKey(ChannelMixVisualization.meta)]: {
|
|
398
|
-
data: [
|
|
399
|
-
{ channel: "Direct", sessions: 4200 },
|
|
400
|
-
{ channel: "Organic Search", sessions: 3600 },
|
|
401
|
-
{ channel: "Paid Search", sessions: 2100 },
|
|
402
|
-
{ channel: "Partner", sessions: 1400 },
|
|
403
|
-
{ channel: "Referral", sessions: 900 }
|
|
404
|
-
]
|
|
405
|
-
},
|
|
406
|
-
[visualizationRefKey(EngagementHeatmapVisualization.meta)]: {
|
|
407
|
-
data: [
|
|
408
|
-
{ weekday: "Mon", timeBand: "09:00", engagementScore: 74 },
|
|
409
|
-
{ weekday: "Mon", timeBand: "13:00", engagementScore: 82 },
|
|
410
|
-
{ weekday: "Tue", timeBand: "09:00", engagementScore: 69 },
|
|
411
|
-
{ weekday: "Tue", timeBand: "13:00", engagementScore: 88 },
|
|
412
|
-
{ weekday: "Wed", timeBand: "09:00", engagementScore: 77 },
|
|
413
|
-
{ weekday: "Wed", timeBand: "13:00", engagementScore: 91 },
|
|
414
|
-
{ weekday: "Thu", timeBand: "09:00", engagementScore: 72 },
|
|
415
|
-
{ weekday: "Thu", timeBand: "13:00", engagementScore: 86 },
|
|
416
|
-
{ weekday: "Fri", timeBand: "09:00", engagementScore: 65 },
|
|
417
|
-
{ weekday: "Fri", timeBand: "13:00", engagementScore: 79 }
|
|
418
|
-
]
|
|
419
|
-
},
|
|
420
|
-
[visualizationRefKey(ConversionFunnelVisualization.meta)]: {
|
|
421
|
-
data: [
|
|
422
|
-
{ stage: "Visited Site", users: 12000 },
|
|
423
|
-
{ stage: "Started Trial", users: 4200 },
|
|
424
|
-
{ stage: "Activated Workspace", users: 2400 },
|
|
425
|
-
{ stage: "Requested Demo", users: 980 },
|
|
426
|
-
{ stage: "Closed Won", users: 310 }
|
|
427
|
-
]
|
|
428
|
-
},
|
|
429
|
-
[visualizationRefKey(AccountCoverageGeoVisualization.meta)]: {
|
|
430
|
-
data: [
|
|
431
|
-
{ city: "Paris", latitude: 48.8566, longitude: 2.3522, accounts: 48 },
|
|
432
|
-
{ city: "London", latitude: 51.5072, longitude: -0.1276, accounts: 62 },
|
|
433
|
-
{ city: "New York", latitude: 40.7128, longitude: -74.006, accounts: 71 },
|
|
434
|
-
{ city: "Toronto", latitude: 43.6532, longitude: -79.3832, accounts: 36 },
|
|
435
|
-
{
|
|
436
|
-
city: "Singapore",
|
|
437
|
-
latitude: 1.3521,
|
|
438
|
-
longitude: 103.8198,
|
|
439
|
-
accounts: 29
|
|
440
|
-
}
|
|
441
|
-
]
|
|
442
|
-
}
|
|
443
|
-
};
|
|
444
|
-
function refOf(spec) {
|
|
445
|
-
return { key: spec.meta.key, version: spec.meta.version };
|
|
446
|
-
}
|
|
447
|
-
function visualizationRefKey(ref) {
|
|
448
|
-
return `${ref.key}.v${ref.version}`;
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
// src/visualizations/widgets.ts
|
|
452
|
-
var LEGACY_VISUALIZATION_REFS = {
|
|
453
|
-
METRIC: refOf(RevenueMetricVisualization),
|
|
454
|
-
LINE_CHART: refOf(RevenueTrendVisualization),
|
|
455
|
-
BAR_CHART: refOf(RegionalRevenueVisualization),
|
|
456
|
-
AREA_CHART: refOf(RetentionAreaVisualization),
|
|
457
|
-
SCATTER_PLOT: refOf(PipelineScatterVisualization),
|
|
458
|
-
PIE_CHART: refOf(ChannelMixVisualization),
|
|
459
|
-
HEATMAP: refOf(EngagementHeatmapVisualization),
|
|
460
|
-
FUNNEL: refOf(ConversionFunnelVisualization),
|
|
461
|
-
MAP: refOf(AccountCoverageGeoVisualization)
|
|
462
|
-
};
|
|
463
|
-
function createExampleWidgets(dashboardId) {
|
|
464
|
-
return [
|
|
465
|
-
widget(dashboardId, "widget_revenue_metric", "Revenue Snapshot", "METRIC", 0, 0, 4, 2, {
|
|
466
|
-
layout: "single",
|
|
467
|
-
bindings: [binding(RevenueMetricVisualization, 200)]
|
|
468
|
-
}),
|
|
469
|
-
widget(dashboardId, "widget_revenue_trend", "Revenue Trend", "LINE_CHART", 4, 0, 8, 4, {
|
|
470
|
-
layout: "single",
|
|
471
|
-
bindings: [binding(RevenueTrendVisualization)]
|
|
472
|
-
}),
|
|
473
|
-
widget(dashboardId, "widget_regional_revenue", "Regional Revenue", "BAR_CHART", 0, 2, 6, 4, {
|
|
474
|
-
layout: "single",
|
|
475
|
-
bindings: [binding(RegionalRevenueVisualization)]
|
|
476
|
-
}),
|
|
477
|
-
widget(dashboardId, "widget_channel_mix", "Channel Mix", "PIE_CHART", 6, 2, 6, 4, {
|
|
478
|
-
layout: "single",
|
|
479
|
-
bindings: [binding(ChannelMixVisualization)]
|
|
480
|
-
}),
|
|
481
|
-
widget(dashboardId, "widget_retention", "Retention Curve", "AREA_CHART", 0, 6, 6, 4, {
|
|
482
|
-
layout: "single",
|
|
483
|
-
bindings: [binding(RetentionAreaVisualization)]
|
|
484
|
-
}),
|
|
485
|
-
widget(dashboardId, "widget_pipeline", "Pipeline Velocity", "SCATTER_PLOT", 6, 6, 6, 4, {
|
|
486
|
-
layout: "single",
|
|
487
|
-
bindings: [binding(PipelineScatterVisualization)]
|
|
488
|
-
}),
|
|
489
|
-
widget(dashboardId, "widget_heatmap", "Engagement Heatmap", "HEATMAP", 0, 10, 8, 4, {
|
|
490
|
-
layout: "single",
|
|
491
|
-
bindings: [binding(EngagementHeatmapVisualization)]
|
|
492
|
-
}),
|
|
493
|
-
widget(dashboardId, "widget_funnel", "Conversion Funnel", "FUNNEL", 8, 10, 4, 4, {
|
|
494
|
-
layout: "single",
|
|
495
|
-
bindings: [binding(ConversionFunnelVisualization)]
|
|
496
|
-
}),
|
|
497
|
-
widget(dashboardId, "widget_geo", "Account Coverage", "MAP", 0, 14, 12, 5, {
|
|
498
|
-
layout: "single",
|
|
499
|
-
bindings: [binding(AccountCoverageGeoVisualization, 360)]
|
|
500
|
-
}),
|
|
501
|
-
widget(dashboardId, "widget_comparison", "Commercial Comparison", "EMBED", 0, 19, 12, 6, {
|
|
502
|
-
layout: "comparison",
|
|
503
|
-
description: "Compare regional distribution, channel balance, and funnel shape.",
|
|
504
|
-
bindings: [
|
|
505
|
-
binding(RegionalRevenueVisualization, 240),
|
|
506
|
-
binding(ChannelMixVisualization, 240),
|
|
507
|
-
binding(ConversionFunnelVisualization, 240)
|
|
508
|
-
]
|
|
509
|
-
}),
|
|
510
|
-
widget(dashboardId, "widget_timeline", "Growth Timeline", "EMBED", 0, 25, 12, 6, {
|
|
511
|
-
layout: "timeline",
|
|
512
|
-
description: "Track revenue and retention over the same reporting cadence.",
|
|
513
|
-
bindings: [
|
|
514
|
-
binding(RevenueTrendVisualization, 220),
|
|
515
|
-
binding(RetentionAreaVisualization, 220)
|
|
516
|
-
]
|
|
517
|
-
})
|
|
518
|
-
];
|
|
519
|
-
}
|
|
520
|
-
function resolveAnalyticsWidget(widget) {
|
|
521
|
-
const config = parseWidgetConfig(widget);
|
|
522
|
-
const bindings = config.bindings.map((binding) => {
|
|
523
|
-
const spec = AnalyticsVisualizationSpecMap.get(visualizationRefKey(binding.ref));
|
|
524
|
-
if (!spec)
|
|
525
|
-
return null;
|
|
526
|
-
return {
|
|
527
|
-
key: `${widget.id}:${visualizationRefKey(binding.ref)}`,
|
|
528
|
-
spec,
|
|
529
|
-
data: binding.data,
|
|
530
|
-
title: binding.title ?? spec.meta.title,
|
|
531
|
-
description: binding.description ?? spec.meta.description,
|
|
532
|
-
height: binding.height
|
|
533
|
-
};
|
|
534
|
-
}).filter((binding) => Boolean(binding));
|
|
535
|
-
if (!bindings.length)
|
|
536
|
-
return null;
|
|
537
|
-
return {
|
|
538
|
-
id: widget.id,
|
|
539
|
-
name: widget.name,
|
|
540
|
-
description: config.description,
|
|
541
|
-
layout: config.layout,
|
|
542
|
-
gridX: widget.gridX,
|
|
543
|
-
gridY: widget.gridY,
|
|
544
|
-
gridWidth: widget.gridWidth,
|
|
545
|
-
gridHeight: widget.gridHeight,
|
|
546
|
-
bindings
|
|
547
|
-
};
|
|
548
|
-
}
|
|
549
|
-
function parseWidgetConfig(widget) {
|
|
550
|
-
if (isAnalyticsWidgetConfig(widget.config)) {
|
|
551
|
-
return widget.config;
|
|
552
|
-
}
|
|
553
|
-
const legacyRef = LEGACY_VISUALIZATION_REFS[widget.type];
|
|
554
|
-
return legacyRef ? {
|
|
555
|
-
layout: "single",
|
|
556
|
-
bindings: [
|
|
557
|
-
{
|
|
558
|
-
ref: legacyRef,
|
|
559
|
-
data: AnalyticsVisualizationSampleData[visualizationRefKey(legacyRef)]
|
|
560
|
-
}
|
|
561
|
-
]
|
|
562
|
-
} : { layout: "single", bindings: [] };
|
|
563
|
-
}
|
|
564
|
-
function binding(spec, height = 280) {
|
|
565
|
-
return {
|
|
566
|
-
ref: refOf(spec),
|
|
567
|
-
data: AnalyticsVisualizationSampleData[visualizationRefKey(spec.meta)],
|
|
568
|
-
height
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
function widget(dashboardId, id, name, type, gridX, gridY, gridWidth, gridHeight, config) {
|
|
572
|
-
const now = new Date;
|
|
573
|
-
return {
|
|
574
|
-
id,
|
|
575
|
-
dashboardId,
|
|
576
|
-
name,
|
|
577
|
-
type,
|
|
578
|
-
gridX,
|
|
579
|
-
gridY,
|
|
580
|
-
gridWidth,
|
|
581
|
-
gridHeight,
|
|
582
|
-
config,
|
|
583
|
-
createdAt: now,
|
|
584
|
-
updatedAt: now
|
|
585
|
-
};
|
|
586
|
-
}
|
|
587
|
-
function isAnalyticsWidgetConfig(value) {
|
|
588
|
-
if (!value || typeof value !== "object")
|
|
589
|
-
return false;
|
|
590
|
-
const candidate = value;
|
|
591
|
-
return (candidate.layout === "single" || candidate.layout === "comparison" || candidate.layout === "timeline") && Array.isArray(candidate.bindings);
|
|
592
|
-
}
|
|
593
|
-
// src/dashboard.feature.ts
|
|
594
|
-
import { defineFeature } from "@contractspec/lib.contracts-spec";
|
|
595
|
-
var AnalyticsDashboardFeature = defineFeature({
|
|
596
|
-
meta: {
|
|
597
|
-
key: "analytics-dashboard",
|
|
598
|
-
version: "1.0.0",
|
|
599
|
-
title: "Analytics Dashboard",
|
|
600
|
-
description: "Analytics dashboards with customizable widgets and queries",
|
|
601
|
-
domain: "analytics",
|
|
602
|
-
owners: ["@analytics-dashboard"],
|
|
603
|
-
tags: ["analytics", "dashboards", "widgets", "queries"],
|
|
604
|
-
stability: "experimental"
|
|
605
|
-
},
|
|
606
|
-
operations: [
|
|
607
|
-
{ key: "analytics.dashboard.create", version: "1.0.0" },
|
|
608
|
-
{ key: "analytics.dashboard.list", version: "1.0.0" },
|
|
609
|
-
{ key: "analytics.dashboard.get", version: "1.0.0" },
|
|
610
|
-
{ key: "analytics.widget.add", version: "1.0.0" },
|
|
611
|
-
{ key: "analytics.query.create", version: "1.0.0" },
|
|
612
|
-
{ key: "analytics.query.execute", version: "1.0.0" }
|
|
613
|
-
],
|
|
614
|
-
events: [
|
|
615
|
-
{ key: "analytics.dashboard.created", version: "1.0.0" },
|
|
616
|
-
{ key: "analytics.widget.added", version: "1.0.0" },
|
|
617
|
-
{ key: "analytics.query.created", version: "1.0.0" }
|
|
618
|
-
],
|
|
619
|
-
presentations: [
|
|
620
|
-
{ key: "analytics.dashboard.viewList", version: "1.0.0" },
|
|
621
|
-
{ key: "analytics.dashboard.view", version: "1.0.0" },
|
|
622
|
-
{ key: "analytics.dashboard.editor", version: "1.0.0" },
|
|
623
|
-
{ key: "analytics.query.list", version: "1.0.0" },
|
|
624
|
-
{ key: "analytics.query.builder", version: "1.0.0" }
|
|
625
|
-
],
|
|
626
|
-
visualizations: [...AnalyticsVisualizationRefs],
|
|
627
|
-
opToPresentation: [
|
|
628
|
-
{
|
|
629
|
-
op: { key: "analytics.dashboard.list", version: "1.0.0" },
|
|
630
|
-
pres: { key: "analytics.dashboard.viewList", version: "1.0.0" }
|
|
631
|
-
},
|
|
632
|
-
{
|
|
633
|
-
op: { key: "analytics.dashboard.get", version: "1.0.0" },
|
|
634
|
-
pres: { key: "analytics.dashboard.view", version: "1.0.0" }
|
|
635
|
-
},
|
|
636
|
-
{
|
|
637
|
-
op: { key: "analytics.dashboard.create", version: "1.0.0" },
|
|
638
|
-
pres: { key: "analytics.dashboard.editor", version: "1.0.0" }
|
|
639
|
-
},
|
|
640
|
-
{
|
|
641
|
-
op: { key: "analytics.query.create", version: "1.0.0" },
|
|
642
|
-
pres: { key: "analytics.query.builder", version: "1.0.0" }
|
|
643
|
-
}
|
|
644
|
-
],
|
|
645
|
-
presentationsTargets: [
|
|
646
|
-
{
|
|
647
|
-
key: "analytics.dashboard.viewList",
|
|
648
|
-
version: "1.0.0",
|
|
649
|
-
targets: ["react", "markdown", "application/json"]
|
|
650
|
-
},
|
|
651
|
-
{
|
|
652
|
-
key: "analytics.dashboard.view",
|
|
653
|
-
version: "1.0.0",
|
|
654
|
-
targets: ["react", "markdown"]
|
|
655
|
-
},
|
|
656
|
-
{
|
|
657
|
-
key: "analytics.dashboard.editor",
|
|
658
|
-
version: "1.0.0",
|
|
659
|
-
targets: ["react"]
|
|
660
|
-
},
|
|
661
|
-
{
|
|
662
|
-
key: "analytics.query.builder",
|
|
663
|
-
version: "1.0.0",
|
|
664
|
-
targets: ["react"]
|
|
665
|
-
}
|
|
666
|
-
],
|
|
667
|
-
capabilities: {
|
|
668
|
-
requires: [
|
|
669
|
-
{ key: "identity", version: "1.0.0" },
|
|
670
|
-
{ key: "metering", version: "1.0.0" },
|
|
671
|
-
{ key: "audit-trail", version: "1.0.0" }
|
|
672
|
-
]
|
|
673
|
-
},
|
|
674
|
-
telemetry: [{ key: "analytics-dashboard.telemetry", version: "1.0.0" }],
|
|
675
|
-
docs: [
|
|
676
|
-
"docs.examples.analytics-dashboard",
|
|
677
|
-
"docs.examples.analytics-dashboard.goal",
|
|
678
|
-
"docs.examples.analytics-dashboard.usage",
|
|
679
|
-
"docs.examples.analytics-dashboard.constraints"
|
|
680
|
-
]
|
|
681
|
-
});
|
|
682
|
-
|
|
683
|
-
// src/datasource/posthog-datasource.ts
|
|
684
|
-
class PosthogQueryEngine {
|
|
685
|
-
reader;
|
|
686
|
-
defaultLimit;
|
|
687
|
-
constructor(reader, options = {}) {
|
|
688
|
-
this.reader = reader;
|
|
689
|
-
this.defaultLimit = options.defaultLimit ?? 100;
|
|
690
|
-
}
|
|
691
|
-
async execute(definition, params) {
|
|
692
|
-
const startTime = Date.now();
|
|
693
|
-
const validation = this.validateQuery(definition);
|
|
694
|
-
if (!validation.valid) {
|
|
695
|
-
return {
|
|
696
|
-
data: [],
|
|
697
|
-
columns: [],
|
|
698
|
-
rowCount: 0,
|
|
699
|
-
executionTimeMs: Date.now() - startTime,
|
|
700
|
-
cached: false,
|
|
701
|
-
error: validation.errors.join(", ")
|
|
702
|
-
};
|
|
703
|
-
}
|
|
704
|
-
if (!this.reader.queryHogQL) {
|
|
705
|
-
return {
|
|
706
|
-
data: [],
|
|
707
|
-
columns: [],
|
|
708
|
-
rowCount: 0,
|
|
709
|
-
executionTimeMs: Date.now() - startTime,
|
|
710
|
-
cached: false,
|
|
711
|
-
error: "Analytics reader does not support HogQL queries."
|
|
712
|
-
};
|
|
713
|
-
}
|
|
714
|
-
try {
|
|
715
|
-
const result = await this.executeHogQL(definition, params);
|
|
716
|
-
return {
|
|
717
|
-
data: result.data,
|
|
718
|
-
columns: result.columns,
|
|
719
|
-
rowCount: result.rowCount,
|
|
720
|
-
executionTimeMs: Date.now() - startTime,
|
|
721
|
-
cached: false
|
|
722
|
-
};
|
|
723
|
-
} catch (error) {
|
|
724
|
-
return {
|
|
725
|
-
data: [],
|
|
726
|
-
columns: [],
|
|
727
|
-
rowCount: 0,
|
|
728
|
-
executionTimeMs: Date.now() - startTime,
|
|
729
|
-
cached: false,
|
|
730
|
-
error: error instanceof Error ? error.message : "Unknown error"
|
|
731
|
-
};
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
validateQuery(definition) {
|
|
735
|
-
const errors = [];
|
|
736
|
-
if (definition.type === "SQL" && !definition.sql) {
|
|
737
|
-
errors.push("SQL query is missing.");
|
|
738
|
-
}
|
|
739
|
-
if (definition.type === "AGGREGATION" && !definition.aggregation) {
|
|
740
|
-
errors.push("Aggregation definition is missing.");
|
|
741
|
-
}
|
|
742
|
-
if (definition.type === "METRIC" && !definition.metricIds?.length) {
|
|
743
|
-
errors.push("Metric IDs are missing.");
|
|
744
|
-
}
|
|
745
|
-
if (definition.type === "CUSTOM" && !definition.custom?.handler) {
|
|
746
|
-
errors.push("Custom handler is missing.");
|
|
747
|
-
}
|
|
748
|
-
return { valid: errors.length === 0, errors };
|
|
749
|
-
}
|
|
750
|
-
async executeHogQL(definition, params) {
|
|
751
|
-
if (!this.reader.queryHogQL) {
|
|
752
|
-
throw new Error("Analytics reader does not support HogQL queries.");
|
|
753
|
-
}
|
|
754
|
-
if (definition.type === "SQL") {
|
|
755
|
-
const result = await this.reader.queryHogQL({
|
|
756
|
-
query: definition.sql ?? "",
|
|
757
|
-
values: params.parameters ?? {}
|
|
758
|
-
});
|
|
759
|
-
return mapHogqlResult(result);
|
|
760
|
-
}
|
|
761
|
-
if (definition.type === "AGGREGATION" && definition.aggregation) {
|
|
762
|
-
const { query, values } = buildAggregationQuery(definition.aggregation, params);
|
|
763
|
-
const result = await this.reader.queryHogQL({ query, values });
|
|
764
|
-
return mapHogqlResult(result);
|
|
765
|
-
}
|
|
766
|
-
if (definition.type === "METRIC" && definition.metricIds) {
|
|
767
|
-
const { query, values } = buildMetricQuery(definition.metricIds, params);
|
|
768
|
-
const result = await this.reader.queryHogQL({ query, values });
|
|
769
|
-
return mapHogqlResult(result);
|
|
770
|
-
}
|
|
771
|
-
throw new Error("Unsupported query type for PostHog datasource.");
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
function createPosthogQueryEngine(reader, options) {
|
|
775
|
-
return new PosthogQueryEngine(reader, options);
|
|
776
|
-
}
|
|
777
|
-
function buildMetricQuery(metricIds, params) {
|
|
778
|
-
const range = resolveDateRange(params);
|
|
779
|
-
const values = {
|
|
780
|
-
dateFrom: range?.from.toISOString(),
|
|
781
|
-
dateTo: range?.to.toISOString()
|
|
782
|
-
};
|
|
783
|
-
const metricClauses = metricIds.map((metricId, index) => {
|
|
784
|
-
values[`metric${index}`] = metricId;
|
|
785
|
-
return `event = {metric${index}}`;
|
|
786
|
-
});
|
|
787
|
-
const whereClauses = [
|
|
788
|
-
metricClauses.length ? `(${metricClauses.join(" or ")})` : "",
|
|
789
|
-
range ? "timestamp >= {dateFrom} and timestamp < {dateTo}" : ""
|
|
790
|
-
].filter(Boolean).join(" and ");
|
|
791
|
-
return {
|
|
792
|
-
query: [
|
|
793
|
-
"select",
|
|
794
|
-
" event as metric,",
|
|
795
|
-
" count() as total",
|
|
796
|
-
"from events",
|
|
797
|
-
whereClauses ? `where ${whereClauses}` : "",
|
|
798
|
-
"group by metric"
|
|
799
|
-
].filter(Boolean).join(`
|
|
800
|
-
`),
|
|
801
|
-
values
|
|
802
|
-
};
|
|
803
|
-
}
|
|
804
|
-
function buildAggregationQuery(aggregation, params) {
|
|
805
|
-
const measures = aggregation.measures.map((measure) => ({
|
|
806
|
-
...measure,
|
|
807
|
-
expression: buildMeasureExpression(measure.field, measure.aggregation)
|
|
808
|
-
}));
|
|
809
|
-
const dimensions = aggregation.dimensions.map((dimension) => ({
|
|
810
|
-
...dimension,
|
|
811
|
-
expression: buildDimensionExpression(dimension.field, dimension.type, dimension.granularity)
|
|
812
|
-
}));
|
|
813
|
-
const selections = [
|
|
814
|
-
...dimensions.map((dimension) => `${dimension.expression} as ${dimension.name}`),
|
|
815
|
-
...measures.map((measure) => `${measure.expression} as ${measure.name}`)
|
|
816
|
-
];
|
|
817
|
-
const values = {};
|
|
818
|
-
const filters = buildFilterClauses(aggregation, params, values);
|
|
819
|
-
const limit = aggregation.limit ?? 100;
|
|
820
|
-
const orderBy = aggregation.orderBy?.length ? `order by ${aggregation.orderBy.map((order) => `${order.field} ${order.direction}`).join(", ")}` : "";
|
|
821
|
-
return {
|
|
822
|
-
query: [
|
|
823
|
-
"select",
|
|
824
|
-
` ${selections.join(`,
|
|
825
|
-
`)}`,
|
|
826
|
-
`from ${aggregation.source}`,
|
|
827
|
-
filters.length ? `where ${filters.join(" and ")}` : "",
|
|
828
|
-
dimensions.length ? `group by ${dimensions.map((d) => d.name).join(", ")}` : "",
|
|
829
|
-
orderBy,
|
|
830
|
-
`limit ${limit}`
|
|
831
|
-
].filter(Boolean).join(`
|
|
832
|
-
`),
|
|
833
|
-
values
|
|
834
|
-
};
|
|
835
|
-
}
|
|
836
|
-
function buildMeasureExpression(field, aggregation) {
|
|
837
|
-
switch (aggregation) {
|
|
838
|
-
case "COUNT":
|
|
839
|
-
return field === "*" ? "count()" : `count(${field})`;
|
|
840
|
-
case "COUNT_DISTINCT":
|
|
841
|
-
return `countDistinct(${field})`;
|
|
842
|
-
case "SUM":
|
|
843
|
-
return `sum(${field})`;
|
|
844
|
-
case "AVG":
|
|
845
|
-
return `avg(${field})`;
|
|
846
|
-
case "MIN":
|
|
847
|
-
return `min(${field})`;
|
|
848
|
-
case "MAX":
|
|
849
|
-
return `max(${field})`;
|
|
850
|
-
default:
|
|
851
|
-
return `count(${field})`;
|
|
852
|
-
}
|
|
853
|
-
}
|
|
854
|
-
function buildDimensionExpression(field, type, granularity) {
|
|
855
|
-
if (type === "TIME") {
|
|
856
|
-
switch (granularity) {
|
|
857
|
-
case "HOUR":
|
|
858
|
-
return `toStartOfHour(${field})`;
|
|
859
|
-
case "WEEK":
|
|
860
|
-
return `toStartOfWeek(${field})`;
|
|
861
|
-
case "MONTH":
|
|
862
|
-
return `toStartOfMonth(${field})`;
|
|
863
|
-
case "YEAR":
|
|
864
|
-
return `toStartOfYear(${field})`;
|
|
865
|
-
case "DAY":
|
|
866
|
-
default:
|
|
867
|
-
return `toStartOfDay(${field})`;
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
return field;
|
|
871
|
-
}
|
|
872
|
-
function buildFilterClauses(aggregation, params, values) {
|
|
873
|
-
const clauses = [];
|
|
874
|
-
const range = resolveDateRange(params);
|
|
875
|
-
if (range) {
|
|
876
|
-
values.dateFrom = range.from.toISOString();
|
|
877
|
-
values.dateTo = range.to.toISOString();
|
|
878
|
-
clauses.push(`timestamp >= {dateFrom} and timestamp < {dateTo}`);
|
|
879
|
-
}
|
|
880
|
-
aggregation.filters?.forEach((filter, index) => {
|
|
881
|
-
const key = `filter${index}`;
|
|
882
|
-
switch (filter.operator) {
|
|
883
|
-
case "eq":
|
|
884
|
-
values[key] = filter.value;
|
|
885
|
-
clauses.push(`${filter.field} = {${key}}`);
|
|
886
|
-
break;
|
|
887
|
-
case "neq":
|
|
888
|
-
values[key] = filter.value;
|
|
889
|
-
clauses.push(`${filter.field} != {${key}}`);
|
|
890
|
-
break;
|
|
891
|
-
case "gt":
|
|
892
|
-
values[key] = filter.value;
|
|
893
|
-
clauses.push(`${filter.field} > {${key}}`);
|
|
894
|
-
break;
|
|
895
|
-
case "gte":
|
|
896
|
-
values[key] = filter.value;
|
|
897
|
-
clauses.push(`${filter.field} >= {${key}}`);
|
|
898
|
-
break;
|
|
899
|
-
case "lt":
|
|
900
|
-
values[key] = filter.value;
|
|
901
|
-
clauses.push(`${filter.field} < {${key}}`);
|
|
902
|
-
break;
|
|
903
|
-
case "lte":
|
|
904
|
-
values[key] = filter.value;
|
|
905
|
-
clauses.push(`${filter.field} <= {${key}}`);
|
|
906
|
-
break;
|
|
907
|
-
case "contains":
|
|
908
|
-
values[key] = filter.value;
|
|
909
|
-
clauses.push(`${filter.field} LIKE '%' || {${key}} || '%'`);
|
|
910
|
-
break;
|
|
911
|
-
case "between": {
|
|
912
|
-
if (Array.isArray(filter.value) && filter.value.length >= 2) {
|
|
913
|
-
values[`${key}Start`] = filter.value[0];
|
|
914
|
-
values[`${key}End`] = filter.value[1];
|
|
915
|
-
clauses.push(`${filter.field} BETWEEN {${key}Start} AND {${key}End}`);
|
|
916
|
-
}
|
|
917
|
-
break;
|
|
918
|
-
}
|
|
919
|
-
case "in":
|
|
920
|
-
case "nin":
|
|
921
|
-
if (Array.isArray(filter.value)) {
|
|
922
|
-
const placeholders = [];
|
|
923
|
-
filter.value.forEach((value, valueIndex) => {
|
|
924
|
-
const valueKey = `${key}_${valueIndex}`;
|
|
925
|
-
values[valueKey] = value;
|
|
926
|
-
placeholders.push(`{${valueKey}}`);
|
|
927
|
-
});
|
|
928
|
-
if (placeholders.length) {
|
|
929
|
-
clauses.push(`${filter.field} ${filter.operator === "in" ? "IN" : "NOT IN"} (${placeholders.join(", ")})`);
|
|
930
|
-
}
|
|
931
|
-
}
|
|
932
|
-
break;
|
|
933
|
-
default:
|
|
934
|
-
break;
|
|
935
|
-
}
|
|
936
|
-
});
|
|
937
|
-
return clauses;
|
|
938
|
-
}
|
|
939
|
-
function resolveDateRange(params) {
|
|
940
|
-
const range = params.dateRange;
|
|
941
|
-
if (!range)
|
|
942
|
-
return null;
|
|
943
|
-
return { from: range.start, to: range.end };
|
|
944
|
-
}
|
|
945
|
-
function mapHogqlResult(result) {
|
|
946
|
-
if (!Array.isArray(result.results) || !Array.isArray(result.columns)) {
|
|
947
|
-
return { data: [], columns: [], rowCount: 0 };
|
|
948
|
-
}
|
|
949
|
-
const columns = result.columns.map((name) => ({
|
|
950
|
-
name,
|
|
951
|
-
type: "STRING"
|
|
952
|
-
}));
|
|
953
|
-
const data = result.results.map((row) => {
|
|
954
|
-
if (!Array.isArray(row))
|
|
955
|
-
return {};
|
|
956
|
-
const record = {};
|
|
957
|
-
result.columns?.forEach((column, index) => {
|
|
958
|
-
record[column] = row[index];
|
|
959
|
-
});
|
|
960
|
-
return record;
|
|
961
|
-
});
|
|
962
|
-
return {
|
|
963
|
-
data,
|
|
964
|
-
columns,
|
|
965
|
-
rowCount: data.length
|
|
966
|
-
};
|
|
967
|
-
}
|
|
968
|
-
|
|
969
|
-
// src/handlers/analytics.handlers.ts
|
|
970
|
-
import { web } from "@contractspec/lib.runtime-sandbox";
|
|
971
|
-
var { generateId } = web;
|
|
972
|
-
function rowToDashboard(row) {
|
|
973
|
-
return {
|
|
974
|
-
id: row.id,
|
|
975
|
-
projectId: row.projectId,
|
|
976
|
-
organizationId: row.organizationId,
|
|
977
|
-
name: row.name,
|
|
978
|
-
slug: row.slug,
|
|
979
|
-
description: row.description ?? undefined,
|
|
980
|
-
status: row.status,
|
|
981
|
-
refreshInterval: row.refreshInterval,
|
|
982
|
-
isPublic: row.isPublic === 1,
|
|
983
|
-
shareToken: row.shareToken ?? undefined,
|
|
984
|
-
createdAt: new Date(row.createdAt),
|
|
985
|
-
updatedAt: new Date(row.updatedAt)
|
|
986
|
-
};
|
|
987
|
-
}
|
|
988
|
-
function rowToWidget(row) {
|
|
989
|
-
return {
|
|
990
|
-
id: row.id,
|
|
991
|
-
dashboardId: row.dashboardId,
|
|
992
|
-
name: row.name,
|
|
993
|
-
type: row.type,
|
|
994
|
-
gridX: row.gridX,
|
|
995
|
-
gridY: row.gridY,
|
|
996
|
-
gridWidth: row.gridWidth,
|
|
997
|
-
gridHeight: row.gridHeight,
|
|
998
|
-
queryId: row.queryId ?? undefined,
|
|
999
|
-
config: row.config ? JSON.parse(row.config) : undefined,
|
|
1000
|
-
createdAt: new Date(row.createdAt),
|
|
1001
|
-
updatedAt: new Date(row.updatedAt)
|
|
1002
|
-
};
|
|
1003
|
-
}
|
|
1004
|
-
function rowToQuery(row) {
|
|
1005
|
-
return {
|
|
1006
|
-
id: row.id,
|
|
1007
|
-
projectId: row.projectId,
|
|
1008
|
-
organizationId: row.organizationId,
|
|
1009
|
-
name: row.name,
|
|
1010
|
-
description: row.description ?? undefined,
|
|
1011
|
-
type: row.type,
|
|
1012
|
-
definition: JSON.parse(row.definition),
|
|
1013
|
-
sql: row.sql ?? undefined,
|
|
1014
|
-
cacheTtlSeconds: row.cacheTtlSeconds,
|
|
1015
|
-
isShared: row.isShared === 1,
|
|
1016
|
-
createdAt: new Date(row.createdAt),
|
|
1017
|
-
updatedAt: new Date(row.updatedAt)
|
|
1018
|
-
};
|
|
1019
|
-
}
|
|
1020
|
-
function createAnalyticsHandlers(db) {
|
|
1021
|
-
async function listDashboards(input) {
|
|
1022
|
-
const { projectId, status, search, limit = 20, offset = 0 } = input;
|
|
1023
|
-
let whereClause = "WHERE projectId = ?";
|
|
1024
|
-
const params = [projectId];
|
|
1025
|
-
if (status && status !== "all") {
|
|
1026
|
-
whereClause += " AND status = ?";
|
|
1027
|
-
params.push(status);
|
|
1028
|
-
}
|
|
1029
|
-
if (search) {
|
|
1030
|
-
whereClause += " AND (name LIKE ? OR description LIKE ?)";
|
|
1031
|
-
params.push(`%${search}%`, `%${search}%`);
|
|
1032
|
-
}
|
|
1033
|
-
const countResult = (await db.query(`SELECT COUNT(*) as count FROM analytics_dashboard ${whereClause}`, params)).rows;
|
|
1034
|
-
const total = countResult[0]?.count ?? 0;
|
|
1035
|
-
const rows = (await db.query(`SELECT * FROM analytics_dashboard ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
|
|
1036
|
-
return {
|
|
1037
|
-
dashboards: rows.map(rowToDashboard),
|
|
1038
|
-
total
|
|
1039
|
-
};
|
|
1040
|
-
}
|
|
1041
|
-
async function createDashboard(input, context) {
|
|
1042
|
-
const id = generateId("dash");
|
|
1043
|
-
const now = new Date().toISOString();
|
|
1044
|
-
await db.execute(`INSERT INTO analytics_dashboard (id, projectId, organizationId, name, slug, description, status, refreshInterval, isPublic, createdAt, updatedAt)
|
|
1045
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
1046
|
-
id,
|
|
1047
|
-
context.projectId,
|
|
1048
|
-
context.organizationId,
|
|
1049
|
-
input.name,
|
|
1050
|
-
input.slug,
|
|
1051
|
-
input.description ?? null,
|
|
1052
|
-
"DRAFT",
|
|
1053
|
-
input.refreshInterval ?? "NONE",
|
|
1054
|
-
0,
|
|
1055
|
-
now,
|
|
1056
|
-
now
|
|
1057
|
-
]);
|
|
1058
|
-
const rows = (await db.query(`SELECT * FROM analytics_dashboard WHERE id = ?`, [id])).rows;
|
|
1059
|
-
return rowToDashboard(rows[0]);
|
|
1060
|
-
}
|
|
1061
|
-
async function getDashboard(input) {
|
|
1062
|
-
let whereClause = "";
|
|
1063
|
-
const params = [];
|
|
1064
|
-
if (input.dashboardId) {
|
|
1065
|
-
whereClause = "WHERE id = ?";
|
|
1066
|
-
params.push(input.dashboardId);
|
|
1067
|
-
} else if (input.slug) {
|
|
1068
|
-
whereClause = "WHERE slug = ?";
|
|
1069
|
-
params.push(input.slug);
|
|
1070
|
-
} else if (input.shareToken) {
|
|
1071
|
-
whereClause = "WHERE shareToken = ?";
|
|
1072
|
-
params.push(input.shareToken);
|
|
1073
|
-
} else {
|
|
1074
|
-
return null;
|
|
1075
|
-
}
|
|
1076
|
-
const rows = (await db.query(`SELECT * FROM analytics_dashboard ${whereClause}`, params)).rows;
|
|
1077
|
-
return rows[0] ? rowToDashboard(rows[0]) : null;
|
|
1078
|
-
}
|
|
1079
|
-
async function updateDashboard(dashboardId, updates) {
|
|
1080
|
-
const now = new Date().toISOString();
|
|
1081
|
-
const setClauses = ["updatedAt = ?"];
|
|
1082
|
-
const params = [now];
|
|
1083
|
-
if (updates.name !== undefined) {
|
|
1084
|
-
setClauses.push("name = ?");
|
|
1085
|
-
params.push(updates.name);
|
|
1086
|
-
}
|
|
1087
|
-
if (updates.description !== undefined) {
|
|
1088
|
-
setClauses.push("description = ?");
|
|
1089
|
-
params.push(updates.description);
|
|
1090
|
-
}
|
|
1091
|
-
if (updates.status !== undefined) {
|
|
1092
|
-
setClauses.push("status = ?");
|
|
1093
|
-
params.push(updates.status);
|
|
1094
|
-
}
|
|
1095
|
-
if (updates.refreshInterval !== undefined) {
|
|
1096
|
-
setClauses.push("refreshInterval = ?");
|
|
1097
|
-
params.push(updates.refreshInterval);
|
|
1098
|
-
}
|
|
1099
|
-
if (updates.isPublic !== undefined) {
|
|
1100
|
-
setClauses.push("isPublic = ?");
|
|
1101
|
-
params.push(updates.isPublic ? 1 : 0);
|
|
1102
|
-
if (updates.isPublic) {
|
|
1103
|
-
setClauses.push("shareToken = ?");
|
|
1104
|
-
params.push(generateId("share"));
|
|
1105
|
-
} else {
|
|
1106
|
-
setClauses.push("shareToken = NULL");
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1109
|
-
params.push(dashboardId);
|
|
1110
|
-
await db.execute(`UPDATE analytics_dashboard SET ${setClauses.join(", ")} WHERE id = ?`, params);
|
|
1111
|
-
const rows = (await db.query(`SELECT * FROM analytics_dashboard WHERE id = ?`, [
|
|
1112
|
-
dashboardId
|
|
1113
|
-
])).rows;
|
|
1114
|
-
return rowToDashboard(rows[0]);
|
|
1115
|
-
}
|
|
1116
|
-
async function getWidgets(dashboardId) {
|
|
1117
|
-
const rows = (await db.query(`SELECT * FROM analytics_widget WHERE dashboardId = ? ORDER BY gridY, gridX`, [dashboardId])).rows;
|
|
1118
|
-
return rows.map(rowToWidget);
|
|
1119
|
-
}
|
|
1120
|
-
async function addWidget(input) {
|
|
1121
|
-
const id = generateId("widget");
|
|
1122
|
-
const now = new Date().toISOString();
|
|
1123
|
-
await db.execute(`INSERT INTO analytics_widget (id, dashboardId, name, type, gridX, gridY, gridWidth, gridHeight, queryId, config, createdAt, updatedAt)
|
|
1124
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
1125
|
-
id,
|
|
1126
|
-
input.dashboardId,
|
|
1127
|
-
input.name,
|
|
1128
|
-
input.type,
|
|
1129
|
-
input.gridX ?? 0,
|
|
1130
|
-
input.gridY ?? 0,
|
|
1131
|
-
input.gridWidth ?? 6,
|
|
1132
|
-
input.gridHeight ?? 4,
|
|
1133
|
-
input.queryId ?? null,
|
|
1134
|
-
input.config ? JSON.stringify(input.config) : null,
|
|
1135
|
-
now,
|
|
1136
|
-
now
|
|
1137
|
-
]);
|
|
1138
|
-
const rows = (await db.query(`SELECT * FROM analytics_widget WHERE id = ?`, [id])).rows;
|
|
1139
|
-
return rowToWidget(rows[0]);
|
|
1140
|
-
}
|
|
1141
|
-
async function updateWidget(widgetId, updates) {
|
|
1142
|
-
const now = new Date().toISOString();
|
|
1143
|
-
const setClauses = ["updatedAt = ?"];
|
|
1144
|
-
const params = [now];
|
|
1145
|
-
if (updates.name !== undefined) {
|
|
1146
|
-
setClauses.push("name = ?");
|
|
1147
|
-
params.push(updates.name);
|
|
1148
|
-
}
|
|
1149
|
-
if (updates.gridX !== undefined) {
|
|
1150
|
-
setClauses.push("gridX = ?");
|
|
1151
|
-
params.push(updates.gridX);
|
|
1152
|
-
}
|
|
1153
|
-
if (updates.gridY !== undefined) {
|
|
1154
|
-
setClauses.push("gridY = ?");
|
|
1155
|
-
params.push(updates.gridY);
|
|
1156
|
-
}
|
|
1157
|
-
if (updates.gridWidth !== undefined) {
|
|
1158
|
-
setClauses.push("gridWidth = ?");
|
|
1159
|
-
params.push(updates.gridWidth);
|
|
1160
|
-
}
|
|
1161
|
-
if (updates.gridHeight !== undefined) {
|
|
1162
|
-
setClauses.push("gridHeight = ?");
|
|
1163
|
-
params.push(updates.gridHeight);
|
|
1164
|
-
}
|
|
1165
|
-
if (updates.queryId !== undefined) {
|
|
1166
|
-
setClauses.push("queryId = ?");
|
|
1167
|
-
params.push(updates.queryId ?? null);
|
|
1168
|
-
}
|
|
1169
|
-
if (updates.config !== undefined) {
|
|
1170
|
-
setClauses.push("config = ?");
|
|
1171
|
-
params.push(updates.config ? JSON.stringify(updates.config) : null);
|
|
1172
|
-
}
|
|
1173
|
-
params.push(widgetId);
|
|
1174
|
-
await db.execute(`UPDATE analytics_widget SET ${setClauses.join(", ")} WHERE id = ?`, params);
|
|
1175
|
-
const rows = (await db.query(`SELECT * FROM analytics_widget WHERE id = ?`, [widgetId])).rows;
|
|
1176
|
-
return rowToWidget(rows[0]);
|
|
1177
|
-
}
|
|
1178
|
-
async function deleteWidget(widgetId) {
|
|
1179
|
-
await db.execute(`DELETE FROM analytics_widget WHERE id = ?`, [widgetId]);
|
|
1180
|
-
}
|
|
1181
|
-
async function listQueries(input) {
|
|
1182
|
-
const { projectId, type, isShared, search, limit = 20, offset = 0 } = input;
|
|
1183
|
-
let whereClause = "WHERE projectId = ?";
|
|
1184
|
-
const params = [projectId];
|
|
1185
|
-
if (type && type !== "all") {
|
|
1186
|
-
whereClause += " AND type = ?";
|
|
1187
|
-
params.push(type);
|
|
1188
|
-
}
|
|
1189
|
-
if (isShared !== undefined) {
|
|
1190
|
-
whereClause += " AND isShared = ?";
|
|
1191
|
-
params.push(isShared ? 1 : 0);
|
|
1192
|
-
}
|
|
1193
|
-
if (search) {
|
|
1194
|
-
whereClause += " AND (name LIKE ? OR description LIKE ?)";
|
|
1195
|
-
params.push(`%${search}%`, `%${search}%`);
|
|
1196
|
-
}
|
|
1197
|
-
const countResult = (await db.query(`SELECT COUNT(*) as count FROM analytics_query ${whereClause}`, params)).rows;
|
|
1198
|
-
const total = countResult[0]?.count ?? 0;
|
|
1199
|
-
const rows = (await db.query(`SELECT * FROM analytics_query ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
|
|
1200
|
-
return {
|
|
1201
|
-
queries: rows.map(rowToQuery),
|
|
1202
|
-
total
|
|
1203
|
-
};
|
|
1204
|
-
}
|
|
1205
|
-
async function createQuery(input, context) {
|
|
1206
|
-
const id = generateId("query");
|
|
1207
|
-
const now = new Date().toISOString();
|
|
1208
|
-
await db.execute(`INSERT INTO analytics_query (id, projectId, organizationId, name, description, type, definition, sql, cacheTtlSeconds, isShared, createdAt, updatedAt)
|
|
1209
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
1210
|
-
id,
|
|
1211
|
-
context.projectId,
|
|
1212
|
-
context.organizationId,
|
|
1213
|
-
input.name,
|
|
1214
|
-
input.description ?? null,
|
|
1215
|
-
input.type,
|
|
1216
|
-
JSON.stringify(input.definition),
|
|
1217
|
-
input.sql ?? null,
|
|
1218
|
-
input.cacheTtlSeconds ?? 300,
|
|
1219
|
-
input.isShared ? 1 : 0,
|
|
1220
|
-
now,
|
|
1221
|
-
now
|
|
1222
|
-
]);
|
|
1223
|
-
const rows = (await db.query(`SELECT * FROM analytics_query WHERE id = ?`, [id])).rows;
|
|
1224
|
-
return rowToQuery(rows[0]);
|
|
1225
|
-
}
|
|
1226
|
-
async function getQuery(queryId) {
|
|
1227
|
-
const rows = (await db.query(`SELECT * FROM analytics_query WHERE id = ?`, [queryId])).rows;
|
|
1228
|
-
return rows[0] ? rowToQuery(rows[0]) : null;
|
|
1229
|
-
}
|
|
1230
|
-
return {
|
|
1231
|
-
listDashboards,
|
|
1232
|
-
createDashboard,
|
|
1233
|
-
getDashboard,
|
|
1234
|
-
updateDashboard,
|
|
1235
|
-
getWidgets,
|
|
1236
|
-
addWidget,
|
|
1237
|
-
updateWidget,
|
|
1238
|
-
deleteWidget,
|
|
1239
|
-
listQueries,
|
|
1240
|
-
createQuery,
|
|
1241
|
-
getQuery
|
|
1242
|
-
};
|
|
1243
|
-
}
|
|
1244
|
-
|
|
1245
|
-
// src/query/query.enum.ts
|
|
1246
|
-
import { defineEnum } from "@contractspec/lib.schema";
|
|
1247
|
-
var QueryTypeEnum = defineEnum("QueryType", [
|
|
1248
|
-
"SQL",
|
|
1249
|
-
"METRIC",
|
|
1250
|
-
"AGGREGATION",
|
|
1251
|
-
"CUSTOM"
|
|
1252
|
-
]);
|
|
1253
|
-
|
|
1254
|
-
// src/query/query.schema.ts
|
|
1255
|
-
import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
|
|
1256
|
-
var QueryModel = defineSchemaModel({
|
|
1257
|
-
name: "QueryModel",
|
|
1258
|
-
fields: {
|
|
1259
|
-
id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
1260
|
-
name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
1261
|
-
description: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
|
|
1262
|
-
type: { type: QueryTypeEnum, isOptional: false },
|
|
1263
|
-
definition: { type: ScalarTypeEnum.JSON(), isOptional: false },
|
|
1264
|
-
sql: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
|
|
1265
|
-
cacheTtlSeconds: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
|
|
1266
|
-
isShared: { type: ScalarTypeEnum.Boolean(), isOptional: false },
|
|
1267
|
-
createdAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
|
|
1268
|
-
}
|
|
1269
|
-
});
|
|
1270
|
-
var QueryResultModel = defineSchemaModel({
|
|
1271
|
-
name: "QueryResultModel",
|
|
1272
|
-
fields: {
|
|
1273
|
-
queryId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
1274
|
-
data: { type: ScalarTypeEnum.JSON(), isOptional: false },
|
|
1275
|
-
columns: { type: ScalarTypeEnum.JSON(), isOptional: false },
|
|
1276
|
-
rowCount: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
|
|
1277
|
-
executionTimeMs: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
|
|
1278
|
-
cachedAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
|
|
1279
|
-
error: { type: ScalarTypeEnum.String_unsecure(), isOptional: true }
|
|
1280
|
-
}
|
|
1281
|
-
});
|
|
1282
|
-
var CreateQueryInputModel = defineSchemaModel({
|
|
1283
|
-
name: "CreateQueryInput",
|
|
1284
|
-
fields: {
|
|
1285
|
-
name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
|
|
1286
|
-
description: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
|
|
1287
|
-
type: { type: QueryTypeEnum, isOptional: false },
|
|
1288
|
-
definition: { type: ScalarTypeEnum.JSON(), isOptional: false },
|
|
1289
|
-
sql: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
|
|
1290
|
-
metricIds: {
|
|
1291
|
-
type: ScalarTypeEnum.String_unsecure(),
|
|
1292
|
-
isArray: true,
|
|
1293
|
-
isOptional: true
|
|
1294
|
-
},
|
|
1295
|
-
cacheTtlSeconds: { type: ScalarTypeEnum.Int_unsecure(), isOptional: true },
|
|
1296
|
-
isShared: { type: ScalarTypeEnum.Boolean(), isOptional: true }
|
|
1297
|
-
}
|
|
1298
|
-
});
|
|
1299
|
-
var ExecuteQueryInputModel = defineSchemaModel({
|
|
1300
|
-
name: "ExecuteQueryInput",
|
|
1301
|
-
fields: {
|
|
1302
|
-
queryId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
|
|
1303
|
-
parameters: { type: ScalarTypeEnum.JSON(), isOptional: true },
|
|
1304
|
-
dateRange: { type: ScalarTypeEnum.JSON(), isOptional: true },
|
|
1305
|
-
filters: { type: ScalarTypeEnum.JSON(), isOptional: true },
|
|
1306
|
-
forceRefresh: { type: ScalarTypeEnum.Boolean(), isOptional: true }
|
|
1307
|
-
}
|
|
1308
|
-
});
|
|
1309
|
-
|
|
1310
|
-
// src/query/query.operation.ts
|
|
1311
|
-
import {
|
|
1312
|
-
defineCommand,
|
|
1313
|
-
defineQuery
|
|
1314
|
-
} from "@contractspec/lib.contracts-spec/operations";
|
|
1315
|
-
var OWNERS = ["@example.analytics-dashboard"];
|
|
1316
|
-
var CreateQueryContract = defineCommand({
|
|
1317
|
-
meta: {
|
|
1318
|
-
key: "analytics.query.create",
|
|
1319
|
-
version: "1.0.0",
|
|
1320
|
-
stability: "stable",
|
|
1321
|
-
owners: [...OWNERS],
|
|
1322
|
-
tags: ["analytics", "query", "create"],
|
|
1323
|
-
description: "Create a data query.",
|
|
1324
|
-
goal: "Define reusable data queries.",
|
|
1325
|
-
context: "Query builder."
|
|
1326
|
-
},
|
|
1327
|
-
io: { input: CreateQueryInputModel, output: QueryModel },
|
|
1328
|
-
policy: { auth: "user" },
|
|
1329
|
-
sideEffects: {
|
|
1330
|
-
emits: [
|
|
1331
|
-
{
|
|
1332
|
-
key: "analytics.query.created",
|
|
1333
|
-
version: "1.0.0",
|
|
1334
|
-
stability: "stable",
|
|
1335
|
-
owners: [...OWNERS],
|
|
1336
|
-
tags: ["analytics", "query", "created"],
|
|
1337
|
-
when: "Query created",
|
|
1338
|
-
payload: QueryModel
|
|
1339
|
-
}
|
|
1340
|
-
],
|
|
1341
|
-
audit: ["analytics.query.created"]
|
|
1342
|
-
},
|
|
1343
|
-
acceptance: {
|
|
1344
|
-
scenarios: [
|
|
1345
|
-
{
|
|
1346
|
-
key: "create-query-happy-path",
|
|
1347
|
-
given: ["User is authenticated"],
|
|
1348
|
-
when: ["User submits valid query definition"],
|
|
1349
|
-
then: ["Query is created", "QueryCreated event is emitted"]
|
|
1350
|
-
}
|
|
1351
|
-
],
|
|
1352
|
-
examples: [
|
|
1353
|
-
{
|
|
1354
|
-
key: "create-sql-query",
|
|
1355
|
-
input: {
|
|
1356
|
-
name: "Monthly Revenue",
|
|
1357
|
-
sql: "SELECT SUM(amount) FROM orders WHERE date >= :startDate"
|
|
1358
|
-
},
|
|
1359
|
-
output: { id: "query-123", name: "Monthly Revenue", type: "sql" }
|
|
1360
|
-
}
|
|
1361
|
-
]
|
|
1362
|
-
}
|
|
1363
|
-
});
|
|
1364
|
-
var ExecuteQueryContract = defineQuery({
|
|
1365
|
-
meta: {
|
|
1366
|
-
key: "analytics.query.execute",
|
|
1367
|
-
version: "1.0.0",
|
|
1368
|
-
stability: "stable",
|
|
1369
|
-
owners: [...OWNERS],
|
|
1370
|
-
tags: ["analytics", "query", "execute"],
|
|
1371
|
-
description: "Execute a data query.",
|
|
1372
|
-
goal: "Fetch data for visualizations.",
|
|
1373
|
-
context: "Dashboard rendering."
|
|
1374
|
-
},
|
|
1375
|
-
io: { input: ExecuteQueryInputModel, output: QueryResultModel },
|
|
1376
|
-
policy: { auth: "user" },
|
|
1377
|
-
acceptance: {
|
|
1378
|
-
scenarios: [
|
|
1379
|
-
{
|
|
1380
|
-
key: "execute-query-happy-path",
|
|
1381
|
-
given: ["Query exists"],
|
|
1382
|
-
when: ["User executes query with parameters"],
|
|
1383
|
-
then: ["Query results are returned"]
|
|
1384
|
-
}
|
|
1385
|
-
],
|
|
1386
|
-
examples: [
|
|
1387
|
-
{
|
|
1388
|
-
key: "execute-with-params",
|
|
1389
|
-
input: { queryId: "query-123", params: { startDate: "2025-01-01" } },
|
|
1390
|
-
output: { columns: ["total"], rows: [{ total: 50000 }], rowCount: 1 }
|
|
1391
|
-
}
|
|
1392
|
-
]
|
|
1393
|
-
}
|
|
1394
|
-
});
|
|
1395
|
-
// src/query-engine/index.ts
|
|
1396
|
-
class InMemoryQueryCache {
|
|
1397
|
-
cache = new Map;
|
|
1398
|
-
async get(key) {
|
|
1399
|
-
const entry = this.cache.get(key);
|
|
1400
|
-
if (!entry)
|
|
1401
|
-
return null;
|
|
1402
|
-
if (entry.expiresAt < new Date) {
|
|
1403
|
-
this.cache.delete(key);
|
|
1404
|
-
return null;
|
|
1405
|
-
}
|
|
1406
|
-
return { ...entry.result, cached: true, cachedAt: entry.expiresAt };
|
|
1407
|
-
}
|
|
1408
|
-
async set(key, result, ttlSeconds) {
|
|
1409
|
-
const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
|
|
1410
|
-
this.cache.set(key, { result, expiresAt });
|
|
1411
|
-
}
|
|
1412
|
-
async invalidate(pattern) {
|
|
1413
|
-
const regex = new RegExp(pattern);
|
|
1414
|
-
for (const key of this.cache.keys()) {
|
|
1415
|
-
if (regex.test(key)) {
|
|
1416
|
-
this.cache.delete(key);
|
|
1417
|
-
}
|
|
1418
|
-
}
|
|
1419
|
-
}
|
|
1420
|
-
}
|
|
1421
|
-
|
|
1422
|
-
class BasicQueryEngine {
|
|
1423
|
-
cache;
|
|
1424
|
-
constructor(cache) {
|
|
1425
|
-
this.cache = cache ?? new InMemoryQueryCache;
|
|
1426
|
-
}
|
|
1427
|
-
async execute(definition, params) {
|
|
1428
|
-
const startTime = Date.now();
|
|
1429
|
-
const validation = this.validateQuery(definition);
|
|
1430
|
-
if (!validation.valid) {
|
|
1431
|
-
return {
|
|
1432
|
-
data: [],
|
|
1433
|
-
columns: [],
|
|
1434
|
-
rowCount: 0,
|
|
1435
|
-
executionTimeMs: Date.now() - startTime,
|
|
1436
|
-
cached: false,
|
|
1437
|
-
error: validation.errors.join(", ")
|
|
1438
|
-
};
|
|
1439
|
-
}
|
|
1440
|
-
const cacheKey = this.buildCacheKey(definition, params);
|
|
1441
|
-
const cachedResult = await this.cache.get(cacheKey);
|
|
1442
|
-
if (cachedResult) {
|
|
1443
|
-
return cachedResult;
|
|
1444
|
-
}
|
|
1445
|
-
let result;
|
|
1446
|
-
switch (definition.type) {
|
|
1447
|
-
case "AGGREGATION":
|
|
1448
|
-
if (!definition.aggregation) {
|
|
1449
|
-
throw new Error("Aggregation definition is missing");
|
|
1450
|
-
}
|
|
1451
|
-
result = await this.executeAggregation(definition.aggregation, params);
|
|
1452
|
-
break;
|
|
1453
|
-
case "METRIC":
|
|
1454
|
-
if (!definition.metricIds) {
|
|
1455
|
-
throw new Error("Metric IDs are missing");
|
|
1456
|
-
}
|
|
1457
|
-
result = await this.executeMetric(definition.metricIds, params);
|
|
1458
|
-
break;
|
|
1459
|
-
case "SQL":
|
|
1460
|
-
if (!definition.sql) {
|
|
1461
|
-
throw new Error("SQL query is missing");
|
|
1462
|
-
}
|
|
1463
|
-
result = await this.executeSql(definition.sql, params);
|
|
1464
|
-
break;
|
|
1465
|
-
default:
|
|
1466
|
-
result = {
|
|
1467
|
-
data: [],
|
|
1468
|
-
columns: [],
|
|
1469
|
-
rowCount: 0,
|
|
1470
|
-
executionTimeMs: Date.now() - startTime,
|
|
1471
|
-
cached: false,
|
|
1472
|
-
error: `Unknown query type: ${definition.type}`
|
|
1473
|
-
};
|
|
1474
|
-
}
|
|
1475
|
-
result.executionTimeMs = Date.now() - startTime;
|
|
1476
|
-
result.cached = false;
|
|
1477
|
-
await this.cache.set(cacheKey, result, 300);
|
|
1478
|
-
return result;
|
|
1479
|
-
}
|
|
1480
|
-
validateQuery(definition) {
|
|
1481
|
-
const errors = [];
|
|
1482
|
-
if (!definition.type) {
|
|
1483
|
-
errors.push("Query type is required");
|
|
1484
|
-
}
|
|
1485
|
-
switch (definition.type) {
|
|
1486
|
-
case "SQL":
|
|
1487
|
-
if (!definition.sql) {
|
|
1488
|
-
errors.push("SQL query is required for SQL type");
|
|
1489
|
-
}
|
|
1490
|
-
break;
|
|
1491
|
-
case "METRIC":
|
|
1492
|
-
if (!definition.metricIds || definition.metricIds.length === 0) {
|
|
1493
|
-
errors.push("Metric IDs are required for METRIC type");
|
|
1494
|
-
}
|
|
1495
|
-
break;
|
|
1496
|
-
case "AGGREGATION":
|
|
1497
|
-
if (!definition.aggregation) {
|
|
1498
|
-
errors.push("Aggregation definition is required for AGGREGATION type");
|
|
1499
|
-
} else {
|
|
1500
|
-
if (!definition.aggregation.source) {
|
|
1501
|
-
errors.push("Aggregation source is required");
|
|
1502
|
-
}
|
|
1503
|
-
if (!definition.aggregation.measures || definition.aggregation.measures.length === 0) {
|
|
1504
|
-
errors.push("At least one measure is required");
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
break;
|
|
1508
|
-
}
|
|
1509
|
-
return { valid: errors.length === 0, errors };
|
|
1510
|
-
}
|
|
1511
|
-
buildCacheKey(definition, params) {
|
|
1512
|
-
return JSON.stringify({ definition, params });
|
|
1513
|
-
}
|
|
1514
|
-
async executeAggregation(aggregation, params) {
|
|
1515
|
-
const columns = [
|
|
1516
|
-
...aggregation.dimensions.map((d) => ({
|
|
1517
|
-
name: d.name,
|
|
1518
|
-
type: d.type === "NUMBER" ? "NUMBER" : d.type === "TIME" ? "DATE" : "STRING",
|
|
1519
|
-
label: d.name
|
|
1520
|
-
})),
|
|
1521
|
-
...aggregation.measures.map((m) => ({
|
|
1522
|
-
name: m.name,
|
|
1523
|
-
type: "NUMBER",
|
|
1524
|
-
label: m.name,
|
|
1525
|
-
format: m.format
|
|
1526
|
-
}))
|
|
1527
|
-
];
|
|
1528
|
-
const data = this.generateMockData(aggregation, params);
|
|
1529
|
-
return {
|
|
1530
|
-
data,
|
|
1531
|
-
columns,
|
|
1532
|
-
rowCount: data.length,
|
|
1533
|
-
executionTimeMs: 0,
|
|
1534
|
-
cached: false
|
|
1535
|
-
};
|
|
1536
|
-
}
|
|
1537
|
-
async executeMetric(metricIds, _params) {
|
|
1538
|
-
const data = metricIds.map((id) => ({
|
|
1539
|
-
metricId: id,
|
|
1540
|
-
value: Math.random() * 1000,
|
|
1541
|
-
change: (Math.random() - 0.5) * 20
|
|
1542
|
-
}));
|
|
1543
|
-
return {
|
|
1544
|
-
data,
|
|
1545
|
-
columns: [
|
|
1546
|
-
{ name: "metricId", type: "STRING" },
|
|
1547
|
-
{ name: "value", type: "NUMBER" },
|
|
1548
|
-
{ name: "change", type: "NUMBER" }
|
|
1549
|
-
],
|
|
1550
|
-
rowCount: data.length,
|
|
1551
|
-
executionTimeMs: 0,
|
|
1552
|
-
cached: false
|
|
1553
|
-
};
|
|
1554
|
-
}
|
|
1555
|
-
async executeSql(_sql, _params) {
|
|
1556
|
-
return {
|
|
1557
|
-
data: [],
|
|
1558
|
-
columns: [],
|
|
1559
|
-
rowCount: 0,
|
|
1560
|
-
executionTimeMs: 0,
|
|
1561
|
-
cached: false,
|
|
1562
|
-
error: "SQL execution not implemented in demo"
|
|
1563
|
-
};
|
|
1564
|
-
}
|
|
1565
|
-
generateMockData(aggregation, params) {
|
|
1566
|
-
const data = [];
|
|
1567
|
-
const rowCount = 10;
|
|
1568
|
-
const timeDimension = aggregation.dimensions.find((d) => d.type === "TIME");
|
|
1569
|
-
for (let i = 0;i < rowCount; i++) {
|
|
1570
|
-
const row = {};
|
|
1571
|
-
for (const dim of aggregation.dimensions) {
|
|
1572
|
-
if (dim.type === "TIME") {
|
|
1573
|
-
const date = new Date(params.dateRange?.start ?? new Date);
|
|
1574
|
-
date.setDate(date.getDate() + i);
|
|
1575
|
-
row[dim.name] = date.toISOString().split("T")[0];
|
|
1576
|
-
} else {
|
|
1577
|
-
row[dim.name] = `${dim.name}_${i % 5}`;
|
|
1578
|
-
}
|
|
1579
|
-
}
|
|
1580
|
-
for (const measure of aggregation.measures) {
|
|
1581
|
-
const baseValue = timeDimension ? 100 + i * 10 : Math.random() * 1000;
|
|
1582
|
-
const noise = (Math.random() - 0.5) * 20;
|
|
1583
|
-
row[measure.name] = Math.round((baseValue + noise) * 100) / 100;
|
|
1584
|
-
}
|
|
1585
|
-
data.push(row);
|
|
1586
|
-
}
|
|
1587
|
-
return data;
|
|
1588
|
-
}
|
|
1589
|
-
}
|
|
1590
|
-
function createQueryEngine(cache) {
|
|
1591
|
-
return new BasicQueryEngine(cache);
|
|
1592
|
-
}
|
|
1593
|
-
|
|
1594
|
-
// src/ui/AnalyticsDashboard.widgets.tsx
|
|
1595
|
-
import {
|
|
1596
|
-
ComparisonView,
|
|
1597
|
-
TimelineView,
|
|
1598
|
-
VisualizationCard,
|
|
1599
|
-
VisualizationGrid
|
|
1600
|
-
} from "@contractspec/lib.design-system";
|
|
1601
|
-
import { jsxDEV } from "react/jsx-dev-runtime";
|
|
1602
|
-
"use client";
|
|
1603
|
-
function AnalyticsWidgetBoard({
|
|
1604
|
-
dashboardName,
|
|
1605
|
-
widgets
|
|
1606
|
-
}) {
|
|
1607
|
-
if (!widgets.length) {
|
|
1608
|
-
return /* @__PURE__ */ jsxDEV("div", {
|
|
1609
|
-
className: "rounded-lg border border-dashed p-10 text-center text-muted-foreground",
|
|
1610
|
-
children: [
|
|
1611
|
-
'No visualization widgets configured for "',
|
|
1612
|
-
dashboardName,
|
|
1613
|
-
'".'
|
|
1614
|
-
]
|
|
1615
|
-
}, undefined, true, undefined, this);
|
|
1616
|
-
}
|
|
1617
|
-
return /* @__PURE__ */ jsxDEV("div", {
|
|
1618
|
-
children: [
|
|
1619
|
-
/* @__PURE__ */ jsxDEV("h3", {
|
|
1620
|
-
className: "mb-4 font-semibold text-lg",
|
|
1621
|
-
children: [
|
|
1622
|
-
'Widgets in "',
|
|
1623
|
-
dashboardName,
|
|
1624
|
-
'"'
|
|
1625
|
-
]
|
|
1626
|
-
}, undefined, true, undefined, this),
|
|
1627
|
-
/* @__PURE__ */ jsxDEV(VisualizationGrid, {
|
|
1628
|
-
children: widgets.map((widget2) => /* @__PURE__ */ jsxDEV("div", {
|
|
1629
|
-
className: gridSpanClass(widget2.gridWidth),
|
|
1630
|
-
children: renderVisualizationWidget(widget2)
|
|
1631
|
-
}, widget2.id, false, undefined, this))
|
|
1632
|
-
}, undefined, false, undefined, this)
|
|
1633
|
-
]
|
|
1634
|
-
}, undefined, true, undefined, this);
|
|
1635
|
-
}
|
|
1636
|
-
function renderVisualizationWidget(widget2) {
|
|
1637
|
-
const footer = /* @__PURE__ */ jsxDEV("span", {
|
|
1638
|
-
className: "text-muted-foreground text-xs",
|
|
1639
|
-
children: [
|
|
1640
|
-
"Position: (",
|
|
1641
|
-
widget2.gridX,
|
|
1642
|
-
", ",
|
|
1643
|
-
widget2.gridY,
|
|
1644
|
-
") \u2022 ",
|
|
1645
|
-
widget2.gridWidth,
|
|
1646
|
-
"x",
|
|
1647
|
-
widget2.gridHeight
|
|
1648
|
-
]
|
|
1649
|
-
}, undefined, true, undefined, this);
|
|
1650
|
-
if (widget2.layout === "comparison") {
|
|
1651
|
-
return /* @__PURE__ */ jsxDEV(ComparisonView, {
|
|
1652
|
-
description: widget2.description,
|
|
1653
|
-
items: widget2.bindings.map((binding3) => ({ ...binding3, footer })),
|
|
1654
|
-
title: widget2.name
|
|
1655
|
-
}, undefined, false, undefined, this);
|
|
1656
|
-
}
|
|
1657
|
-
if (widget2.layout === "timeline") {
|
|
1658
|
-
return /* @__PURE__ */ jsxDEV(TimelineView, {
|
|
1659
|
-
description: widget2.description,
|
|
1660
|
-
items: widget2.bindings.map((binding3) => ({ ...binding3, footer })),
|
|
1661
|
-
title: widget2.name
|
|
1662
|
-
}, undefined, false, undefined, this);
|
|
1663
|
-
}
|
|
1664
|
-
const binding2 = widget2.bindings[0];
|
|
1665
|
-
if (!binding2)
|
|
1666
|
-
return null;
|
|
1667
|
-
return /* @__PURE__ */ jsxDEV(VisualizationCard, {
|
|
1668
|
-
data: binding2.data,
|
|
1669
|
-
description: widget2.description ?? binding2.description,
|
|
1670
|
-
footer,
|
|
1671
|
-
height: binding2.height,
|
|
1672
|
-
spec: binding2.spec,
|
|
1673
|
-
title: widget2.name
|
|
1674
|
-
}, undefined, false, undefined, this);
|
|
1675
|
-
}
|
|
1676
|
-
function gridSpanClass(gridWidth) {
|
|
1677
|
-
if (gridWidth >= 12)
|
|
1678
|
-
return "md:col-span-2 xl:col-span-3";
|
|
1679
|
-
if (gridWidth >= 8)
|
|
1680
|
-
return "xl:col-span-2";
|
|
1681
|
-
if (gridWidth >= 6)
|
|
1682
|
-
return "md:col-span-2";
|
|
1683
|
-
return "";
|
|
1684
|
-
}
|
|
1685
|
-
|
|
1686
|
-
// src/ui/AnalyticsQueriesTable.tsx
|
|
1687
|
-
import { DataTable } from "@contractspec/lib.design-system";
|
|
1688
|
-
import { useContractTable } from "@contractspec/lib.presentation-runtime-react";
|
|
1689
|
-
import { Badge } from "@contractspec/lib.ui-kit-web/ui/badge";
|
|
1690
|
-
import { HStack, VStack } from "@contractspec/lib.ui-kit-web/ui/stack";
|
|
1691
|
-
import { Text } from "@contractspec/lib.ui-kit-web/ui/text";
|
|
1692
|
-
import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
|
|
1693
|
-
"use client";
|
|
1694
|
-
var QUERY_TYPE_COLORS = {
|
|
1695
|
-
SQL: "default",
|
|
1696
|
-
METRIC: "secondary",
|
|
1697
|
-
AGGREGATION: "secondary",
|
|
1698
|
-
CUSTOM: "outline"
|
|
1699
|
-
};
|
|
1700
|
-
function formatJson(value) {
|
|
1701
|
-
return JSON.stringify(value, null, 2);
|
|
1702
|
-
}
|
|
1703
|
-
function AnalyticsQueriesTable({ queries }) {
|
|
1704
|
-
const controller = useContractTable({
|
|
1705
|
-
data: queries,
|
|
1706
|
-
columns: [
|
|
1707
|
-
{
|
|
1708
|
-
id: "query",
|
|
1709
|
-
header: "Query",
|
|
1710
|
-
label: "Query",
|
|
1711
|
-
accessor: (query) => query.name,
|
|
1712
|
-
cell: ({ item }) => /* @__PURE__ */ jsxDEV2(VStack, {
|
|
1713
|
-
gap: "xs",
|
|
1714
|
-
children: [
|
|
1715
|
-
/* @__PURE__ */ jsxDEV2(Text, {
|
|
1716
|
-
className: "font-medium text-sm",
|
|
1717
|
-
children: item.name
|
|
1718
|
-
}, undefined, false, undefined, this),
|
|
1719
|
-
/* @__PURE__ */ jsxDEV2(Text, {
|
|
1720
|
-
className: "text-muted-foreground text-xs",
|
|
1721
|
-
children: [
|
|
1722
|
-
"Updated ",
|
|
1723
|
-
item.updatedAt.toLocaleDateString()
|
|
1724
|
-
]
|
|
1725
|
-
}, undefined, true, undefined, this)
|
|
1726
|
-
]
|
|
1727
|
-
}, undefined, true, undefined, this),
|
|
1728
|
-
size: 240,
|
|
1729
|
-
minSize: 180,
|
|
1730
|
-
canSort: true,
|
|
1731
|
-
canPin: true,
|
|
1732
|
-
canResize: true
|
|
1733
|
-
},
|
|
1734
|
-
{
|
|
1735
|
-
id: "description",
|
|
1736
|
-
header: "Description",
|
|
1737
|
-
label: "Description",
|
|
1738
|
-
accessor: (query) => query.description ?? "",
|
|
1739
|
-
cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Text, {
|
|
1740
|
-
className: "line-clamp-2 text-muted-foreground text-sm",
|
|
1741
|
-
children: String(value || "No description")
|
|
1742
|
-
}, undefined, false, undefined, this),
|
|
1743
|
-
size: 300,
|
|
1744
|
-
minSize: 220,
|
|
1745
|
-
canSort: false,
|
|
1746
|
-
canHide: true,
|
|
1747
|
-
canResize: true
|
|
1748
|
-
},
|
|
1749
|
-
{
|
|
1750
|
-
id: "type",
|
|
1751
|
-
header: "Type",
|
|
1752
|
-
label: "Type",
|
|
1753
|
-
accessorKey: "type",
|
|
1754
|
-
cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Badge, {
|
|
1755
|
-
variant: QUERY_TYPE_COLORS[String(value)],
|
|
1756
|
-
children: String(value)
|
|
1757
|
-
}, undefined, false, undefined, this),
|
|
1758
|
-
size: 150,
|
|
1759
|
-
canSort: true,
|
|
1760
|
-
canHide: true,
|
|
1761
|
-
canResize: true
|
|
1762
|
-
},
|
|
1763
|
-
{
|
|
1764
|
-
id: "cacheTtlSeconds",
|
|
1765
|
-
header: "Cache TTL",
|
|
1766
|
-
label: "Cache TTL",
|
|
1767
|
-
accessorKey: "cacheTtlSeconds",
|
|
1768
|
-
cell: ({ value }) => `${String(value)}s`,
|
|
1769
|
-
align: "right",
|
|
1770
|
-
size: 140,
|
|
1771
|
-
canSort: true,
|
|
1772
|
-
canResize: true
|
|
1773
|
-
},
|
|
1774
|
-
{
|
|
1775
|
-
id: "isShared",
|
|
1776
|
-
header: "Shared",
|
|
1777
|
-
label: "Shared",
|
|
1778
|
-
accessorKey: "isShared",
|
|
1779
|
-
cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Badge, {
|
|
1780
|
-
variant: value ? "default" : "outline",
|
|
1781
|
-
children: value ? "Shared" : "Private"
|
|
1782
|
-
}, undefined, false, undefined, this),
|
|
1783
|
-
size: 140,
|
|
1784
|
-
canSort: true,
|
|
1785
|
-
canHide: true,
|
|
1786
|
-
canResize: true
|
|
1787
|
-
}
|
|
1788
|
-
],
|
|
1789
|
-
initialState: {
|
|
1790
|
-
pagination: { pageIndex: 0, pageSize: 3 },
|
|
1791
|
-
columnVisibility: { description: false },
|
|
1792
|
-
columnPinning: { left: ["query"], right: [] }
|
|
1793
|
-
},
|
|
1794
|
-
renderExpandedContent: (query) => /* @__PURE__ */ jsxDEV2(VStack, {
|
|
1795
|
-
gap: "sm",
|
|
1796
|
-
className: "py-2",
|
|
1797
|
-
children: [
|
|
1798
|
-
/* @__PURE__ */ jsxDEV2(VStack, {
|
|
1799
|
-
gap: "xs",
|
|
1800
|
-
children: [
|
|
1801
|
-
/* @__PURE__ */ jsxDEV2(Text, {
|
|
1802
|
-
className: "font-medium text-sm",
|
|
1803
|
-
children: "Description"
|
|
1804
|
-
}, undefined, false, undefined, this),
|
|
1805
|
-
/* @__PURE__ */ jsxDEV2(Text, {
|
|
1806
|
-
className: "text-muted-foreground text-sm",
|
|
1807
|
-
children: query.description ?? "No description"
|
|
1808
|
-
}, undefined, false, undefined, this)
|
|
1809
|
-
]
|
|
1810
|
-
}, undefined, true, undefined, this),
|
|
1811
|
-
query.sql ? /* @__PURE__ */ jsxDEV2(VStack, {
|
|
1812
|
-
gap: "xs",
|
|
1813
|
-
children: [
|
|
1814
|
-
/* @__PURE__ */ jsxDEV2(Text, {
|
|
1815
|
-
className: "font-medium text-sm",
|
|
1816
|
-
children: "SQL"
|
|
1817
|
-
}, undefined, false, undefined, this),
|
|
1818
|
-
/* @__PURE__ */ jsxDEV2("pre", {
|
|
1819
|
-
className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
|
|
1820
|
-
children: query.sql
|
|
1821
|
-
}, undefined, false, undefined, this)
|
|
1822
|
-
]
|
|
1823
|
-
}, undefined, true, undefined, this) : null,
|
|
1824
|
-
/* @__PURE__ */ jsxDEV2(VStack, {
|
|
1825
|
-
gap: "xs",
|
|
1826
|
-
children: [
|
|
1827
|
-
/* @__PURE__ */ jsxDEV2(Text, {
|
|
1828
|
-
className: "font-medium text-sm",
|
|
1829
|
-
children: "Definition"
|
|
1830
|
-
}, undefined, false, undefined, this),
|
|
1831
|
-
/* @__PURE__ */ jsxDEV2("pre", {
|
|
1832
|
-
className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
|
|
1833
|
-
children: formatJson(query.definition)
|
|
1834
|
-
}, undefined, false, undefined, this)
|
|
1835
|
-
]
|
|
1836
|
-
}, undefined, true, undefined, this)
|
|
1837
|
-
]
|
|
1838
|
-
}, undefined, true, undefined, this),
|
|
1839
|
-
getCanExpand: () => true
|
|
1840
|
-
});
|
|
1841
|
-
return /* @__PURE__ */ jsxDEV2(DataTable, {
|
|
1842
|
-
controller,
|
|
1843
|
-
title: "Saved Queries",
|
|
1844
|
-
description: "Client-mode table using the shared ContractSpec controller and renderer.",
|
|
1845
|
-
toolbar: /* @__PURE__ */ jsxDEV2(HStack, {
|
|
1846
|
-
gap: "sm",
|
|
1847
|
-
className: "flex-wrap",
|
|
1848
|
-
children: [
|
|
1849
|
-
/* @__PURE__ */ jsxDEV2(Text, {
|
|
1850
|
-
className: "text-muted-foreground text-sm",
|
|
1851
|
-
children: [
|
|
1852
|
-
queries.length,
|
|
1853
|
-
" queries"
|
|
1854
|
-
]
|
|
1855
|
-
}, undefined, true, undefined, this),
|
|
1856
|
-
/* @__PURE__ */ jsxDEV2(Text, {
|
|
1857
|
-
className: "text-muted-foreground text-sm",
|
|
1858
|
-
children: [
|
|
1859
|
-
queries.filter((query) => query.isShared).length,
|
|
1860
|
-
" shared"
|
|
1861
|
-
]
|
|
1862
|
-
}, undefined, true, undefined, this)
|
|
1863
|
-
]
|
|
1864
|
-
}, undefined, true, undefined, this),
|
|
1865
|
-
emptyState: /* @__PURE__ */ jsxDEV2("div", {
|
|
1866
|
-
className: "rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",
|
|
1867
|
-
children: "No queries saved"
|
|
1868
|
-
}, undefined, false, undefined, this)
|
|
1869
|
-
}, undefined, false, undefined, this);
|
|
1870
|
-
}
|
|
1871
|
-
|
|
1872
|
-
// src/ui/hooks/useAnalyticsData.ts
|
|
1873
|
-
import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
|
|
1874
|
-
import { useCallback, useEffect, useState } from "react";
|
|
1875
|
-
"use client";
|
|
1876
|
-
function useAnalyticsData(projectId = "local-project") {
|
|
1877
|
-
const { handlers } = useTemplateRuntime();
|
|
1878
|
-
const analytics = handlers.analytics;
|
|
1879
|
-
const [dashboards, setDashboards] = useState([]);
|
|
1880
|
-
const [queries, setQueries] = useState([]);
|
|
1881
|
-
const [selectedDashboard, setSelectedDashboard] = useState(null);
|
|
1882
|
-
const [widgets, setWidgets] = useState([]);
|
|
1883
|
-
const [loading, setLoading] = useState(true);
|
|
1884
|
-
const [error, setError] = useState(null);
|
|
1885
|
-
const fetchData = useCallback(async () => {
|
|
1886
|
-
try {
|
|
1887
|
-
setLoading(true);
|
|
1888
|
-
setError(null);
|
|
1889
|
-
const [dashResult, queryResult] = await Promise.all([
|
|
1890
|
-
analytics.listDashboards({ projectId, limit: 100 }),
|
|
1891
|
-
analytics.listQueries({ projectId, limit: 100 })
|
|
1892
|
-
]);
|
|
1893
|
-
setDashboards(dashResult.dashboards);
|
|
1894
|
-
setQueries(queryResult.queries);
|
|
1895
|
-
if (dashResult.dashboards.length > 0 && !selectedDashboard) {
|
|
1896
|
-
const first = dashResult.dashboards[0];
|
|
1897
|
-
if (first) {
|
|
1898
|
-
setSelectedDashboard(first);
|
|
1899
|
-
const dashboardWidgets = await analytics.getWidgets(first.id);
|
|
1900
|
-
setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(first.id));
|
|
1901
|
-
}
|
|
1902
|
-
}
|
|
1903
|
-
} catch (err) {
|
|
1904
|
-
setError(err instanceof Error ? err : new Error("Failed to load analytics"));
|
|
1905
|
-
} finally {
|
|
1906
|
-
setLoading(false);
|
|
1907
|
-
}
|
|
1908
|
-
}, [analytics, projectId, selectedDashboard]);
|
|
1909
|
-
useEffect(() => {
|
|
1910
|
-
fetchData();
|
|
1911
|
-
}, [fetchData]);
|
|
1912
|
-
const selectDashboard = useCallback(async (dashboard) => {
|
|
1913
|
-
setSelectedDashboard(dashboard);
|
|
1914
|
-
const dashboardWidgets = await analytics.getWidgets(dashboard.id);
|
|
1915
|
-
setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(dashboard.id));
|
|
1916
|
-
}, [analytics]);
|
|
1917
|
-
const stats = {
|
|
1918
|
-
totalDashboards: dashboards.length,
|
|
1919
|
-
publishedDashboards: dashboards.filter((d) => d.status === "PUBLISHED").length,
|
|
1920
|
-
totalQueries: queries.length,
|
|
1921
|
-
sharedQueries: queries.filter((q) => q.isShared).length
|
|
1922
|
-
};
|
|
1923
|
-
return {
|
|
1924
|
-
dashboards,
|
|
1925
|
-
queries,
|
|
1926
|
-
selectedDashboard,
|
|
1927
|
-
widgets,
|
|
1928
|
-
loading,
|
|
1929
|
-
error,
|
|
1930
|
-
stats,
|
|
1931
|
-
refetch: fetchData,
|
|
1932
|
-
selectDashboard
|
|
1933
|
-
};
|
|
1934
|
-
}
|
|
1935
|
-
|
|
1936
|
-
// src/ui/AnalyticsDashboard.tsx
|
|
1937
|
-
import {
|
|
1938
|
-
Button,
|
|
1939
|
-
ErrorState,
|
|
1940
|
-
LoaderBlock,
|
|
1941
|
-
StatCard,
|
|
1942
|
-
StatCardGroup
|
|
1943
|
-
} from "@contractspec/lib.design-system";
|
|
1944
|
-
import { useMemo, useState as useState2 } from "react";
|
|
1945
|
-
import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
|
|
1946
|
-
"use client";
|
|
1947
|
-
var STATUS_COLORS = {
|
|
1948
|
-
PUBLISHED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
|
|
1949
|
-
DRAFT: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
|
|
1950
|
-
ARCHIVED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
|
|
1951
|
-
};
|
|
1952
|
-
function AnalyticsDashboard() {
|
|
1953
|
-
const [activeTab, setActiveTab] = useState2("dashboards");
|
|
1954
|
-
const {
|
|
1955
|
-
dashboards,
|
|
1956
|
-
queries,
|
|
1957
|
-
selectedDashboard,
|
|
1958
|
-
widgets,
|
|
1959
|
-
loading,
|
|
1960
|
-
error,
|
|
1961
|
-
stats,
|
|
1962
|
-
refetch,
|
|
1963
|
-
selectDashboard
|
|
1964
|
-
} = useAnalyticsData();
|
|
1965
|
-
const tabs = [
|
|
1966
|
-
{ id: "dashboards", label: "Dashboards", icon: "\uD83D\uDCCA" },
|
|
1967
|
-
{ id: "queries", label: "Queries", icon: "\uD83D\uDD0D" }
|
|
1968
|
-
];
|
|
1969
|
-
const resolvedWidgets = useMemo(() => widgets.map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2)), [widgets]);
|
|
1970
|
-
if (loading) {
|
|
1971
|
-
return /* @__PURE__ */ jsxDEV3(LoaderBlock, {
|
|
1972
|
-
label: "Loading Analytics..."
|
|
1973
|
-
}, undefined, false, undefined, this);
|
|
1974
|
-
}
|
|
1975
|
-
if (error) {
|
|
1976
|
-
return /* @__PURE__ */ jsxDEV3(ErrorState, {
|
|
1977
|
-
title: "Failed to load Analytics",
|
|
1978
|
-
description: error.message,
|
|
1979
|
-
onRetry: refetch,
|
|
1980
|
-
retryLabel: "Retry"
|
|
1981
|
-
}, undefined, false, undefined, this);
|
|
1982
|
-
}
|
|
1983
|
-
return /* @__PURE__ */ jsxDEV3("div", {
|
|
1984
|
-
className: "space-y-6",
|
|
1985
|
-
children: [
|
|
1986
|
-
/* @__PURE__ */ jsxDEV3("div", {
|
|
1987
|
-
className: "flex items-center justify-between",
|
|
1988
|
-
children: [
|
|
1989
|
-
/* @__PURE__ */ jsxDEV3("h2", {
|
|
1990
|
-
className: "font-bold text-2xl",
|
|
1991
|
-
children: "Analytics Dashboard"
|
|
1992
|
-
}, undefined, false, undefined, this),
|
|
1993
|
-
/* @__PURE__ */ jsxDEV3(Button, {
|
|
1994
|
-
onClick: () => alert("Create dashboard modal"),
|
|
1995
|
-
children: [
|
|
1996
|
-
/* @__PURE__ */ jsxDEV3("span", {
|
|
1997
|
-
className: "mr-2",
|
|
1998
|
-
children: "+"
|
|
1999
|
-
}, undefined, false, undefined, this),
|
|
2000
|
-
" New Dashboard"
|
|
2001
|
-
]
|
|
2002
|
-
}, undefined, true, undefined, this)
|
|
2003
|
-
]
|
|
2004
|
-
}, undefined, true, undefined, this),
|
|
2005
|
-
/* @__PURE__ */ jsxDEV3(StatCardGroup, {
|
|
2006
|
-
children: [
|
|
2007
|
-
/* @__PURE__ */ jsxDEV3(StatCard, {
|
|
2008
|
-
label: "Dashboards",
|
|
2009
|
-
value: stats.totalDashboards,
|
|
2010
|
-
hint: `${stats.publishedDashboards} published`
|
|
2011
|
-
}, undefined, false, undefined, this),
|
|
2012
|
-
/* @__PURE__ */ jsxDEV3(StatCard, {
|
|
2013
|
-
label: "Queries",
|
|
2014
|
-
value: stats.totalQueries,
|
|
2015
|
-
hint: `${stats.sharedQueries} shared`
|
|
2016
|
-
}, undefined, false, undefined, this),
|
|
2017
|
-
/* @__PURE__ */ jsxDEV3(StatCard, {
|
|
2018
|
-
label: "Widgets",
|
|
2019
|
-
value: widgets.length,
|
|
2020
|
-
hint: "on current dashboard"
|
|
2021
|
-
}, undefined, false, undefined, this)
|
|
2022
|
-
]
|
|
2023
|
-
}, undefined, true, undefined, this),
|
|
2024
|
-
/* @__PURE__ */ jsxDEV3("nav", {
|
|
2025
|
-
className: "flex gap-1 rounded-lg bg-muted p-1",
|
|
2026
|
-
role: "tablist",
|
|
2027
|
-
children: tabs.map((tab) => /* @__PURE__ */ jsxDEV3(Button, {
|
|
2028
|
-
type: "button",
|
|
2029
|
-
role: "tab",
|
|
2030
|
-
"aria-selected": activeTab === tab.id,
|
|
2031
|
-
onClick: () => setActiveTab(tab.id),
|
|
2032
|
-
className: `flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${activeTab === tab.id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
|
|
2033
|
-
children: [
|
|
2034
|
-
/* @__PURE__ */ jsxDEV3("span", {
|
|
2035
|
-
children: tab.icon
|
|
2036
|
-
}, undefined, false, undefined, this),
|
|
2037
|
-
tab.label
|
|
2038
|
-
]
|
|
2039
|
-
}, tab.id, true, undefined, this))
|
|
2040
|
-
}, undefined, false, undefined, this),
|
|
2041
|
-
/* @__PURE__ */ jsxDEV3("div", {
|
|
2042
|
-
className: "min-h-[400px]",
|
|
2043
|
-
role: "tabpanel",
|
|
2044
|
-
children: [
|
|
2045
|
-
activeTab === "dashboards" && /* @__PURE__ */ jsxDEV3("div", {
|
|
2046
|
-
className: "space-y-6",
|
|
2047
|
-
children: [
|
|
2048
|
-
/* @__PURE__ */ jsxDEV3("div", {
|
|
2049
|
-
className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
|
|
2050
|
-
children: [
|
|
2051
|
-
dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV3("div", {
|
|
2052
|
-
onClick: () => selectDashboard(dashboard),
|
|
2053
|
-
className: `cursor-pointer rounded-lg border border-border bg-card p-4 transition-all ${selectedDashboard?.id === dashboard.id ? "ring-2 ring-primary" : "hover:bg-muted/50"}`,
|
|
2054
|
-
role: "button",
|
|
2055
|
-
tabIndex: 0,
|
|
2056
|
-
onKeyDown: (e) => {
|
|
2057
|
-
if (e.key === "Enter" || e.key === " ")
|
|
2058
|
-
selectDashboard(dashboard);
|
|
2059
|
-
},
|
|
2060
|
-
children: [
|
|
2061
|
-
/* @__PURE__ */ jsxDEV3("div", {
|
|
2062
|
-
className: "mb-2 flex items-center justify-between",
|
|
2063
|
-
children: [
|
|
2064
|
-
/* @__PURE__ */ jsxDEV3("h3", {
|
|
2065
|
-
className: "font-medium",
|
|
2066
|
-
children: dashboard.name
|
|
2067
|
-
}, undefined, false, undefined, this),
|
|
2068
|
-
/* @__PURE__ */ jsxDEV3("span", {
|
|
2069
|
-
className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[dashboard.status] ?? ""}`,
|
|
2070
|
-
children: dashboard.status
|
|
2071
|
-
}, undefined, false, undefined, this)
|
|
2072
|
-
]
|
|
2073
|
-
}, undefined, true, undefined, this),
|
|
2074
|
-
/* @__PURE__ */ jsxDEV3("p", {
|
|
2075
|
-
className: "mb-3 text-muted-foreground text-sm",
|
|
2076
|
-
children: dashboard.description
|
|
2077
|
-
}, undefined, false, undefined, this),
|
|
2078
|
-
/* @__PURE__ */ jsxDEV3("div", {
|
|
2079
|
-
className: "flex items-center justify-between text-muted-foreground text-xs",
|
|
2080
|
-
children: [
|
|
2081
|
-
/* @__PURE__ */ jsxDEV3("span", {
|
|
2082
|
-
children: [
|
|
2083
|
-
"/",
|
|
2084
|
-
dashboard.slug
|
|
2085
|
-
]
|
|
2086
|
-
}, undefined, true, undefined, this),
|
|
2087
|
-
dashboard.isPublic && /* @__PURE__ */ jsxDEV3("span", {
|
|
2088
|
-
className: "text-green-600 dark:text-green-400",
|
|
2089
|
-
children: "\uD83C\uDF10 Public"
|
|
2090
|
-
}, undefined, false, undefined, this)
|
|
2091
|
-
]
|
|
2092
|
-
}, undefined, true, undefined, this)
|
|
2093
|
-
]
|
|
2094
|
-
}, dashboard.id, true, undefined, this)),
|
|
2095
|
-
dashboards.length === 0 && /* @__PURE__ */ jsxDEV3("div", {
|
|
2096
|
-
className: "col-span-full flex h-64 items-center justify-center text-muted-foreground",
|
|
2097
|
-
children: "No dashboards created yet"
|
|
2098
|
-
}, undefined, false, undefined, this)
|
|
2099
|
-
]
|
|
2100
|
-
}, undefined, true, undefined, this),
|
|
2101
|
-
selectedDashboard ? /* @__PURE__ */ jsxDEV3(AnalyticsWidgetBoard, {
|
|
2102
|
-
dashboardName: selectedDashboard.name,
|
|
2103
|
-
widgets: resolvedWidgets
|
|
2104
|
-
}, undefined, false, undefined, this) : null
|
|
2105
|
-
]
|
|
2106
|
-
}, undefined, true, undefined, this),
|
|
2107
|
-
activeTab === "queries" && /* @__PURE__ */ jsxDEV3(AnalyticsQueriesTable, {
|
|
2108
|
-
queries
|
|
2109
|
-
}, undefined, false, undefined, this)
|
|
2110
|
-
]
|
|
2111
|
-
}, undefined, true, undefined, this)
|
|
2112
|
-
]
|
|
2113
|
-
}, undefined, true, undefined, this);
|
|
2114
|
-
}
|
|
2115
|
-
|
|
2116
|
-
// src/ui/hooks/index.ts
|
|
2117
|
-
"use client";
|
|
2118
|
-
|
|
2119
|
-
// src/ui/renderers/analytics.markdown.ts
|
|
2120
|
-
var mockDashboards = [
|
|
2121
|
-
{
|
|
2122
|
-
id: "dash-1",
|
|
2123
|
-
name: "Sales Overview",
|
|
2124
|
-
slug: "sales-overview",
|
|
2125
|
-
status: "PUBLISHED",
|
|
2126
|
-
widgetCount: 11,
|
|
2127
|
-
viewCount: 1250,
|
|
2128
|
-
lastViewedAt: "2026-03-18T12:00:00Z"
|
|
2129
|
-
},
|
|
2130
|
-
{
|
|
2131
|
-
id: "dash-2",
|
|
2132
|
-
name: "User Engagement",
|
|
2133
|
-
slug: "user-engagement",
|
|
2134
|
-
status: "PUBLISHED",
|
|
2135
|
-
widgetCount: 8,
|
|
2136
|
-
viewCount: 890,
|
|
2137
|
-
lastViewedAt: "2026-03-18T10:00:00Z"
|
|
2138
|
-
}
|
|
2139
|
-
];
|
|
2140
|
-
var mockQueries = [
|
|
2141
|
-
{
|
|
2142
|
-
id: "q-1",
|
|
2143
|
-
name: "Monthly Revenue",
|
|
2144
|
-
type: "AGGREGATION",
|
|
2145
|
-
isShared: true,
|
|
2146
|
-
executionCount: 1500
|
|
2147
|
-
},
|
|
2148
|
-
{
|
|
2149
|
-
id: "q-2",
|
|
2150
|
-
name: "User Growth",
|
|
2151
|
-
type: "METRIC",
|
|
2152
|
-
isShared: true,
|
|
2153
|
-
executionCount: 890
|
|
2154
|
-
},
|
|
2155
|
-
{
|
|
2156
|
-
id: "q-3",
|
|
2157
|
-
name: "Product Sales",
|
|
2158
|
-
type: "SQL",
|
|
2159
|
-
isShared: false,
|
|
2160
|
-
executionCount: 340
|
|
2161
|
-
},
|
|
2162
|
-
{
|
|
2163
|
-
id: "q-4",
|
|
2164
|
-
name: "Conversion Funnel",
|
|
2165
|
-
type: "AGGREGATION",
|
|
2166
|
-
isShared: true,
|
|
2167
|
-
executionCount: 450
|
|
2168
|
-
}
|
|
2169
|
-
];
|
|
2170
|
-
function dashboardWidgets(dashboardId) {
|
|
2171
|
-
return createExampleWidgets(dashboardId).map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2));
|
|
2172
|
-
}
|
|
2173
|
-
var analyticsDashboardMarkdownRenderer = {
|
|
2174
|
-
target: "markdown",
|
|
2175
|
-
render: async (desc) => {
|
|
2176
|
-
if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
|
|
2177
|
-
throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
|
|
2178
|
-
}
|
|
2179
|
-
const dashboard = mockDashboards[0];
|
|
2180
|
-
if (!dashboard) {
|
|
2181
|
-
return {
|
|
2182
|
-
mimeType: "text/markdown",
|
|
2183
|
-
body: `# No Dashboards
|
|
2184
|
-
|
|
2185
|
-
No dashboards available.`
|
|
2186
|
-
};
|
|
2187
|
-
}
|
|
2188
|
-
const widgets = dashboardWidgets(dashboard.id);
|
|
2189
|
-
const metricWidgets = widgets.filter((widget2) => widget2.bindings[0]?.spec.visualization.kind === "metric");
|
|
2190
|
-
const lines = [
|
|
2191
|
-
`# ${dashboard.name}`,
|
|
2192
|
-
"",
|
|
2193
|
-
"> Contract-backed analytics dashboard overview.",
|
|
2194
|
-
"",
|
|
2195
|
-
"## Key Metrics",
|
|
2196
|
-
""
|
|
2197
|
-
];
|
|
2198
|
-
for (const widget2 of metricWidgets) {
|
|
2199
|
-
const binding2 = widget2.bindings[0];
|
|
2200
|
-
if (!binding2)
|
|
2201
|
-
continue;
|
|
2202
|
-
lines.push(`- **${widget2.name}** via \`${binding2.spec.meta.key}\``);
|
|
2203
|
-
}
|
|
2204
|
-
lines.push("");
|
|
2205
|
-
lines.push("## Visual Blocks");
|
|
2206
|
-
lines.push("");
|
|
2207
|
-
for (const widget2 of widgets) {
|
|
2208
|
-
const kinds = widget2.bindings.map((binding2) => binding2.spec.visualization.kind).join(", ");
|
|
2209
|
-
lines.push(`- **${widget2.name}** (${widget2.layout}) \u2192 ${kinds}`);
|
|
2210
|
-
}
|
|
2211
|
-
lines.push("");
|
|
2212
|
-
lines.push("## Dashboard Stats");
|
|
2213
|
-
lines.push("");
|
|
2214
|
-
lines.push("| Metric | Value |");
|
|
2215
|
-
lines.push("|--------|-------|");
|
|
2216
|
-
lines.push(`| Total Dashboards | ${mockDashboards.length} |`);
|
|
2217
|
-
lines.push(`| Published | ${mockDashboards.filter((item) => item.status === "PUBLISHED").length} |`);
|
|
2218
|
-
lines.push(`| Shared Queries | ${mockQueries.filter((query) => query.isShared).length} |`);
|
|
2219
|
-
return {
|
|
2220
|
-
mimeType: "text/markdown",
|
|
2221
|
-
body: lines.join(`
|
|
2222
|
-
`)
|
|
2223
|
-
};
|
|
2224
|
-
}
|
|
2225
|
-
};
|
|
2226
|
-
var dashboardListMarkdownRenderer = {
|
|
2227
|
-
target: "markdown",
|
|
2228
|
-
render: async (desc) => {
|
|
2229
|
-
if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
|
|
2230
|
-
throw new Error("dashboardListMarkdownRenderer: not DashboardList");
|
|
2231
|
-
}
|
|
2232
|
-
const lines = [
|
|
2233
|
-
"# Dashboards",
|
|
2234
|
-
"",
|
|
2235
|
-
"> Browse and manage analytics dashboards",
|
|
2236
|
-
"",
|
|
2237
|
-
"| Dashboard | Widgets | Views | Status | Last Viewed |",
|
|
2238
|
-
"|-----------|---------|-------|--------|-------------|"
|
|
2239
|
-
];
|
|
2240
|
-
for (const dashboard of mockDashboards) {
|
|
2241
|
-
const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
|
|
2242
|
-
const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "\u26AB";
|
|
2243
|
-
lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
|
|
2244
|
-
}
|
|
2245
|
-
return {
|
|
2246
|
-
mimeType: "text/markdown",
|
|
2247
|
-
body: lines.join(`
|
|
2248
|
-
`)
|
|
2249
|
-
};
|
|
2250
|
-
}
|
|
2251
|
-
};
|
|
2252
|
-
var queryBuilderMarkdownRenderer = {
|
|
2253
|
-
target: "markdown",
|
|
2254
|
-
render: async (desc) => {
|
|
2255
|
-
if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
|
|
2256
|
-
throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
|
|
2257
|
-
}
|
|
2258
|
-
const lines = [
|
|
2259
|
-
"# Query Builder",
|
|
2260
|
-
"",
|
|
2261
|
-
"> Create and manage reusable data queries.",
|
|
2262
|
-
"",
|
|
2263
|
-
"| Query | Type | Shared | Executions |",
|
|
2264
|
-
"|-------|------|--------|------------|"
|
|
2265
|
-
];
|
|
2266
|
-
for (const query of mockQueries) {
|
|
2267
|
-
lines.push(`| ${query.name} | ${query.type} | ${query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12"} | ${query.executionCount.toLocaleString()} |`);
|
|
2268
|
-
}
|
|
2269
|
-
lines.push("");
|
|
2270
|
-
lines.push("## Visualization Contracts");
|
|
2271
|
-
lines.push("");
|
|
2272
|
-
lines.push("Widgets reference `VisualizationSpec` contracts instead of rendering ad-hoc widget types.");
|
|
2273
|
-
return {
|
|
2274
|
-
mimeType: "text/markdown",
|
|
2275
|
-
body: lines.join(`
|
|
2276
|
-
`)
|
|
2277
|
-
};
|
|
2278
|
-
}
|
|
2279
|
-
};
|
|
2280
|
-
export {
|
|
2281
|
-
visualizationRefKey,
|
|
2282
|
-
useAnalyticsData,
|
|
2283
|
-
resolveAnalyticsWidget,
|
|
2284
|
-
refOf,
|
|
2285
|
-
queryBuilderMarkdownRenderer,
|
|
2286
|
-
dashboardListMarkdownRenderer,
|
|
2287
|
-
createQueryEngine,
|
|
2288
|
-
createPosthogQueryEngine,
|
|
2289
|
-
createExampleWidgets,
|
|
2290
|
-
createAnalyticsHandlers,
|
|
2291
|
-
analyticsDashboardMarkdownRenderer,
|
|
2292
|
-
RevenueTrendVisualization,
|
|
2293
|
-
RevenueMetricVisualization,
|
|
2294
|
-
RetentionAreaVisualization,
|
|
2295
|
-
RegionalRevenueVisualization,
|
|
2296
|
-
QueryTypeEnum,
|
|
2297
|
-
QueryResultModel,
|
|
2298
|
-
QueryModel,
|
|
2299
|
-
PosthogQueryEngine,
|
|
2300
|
-
PipelineScatterVisualization,
|
|
2301
|
-
InMemoryQueryCache,
|
|
2302
|
-
ExecuteQueryInputModel,
|
|
2303
|
-
ExecuteQueryContract,
|
|
2304
|
-
EngagementHeatmapVisualization,
|
|
2305
|
-
CreateQueryInputModel,
|
|
2306
|
-
CreateQueryContract,
|
|
2307
|
-
ConversionFunnelVisualization,
|
|
2308
|
-
ChannelMixVisualization,
|
|
2309
|
-
BasicQueryEngine,
|
|
2310
|
-
AnalyticsVisualizationSpecs,
|
|
2311
|
-
AnalyticsVisualizationSpecMap,
|
|
2312
|
-
AnalyticsVisualizationSampleData,
|
|
2313
|
-
AnalyticsVisualizationRegistry,
|
|
2314
|
-
AnalyticsVisualizationRefs,
|
|
2315
|
-
AnalyticsDashboardFeature,
|
|
2316
|
-
AnalyticsDashboard,
|
|
2317
|
-
AccountCoverageGeoVisualization
|
|
2318
|
-
};
|
|
2
|
+
import{defineVisualization as b}from"@contractspec/lib.contracts-spec/visualizations";var s={key:"analytics.query.execute",version:"1.0.0"},i={version:"1.0.0",domain:"analytics",stability:"experimental",owners:["@example.analytics-dashboard"],tags:["analytics","dashboard","visualization"]},R=b({meta:{...i,key:"analytics.visualization.channel-mix",title:"Channel Mix",description:"Session distribution across acquisition channels.",goal:"Explain which channels currently drive the largest share of traffic.",context:"Marketing attribution dashboard."},source:{primary:s,resultPath:"data"},visualization:{kind:"pie",nameDimension:"channel",valueMeasure:"sessions",dimensions:[{key:"channel",label:"Channel",dataPath:"channel",type:"category"}],measures:[{key:"sessions",label:"Sessions",dataPath:"sessions"}],table:{caption:"Sessions by acquisition channel."}}}),S=b({meta:{...i,key:"analytics.visualization.engagement-heatmap",title:"Engagement Heatmap",description:"Average engagement score by weekday and time band.",goal:"Reveal the highest-engagement time windows for product activity.",context:"Usage analytics dashboard."},source:{primary:s,resultPath:"data"},visualization:{kind:"heatmap",xDimension:"timeBand",yDimension:"weekday",valueMeasure:"engagementScore",dimensions:[{key:"timeBand",label:"Time Band",dataPath:"timeBand",type:"category"},{key:"weekday",label:"Weekday",dataPath:"weekday",type:"category"}],measures:[{key:"engagementScore",label:"Engagement",dataPath:"engagementScore"}],table:{caption:"Engagement score by weekday and time band."}}}),_=b({meta:{...i,key:"analytics.visualization.conversion-funnel",title:"Conversion Funnel",description:"Progression through the main acquisition funnel.",goal:"Show where the product is losing the largest share of prospects.",context:"Growth dashboard."},source:{primary:s,resultPath:"data"},visualization:{kind:"funnel",nameDimension:"stage",valueMeasure:"users",sort:"descending",dimensions:[{key:"stage",label:"Stage",dataPath:"stage",type:"category"}],measures:[{key:"users",label:"Users",dataPath:"users"}],table:{caption:"Users per conversion stage."}}}),g=b({meta:{...i,key:"analytics.visualization.account-coverage-geo",title:"Account Coverage",description:"High-value accounts plotted on a slippy-map surface.",goal:"Locate where active commercial concentration is strongest.",context:"Territory coverage dashboard."},source:{primary:s,resultPath:"data"},visualization:{kind:"geo",mode:"slippy-map",variant:"scatter",nameDimension:"city",latitudeDimension:"latitude",longitudeDimension:"longitude",valueMeasure:"accounts",dimensions:[{key:"city",label:"City",dataPath:"city",type:"category"},{key:"latitude",label:"Latitude",dataPath:"latitude",type:"latitude"},{key:"longitude",label:"Longitude",dataPath:"longitude",type:"longitude"}],measures:[{key:"accounts",label:"Accounts",dataPath:"accounts"}],table:{caption:"Account concentration by city."}}});import{defineVisualization as T}from"@contractspec/lib.contracts-spec/visualizations";var z={key:"analytics.query.execute",version:"1.0.0"},e={version:"1.0.0",domain:"analytics",stability:"experimental",owners:["@example.analytics-dashboard"],tags:["analytics","dashboard","visualization"]},x=T({meta:{...e,key:"analytics.visualization.revenue-metric",title:"Revenue Snapshot",description:"Current recurring revenue with prior-period comparison.",goal:"Highlight the headline commercial metric for the dashboard.",context:"Executive revenue overview."},source:{primary:z,resultPath:"data"},visualization:{kind:"metric",measure:"totalRevenue",comparisonMeasure:"priorRevenue",dimensions:[{key:"period",label:"Period",dataPath:"period",type:"time"}],measures:[{key:"totalRevenue",label:"Revenue",dataPath:"totalRevenue",format:"currency"},{key:"priorRevenue",label:"Prior Revenue",dataPath:"priorRevenue",format:"currency"}],sparkline:{dimension:"period",measure:"totalRevenue"},table:{caption:"Revenue trend and prior period values."}}}),f=T({meta:{...e,key:"analytics.visualization.revenue-trend",title:"Revenue Trend",description:"Monthly revenue progression for the current quarter.",goal:"Track whether revenue growth is accelerating or stalling.",context:"Quarterly commercial dashboard."},source:{primary:z,resultPath:"data"},visualization:{kind:"cartesian",variant:"line",xDimension:"date",yMeasures:["revenue"],dimensions:[{key:"date",label:"Month",dataPath:"date",type:"time"}],measures:[{key:"revenue",label:"Revenue",dataPath:"revenue",format:"currency",color:"#0f766e"}],thresholds:[{key:"target",value:140000,label:"Target",color:"#dc2626"}],table:{caption:"Monthly revenue values."}}}),h=T({meta:{...e,key:"analytics.visualization.regional-revenue",title:"Regional Revenue",description:"Revenue split by sales territory.",goal:"Compare the strongest and weakest performing territories.",context:"Territory planning and commercial comparison."},source:{primary:z,resultPath:"data"},visualization:{kind:"cartesian",variant:"bar",xDimension:"region",yMeasures:["revenue"],dimensions:[{key:"region",label:"Region",dataPath:"region",type:"category"}],measures:[{key:"revenue",label:"Revenue",dataPath:"revenue",format:"currency",color:"#1d4ed8"}],table:{caption:"Revenue by region."}}}),E=T({meta:{...e,key:"analytics.visualization.retention-area",title:"Retention Curve",description:"Weekly retention progression across the active cohort.",goal:"Show whether user retention remains above the desired floor.",context:"Product health dashboard."},source:{primary:z,resultPath:"data"},visualization:{kind:"cartesian",variant:"area",xDimension:"week",yMeasures:["retentionRate"],dimensions:[{key:"week",label:"Week",dataPath:"week",type:"category"}],measures:[{key:"retentionRate",label:"Retention",dataPath:"retentionRate",format:"percentage",color:"#16a34a"}],thresholds:[{key:"floor",value:0.5,label:"Floor",color:"#f59e0b"}],table:{caption:"Weekly retention rate."}}}),I=T({meta:{...e,key:"analytics.visualization.pipeline-scatter",title:"Pipeline Velocity",description:"Deal-cycle length against win rate for active accounts.",goal:"Spot outliers where the sales cycle is long but conversion remains weak.",context:"Commercial operations dashboard."},source:{primary:z,resultPath:"data"},visualization:{kind:"cartesian",variant:"scatter",xDimension:"cycleDays",yMeasures:["winRate"],dimensions:[{key:"cycleDays",label:"Cycle Days",dataPath:"cycleDays",type:"number"}],measures:[{key:"winRate",label:"Win Rate",dataPath:"winRate",format:"percentage",color:"#7c3aed"},{key:"arr",label:"ARR",dataPath:"arr",format:"currency"}],series:[{key:"pipeline",label:"Accounts",measure:"winRate",type:"scatter",color:"#7c3aed"}],table:{caption:"Sales cycle and win rate per account."}}});import{VisualizationRegistry as Fr}from"@contractspec/lib.contracts-spec/visualizations";var d=[x,f,h,E,I,R,S,_,g],Yr=new Fr([...d]),Ar=d.map((r)=>Z(r)),tr=new Map(d.map((r)=>[B(r.meta),r])),a={[B(x.meta)]:{data:[{period:"2025-11-01",totalRevenue:112000,priorRevenue:103000},{period:"2025-12-01",totalRevenue:119000,priorRevenue:110000},{period:"2026-01-01",totalRevenue:126500,priorRevenue:116000},{period:"2026-02-01",totalRevenue:133000,priorRevenue:124000},{period:"2026-03-01",totalRevenue:145500,priorRevenue:133000}]},[B(f.meta)]:{data:[{date:"2025-11-01",revenue:112000},{date:"2025-12-01",revenue:119000},{date:"2026-01-01",revenue:126500},{date:"2026-02-01",revenue:133000},{date:"2026-03-01",revenue:145500}]},[B(h.meta)]:{data:[{region:"North America",revenue:210000},{region:"EMEA",revenue:174000},{region:"APAC",revenue:132000},{region:"LATAM",revenue:88000}]},[B(E.meta)]:{data:[{week:"Week 1",retentionRate:0.71},{week:"Week 2",retentionRate:0.66},{week:"Week 3",retentionRate:0.62},{week:"Week 4",retentionRate:0.58},{week:"Week 5",retentionRate:0.55},{week:"Week 6",retentionRate:0.53}]},[B(I.meta)]:{data:[{cycleDays:18,winRate:0.31,arr:82000},{cycleDays:26,winRate:0.44,arr:65000},{cycleDays:33,winRate:0.27,arr:91000},{cycleDays:14,winRate:0.56,arr:47000},{cycleDays:21,winRate:0.48,arr:59000},{cycleDays:39,winRate:0.22,arr:114000}]},[B(R.meta)]:{data:[{channel:"Direct",sessions:4200},{channel:"Organic Search",sessions:3600},{channel:"Paid Search",sessions:2100},{channel:"Partner",sessions:1400},{channel:"Referral",sessions:900}]},[B(S.meta)]:{data:[{weekday:"Mon",timeBand:"09:00",engagementScore:74},{weekday:"Mon",timeBand:"13:00",engagementScore:82},{weekday:"Tue",timeBand:"09:00",engagementScore:69},{weekday:"Tue",timeBand:"13:00",engagementScore:88},{weekday:"Wed",timeBand:"09:00",engagementScore:77},{weekday:"Wed",timeBand:"13:00",engagementScore:91},{weekday:"Thu",timeBand:"09:00",engagementScore:72},{weekday:"Thu",timeBand:"13:00",engagementScore:86},{weekday:"Fri",timeBand:"09:00",engagementScore:65},{weekday:"Fri",timeBand:"13:00",engagementScore:79}]},[B(_.meta)]:{data:[{stage:"Visited Site",users:12000},{stage:"Started Trial",users:4200},{stage:"Activated Workspace",users:2400},{stage:"Requested Demo",users:980},{stage:"Closed Won",users:310}]},[B(g.meta)]:{data:[{city:"Paris",latitude:48.8566,longitude:2.3522,accounts:48},{city:"London",latitude:51.5072,longitude:-0.1276,accounts:62},{city:"New York",latitude:40.7128,longitude:-74.006,accounts:71},{city:"Toronto",latitude:43.6532,longitude:-79.3832,accounts:36},{city:"Singapore",latitude:1.3521,longitude:103.8198,accounts:29}]}};function Z(r){return{key:r.meta.key,version:r.meta.version}}function B(r){return`${r.key}.v${r.version}`}var Rr={METRIC:Z(x),LINE_CHART:Z(f),BAR_CHART:Z(h),AREA_CHART:Z(E),SCATTER_PLOT:Z(I),PIE_CHART:Z(R),HEATMAP:Z(S),FUNNEL:Z(_),MAP:Z(g)};function V(r){return[K(r,"widget_revenue_metric","Revenue Snapshot","METRIC",0,0,4,2,{layout:"single",bindings:[U(x,200)]}),K(r,"widget_revenue_trend","Revenue Trend","LINE_CHART",4,0,8,4,{layout:"single",bindings:[U(f)]}),K(r,"widget_regional_revenue","Regional Revenue","BAR_CHART",0,2,6,4,{layout:"single",bindings:[U(h)]}),K(r,"widget_channel_mix","Channel Mix","PIE_CHART",6,2,6,4,{layout:"single",bindings:[U(R)]}),K(r,"widget_retention","Retention Curve","AREA_CHART",0,6,6,4,{layout:"single",bindings:[U(E)]}),K(r,"widget_pipeline","Pipeline Velocity","SCATTER_PLOT",6,6,6,4,{layout:"single",bindings:[U(I)]}),K(r,"widget_heatmap","Engagement Heatmap","HEATMAP",0,10,8,4,{layout:"single",bindings:[U(S)]}),K(r,"widget_funnel","Conversion Funnel","FUNNEL",8,10,4,4,{layout:"single",bindings:[U(_)]}),K(r,"widget_geo","Account Coverage","MAP",0,14,12,5,{layout:"single",bindings:[U(g,360)]}),K(r,"widget_comparison","Commercial Comparison","EMBED",0,19,12,6,{layout:"comparison",description:"Compare regional distribution, channel balance, and funnel shape.",bindings:[U(h,240),U(R,240),U(_,240)]}),K(r,"widget_timeline","Growth Timeline","EMBED",0,25,12,6,{layout:"timeline",description:"Track revenue and retention over the same reporting cadence.",bindings:[U(f,220),U(E,220)]})]}function j(r){let o=_r(r),n=o.bindings.map(($)=>{let y=tr.get(B($.ref));if(!y)return null;return{key:`${r.id}:${B($.ref)}`,spec:y,data:$.data,title:$.title??y.meta.title,description:$.description??y.meta.description,height:$.height}}).filter(($)=>Boolean($));if(!n.length)return null;return{id:r.id,name:r.name,description:o.description,layout:o.layout,gridX:r.gridX,gridY:r.gridY,gridWidth:r.gridWidth,gridHeight:r.gridHeight,bindings:n}}function _r(r){if(fr(r.config))return r.config;let o=Rr[r.type];return o?{layout:"single",bindings:[{ref:o,data:a[B(o)]}]}:{layout:"single",bindings:[]}}function U(r,o=280){return{ref:Z(r),data:a[B(r.meta)],height:o}}function K(r,o,n,$,y,c,Q,t,G){let L=new Date;return{id:o,dashboardId:r,name:n,type:$,gridX:y,gridY:c,gridWidth:Q,gridHeight:t,config:G,createdAt:L,updatedAt:L}}function fr(r){if(!r||typeof r!=="object")return!1;let o=r;return(o.layout==="single"||o.layout==="comparison"||o.layout==="timeline")&&Array.isArray(o.bindings)}import{defineFeature as hr}from"@contractspec/lib.contracts-spec";var gn=hr({meta:{key:"analytics-dashboard",version:"1.0.0",title:"Analytics Dashboard",description:"Analytics dashboards with customizable widgets and queries",domain:"analytics",owners:["@analytics-dashboard"],tags:["analytics","dashboards","widgets","queries"],stability:"experimental"},operations:[{key:"analytics.dashboard.create",version:"1.0.0"},{key:"analytics.dashboard.list",version:"1.0.0"},{key:"analytics.dashboard.get",version:"1.0.0"},{key:"analytics.widget.add",version:"1.0.0"},{key:"analytics.query.create",version:"1.0.0"},{key:"analytics.query.execute",version:"1.0.0"}],events:[{key:"analytics.dashboard.created",version:"1.0.0"},{key:"analytics.widget.added",version:"1.0.0"},{key:"analytics.query.created",version:"1.0.0"}],presentations:[{key:"analytics.dashboard.viewList",version:"1.0.0"},{key:"analytics.dashboard.view",version:"1.0.0"},{key:"analytics.dashboard.editor",version:"1.0.0"},{key:"analytics.query.list",version:"1.0.0"},{key:"analytics.query.builder",version:"1.0.0"}],visualizations:[...Ar],opToPresentation:[{op:{key:"analytics.dashboard.list",version:"1.0.0"},pres:{key:"analytics.dashboard.viewList",version:"1.0.0"}},{op:{key:"analytics.dashboard.get",version:"1.0.0"},pres:{key:"analytics.dashboard.view",version:"1.0.0"}},{op:{key:"analytics.dashboard.create",version:"1.0.0"},pres:{key:"analytics.dashboard.editor",version:"1.0.0"}},{op:{key:"analytics.query.create",version:"1.0.0"},pres:{key:"analytics.query.builder",version:"1.0.0"}}],presentationsTargets:[{key:"analytics.dashboard.viewList",version:"1.0.0",targets:["react","markdown","application/json"]},{key:"analytics.dashboard.view",version:"1.0.0",targets:["react","markdown"]},{key:"analytics.dashboard.editor",version:"1.0.0",targets:["react"]},{key:"analytics.query.builder",version:"1.0.0",targets:["react"]}],capabilities:{requires:[{key:"identity",version:"1.0.0"},{key:"metering",version:"1.0.0"},{key:"audit-trail",version:"1.0.0"}]},telemetry:[{key:"analytics-dashboard.telemetry",version:"1.0.0"}],docs:["docs.examples.analytics-dashboard","docs.examples.analytics-dashboard.goal","docs.examples.analytics-dashboard.usage","docs.examples.analytics-dashboard.constraints"]});class Qr{reader;defaultLimit;constructor(r,o={}){this.reader=r,this.defaultLimit=o.defaultLimit??100}async execute(r,o){let n=Date.now(),$=this.validateQuery(r);if(!$.valid)return{data:[],columns:[],rowCount:0,executionTimeMs:Date.now()-n,cached:!1,error:$.errors.join(", ")};if(!this.reader.queryHogQL)return{data:[],columns:[],rowCount:0,executionTimeMs:Date.now()-n,cached:!1,error:"Analytics reader does not support HogQL queries."};try{let y=await this.executeHogQL(r,o);return{data:y.data,columns:y.columns,rowCount:y.rowCount,executionTimeMs:Date.now()-n,cached:!1}}catch(y){return{data:[],columns:[],rowCount:0,executionTimeMs:Date.now()-n,cached:!1,error:y instanceof Error?y.message:"Unknown error"}}}validateQuery(r){let o=[];if(r.type==="SQL"&&!r.sql)o.push("SQL query is missing.");if(r.type==="AGGREGATION"&&!r.aggregation)o.push("Aggregation definition is missing.");if(r.type==="METRIC"&&!r.metricIds?.length)o.push("Metric IDs are missing.");if(r.type==="CUSTOM"&&!r.custom?.handler)o.push("Custom handler is missing.");return{valid:o.length===0,errors:o}}async executeHogQL(r,o){if(!this.reader.queryHogQL)throw Error("Analytics reader does not support HogQL queries.");if(r.type==="SQL"){let n=await this.reader.queryHogQL({query:r.sql??"",values:o.parameters??{}});return kr(n)}if(r.type==="AGGREGATION"&&r.aggregation){let{query:n,values:$}=gr(r.aggregation,o),y=await this.reader.queryHogQL({query:n,values:$});return kr(y)}if(r.type==="METRIC"&&r.metricIds){let{query:n,values:$}=Sr(r.metricIds,o),y=await this.reader.queryHogQL({query:n,values:$});return kr(y)}throw Error("Unsupported query type for PostHog datasource.")}}function Er(r,o){return new Qr(r,o)}function Sr(r,o){let n=Ur(o),$={dateFrom:n?.from.toISOString(),dateTo:n?.to.toISOString()},y=r.map((Q,t)=>{return $[`metric${t}`]=Q,`event = {metric${t}}`}),c=[y.length?`(${y.join(" or ")})`:"",n?"timestamp >= {dateFrom} and timestamp < {dateTo}":""].filter(Boolean).join(" and ");return{query:["select"," event as metric,"," count() as total","from events",c?`where ${c}`:"","group by metric"].filter(Boolean).join(`
|
|
3
|
+
`),values:$}}function gr(r,o){let n=r.measures.map((L)=>({...L,expression:xr(L.field,L.aggregation)})),$=r.dimensions.map((L)=>({...L,expression:Ir(L.field,L.type,L.granularity)})),y=[...$.map((L)=>`${L.expression} as ${L.name}`),...n.map((L)=>`${L.expression} as ${L.name}`)],c={},Q=Vr(r,o,c),t=r.limit??100,G=r.orderBy?.length?`order by ${r.orderBy.map((L)=>`${L.field} ${L.direction}`).join(", ")}`:"";return{query:["select",` ${y.join(`,
|
|
4
|
+
`)}`,`from ${r.source}`,Q.length?`where ${Q.join(" and ")}`:"",$.length?`group by ${$.map((L)=>L.name).join(", ")}`:"",G,`limit ${t}`].filter(Boolean).join(`
|
|
5
|
+
`),values:c}}function xr(r,o){switch(o){case"COUNT":return r==="*"?"count()":`count(${r})`;case"COUNT_DISTINCT":return`countDistinct(${r})`;case"SUM":return`sum(${r})`;case"AVG":return`avg(${r})`;case"MIN":return`min(${r})`;case"MAX":return`max(${r})`;default:return`count(${r})`}}function Ir(r,o,n){if(o==="TIME")switch(n){case"HOUR":return`toStartOfHour(${r})`;case"WEEK":return`toStartOfWeek(${r})`;case"MONTH":return`toStartOfMonth(${r})`;case"YEAR":return`toStartOfYear(${r})`;case"DAY":default:return`toStartOfDay(${r})`}return r}function Vr(r,o,n){let $=[],y=Ur(o);if(y)n.dateFrom=y.from.toISOString(),n.dateTo=y.to.toISOString(),$.push("timestamp >= {dateFrom} and timestamp < {dateTo}");return r.filters?.forEach((c,Q)=>{let t=`filter${Q}`;switch(c.operator){case"eq":n[t]=c.value,$.push(`${c.field} = {${t}}`);break;case"neq":n[t]=c.value,$.push(`${c.field} != {${t}}`);break;case"gt":n[t]=c.value,$.push(`${c.field} > {${t}}`);break;case"gte":n[t]=c.value,$.push(`${c.field} >= {${t}}`);break;case"lt":n[t]=c.value,$.push(`${c.field} < {${t}}`);break;case"lte":n[t]=c.value,$.push(`${c.field} <= {${t}}`);break;case"contains":n[t]=c.value,$.push(`${c.field} LIKE '%' || {${t}} || '%'`);break;case"between":{if(Array.isArray(c.value)&&c.value.length>=2)n[`${t}Start`]=c.value[0],n[`${t}End`]=c.value[1],$.push(`${c.field} BETWEEN {${t}Start} AND {${t}End}`);break}case"in":case"nin":if(Array.isArray(c.value)){let G=[];if(c.value.forEach((L,C)=>{let Y=`${t}_${C}`;n[Y]=L,G.push(`{${Y}}`)}),G.length)$.push(`${c.field} ${c.operator==="in"?"IN":"NOT IN"} (${G.join(", ")})`)}break;default:break}}),$}function Ur(r){let o=r.dateRange;if(!o)return null;return{from:o.start,to:o.end}}function kr(r){if(!Array.isArray(r.results)||!Array.isArray(r.columns))return{data:[],columns:[],rowCount:0};let o=r.columns.map(($)=>({name:$,type:"STRING"})),n=r.results.map(($)=>{if(!Array.isArray($))return{};let y={};return r.columns?.forEach((c,Q)=>{y[c]=$[Q]}),y});return{data:n,columns:o,rowCount:n.length}}import{web as ur}from"@contractspec/lib.runtime-sandbox";var{generateId:rr}=ur;function nr(r){return{id:r.id,projectId:r.projectId,organizationId:r.organizationId,name:r.name,slug:r.slug,description:r.description??void 0,status:r.status,refreshInterval:r.refreshInterval,isPublic:r.isPublic===1,shareToken:r.shareToken??void 0,createdAt:new Date(r.createdAt),updatedAt:new Date(r.updatedAt)}}function Lr(r){return{id:r.id,dashboardId:r.dashboardId,name:r.name,type:r.type,gridX:r.gridX,gridY:r.gridY,gridWidth:r.gridWidth,gridHeight:r.gridHeight,queryId:r.queryId??void 0,config:r.config?JSON.parse(r.config):void 0,createdAt:new Date(r.createdAt),updatedAt:new Date(r.updatedAt)}}function Dr(r){return{id:r.id,projectId:r.projectId,organizationId:r.organizationId,name:r.name,description:r.description??void 0,type:r.type,definition:JSON.parse(r.definition),sql:r.sql??void 0,cacheTtlSeconds:r.cacheTtlSeconds,isShared:r.isShared===1,createdAt:new Date(r.createdAt),updatedAt:new Date(r.updatedAt)}}function un(r){async function o(A){let{projectId:m,status:D,search:k,limit:N=20,offset:W=0}=A,H="WHERE projectId = ?",O=[m];if(D&&D!=="all")H+=" AND status = ?",O.push(D);if(k)H+=" AND (name LIKE ? OR description LIKE ?)",O.push(`%${k}%`,`%${k}%`);let l=(await r.query(`SELECT COUNT(*) as count FROM analytics_dashboard ${H}`,O)).rows[0]?.count??0;return{dashboards:(await r.query(`SELECT * FROM analytics_dashboard ${H} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`,[...O,N,W])).rows.map(nr),total:l}}async function n(A,m){let D=rr("dash"),k=new Date().toISOString();await r.execute(`INSERT INTO analytics_dashboard (id, projectId, organizationId, name, slug, description, status, refreshInterval, isPublic, createdAt, updatedAt)
|
|
6
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,m.projectId,m.organizationId,A.name,A.slug,A.description??null,"DRAFT",A.refreshInterval??"NONE",0,k,k]);let N=(await r.query("SELECT * FROM analytics_dashboard WHERE id = ?",[D])).rows;return nr(N[0])}async function $(A){let m="",D=[];if(A.dashboardId)m="WHERE id = ?",D.push(A.dashboardId);else if(A.slug)m="WHERE slug = ?",D.push(A.slug);else if(A.shareToken)m="WHERE shareToken = ?",D.push(A.shareToken);else return null;let k=(await r.query(`SELECT * FROM analytics_dashboard ${m}`,D)).rows;return k[0]?nr(k[0]):null}async function y(A,m){let D=new Date().toISOString(),k=["updatedAt = ?"],N=[D];if(m.name!==void 0)k.push("name = ?"),N.push(m.name);if(m.description!==void 0)k.push("description = ?"),N.push(m.description);if(m.status!==void 0)k.push("status = ?"),N.push(m.status);if(m.refreshInterval!==void 0)k.push("refreshInterval = ?"),N.push(m.refreshInterval);if(m.isPublic!==void 0)if(k.push("isPublic = ?"),N.push(m.isPublic?1:0),m.isPublic)k.push("shareToken = ?"),N.push(rr("share"));else k.push("shareToken = NULL");N.push(A),await r.execute(`UPDATE analytics_dashboard SET ${k.join(", ")} WHERE id = ?`,N);let W=(await r.query("SELECT * FROM analytics_dashboard WHERE id = ?",[A])).rows;return nr(W[0])}async function c(A){return(await r.query("SELECT * FROM analytics_widget WHERE dashboardId = ? ORDER BY gridY, gridX",[A])).rows.map(Lr)}async function Q(A){let m=rr("widget"),D=new Date().toISOString();await r.execute(`INSERT INTO analytics_widget (id, dashboardId, name, type, gridX, gridY, gridWidth, gridHeight, queryId, config, createdAt, updatedAt)
|
|
7
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[m,A.dashboardId,A.name,A.type,A.gridX??0,A.gridY??0,A.gridWidth??6,A.gridHeight??4,A.queryId??null,A.config?JSON.stringify(A.config):null,D,D]);let k=(await r.query("SELECT * FROM analytics_widget WHERE id = ?",[m])).rows;return Lr(k[0])}async function t(A,m){let D=new Date().toISOString(),k=["updatedAt = ?"],N=[D];if(m.name!==void 0)k.push("name = ?"),N.push(m.name);if(m.gridX!==void 0)k.push("gridX = ?"),N.push(m.gridX);if(m.gridY!==void 0)k.push("gridY = ?"),N.push(m.gridY);if(m.gridWidth!==void 0)k.push("gridWidth = ?"),N.push(m.gridWidth);if(m.gridHeight!==void 0)k.push("gridHeight = ?"),N.push(m.gridHeight);if(m.queryId!==void 0)k.push("queryId = ?"),N.push(m.queryId??null);if(m.config!==void 0)k.push("config = ?"),N.push(m.config?JSON.stringify(m.config):null);N.push(A),await r.execute(`UPDATE analytics_widget SET ${k.join(", ")} WHERE id = ?`,N);let W=(await r.query("SELECT * FROM analytics_widget WHERE id = ?",[A])).rows;return Lr(W[0])}async function G(A){await r.execute("DELETE FROM analytics_widget WHERE id = ?",[A])}async function L(A){let{projectId:m,type:D,isShared:k,search:N,limit:W=20,offset:H=0}=A,O="WHERE projectId = ?",J=[m];if(D&&D!=="all")O+=" AND type = ?",J.push(D);if(k!==void 0)O+=" AND isShared = ?",J.push(k?1:0);if(N)O+=" AND (name LIKE ? OR description LIKE ?)",J.push(`%${N}%`,`%${N}%`);let Or=(await r.query(`SELECT COUNT(*) as count FROM analytics_query ${O}`,J)).rows[0]?.count??0;return{queries:(await r.query(`SELECT * FROM analytics_query ${O} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`,[...J,W,H])).rows.map(Dr),total:Or}}async function C(A,m){let D=rr("query"),k=new Date().toISOString();await r.execute(`INSERT INTO analytics_query (id, projectId, organizationId, name, description, type, definition, sql, cacheTtlSeconds, isShared, createdAt, updatedAt)
|
|
8
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[D,m.projectId,m.organizationId,A.name,A.description??null,A.type,JSON.stringify(A.definition),A.sql??null,A.cacheTtlSeconds??300,A.isShared?1:0,k,k]);let N=(await r.query("SELECT * FROM analytics_query WHERE id = ?",[D])).rows;return Dr(N[0])}async function Y(A){let m=(await r.query("SELECT * FROM analytics_query WHERE id = ?",[A])).rows;return m[0]?Dr(m[0]):null}return{listDashboards:o,createDashboard:n,getDashboard:$,updateDashboard:y,getWidgets:c,addWidget:Q,updateWidget:t,deleteWidget:G,listQueries:L,createQuery:C,getQuery:Y}}import{defineEnum as lr}from"@contractspec/lib.schema";var or=lr("QueryType",["SQL","METRIC","AGGREGATION","CUSTOM"]);import{defineSchemaModel as mr,ScalarTypeEnum as P}from"@contractspec/lib.schema";var $r=mr({name:"QueryModel",fields:{id:{type:P.String_unsecure(),isOptional:!1},name:{type:P.String_unsecure(),isOptional:!1},description:{type:P.String_unsecure(),isOptional:!0},type:{type:or,isOptional:!1},definition:{type:P.JSON(),isOptional:!1},sql:{type:P.String_unsecure(),isOptional:!0},cacheTtlSeconds:{type:P.Int_unsecure(),isOptional:!1},isShared:{type:P.Boolean(),isOptional:!1},createdAt:{type:P.DateTime(),isOptional:!1}}}),Nr=mr({name:"QueryResultModel",fields:{queryId:{type:P.String_unsecure(),isOptional:!1},data:{type:P.JSON(),isOptional:!1},columns:{type:P.JSON(),isOptional:!1},rowCount:{type:P.Int_unsecure(),isOptional:!1},executionTimeMs:{type:P.Int_unsecure(),isOptional:!1},cachedAt:{type:P.DateTime(),isOptional:!0},error:{type:P.String_unsecure(),isOptional:!0}}}),Pr=mr({name:"CreateQueryInput",fields:{name:{type:P.NonEmptyString(),isOptional:!1},description:{type:P.String_unsecure(),isOptional:!0},type:{type:or,isOptional:!1},definition:{type:P.JSON(),isOptional:!1},sql:{type:P.String_unsecure(),isOptional:!0},metricIds:{type:P.String_unsecure(),isArray:!0,isOptional:!0},cacheTtlSeconds:{type:P.Int_unsecure(),isOptional:!0},isShared:{type:P.Boolean(),isOptional:!0}}}),Gr=mr({name:"ExecuteQueryInput",fields:{queryId:{type:P.String_unsecure(),isOptional:!1},parameters:{type:P.JSON(),isOptional:!0},dateRange:{type:P.JSON(),isOptional:!0},filters:{type:P.JSON(),isOptional:!0},forceRefresh:{type:P.Boolean(),isOptional:!0}}});import{defineCommand as Tr,defineQuery as zr}from"@contractspec/lib.contracts-spec/operations";var Hr=["@example.analytics-dashboard"],er=Tr({meta:{key:"analytics.query.create",version:"1.0.0",stability:"stable",owners:[...Hr],tags:["analytics","query","create"],description:"Create a data query.",goal:"Define reusable data queries.",context:"Query builder."},io:{input:Pr,output:$r},policy:{auth:"user"},sideEffects:{emits:[{key:"analytics.query.created",version:"1.0.0",stability:"stable",owners:[...Hr],tags:["analytics","query","created"],when:"Query created",payload:$r}],audit:["analytics.query.created"]},acceptance:{scenarios:[{key:"create-query-happy-path",given:["User is authenticated"],when:["User submits valid query definition"],then:["Query is created","QueryCreated event is emitted"]}],examples:[{key:"create-sql-query",input:{name:"Monthly Revenue",sql:"SELECT SUM(amount) FROM orders WHERE date >= :startDate"},output:{id:"query-123",name:"Monthly Revenue",type:"sql"}}]}}),jr=zr({meta:{key:"analytics.query.execute",version:"1.0.0",stability:"stable",owners:[...Hr],tags:["analytics","query","execute"],description:"Execute a data query.",goal:"Fetch data for visualizations.",context:"Dashboard rendering."},io:{input:Gr,output:Nr},policy:{auth:"user"},acceptance:{scenarios:[{key:"execute-query-happy-path",given:["Query exists"],when:["User executes query with parameters"],then:["Query results are returned"]}],examples:[{key:"execute-with-params",input:{queryId:"query-123",params:{startDate:"2025-01-01"}},output:{columns:["total"],rows:[{total:50000}],rowCount:1}}]}});class Zr{cache=new Map;async get(r){let o=this.cache.get(r);if(!o)return null;if(o.expiresAt<new Date)return this.cache.delete(r),null;return{...o.result,cached:!0,cachedAt:o.expiresAt}}async set(r,o,n){let $=new Date(Date.now()+n*1000);this.cache.set(r,{result:o,expiresAt:$})}async invalidate(r){let o=new RegExp(r);for(let n of this.cache.keys())if(o.test(n))this.cache.delete(n)}}class qr{cache;constructor(r){this.cache=r??new Zr}async execute(r,o){let n=Date.now(),$=this.validateQuery(r);if(!$.valid)return{data:[],columns:[],rowCount:0,executionTimeMs:Date.now()-n,cached:!1,error:$.errors.join(", ")};let y=this.buildCacheKey(r,o),c=await this.cache.get(y);if(c)return c;let Q;switch(r.type){case"AGGREGATION":if(!r.aggregation)throw Error("Aggregation definition is missing");Q=await this.executeAggregation(r.aggregation,o);break;case"METRIC":if(!r.metricIds)throw Error("Metric IDs are missing");Q=await this.executeMetric(r.metricIds,o);break;case"SQL":if(!r.sql)throw Error("SQL query is missing");Q=await this.executeSql(r.sql,o);break;default:Q={data:[],columns:[],rowCount:0,executionTimeMs:Date.now()-n,cached:!1,error:`Unknown query type: ${r.type}`}}return Q.executionTimeMs=Date.now()-n,Q.cached=!1,await this.cache.set(y,Q,300),Q}validateQuery(r){let o=[];if(!r.type)o.push("Query type is required");switch(r.type){case"SQL":if(!r.sql)o.push("SQL query is required for SQL type");break;case"METRIC":if(!r.metricIds||r.metricIds.length===0)o.push("Metric IDs are required for METRIC type");break;case"AGGREGATION":if(!r.aggregation)o.push("Aggregation definition is required for AGGREGATION type");else{if(!r.aggregation.source)o.push("Aggregation source is required");if(!r.aggregation.measures||r.aggregation.measures.length===0)o.push("At least one measure is required")}break}return{valid:o.length===0,errors:o}}buildCacheKey(r,o){return JSON.stringify({definition:r,params:o})}async executeAggregation(r,o){let n=[...r.dimensions.map((y)=>({name:y.name,type:y.type==="NUMBER"?"NUMBER":y.type==="TIME"?"DATE":"STRING",label:y.name})),...r.measures.map((y)=>({name:y.name,type:"NUMBER",label:y.name,format:y.format}))],$=this.generateMockData(r,o);return{data:$,columns:n,rowCount:$.length,executionTimeMs:0,cached:!1}}async executeMetric(r,o){let n=r.map(($)=>({metricId:$,value:Math.random()*1000,change:(Math.random()-0.5)*20}));return{data:n,columns:[{name:"metricId",type:"STRING"},{name:"value",type:"NUMBER"},{name:"change",type:"NUMBER"}],rowCount:n.length,executionTimeMs:0,cached:!1}}async executeSql(r,o){return{data:[],columns:[],rowCount:0,executionTimeMs:0,cached:!1,error:"SQL execution not implemented in demo"}}generateMockData(r,o){let n=[],$=10,y=r.dimensions.find((c)=>c.type==="TIME");for(let c=0;c<10;c++){let Q={};for(let t of r.dimensions)if(t.type==="TIME"){let G=new Date(o.dateRange?.start??new Date);G.setDate(G.getDate()+c),Q[t.name]=G.toISOString().split("T")[0]}else Q[t.name]=`${t.name}_${c%5}`;for(let t of r.measures){let G=y?100+c*10:Math.random()*1000,L=(Math.random()-0.5)*20;Q[t.name]=Math.round((G+L)*100)/100}n.push(Q)}return n}}function oo(r){return new qr(r)}import{ComparisonView as pr,TimelineView as wr,VisualizationCard as br,VisualizationGrid as sr}from"@contractspec/lib.design-system";import{jsx as p,jsxs as yr}from"react/jsx-runtime";function Xr({dashboardName:r,widgets:o}){if(!o.length)return yr("div",{className:"rounded-lg border border-dashed p-10 text-center text-muted-foreground",children:['No visualization widgets configured for "',r,'".']});return yr("div",{children:[yr("h3",{className:"mb-4 font-semibold text-lg",children:['Widgets in "',r,'"']}),p(sr,{children:o.map((n)=>p("div",{className:dr(n.gridWidth),children:ir(n)},n.id))})]})}function ir(r){let o=yr("span",{className:"text-muted-foreground text-xs",children:["Position: (",r.gridX,", ",r.gridY,") \u2022 ",r.gridWidth,"x",r.gridHeight]});if(r.layout==="comparison")return p(pr,{description:r.description,items:r.bindings.map(($)=>({...$,footer:o})),title:r.name});if(r.layout==="timeline")return p(wr,{description:r.description,items:r.bindings.map(($)=>({...$,footer:o})),title:r.name});let n=r.bindings[0];if(!n)return null;return p(br,{data:n.data,description:r.description??n.description,footer:o,height:n.height,spec:n.spec,title:r.name})}function dr(r){if(r>=12)return"md:col-span-2 xl:col-span-3";if(r>=8)return"xl:col-span-2";if(r>=6)return"md:col-span-2";return""}import{DataTable as ar}from"@contractspec/lib.design-system";import{useContractTable as rn}from"@contractspec/lib.presentation-runtime-react";import{Badge as Jr}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as nn,VStack as w}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as v}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as q,jsxs as F}from"react/jsx-runtime";var on={SQL:"default",METRIC:"secondary",AGGREGATION:"secondary",CUSTOM:"outline"};function mn(r){return JSON.stringify(r,null,2)}function Kr({queries:r}){let o=rn({data:r,columns:[{id:"query",header:"Query",label:"Query",accessor:(n)=>n.name,cell:({item:n})=>F(w,{gap:"xs",children:[q(v,{className:"font-medium text-sm",children:n.name}),F(v,{className:"text-muted-foreground text-xs",children:["Updated ",n.updatedAt.toLocaleDateString()]})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"description",header:"Description",label:"Description",accessor:(n)=>n.description??"",cell:({value:n})=>q(v,{className:"line-clamp-2 text-muted-foreground text-sm",children:String(n||"No description")}),size:300,minSize:220,canSort:!1,canHide:!0,canResize:!0},{id:"type",header:"Type",label:"Type",accessorKey:"type",cell:({value:n})=>q(Jr,{variant:on[String(n)],children:String(n)}),size:150,canSort:!0,canHide:!0,canResize:!0},{id:"cacheTtlSeconds",header:"Cache TTL",label:"Cache TTL",accessorKey:"cacheTtlSeconds",cell:({value:n})=>`${String(n)}s`,align:"right",size:140,canSort:!0,canResize:!0},{id:"isShared",header:"Shared",label:"Shared",accessorKey:"isShared",cell:({value:n})=>q(Jr,{variant:n?"default":"outline",children:n?"Shared":"Private"}),size:140,canSort:!0,canHide:!0,canResize:!0}],initialState:{pagination:{pageIndex:0,pageSize:3},columnVisibility:{description:!1},columnPinning:{left:["query"],right:[]}},renderExpandedContent:(n)=>F(w,{gap:"sm",className:"py-2",children:[F(w,{gap:"xs",children:[q(v,{className:"font-medium text-sm",children:"Description"}),q(v,{className:"text-muted-foreground text-sm",children:n.description??"No description"})]}),n.sql?F(w,{gap:"xs",children:[q(v,{className:"font-medium text-sm",children:"SQL"}),q("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:n.sql})]}):null,F(w,{gap:"xs",children:[q(v,{className:"font-medium text-sm",children:"Definition"}),q("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:mn(n.definition)})]})]}),getCanExpand:()=>!0});return q(ar,{controller:o,title:"Saved Queries",description:"Client-mode table using the shared ContractSpec controller and renderer.",toolbar:F(nn,{gap:"sm",className:"flex-wrap",children:[F(v,{className:"text-muted-foreground text-sm",children:[r.length," queries"]}),F(v,{className:"text-muted-foreground text-sm",children:[r.filter((n)=>n.isShared).length," shared"]})]}),emptyState:q("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No queries saved"})})}import{useTemplateRuntime as $n}from"@contractspec/lib.example-shared-ui";import{useCallback as Cr,useEffect as yn,useState as u}from"react";function Br(r="local-project"){let{handlers:o}=$n(),n=o.analytics,[$,y]=u([]),[c,Q]=u([]),[t,G]=u(null),[L,C]=u([]),[Y,A]=u(!0),[m,D]=u(null),k=Cr(async()=>{try{A(!0),D(null);let[H,O]=await Promise.all([n.listDashboards({projectId:r,limit:100}),n.listQueries({projectId:r,limit:100})]);if(y(H.dashboards),Q(O.queries),H.dashboards.length>0&&!t){let J=H.dashboards[0];if(J){G(J);let l=await n.getWidgets(J.id);C(l.length>0?l:V(J.id))}}}catch(H){D(H instanceof Error?H:Error("Failed to load analytics"))}finally{A(!1)}},[n,r,t]);yn(()=>{k()},[k]);let N=Cr(async(H)=>{G(H);let O=await n.getWidgets(H.id);C(O.length>0?O:V(H.id))},[n]),W={totalDashboards:$.length,publishedDashboards:$.filter((H)=>H.status==="PUBLISHED").length,totalQueries:c.length,sharedQueries:c.filter((H)=>H.isShared).length};return{dashboards:$,queries:c,selectedDashboard:t,widgets:L,loading:Y,error:m,stats:W,refetch:k,selectDashboard:N}}import{Button as Wr,ErrorState as cn,LoaderBlock as An,StatCard as Mr,StatCardGroup as tn}from"@contractspec/lib.design-system";import{useMemo as kn,useState as Qn}from"react";import{jsx as M,jsxs as X}from"react/jsx-runtime";var Ln={PUBLISHED:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",DRAFT:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",ARCHIVED:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"};function Dn(){let[r,o]=Qn("dashboards"),{dashboards:n,queries:$,selectedDashboard:y,widgets:c,loading:Q,error:t,stats:G,refetch:L,selectDashboard:C}=Br(),Y=[{id:"dashboards",label:"Dashboards",icon:"\uD83D\uDCCA"},{id:"queries",label:"Queries",icon:"\uD83D\uDD0D"}],A=kn(()=>c.map((m)=>j(m)).filter((m)=>Boolean(m)),[c]);if(Q)return M(An,{label:"Loading Analytics..."});if(t)return M(cn,{title:"Failed to load Analytics",description:t.message,onRetry:L,retryLabel:"Retry"});return X("div",{className:"space-y-6",children:[X("div",{className:"flex items-center justify-between",children:[M("h2",{className:"font-bold text-2xl",children:"Analytics Dashboard"}),X(Wr,{onClick:()=>alert("Create dashboard modal"),children:[M("span",{className:"mr-2",children:"+"})," New Dashboard"]})]}),X(tn,{children:[M(Mr,{label:"Dashboards",value:G.totalDashboards,hint:`${G.publishedDashboards} published`}),M(Mr,{label:"Queries",value:G.totalQueries,hint:`${G.sharedQueries} shared`}),M(Mr,{label:"Widgets",value:c.length,hint:"on current dashboard"})]}),M("nav",{className:"flex gap-1 rounded-lg bg-muted p-1",role:"tablist",children:Y.map((m)=>X(Wr,{type:"button",role:"tab","aria-selected":r===m.id,onClick:()=>o(m.id),className:`flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${r===m.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[M("span",{children:m.icon}),m.label]},m.id))}),X("div",{className:"min-h-[400px]",role:"tabpanel",children:[r==="dashboards"&&X("div",{className:"space-y-6",children:[X("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[n.map((m)=>X("div",{onClick:()=>C(m),className:`cursor-pointer rounded-lg border border-border bg-card p-4 transition-all ${y?.id===m.id?"ring-2 ring-primary":"hover:bg-muted/50"}`,role:"button",tabIndex:0,onKeyDown:(D)=>{if(D.key==="Enter"||D.key===" ")C(m)},children:[X("div",{className:"mb-2 flex items-center justify-between",children:[M("h3",{className:"font-medium",children:m.name}),M("span",{className:`inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${Ln[m.status]??""}`,children:m.status})]}),M("p",{className:"mb-3 text-muted-foreground text-sm",children:m.description}),X("div",{className:"flex items-center justify-between text-muted-foreground text-xs",children:[X("span",{children:["/",m.slug]}),m.isPublic&&M("span",{className:"text-green-600 dark:text-green-400",children:"\uD83C\uDF10 Public"})]})]},m.id)),n.length===0&&M("div",{className:"col-span-full flex h-64 items-center justify-center text-muted-foreground",children:"No dashboards created yet"})]}),y?M(Xr,{dashboardName:y.name,widgets:A}):null]}),r==="queries"&&M(Kr,{queries:$})]})]})}var cr=[{id:"dash-1",name:"Sales Overview",slug:"sales-overview",status:"PUBLISHED",widgetCount:11,viewCount:1250,lastViewedAt:"2026-03-18T12:00:00Z"},{id:"dash-2",name:"User Engagement",slug:"user-engagement",status:"PUBLISHED",widgetCount:8,viewCount:890,lastViewedAt:"2026-03-18T10:00:00Z"}],vr=[{id:"q-1",name:"Monthly Revenue",type:"AGGREGATION",isShared:!0,executionCount:1500},{id:"q-2",name:"User Growth",type:"METRIC",isShared:!0,executionCount:890},{id:"q-3",name:"Product Sales",type:"SQL",isShared:!1,executionCount:340},{id:"q-4",name:"Conversion Funnel",type:"AGGREGATION",isShared:!0,executionCount:450}];function Nn(r){return V(r).map((o)=>j(o)).filter((o)=>Boolean(o))}var Pn={target:"markdown",render:async(r)=>{if(r.source.type!=="component"||r.source.componentKey!=="AnalyticsDashboard")throw Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");let o=cr[0];if(!o)return{mimeType:"text/markdown",body:`# No Dashboards
|
|
9
|
+
|
|
10
|
+
No dashboards available.`};let n=Nn(o.id),$=n.filter((c)=>c.bindings[0]?.spec.visualization.kind==="metric"),y=[`# ${o.name}`,"","> Contract-backed analytics dashboard overview.","","## Key Metrics",""];for(let c of $){let Q=c.bindings[0];if(!Q)continue;y.push(`- **${c.name}** via \`${Q.spec.meta.key}\``)}y.push(""),y.push("## Visual Blocks"),y.push("");for(let c of n){let Q=c.bindings.map((t)=>t.spec.visualization.kind).join(", ");y.push(`- **${c.name}** (${c.layout}) \u2192 ${Q}`)}return y.push(""),y.push("## Dashboard Stats"),y.push(""),y.push("| Metric | Value |"),y.push("|--------|-------|"),y.push(`| Total Dashboards | ${cr.length} |`),y.push(`| Published | ${cr.filter((c)=>c.status==="PUBLISHED").length} |`),y.push(`| Shared Queries | ${vr.filter((c)=>c.isShared).length} |`),{mimeType:"text/markdown",body:y.join(`
|
|
11
|
+
`)}}},Gn={target:"markdown",render:async(r)=>{if(r.source.type!=="component"||r.source.componentKey!=="DashboardList")throw Error("dashboardListMarkdownRenderer: not DashboardList");let o=["# Dashboards","","> Browse and manage analytics dashboards","","| Dashboard | Widgets | Views | Status | Last Viewed |","|-----------|---------|-------|--------|-------------|"];for(let n of cr){let $=n.lastViewedAt?new Date(n.lastViewedAt).toLocaleDateString():"Never",y=n.status==="PUBLISHED"?"\uD83D\uDFE2":"\u26AB";o.push(`| [${n.name}](/dashboards/${n.slug}) | ${n.widgetCount} | ${n.viewCount.toLocaleString()} | ${y} ${n.status} | ${$} |`)}return{mimeType:"text/markdown",body:o.join(`
|
|
12
|
+
`)}}},Hn={target:"markdown",render:async(r)=>{if(r.source.type!=="component"||r.source.componentKey!=="QueryBuilder")throw Error("queryBuilderMarkdownRenderer: not QueryBuilder");let o=["# Query Builder","","> Create and manage reusable data queries.","","| Query | Type | Shared | Executions |","|-------|------|--------|------------|"];for(let n of vr)o.push(`| ${n.name} | ${n.type} | ${n.isShared?"\uD83C\uDF10":"\uD83D\uDD12"} | ${n.executionCount.toLocaleString()} |`);return o.push(""),o.push("## Visualization Contracts"),o.push(""),o.push("Widgets reference `VisualizationSpec` contracts instead of rendering ad-hoc widget types."),{mimeType:"text/markdown",body:o.join(`
|
|
13
|
+
`)}}};export{B as visualizationRefKey,Br as useAnalyticsData,j as resolveAnalyticsWidget,Z as refOf,Hn as queryBuilderMarkdownRenderer,Gn as dashboardListMarkdownRenderer,oo as createQueryEngine,Er as createPosthogQueryEngine,V as createExampleWidgets,un as createAnalyticsHandlers,Pn as analyticsDashboardMarkdownRenderer,f as RevenueTrendVisualization,x as RevenueMetricVisualization,E as RetentionAreaVisualization,h as RegionalRevenueVisualization,or as QueryTypeEnum,Nr as QueryResultModel,$r as QueryModel,Qr as PosthogQueryEngine,I as PipelineScatterVisualization,Zr as InMemoryQueryCache,Gr as ExecuteQueryInputModel,jr as ExecuteQueryContract,S as EngagementHeatmapVisualization,Pr as CreateQueryInputModel,er as CreateQueryContract,_ as ConversionFunnelVisualization,R as ChannelMixVisualization,qr as BasicQueryEngine,d as AnalyticsVisualizationSpecs,tr as AnalyticsVisualizationSpecMap,a as AnalyticsVisualizationSampleData,Yr as AnalyticsVisualizationRegistry,Ar as AnalyticsVisualizationRefs,gn as AnalyticsDashboardFeature,Dn as AnalyticsDashboard,g as AccountCoverageGeoVisualization};
|