@contractspec/example.analytics-dashboard 3.9.9 → 3.9.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/browser/dashboard/dashboard.enum.js +1 -34
  2. package/dist/browser/dashboard/dashboard.operation.js +1 -289
  3. package/dist/browser/dashboard/dashboard.presentation.js +1 -200
  4. package/dist/browser/dashboard/dashboard.schema.js +1 -126
  5. package/dist/browser/dashboard/dashboard.test-spec.js +1 -213
  6. package/dist/browser/dashboard/index.js +1 -299
  7. package/dist/browser/dashboard.feature.js +1 -683
  8. package/dist/browser/datasource/posthog-datasource.js +4 -289
  9. package/dist/browser/docs/analytics-dashboard.docblock.js +5 -49
  10. package/dist/browser/docs/index.js +5 -49
  11. package/dist/browser/events.js +1 -81
  12. package/dist/browser/example.js +1 -42
  13. package/dist/browser/handlers/analytics.handlers.js +4 -278
  14. package/dist/browser/handlers/index.js +7 -571
  15. package/dist/browser/handlers/query.handlers.js +4 -294
  16. package/dist/browser/index.js +12 -2317
  17. package/dist/browser/query/index.js +1 -159
  18. package/dist/browser/query/query.enum.js +1 -11
  19. package/dist/browser/query/query.operation.js +1 -154
  20. package/dist/browser/query/query.presentation.js +1 -122
  21. package/dist/browser/query/query.schema.js +1 -70
  22. package/dist/browser/query/query.test-spec.js +1 -113
  23. package/dist/browser/query-engine/index.js +4 -491
  24. package/dist/browser/seeders/index.js +2 -20
  25. package/dist/browser/ui/AnalyticsDashboard.js +1 -1115
  26. package/dist/browser/ui/AnalyticsDashboard.widgets.js +1 -94
  27. package/dist/browser/ui/AnalyticsQueriesTable.js +1 -188
  28. package/dist/browser/ui/hooks/index.js +1 -660
  29. package/dist/browser/ui/hooks/useAnalyticsData.js +1 -657
  30. package/dist/browser/ui/index.js +5 -1283
  31. package/dist/browser/ui/renderers/analytics.markdown.js +5 -756
  32. package/dist/browser/ui/renderers/index.js +5 -756
  33. package/dist/browser/visualizations/catalog.js +1 -457
  34. package/dist/browser/visualizations/index.js +1 -611
  35. package/dist/browser/visualizations/specs.breakdown.js +1 -140
  36. package/dist/browser/visualizations/specs.performance.js +1 -198
  37. package/dist/browser/visualizations/widgets.js +1 -595
  38. package/dist/dashboard/dashboard.enum.js +1 -34
  39. package/dist/dashboard/dashboard.operation.js +1 -289
  40. package/dist/dashboard/dashboard.presentation.js +1 -200
  41. package/dist/dashboard/dashboard.schema.js +1 -126
  42. package/dist/dashboard/dashboard.test-spec.js +1 -213
  43. package/dist/dashboard/index.js +1 -299
  44. package/dist/dashboard.feature.js +1 -683
  45. package/dist/datasource/posthog-datasource.js +4 -289
  46. package/dist/docs/analytics-dashboard.docblock.js +5 -49
  47. package/dist/docs/index.js +5 -49
  48. package/dist/events.js +1 -81
  49. package/dist/example.js +1 -42
  50. package/dist/handlers/analytics.handlers.js +4 -278
  51. package/dist/handlers/index.js +7 -571
  52. package/dist/handlers/query.handlers.js +4 -294
  53. package/dist/index.js +12 -2317
  54. package/dist/node/dashboard/dashboard.enum.js +1 -34
  55. package/dist/node/dashboard/dashboard.operation.js +1 -289
  56. package/dist/node/dashboard/dashboard.presentation.js +1 -200
  57. package/dist/node/dashboard/dashboard.schema.js +1 -126
  58. package/dist/node/dashboard/dashboard.test-spec.js +1 -213
  59. package/dist/node/dashboard/index.js +1 -299
  60. package/dist/node/dashboard.feature.js +1 -683
  61. package/dist/node/datasource/posthog-datasource.js +4 -289
  62. package/dist/node/docs/analytics-dashboard.docblock.js +5 -49
  63. package/dist/node/docs/index.js +5 -49
  64. package/dist/node/events.js +1 -81
  65. package/dist/node/example.js +1 -42
  66. package/dist/node/handlers/analytics.handlers.js +4 -278
  67. package/dist/node/handlers/index.js +7 -571
  68. package/dist/node/handlers/query.handlers.js +4 -294
  69. package/dist/node/index.js +12 -2317
  70. package/dist/node/query/index.js +1 -159
  71. package/dist/node/query/query.enum.js +1 -11
  72. package/dist/node/query/query.operation.js +1 -154
  73. package/dist/node/query/query.presentation.js +1 -122
  74. package/dist/node/query/query.schema.js +1 -70
  75. package/dist/node/query/query.test-spec.js +1 -113
  76. package/dist/node/query-engine/index.js +4 -491
  77. package/dist/node/seeders/index.js +2 -20
  78. package/dist/node/ui/AnalyticsDashboard.js +1 -1115
  79. package/dist/node/ui/AnalyticsDashboard.widgets.js +1 -94
  80. package/dist/node/ui/AnalyticsQueriesTable.js +1 -188
  81. package/dist/node/ui/hooks/index.js +1 -660
  82. package/dist/node/ui/hooks/useAnalyticsData.js +1 -657
  83. package/dist/node/ui/index.js +5 -1283
  84. package/dist/node/ui/renderers/analytics.markdown.js +5 -756
  85. package/dist/node/ui/renderers/index.js +5 -756
  86. package/dist/node/visualizations/catalog.js +1 -457
  87. package/dist/node/visualizations/index.js +1 -611
  88. package/dist/node/visualizations/specs.breakdown.js +1 -140
  89. package/dist/node/visualizations/specs.performance.js +1 -198
  90. package/dist/node/visualizations/widgets.js +1 -595
  91. package/dist/query/index.js +1 -159
  92. package/dist/query/query.enum.js +1 -11
  93. package/dist/query/query.operation.js +1 -154
  94. package/dist/query/query.presentation.js +1 -122
  95. package/dist/query/query.schema.js +1 -70
  96. package/dist/query/query.test-spec.js +1 -113
  97. package/dist/query-engine/index.js +4 -491
  98. package/dist/seeders/index.js +2 -20
  99. package/dist/ui/AnalyticsDashboard.js +1 -1115
  100. package/dist/ui/AnalyticsDashboard.widgets.js +1 -94
  101. package/dist/ui/AnalyticsQueriesTable.js +1 -188
  102. package/dist/ui/hooks/index.js +1 -660
  103. package/dist/ui/hooks/useAnalyticsData.js +1 -657
  104. package/dist/ui/index.js +5 -1283
  105. package/dist/ui/renderers/analytics.markdown.js +5 -756
  106. package/dist/ui/renderers/index.js +5 -756
  107. package/dist/visualizations/catalog.js +1 -457
  108. package/dist/visualizations/index.js +1 -611
  109. package/dist/visualizations/specs.breakdown.js +1 -140
  110. package/dist/visualizations/specs.performance.js +1 -198
  111. package/dist/visualizations/widgets.js +1 -595
  112. package/package.json +10 -10
