@contractspec/example.analytics-dashboard 3.7.6 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +64 -271
  2. package/dist/browser/dashboard.feature.js +592 -0
  3. package/dist/browser/events.js +1 -1
  4. package/dist/browser/index.js +1171 -627
  5. package/dist/browser/ui/AnalyticsDashboard.js +826 -194
  6. package/dist/browser/ui/AnalyticsDashboard.widgets.js +94 -0
  7. package/dist/browser/ui/AnalyticsQueriesTable.js +99 -0
  8. package/dist/browser/ui/hooks/index.js +594 -3
  9. package/dist/browser/ui/hooks/useAnalyticsData.js +594 -3
  10. package/dist/browser/ui/index.js +964 -440
  11. package/dist/browser/ui/renderers/analytics.markdown.js +620 -138
  12. package/dist/browser/ui/renderers/index.js +620 -138
  13. package/dist/browser/visualizations/catalog.js +457 -0
  14. package/dist/browser/visualizations/index.js +611 -0
  15. package/dist/browser/visualizations/specs.breakdown.js +140 -0
  16. package/dist/browser/visualizations/specs.performance.js +198 -0
  17. package/dist/browser/visualizations/widgets.js +595 -0
  18. package/dist/dashboard/index.d.ts +3 -3
  19. package/dist/dashboard.feature.js +592 -0
  20. package/dist/events.js +1 -1
  21. package/dist/index.d.ts +4 -3
  22. package/dist/index.js +1171 -627
  23. package/dist/node/dashboard.feature.js +592 -0
  24. package/dist/node/events.js +1 -1
  25. package/dist/node/index.js +1171 -627
  26. package/dist/node/ui/AnalyticsDashboard.js +826 -194
  27. package/dist/node/ui/AnalyticsDashboard.widgets.js +94 -0
  28. package/dist/node/ui/AnalyticsQueriesTable.js +99 -0
  29. package/dist/node/ui/hooks/index.js +594 -3
  30. package/dist/node/ui/hooks/useAnalyticsData.js +594 -3
  31. package/dist/node/ui/index.js +964 -440
  32. package/dist/node/ui/renderers/analytics.markdown.js +620 -138
  33. package/dist/node/ui/renderers/index.js +620 -138
  34. package/dist/node/visualizations/catalog.js +457 -0
  35. package/dist/node/visualizations/index.js +611 -0
  36. package/dist/node/visualizations/specs.breakdown.js +140 -0
  37. package/dist/node/visualizations/specs.performance.js +198 -0
  38. package/dist/node/visualizations/widgets.js +595 -0
  39. package/dist/query/index.d.ts +1 -1
  40. package/dist/query-engine/index.d.ts +1 -1
  41. package/dist/ui/AnalyticsDashboard.js +826 -194
  42. package/dist/ui/AnalyticsDashboard.widgets.d.ts +5 -0
  43. package/dist/ui/AnalyticsDashboard.widgets.js +95 -0
  44. package/dist/ui/AnalyticsQueriesTable.d.ts +4 -0
  45. package/dist/ui/AnalyticsQueriesTable.js +100 -0
  46. package/dist/ui/hooks/index.d.ts +1 -1
  47. package/dist/ui/hooks/index.js +594 -3
  48. package/dist/ui/hooks/useAnalyticsData.js +594 -3
  49. package/dist/ui/index.d.ts +1 -1
  50. package/dist/ui/index.js +964 -440
  51. package/dist/ui/renderers/analytics.markdown.d.ts +0 -9
  52. package/dist/ui/renderers/analytics.markdown.js +620 -138
  53. package/dist/ui/renderers/index.js +620 -138
  54. package/dist/visualizations/catalog.d.ts +9 -0
  55. package/dist/visualizations/catalog.js +458 -0
  56. package/dist/visualizations/index.d.ts +4 -0
  57. package/dist/visualizations/index.js +612 -0
  58. package/dist/visualizations/specs.breakdown.d.ts +4 -0
  59. package/dist/visualizations/specs.breakdown.js +141 -0
  60. package/dist/visualizations/specs.performance.d.ts +5 -0
  61. package/dist/visualizations/specs.performance.js +199 -0
  62. package/dist/visualizations/widgets.d.ts +24 -0
  63. package/dist/visualizations/widgets.js +596 -0
  64. package/dist/visualizations/widgets.test.d.ts +1 -0
  65. package/package.json +105 -7
package/dist/index.js CHANGED
@@ -1,4 +1,595 @@
1
1
  // @bun
