@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
@@ -1,3 +1,594 @@
1
+ // src/visualizations/specs.breakdown.ts
2
+ import { defineVisualization } from "@contractspec/lib.contracts-spec/visualizations";
3
+ var QUERY_REF = { key: "analytics.query.execute", version: "1.0.0" };
4
+ var META = {
5
+ version: "1.0.0",
6
+ domain: "analytics",
7
+ stability: "experimental",
8
+ owners: ["@example.analytics-dashboard"],
9
+ tags: ["analytics", "dashboard", "visualization"]
10
+ };
11
+ var ChannelMixVisualization = defineVisualization({
12
+ meta: {
13
+ ...META,
14
+ key: "analytics.visualization.channel-mix",
15
+ title: "Channel Mix",
16
+ description: "Session distribution across acquisition channels.",
17
+ goal: "Explain which channels currently drive the largest share of traffic.",
18
+ context: "Marketing attribution dashboard."
19
+ },
20
+ source: { primary: QUERY_REF, resultPath: "data" },
21
+ visualization: {
22
+ kind: "pie",
23
+ nameDimension: "channel",
24
+ valueMeasure: "sessions",
25
+ dimensions: [
26
+ {
27
+ key: "channel",
28
+ label: "Channel",
29
+ dataPath: "channel",
30
+ type: "category"
31
+ }
32
+ ],
33
+ measures: [{ key: "sessions", label: "Sessions", dataPath: "sessions" }],
34
+ table: { caption: "Sessions by acquisition channel." }
35
+ }
36
+ });
37
+ var EngagementHeatmapVisualization = defineVisualization({
38
+ meta: {
39
+ ...META,
40
+ key: "analytics.visualization.engagement-heatmap",
41
+ title: "Engagement Heatmap",
42
+ description: "Average engagement score by weekday and time band.",
43
+ goal: "Reveal the highest-engagement time windows for product activity.",
44
+ context: "Usage analytics dashboard."
45
+ },
46
+ source: { primary: QUERY_REF, resultPath: "data" },
47
+ visualization: {
48
+ kind: "heatmap",
49
+ xDimension: "timeBand",
50
+ yDimension: "weekday",
51
+ valueMeasure: "engagementScore",
52
+ dimensions: [
53
+ {
54
+ key: "timeBand",
55
+ label: "Time Band",
56
+ dataPath: "timeBand",
57
+ type: "category"
58
+ },
59
+ {
60
+ key: "weekday",
61
+ label: "Weekday",
62
+ dataPath: "weekday",
63
+ type: "category"
64
+ }
65
+ ],
66
+ measures: [
67
+ {
68
+ key: "engagementScore",
69
+ label: "Engagement",
70
+ dataPath: "engagementScore"
71
+ }
72
+ ],
73
+ table: { caption: "Engagement score by weekday and time band." }
74
+ }
75
+ });
76
+ var ConversionFunnelVisualization = defineVisualization({
77
+ meta: {
78
+ ...META,
79
+ key: "analytics.visualization.conversion-funnel",
80
+ title: "Conversion Funnel",
81
+ description: "Progression through the main acquisition funnel.",
82
+ goal: "Show where the product is losing the largest share of prospects.",
83
+ context: "Growth dashboard."
84
+ },
85
+ source: { primary: QUERY_REF, resultPath: "data" },
86
+ visualization: {
87
+ kind: "funnel",
88
+ nameDimension: "stage",
89
+ valueMeasure: "users",
90
+ sort: "descending",
91
+ dimensions: [
92
+ { key: "stage", label: "Stage", dataPath: "stage", type: "category" }
93
+ ],
94
+ measures: [{ key: "users", label: "Users", dataPath: "users" }],
95
+ table: { caption: "Users per conversion stage." }
96
+ }
97
+ });
98
+ var AccountCoverageGeoVisualization = defineVisualization({
99
+ meta: {
100
+ ...META,
101
+ key: "analytics.visualization.account-coverage-geo",
102
+ title: "Account Coverage",
103
+ description: "High-value accounts plotted on a slippy-map surface.",
104
+ goal: "Locate where active commercial concentration is strongest.",
105
+ context: "Territory coverage dashboard."
106
+ },
107
+ source: { primary: QUERY_REF, resultPath: "data" },
108
+ visualization: {
109
+ kind: "geo",
110
+ mode: "slippy-map",
111
+ variant: "scatter",
112
+ nameDimension: "city",
113
+ latitudeDimension: "latitude",
114
+ longitudeDimension: "longitude",
115
+ valueMeasure: "accounts",
116
+ dimensions: [
117
+ { key: "city", label: "City", dataPath: "city", type: "category" },
118
+ {
119
+ key: "latitude",
120
+ label: "Latitude",
121
+ dataPath: "latitude",
122
+ type: "latitude"
123
+ },
124
+ {
125
+ key: "longitude",
126
+ label: "Longitude",
127
+ dataPath: "longitude",
128
+ type: "longitude"
129
+ }
130
+ ],
131
+ measures: [{ key: "accounts", label: "Accounts", dataPath: "accounts" }],
132
+ table: { caption: "Account concentration by city." }
133
+ }
134
+ });
135
+
136
+ // src/visualizations/specs.performance.ts
137
+ import { defineVisualization as defineVisualization2 } from "@contractspec/lib.contracts-spec/visualizations";
138
+ var QUERY_REF2 = { key: "analytics.query.execute", version: "1.0.0" };
139
+ var META2 = {
140
+ version: "1.0.0",
141
+ domain: "analytics",
142
+ stability: "experimental",
143
+ owners: ["@example.analytics-dashboard"],
144
+ tags: ["analytics", "dashboard", "visualization"]
145
+ };
146
+ var RevenueMetricVisualization = defineVisualization2({
147
+ meta: {
148
+ ...META2,
149
+ key: "analytics.visualization.revenue-metric",
150
+ title: "Revenue Snapshot",
151
+ description: "Current recurring revenue with prior-period comparison.",
152
+ goal: "Highlight the headline commercial metric for the dashboard.",
153
+ context: "Executive revenue overview."
154
+ },
155
+ source: { primary: QUERY_REF2, resultPath: "data" },
156
+ visualization: {
157
+ kind: "metric",
158
+ measure: "totalRevenue",
159
+ comparisonMeasure: "priorRevenue",
160
+ dimensions: [
161
+ { key: "period", label: "Period", dataPath: "period", type: "time" }
162
+ ],
163
+ measures: [
164
+ {
165
+ key: "totalRevenue",
166
+ label: "Revenue",
167
+ dataPath: "totalRevenue",
168
+ format: "currency"
169
+ },
170
+ {
171
+ key: "priorRevenue",
172
+ label: "Prior Revenue",
173
+ dataPath: "priorRevenue",
174
+ format: "currency"
175
+ }
176
+ ],
177
+ sparkline: { dimension: "period", measure: "totalRevenue" },
178
+ table: { caption: "Revenue trend and prior period values." }
179
+ }
180
+ });
181
+ var RevenueTrendVisualization = defineVisualization2({
182
+ meta: {
183
+ ...META2,
184
+ key: "analytics.visualization.revenue-trend",
185
+ title: "Revenue Trend",
186
+ description: "Monthly revenue progression for the current quarter.",
187
+ goal: "Track whether revenue growth is accelerating or stalling.",
188
+ context: "Quarterly commercial dashboard."
189
+ },
190
+ source: { primary: QUERY_REF2, resultPath: "data" },
191
+ visualization: {
192
+ kind: "cartesian",
193
+ variant: "line",
194
+ xDimension: "date",
195
+ yMeasures: ["revenue"],
196
+ dimensions: [
197
+ { key: "date", label: "Month", dataPath: "date", type: "time" }
198
+ ],
199
+ measures: [
200
+ {
201
+ key: "revenue",
202
+ label: "Revenue",
203
+ dataPath: "revenue",
204
+ format: "currency",
205
+ color: "#0f766e"
206
+ }
207
+ ],
208
+ thresholds: [
209
+ { key: "target", value: 140000, label: "Target", color: "#dc2626" }
210
+ ],
211
+ table: { caption: "Monthly revenue values." }
212
+ }
213
+ });
214
+ var RegionalRevenueVisualization = defineVisualization2({
215
+ meta: {
216
+ ...META2,
217
+ key: "analytics.visualization.regional-revenue",
218
+ title: "Regional Revenue",
219
+ description: "Revenue split by sales territory.",
220
+ goal: "Compare the strongest and weakest performing territories.",
221
+ context: "Territory planning and commercial comparison."
222
+ },
223
+ source: { primary: QUERY_REF2, resultPath: "data" },
224
+ visualization: {
225
+ kind: "cartesian",
226
+ variant: "bar",
227
+ xDimension: "region",
228
+ yMeasures: ["revenue"],
229
+ dimensions: [
230
+ { key: "region", label: "Region", dataPath: "region", type: "category" }
231
+ ],
232
+ measures: [
233
+ {
234
+ key: "revenue",
235
+ label: "Revenue",
236
+ dataPath: "revenue",
237
+ format: "currency",
238
+ color: "#1d4ed8"
239
+ }
240
+ ],
241
+ table: { caption: "Revenue by region." }
242
+ }
243
+ });
244
+ var RetentionAreaVisualization = defineVisualization2({
245
+ meta: {
246
+ ...META2,
247
+ key: "analytics.visualization.retention-area",
248
+ title: "Retention Curve",
249
+ description: "Weekly retention progression across the active cohort.",
250
+ goal: "Show whether user retention remains above the desired floor.",
251
+ context: "Product health dashboard."
252
+ },
253
+ source: { primary: QUERY_REF2, resultPath: "data" },
254
+ visualization: {
255
+ kind: "cartesian",
256
+ variant: "area",
257
+ xDimension: "week",
258
+ yMeasures: ["retentionRate"],
259
+ dimensions: [
260
+ { key: "week", label: "Week", dataPath: "week", type: "category" }
261
+ ],
262
+ measures: [
263
+ {
264
+ key: "retentionRate",
265
+ label: "Retention",
266
+ dataPath: "retentionRate",
267
+ format: "percentage",
268
+ color: "#16a34a"
269
+ }
270
+ ],
271
+ thresholds: [
272
+ { key: "floor", value: 0.5, label: "Floor", color: "#f59e0b" }
273
+ ],
274
+ table: { caption: "Weekly retention rate." }
275
+ }
276
+ });
277
+ var PipelineScatterVisualization = defineVisualization2({
278
+ meta: {
279
+ ...META2,
280
+ key: "analytics.visualization.pipeline-scatter",
281
+ title: "Pipeline Velocity",
282
+ description: "Deal-cycle length against win rate for active accounts.",
283
+ goal: "Spot outliers where the sales cycle is long but conversion remains weak.",
284
+ context: "Commercial operations dashboard."
285
+ },
286
+ source: { primary: QUERY_REF2, resultPath: "data" },
287
+ visualization: {
288
+ kind: "cartesian",
289
+ variant: "scatter",
290
+ xDimension: "cycleDays",
291
+ yMeasures: ["winRate"],
292
+ dimensions: [
293
+ {
294
+ key: "cycleDays",
295
+ label: "Cycle Days",
296
+ dataPath: "cycleDays",
297
+ type: "number"
298
+ }
299
+ ],
300
+ measures: [
301
+ {
302
+ key: "winRate",
303
+ label: "Win Rate",
304
+ dataPath: "winRate",
305
+ format: "percentage",
306
+ color: "#7c3aed"
307
+ },
308
+ {
309
+ key: "arr",
310
+ label: "ARR",
311
+ dataPath: "arr",
312
+ format: "currency"
313
+ }
314
+ ],
315
+ series: [
316
+ {
317
+ key: "pipeline",
318
+ label: "Accounts",
319
+ measure: "winRate",
320
+ type: "scatter",
321
+ color: "#7c3aed"
322
+ }
323
+ ],
324
+ table: { caption: "Sales cycle and win rate per account." }
325
+ }
326
+ });
327
+
328
+ // src/visualizations/catalog.ts
329
+ import { VisualizationRegistry } from "@contractspec/lib.contracts-spec/visualizations";
330
+ var AnalyticsVisualizationSpecs = [
331
+ RevenueMetricVisualization,
332
+ RevenueTrendVisualization,
333
+ RegionalRevenueVisualization,
334
+ RetentionAreaVisualization,
335
+ PipelineScatterVisualization,
336
+ ChannelMixVisualization,
337
+ EngagementHeatmapVisualization,
338
+ ConversionFunnelVisualization,
339
+ AccountCoverageGeoVisualization
340
+ ];
341
+ var AnalyticsVisualizationRegistry = new VisualizationRegistry([
342
+ ...AnalyticsVisualizationSpecs
343
+ ]);
344
+ var AnalyticsVisualizationRefs = AnalyticsVisualizationSpecs.map((spec) => refOf(spec));
345
+ var AnalyticsVisualizationSpecMap = new Map(AnalyticsVisualizationSpecs.map((spec) => [
346
+ visualizationRefKey(spec.meta),
347
+ spec
348
+ ]));
349
+ var AnalyticsVisualizationSampleData = {
350
+ [visualizationRefKey(RevenueMetricVisualization.meta)]: {
351
+ data: [
352
+ { period: "2025-11-01", totalRevenue: 112000, priorRevenue: 103000 },
353
+ { period: "2025-12-01", totalRevenue: 119000, priorRevenue: 110000 },
354
+ { period: "2026-01-01", totalRevenue: 126500, priorRevenue: 116000 },
355
+ { period: "2026-02-01", totalRevenue: 133000, priorRevenue: 124000 },
356
+ { period: "2026-03-01", totalRevenue: 145500, priorRevenue: 133000 }
357
+ ]
358
+ },
359
+ [visualizationRefKey(RevenueTrendVisualization.meta)]: {
360
+ data: [
361
+ { date: "2025-11-01", revenue: 112000 },
362
+ { date: "2025-12-01", revenue: 119000 },
363
+ { date: "2026-01-01", revenue: 126500 },
364
+ { date: "2026-02-01", revenue: 133000 },
365
+ { date: "2026-03-01", revenue: 145500 }
366
+ ]
367
+ },
368
+ [visualizationRefKey(RegionalRevenueVisualization.meta)]: {
369
+ data: [
370
+ { region: "North America", revenue: 210000 },
371
+ { region: "EMEA", revenue: 174000 },
372
+ { region: "APAC", revenue: 132000 },
373
+ { region: "LATAM", revenue: 88000 }
374
+ ]
375
+ },
376
+ [visualizationRefKey(RetentionAreaVisualization.meta)]: {
377
+ data: [
378
+ { week: "Week 1", retentionRate: 0.71 },
379
+ { week: "Week 2", retentionRate: 0.66 },
380
+ { week: "Week 3", retentionRate: 0.62 },
381
+ { week: "Week 4", retentionRate: 0.58 },
382
+ { week: "Week 5", retentionRate: 0.55 },
383
+ { week: "Week 6", retentionRate: 0.53 }
384
+ ]
385
+ },
386
+ [visualizationRefKey(PipelineScatterVisualization.meta)]: {
387
+ data: [
388
+ { cycleDays: 18, winRate: 0.31, arr: 82000 },
389
+ { cycleDays: 26, winRate: 0.44, arr: 65000 },
390
+ { cycleDays: 33, winRate: 0.27, arr: 91000 },
391
+ { cycleDays: 14, winRate: 0.56, arr: 47000 },
392
+ { cycleDays: 21, winRate: 0.48, arr: 59000 },
393
+ { cycleDays: 39, winRate: 0.22, arr: 114000 }
394
+ ]
395
+ },
396
+ [visualizationRefKey(ChannelMixVisualization.meta)]: {
397
+ data: [
398
+ { channel: "Direct", sessions: 4200 },
399
+ { channel: "Organic Search", sessions: 3600 },
400
+ { channel: "Paid Search", sessions: 2100 },
401
+ { channel: "Partner", sessions: 1400 },
402
+ { channel: "Referral", sessions: 900 }
403
+ ]
404
+ },
405
+ [visualizationRefKey(EngagementHeatmapVisualization.meta)]: {
406
+ data: [
407
+ { weekday: "Mon", timeBand: "09:00", engagementScore: 74 },
408
+ { weekday: "Mon", timeBand: "13:00", engagementScore: 82 },
409
+ { weekday: "Tue", timeBand: "09:00", engagementScore: 69 },
410
+ { weekday: "Tue", timeBand: "13:00", engagementScore: 88 },
411
+ { weekday: "Wed", timeBand: "09:00", engagementScore: 77 },
412
+ { weekday: "Wed", timeBand: "13:00", engagementScore: 91 },
413
+ { weekday: "Thu", timeBand: "09:00", engagementScore: 72 },
414
+ { weekday: "Thu", timeBand: "13:00", engagementScore: 86 },
415
+ { weekday: "Fri", timeBand: "09:00", engagementScore: 65 },
416
+ { weekday: "Fri", timeBand: "13:00", engagementScore: 79 }
417
+ ]
418
+ },
419
+ [visualizationRefKey(ConversionFunnelVisualization.meta)]: {
420
+ data: [
421
+ { stage: "Visited Site", users: 12000 },
422
+ { stage: "Started Trial", users: 4200 },
423
+ { stage: "Activated Workspace", users: 2400 },
424
+ { stage: "Requested Demo", users: 980 },
425
+ { stage: "Closed Won", users: 310 }
426
+ ]
427
+ },
428
+ [visualizationRefKey(AccountCoverageGeoVisualization.meta)]: {
429
+ data: [
430
+ { city: "Paris", latitude: 48.8566, longitude: 2.3522, accounts: 48 },
431
+ { city: "London", latitude: 51.5072, longitude: -0.1276, accounts: 62 },
432
+ { city: "New York", latitude: 40.7128, longitude: -74.006, accounts: 71 },
433
+ { city: "Toronto", latitude: 43.6532, longitude: -79.3832, accounts: 36 },
434
+ {
435
+ city: "Singapore",
436
+ latitude: 1.3521,
437
+ longitude: 103.8198,
438
+ accounts: 29
439
+ }
440
+ ]
441
+ }
442
+ };
443
+ function refOf(spec) {
444
+ return { key: spec.meta.key, version: spec.meta.version };
445
+ }
446
+ function visualizationRefKey(ref) {
447
+ return `${ref.key}.v${ref.version}`;
448
+ }
449
+
450
+ // src/visualizations/widgets.ts
451
+ var LEGACY_VISUALIZATION_REFS = {
452
+ METRIC: refOf(RevenueMetricVisualization),
453
+ LINE_CHART: refOf(RevenueTrendVisualization),
454
+ BAR_CHART: refOf(RegionalRevenueVisualization),
455
+ AREA_CHART: refOf(RetentionAreaVisualization),
456
+ SCATTER_PLOT: refOf(PipelineScatterVisualization),
457
+ PIE_CHART: refOf(ChannelMixVisualization),
458
+ HEATMAP: refOf(EngagementHeatmapVisualization),
459
+ FUNNEL: refOf(ConversionFunnelVisualization),
460
+ MAP: refOf(AccountCoverageGeoVisualization)
461
+ };
462
+ function createExampleWidgets(dashboardId) {
463
+ return [
464
+ widget(dashboardId, "widget_revenue_metric", "Revenue Snapshot", "METRIC", 0, 0, 4, 2, {
465
+ layout: "single",
466
+ bindings: [binding(RevenueMetricVisualization, 200)]
467
+ }),
468
+ widget(dashboardId, "widget_revenue_trend", "Revenue Trend", "LINE_CHART", 4, 0, 8, 4, {
469
+ layout: "single",
470
+ bindings: [binding(RevenueTrendVisualization)]
471
+ }),
472
+ widget(dashboardId, "widget_regional_revenue", "Regional Revenue", "BAR_CHART", 0, 2, 6, 4, {
473
+ layout: "single",
474
+ bindings: [binding(RegionalRevenueVisualization)]
475
+ }),
476
+ widget(dashboardId, "widget_channel_mix", "Channel Mix", "PIE_CHART", 6, 2, 6, 4, {
477
+ layout: "single",
478
+ bindings: [binding(ChannelMixVisualization)]
479
+ }),
480
+ widget(dashboardId, "widget_retention", "Retention Curve", "AREA_CHART", 0, 6, 6, 4, {
481
+ layout: "single",
482
+ bindings: [binding(RetentionAreaVisualization)]
483
+ }),
484
+ widget(dashboardId, "widget_pipeline", "Pipeline Velocity", "SCATTER_PLOT", 6, 6, 6, 4, {
485
+ layout: "single",
486
+ bindings: [binding(PipelineScatterVisualization)]
487
+ }),
488
+ widget(dashboardId, "widget_heatmap", "Engagement Heatmap", "HEATMAP", 0, 10, 8, 4, {
489
+ layout: "single",
490
+ bindings: [binding(EngagementHeatmapVisualization)]
491
+ }),
492
+ widget(dashboardId, "widget_funnel", "Conversion Funnel", "FUNNEL", 8, 10, 4, 4, {
493
+ layout: "single",
494
+ bindings: [binding(ConversionFunnelVisualization)]
495
+ }),
496
+ widget(dashboardId, "widget_geo", "Account Coverage", "MAP", 0, 14, 12, 5, {
497
+ layout: "single",
498
+ bindings: [binding(AccountCoverageGeoVisualization, 360)]
499
+ }),
500
+ widget(dashboardId, "widget_comparison", "Commercial Comparison", "EMBED", 0, 19, 12, 6, {
501
+ layout: "comparison",
502
+ description: "Compare regional distribution, channel balance, and funnel shape.",
503
+ bindings: [
504
+ binding(RegionalRevenueVisualization, 240),
505
+ binding(ChannelMixVisualization, 240),
506
+ binding(ConversionFunnelVisualization, 240)
507
+ ]
508
+ }),
509
+ widget(dashboardId, "widget_timeline", "Growth Timeline", "EMBED", 0, 25, 12, 6, {
510
+ layout: "timeline",
511
+ description: "Track revenue and retention over the same reporting cadence.",
512
+ bindings: [
513
+ binding(RevenueTrendVisualization, 220),
514
+ binding(RetentionAreaVisualization, 220)
515
+ ]
516
+ })
517
+ ];
518
+ }
519
+ function resolveAnalyticsWidget(widget) {
520
+ const config = parseWidgetConfig(widget);
521
+ const bindings = config.bindings.map((binding) => {
522
+ const spec = AnalyticsVisualizationSpecMap.get(visualizationRefKey(binding.ref));
523
+ if (!spec)
524
+ return null;
525
+ return {
526
+ key: `${widget.id}:${visualizationRefKey(binding.ref)}`,
527
+ spec,
528
+ data: binding.data,
529
+ title: binding.title ?? spec.meta.title,
530
+ description: binding.description ?? spec.meta.description,
531
+ height: binding.height
532
+ };
533
+ }).filter((binding) => Boolean(binding));
534
+ if (!bindings.length)
535
+ return null;
536
+ return {
537
+ id: widget.id,
538
+ name: widget.name,
539
+ description: config.description,
540
+ layout: config.layout,
541
+ gridX: widget.gridX,
542
+ gridY: widget.gridY,
543
+ gridWidth: widget.gridWidth,
544
+ gridHeight: widget.gridHeight,
545
+ bindings
546
+ };
547
+ }
548
+ function parseWidgetConfig(widget) {
549
+ if (isAnalyticsWidgetConfig(widget.config)) {
550
+ return widget.config;
551
+ }
552
+ const legacyRef = LEGACY_VISUALIZATION_REFS[widget.type];
553
+ return legacyRef ? {
554
+ layout: "single",
555
+ bindings: [
556
+ {
557
+ ref: legacyRef,
558
+ data: AnalyticsVisualizationSampleData[visualizationRefKey(legacyRef)]
559
+ }
560
+ ]
561
+ } : { layout: "single", bindings: [] };
562
+ }
563
+ function binding(spec, height = 280) {
564
+ return {
565
+ ref: refOf(spec),
566
+ data: AnalyticsVisualizationSampleData[visualizationRefKey(spec.meta)],
567
+ height
568
+ };
569
+ }
570
+ function widget(dashboardId, id, name, type, gridX, gridY, gridWidth, gridHeight, config) {
571
+ const now = new Date;
572
+ return {
573
+ id,
574
+ dashboardId,
575
+ name,
576
+ type,
577
+ gridX,
578
+ gridY,
579
+ gridWidth,
580
+ gridHeight,
581
+ config,
582
+ createdAt: now,
583
+ updatedAt: now
584
+ };
585
+ }
586
+ function isAnalyticsWidgetConfig(value) {
587
+ if (!value || typeof value !== "object")
588
+ return false;
589
+ const candidate = value;
590
+ return (candidate.layout === "single" || candidate.layout === "comparison" || candidate.layout === "timeline") && Array.isArray(candidate.bindings);
591
+ }
1
592
  // src/dashboard.feature.ts