@@ -1,1284 +1,6 @@
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
- });
1
+ import{defineVisualization as l}from"@contractspec/lib.contracts-spec/visualizations";var z={key:"analytics.query.execute",version:"1.0.0"},x={version:"1.0.0",domain:"analytics",stability:"experimental",owners:["@example.analytics-dashboard"],tags:["analytics","dashboard","visualization"]},C=l({meta:{...x,key:"analytics.visualization.channel-mix",title:"Channel Mix",description:"Session distribution across acquisition channels.",goal:"Explain which channels currently drive the largest share of traffic.",context:"Marketing attribution dashboard."},source:{primary:z,resultPath:"data"},visualization:{kind:"pie",nameDimension:"channel",valueMeasure:"sessions",dimensions:[{key:"channel",label:"Channel",dataPath:"channel",type:"category"}],measures:[{key:"sessions",label:"Sessions",dataPath:"sessions"}],table:{caption:"Sessions by acquisition channel."}}}),U=l({meta:{...x,key:"analytics.visualization.engagement-heatmap",title:"Engagement Heatmap",description:"Average engagement score by weekday and time band.",goal:"Reveal the highest-engagement time windows for product activity.",context:"Usage analytics dashboard."},source:{primary:z,resultPath:"data"},visualization:{kind:"heatmap",xDimension:"timeBand",yDimension:"weekday",valueMeasure:"engagementScore",dimensions:[{key:"timeBand",label:"Time Band",dataPath:"timeBand",type:"category"},{key:"weekday",label:"Weekday",dataPath:"weekday",type:"category"}],measures:[{key:"engagementScore",label:"Engagement",dataPath:"engagementScore"}],table:{caption:"Engagement score by weekday and time band."}}}),A=l({meta:{...x,key:"analytics.visualization.conversion-funnel",title:"Conversion Funnel",description:"Progression through the main acquisition funnel.",goal:"Show where the product is losing the largest share of prospects.",context:"Growth dashboard."},source:{primary:z,resultPath:"data"},visualization:{kind:"funnel",nameDimension:"stage",valueMeasure:"users",sort:"descending",dimensions:[{key:"stage",label:"Stage",dataPath:"stage",type:"category"}],measures:[{key:"users",label:"Users",dataPath:"users"}],table:{caption:"Users per conversion stage."}}}),t=l({meta:{...x,key:"analytics.visualization.account-coverage-geo",title:"Account Coverage",description:"High-value accounts plotted on a slippy-map surface.",goal:"Locate where active commercial concentration is strongest.",context:"Territory coverage dashboard."},source:{primary:z,resultPath:"data"},visualization:{kind:"geo",mode:"slippy-map",variant:"scatter",nameDimension:"city",latitudeDimension:"latitude",longitudeDimension:"longitude",valueMeasure:"accounts",dimensions:[{key:"city",label:"City",dataPath:"city",type:"category"},{key:"latitude",label:"Latitude",dataPath:"latitude",type:"latitude"},{key:"longitude",label:"Longitude",dataPath:"longitude",type:"longitude"}],measures:[{key:"accounts",label:"Accounts",dataPath:"accounts"}],table:{caption:"Account concentration by city."}}});import{defineVisualization as u}from"@contractspec/lib.contracts-spec/visualizations";var q={key:"analytics.query.execute",version:"1.0.0"},T={version:"1.0.0",domain:"analytics",stability:"experimental",owners:["@example.analytics-dashboard"],tags:["analytics","dashboard","visualization"]},f=u({meta:{...T,key:"analytics.visualization.revenue-metric",title:"Revenue Snapshot",description:"Current recurring revenue with prior-period comparison.",goal:"Highlight the headline commercial metric for the dashboard.",context:"Executive revenue overview."},source:{primary:q,resultPath:"data"},visualization:{kind:"metric",measure:"totalRevenue",comparisonMeasure:"priorRevenue",dimensions:[{key:"period",label:"Period",dataPath:"period",type:"time"}],measures:[{key:"totalRevenue",label:"Revenue",dataPath:"totalRevenue",format:"currency"},{key:"priorRevenue",label:"Prior Revenue",dataPath:"priorRevenue",format:"currency"}],sparkline:{dimension:"period",measure:"totalRevenue"},table:{caption:"Revenue trend and prior period values."}}}),M=u({meta:{...T,key:"analytics.visualization.revenue-trend",title:"Revenue Trend",description:"Monthly revenue progression for the current quarter.",goal:"Track whether revenue growth is accelerating or stalling.",context:"Quarterly commercial dashboard."},source:{primary:q,resultPath:"data"},visualization:{kind:"cartesian",variant:"line",xDimension:"date",yMeasures:["revenue"],dimensions:[{key:"date",label:"Month",dataPath:"date",type:"time"}],measures:[{key:"revenue",label:"Revenue",dataPath:"revenue",format:"currency",color:"#0f766e"}],thresholds:[{key:"target",value:140000,label:"Target",color:"#dc2626"}],table:{caption:"Monthly revenue values."}}}),K=u({meta:{...T,key:"analytics.visualization.regional-revenue",title:"Regional Revenue",description:"Revenue split by sales territory.",goal:"Compare the strongest and weakest performing territories.",context:"Territory planning and commercial comparison."},source:{primary:q,resultPath:"data"},visualization:{kind:"cartesian",variant:"bar",xDimension:"region",yMeasures:["revenue"],dimensions:[{key:"region",label:"Region",dataPath:"region",type:"category"}],measures:[{key:"revenue",label:"Revenue",dataPath:"revenue",format:"currency",color:"#1d4ed8"}],table:{caption:"Revenue by region."}}}),Q=u({meta:{...T,key:"analytics.visualization.retention-area",title:"Retention Curve",description:"Weekly retention progression across the active cohort.",goal:"Show whether user retention remains above the desired floor.",context:"Product health dashboard."},source:{primary:q,resultPath:"data"},visualization:{kind:"cartesian",variant:"area",xDimension:"week",yMeasures:["retentionRate"],dimensions:[{key:"week",label:"Week",dataPath:"week",type:"category"}],measures:[{key:"retentionRate",label:"Retention",dataPath:"retentionRate",format:"percentage",color:"#16a34a"}],thresholds:[{key:"floor",value:0.5,label:"Floor",color:"#f59e0b"}],table:{caption:"Weekly retention rate."}}}),S=u({meta:{...T,key:"analytics.visualization.pipeline-scatter",title:"Pipeline Velocity",description:"Deal-cycle length against win rate for active accounts.",goal:"Spot outliers where the sales cycle is long but conversion remains weak.",context:"Commercial operations dashboard."},source:{primary:q,resultPath:"data"},visualization:{kind:"cartesian",variant:"scatter",xDimension:"cycleDays",yMeasures:["winRate"],dimensions:[{key:"cycleDays",label:"Cycle Days",dataPath:"cycleDays",type:"number"}],measures:[{key:"winRate",label:"Win Rate",dataPath:"winRate",format:"percentage",color:"#7c3aed"},{key:"arr",label:"ARR",dataPath:"arr",format:"currency"}],series:[{key:"pipeline",label:"Accounts",measure:"winRate",type:"scatter",color:"#7c3aed"}],table:{caption:"Sales cycle and win rate per account."}}});import{VisualizationRegistry as Pm}from"@contractspec/lib.contracts-spec/visualizations";var g=[f,M,K,Q,S,C,U,A,t],Gm=new Pm([...g]),Lm=g.map((m)=>G(m)),i=new Map(g.map((m)=>[k(m.meta),m])),e={[k(f.meta)]:{data:[{period:"2025-11-01",totalRevenue:112000,priorRevenue:103000},{period:"2025-12-01",totalRevenue:119000,priorRevenue:110000},{period:"2026-01-01",totalRevenue:126500,priorRevenue:116000},{period:"2026-02-01",totalRevenue:133000,priorRevenue:124000},{period:"2026-03-01",totalRevenue:145500,priorRevenue:133000}]},[k(M.meta)]:{data:[{date:"2025-11-01",revenue:112000},{date:"2025-12-01",revenue:119000},{date:"2026-01-01",revenue:126500},{date:"2026-02-01",revenue:133000},{date:"2026-03-01",revenue:145500}]},[k(K.meta)]:{data:[{region:"North America",revenue:210000},{region:"EMEA",revenue:174000},{region:"APAC",revenue:132000},{region:"LATAM",revenue:88000}]},[k(Q.meta)]:{data:[{week:"Week 1",retentionRate:0.71},{week:"Week 2",retentionRate:0.66},{week:"Week 3",retentionRate:0.62},{week:"Week 4",retentionRate:0.58},{week:"Week 5",retentionRate:0.55},{week:"Week 6",retentionRate:0.53}]},[k(S.meta)]:{data:[{cycleDays:18,winRate:0.31,arr:82000},{cycleDays:26,winRate:0.44,arr:65000},{cycleDays:33,winRate:0.27,arr:91000},{cycleDays:14,winRate:0.56,arr:47000},{cycleDays:21,winRate:0.48,arr:59000},{cycleDays:39,winRate:0.22,arr:114000}]},[k(C.meta)]:{data:[{channel:"Direct",sessions:4200},{channel:"Organic Search",sessions:3600},{channel:"Paid Search",sessions:2100},{channel:"Partner",sessions:1400},{channel:"Referral",sessions:900}]},[k(U.meta)]:{data:[{weekday:"Mon",timeBand:"09:00",engagementScore:74},{weekday:"Mon",timeBand:"13:00",engagementScore:82},{weekday:"Tue",timeBand:"09:00",engagementScore:69},{weekday:"Tue",timeBand:"13:00",engagementScore:88},{weekday:"Wed",timeBand:"09:00",engagementScore:77},{weekday:"Wed",timeBand:"13:00",engagementScore:91},{weekday:"Thu",timeBand:"09:00",engagementScore:72},{weekday:"Thu",timeBand:"13:00",engagementScore:86},{weekday:"Fri",timeBand:"09:00",engagementScore:65},{weekday:"Fri",timeBand:"13:00",engagementScore:79}]},[k(A.meta)]:{data:[{stage:"Visited Site",users:12000},{stage:"Started Trial",users:4200},{stage:"Activated Workspace",users:2400},{stage:"Requested Demo",users:980},{stage:"Closed Won",users:310}]},[k(t.meta)]:{data:[{city:"Paris",latitude:48.8566,longitude:2.3522,accounts:48},{city:"London",latitude:51.5072,longitude:-0.1276,accounts:62},{city:"New York",latitude:40.7128,longitude:-74.006,accounts:71},{city:"Toronto",latitude:43.6532,longitude:-79.3832,accounts:36},{city:"Singapore",latitude:1.3521,longitude:103.8198,accounts:29}]}};function G(m){return{key:m.meta.key,version:m.meta.version}}function k(m){return`${m.key}.v${m.version}`}var Dm={METRIC:G(f),LINE_CHART:G(M),BAR_CHART:G(K),AREA_CHART:G(Q),SCATTER_PLOT:G(S),PIE_CHART:G(C),HEATMAP:G(U),FUNNEL:G(A),MAP:G(t)};function F(m){return[Z(m,"widget_revenue_metric","Revenue Snapshot","METRIC",0,0,4,2,{layout:"single",bindings:[P(f,200)]}),Z(m,"widget_revenue_trend","Revenue Trend","LINE_CHART",4,0,8,4,{layout:"single",bindings:[P(M)]}),Z(m,"widget_regional_revenue","Regional Revenue","BAR_CHART",0,2,6,4,{layout:"single",bindings:[P(K)]}),Z(m,"widget_channel_mix","Channel Mix","PIE_CHART",6,2,6,4,{layout:"single",bindings:[P(C)]}),Z(m,"widget_retention","Retention Curve","AREA_CHART",0,6,6,4,{layout:"single",bindings:[P(Q)]}),Z(m,"widget_pipeline","Pipeline Velocity","SCATTER_PLOT",6,6,6,4,{layout:"single",bindings:[P(S)]}),Z(m,"widget_heatmap","Engagement Heatmap","HEATMAP",0,10,8,4,{layout:"single",bindings:[P(U)]}),Z(m,"widget_funnel","Conversion Funnel","FUNNEL",8,10,4,4,{layout:"single",bindings:[P(A)]}),Z(m,"widget_geo","Account Coverage","MAP",0,14,12,5,{layout:"single",bindings:[P(t,360)]}),Z(m,"widget_comparison","Commercial Comparison","EMBED",0,19,12,6,{layout:"comparison",description:"Compare regional distribution, channel balance, and funnel shape.",bindings:[P(K,240),P(C,240),P(A,240)]}),Z(m,"widget_timeline","Growth Timeline","EMBED",0,25,12,6,{layout:"timeline",description:"Track revenue and retention over the same reporting cadence.",bindings:[P(M,220),P(Q,220)]})]}function E(m){let o=Zm(m),r=o.bindings.map((p)=>{let n=i.get(k(p.ref));if(!n)return null;return{key:`${m.id}:${k(p.ref)}`,spec:n,data:p.data,title:p.title??n.meta.title,description:p.description??n.meta.description,height:p.height}}).filter((p)=>Boolean(p));if(!r.length)return null;return{id:m.id,name:m.name,description:o.description,layout:o.layout,gridX:m.gridX,gridY:m.gridY,gridWidth:m.gridWidth,gridHeight:m.gridHeight,bindings:r}}function Zm(m){if(Hm(m.config))return m.config;let o=Dm[m.type];return o?{layout:"single",bindings:[{ref:o,data:e[k(o)]}]}:{layout:"single",bindings:[]}}function P(m,o=280){return{ref:G(m),data:e[k(m.meta)],height:o}}function Z(m,o,r,p,n,$,H,W,J){let O=new Date;return{id:o,dashboardId:m,name:r,type:p,gridX:n,gridY:$,gridWidth:H,gridHeight:W,config:J,createdAt:O,updatedAt:O}}function Hm(m){if(!m||typeof m!=="object")return!1;let o=m;return(o.layout==="single"||o.layout==="comparison"||o.layout==="timeline")&&Array.isArray(o.bindings)}import{ComparisonView as Wm,TimelineView as Jm,VisualizationCard as Xm,VisualizationGrid as wm}from"@contractspec/lib.design-system";import{jsx as h,jsxs as j}from"react/jsx-runtime";function om({dashboardName:m,widgets:o}){if(!o.length)return j("div",{className:"rounded-lg border border-dashed p-10 text-center text-muted-foreground",children:['No visualization widgets configured for "',m,'".']});return j("div",{children:[j("h3",{className:"mb-4 font-semibold text-lg",children:['Widgets in "',m,'"']}),h(wm,{children:o.map((r)=>h("div",{className:Am(r.gridWidth),children:Cm(r)},r.id))})]})}function Cm(m){let o=j("span",{className:"text-muted-foreground text-xs",children:["Position: (",m.gridX,", ",m.gridY,") • ",m.gridWidth,"x",m.gridHeight]});if(m.layout==="comparison")return h(Wm,{description:m.description,items:m.bindings.map((p)=>({...p,footer:o})),title:m.name});if(m.layout==="timeline")return h(Jm,{description:m.description,items:m.bindings.map((p)=>({...p,footer:o})),title:m.name});let r=m.bindings[0];if(!r)return null;return h(Xm,{data:r.data,description:m.description??r.description,footer:o,height:r.height,spec:r.spec,title:m.name})}function Am(m){if(m>=12)return"md:col-span-2 xl:col-span-3";if(m>=8)return"xl:col-span-2";if(m>=6)return"md:col-span-2";return""}import{DataTable as Mm}from"@contractspec/lib.design-system";import{useContractTable as Km}from"@contractspec/lib.presentation-runtime-react";import{Badge as nm}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as Qm,VStack as V}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as X}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as L,jsxs as w}from"react/jsx-runtime";var Um={SQL:"default",METRIC:"secondary",AGGREGATION:"secondary",CUSTOM:"outline"};function tm(m){return JSON.stringify(m,null,2)}function pm({queries:m}){let o=Km({data:m,columns:[{id:"query",header:"Query",label:"Query",accessor:(r)=>r.name,cell:({item:r})=>w(V,{gap:"xs",children:[L(X,{className:"font-medium text-sm",children:r.name}),w(X,{className:"text-muted-foreground text-xs",children:["Updated ",r.updatedAt.toLocaleDateString()]})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"description",header:"Description",label:"Description",accessor:(r)=>r.description??"",cell:({value:r})=>L(X,{className:"line-clamp-2 text-muted-foreground text-sm",children:String(r||"No description")}),size:300,minSize:220,canSort:!1,canHide:!0,canResize:!0},{id:"type",header:"Type",label:"Type",accessorKey:"type",cell:({value:r})=>L(nm,{variant:Um[String(r)],children:String(r)}),size:150,canSort:!0,canHide:!0,canResize:!0},{id:"cacheTtlSeconds",header:"Cache TTL",label:"Cache TTL",accessorKey:"cacheTtlSeconds",cell:({value:r})=>`${String(r)}s`,align:"right",size:140,canSort:!0,canResize:!0},{id:"isShared",header:"Shared",label:"Shared",accessorKey:"isShared",cell:({value:r})=>L(nm,{variant:r?"default":"outline",children:r?"Shared":"Private"}),size:140,canSort:!0,canHide:!0,canResize:!0}],initialState:{pagination:{pageIndex:0,pageSize:3},columnVisibility:{description:!1},columnPinning:{left:["query"],right:[]}},renderExpandedContent:(r)=>w(V,{gap:"sm",className:"py-2",children:[w(V,{gap:"xs",children:[L(X,{className:"font-medium text-sm",children:"Description"}),L(X,{className:"text-muted-foreground text-sm",children:r.description??"No description"})]}),r.sql?w(V,{gap:"xs",children:[L(X,{className:"font-medium text-sm",children:"SQL"}),L("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:r.sql})]}):null,w(V,{gap:"xs",children:[L(X,{className:"font-medium text-sm",children:"Definition"}),L("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:tm(r.definition)})]})]}),getCanExpand:()=>!0});return L(Mm,{controller:o,title:"Saved Queries",description:"Client-mode table using the shared ContractSpec controller and renderer.",toolbar:w(Qm,{gap:"sm",className:"flex-wrap",children:[w(X,{className:"text-muted-foreground text-sm",children:[m.length," queries"]}),w(X,{className:"text-muted-foreground text-sm",children:[m.filter((r)=>r.isShared).length," shared"]})]}),emptyState:L("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No queries saved"})})}import{useTemplateRuntime as fm}from"@contractspec/lib.example-shared-ui";import{useCallback as ym,useEffect as Sm,useState as Y}from"react";function a(m="local-project"){let{handlers:o}=fm(),r=o.analytics,[p,n]=Y([]),[$,H]=Y([]),[W,J]=Y(null),[O,_]=Y([]),[s,I]=Y(!0),[y,c]=Y(null),d=ym(async()=>{try{I(!0),c(null);let[B,v]=await Promise.all([r.listDashboards({projectId:m,limit:100}),r.listQueries({projectId:m,limit:100})]);if(n(B.dashboards),H(v.queries),B.dashboards.length>0&&!W){let R=B.dashboards[0];if(R){J(R);let rm=await r.getWidgets(R.id);_(rm.length>0?rm:F(R.id))}}}catch(B){c(B instanceof Error?B:Error("Failed to load analytics"))}finally{I(!1)}},[r,m,W]);Sm(()=>{d()},[d]);let Nm=ym(async(B)=>{J(B);let v=await r.getWidgets(B.id);_(v.length>0?v:F(B.id))},[r]),Bm={totalDashboards:p.length,publishedDashboards:p.filter((B)=>B.status==="PUBLISHED").length,totalQueries:$.length,sharedQueries:$.filter((B)=>B.isShared).length};return{dashboards:p,queries:$,selectedDashboard:W,widgets:O,loading:s,error:y,stats:Bm,refetch:d,selectDashboard:Nm}}import{Button as $m,ErrorState as Om,LoaderBlock as Fm,StatCard as mm,StatCardGroup as Ym}from"@contractspec/lib.design-system";import{useMemo as _m,useState as cm}from"react";import{jsx as N,jsxs as D}from"react/jsx-runtime";var um={PUBLISHED:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",DRAFT:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",ARCHIVED:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"};function qm(){let[m,o]=cm("dashboards"),{dashboards:r,queries:p,selectedDashboard:n,widgets:$,loading:H,error:W,stats:J,refetch:O,selectDashboard:_}=a(),s=[{id:"dashboards",label:"Dashboards",icon:"\uD83D\uDCCA"},{id:"queries",label:"Queries",icon:"\uD83D\uDD0D"}],I=_m(()=>$.map((y)=>E(y)).filter((y)=>Boolean(y)),[$]);if(H)return N(Fm,{label:"Loading Analytics..."});if(W)return N(Om,{title:"Failed to load Analytics",description:W.message,onRetry:O,retryLabel:"Retry"});return D("div",{className:"space-y-6",children:[D("div",{className:"flex items-center justify-between",children:[N("h2",{className:"font-bold text-2xl",children:"Analytics Dashboard"}),D($m,{onClick:()=>alert("Create dashboard modal"),children:[N("span",{className:"mr-2",children:"+"})," New Dashboard"]})]}),D(Ym,{children:[N(mm,{label:"Dashboards",value:J.totalDashboards,hint:`${J.publishedDashboards} published`}),N(mm,{label:"Queries",value:J.totalQueries,hint:`${J.sharedQueries} shared`}),N(mm,{label:"Widgets",value:$.length,hint:"on current dashboard"})]}),N("nav",{className:"flex gap-1 rounded-lg bg-muted p-1",role:"tablist",children:s.map((y)=>D($m,{type:"button",role:"tab","aria-selected":m===y.id,onClick:()=>o(y.id),className:`flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${m===y.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[N("span",{children:y.icon}),y.label]},y.id))}),D("div",{className:"min-h-[400px]",role:"tabpanel",children:[m==="dashboards"&&D("div",{className:"space-y-6",children:[D("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[r.map((y)=>D("div",{onClick:()=>_(y),className:`cursor-pointer rounded-lg border border-border bg-card p-4 transition-all ${n?.id===y.id?"ring-2 ring-primary":"hover:bg-muted/50"}`,role:"button",tabIndex:0,onKeyDown:(c)=>{if(c.key==="Enter"||c.key===" ")_(y)},children:[D("div",{className:"mb-2 flex items-center justify-between",children:[N("h3",{className:"font-medium",children:y.name}),N("span",{className:`inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${um[y.status]??""}`,children:y.status})]}),N("p",{className:"mb-3 text-muted-foreground text-sm",children:y.description}),D("div",{className:"flex items-center justify-between text-muted-foreground text-xs",children:[D("span",{children:["/",y.slug]}),y.isPublic&&N("span",{className:"text-green-600 dark:text-green-400",children:"\uD83C\uDF10 Public"})]})]},y.id)),r.length===0&&N("div",{className:"col-span-full flex h-64 items-center justify-center text-muted-foreground",children:"No dashboards created yet"})]}),n?N(om,{dashboardName:n.name,widgets:I}):null]}),m==="queries"&&N(pm,{queries:p})]})]})}var b=[{id:"dash-1",name:"Sales Overview",slug:"sales-overview",status:"PUBLISHED",widgetCount:11,viewCount:1250,lastViewedAt:"2026-03-18T12:00:00Z"},{id:"dash-2",name:"User Engagement",slug:"user-engagement",status:"PUBLISHED",widgetCount:8,viewCount:890,lastViewedAt:"2026-03-18T10:00:00Z"}],km=[{id:"q-1",name:"Monthly Revenue",type:"AGGREGATION",isShared:!0,executionCount:1500},{id:"q-2",name:"User Growth",type:"METRIC",isShared:!0,executionCount:890},{id:"q-3",name:"Product Sales",type:"SQL",isShared:!1,executionCount:340},{id:"q-4",name:"Conversion Funnel",type:"AGGREGATION",isShared:!0,executionCount:450}];function Tm(m){return F(m).map((o)=>E(o)).filter((o)=>Boolean(o))}var Em={target:"markdown",render:async(m)=>{if(m.source.type!=="component"||m.source.componentKey!=="AnalyticsDashboard")throw Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");let o=b[0];if(!o)return{mimeType:"text/markdown",body:`# No Dashboards
135
2
 
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
- }
592
- // src/ui/AnalyticsDashboard.widgets.tsx
593
- import {
594
- ComparisonView,
595
- TimelineView,
596
- VisualizationCard,
597
- VisualizationGrid
598
- } from "@contractspec/lib.design-system";
599
- import { jsxDEV } from "react/jsx-dev-runtime";
600
- "use client";
601
- function AnalyticsWidgetBoard({
602
- dashboardName,
603
- widgets
604
- }) {
605
- if (!widgets.length) {
606
- return /* @__PURE__ */ jsxDEV("div", {
607
- className: "rounded-lg border border-dashed p-10 text-center text-muted-foreground",
608
- children: [
609
- 'No visualization widgets configured for "',
610
- dashboardName,
611
- '".'
612
- ]
613
- }, undefined, true, undefined, this);
614
- }
615
- return /* @__PURE__ */ jsxDEV("div", {
616
- children: [
617
- /* @__PURE__ */ jsxDEV("h3", {
618
- className: "mb-4 font-semibold text-lg",
619
- children: [
620
- 'Widgets in "',
621
- dashboardName,
622
- '"'
623
- ]
624
- }, undefined, true, undefined, this),
625
- /* @__PURE__ */ jsxDEV(VisualizationGrid, {
626
- children: widgets.map((widget2) => /* @__PURE__ */ jsxDEV("div", {
627
- className: gridSpanClass(widget2.gridWidth),
628
- children: renderVisualizationWidget(widget2)
629
- }, widget2.id, false, undefined, this))
630
- }, undefined, false, undefined, this)
631
- ]
632
- }, undefined, true, undefined, this);
633
- }
634
- function renderVisualizationWidget(widget2) {
635
- const footer = /* @__PURE__ */ jsxDEV("span", {
636
- className: "text-muted-foreground text-xs",
637
- children: [
638
- "Position: (",
639
- widget2.gridX,
640
- ", ",
641
- widget2.gridY,
642
- ") • ",
643
- widget2.gridWidth,
644
- "x",
645
- widget2.gridHeight
646
- ]
647
- }, undefined, true, undefined, this);
648
- if (widget2.layout === "comparison") {
649
- return /* @__PURE__ */ jsxDEV(ComparisonView, {
650
- description: widget2.description,
651
- items: widget2.bindings.map((binding3) => ({ ...binding3, footer })),
652
- title: widget2.name
653
- }, undefined, false, undefined, this);
654
- }
655
- if (widget2.layout === "timeline") {
656
- return /* @__PURE__ */ jsxDEV(TimelineView, {
657
- description: widget2.description,
658
- items: widget2.bindings.map((binding3) => ({ ...binding3, footer })),
659
- title: widget2.name
660
- }, undefined, false, undefined, this);
661
- }
662
- const binding2 = widget2.bindings[0];
663
- if (!binding2)
664
- return null;
665
- return /* @__PURE__ */ jsxDEV(VisualizationCard, {
666
- data: binding2.data,
667
- description: widget2.description ?? binding2.description,
668
- footer,
669
- height: binding2.height,
670
- spec: binding2.spec,
671
- title: widget2.name
672
- }, undefined, false, undefined, this);
673
- }
674
- function gridSpanClass(gridWidth) {
675
- if (gridWidth >= 12)
676
- return "md:col-span-2 xl:col-span-3";
677
- if (gridWidth >= 8)
678
- return "xl:col-span-2";
679
- if (gridWidth >= 6)
680
- return "md:col-span-2";
681
- return "";
682
- }
683
-
684
- // src/ui/AnalyticsQueriesTable.tsx
685
- import { DataTable } from "@contractspec/lib.design-system";
686
- import { useContractTable } from "@contractspec/lib.presentation-runtime-react";
687
- import { Badge } from "@contractspec/lib.ui-kit-web/ui/badge";
688
- import { HStack, VStack } from "@contractspec/lib.ui-kit-web/ui/stack";
689
- import { Text } from "@contractspec/lib.ui-kit-web/ui/text";
690
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
691
- "use client";
692
- var QUERY_TYPE_COLORS = {
693
- SQL: "default",
694
- METRIC: "secondary",
695
- AGGREGATION: "secondary",
696
- CUSTOM: "outline"
697
- };
698
- function formatJson(value) {
699
- return JSON.stringify(value, null, 2);
700
- }
701
- function AnalyticsQueriesTable({ queries }) {
702
- const controller = useContractTable({
703
- data: queries,
704
- columns: [
705
- {
706
- id: "query",
707
- header: "Query",
708
- label: "Query",
709
- accessor: (query) => query.name,
710
- cell: ({ item }) => /* @__PURE__ */ jsxDEV2(VStack, {
711
- gap: "xs",
712
- children: [
713
- /* @__PURE__ */ jsxDEV2(Text, {
714
- className: "font-medium text-sm",
715
- children: item.name
716
- }, undefined, false, undefined, this),
717
- /* @__PURE__ */ jsxDEV2(Text, {
718
- className: "text-muted-foreground text-xs",
719
- children: [
720
- "Updated ",
721
- item.updatedAt.toLocaleDateString()
722
- ]
723
- }, undefined, true, undefined, this)
724
- ]
725
- }, undefined, true, undefined, this),
726
- size: 240,
727
- minSize: 180,
728
- canSort: true,
729
- canPin: true,
730
- canResize: true
731
- },
732
- {
733
- id: "description",
734
- header: "Description",
735
- label: "Description",
736
- accessor: (query) => query.description ?? "",
737
- cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Text, {
738
- className: "line-clamp-2 text-muted-foreground text-sm",
739
- children: String(value || "No description")
740
- }, undefined, false, undefined, this),
741
- size: 300,
742
- minSize: 220,
743
- canSort: false,
744
- canHide: true,
745
- canResize: true
746
- },
747
- {
748
- id: "type",
749
- header: "Type",
750
- label: "Type",
751
- accessorKey: "type",
752
- cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Badge, {
753
- variant: QUERY_TYPE_COLORS[String(value)],
754
- children: String(value)
755
- }, undefined, false, undefined, this),
756
- size: 150,
757
- canSort: true,
758
- canHide: true,
759
- canResize: true
760
- },
761
- {
762
- id: "cacheTtlSeconds",
763
- header: "Cache TTL",
764
- label: "Cache TTL",
765
- accessorKey: "cacheTtlSeconds",
766
- cell: ({ value }) => `${String(value)}s`,
767
- align: "right",
768
- size: 140,
769
- canSort: true,
770
- canResize: true
771
- },
772
- {
773
- id: "isShared",
774
- header: "Shared",
775
- label: "Shared",
776
- accessorKey: "isShared",
777
- cell: ({ value }) => /* @__PURE__ */ jsxDEV2(Badge, {
778
- variant: value ? "default" : "outline",
779
- children: value ? "Shared" : "Private"
780
- }, undefined, false, undefined, this),
781
- size: 140,
782
- canSort: true,
783
- canHide: true,
784
- canResize: true
785
- }
786
- ],
787
- initialState: {
788
- pagination: { pageIndex: 0, pageSize: 3 },
789
- columnVisibility: { description: false },
790
- columnPinning: { left: ["query"], right: [] }
791
- },
792
- renderExpandedContent: (query) => /* @__PURE__ */ jsxDEV2(VStack, {
793
- gap: "sm",
794
- className: "py-2",
795
- children: [
796
- /* @__PURE__ */ jsxDEV2(VStack, {
797
- gap: "xs",
798
- children: [
799
- /* @__PURE__ */ jsxDEV2(Text, {
800
- className: "font-medium text-sm",
801
- children: "Description"
802
- }, undefined, false, undefined, this),
803
- /* @__PURE__ */ jsxDEV2(Text, {
804
- className: "text-muted-foreground text-sm",
805
- children: query.description ?? "No description"
806
- }, undefined, false, undefined, this)
807
- ]
808
- }, undefined, true, undefined, this),
809
- query.sql ? /* @__PURE__ */ jsxDEV2(VStack, {
810
- gap: "xs",
811
- children: [
812
- /* @__PURE__ */ jsxDEV2(Text, {
813
- className: "font-medium text-sm",
814
- children: "SQL"
815
- }, undefined, false, undefined, this),
816
- /* @__PURE__ */ jsxDEV2("pre", {
817
- className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
818
- children: query.sql
819
- }, undefined, false, undefined, this)
820
- ]
821
- }, undefined, true, undefined, this) : null,
822
- /* @__PURE__ */ jsxDEV2(VStack, {
823
- gap: "xs",
824
- children: [
825
- /* @__PURE__ */ jsxDEV2(Text, {
826
- className: "font-medium text-sm",
827
- children: "Definition"
828
- }, undefined, false, undefined, this),
829
- /* @__PURE__ */ jsxDEV2("pre", {
830
- className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
831
- children: formatJson(query.definition)
832
- }, undefined, false, undefined, this)
833
- ]
834
- }, undefined, true, undefined, this)
835
- ]
836
- }, undefined, true, undefined, this),
837
- getCanExpand: () => true
838
- });
839
- return /* @__PURE__ */ jsxDEV2(DataTable, {
840
- controller,
841
- title: "Saved Queries",
842
- description: "Client-mode table using the shared ContractSpec controller and renderer.",
843
- toolbar: /* @__PURE__ */ jsxDEV2(HStack, {
844
- gap: "sm",
845
- className: "flex-wrap",
846
- children: [
847
- /* @__PURE__ */ jsxDEV2(Text, {
848
- className: "text-muted-foreground text-sm",
849
- children: [
850
- queries.length,
851
- " queries"
852
- ]
853
- }, undefined, true, undefined, this),
854
- /* @__PURE__ */ jsxDEV2(Text, {
855
- className: "text-muted-foreground text-sm",
856
- children: [
857
- queries.filter((query) => query.isShared).length,
858
- " shared"
859
- ]
860
- }, undefined, true, undefined, this)
861
- ]
862
- }, undefined, true, undefined, this),
863
- emptyState: /* @__PURE__ */ jsxDEV2("div", {
864
- className: "rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",
865
- children: "No queries saved"
866
- }, undefined, false, undefined, this)
867
- }, undefined, false, undefined, this);
868
- }
869
-
870
- // src/ui/hooks/useAnalyticsData.ts
871
- import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
872
- import { useCallback, useEffect, useState } from "react";
873
- "use client";
874
- function useAnalyticsData(projectId = "local-project") {
875
- const { handlers } = useTemplateRuntime();
876
- const analytics = handlers.analytics;
877
- const [dashboards, setDashboards] = useState([]);
878
- const [queries, setQueries] = useState([]);
879
- const [selectedDashboard, setSelectedDashboard] = useState(null);
880
- const [widgets, setWidgets] = useState([]);
881
- const [loading, setLoading] = useState(true);
882
- const [error, setError] = useState(null);
883
- const fetchData = useCallback(async () => {
884
- try {
885
- setLoading(true);
886
- setError(null);
887
- const [dashResult, queryResult] = await Promise.all([
888
- analytics.listDashboards({ projectId, limit: 100 }),
889
- analytics.listQueries({ projectId, limit: 100 })
890
- ]);
891
- setDashboards(dashResult.dashboards);
892
- setQueries(queryResult.queries);
893
- if (dashResult.dashboards.length > 0 && !selectedDashboard) {
894
- const first = dashResult.dashboards[0];
895
- if (first) {
896
- setSelectedDashboard(first);
897
- const dashboardWidgets = await analytics.getWidgets(first.id);
898
- setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(first.id));
899
- }
900
- }
901
- } catch (err) {
902
- setError(err instanceof Error ? err : new Error("Failed to load analytics"));
903
- } finally {
904
- setLoading(false);
905
- }
906
- }, [analytics, projectId, selectedDashboard]);
907
- useEffect(() => {
908
- fetchData();
909
- }, [fetchData]);
910
- const selectDashboard = useCallback(async (dashboard) => {
911
- setSelectedDashboard(dashboard);
912
- const dashboardWidgets = await analytics.getWidgets(dashboard.id);
913
- setWidgets(dashboardWidgets.length > 0 ? dashboardWidgets : createExampleWidgets(dashboard.id));
914
- }, [analytics]);
915
- const stats = {
916
- totalDashboards: dashboards.length,
917
- publishedDashboards: dashboards.filter((d) => d.status === "PUBLISHED").length,
918
- totalQueries: queries.length,
919
- sharedQueries: queries.filter((q) => q.isShared).length
920
- };
921
- return {
922
- dashboards,
923
- queries,
924
- selectedDashboard,
925
- widgets,
926
- loading,
927
- error,
928
- stats,
929
- refetch: fetchData,
930
- selectDashboard
931
- };
932
- }
933
-
934
- // src/ui/AnalyticsDashboard.tsx
935
- import {
936
- Button,
937
- ErrorState,
938
- LoaderBlock,
939
- StatCard,
940
- StatCardGroup
941
- } from "@contractspec/lib.design-system";
942
- import { useMemo, useState as useState2 } from "react";
943
- import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
944
- "use client";
945
- var STATUS_COLORS = {
946
- PUBLISHED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
947
- DRAFT: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
948
- ARCHIVED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
949
- };
950
- function AnalyticsDashboard() {
951
- const [activeTab, setActiveTab] = useState2("dashboards");
952
- const {
953
- dashboards,
954
- queries,
955
- selectedDashboard,
956
- widgets,
957
- loading,
958
- error,
959
- stats,
960
- refetch,
961
- selectDashboard
962
- } = useAnalyticsData();
963
- const tabs = [
964
- { id: "dashboards", label: "Dashboards", icon: "\uD83D\uDCCA" },
965
- { id: "queries", label: "Queries", icon: "\uD83D\uDD0D" }
966
- ];
967
- const resolvedWidgets = useMemo(() => widgets.map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2)), [widgets]);
968
- if (loading) {
969
- return /* @__PURE__ */ jsxDEV3(LoaderBlock, {
970
- label: "Loading Analytics..."
971
- }, undefined, false, undefined, this);
972
- }
973
- if (error) {
974
- return /* @__PURE__ */ jsxDEV3(ErrorState, {
975
- title: "Failed to load Analytics",
976
- description: error.message,
977
- onRetry: refetch,
978
- retryLabel: "Retry"
979
- }, undefined, false, undefined, this);
980
- }
981
- return /* @__PURE__ */ jsxDEV3("div", {
982
- className: "space-y-6",
983
- children: [
984
- /* @__PURE__ */ jsxDEV3("div", {
985
- className: "flex items-center justify-between",
986
- children: [
987
- /* @__PURE__ */ jsxDEV3("h2", {
988
- className: "font-bold text-2xl",
989
- children: "Analytics Dashboard"
990
- }, undefined, false, undefined, this),
991
- /* @__PURE__ */ jsxDEV3(Button, {
992
- onClick: () => alert("Create dashboard modal"),
993
- children: [
994
- /* @__PURE__ */ jsxDEV3("span", {
995
- className: "mr-2",
996
- children: "+"
997
- }, undefined, false, undefined, this),
998
- " New Dashboard"
999
- ]
1000
- }, undefined, true, undefined, this)
1001
- ]
1002
- }, undefined, true, undefined, this),
1003
- /* @__PURE__ */ jsxDEV3(StatCardGroup, {
1004
- children: [
1005
- /* @__PURE__ */ jsxDEV3(StatCard, {
1006
- label: "Dashboards",
1007
- value: stats.totalDashboards,
1008
- hint: `${stats.publishedDashboards} published`
1009
- }, undefined, false, undefined, this),
1010
- /* @__PURE__ */ jsxDEV3(StatCard, {
1011
- label: "Queries",
1012
- value: stats.totalQueries,
1013
- hint: `${stats.sharedQueries} shared`
1014
- }, undefined, false, undefined, this),
1015
- /* @__PURE__ */ jsxDEV3(StatCard, {
1016
- label: "Widgets",
1017
- value: widgets.length,
1018
- hint: "on current dashboard"
1019
- }, undefined, false, undefined, this)
1020
- ]
1021
- }, undefined, true, undefined, this),
1022
- /* @__PURE__ */ jsxDEV3("nav", {
1023
- className: "flex gap-1 rounded-lg bg-muted p-1",
1024
- role: "tablist",
1025
- children: tabs.map((tab) => /* @__PURE__ */ jsxDEV3(Button, {
1026
- type: "button",
1027
- role: "tab",
1028
- "aria-selected": activeTab === tab.id,
1029
- onClick: () => setActiveTab(tab.id),
1030
- 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"}`,
1031
- children: [
1032
- /* @__PURE__ */ jsxDEV3("span", {
1033
- children: tab.icon
1034
- }, undefined, false, undefined, this),
1035
- tab.label
1036
- ]
1037
- }, tab.id, true, undefined, this))
1038
- }, undefined, false, undefined, this),
1039
- /* @__PURE__ */ jsxDEV3("div", {
1040
- className: "min-h-[400px]",
1041
- role: "tabpanel",
1042
- children: [
1043
- activeTab === "dashboards" && /* @__PURE__ */ jsxDEV3("div", {
1044
- className: "space-y-6",
1045
- children: [
1046
- /* @__PURE__ */ jsxDEV3("div", {
1047
- className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1048
- children: [
1049
- dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV3("div", {
1050
- onClick: () => selectDashboard(dashboard),
1051
- 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"}`,
1052
- role: "button",
1053
- tabIndex: 0,
1054
- onKeyDown: (e) => {
1055
- if (e.key === "Enter" || e.key === " ")
1056
- selectDashboard(dashboard);
1057
- },
1058
- children: [
1059
- /* @__PURE__ */ jsxDEV3("div", {
1060
- className: "mb-2 flex items-center justify-between",
1061
- children: [
1062
- /* @__PURE__ */ jsxDEV3("h3", {
1063
- className: "font-medium",
1064
- children: dashboard.name
1065
- }, undefined, false, undefined, this),
1066
- /* @__PURE__ */ jsxDEV3("span", {
1067
- className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[dashboard.status] ?? ""}`,
1068
- children: dashboard.status
1069
- }, undefined, false, undefined, this)
1070
- ]
1071
- }, undefined, true, undefined, this),
1072
- /* @__PURE__ */ jsxDEV3("p", {
1073
- className: "mb-3 text-muted-foreground text-sm",
1074
- children: dashboard.description
1075
- }, undefined, false, undefined, this),
1076
- /* @__PURE__ */ jsxDEV3("div", {
1077
- className: "flex items-center justify-between text-muted-foreground text-xs",
1078
- children: [
1079
- /* @__PURE__ */ jsxDEV3("span", {
1080
- children: [
1081
- "/",
1082
- dashboard.slug
1083
- ]
1084
- }, undefined, true, undefined, this),
1085
- dashboard.isPublic && /* @__PURE__ */ jsxDEV3("span", {
1086
- className: "text-green-600 dark:text-green-400",
1087
- children: "\uD83C\uDF10 Public"
1088
- }, undefined, false, undefined, this)
1089
- ]
1090
- }, undefined, true, undefined, this)
1091
- ]
1092
- }, dashboard.id, true, undefined, this)),
1093
- dashboards.length === 0 && /* @__PURE__ */ jsxDEV3("div", {
1094
- className: "col-span-full flex h-64 items-center justify-center text-muted-foreground",
1095
- children: "No dashboards created yet"
1096
- }, undefined, false, undefined, this)
1097
- ]
1098
- }, undefined, true, undefined, this),
1099
- selectedDashboard ? /* @__PURE__ */ jsxDEV3(AnalyticsWidgetBoard, {
1100
- dashboardName: selectedDashboard.name,
1101
- widgets: resolvedWidgets
1102
- }, undefined, false, undefined, this) : null
1103
- ]
1104
- }, undefined, true, undefined, this),
1105
- activeTab === "queries" && /* @__PURE__ */ jsxDEV3(AnalyticsQueriesTable, {
1106
- queries
1107
- }, undefined, false, undefined, this)
1108
- ]
1109
- }, undefined, true, undefined, this)
1110
- ]
1111
- }, undefined, true, undefined, this);
1112
- }
1113
-
1114
- // src/ui/hooks/index.ts
1115
- "use client";
1116
-
1117
- // src/ui/renderers/analytics.markdown.ts
1118
- var mockDashboards = [
1119
- {
1120
- id: "dash-1",
1121
- name: "Sales Overview",
1122
- slug: "sales-overview",
1123
- status: "PUBLISHED",
1124
- widgetCount: 11,
1125
- viewCount: 1250,
1126
- lastViewedAt: "2026-03-18T12:00:00Z"
1127
- },
1128
- {
1129
- id: "dash-2",
1130
- name: "User Engagement",
1131
- slug: "user-engagement",
1132
- status: "PUBLISHED",
1133
- widgetCount: 8,
1134
- viewCount: 890,
1135
- lastViewedAt: "2026-03-18T10:00:00Z"
1136
- }
1137
- ];
1138
- var mockQueries = [
1139
- {
1140
- id: "q-1",
1141
- name: "Monthly Revenue",
1142
- type: "AGGREGATION",
1143
- isShared: true,
1144
- executionCount: 1500
1145
- },
1146
- {
1147
- id: "q-2",
1148
- name: "User Growth",
1149
- type: "METRIC",
1150
- isShared: true,
1151
- executionCount: 890
1152
- },
1153
- {
1154
- id: "q-3",
1155
- name: "Product Sales",
1156
- type: "SQL",
1157
- isShared: false,
1158
- executionCount: 340
1159
- },
1160
- {
1161
- id: "q-4",
1162
- name: "Conversion Funnel",
1163
- type: "AGGREGATION",
1164
- isShared: true,
1165
- executionCount: 450
1166
- }
1167
- ];
1168
- function dashboardWidgets(dashboardId) {
1169
- return createExampleWidgets(dashboardId).map((widget2) => resolveAnalyticsWidget(widget2)).filter((widget2) => Boolean(widget2));
1170
- }
1171
- var analyticsDashboardMarkdownRenderer = {
1172
- target: "markdown",
1173
- render: async (desc) => {
1174
- if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
1175
- throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
1176
- }
1177
- const dashboard = mockDashboards[0];
1178
- if (!dashboard) {
1179
- return {
1180
- mimeType: "text/markdown",
1181
- body: `# No Dashboards
1182
-
1183
- No dashboards available.`
1184
- };
1185
- }
1186
- const widgets = dashboardWidgets(dashboard.id);
1187
- const metricWidgets = widgets.filter((widget2) => widget2.bindings[0]?.spec.visualization.kind === "metric");
1188
- const lines = [
1189
- `# ${dashboard.name}`,
1190
- "",
1191
- "> Contract-backed analytics dashboard overview.",
1192
- "",
1193
- "## Key Metrics",
1194
- ""
1195
- ];
1196
- for (const widget2 of metricWidgets) {
1197
- const binding2 = widget2.bindings[0];
1198
- if (!binding2)
1199
- continue;
1200
- lines.push(`- **${widget2.name}** via \`${binding2.spec.meta.key}\``);
1201
- }
1202
- lines.push("");
1203
- lines.push("## Visual Blocks");
1204
- lines.push("");
1205
- for (const widget2 of widgets) {
1206
- const kinds = widget2.bindings.map((binding2) => binding2.spec.visualization.kind).join(", ");
1207
- lines.push(`- **${widget2.name}** (${widget2.layout}) → ${kinds}`);
1208
- }
1209
- lines.push("");
1210
- lines.push("## Dashboard Stats");
1211
- lines.push("");
1212
- lines.push("| Metric | Value |");
1213
- lines.push("|--------|-------|");
1214
- lines.push(`| Total Dashboards | ${mockDashboards.length} |`);
1215
- lines.push(`| Published | ${mockDashboards.filter((item) => item.status === "PUBLISHED").length} |`);
1216
- lines.push(`| Shared Queries | ${mockQueries.filter((query) => query.isShared).length} |`);
1217
- return {
1218
- mimeType: "text/markdown",
1219
- body: lines.join(`
1220
- `)
1221
- };
1222
- }
1223
- };
1224
- var dashboardListMarkdownRenderer = {
1225
- target: "markdown",
1226
- render: async (desc) => {
1227
- if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
1228
- throw new Error("dashboardListMarkdownRenderer: not DashboardList");
1229
- }
1230
- const lines = [
1231
- "# Dashboards",
1232
- "",
1233
- "> Browse and manage analytics dashboards",
1234
- "",
1235
- "| Dashboard | Widgets | Views | Status | Last Viewed |",
1236
- "|-----------|---------|-------|--------|-------------|"
1237
- ];
1238
- for (const dashboard of mockDashboards) {
1239
- const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
1240
- const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "⚫";
1241
- lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
1242
- }
1243
- return {
1244
- mimeType: "text/markdown",
1245
- body: lines.join(`
1246
- `)
1247
- };
1248
- }
1249
- };
1250
- var queryBuilderMarkdownRenderer = {
1251
- target: "markdown",
1252
- render: async (desc) => {
1253
- if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
1254
- throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
1255
- }
1256
- const lines = [
1257
- "# Query Builder",
1258
- "",
1259
- "> Create and manage reusable data queries.",
1260
- "",
1261
- "| Query | Type | Shared | Executions |",
1262
- "|-------|------|--------|------------|"
1263
- ];
1264
- for (const query of mockQueries) {
1265
- lines.push(`| ${query.name} | ${query.type} | ${query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12"} | ${query.executionCount.toLocaleString()} |`);
1266
- }
1267
- lines.push("");
1268
- lines.push("## Visualization Contracts");
1269
- lines.push("");
1270
- lines.push("Widgets reference `VisualizationSpec` contracts instead of rendering ad-hoc widget types.");
1271
- return {
1272
- mimeType: "text/markdown",
1273
- body: lines.join(`
1274
- `)
1275
- };
1276
- }
1277
- };
1278
- export {
1279
- useAnalyticsData,
1280
- queryBuilderMarkdownRenderer,
1281
- dashboardListMarkdownRenderer,
1282
- analyticsDashboardMarkdownRenderer,
1283
- AnalyticsDashboard
1284
- };
3
+ No dashboards available.`};let r=Tm(o.id),p=r.filter(($)=>$.bindings[0]?.spec.visualization.kind==="metric"),n=[`# ${o.name}`,"","> Contract-backed analytics dashboard overview.","","## Key Metrics",""];for(let $ of p){let H=$.bindings[0];if(!H)continue;n.push(`- **${$.name}** via \`${H.spec.meta.key}\``)}n.push(""),n.push("## Visual Blocks"),n.push("");for(let $ of r){let H=$.bindings.map((W)=>W.spec.visualization.kind).join(", ");n.push(`- **${$.name}** (${$.layout}) → ${H}`)}return n.push(""),n.push("## Dashboard Stats"),n.push(""),n.push("| Metric | Value |"),n.push("|--------|-------|"),n.push(`| Total Dashboards | ${b.length} |`),n.push(`| Published | ${b.filter(($)=>$.status==="PUBLISHED").length} |`),n.push(`| Shared Queries | ${km.filter(($)=>$.isShared).length} |`),{mimeType:"text/markdown",body:n.join(`
4
+ `)}}},hm={target:"markdown",render:async(m)=>{if(m.source.type!=="component"||m.source.componentKey!=="DashboardList")throw Error("dashboardListMarkdownRenderer: not DashboardList");let o=["# Dashboards","","> Browse and manage analytics dashboards","","| Dashboard | Widgets | Views | Status | Last Viewed |","|-----------|---------|-------|--------|-------------|"];for(let r of b){let p=r.lastViewedAt?new Date(r.lastViewedAt).toLocaleDateString():"Never",n=r.status==="PUBLISHED"?"\uD83D\uDFE2":"⚫";o.push(`| [${r.name}](/dashboards/${r.slug}) | ${r.widgetCount} | ${r.viewCount.toLocaleString()} | ${n} ${r.status} | ${p} |`)}return{mimeType:"text/markdown",body:o.join(`
5
+ `)}}},Vm={target:"markdown",render:async(m)=>{if(m.source.type!=="component"||m.source.componentKey!=="QueryBuilder")throw Error("queryBuilderMarkdownRenderer: not QueryBuilder");let o=["# Query Builder","","> Create and manage reusable data queries.","","| Query | Type | Shared | Executions |","|-------|------|--------|------------|"];for(let r of km)o.push(`| ${r.name} | ${r.type} | ${r.isShared?"\uD83C\uDF10":"\uD83D\uDD12"} | ${r.executionCount.toLocaleString()} |`);return o.push(""),o.push("## Visualization Contracts"),o.push(""),o.push("Widgets reference `VisualizationSpec` contracts instead of rendering ad-hoc widget types."),{mimeType:"text/markdown",body:o.join(`
6
+ `)}}};export{a as useAnalyticsData,Vm as queryBuilderMarkdownRenderer,hm as dashboardListMarkdownRenderer,Em as analyticsDashboardMarkdownRenderer,qm as AnalyticsDashboard};