2
+ // src/visualizations/specs.breakdown.ts
3
+ import { defineVisualization } from "@contractspec/lib.contracts-spec/visualizations";
4
+ var QUERY_REF = { key: "analytics.query.execute", version: "1.0.0" };
5
+ var META = {
6
+ version: "1.0.0",
7
+ domain: "analytics",
8
+ stability: "experimental",
9
+ owners: ["@example.analytics-dashboard"],
10
+ tags: ["analytics", "dashboard", "visualization"]
11
+ };
12
+ var ChannelMixVisualization = defineVisualization({
13
+ meta: {
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
+ }
2
593
  // src/dashboard.feature.ts
3
594
  import { defineFeature } from "@contractspec/lib.contracts-spec";
4
595
  var AnalyticsDashboardFeature = defineFeature({
@@ -32,6 +623,7 @@ var AnalyticsDashboardFeature = defineFeature({
32
623
  { key: "analytics.query.list", version: "1.0.0" },
33
624
  { key: "analytics.query.builder", version: "1.0.0" }
34
625
  ],
626
+ visualizations: [...AnalyticsVisualizationRefs],
35
627
  opToPresentation: [
36
628
  {
37
629
  op: { key: "analytics.dashboard.list", version: "1.0.0" },
@@ -800,279 +1392,397 @@ var ExecuteQueryContract = defineQuery({
800
1392
  ]
801
1393
  }
802
1394
  });
803
- // src/ui/renderers/analytics.markdown.ts
804
- var mockDashboards = [
805
- {
806
- id: "dash-1",
807
- name: "Sales Overview",
808
- slug: "sales-overview",
809
- status: "PUBLISHED",
810
- widgetCount: 8,
811
- viewCount: 1250,
812
- lastViewedAt: "2024-01-16T12:00:00Z"
813
- },
814
- {
815
- id: "dash-2",
816
- name: "User Engagement",
817
- slug: "user-engagement",
818
- status: "PUBLISHED",
819
- widgetCount: 6,
820
- viewCount: 890,
821
- lastViewedAt: "2024-01-16T10:00:00Z"
822
- },
823
- {
824
- id: "dash-3",
825
- name: "Product Analytics",
826
- slug: "product-analytics",
827
- status: "PUBLISHED",
828
- widgetCount: 10,
829
- viewCount: 560,
830
- lastViewedAt: "2024-01-15T14:00:00Z"
831
- },
832
- {
833
- id: "dash-4",
834
- name: "Finance Report",
835
- slug: "finance-report",
836
- status: "DRAFT",
837
- widgetCount: 4,
838
- viewCount: 0,
839
- lastViewedAt: null
840
- }
841
- ];
842
- var mockWidgets = [
843
- {
844
- id: "w-1",
845
- dashboardId: "dash-1",
846
- name: "Total Revenue",
847
- type: "METRIC",
848
- value: 125000,
849
- change: 12.5
850
- },
851
- {
852
- id: "w-2",
853
- dashboardId: "dash-1",
854
- name: "Active Users",
855
- type: "METRIC",
856
- value: 4500,
857
- change: 8.2
858
- },
859
- {
860
- id: "w-3",
861
- dashboardId: "dash-1",
862
- name: "Revenue Trend",
863
- type: "LINE_CHART",
864
- dataPoints: 30
865
- },
866
- {
867
- id: "w-4",
868
- dashboardId: "dash-1",
869
- name: "Top Products",
870
- type: "BAR_CHART",
871
- dataPoints: 10
872
- },
873
- {
874
- id: "w-5",
875
- dashboardId: "dash-2",
876
- name: "Daily Active Users",
877
- type: "LINE_CHART",
878
- dataPoints: 30
879
- },
880
- {
881
- id: "w-6",
882
- dashboardId: "dash-2",
883
- name: "Session Duration",
884
- type: "METRIC",
885
- value: 245,
886
- change: -3.1
887
- }
888
- ];
889
- var mockQueries = [
890
- {
891
- id: "q-1",
892
- name: "Monthly Revenue",
893
- type: "AGGREGATION",
894
- isShared: true,
895
- executionCount: 1500
896
- },
897
- {
898
- id: "q-2",
899
- name: "User Growth",
900
- type: "METRIC",
901
- isShared: true,
902
- executionCount: 890
903
- },
904
- {
905
- id: "q-3",
906
- name: "Product Sales",
907
- type: "SQL",
908
- isShared: false,
909
- executionCount: 340
910
- },
911
- {
912
- id: "q-4",
913
- name: "Conversion Funnel",
914
- type: "AGGREGATION",
915
- isShared: true,
916
- executionCount: 450
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 };
917
1407
  }
918
- ];
919
- function formatNumber(value) {
920
- if (value >= 1e6) {
921
- return `${(value / 1e6).toFixed(1)}M`;
1408
+ async set(key, result, ttlSeconds) {
1409
+ const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
1410
+ this.cache.set(key, { result, expiresAt });
922
1411
  }
923
- if (value >= 1000) {
924
- return `${(value / 1000).toFixed(1)}K`;
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
+ }
925
1419
  }
926
- return value.toString();
927
- }
928
- function formatChange(change) {
929
- const icon = change >= 0 ? "\uD83D\uDCC8" : "\uD83D\uDCC9";
930
- const sign = change >= 0 ? "+" : "";
931
- return `${icon} ${sign}${change.toFixed(1)}%`;
932
1420
  }
933
- var analyticsDashboardMarkdownRenderer = {
934
- target: "markdown",
935
- render: async (desc) => {
936
- if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
937
- throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
938
- }
939
- const dashboards = mockDashboards;
940
- const widgets = mockWidgets;
941
- const queries = mockQueries;
942
- const dashboard = dashboards[0];
943
- if (!dashboard) {
944
- return {
945
- mimeType: "text/markdown",
946
- body: `# No Dashboards
947
1421
 
948
- No dashboards available.`
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(", ")
949
1438
  };
950
1439
  }
951
- const dashboardWidgets = widgets.filter((w) => w.dashboardId === dashboard.id);
952
- const publishedDashboards = dashboards.filter((d) => d.status === "PUBLISHED");
953
- const totalViews = dashboards.reduce((sum, d) => sum + d.viewCount, 0);
954
- const sharedQueries = queries.filter((q) => q.isShared);
955
- const lines = [
956
- `# ${dashboard.name}`,
957
- "",
958
- "> Analytics dashboard overview",
959
- "",
960
- "## Key Metrics",
961
- ""
962
- ];
963
- const metricWidgets = dashboardWidgets.filter((w) => w.type === "METRIC");
964
- for (const widget of metricWidgets) {
965
- const w = widget;
966
- lines.push(`### ${w.name}`);
967
- lines.push(`**${formatNumber(w.value)}** ${formatChange(w.change)}`);
968
- lines.push("");
1440
+ const cacheKey = this.buildCacheKey(definition, params);
1441
+ const cachedResult = await this.cache.get(cacheKey);
1442
+ if (cachedResult) {
1443
+ return cachedResult;
969
1444
  }
970
- lines.push("## Visualizations");
971
- lines.push("");
972
- const chartWidgets = dashboardWidgets.filter((w) => w.type !== "METRIC");
973
- for (const widget of chartWidgets) {
974
- const w = widget;
975
- lines.push(`- **${w.name}** (${w.type.replace("_", " ")}) - ${w.dataPoints} data points`);
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
+ };
976
1474
  }
977
- lines.push("");
978
- lines.push("## Dashboard Stats");
979
- lines.push("");
980
- lines.push("| Metric | Value |");
981
- lines.push("|--------|-------|");
982
- lines.push(`| Total Dashboards | ${dashboards.length} |`);
983
- lines.push(`| Published | ${publishedDashboards.length} |`);
984
- lines.push(`| Total Views | ${totalViews.toLocaleString()} |`);
985
- lines.push(`| Shared Queries | ${sharedQueries.length} |`);
986
- return {
987
- mimeType: "text/markdown",
988
- body: lines.join(`
989
- `)
990
- };
1475
+ result.executionTimeMs = Date.now() - startTime;
1476
+ result.cached = false;
1477
+ await this.cache.set(cacheKey, result, 300);
1478
+ return result;
991
1479
  }
992
- };
993
- var dashboardListMarkdownRenderer = {
994
- target: "markdown",
995
- render: async (desc) => {
996
- if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
997
- throw new Error("dashboardListMarkdownRenderer: not DashboardList");
1480
+ validateQuery(definition) {
1481
+ const errors = [];
1482
+ if (!definition.type) {
1483
+ errors.push("Query type is required");
998
1484
  }
999
- const dashboards = mockDashboards;
1000
- const lines = [
1001
- "# Dashboards",
1002
- "",
1003
- "> Browse and manage analytics dashboards",
1004
- "",
1005
- "| Dashboard | Widgets | Views | Status | Last Viewed |",
1006
- "|-----------|---------|-------|--------|-------------|"
1007
- ];
1008
- for (const dashboard of dashboards) {
1009
- const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
1010
- const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "\u26AB";
1011
- lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
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;
1012
1508
  }
1013
- lines.push("");
1014
- lines.push("## Quick Actions");
1015
- lines.push("");
1016
- lines.push("- **Create Dashboard** - Start with a blank canvas");
1017
- lines.push("- **Import Template** - Use a pre-built template");
1018
- lines.push("- **Clone Dashboard** - Duplicate an existing dashboard");
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);
1019
1529
  return {
1020
- mimeType: "text/markdown",
1021
- body: lines.join(`
1022
- `)
1530
+ data,
1531
+ columns,
1532
+ rowCount: data.length,
1533
+ executionTimeMs: 0,
1534
+ cached: false
1023
1535
  };
1024
1536
  }
1025
- };
1026
- var queryBuilderMarkdownRenderer = {
1027
- target: "markdown",
1028
- render: async (desc) => {
1029
- if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
1030
- throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
1031
- }
1032
- const queries = mockQueries;
1033
- const lines = [
1034
- "# Query Builder",
1035
- "",
1036
- "> Create and manage data queries",
1037
- "",
1038
- "## Saved Queries",
1039
- "",
1040
- "| Query | Type | Shared | Executions |",
1041
- "|-------|------|--------|------------|"
1042
- ];
1043
- for (const query of queries) {
1044
- const sharedIcon = query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12";
1045
- lines.push(`| ${query.name} | ${query.type} | ${sharedIcon} | ${query.executionCount.toLocaleString()} |`);
1046
- }
1047
- lines.push("");
1048
- lines.push("## Query Types");
1049
- lines.push("");
1050
- lines.push("### METRIC");
1051
- lines.push("Query usage metrics from the metering system.");
1052
- lines.push("");
1053
- lines.push("### AGGREGATION");
1054
- lines.push("Build aggregations with measures and dimensions without writing SQL.");
1055
- lines.push("");
1056
- lines.push("### SQL");
1057
- lines.push("Write custom SQL queries for advanced analysis.");
1058
- lines.push("");
1059
- lines.push("## Features");
1060
- lines.push("");
1061
- lines.push("- Visual query builder");
1062
- lines.push("- Auto-complete for fields and functions");
1063
- lines.push("- Query validation and optimization");
1064
- lines.push("- Result caching");
1065
- lines.push("- Query sharing and collaboration");
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
+ }));
1066
1543
  return {
1067
- mimeType: "text/markdown",
1068
- body: lines.join(`
1069
- `)
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"
1070
1563
  };
1071
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 { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
1688
+ "use client";
1689
+ var QUERY_TYPE_COLORS = {
1690
+ SQL: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
1691
+ METRIC: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",
1692
+ AGGREGATION: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",
1693
+ CUSTOM: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400"
1072
1694
  };
1695
+ function AnalyticsQueriesTable({ queries }) {
1696
+ return /* @__PURE__ */ jsxDEV2("div", {
1697
+ className: "rounded-lg border border-border",
1698
+ children: /* @__PURE__ */ jsxDEV2("table", {
1699
+ className: "w-full",
1700
+ children: [
1701
+ /* @__PURE__ */ jsxDEV2("thead", {
1702
+ className: "border-border border-b bg-muted/30",
1703
+ children: /* @__PURE__ */ jsxDEV2("tr", {
1704
+ children: [
1705
+ /* @__PURE__ */ jsxDEV2("th", {
1706
+ className: "px-4 py-3 text-left font-medium text-sm",
1707
+ children: "Query"
1708
+ }, undefined, false, undefined, this),
1709
+ /* @__PURE__ */ jsxDEV2("th", {
1710
+ className: "px-4 py-3 text-left font-medium text-sm",
1711
+ children: "Type"
1712
+ }, undefined, false, undefined, this),
1713
+ /* @__PURE__ */ jsxDEV2("th", {
1714
+ className: "px-4 py-3 text-left font-medium text-sm",
1715
+ children: "Cache TTL"
1716
+ }, undefined, false, undefined, this),
1717
+ /* @__PURE__ */ jsxDEV2("th", {
1718
+ className: "px-4 py-3 text-left font-medium text-sm",
1719
+ children: "Shared"
1720
+ }, undefined, false, undefined, this)
1721
+ ]
1722
+ }, undefined, true, undefined, this)
1723
+ }, undefined, false, undefined, this),
1724
+ /* @__PURE__ */ jsxDEV2("tbody", {
1725
+ className: "divide-y divide-border",
1726
+ children: [
1727
+ queries.map((query) => /* @__PURE__ */ jsxDEV2("tr", {
1728
+ className: "hover:bg-muted/50",
1729
+ children: [
1730
+ /* @__PURE__ */ jsxDEV2("td", {
1731
+ className: "px-4 py-3",
1732
+ children: [
1733
+ /* @__PURE__ */ jsxDEV2("div", {
1734
+ className: "font-medium",
1735
+ children: query.name
1736
+ }, undefined, false, undefined, this),
1737
+ /* @__PURE__ */ jsxDEV2("div", {
1738
+ className: "text-muted-foreground text-sm",
1739
+ children: query.description
1740
+ }, undefined, false, undefined, this)
1741
+ ]
1742
+ }, undefined, true, undefined, this),
1743
+ /* @__PURE__ */ jsxDEV2("td", {
1744
+ className: "px-4 py-3",
1745
+ children: /* @__PURE__ */ jsxDEV2("span", {
1746
+ className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${QUERY_TYPE_COLORS[query.type] ?? ""}`,
1747
+ children: query.type
1748
+ }, undefined, false, undefined, this)
1749
+ }, undefined, false, undefined, this),
1750
+ /* @__PURE__ */ jsxDEV2("td", {
1751
+ className: "px-4 py-3 text-muted-foreground text-sm",
1752
+ children: [
1753
+ query.cacheTtlSeconds,
1754
+ "s"
1755
+ ]
1756
+ }, undefined, true, undefined, this),
1757
+ /* @__PURE__ */ jsxDEV2("td", {
1758
+ className: "px-4 py-3",
1759
+ children: query.isShared ? /* @__PURE__ */ jsxDEV2("span", {
1760
+ className: "text-green-600 dark:text-green-400",
1761
+ children: "\u2713"
1762
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV2("span", {
1763
+ className: "text-muted-foreground",
1764
+ children: "\u2014"
1765
+ }, undefined, false, undefined, this)
1766
+ }, undefined, false, undefined, this)
1767
+ ]
1768
+ }, query.id, true, undefined, this)),
1769
+ queries.length === 0 && /* @__PURE__ */ jsxDEV2("tr", {
1770
+ children: /* @__PURE__ */ jsxDEV2("td", {
1771
+ colSpan: 4,
1772
+ className: "px-4 py-8 text-center text-muted-foreground",
1773
+ children: "No queries saved"
1774
+ }, undefined, false, undefined, this)
1775
+ }, undefined, false, undefined, this)
1776
+ ]
1777
+ }, undefined, true, undefined, this)
1778
+ ]
1779
+ }, undefined, true, undefined, this)
1780
+ }, undefined, false, undefined, this);
1781
+ }
1782
+
1073
1783
  // src/ui/hooks/useAnalyticsData.ts
1074
- import { useCallback, useEffect, useState } from "react";
1075
1784
  import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
1785
+ import { useCallback, useEffect, useState } from "react";
1076
1786
  "use client";
1077
1787
  function useAnalyticsData(projectId = "local-project") {
1078
1788
  const { handlers } = useTemplateRuntime();
@@ -1098,7 +1808,7 @@ function useAnalyticsData(projectId = "local-project") {
1098
1808
  if (first) {
1099
1809
  setSelectedDashboard(first);
1100
1810
  const dashboardWidgets = await analytics.getWidgets(first.id);
1101
- setWidgets(dashboardWidgets);
1811
+ setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(first.id));
1102
1812
  }
1103
1813
  }
1104
1814
  } catch (err) {
@@ -1113,7 +1823,7 @@ function useAnalyticsData(projectId = "local-project") {
1113
1823
  const selectDashboard = useCallback(async (dashboard) => {
1114
1824
  setSelectedDashboard(dashboard);
1115
1825
  const dashboardWidgets = await analytics.getWidgets(dashboard.id);
1116
- setWidgets(dashboardWidgets);
1826
+ setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(dashboard.id));
1117
1827
  }, [analytics]);
1118
1828
  const stats = {
1119
1829
  totalDashboards: dashboards.length,
@@ -1135,7 +1845,6 @@ function useAnalyticsData(projectId = "local-project") {
1135
1845
  }
1136
1846
 
1137
1847
  // src/ui/AnalyticsDashboard.tsx
1138
- import { useState as useState2 } from "react";
1139
1848
  import {
1140
1849
  Button,
1141
1850
  ErrorState,
@@ -1143,33 +1852,14 @@ import {
1143
1852
  StatCard,
1144
1853
  StatCardGroup
1145
1854
  } from "@contractspec/lib.design-system";
1146
- import { jsxDEV } from "react/jsx-dev-runtime";
1855
+ import { useMemo, useState as useState2 } from "react";
1856
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1147
1857
  "use client";
1148
1858
  var STATUS_COLORS = {
1149
1859
  PUBLISHED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
1150
1860
  DRAFT: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
1151
1861
  ARCHIVED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
1152
1862
  };
1153
- var WIDGET_ICONS = {
1154
- LINE_CHART: "\uD83D\uDCC8",
1155
- BAR_CHART: "\uD83D\uDCCA",
1156
- PIE_CHART: "\uD83E\uDD67",
1157
- AREA_CHART: "\uD83D\uDCC9",
1158
- SCATTER_PLOT: "\u26AC",
1159
- METRIC: "\uD83D\uDD22",
1160
- TABLE: "\uD83D\uDCCB",
1161
- HEATMAP: "\uD83D\uDDFA\uFE0F",
1162
- FUNNEL: "\u23EC",
1163
- MAP: "\uD83C\uDF0D",
1164
- TEXT: "\uD83D\uDCDD",
1165
- EMBED: "\uD83D\uDD17"
1166
- };
1167
- var QUERY_TYPE_COLORS = {
1168
- SQL: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
1169
- METRIC: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",
1170
- AGGREGATION: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",
1171
- CUSTOM: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400"
1172
- };
1173
1863
  function AnalyticsDashboard() {
1174
1864
  const [activeTab, setActiveTab] = useState2("dashboards");
1175
1865
  const {
@@ -1187,33 +1877,34 @@ function AnalyticsDashboard() {
1187
1877
  { id: "dashboards", label: "Dashboards", icon: "\uD83D\uDCCA" },
1188
1878
  { id: "queries", label: "Queries", icon: "\uD83D\uDD0D" }
1189
1879
  ];
1880
+ const resolvedWidgets = useMemo(() => widgets.map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2)), [widgets]);
1190
1881
  if (loading) {
1191
- return /* @__PURE__ */ jsxDEV(LoaderBlock, {
1882
+ return /* @__PURE__ */ jsxDEV3(LoaderBlock, {
1192
1883
  label: "Loading Analytics..."
1193
1884
  }, undefined, false, undefined, this);
1194
1885
  }
1195
1886
  if (error) {
1196
- return /* @__PURE__ */ jsxDEV(ErrorState, {
1887
+ return /* @__PURE__ */ jsxDEV3(ErrorState, {
1197
1888
  title: "Failed to load Analytics",
1198
1889
  description: error.message,
1199
1890
  onRetry: refetch,
1200
1891
  retryLabel: "Retry"
1201
1892
  }, undefined, false, undefined, this);
1202
1893
  }
1203
- return /* @__PURE__ */ jsxDEV("div", {
1894
+ return /* @__PURE__ */ jsxDEV3("div", {
1204
1895
  className: "space-y-6",
1205
1896
  children: [
1206
- /* @__PURE__ */ jsxDEV("div", {
1897
+ /* @__PURE__ */ jsxDEV3("div", {
1207
1898
  className: "flex items-center justify-between",
1208
1899
  children: [
1209
- /* @__PURE__ */ jsxDEV("h2", {
1210
- className: "text-2xl font-bold",
1900
+ /* @__PURE__ */ jsxDEV3("h2", {
1901
+ className: "font-bold text-2xl",
1211
1902
  children: "Analytics Dashboard"
1212
1903
  }, undefined, false, undefined, this),
1213
- /* @__PURE__ */ jsxDEV(Button, {
1904
+ /* @__PURE__ */ jsxDEV3(Button, {
1214
1905
  onClick: () => alert("Create dashboard modal"),
1215
1906
  children: [
1216
- /* @__PURE__ */ jsxDEV("span", {
1907
+ /* @__PURE__ */ jsxDEV3("span", {
1217
1908
  className: "mr-2",
1218
1909
  children: "+"
1219
1910
  }, undefined, false, undefined, this),
@@ -1222,55 +1913,55 @@ function AnalyticsDashboard() {
1222
1913
  }, undefined, true, undefined, this)
1223
1914
  ]
1224
1915
  }, undefined, true, undefined, this),
1225
- /* @__PURE__ */ jsxDEV(StatCardGroup, {
1916
+ /* @__PURE__ */ jsxDEV3(StatCardGroup, {
1226
1917
  children: [
1227
- /* @__PURE__ */ jsxDEV(StatCard, {
1918
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1228
1919
  label: "Dashboards",
1229
1920
  value: stats.totalDashboards,
1230
1921
  hint: `${stats.publishedDashboards} published`
1231
1922
  }, undefined, false, undefined, this),
1232
- /* @__PURE__ */ jsxDEV(StatCard, {
1923
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1233
1924
  label: "Queries",
1234
1925
  value: stats.totalQueries,
1235
1926
  hint: `${stats.sharedQueries} shared`
1236
1927
  }, undefined, false, undefined, this),
1237
- /* @__PURE__ */ jsxDEV(StatCard, {
1928
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1238
1929
  label: "Widgets",
1239
1930
  value: widgets.length,
1240
1931
  hint: "on current dashboard"
1241
1932
  }, undefined, false, undefined, this)
1242
1933
  ]
1243
1934
  }, undefined, true, undefined, this),
1244
- /* @__PURE__ */ jsxDEV("nav", {
1245
- className: "bg-muted flex gap-1 rounded-lg p-1",
1935
+ /* @__PURE__ */ jsxDEV3("nav", {
1936
+ className: "flex gap-1 rounded-lg bg-muted p-1",
1246
1937
  role: "tablist",
1247
- children: tabs.map((tab) => /* @__PURE__ */ jsxDEV(Button, {
1938
+ children: tabs.map((tab) => /* @__PURE__ */ jsxDEV3(Button, {
1248
1939
  type: "button",
1249
1940
  role: "tab",
1250
1941
  "aria-selected": activeTab === tab.id,
1251
1942
  onClick: () => setActiveTab(tab.id),
1252
- className: `flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium transition-colors ${activeTab === tab.id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
1943
+ 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"}`,
1253
1944
  children: [
1254
- /* @__PURE__ */ jsxDEV("span", {
1945
+ /* @__PURE__ */ jsxDEV3("span", {
1255
1946
  children: tab.icon
1256
1947
  }, undefined, false, undefined, this),
1257
1948
  tab.label
1258
1949
  ]
1259
1950
  }, tab.id, true, undefined, this))
1260
1951
  }, undefined, false, undefined, this),
1261
- /* @__PURE__ */ jsxDEV("div", {
1952
+ /* @__PURE__ */ jsxDEV3("div", {
1262
1953
  className: "min-h-[400px]",
1263
1954
  role: "tabpanel",
1264
1955
  children: [
1265
- activeTab === "dashboards" && /* @__PURE__ */ jsxDEV("div", {
1956
+ activeTab === "dashboards" && /* @__PURE__ */ jsxDEV3("div", {
1266
1957
  className: "space-y-6",
1267
1958
  children: [
1268
- /* @__PURE__ */ jsxDEV("div", {
1959
+ /* @__PURE__ */ jsxDEV3("div", {
1269
1960
  className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1270
1961
  children: [
1271
- dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV("div", {
1962
+ dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV3("div", {
1272
1963
  onClick: () => selectDashboard(dashboard),
1273
- className: `border-border bg-card cursor-pointer rounded-lg border p-4 transition-all ${selectedDashboard?.id === dashboard.id ? "ring-primary ring-2" : "hover:bg-muted/50"}`,
1964
+ 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"}`,
1274
1965
  role: "button",
1275
1966
  tabIndex: 0,
1276
1967
  onKeyDown: (e) => {
@@ -1278,33 +1969,33 @@ function AnalyticsDashboard() {
1278
1969
  selectDashboard(dashboard);
1279
1970
  },
1280
1971
  children: [
1281
- /* @__PURE__ */ jsxDEV("div", {
1972
+ /* @__PURE__ */ jsxDEV3("div", {
1282
1973
  className: "mb-2 flex items-center justify-between",
1283
1974
  children: [
1284
- /* @__PURE__ */ jsxDEV("h3", {
1975
+ /* @__PURE__ */ jsxDEV3("h3", {
1285
1976
  className: "font-medium",
1286
1977
  children: dashboard.name
1287
1978
  }, undefined, false, undefined, this),
1288
- /* @__PURE__ */ jsxDEV("span", {
1289
- className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_COLORS[dashboard.status] ?? ""}`,
1979
+ /* @__PURE__ */ jsxDEV3("span", {
1980
+ className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[dashboard.status] ?? ""}`,
1290
1981
  children: dashboard.status
1291
1982
  }, undefined, false, undefined, this)
1292
1983
  ]
1293
1984
  }, undefined, true, undefined, this),
1294
- /* @__PURE__ */ jsxDEV("p", {
1295
- className: "text-muted-foreground mb-3 text-sm",
1985
+ /* @__PURE__ */ jsxDEV3("p", {
1986
+ className: "mb-3 text-muted-foreground text-sm",
1296
1987
  children: dashboard.description
1297
1988
  }, undefined, false, undefined, this),
1298
- /* @__PURE__ */ jsxDEV("div", {
1299
- className: "text-muted-foreground flex items-center justify-between text-xs",
1989
+ /* @__PURE__ */ jsxDEV3("div", {
1990
+ className: "flex items-center justify-between text-muted-foreground text-xs",
1300
1991
  children: [
1301
- /* @__PURE__ */ jsxDEV("span", {
1992
+ /* @__PURE__ */ jsxDEV3("span", {
1302
1993
  children: [
1303
1994
  "/",
1304
1995
  dashboard.slug
1305
1996
  ]
1306
1997
  }, undefined, true, undefined, this),
1307
- dashboard.isPublic && /* @__PURE__ */ jsxDEV("span", {
1998
+ dashboard.isPublic && /* @__PURE__ */ jsxDEV3("span", {
1308
1999
  className: "text-green-600 dark:text-green-400",
1309
2000
  children: "\uD83C\uDF10 Public"
1310
2001
  }, undefined, false, undefined, this)
@@ -1312,149 +2003,20 @@ function AnalyticsDashboard() {
1312
2003
  }, undefined, true, undefined, this)
1313
2004
  ]
1314
2005
  }, dashboard.id, true, undefined, this)),
1315
- dashboards.length === 0 && /* @__PURE__ */ jsxDEV("div", {
1316
- className: "text-muted-foreground col-span-full flex h-64 items-center justify-center",
2006
+ dashboards.length === 0 && /* @__PURE__ */ jsxDEV3("div", {
2007
+ className: "col-span-full flex h-64 items-center justify-center text-muted-foreground",
1317
2008
  children: "No dashboards created yet"
1318
2009
  }, undefined, false, undefined, this)
1319
2010
  ]
1320
2011
  }, undefined, true, undefined, this),
1321
- selectedDashboard && widgets.length > 0 && /* @__PURE__ */ jsxDEV("div", {
1322
- children: [
1323
- /* @__PURE__ */ jsxDEV("h3", {
1324
- className: "mb-4 text-lg font-semibold",
1325
- children: [
1326
- 'Widgets in "',
1327
- selectedDashboard.name,
1328
- '"'
1329
- ]
1330
- }, undefined, true, undefined, this),
1331
- /* @__PURE__ */ jsxDEV("div", {
1332
- className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1333
- children: widgets.map((widget) => /* @__PURE__ */ jsxDEV("div", {
1334
- className: "border-border bg-card rounded-lg border p-4",
1335
- children: [
1336
- /* @__PURE__ */ jsxDEV("div", {
1337
- className: "mb-2 flex items-center gap-2",
1338
- children: [
1339
- /* @__PURE__ */ jsxDEV("span", {
1340
- className: "text-xl",
1341
- children: WIDGET_ICONS[widget.type] ?? "\uD83D\uDCCA"
1342
- }, undefined, false, undefined, this),
1343
- /* @__PURE__ */ jsxDEV("span", {
1344
- className: "font-medium",
1345
- children: widget.name
1346
- }, undefined, false, undefined, this)
1347
- ]
1348
- }, undefined, true, undefined, this),
1349
- /* @__PURE__ */ jsxDEV("div", {
1350
- className: "text-muted-foreground text-sm",
1351
- children: widget.type.replace(/_/g, " ")
1352
- }, undefined, false, undefined, this),
1353
- /* @__PURE__ */ jsxDEV("div", {
1354
- className: "text-muted-foreground mt-2 text-xs",
1355
- children: [
1356
- "Position: (",
1357
- widget.gridX,
1358
- ", ",
1359
- widget.gridY,
1360
- ") \u2022",
1361
- " ",
1362
- widget.gridWidth,
1363
- "x",
1364
- widget.gridHeight
1365
- ]
1366
- }, undefined, true, undefined, this)
1367
- ]
1368
- }, widget.id, true, undefined, this))
1369
- }, undefined, false, undefined, this)
1370
- ]
1371
- }, undefined, true, undefined, this)
2012
+ selectedDashboard ? /* @__PURE__ */ jsxDEV3(AnalyticsWidgetBoard, {
2013
+ dashboardName: selectedDashboard.name,
2014
+ widgets: resolvedWidgets
2015
+ }, undefined, false, undefined, this) : null
1372
2016
  ]
1373
2017
  }, undefined, true, undefined, this),
1374
- activeTab === "queries" && /* @__PURE__ */ jsxDEV("div", {
1375
- className: "border-border rounded-lg border",
1376
- children: /* @__PURE__ */ jsxDEV("table", {
1377
- className: "w-full",
1378
- children: [
1379
- /* @__PURE__ */ jsxDEV("thead", {
1380
- className: "border-border bg-muted/30 border-b",
1381
- children: /* @__PURE__ */ jsxDEV("tr", {
1382
- children: [
1383
- /* @__PURE__ */ jsxDEV("th", {
1384
- className: "px-4 py-3 text-left text-sm font-medium",
1385
- children: "Query"
1386
- }, undefined, false, undefined, this),
1387
- /* @__PURE__ */ jsxDEV("th", {
1388
- className: "px-4 py-3 text-left text-sm font-medium",
1389
- children: "Type"
1390
- }, undefined, false, undefined, this),
1391
- /* @__PURE__ */ jsxDEV("th", {
1392
- className: "px-4 py-3 text-left text-sm font-medium",
1393
- children: "Cache TTL"
1394
- }, undefined, false, undefined, this),
1395
- /* @__PURE__ */ jsxDEV("th", {
1396
- className: "px-4 py-3 text-left text-sm font-medium",
1397
- children: "Shared"
1398
- }, undefined, false, undefined, this)
1399
- ]
1400
- }, undefined, true, undefined, this)
1401
- }, undefined, false, undefined, this),
1402
- /* @__PURE__ */ jsxDEV("tbody", {
1403
- className: "divide-border divide-y",
1404
- children: [
1405
- queries.map((query) => /* @__PURE__ */ jsxDEV("tr", {
1406
- className: "hover:bg-muted/50",
1407
- children: [
1408
- /* @__PURE__ */ jsxDEV("td", {
1409
- className: "px-4 py-3",
1410
- children: [
1411
- /* @__PURE__ */ jsxDEV("div", {
1412
- className: "font-medium",
1413
- children: query.name
1414
- }, undefined, false, undefined, this),
1415
- /* @__PURE__ */ jsxDEV("div", {
1416
- className: "text-muted-foreground text-sm",
1417
- children: query.description
1418
- }, undefined, false, undefined, this)
1419
- ]
1420
- }, undefined, true, undefined, this),
1421
- /* @__PURE__ */ jsxDEV("td", {
1422
- className: "px-4 py-3",
1423
- children: /* @__PURE__ */ jsxDEV("span", {
1424
- className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${QUERY_TYPE_COLORS[query.type] ?? ""}`,
1425
- children: query.type
1426
- }, undefined, false, undefined, this)
1427
- }, undefined, false, undefined, this),
1428
- /* @__PURE__ */ jsxDEV("td", {
1429
- className: "text-muted-foreground px-4 py-3 text-sm",
1430
- children: [
1431
- query.cacheTtlSeconds,
1432
- "s"
1433
- ]
1434
- }, undefined, true, undefined, this),
1435
- /* @__PURE__ */ jsxDEV("td", {
1436
- className: "px-4 py-3",
1437
- children: query.isShared ? /* @__PURE__ */ jsxDEV("span", {
1438
- className: "text-green-600 dark:text-green-400",
1439
- children: "\u2713"
1440
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("span", {
1441
- className: "text-muted-foreground",
1442
- children: "\u2014"
1443
- }, undefined, false, undefined, this)
1444
- }, undefined, false, undefined, this)
1445
- ]
1446
- }, query.id, true, undefined, this)),
1447
- queries.length === 0 && /* @__PURE__ */ jsxDEV("tr", {
1448
- children: /* @__PURE__ */ jsxDEV("td", {
1449
- colSpan: 4,
1450
- className: "text-muted-foreground px-4 py-8 text-center",
1451
- children: "No queries saved"
1452
- }, undefined, false, undefined, this)
1453
- }, undefined, false, undefined, this)
1454
- ]
1455
- }, undefined, true, undefined, this)
1456
- ]
1457
- }, undefined, true, undefined, this)
2018
+ activeTab === "queries" && /* @__PURE__ */ jsxDEV3(AnalyticsQueriesTable, {
2019
+ queries
1458
2020
  }, undefined, false, undefined, this)
1459
2021
  ]
1460
2022
  }, undefined, true, undefined, this)
@@ -1464,222 +2026,204 @@ function AnalyticsDashboard() {
1464
2026
 
1465
2027
  // src/ui/hooks/index.ts
1466
2028
  "use client";
1467
- // src/query-engine/index.ts
1468
- class InMemoryQueryCache {
1469
- cache = new Map;
1470
- async get(key) {
1471
- const entry = this.cache.get(key);
1472
- if (!entry)
1473
- return null;
1474
- if (entry.expiresAt < new Date) {
1475
- this.cache.delete(key);
1476
- return null;
1477
- }
1478
- return { ...entry.result, cached: true, cachedAt: entry.expiresAt };
1479
- }
1480
- async set(key, result, ttlSeconds) {
1481
- const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
1482
- this.cache.set(key, { result, expiresAt });
2029
+
2030
+ // src/ui/renderers/analytics.markdown.ts
2031
+ var mockDashboards = [
2032
+ {
2033
+ id: "dash-1",
2034
+ name: "Sales Overview",
2035
+ slug: "sales-overview",
2036
+ status: "PUBLISHED",
2037
+ widgetCount: 11,
2038
+ viewCount: 1250,
2039
+ lastViewedAt: "2026-03-18T12:00:00Z"
2040
+ },
2041
+ {
2042
+ id: "dash-2",
2043
+ name: "User Engagement",
2044
+ slug: "user-engagement",
2045
+ status: "PUBLISHED",
2046
+ widgetCount: 8,
2047
+ viewCount: 890,
2048
+ lastViewedAt: "2026-03-18T10:00:00Z"
1483
2049
  }
1484
- async invalidate(pattern) {
1485
- const regex = new RegExp(pattern);
1486
- for (const key of this.cache.keys()) {
1487
- if (regex.test(key)) {
1488
- this.cache.delete(key);
1489
- }
1490
- }
2050
+ ];
2051
+ var mockQueries = [
2052
+ {
2053
+ id: "q-1",
2054
+ name: "Monthly Revenue",
2055
+ type: "AGGREGATION",
2056
+ isShared: true,
2057
+ executionCount: 1500
2058
+ },
2059
+ {
2060
+ id: "q-2",
2061
+ name: "User Growth",
2062
+ type: "METRIC",
2063
+ isShared: true,
2064
+ executionCount: 890
2065
+ },
2066
+ {
2067
+ id: "q-3",
2068
+ name: "Product Sales",
2069
+ type: "SQL",
2070
+ isShared: false,
2071
+ executionCount: 340
2072
+ },
2073
+ {
2074
+ id: "q-4",
2075
+ name: "Conversion Funnel",
2076
+ type: "AGGREGATION",
2077
+ isShared: true,
2078
+ executionCount: 450
1491
2079
  }
2080
+ ];
2081
+ function dashboardWidgets(dashboardId) {
2082
+ return createExampleWidgets(dashboardId).map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2));
1492
2083
  }
1493
-
1494
- class BasicQueryEngine {
1495
- cache;
1496
- constructor(cache) {
1497
- this.cache = cache ?? new InMemoryQueryCache;
1498
- }
1499
- async execute(definition, params) {
1500
- const startTime = Date.now();
1501
- const validation = this.validateQuery(definition);
1502
- if (!validation.valid) {
2084
+ var analyticsDashboardMarkdownRenderer = {
2085
+ target: "markdown",
2086
+ render: async (desc) => {
2087
+ if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
2088
+ throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
2089
+ }
2090
+ const dashboard = mockDashboards[0];
2091
+ if (!dashboard) {
1503
2092
  return {
1504
- data: [],
1505
- columns: [],
1506
- rowCount: 0,
1507
- executionTimeMs: Date.now() - startTime,
1508
- cached: false,
1509
- error: validation.errors.join(", ")
2093
+ mimeType: "text/markdown",
2094
+ body: `# No Dashboards
2095
+
2096
+ No dashboards available.`
1510
2097
  };
1511
2098
  }
1512
- const cacheKey = this.buildCacheKey(definition, params);
1513
- const cachedResult = await this.cache.get(cacheKey);
1514
- if (cachedResult) {
1515
- return cachedResult;
1516
- }
1517
- let result;
1518
- switch (definition.type) {
1519
- case "AGGREGATION":
1520
- if (!definition.aggregation) {
1521
- throw new Error("Aggregation definition is missing");
1522
- }
1523
- result = await this.executeAggregation(definition.aggregation, params);
1524
- break;
1525
- case "METRIC":
1526
- if (!definition.metricIds) {
1527
- throw new Error("Metric IDs are missing");
1528
- }
1529
- result = await this.executeMetric(definition.metricIds, params);
1530
- break;
1531
- case "SQL":
1532
- if (!definition.sql) {
1533
- throw new Error("SQL query is missing");
1534
- }
1535
- result = await this.executeSql(definition.sql, params);
1536
- break;
1537
- default:
1538
- result = {
1539
- data: [],
1540
- columns: [],
1541
- rowCount: 0,
1542
- executionTimeMs: Date.now() - startTime,
1543
- cached: false,
1544
- error: `Unknown query type: ${definition.type}`
1545
- };
1546
- }
1547
- result.executionTimeMs = Date.now() - startTime;
1548
- result.cached = false;
1549
- await this.cache.set(cacheKey, result, 300);
1550
- return result;
1551
- }
1552
- validateQuery(definition) {
1553
- const errors = [];
1554
- if (!definition.type) {
1555
- errors.push("Query type is required");
2099
+ const widgets = dashboardWidgets(dashboard.id);
2100
+ const metricWidgets = widgets.filter((widget2) => widget2.bindings[0]?.spec.visualization.kind === "metric");
2101
+ const lines = [
2102
+ `# ${dashboard.name}`,
2103
+ "",
2104
+ "> Contract-backed analytics dashboard overview.",
2105
+ "",
2106
+ "## Key Metrics",
2107
+ ""
2108
+ ];
2109
+ for (const widget2 of metricWidgets) {
2110
+ const binding2 = widget2.bindings[0];
2111
+ if (!binding2)
2112
+ continue;
2113
+ lines.push(`- **${widget2.name}** via \`${binding2.spec.meta.key}\``);
1556
2114
  }
1557
- switch (definition.type) {
1558
- case "SQL":
1559
- if (!definition.sql) {
1560
- errors.push("SQL query is required for SQL type");
1561
- }
1562
- break;
1563
- case "METRIC":
1564
- if (!definition.metricIds || definition.metricIds.length === 0) {
1565
- errors.push("Metric IDs are required for METRIC type");
1566
- }
1567
- break;
1568
- case "AGGREGATION":
1569
- if (!definition.aggregation) {
1570
- errors.push("Aggregation definition is required for AGGREGATION type");
1571
- } else {
1572
- if (!definition.aggregation.source) {
1573
- errors.push("Aggregation source is required");
1574
- }
1575
- if (!definition.aggregation.measures || definition.aggregation.measures.length === 0) {
1576
- errors.push("At least one measure is required");
1577
- }
1578
- }
1579
- break;
2115
+ lines.push("");
2116
+ lines.push("## Visual Blocks");
2117
+ lines.push("");
2118
+ for (const widget2 of widgets) {
2119
+ const kinds = widget2.bindings.map((binding2) => binding2.spec.visualization.kind).join(", ");
2120
+ lines.push(`- **${widget2.name}** (${widget2.layout}) \u2192 ${kinds}`);
1580
2121
  }
1581
- return { valid: errors.length === 0, errors };
1582
- }
1583
- buildCacheKey(definition, params) {
1584
- return JSON.stringify({ definition, params });
1585
- }
1586
- async executeAggregation(aggregation, params) {
1587
- const columns = [
1588
- ...aggregation.dimensions.map((d) => ({
1589
- name: d.name,
1590
- type: d.type === "NUMBER" ? "NUMBER" : d.type === "TIME" ? "DATE" : "STRING",
1591
- label: d.name
1592
- })),
1593
- ...aggregation.measures.map((m) => ({
1594
- name: m.name,
1595
- type: "NUMBER",
1596
- label: m.name,
1597
- format: m.format
1598
- }))
1599
- ];
1600
- const data = this.generateMockData(aggregation, params);
2122
+ lines.push("");
2123
+ lines.push("## Dashboard Stats");
2124
+ lines.push("");
2125
+ lines.push("| Metric | Value |");
2126
+ lines.push("|--------|-------|");
2127
+ lines.push(`| Total Dashboards | ${mockDashboards.length} |`);
2128
+ lines.push(`| Published | ${mockDashboards.filter((item) => item.status === "PUBLISHED").length} |`);
2129
+ lines.push(`| Shared Queries | ${mockQueries.filter((query) => query.isShared).length} |`);
1601
2130
  return {
1602
- data,
1603
- columns,
1604
- rowCount: data.length,
1605
- executionTimeMs: 0,
1606
- cached: false
2131
+ mimeType: "text/markdown",
2132
+ body: lines.join(`
2133
+ `)
1607
2134
  };
1608
2135
  }
1609
- async executeMetric(metricIds, _params) {
1610
- const data = metricIds.map((id) => ({
1611
- metricId: id,
1612
- value: Math.random() * 1000,
1613
- change: (Math.random() - 0.5) * 20
1614
- }));
2136
+ };
2137
+ var dashboardListMarkdownRenderer = {
2138
+ target: "markdown",
2139
+ render: async (desc) => {
2140
+ if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
2141
+ throw new Error("dashboardListMarkdownRenderer: not DashboardList");
2142
+ }
2143
+ const lines = [
2144
+ "# Dashboards",
2145
+ "",
2146
+ "> Browse and manage analytics dashboards",
2147
+ "",
2148
+ "| Dashboard | Widgets | Views | Status | Last Viewed |",
2149
+ "|-----------|---------|-------|--------|-------------|"
2150
+ ];
2151
+ for (const dashboard of mockDashboards) {
2152
+ const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
2153
+ const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "\u26AB";
2154
+ lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
2155
+ }
1615
2156
  return {
1616
- data,
1617
- columns: [
1618
- { name: "metricId", type: "STRING" },
1619
- { name: "value", type: "NUMBER" },
1620
- { name: "change", type: "NUMBER" }
1621
- ],
1622
- rowCount: data.length,
1623
- executionTimeMs: 0,
1624
- cached: false
2157
+ mimeType: "text/markdown",
2158
+ body: lines.join(`
2159
+ `)
1625
2160
  };
1626
2161
  }
1627
- async executeSql(_sql, _params) {
2162
+ };
2163
+ var queryBuilderMarkdownRenderer = {
2164
+ target: "markdown",
2165
+ render: async (desc) => {
2166
+ if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
2167
+ throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
2168
+ }
2169
+ const lines = [
2170
+ "# Query Builder",
2171
+ "",
2172
+ "> Create and manage reusable data queries.",
2173
+ "",
2174
+ "| Query | Type | Shared | Executions |",
2175
+ "|-------|------|--------|------------|"
2176
+ ];
2177
+ for (const query of mockQueries) {
2178
+ lines.push(`| ${query.name} | ${query.type} | ${query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12"} | ${query.executionCount.toLocaleString()} |`);
2179
+ }
2180
+ lines.push("");
2181
+ lines.push("## Visualization Contracts");
2182
+ lines.push("");
2183
+ lines.push("Widgets reference `VisualizationSpec` contracts instead of rendering ad-hoc widget types.");
1628
2184
  return {
1629
- data: [],
1630
- columns: [],
1631
- rowCount: 0,
1632
- executionTimeMs: 0,
1633
- cached: false,
1634
- error: "SQL execution not implemented in demo"
2185
+ mimeType: "text/markdown",
2186
+ body: lines.join(`
2187
+ `)
1635
2188
  };
1636
2189
  }
1637
- generateMockData(aggregation, params) {
1638
- const data = [];
1639
- const rowCount = 10;
1640
- const timeDimension = aggregation.dimensions.find((d) => d.type === "TIME");
1641
- for (let i = 0;i < rowCount; i++) {
1642
- const row = {};
1643
- for (const dim of aggregation.dimensions) {
1644
- if (dim.type === "TIME") {
1645
- const date = new Date(params.dateRange?.start ?? new Date);
1646
- date.setDate(date.getDate() + i);
1647
- row[dim.name] = date.toISOString().split("T")[0];
1648
- } else {
1649
- row[dim.name] = `${dim.name}_${i % 5}`;
1650
- }
1651
- }
1652
- for (const measure of aggregation.measures) {
1653
- const baseValue = timeDimension ? 100 + i * 10 : Math.random() * 1000;
1654
- const noise = (Math.random() - 0.5) * 20;
1655
- row[measure.name] = Math.round((baseValue + noise) * 100) / 100;
1656
- }
1657
- data.push(row);
1658
- }
1659
- return data;
1660
- }
1661
- }
1662
- function createQueryEngine(cache) {
1663
- return new BasicQueryEngine(cache);
1664
- }
2190
+ };
1665
2191
  export {
2192
+ visualizationRefKey,
1666
2193
  useAnalyticsData,
2194
+ resolveAnalyticsWidget,
2195
+ refOf,
1667
2196
  queryBuilderMarkdownRenderer,
1668
2197
  dashboardListMarkdownRenderer,
1669
2198
  createQueryEngine,
1670
2199
  createPosthogQueryEngine,
2200
+ createExampleWidgets,
1671
2201
  createAnalyticsHandlers,
1672
2202
  analyticsDashboardMarkdownRenderer,
2203
+ RevenueTrendVisualization,
2204
+ RevenueMetricVisualization,
2205
+ RetentionAreaVisualization,
2206
+ RegionalRevenueVisualization,
1673
2207
  QueryTypeEnum,
1674
2208
  QueryResultModel,
1675
2209
  QueryModel,
1676
2210
  PosthogQueryEngine,
2211
+ PipelineScatterVisualization,
1677
2212
  InMemoryQueryCache,
1678
2213
  ExecuteQueryInputModel,
1679
2214
  ExecuteQueryContract,
2215
+ EngagementHeatmapVisualization,
1680
2216
  CreateQueryInputModel,
1681
2217
  CreateQueryContract,
2218
+ ConversionFunnelVisualization,
2219
+ ChannelMixVisualization,
1682
2220
  BasicQueryEngine,
2221
+ AnalyticsVisualizationSpecs,
2222
+ AnalyticsVisualizationSpecMap,
2223
+ AnalyticsVisualizationSampleData,
2224
+ AnalyticsVisualizationRegistry,
2225
+ AnalyticsVisualizationRefs,
1683
2226
  AnalyticsDashboardFeature,
1684
- AnalyticsDashboard
2227
+ AnalyticsDashboard,
2228
+ AccountCoverageGeoVisualization
1685
2229
  };