2
593
  import { defineFeature } from "@contractspec/lib.contracts-spec";
3
594
  var AnalyticsDashboardFeature = defineFeature({
@@ -31,6 +622,7 @@ var AnalyticsDashboardFeature = defineFeature({
31
622
  { key: "analytics.query.list", version: "1.0.0" },
32
623
  { key: "analytics.query.builder", version: "1.0.0" }
33
624
  ],
625
+ visualizations: [...AnalyticsVisualizationRefs],
34
626
  opToPresentation: [
35
627
  {
36
628
  op: { key: "analytics.dashboard.list", version: "1.0.0" },
@@ -799,279 +1391,397 @@ var ExecuteQueryContract = defineQuery({
799
1391
  ]
800
1392
  }
801
1393
  });
802
- // src/ui/renderers/analytics.markdown.ts
803
- var mockDashboards = [
804
- {
805
- id: "dash-1",
806
- name: "Sales Overview",
807
- slug: "sales-overview",
808
- status: "PUBLISHED",
809
- widgetCount: 8,
810
- viewCount: 1250,
811
- lastViewedAt: "2024-01-16T12:00:00Z"
812
- },
813
- {
814
- id: "dash-2",
815
- name: "User Engagement",
816
- slug: "user-engagement",
817
- status: "PUBLISHED",
818
- widgetCount: 6,
819
- viewCount: 890,
820
- lastViewedAt: "2024-01-16T10:00:00Z"
821
- },
822
- {
823
- id: "dash-3",
824
- name: "Product Analytics",
825
- slug: "product-analytics",
826
- status: "PUBLISHED",
827
- widgetCount: 10,
828
- viewCount: 560,
829
- lastViewedAt: "2024-01-15T14:00:00Z"
830
- },
831
- {
832
- id: "dash-4",
833
- name: "Finance Report",
834
- slug: "finance-report",
835
- status: "DRAFT",
836
- widgetCount: 4,
837
- viewCount: 0,
838
- lastViewedAt: null
839
- }
840
- ];
841
- var mockWidgets = [
842
- {
843
- id: "w-1",
844
- dashboardId: "dash-1",
845
- name: "Total Revenue",
846
- type: "METRIC",
847
- value: 125000,
848
- change: 12.5
849
- },
850
- {
851
- id: "w-2",
852
- dashboardId: "dash-1",
853
- name: "Active Users",
854
- type: "METRIC",
855
- value: 4500,
856
- change: 8.2
857
- },
858
- {
859
- id: "w-3",
860
- dashboardId: "dash-1",
861
- name: "Revenue Trend",
862
- type: "LINE_CHART",
863
- dataPoints: 30
864
- },
865
- {
866
- id: "w-4",
867
- dashboardId: "dash-1",
868
- name: "Top Products",
869
- type: "BAR_CHART",
870
- dataPoints: 10
871
- },
872
- {
873
- id: "w-5",
874
- dashboardId: "dash-2",
875
- name: "Daily Active Users",
876
- type: "LINE_CHART",
877
- dataPoints: 30
878
- },
879
- {
880
- id: "w-6",
881
- dashboardId: "dash-2",
882
- name: "Session Duration",
883
- type: "METRIC",
884
- value: 245,
885
- change: -3.1
886
- }
887
- ];
888
- var mockQueries = [
889
- {
890
- id: "q-1",
891
- name: "Monthly Revenue",
892
- type: "AGGREGATION",
893
- isShared: true,
894
- executionCount: 1500
895
- },
896
- {
897
- id: "q-2",
898
- name: "User Growth",
899
- type: "METRIC",
900
- isShared: true,
901
- executionCount: 890
902
- },
903
- {
904
- id: "q-3",
905
- name: "Product Sales",
906
- type: "SQL",
907
- isShared: false,
908
- executionCount: 340
909
- },
910
- {
911
- id: "q-4",
912
- name: "Conversion Funnel",
913
- type: "AGGREGATION",
914
- isShared: true,
915
- executionCount: 450
1394
+ // src/query-engine/index.ts
1395
+ class InMemoryQueryCache {
1396
+ cache = new Map;
1397
+ async get(key) {
1398
+ const entry = this.cache.get(key);
1399
+ if (!entry)
1400
+ return null;
1401
+ if (entry.expiresAt < new Date) {
1402
+ this.cache.delete(key);
1403
+ return null;
1404
+ }
1405
+ return { ...entry.result, cached: true, cachedAt: entry.expiresAt };
916
1406
  }
917
- ];
918
- function formatNumber(value) {
919
- if (value >= 1e6) {
920
- return `${(value / 1e6).toFixed(1)}M`;
1407
+ async set(key, result, ttlSeconds) {
1408
+ const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
1409
+ this.cache.set(key, { result, expiresAt });
921
1410
  }
922
- if (value >= 1000) {
923
- return `${(value / 1000).toFixed(1)}K`;
1411
+ async invalidate(pattern) {
1412
+ const regex = new RegExp(pattern);
1413
+ for (const key of this.cache.keys()) {
1414
+ if (regex.test(key)) {
1415
+ this.cache.delete(key);
1416
+ }
1417
+ }
924
1418
  }
925
- return value.toString();
926
- }
927
- function formatChange(change) {
928
- const icon = change >= 0 ? "\uD83D\uDCC8" : "\uD83D\uDCC9";
929
- const sign = change >= 0 ? "+" : "";
930
- return `${icon} ${sign}${change.toFixed(1)}%`;
931
1419
  }
932
- var analyticsDashboardMarkdownRenderer = {
933
- target: "markdown",
934
- render: async (desc) => {
935
- if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
936
- throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
937
- }
938
- const dashboards = mockDashboards;
939
- const widgets = mockWidgets;
940
- const queries = mockQueries;
941
- const dashboard = dashboards[0];
942
- if (!dashboard) {
943
- return {
944
- mimeType: "text/markdown",
945
- body: `# No Dashboards
946
1420
 
947
- No dashboards available.`
1421
+ class BasicQueryEngine {
1422
+ cache;
1423
+ constructor(cache) {
1424
+ this.cache = cache ?? new InMemoryQueryCache;
1425
+ }
1426
+ async execute(definition, params) {
1427
+ const startTime = Date.now();
1428
+ const validation = this.validateQuery(definition);
1429
+ if (!validation.valid) {
1430
+ return {
1431
+ data: [],
1432
+ columns: [],
1433
+ rowCount: 0,
1434
+ executionTimeMs: Date.now() - startTime,
1435
+ cached: false,
1436
+ error: validation.errors.join(", ")
948
1437
  };
949
1438
  }
950
- const dashboardWidgets = widgets.filter((w) => w.dashboardId === dashboard.id);
951
- const publishedDashboards = dashboards.filter((d) => d.status === "PUBLISHED");
952
- const totalViews = dashboards.reduce((sum, d) => sum + d.viewCount, 0);
953
- const sharedQueries = queries.filter((q) => q.isShared);
954
- const lines = [
955
- `# ${dashboard.name}`,
956
- "",
957
- "> Analytics dashboard overview",
958
- "",
959
- "## Key Metrics",
960
- ""
961
- ];
962
- const metricWidgets = dashboardWidgets.filter((w) => w.type === "METRIC");
963
- for (const widget of metricWidgets) {
964
- const w = widget;
965
- lines.push(`### ${w.name}`);
966
- lines.push(`**${formatNumber(w.value)}** ${formatChange(w.change)}`);
967
- lines.push("");
1439
+ const cacheKey = this.buildCacheKey(definition, params);
1440
+ const cachedResult = await this.cache.get(cacheKey);
1441
+ if (cachedResult) {
1442
+ return cachedResult;
968
1443
  }
969
- lines.push("## Visualizations");
970
- lines.push("");
971
- const chartWidgets = dashboardWidgets.filter((w) => w.type !== "METRIC");
972
- for (const widget of chartWidgets) {
973
- const w = widget;
974
- lines.push(`- **${w.name}** (${w.type.replace("_", " ")}) - ${w.dataPoints} data points`);
1444
+ let result;
1445
+ switch (definition.type) {
1446
+ case "AGGREGATION":
1447
+ if (!definition.aggregation) {
1448
+ throw new Error("Aggregation definition is missing");
1449
+ }
1450
+ result = await this.executeAggregation(definition.aggregation, params);
1451
+ break;
1452
+ case "METRIC":
1453
+ if (!definition.metricIds) {
1454
+ throw new Error("Metric IDs are missing");
1455
+ }
1456
+ result = await this.executeMetric(definition.metricIds, params);
1457
+ break;
1458
+ case "SQL":
1459
+ if (!definition.sql) {
1460
+ throw new Error("SQL query is missing");
1461
+ }
1462
+ result = await this.executeSql(definition.sql, params);
1463
+ break;
1464
+ default:
1465
+ result = {
1466
+ data: [],
1467
+ columns: [],
1468
+ rowCount: 0,
1469
+ executionTimeMs: Date.now() - startTime,
1470
+ cached: false,
1471
+ error: `Unknown query type: ${definition.type}`
1472
+ };
975
1473
  }
976
- lines.push("");
977
- lines.push("## Dashboard Stats");
978
- lines.push("");
979
- lines.push("| Metric | Value |");
980
- lines.push("|--------|-------|");
981
- lines.push(`| Total Dashboards | ${dashboards.length} |`);
982
- lines.push(`| Published | ${publishedDashboards.length} |`);
983
- lines.push(`| Total Views | ${totalViews.toLocaleString()} |`);
984
- lines.push(`| Shared Queries | ${sharedQueries.length} |`);
985
- return {
986
- mimeType: "text/markdown",
987
- body: lines.join(`
988
- `)
989
- };
1474
+ result.executionTimeMs = Date.now() - startTime;
1475
+ result.cached = false;
1476
+ await this.cache.set(cacheKey, result, 300);
1477
+ return result;
990
1478
  }
991
- };
992
- var dashboardListMarkdownRenderer = {
993
- target: "markdown",
994
- render: async (desc) => {
995
- if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
996
- throw new Error("dashboardListMarkdownRenderer: not DashboardList");
1479
+ validateQuery(definition) {
1480
+ const errors = [];
1481
+ if (!definition.type) {
1482
+ errors.push("Query type is required");
997
1483
  }
998
- const dashboards = mockDashboards;
999
- const lines = [
1000
- "# Dashboards",
1001
- "",
1002
- "> Browse and manage analytics dashboards",
1003
- "",
1004
- "| Dashboard | Widgets | Views | Status | Last Viewed |",
1005
- "|-----------|---------|-------|--------|-------------|"
1006
- ];
1007
- for (const dashboard of dashboards) {
1008
- const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
1009
- const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "⚫";
1010
- lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
1484
+ switch (definition.type) {
1485
+ case "SQL":
1486
+ if (!definition.sql) {
1487
+ errors.push("SQL query is required for SQL type");
1488
+ }
1489
+ break;
1490
+ case "METRIC":
1491
+ if (!definition.metricIds || definition.metricIds.length === 0) {
1492
+ errors.push("Metric IDs are required for METRIC type");
1493
+ }
1494
+ break;
1495
+ case "AGGREGATION":
1496
+ if (!definition.aggregation) {
1497
+ errors.push("Aggregation definition is required for AGGREGATION type");
1498
+ } else {
1499
+ if (!definition.aggregation.source) {
1500
+ errors.push("Aggregation source is required");
1501
+ }
1502
+ if (!definition.aggregation.measures || definition.aggregation.measures.length === 0) {
1503
+ errors.push("At least one measure is required");
1504
+ }
1505
+ }
1506
+ break;
1011
1507
  }
1012
- lines.push("");
1013
- lines.push("## Quick Actions");
1014
- lines.push("");
1015
- lines.push("- **Create Dashboard** - Start with a blank canvas");
1016
- lines.push("- **Import Template** - Use a pre-built template");
1017
- lines.push("- **Clone Dashboard** - Duplicate an existing dashboard");
1508
+ return { valid: errors.length === 0, errors };
1509
+ }
1510
+ buildCacheKey(definition, params) {
1511
+ return JSON.stringify({ definition, params });
1512
+ }
1513
+ async executeAggregation(aggregation, params) {
1514
+ const columns = [
1515
+ ...aggregation.dimensions.map((d) => ({
1516
+ name: d.name,
1517
+ type: d.type === "NUMBER" ? "NUMBER" : d.type === "TIME" ? "DATE" : "STRING",
1518
+ label: d.name
1519
+ })),
1520
+ ...aggregation.measures.map((m) => ({
1521
+ name: m.name,
1522
+ type: "NUMBER",
1523
+ label: m.name,
1524
+ format: m.format
1525
+ }))
1526
+ ];
1527
+ const data = this.generateMockData(aggregation, params);
1018
1528
  return {
1019
- mimeType: "text/markdown",
1020
- body: lines.join(`
1021
- `)
1529
+ data,
1530
+ columns,
1531
+ rowCount: data.length,
1532
+ executionTimeMs: 0,
1533
+ cached: false
1022
1534
  };
1023
1535
  }
1024
- };
1025
- var queryBuilderMarkdownRenderer = {
1026
- target: "markdown",
1027
- render: async (desc) => {
1028
- if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
1029
- throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
1030
- }
1031
- const queries = mockQueries;
1032
- const lines = [
1033
- "# Query Builder",
1034
- "",
1035
- "> Create and manage data queries",
1036
- "",
1037
- "## Saved Queries",
1038
- "",
1039
- "| Query | Type | Shared | Executions |",
1040
- "|-------|------|--------|------------|"
1041
- ];
1042
- for (const query of queries) {
1043
- const sharedIcon = query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12";
1044
- lines.push(`| ${query.name} | ${query.type} | ${sharedIcon} | ${query.executionCount.toLocaleString()} |`);
1045
- }
1046
- lines.push("");
1047
- lines.push("## Query Types");
1048
- lines.push("");
1049
- lines.push("### METRIC");
1050
- lines.push("Query usage metrics from the metering system.");
1051
- lines.push("");
1052
- lines.push("### AGGREGATION");
1053
- lines.push("Build aggregations with measures and dimensions without writing SQL.");
1054
- lines.push("");
1055
- lines.push("### SQL");
1056
- lines.push("Write custom SQL queries for advanced analysis.");
1057
- lines.push("");
1058
- lines.push("## Features");
1059
- lines.push("");
1060
- lines.push("- Visual query builder");
1061
- lines.push("- Auto-complete for fields and functions");
1062
- lines.push("- Query validation and optimization");
1063
- lines.push("- Result caching");
1064
- lines.push("- Query sharing and collaboration");
1536
+ async executeMetric(metricIds, _params) {
1537
+ const data = metricIds.map((id) => ({
1538
+ metricId: id,
1539
+ value: Math.random() * 1000,
1540
+ change: (Math.random() - 0.5) * 20
1541
+ }));
1065
1542
  return {
1066
- mimeType: "text/markdown",
1067
- body: lines.join(`
1068
- `)
1543
+ data,
1544
+ columns: [
1545
+ { name: "metricId", type: "STRING" },
1546
+ { name: "value", type: "NUMBER" },
1547
+ { name: "change", type: "NUMBER" }
1548
+ ],
1549
+ rowCount: data.length,
1550
+ executionTimeMs: 0,
1551
+ cached: false
1552
+ };
1553
+ }
1554
+ async executeSql(_sql, _params) {
1555
+ return {
1556
+ data: [],
1557
+ columns: [],
1558
+ rowCount: 0,
1559
+ executionTimeMs: 0,
1560
+ cached: false,
1561
+ error: "SQL execution not implemented in demo"
1069
1562
  };
1070
1563
  }
1564
+ generateMockData(aggregation, params) {
1565
+ const data = [];
1566
+ const rowCount = 10;
1567
+ const timeDimension = aggregation.dimensions.find((d) => d.type === "TIME");
1568
+ for (let i = 0;i < rowCount; i++) {
1569
+ const row = {};
1570
+ for (const dim of aggregation.dimensions) {
1571
+ if (dim.type === "TIME") {
1572
+ const date = new Date(params.dateRange?.start ?? new Date);
1573
+ date.setDate(date.getDate() + i);
1574
+ row[dim.name] = date.toISOString().split("T")[0];
1575
+ } else {
1576
+ row[dim.name] = `${dim.name}_${i % 5}`;
1577
+ }
1578
+ }
1579
+ for (const measure of aggregation.measures) {
1580
+ const baseValue = timeDimension ? 100 + i * 10 : Math.random() * 1000;
1581
+ const noise = (Math.random() - 0.5) * 20;
1582
+ row[measure.name] = Math.round((baseValue + noise) * 100) / 100;
1583
+ }
1584
+ data.push(row);
1585
+ }
1586
+ return data;
1587
+ }
1588
+ }
1589
+ function createQueryEngine(cache) {
1590
+ return new BasicQueryEngine(cache);
1591
+ }
1592
+
1593
+ // src/ui/AnalyticsDashboard.widgets.tsx
1594
+ import {
1595
+ ComparisonView,
1596
+ TimelineView,
1597
+ VisualizationCard,
1598
+ VisualizationGrid
1599
+ } from "@contractspec/lib.design-system";
1600
+ import { jsxDEV } from "react/jsx-dev-runtime";
1601
+ "use client";
1602
+ function AnalyticsWidgetBoard({
1603
+ dashboardName,
1604
+ widgets
1605
+ }) {
1606
+ if (!widgets.length) {
1607
+ return /* @__PURE__ */ jsxDEV("div", {
1608
+ className: "rounded-lg border border-dashed p-10 text-center text-muted-foreground",
1609
+ children: [
1610
+ 'No visualization widgets configured for "',
1611
+ dashboardName,
1612
+ '".'
1613
+ ]
1614
+ }, undefined, true, undefined, this);
1615
+ }
1616
+ return /* @__PURE__ */ jsxDEV("div", {
1617
+ children: [
1618
+ /* @__PURE__ */ jsxDEV("h3", {
1619
+ className: "mb-4 font-semibold text-lg",
1620
+ children: [
1621
+ 'Widgets in "',
1622
+ dashboardName,
1623
+ '"'
1624
+ ]
1625
+ }, undefined, true, undefined, this),
1626
+ /* @__PURE__ */ jsxDEV(VisualizationGrid, {
1627
+ children: widgets.map((widget2) => /* @__PURE__ */ jsxDEV("div", {
1628
+ className: gridSpanClass(widget2.gridWidth),
1629
+ children: renderVisualizationWidget(widget2)
1630
+ }, widget2.id, false, undefined, this))
1631
+ }, undefined, false, undefined, this)
1632
+ ]
1633
+ }, undefined, true, undefined, this);
1634
+ }
1635
+ function renderVisualizationWidget(widget2) {
1636
+ const footer = /* @__PURE__ */ jsxDEV("span", {
1637
+ className: "text-muted-foreground text-xs",
1638
+ children: [
1639
+ "Position: (",
1640
+ widget2.gridX,
1641
+ ", ",
1642
+ widget2.gridY,
1643
+ ") • ",
1644
+ widget2.gridWidth,
1645
+ "x",
1646
+ widget2.gridHeight
1647
+ ]
1648
+ }, undefined, true, undefined, this);
1649
+ if (widget2.layout === "comparison") {
1650
+ return /* @__PURE__ */ jsxDEV(ComparisonView, {
1651
+ description: widget2.description,
1652
+ items: widget2.bindings.map((binding3) => ({ ...binding3, footer })),
1653
+ title: widget2.name
1654
+ }, undefined, false, undefined, this);
1655
+ }
1656
+ if (widget2.layout === "timeline") {
1657
+ return /* @__PURE__ */ jsxDEV(TimelineView, {
1658
+ description: widget2.description,
1659
+ items: widget2.bindings.map((binding3) => ({ ...binding3, footer })),
1660
+ title: widget2.name
1661
+ }, undefined, false, undefined, this);
1662
+ }
1663
+ const binding2 = widget2.bindings[0];
1664
+ if (!binding2)
1665
+ return null;
1666
+ return /* @__PURE__ */ jsxDEV(VisualizationCard, {
1667
+ data: binding2.data,
1668
+ description: widget2.description ?? binding2.description,
1669
+ footer,
1670
+ height: binding2.height,
1671
+ spec: binding2.spec,
1672
+ title: widget2.name
1673
+ }, undefined, false, undefined, this);
1674
+ }
1675
+ function gridSpanClass(gridWidth) {
1676
+ if (gridWidth >= 12)
1677
+ return "md:col-span-2 xl:col-span-3";
1678
+ if (gridWidth >= 8)
1679
+ return "xl:col-span-2";
1680
+ if (gridWidth >= 6)
1681
+ return "md:col-span-2";
1682
+ return "";
1683
+ }
1684
+
1685
+ // src/ui/AnalyticsQueriesTable.tsx
1686
+ import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
1687
+ "use client";
1688
+ var QUERY_TYPE_COLORS = {
1689
+ SQL: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
1690
+ METRIC: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",
1691
+ AGGREGATION: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",
1692
+ CUSTOM: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400"
1071
1693
  };
1694
+ function AnalyticsQueriesTable({ queries }) {
1695
+ return /* @__PURE__ */ jsxDEV2("div", {
1696
+ className: "rounded-lg border border-border",
1697
+ children: /* @__PURE__ */ jsxDEV2("table", {
1698
+ className: "w-full",
1699
+ children: [
1700
+ /* @__PURE__ */ jsxDEV2("thead", {
1701
+ className: "border-border border-b bg-muted/30",
1702
+ children: /* @__PURE__ */ jsxDEV2("tr", {
1703
+ children: [
1704
+ /* @__PURE__ */ jsxDEV2("th", {
1705
+ className: "px-4 py-3 text-left font-medium text-sm",
1706
+ children: "Query"
1707
+ }, undefined, false, undefined, this),
1708
+ /* @__PURE__ */ jsxDEV2("th", {
1709
+ className: "px-4 py-3 text-left font-medium text-sm",
1710
+ children: "Type"
1711
+ }, undefined, false, undefined, this),
1712
+ /* @__PURE__ */ jsxDEV2("th", {
1713
+ className: "px-4 py-3 text-left font-medium text-sm",
1714
+ children: "Cache TTL"
1715
+ }, undefined, false, undefined, this),
1716
+ /* @__PURE__ */ jsxDEV2("th", {
1717
+ className: "px-4 py-3 text-left font-medium text-sm",
1718
+ children: "Shared"
1719
+ }, undefined, false, undefined, this)
1720
+ ]
1721
+ }, undefined, true, undefined, this)
1722
+ }, undefined, false, undefined, this),
1723
+ /* @__PURE__ */ jsxDEV2("tbody", {
1724
+ className: "divide-y divide-border",
1725
+ children: [
1726
+ queries.map((query) => /* @__PURE__ */ jsxDEV2("tr", {
1727
+ className: "hover:bg-muted/50",
1728
+ children: [
1729
+ /* @__PURE__ */ jsxDEV2("td", {
1730
+ className: "px-4 py-3",
1731
+ children: [
1732
+ /* @__PURE__ */ jsxDEV2("div", {
1733
+ className: "font-medium",
1734
+ children: query.name
1735
+ }, undefined, false, undefined, this),
1736
+ /* @__PURE__ */ jsxDEV2("div", {
1737
+ className: "text-muted-foreground text-sm",
1738
+ children: query.description
1739
+ }, undefined, false, undefined, this)
1740
+ ]
1741
+ }, undefined, true, undefined, this),
1742
+ /* @__PURE__ */ jsxDEV2("td", {
1743
+ className: "px-4 py-3",
1744
+ children: /* @__PURE__ */ jsxDEV2("span", {
1745
+ className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${QUERY_TYPE_COLORS[query.type] ?? ""}`,
1746
+ children: query.type
1747
+ }, undefined, false, undefined, this)
1748
+ }, undefined, false, undefined, this),
1749
+ /* @__PURE__ */ jsxDEV2("td", {
1750
+ className: "px-4 py-3 text-muted-foreground text-sm",
1751
+ children: [
1752
+ query.cacheTtlSeconds,
1753
+ "s"
1754
+ ]
1755
+ }, undefined, true, undefined, this),
1756
+ /* @__PURE__ */ jsxDEV2("td", {
1757
+ className: "px-4 py-3",
1758
+ children: query.isShared ? /* @__PURE__ */ jsxDEV2("span", {
1759
+ className: "text-green-600 dark:text-green-400",
1760
+ children: "✓"
1761
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV2("span", {
1762
+ className: "text-muted-foreground",
1763
+ children: "—"
1764
+ }, undefined, false, undefined, this)
1765
+ }, undefined, false, undefined, this)
1766
+ ]
1767
+ }, query.id, true, undefined, this)),
1768
+ queries.length === 0 && /* @__PURE__ */ jsxDEV2("tr", {
1769
+ children: /* @__PURE__ */ jsxDEV2("td", {
1770
+ colSpan: 4,
1771
+ className: "px-4 py-8 text-center text-muted-foreground",
1772
+ children: "No queries saved"
1773
+ }, undefined, false, undefined, this)
1774
+ }, undefined, false, undefined, this)
1775
+ ]
1776
+ }, undefined, true, undefined, this)
1777
+ ]
1778
+ }, undefined, true, undefined, this)
1779
+ }, undefined, false, undefined, this);
1780
+ }
1781
+
1072
1782
  // src/ui/hooks/useAnalyticsData.ts
1073
- import { useCallback, useEffect, useState } from "react";
1074
1783
  import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
1784
+ import { useCallback, useEffect, useState } from "react";
1075
1785
  "use client";
1076
1786
  function useAnalyticsData(projectId = "local-project") {
1077
1787
  const { handlers } = useTemplateRuntime();
@@ -1097,7 +1807,7 @@ function useAnalyticsData(projectId = "local-project") {
1097
1807
  if (first) {
1098
1808
  setSelectedDashboard(first);
1099
1809
  const dashboardWidgets = await analytics.getWidgets(first.id);
1100
- setWidgets(dashboardWidgets);
1810
+ setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(first.id));
1101
1811
  }
1102
1812
  }
1103
1813
  } catch (err) {
@@ -1112,7 +1822,7 @@ function useAnalyticsData(projectId = "local-project") {
1112
1822
  const selectDashboard = useCallback(async (dashboard) => {
1113
1823
  setSelectedDashboard(dashboard);
1114
1824
  const dashboardWidgets = await analytics.getWidgets(dashboard.id);
1115
- setWidgets(dashboardWidgets);
1825
+ setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(dashboard.id));
1116
1826
  }, [analytics]);
1117
1827
  const stats = {
1118
1828
  totalDashboards: dashboards.length,
@@ -1134,7 +1844,6 @@ function useAnalyticsData(projectId = "local-project") {
1134
1844
  }
1135
1845
 
1136
1846
  // src/ui/AnalyticsDashboard.tsx
1137
- import { useState as useState2 } from "react";
1138
1847
  import {
1139
1848
  Button,
1140
1849
  ErrorState,
@@ -1142,33 +1851,14 @@ import {
1142
1851
  StatCard,
1143
1852
  StatCardGroup
1144
1853
  } from "@contractspec/lib.design-system";
1145
- import { jsxDEV } from "react/jsx-dev-runtime";
1854
+ import { useMemo, useState as useState2 } from "react";
1855
+ import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1146
1856
  "use client";
1147
1857
  var STATUS_COLORS = {
1148
1858
  PUBLISHED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
1149
1859
  DRAFT: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
1150
1860
  ARCHIVED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
1151
1861
  };
1152
- var WIDGET_ICONS = {
1153
- LINE_CHART: "\uD83D\uDCC8",
1154
- BAR_CHART: "\uD83D\uDCCA",
1155
- PIE_CHART: "\uD83E\uDD67",
1156
- AREA_CHART: "\uD83D\uDCC9",
1157
- SCATTER_PLOT: "⚬",
1158
- METRIC: "\uD83D\uDD22",
1159
- TABLE: "\uD83D\uDCCB",
1160
- HEATMAP: "\uD83D\uDDFA️",
1161
- FUNNEL: "⏬",
1162
- MAP: "\uD83C\uDF0D",
1163
- TEXT: "\uD83D\uDCDD",
1164
- EMBED: "\uD83D\uDD17"
1165
- };
1166
- var QUERY_TYPE_COLORS = {
1167
- SQL: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
1168
- METRIC: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",
1169
- AGGREGATION: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",
1170
- CUSTOM: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400"
1171
- };
1172
1862
  function AnalyticsDashboard() {
1173
1863
  const [activeTab, setActiveTab] = useState2("dashboards");
1174
1864
  const {
@@ -1186,33 +1876,34 @@ function AnalyticsDashboard() {
1186
1876
  { id: "dashboards", label: "Dashboards", icon: "\uD83D\uDCCA" },
1187
1877
  { id: "queries", label: "Queries", icon: "\uD83D\uDD0D" }
1188
1878
  ];
1879
+ const resolvedWidgets = useMemo(() => widgets.map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2)), [widgets]);
1189
1880
  if (loading) {
1190
- return /* @__PURE__ */ jsxDEV(LoaderBlock, {
1881
+ return /* @__PURE__ */ jsxDEV3(LoaderBlock, {
1191
1882
  label: "Loading Analytics..."
1192
1883
  }, undefined, false, undefined, this);
1193
1884
  }
1194
1885
  if (error) {
1195
- return /* @__PURE__ */ jsxDEV(ErrorState, {
1886
+ return /* @__PURE__ */ jsxDEV3(ErrorState, {
1196
1887
  title: "Failed to load Analytics",
1197
1888
  description: error.message,
1198
1889
  onRetry: refetch,
1199
1890
  retryLabel: "Retry"
1200
1891
  }, undefined, false, undefined, this);
1201
1892
  }
1202
- return /* @__PURE__ */ jsxDEV("div", {
1893
+ return /* @__PURE__ */ jsxDEV3("div", {
1203
1894
  className: "space-y-6",
1204
1895
  children: [
1205
- /* @__PURE__ */ jsxDEV("div", {
1896
+ /* @__PURE__ */ jsxDEV3("div", {
1206
1897
  className: "flex items-center justify-between",
1207
1898
  children: [
1208
- /* @__PURE__ */ jsxDEV("h2", {
1209
- className: "text-2xl font-bold",
1899
+ /* @__PURE__ */ jsxDEV3("h2", {
1900
+ className: "font-bold text-2xl",
1210
1901
  children: "Analytics Dashboard"
1211
1902
  }, undefined, false, undefined, this),
1212
- /* @__PURE__ */ jsxDEV(Button, {
1903
+ /* @__PURE__ */ jsxDEV3(Button, {
1213
1904
  onClick: () => alert("Create dashboard modal"),
1214
1905
  children: [
1215
- /* @__PURE__ */ jsxDEV("span", {
1906
+ /* @__PURE__ */ jsxDEV3("span", {
1216
1907
  className: "mr-2",
1217
1908
  children: "+"
1218
1909
  }, undefined, false, undefined, this),
@@ -1221,55 +1912,55 @@ function AnalyticsDashboard() {
1221
1912
  }, undefined, true, undefined, this)
1222
1913
  ]
1223
1914
  }, undefined, true, undefined, this),
1224
- /* @__PURE__ */ jsxDEV(StatCardGroup, {
1915
+ /* @__PURE__ */ jsxDEV3(StatCardGroup, {
1225
1916
  children: [
1226
- /* @__PURE__ */ jsxDEV(StatCard, {
1917
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1227
1918
  label: "Dashboards",
1228
1919
  value: stats.totalDashboards,
1229
1920
  hint: `${stats.publishedDashboards} published`
1230
1921
  }, undefined, false, undefined, this),
1231
- /* @__PURE__ */ jsxDEV(StatCard, {
1922
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1232
1923
  label: "Queries",
1233
1924
  value: stats.totalQueries,
1234
1925
  hint: `${stats.sharedQueries} shared`
1235
1926
  }, undefined, false, undefined, this),
1236
- /* @__PURE__ */ jsxDEV(StatCard, {
1927
+ /* @__PURE__ */ jsxDEV3(StatCard, {
1237
1928
  label: "Widgets",
1238
1929
  value: widgets.length,
1239
1930
  hint: "on current dashboard"
1240
1931
  }, undefined, false, undefined, this)
1241
1932
  ]
1242
1933
  }, undefined, true, undefined, this),
1243
- /* @__PURE__ */ jsxDEV("nav", {
1244
- className: "bg-muted flex gap-1 rounded-lg p-1",
1934
+ /* @__PURE__ */ jsxDEV3("nav", {
1935
+ className: "flex gap-1 rounded-lg bg-muted p-1",
1245
1936
  role: "tablist",
1246
- children: tabs.map((tab) => /* @__PURE__ */ jsxDEV(Button, {
1937
+ children: tabs.map((tab) => /* @__PURE__ */ jsxDEV3(Button, {
1247
1938
  type: "button",
1248
1939
  role: "tab",
1249
1940
  "aria-selected": activeTab === tab.id,
1250
1941
  onClick: () => setActiveTab(tab.id),
1251
- 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"}`,
1942
+ 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"}`,
1252
1943
  children: [
1253
- /* @__PURE__ */ jsxDEV("span", {
1944
+ /* @__PURE__ */ jsxDEV3("span", {
1254
1945
  children: tab.icon
1255
1946
  }, undefined, false, undefined, this),
1256
1947
  tab.label
1257
1948
  ]
1258
1949
  }, tab.id, true, undefined, this))
1259
1950
  }, undefined, false, undefined, this),
1260
- /* @__PURE__ */ jsxDEV("div", {
1951
+ /* @__PURE__ */ jsxDEV3("div", {
1261
1952
  className: "min-h-[400px]",
1262
1953
  role: "tabpanel",
1263
1954
  children: [
1264
- activeTab === "dashboards" && /* @__PURE__ */ jsxDEV("div", {
1955
+ activeTab === "dashboards" && /* @__PURE__ */ jsxDEV3("div", {
1265
1956
  className: "space-y-6",
1266
1957
  children: [
1267
- /* @__PURE__ */ jsxDEV("div", {
1958
+ /* @__PURE__ */ jsxDEV3("div", {
1268
1959
  className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1269
1960
  children: [
1270
- dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV("div", {
1961
+ dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV3("div", {
1271
1962
  onClick: () => selectDashboard(dashboard),
1272
- 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"}`,
1963
+ 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"}`,
1273
1964
  role: "button",
1274
1965
  tabIndex: 0,
1275
1966
  onKeyDown: (e) => {
@@ -1277,33 +1968,33 @@ function AnalyticsDashboard() {
1277
1968
  selectDashboard(dashboard);
1278
1969
  },
1279
1970
  children: [
1280
- /* @__PURE__ */ jsxDEV("div", {
1971
+ /* @__PURE__ */ jsxDEV3("div", {
1281
1972
  className: "mb-2 flex items-center justify-between",
1282
1973
  children: [
1283
- /* @__PURE__ */ jsxDEV("h3", {
1974
+ /* @__PURE__ */ jsxDEV3("h3", {
1284
1975
  className: "font-medium",
1285
1976
  children: dashboard.name
1286
1977
  }, undefined, false, undefined, this),
1287
- /* @__PURE__ */ jsxDEV("span", {
1288
- className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_COLORS[dashboard.status] ?? ""}`,
1978
+ /* @__PURE__ */ jsxDEV3("span", {
1979
+ className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[dashboard.status] ?? ""}`,
1289
1980
  children: dashboard.status
1290
1981
  }, undefined, false, undefined, this)
1291
1982
  ]
1292
1983
  }, undefined, true, undefined, this),
1293
- /* @__PURE__ */ jsxDEV("p", {
1294
- className: "text-muted-foreground mb-3 text-sm",
1984
+ /* @__PURE__ */ jsxDEV3("p", {
1985
+ className: "mb-3 text-muted-foreground text-sm",
1295
1986
  children: dashboard.description
1296
1987
  }, undefined, false, undefined, this),
1297
- /* @__PURE__ */ jsxDEV("div", {
1298
- className: "text-muted-foreground flex items-center justify-between text-xs",
1988
+ /* @__PURE__ */ jsxDEV3("div", {
1989
+ className: "flex items-center justify-between text-muted-foreground text-xs",
1299
1990
  children: [
1300
- /* @__PURE__ */ jsxDEV("span", {
1991
+ /* @__PURE__ */ jsxDEV3("span", {
1301
1992
  children: [
1302
1993
  "/",
1303
1994
  dashboard.slug
1304
1995
  ]
1305
1996
  }, undefined, true, undefined, this),
1306
- dashboard.isPublic && /* @__PURE__ */ jsxDEV("span", {
1997
+ dashboard.isPublic && /* @__PURE__ */ jsxDEV3("span", {
1307
1998
  className: "text-green-600 dark:text-green-400",
1308
1999
  children: "\uD83C\uDF10 Public"
1309
2000
  }, undefined, false, undefined, this)
@@ -1311,149 +2002,20 @@ function AnalyticsDashboard() {
1311
2002
  }, undefined, true, undefined, this)
1312
2003
  ]
1313
2004
  }, dashboard.id, true, undefined, this)),
1314
- dashboards.length === 0 && /* @__PURE__ */ jsxDEV("div", {
1315
- className: "text-muted-foreground col-span-full flex h-64 items-center justify-center",
2005
+ dashboards.length === 0 && /* @__PURE__ */ jsxDEV3("div", {
2006
+ className: "col-span-full flex h-64 items-center justify-center text-muted-foreground",
1316
2007
  children: "No dashboards created yet"
1317
2008
  }, undefined, false, undefined, this)
1318
2009
  ]
1319
2010
  }, undefined, true, undefined, this),
1320
- selectedDashboard && widgets.length > 0 && /* @__PURE__ */ jsxDEV("div", {
1321
- children: [
1322
- /* @__PURE__ */ jsxDEV("h3", {
1323
- className: "mb-4 text-lg font-semibold",
1324
- children: [
1325
- 'Widgets in "',
1326
- selectedDashboard.name,
1327
- '"'
1328
- ]
1329
- }, undefined, true, undefined, this),
1330
- /* @__PURE__ */ jsxDEV("div", {
1331
- className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1332
- children: widgets.map((widget) => /* @__PURE__ */ jsxDEV("div", {
1333
- className: "border-border bg-card rounded-lg border p-4",
1334
- children: [
1335
- /* @__PURE__ */ jsxDEV("div", {
1336
- className: "mb-2 flex items-center gap-2",
1337
- children: [
1338
- /* @__PURE__ */ jsxDEV("span", {
1339
- className: "text-xl",
1340
- children: WIDGET_ICONS[widget.type] ?? "\uD83D\uDCCA"
1341
- }, undefined, false, undefined, this),
1342
- /* @__PURE__ */ jsxDEV("span", {
1343
- className: "font-medium",
1344
- children: widget.name
1345
- }, undefined, false, undefined, this)
1346
- ]
1347
- }, undefined, true, undefined, this),
1348
- /* @__PURE__ */ jsxDEV("div", {
1349
- className: "text-muted-foreground text-sm",
1350
- children: widget.type.replace(/_/g, " ")
1351
- }, undefined, false, undefined, this),
1352
- /* @__PURE__ */ jsxDEV("div", {
1353
- className: "text-muted-foreground mt-2 text-xs",
1354
- children: [
1355
- "Position: (",
1356
- widget.gridX,
1357
- ", ",
1358
- widget.gridY,
1359
- ") •",
1360
- " ",
1361
- widget.gridWidth,
1362
- "x",
1363
- widget.gridHeight
1364
- ]
1365
- }, undefined, true, undefined, this)
1366
- ]
1367
- }, widget.id, true, undefined, this))
1368
- }, undefined, false, undefined, this)
1369
- ]
1370
- }, undefined, true, undefined, this)
2011
+ selectedDashboard ? /* @__PURE__ */ jsxDEV3(AnalyticsWidgetBoard, {
2012
+ dashboardName: selectedDashboard.name,
2013
+ widgets: resolvedWidgets
2014
+ }, undefined, false, undefined, this) : null
1371
2015
  ]
1372
2016
  }, undefined, true, undefined, this),
1373
- activeTab === "queries" && /* @__PURE__ */ jsxDEV("div", {
1374
- className: "border-border rounded-lg border",
1375
- children: /* @__PURE__ */ jsxDEV("table", {
1376
- className: "w-full",
1377
- children: [
1378
- /* @__PURE__ */ jsxDEV("thead", {
1379
- className: "border-border bg-muted/30 border-b",
1380
- children: /* @__PURE__ */ jsxDEV("tr", {
1381
- children: [
1382
- /* @__PURE__ */ jsxDEV("th", {
1383
- className: "px-4 py-3 text-left text-sm font-medium",
1384
- children: "Query"
1385
- }, undefined, false, undefined, this),
1386
- /* @__PURE__ */ jsxDEV("th", {
1387
- className: "px-4 py-3 text-left text-sm font-medium",
1388
- children: "Type"
1389
- }, undefined, false, undefined, this),
1390
- /* @__PURE__ */ jsxDEV("th", {
1391
- className: "px-4 py-3 text-left text-sm font-medium",
1392
- children: "Cache TTL"
1393
- }, undefined, false, undefined, this),
1394
- /* @__PURE__ */ jsxDEV("th", {
1395
- className: "px-4 py-3 text-left text-sm font-medium",
1396
- children: "Shared"
1397
- }, undefined, false, undefined, this)
1398
- ]
1399
- }, undefined, true, undefined, this)
1400
- }, undefined, false, undefined, this),
1401
- /* @__PURE__ */ jsxDEV("tbody", {
1402
- className: "divide-border divide-y",
1403
- children: [
1404
- queries.map((query) => /* @__PURE__ */ jsxDEV("tr", {
1405
- className: "hover:bg-muted/50",
1406
- children: [
1407
- /* @__PURE__ */ jsxDEV("td", {
1408
- className: "px-4 py-3",
1409
- children: [
1410
- /* @__PURE__ */ jsxDEV("div", {
1411
- className: "font-medium",
1412
- children: query.name
1413
- }, undefined, false, undefined, this),
1414
- /* @__PURE__ */ jsxDEV("div", {
1415
- className: "text-muted-foreground text-sm",
1416
- children: query.description
1417
- }, undefined, false, undefined, this)
1418
- ]
1419
- }, undefined, true, undefined, this),
1420
- /* @__PURE__ */ jsxDEV("td", {
1421
- className: "px-4 py-3",
1422
- children: /* @__PURE__ */ jsxDEV("span", {
1423
- className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${QUERY_TYPE_COLORS[query.type] ?? ""}`,
1424
- children: query.type
1425
- }, undefined, false, undefined, this)
1426
- }, undefined, false, undefined, this),
1427
- /* @__PURE__ */ jsxDEV("td", {
1428
- className: "text-muted-foreground px-4 py-3 text-sm",
1429
- children: [
1430
- query.cacheTtlSeconds,
1431
- "s"
1432
- ]
1433
- }, undefined, true, undefined, this),
1434
- /* @__PURE__ */ jsxDEV("td", {
1435
- className: "px-4 py-3",
1436
- children: query.isShared ? /* @__PURE__ */ jsxDEV("span", {
1437
- className: "text-green-600 dark:text-green-400",
1438
- children: "✓"
1439
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("span", {
1440
- className: "text-muted-foreground",
1441
- children: "—"
1442
- }, undefined, false, undefined, this)
1443
- }, undefined, false, undefined, this)
1444
- ]
1445
- }, query.id, true, undefined, this)),
1446
- queries.length === 0 && /* @__PURE__ */ jsxDEV("tr", {
1447
- children: /* @__PURE__ */ jsxDEV("td", {
1448
- colSpan: 4,
1449
- className: "text-muted-foreground px-4 py-8 text-center",
1450
- children: "No queries saved"
1451
- }, undefined, false, undefined, this)
1452
- }, undefined, false, undefined, this)
1453
- ]
1454
- }, undefined, true, undefined, this)
1455
- ]
1456
- }, undefined, true, undefined, this)
2017
+ activeTab === "queries" && /* @__PURE__ */ jsxDEV3(AnalyticsQueriesTable, {
2018
+ queries
1457
2019
  }, undefined, false, undefined, this)
1458
2020
  ]
1459
2021
  }, undefined, true, undefined, this)
@@ -1463,222 +2025,204 @@ function AnalyticsDashboard() {
1463
2025
 
1464
2026
  // src/ui/hooks/index.ts
1465
2027
  "use client";
1466
- // src/query-engine/index.ts
1467
- class InMemoryQueryCache {
1468
- cache = new Map;
1469
- async get(key) {
1470
- const entry = this.cache.get(key);
1471
- if (!entry)
1472
- return null;
1473
- if (entry.expiresAt < new Date) {
1474
- this.cache.delete(key);
1475
- return null;
1476
- }
1477
- return { ...entry.result, cached: true, cachedAt: entry.expiresAt };
1478
- }
1479
- async set(key, result, ttlSeconds) {
1480
- const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
1481
- this.cache.set(key, { result, expiresAt });
2028
+
2029
+ // src/ui/renderers/analytics.markdown.ts
2030
+ var mockDashboards = [
2031
+ {
2032
+ id: "dash-1",
2033
+ name: "Sales Overview",
2034
+ slug: "sales-overview",
2035
+ status: "PUBLISHED",
2036
+ widgetCount: 11,
2037
+ viewCount: 1250,
2038
+ lastViewedAt: "2026-03-18T12:00:00Z"
2039
+ },
2040
+ {
2041
+ id: "dash-2",
2042
+ name: "User Engagement",
2043
+ slug: "user-engagement",
2044
+ status: "PUBLISHED",
2045
+ widgetCount: 8,
2046
+ viewCount: 890,
2047
+ lastViewedAt: "2026-03-18T10:00:00Z"
1482
2048
  }
1483
- async invalidate(pattern) {
1484
- const regex = new RegExp(pattern);
1485
- for (const key of this.cache.keys()) {
1486
- if (regex.test(key)) {
1487
- this.cache.delete(key);
1488
- }
1489
- }
2049
+ ];
2050
+ var mockQueries = [
2051
+ {
2052
+ id: "q-1",
2053
+ name: "Monthly Revenue",
2054
+ type: "AGGREGATION",
2055
+ isShared: true,
2056
+ executionCount: 1500
2057
+ },
2058
+ {
2059
+ id: "q-2",
2060
+ name: "User Growth",
2061
+ type: "METRIC",
2062
+ isShared: true,
2063
+ executionCount: 890
2064
+ },
2065
+ {
2066
+ id: "q-3",
2067
+ name: "Product Sales",
2068
+ type: "SQL",
2069
+ isShared: false,
2070
+ executionCount: 340
2071
+ },
2072
+ {
2073
+ id: "q-4",
2074
+ name: "Conversion Funnel",
2075
+ type: "AGGREGATION",
2076
+ isShared: true,
2077
+ executionCount: 450
1490
2078
  }
2079
+ ];
2080
+ function dashboardWidgets(dashboardId) {
2081
+ return createExampleWidgets(dashboardId).map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2));
1491
2082
  }
1492
-
1493
- class BasicQueryEngine {
1494
- cache;
1495
- constructor(cache) {
1496
- this.cache = cache ?? new InMemoryQueryCache;
1497
- }
1498
- async execute(definition, params) {
1499
- const startTime = Date.now();
1500
- const validation = this.validateQuery(definition);
1501
- if (!validation.valid) {
2083
+ var analyticsDashboardMarkdownRenderer = {
2084
+ target: "markdown",
2085
+ render: async (desc) => {
2086
+ if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
2087
+ throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
2088
+ }
2089
+ const dashboard = mockDashboards[0];
2090
+ if (!dashboard) {
1502
2091
  return {
1503
- data: [],
1504
- columns: [],
1505
- rowCount: 0,
1506
- executionTimeMs: Date.now() - startTime,
1507
- cached: false,
1508
- error: validation.errors.join(", ")
2092
+ mimeType: "text/markdown",
2093
+ body: `# No Dashboards
2094
+
2095
+ No dashboards available.`
1509
2096
  };
1510
2097
  }
1511
- const cacheKey = this.buildCacheKey(definition, params);
1512
- const cachedResult = await this.cache.get(cacheKey);
1513
- if (cachedResult) {
1514
- return cachedResult;
1515
- }
1516
- let result;
1517
- switch (definition.type) {
1518
- case "AGGREGATION":
1519
- if (!definition.aggregation) {
1520
- throw new Error("Aggregation definition is missing");
1521
- }
1522
- result = await this.executeAggregation(definition.aggregation, params);
1523
- break;
1524
- case "METRIC":
1525
- if (!definition.metricIds) {
1526
- throw new Error("Metric IDs are missing");
1527
- }
1528
- result = await this.executeMetric(definition.metricIds, params);
1529
- break;
1530
- case "SQL":
1531
- if (!definition.sql) {
1532
- throw new Error("SQL query is missing");
1533
- }
1534
- result = await this.executeSql(definition.sql, params);
1535
- break;
1536
- default:
1537
- result = {
1538
- data: [],
1539
- columns: [],
1540
- rowCount: 0,
1541
- executionTimeMs: Date.now() - startTime,
1542
- cached: false,
1543
- error: `Unknown query type: ${definition.type}`
1544
- };
1545
- }
1546
- result.executionTimeMs = Date.now() - startTime;
1547
- result.cached = false;
1548
- await this.cache.set(cacheKey, result, 300);
1549
- return result;
1550
- }
1551
- validateQuery(definition) {
1552
- const errors = [];
1553
- if (!definition.type) {
1554
- errors.push("Query type is required");
2098
+ const widgets = dashboardWidgets(dashboard.id);
2099
+ const metricWidgets = widgets.filter((widget2) => widget2.bindings[0]?.spec.visualization.kind === "metric");
2100
+ const lines = [
2101
+ `# ${dashboard.name}`,
2102
+ "",
2103
+ "> Contract-backed analytics dashboard overview.",
2104
+ "",
2105
+ "## Key Metrics",
2106
+ ""
2107
+ ];
2108
+ for (const widget2 of metricWidgets) {
2109
+ const binding2 = widget2.bindings[0];
2110
+ if (!binding2)
2111
+ continue;
2112
+ lines.push(`- **${widget2.name}** via \`${binding2.spec.meta.key}\``);
1555
2113
  }
1556
- switch (definition.type) {
1557
- case "SQL":
1558
- if (!definition.sql) {
1559
- errors.push("SQL query is required for SQL type");
1560
- }
1561
- break;
1562
- case "METRIC":
1563
- if (!definition.metricIds || definition.metricIds.length === 0) {
1564
- errors.push("Metric IDs are required for METRIC type");
1565
- }
1566
- break;
1567
- case "AGGREGATION":
1568
- if (!definition.aggregation) {
1569
- errors.push("Aggregation definition is required for AGGREGATION type");
1570
- } else {
1571
- if (!definition.aggregation.source) {
1572
- errors.push("Aggregation source is required");
1573
- }
1574
- if (!definition.aggregation.measures || definition.aggregation.measures.length === 0) {
1575
- errors.push("At least one measure is required");
1576
- }
1577
- }
1578
- break;
2114
+ lines.push("");
2115
+ lines.push("## Visual Blocks");
2116
+ lines.push("");
2117
+ for (const widget2 of widgets) {
2118
+ const kinds = widget2.bindings.map((binding2) => binding2.spec.visualization.kind).join(", ");
2119
+ lines.push(`- **${widget2.name}** (${widget2.layout}) → ${kinds}`);
1579
2120
  }
1580
- return { valid: errors.length === 0, errors };
1581
- }
1582
- buildCacheKey(definition, params) {
1583
- return JSON.stringify({ definition, params });
1584
- }
1585
- async executeAggregation(aggregation, params) {
1586
- const columns = [
1587
- ...aggregation.dimensions.map((d) => ({
1588
- name: d.name,
1589
- type: d.type === "NUMBER" ? "NUMBER" : d.type === "TIME" ? "DATE" : "STRING",
1590
- label: d.name
1591
- })),
1592
- ...aggregation.measures.map((m) => ({
1593
- name: m.name,
1594
- type: "NUMBER",
1595
- label: m.name,
1596
- format: m.format
1597
- }))
1598
- ];
1599
- const data = this.generateMockData(aggregation, params);
2121
+ lines.push("");
2122
+ lines.push("## Dashboard Stats");
2123
+ lines.push("");
2124
+ lines.push("| Metric | Value |");
2125
+ lines.push("|--------|-------|");
2126
+ lines.push(`| Total Dashboards | ${mockDashboards.length} |`);
2127
+ lines.push(`| Published | ${mockDashboards.filter((item) => item.status === "PUBLISHED").length} |`);
2128
+ lines.push(`| Shared Queries | ${mockQueries.filter((query) => query.isShared).length} |`);
1600
2129
  return {
1601
- data,
1602
- columns,
1603
- rowCount: data.length,
1604
- executionTimeMs: 0,
1605
- cached: false
2130
+ mimeType: "text/markdown",
2131
+ body: lines.join(`
2132
+ `)
1606
2133
  };
1607
2134
  }
1608
- async executeMetric(metricIds, _params) {
1609
- const data = metricIds.map((id) => ({
1610
- metricId: id,
1611
- value: Math.random() * 1000,
1612
- change: (Math.random() - 0.5) * 20
1613
- }));
2135
+ };
2136
+ var dashboardListMarkdownRenderer = {
2137
+ target: "markdown",
2138
+ render: async (desc) => {
2139
+ if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
2140
+ throw new Error("dashboardListMarkdownRenderer: not DashboardList");
2141
+ }
2142
+ const lines = [
2143
+ "# Dashboards",
2144
+ "",
2145
+ "> Browse and manage analytics dashboards",
2146
+ "",
2147
+ "| Dashboard | Widgets | Views | Status | Last Viewed |",
2148
+ "|-----------|---------|-------|--------|-------------|"
2149
+ ];
2150
+ for (const dashboard of mockDashboards) {
2151
+ const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
2152
+ const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "⚫";
2153
+ lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
2154
+ }
1614
2155
  return {
1615
- data,
1616
- columns: [
1617
- { name: "metricId", type: "STRING" },
1618
- { name: "value", type: "NUMBER" },
1619
- { name: "change", type: "NUMBER" }
1620
- ],
1621
- rowCount: data.length,
1622
- executionTimeMs: 0,
1623
- cached: false
2156
+ mimeType: "text/markdown",
2157
+ body: lines.join(`
2158
+ `)
1624
2159
  };
1625
2160
  }
1626
- async executeSql(_sql, _params) {
2161
+ };
2162
+ var queryBuilderMarkdownRenderer = {
2163
+ target: "markdown",
2164
+ render: async (desc) => {
2165
+ if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
2166
+ throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
2167
+ }
2168
+ const lines = [
2169
+ "# Query Builder",
2170
+ "",
2171
+ "> Create and manage reusable data queries.",
2172
+ "",
2173
+ "| Query | Type | Shared | Executions |",
2174
+ "|-------|------|--------|------------|"
2175
+ ];
2176
+ for (const query of mockQueries) {
2177
+ lines.push(`| ${query.name} | ${query.type} | ${query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12"} | ${query.executionCount.toLocaleString()} |`);
2178
+ }
2179
+ lines.push("");
2180
+ lines.push("## Visualization Contracts");
2181
+ lines.push("");
2182
+ lines.push("Widgets reference `VisualizationSpec` contracts instead of rendering ad-hoc widget types.");
1627
2183
  return {
1628
- data: [],
1629
- columns: [],
1630
- rowCount: 0,
1631
- executionTimeMs: 0,
1632
- cached: false,
1633
- error: "SQL execution not implemented in demo"
2184
+ mimeType: "text/markdown",
2185
+ body: lines.join(`
2186
+ `)
1634
2187
  };
1635
2188
  }
1636
- generateMockData(aggregation, params) {
1637
- const data = [];
1638
- const rowCount = 10;
1639
- const timeDimension = aggregation.dimensions.find((d) => d.type === "TIME");
1640
- for (let i = 0;i < rowCount; i++) {
1641
- const row = {};
1642
- for (const dim of aggregation.dimensions) {
1643
- if (dim.type === "TIME") {
1644
- const date = new Date(params.dateRange?.start ?? new Date);
1645
- date.setDate(date.getDate() + i);
1646
- row[dim.name] = date.toISOString().split("T")[0];
1647
- } else {
1648
- row[dim.name] = `${dim.name}_${i % 5}`;
1649
- }
1650
- }
1651
- for (const measure of aggregation.measures) {
1652
- const baseValue = timeDimension ? 100 + i * 10 : Math.random() * 1000;
1653
- const noise = (Math.random() - 0.5) * 20;
1654
- row[measure.name] = Math.round((baseValue + noise) * 100) / 100;
1655
- }
1656
- data.push(row);
1657
- }
1658
- return data;
1659
- }
1660
- }
1661
- function createQueryEngine(cache) {
1662
- return new BasicQueryEngine(cache);
1663
- }
2189
+ };
1664
2190
  export {
2191
+ visualizationRefKey,
1665
2192
  useAnalyticsData,
2193
+ resolveAnalyticsWidget,
2194
+ refOf,
1666
2195
  queryBuilderMarkdownRenderer,
1667
2196
  dashboardListMarkdownRenderer,
1668
2197
  createQueryEngine,
1669
2198
  createPosthogQueryEngine,
2199
+ createExampleWidgets,
1670
2200
  createAnalyticsHandlers,
1671
2201
  analyticsDashboardMarkdownRenderer,
2202
+ RevenueTrendVisualization,
2203
+ RevenueMetricVisualization,
2204
+ RetentionAreaVisualization,
2205
+ RegionalRevenueVisualization,
1672
2206
  QueryTypeEnum,
1673
2207
  QueryResultModel,
1674
2208
  QueryModel,
1675
2209
  PosthogQueryEngine,
2210
+ PipelineScatterVisualization,
1676
2211
  InMemoryQueryCache,
1677
2212
  ExecuteQueryInputModel,
1678
2213
  ExecuteQueryContract,
2214
+ EngagementHeatmapVisualization,
1679
2215
  CreateQueryInputModel,
1680
2216
  CreateQueryContract,
2217
+ ConversionFunnelVisualization,
2218
+ ChannelMixVisualization,
1681
2219
  BasicQueryEngine,
2220
+ AnalyticsVisualizationSpecs,
2221
+ AnalyticsVisualizationSpecMap,
2222
+ AnalyticsVisualizationSampleData,
2223
+ AnalyticsVisualizationRegistry,
2224
+ AnalyticsVisualizationRefs,
1682
2225
  AnalyticsDashboardFeature,
1683
- AnalyticsDashboard
2226
+ AnalyticsDashboard,
2227
+ AccountCoverageGeoVisualization
1684
2228
  };