@contractspec/example.analytics-dashboard 1.57.0 → 1.58.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 (173) hide show
  1. package/dist/browser/dashboard/dashboard.enum.js +34 -0
  2. package/dist/browser/dashboard/dashboard.operation.js +289 -0
  3. package/dist/browser/dashboard/dashboard.presentation.js +197 -0
  4. package/dist/browser/dashboard/dashboard.schema.js +126 -0
  5. package/dist/browser/dashboard/dashboard.test-spec.js +213 -0
  6. package/dist/browser/dashboard/index.js +299 -0
  7. package/dist/browser/dashboard.feature.js +84 -0
  8. package/dist/browser/datasource/posthog-datasource.js +289 -0
  9. package/dist/browser/docs/analytics-dashboard.docblock.js +103 -0
  10. package/dist/browser/docs/index.js +103 -0
  11. package/dist/browser/events.js +81 -0
  12. package/dist/browser/example.js +42 -0
  13. package/dist/browser/handlers/analytics.handlers.js +278 -0
  14. package/dist/browser/handlers/index.js +571 -0
  15. package/dist/browser/handlers/query.handlers.js +294 -0
  16. package/dist/browser/index.js +1677 -0
  17. package/dist/browser/query/index.js +159 -0
  18. package/dist/browser/query/query.enum.js +11 -0
  19. package/dist/browser/query/query.operation.js +154 -0
  20. package/dist/browser/query/query.presentation.js +119 -0
  21. package/dist/browser/query/query.schema.js +70 -0
  22. package/dist/browser/query/query.test-spec.js +113 -0
  23. package/dist/browser/query-engine/index.js +491 -0
  24. package/dist/browser/seeders/index.js +20 -0
  25. package/dist/browser/ui/AnalyticsDashboard.js +394 -0
  26. package/dist/browser/ui/hooks/index.js +69 -0
  27. package/dist/browser/ui/hooks/useAnalyticsData.js +66 -0
  28. package/dist/browser/ui/index.js +671 -0
  29. package/dist/browser/ui/renderers/analytics.markdown.js +275 -0
  30. package/dist/browser/ui/renderers/index.js +275 -0
  31. package/dist/dashboard/dashboard.enum.d.ts +3 -8
  32. package/dist/dashboard/dashboard.enum.d.ts.map +1 -1
  33. package/dist/dashboard/dashboard.enum.js +31 -39
  34. package/dist/dashboard/dashboard.operation.d.ts +444 -450
  35. package/dist/dashboard/dashboard.operation.d.ts.map +1 -1
  36. package/dist/dashboard/dashboard.operation.js +284 -207
  37. package/dist/dashboard/dashboard.presentation.d.ts +3 -8
  38. package/dist/dashboard/dashboard.presentation.d.ts.map +1 -1
  39. package/dist/dashboard/dashboard.presentation.js +193 -85
  40. package/dist/dashboard/dashboard.schema.d.ts +289 -294
  41. package/dist/dashboard/dashboard.schema.d.ts.map +1 -1
  42. package/dist/dashboard/dashboard.schema.js +119 -228
  43. package/dist/dashboard/dashboard.test-spec.d.ts +4 -9
  44. package/dist/dashboard/dashboard.test-spec.d.ts.map +1 -1
  45. package/dist/dashboard/dashboard.test-spec.js +209 -228
  46. package/dist/dashboard/index.d.ts +7 -4
  47. package/dist/dashboard/index.d.ts.map +1 -0
  48. package/dist/dashboard/index.js +299 -4
  49. package/dist/dashboard.feature.d.ts +1 -6
  50. package/dist/dashboard.feature.d.ts.map +1 -1
  51. package/dist/dashboard.feature.js +83 -175
  52. package/dist/datasource/posthog-datasource.d.ts +15 -19
  53. package/dist/datasource/posthog-datasource.d.ts.map +1 -1
  54. package/dist/datasource/posthog-datasource.js +274 -238
  55. package/dist/docs/analytics-dashboard.docblock.d.ts +2 -1
  56. package/dist/docs/analytics-dashboard.docblock.d.ts.map +1 -0
  57. package/dist/docs/analytics-dashboard.docblock.js +45 -56
  58. package/dist/docs/index.d.ts +2 -1
  59. package/dist/docs/index.d.ts.map +1 -0
  60. package/dist/docs/index.js +104 -1
  61. package/dist/events.d.ts +109 -115
  62. package/dist/events.d.ts.map +1 -1
  63. package/dist/events.js +74 -120
  64. package/dist/example.d.ts +2 -6
  65. package/dist/example.d.ts.map +1 -1
  66. package/dist/example.js +41 -55
  67. package/dist/handlers/analytics.handlers.d.ts +110 -109
  68. package/dist/handlers/analytics.handlers.d.ts.map +1 -1
  69. package/dist/handlers/analytics.handlers.js +267 -298
  70. package/dist/handlers/index.d.ts +3 -3
  71. package/dist/handlers/index.d.ts.map +1 -0
  72. package/dist/handlers/index.js +571 -3
  73. package/dist/handlers/query.handlers.d.ts +7 -11
  74. package/dist/handlers/query.handlers.d.ts.map +1 -1
  75. package/dist/handlers/query.handlers.js +292 -7
  76. package/dist/index.d.ts +12 -13
  77. package/dist/index.d.ts.map +1 -0
  78. package/dist/index.js +1678 -14
  79. package/dist/node/dashboard/dashboard.enum.js +34 -0
  80. package/dist/node/dashboard/dashboard.operation.js +289 -0
  81. package/dist/node/dashboard/dashboard.presentation.js +197 -0
  82. package/dist/node/dashboard/dashboard.schema.js +126 -0
  83. package/dist/node/dashboard/dashboard.test-spec.js +213 -0
  84. package/dist/node/dashboard/index.js +299 -0
  85. package/dist/node/dashboard.feature.js +84 -0
  86. package/dist/node/datasource/posthog-datasource.js +289 -0
  87. package/dist/node/docs/analytics-dashboard.docblock.js +103 -0
  88. package/dist/node/docs/index.js +103 -0
  89. package/dist/node/events.js +81 -0
  90. package/dist/node/example.js +42 -0
  91. package/dist/node/handlers/analytics.handlers.js +278 -0
  92. package/dist/node/handlers/index.js +571 -0
  93. package/dist/node/handlers/query.handlers.js +294 -0
  94. package/dist/node/index.js +1677 -0
  95. package/dist/node/query/index.js +159 -0
  96. package/dist/node/query/query.enum.js +11 -0
  97. package/dist/node/query/query.operation.js +154 -0
  98. package/dist/node/query/query.presentation.js +119 -0
  99. package/dist/node/query/query.schema.js +70 -0
  100. package/dist/node/query/query.test-spec.js +113 -0
  101. package/dist/node/query-engine/index.js +491 -0
  102. package/dist/node/seeders/index.js +20 -0
  103. package/dist/node/ui/AnalyticsDashboard.js +394 -0
  104. package/dist/node/ui/hooks/index.js +69 -0
  105. package/dist/node/ui/hooks/useAnalyticsData.js +66 -0
  106. package/dist/node/ui/index.js +671 -0
  107. package/dist/node/ui/renderers/analytics.markdown.js +275 -0
  108. package/dist/node/ui/renderers/index.js +275 -0
  109. package/dist/query/index.d.ts +7 -4
  110. package/dist/query/index.d.ts.map +1 -0
  111. package/dist/query/index.js +159 -4
  112. package/dist/query/query.enum.d.ts +1 -6
  113. package/dist/query/query.enum.d.ts.map +1 -1
  114. package/dist/query/query.enum.js +10 -14
  115. package/dist/query/query.operation.d.ts +148 -154
  116. package/dist/query/query.operation.d.ts.map +1 -1
  117. package/dist/query/query.operation.js +151 -109
  118. package/dist/query/query.presentation.d.ts +2 -7
  119. package/dist/query/query.presentation.d.ts.map +1 -1
  120. package/dist/query/query.presentation.js +116 -56
  121. package/dist/query/query.schema.d.ts +121 -126
  122. package/dist/query/query.schema.d.ts.map +1 -1
  123. package/dist/query/query.schema.js +66 -152
  124. package/dist/query/query.test-spec.d.ts +2 -7
  125. package/dist/query/query.test-spec.d.ts.map +1 -1
  126. package/dist/query/query.test-spec.js +111 -121
  127. package/dist/query-engine/index.d.ts +84 -88
  128. package/dist/query-engine/index.d.ts.map +1 -1
  129. package/dist/query-engine/index.js +489 -188
  130. package/dist/seeders/index.d.ts +4 -8
  131. package/dist/seeders/index.d.ts.map +1 -1
  132. package/dist/seeders/index.js +18 -16
  133. package/dist/ui/AnalyticsDashboard.d.ts +1 -6
  134. package/dist/ui/AnalyticsDashboard.d.ts.map +1 -1
  135. package/dist/ui/AnalyticsDashboard.js +389 -259
  136. package/dist/ui/hooks/index.d.ts +2 -2
  137. package/dist/ui/hooks/index.d.ts.map +1 -0
  138. package/dist/ui/hooks/index.js +69 -4
  139. package/dist/ui/hooks/useAnalyticsData.d.ts +16 -20
  140. package/dist/ui/hooks/useAnalyticsData.d.ts.map +1 -1
  141. package/dist/ui/hooks/useAnalyticsData.js +63 -69
  142. package/dist/ui/index.d.ts +7 -6
  143. package/dist/ui/index.d.ts.map +1 -0
  144. package/dist/ui/index.js +671 -5
  145. package/dist/ui/renderers/analytics.markdown.d.ts +13 -14
  146. package/dist/ui/renderers/analytics.markdown.d.ts.map +1 -1
  147. package/dist/ui/renderers/analytics.markdown.js +266 -254
  148. package/dist/ui/renderers/index.d.ts +2 -2
  149. package/dist/ui/renderers/index.d.ts.map +1 -0
  150. package/dist/ui/renderers/index.js +275 -2
  151. package/package.json +328 -67
  152. package/dist/dashboard/dashboard.enum.js.map +0 -1
  153. package/dist/dashboard/dashboard.operation.js.map +0 -1
  154. package/dist/dashboard/dashboard.presentation.js.map +0 -1
  155. package/dist/dashboard/dashboard.schema.js.map +0 -1
  156. package/dist/dashboard/dashboard.test-spec.js.map +0 -1
  157. package/dist/dashboard.feature.js.map +0 -1
  158. package/dist/datasource/posthog-datasource.js.map +0 -1
  159. package/dist/docs/analytics-dashboard.docblock.js.map +0 -1
  160. package/dist/events.js.map +0 -1
  161. package/dist/example.js.map +0 -1
  162. package/dist/handlers/analytics.handlers.js.map +0 -1
  163. package/dist/handlers/query.handlers.js.map +0 -1
  164. package/dist/query/query.enum.js.map +0 -1
  165. package/dist/query/query.operation.js.map +0 -1
  166. package/dist/query/query.presentation.js.map +0 -1
  167. package/dist/query/query.schema.js.map +0 -1
  168. package/dist/query/query.test-spec.js.map +0 -1
  169. package/dist/query-engine/index.js.map +0 -1
  170. package/dist/seeders/index.js.map +0 -1
  171. package/dist/ui/AnalyticsDashboard.js.map +0 -1
  172. package/dist/ui/hooks/useAnalyticsData.js.map +0 -1
  173. package/dist/ui/renderers/analytics.markdown.js.map +0 -1
@@ -0,0 +1,1677 @@
1
+ // src/dashboard.feature.ts
2
+ import { defineFeature } from "@contractspec/lib.contracts";
3
+ var AnalyticsDashboardFeature = defineFeature({
4
+ meta: {
5
+ key: "analytics-dashboard",
6
+ version: "1.0.0",
7
+ title: "Analytics Dashboard",
8
+ description: "Analytics dashboards with customizable widgets and queries",
9
+ domain: "analytics",
10
+ owners: ["@analytics-dashboard"],
11
+ tags: ["analytics", "dashboards", "widgets", "queries"],
12
+ stability: "experimental"
13
+ },
14
+ operations: [
15
+ { key: "analytics.dashboard.create", version: "1.0.0" },
16
+ { key: "analytics.dashboard.list", version: "1.0.0" },
17
+ { key: "analytics.dashboard.get", version: "1.0.0" },
18
+ { key: "analytics.widget.add", version: "1.0.0" },
19
+ { key: "analytics.query.create", version: "1.0.0" },
20
+ { key: "analytics.query.execute", version: "1.0.0" }
21
+ ],
22
+ events: [
23
+ { key: "analytics.dashboard.created", version: "1.0.0" },
24
+ { key: "analytics.widget.added", version: "1.0.0" },
25
+ { key: "analytics.query.created", version: "1.0.0" }
26
+ ],
27
+ presentations: [
28
+ { key: "analytics.dashboard.viewList", version: "1.0.0" },
29
+ { key: "analytics.dashboard.view", version: "1.0.0" },
30
+ { key: "analytics.dashboard.editor", version: "1.0.0" },
31
+ { key: "analytics.query.list", version: "1.0.0" },
32
+ { key: "analytics.query.builder", version: "1.0.0" }
33
+ ],
34
+ opToPresentation: [
35
+ {
36
+ op: { key: "analytics.dashboard.list", version: "1.0.0" },
37
+ pres: { key: "analytics.dashboard.viewList", version: "1.0.0" }
38
+ },
39
+ {
40
+ op: { key: "analytics.dashboard.get", version: "1.0.0" },
41
+ pres: { key: "analytics.dashboard.view", version: "1.0.0" }
42
+ },
43
+ {
44
+ op: { key: "analytics.dashboard.create", version: "1.0.0" },
45
+ pres: { key: "analytics.dashboard.editor", version: "1.0.0" }
46
+ },
47
+ {
48
+ op: { key: "analytics.query.create", version: "1.0.0" },
49
+ pres: { key: "analytics.query.builder", version: "1.0.0" }
50
+ }
51
+ ],
52
+ presentationsTargets: [
53
+ {
54
+ key: "analytics.dashboard.viewList",
55
+ version: "1.0.0",
56
+ targets: ["react", "markdown", "application/json"]
57
+ },
58
+ {
59
+ key: "analytics.dashboard.view",
60
+ version: "1.0.0",
61
+ targets: ["react", "markdown"]
62
+ },
63
+ {
64
+ key: "analytics.dashboard.editor",
65
+ version: "1.0.0",
66
+ targets: ["react"]
67
+ },
68
+ {
69
+ key: "analytics.query.builder",
70
+ version: "1.0.0",
71
+ targets: ["react"]
72
+ }
73
+ ],
74
+ capabilities: {
75
+ requires: [
76
+ { key: "identity", version: "1.0.0" },
77
+ { key: "metering", version: "1.0.0" },
78
+ { key: "audit-trail", version: "1.0.0" }
79
+ ]
80
+ }
81
+ });
82
+
83
+ // src/datasource/posthog-datasource.ts
84
+ class PosthogQueryEngine {
85
+ reader;
86
+ defaultLimit;
87
+ constructor(reader, options = {}) {
88
+ this.reader = reader;
89
+ this.defaultLimit = options.defaultLimit ?? 100;
90
+ }
91
+ async execute(definition, params) {
92
+ const startTime = Date.now();
93
+ const validation = this.validateQuery(definition);
94
+ if (!validation.valid) {
95
+ return {
96
+ data: [],
97
+ columns: [],
98
+ rowCount: 0,
99
+ executionTimeMs: Date.now() - startTime,
100
+ cached: false,
101
+ error: validation.errors.join(", ")
102
+ };
103
+ }
104
+ if (!this.reader.queryHogQL) {
105
+ return {
106
+ data: [],
107
+ columns: [],
108
+ rowCount: 0,
109
+ executionTimeMs: Date.now() - startTime,
110
+ cached: false,
111
+ error: "Analytics reader does not support HogQL queries."
112
+ };
113
+ }
114
+ try {
115
+ const result = await this.executeHogQL(definition, params);
116
+ return {
117
+ data: result.data,
118
+ columns: result.columns,
119
+ rowCount: result.rowCount,
120
+ executionTimeMs: Date.now() - startTime,
121
+ cached: false
122
+ };
123
+ } catch (error) {
124
+ return {
125
+ data: [],
126
+ columns: [],
127
+ rowCount: 0,
128
+ executionTimeMs: Date.now() - startTime,
129
+ cached: false,
130
+ error: error instanceof Error ? error.message : "Unknown error"
131
+ };
132
+ }
133
+ }
134
+ validateQuery(definition) {
135
+ const errors = [];
136
+ if (definition.type === "SQL" && !definition.sql) {
137
+ errors.push("SQL query is missing.");
138
+ }
139
+ if (definition.type === "AGGREGATION" && !definition.aggregation) {
140
+ errors.push("Aggregation definition is missing.");
141
+ }
142
+ if (definition.type === "METRIC" && !definition.metricIds?.length) {
143
+ errors.push("Metric IDs are missing.");
144
+ }
145
+ if (definition.type === "CUSTOM" && !definition.custom?.handler) {
146
+ errors.push("Custom handler is missing.");
147
+ }
148
+ return { valid: errors.length === 0, errors };
149
+ }
150
+ async executeHogQL(definition, params) {
151
+ if (!this.reader.queryHogQL) {
152
+ throw new Error("Analytics reader does not support HogQL queries.");
153
+ }
154
+ if (definition.type === "SQL") {
155
+ const result = await this.reader.queryHogQL({
156
+ query: definition.sql ?? "",
157
+ values: params.parameters ?? {}
158
+ });
159
+ return mapHogqlResult(result);
160
+ }
161
+ if (definition.type === "AGGREGATION" && definition.aggregation) {
162
+ const { query, values } = buildAggregationQuery(definition.aggregation, params);
163
+ const result = await this.reader.queryHogQL({ query, values });
164
+ return mapHogqlResult(result);
165
+ }
166
+ if (definition.type === "METRIC" && definition.metricIds) {
167
+ const { query, values } = buildMetricQuery(definition.metricIds, params);
168
+ const result = await this.reader.queryHogQL({ query, values });
169
+ return mapHogqlResult(result);
170
+ }
171
+ throw new Error("Unsupported query type for PostHog datasource.");
172
+ }
173
+ }
174
+ function createPosthogQueryEngine(reader, options) {
175
+ return new PosthogQueryEngine(reader, options);
176
+ }
177
+ function buildMetricQuery(metricIds, params) {
178
+ const range = resolveDateRange(params);
179
+ const values = {
180
+ dateFrom: range?.from.toISOString(),
181
+ dateTo: range?.to.toISOString()
182
+ };
183
+ const metricClauses = metricIds.map((metricId, index) => {
184
+ values[`metric${index}`] = metricId;
185
+ return `event = {metric${index}}`;
186
+ });
187
+ const whereClauses = [
188
+ metricClauses.length ? `(${metricClauses.join(" or ")})` : "",
189
+ range ? "timestamp >= {dateFrom} and timestamp < {dateTo}" : ""
190
+ ].filter(Boolean).join(" and ");
191
+ return {
192
+ query: [
193
+ "select",
194
+ " event as metric,",
195
+ " count() as total",
196
+ "from events",
197
+ whereClauses ? `where ${whereClauses}` : "",
198
+ "group by metric"
199
+ ].filter(Boolean).join(`
200
+ `),
201
+ values
202
+ };
203
+ }
204
+ function buildAggregationQuery(aggregation, params) {
205
+ const measures = aggregation.measures.map((measure) => ({
206
+ ...measure,
207
+ expression: buildMeasureExpression(measure.field, measure.aggregation)
208
+ }));
209
+ const dimensions = aggregation.dimensions.map((dimension) => ({
210
+ ...dimension,
211
+ expression: buildDimensionExpression(dimension.field, dimension.type, dimension.granularity)
212
+ }));
213
+ const selections = [
214
+ ...dimensions.map((dimension) => `${dimension.expression} as ${dimension.name}`),
215
+ ...measures.map((measure) => `${measure.expression} as ${measure.name}`)
216
+ ];
217
+ const values = {};
218
+ const filters = buildFilterClauses(aggregation, params, values);
219
+ const limit = aggregation.limit ?? 100;
220
+ const orderBy = aggregation.orderBy?.length ? `order by ${aggregation.orderBy.map((order) => `${order.field} ${order.direction}`).join(", ")}` : "";
221
+ return {
222
+ query: [
223
+ "select",
224
+ ` ${selections.join(`,
225
+ `)}`,
226
+ `from ${aggregation.source}`,
227
+ filters.length ? `where ${filters.join(" and ")}` : "",
228
+ dimensions.length ? `group by ${dimensions.map((d) => d.name).join(", ")}` : "",
229
+ orderBy,
230
+ `limit ${limit}`
231
+ ].filter(Boolean).join(`
232
+ `),
233
+ values
234
+ };
235
+ }
236
+ function buildMeasureExpression(field, aggregation) {
237
+ switch (aggregation) {
238
+ case "COUNT":
239
+ return field === "*" ? "count()" : `count(${field})`;
240
+ case "COUNT_DISTINCT":
241
+ return `countDistinct(${field})`;
242
+ case "SUM":
243
+ return `sum(${field})`;
244
+ case "AVG":
245
+ return `avg(${field})`;
246
+ case "MIN":
247
+ return `min(${field})`;
248
+ case "MAX":
249
+ return `max(${field})`;
250
+ default:
251
+ return `count(${field})`;
252
+ }
253
+ }
254
+ function buildDimensionExpression(field, type, granularity) {
255
+ if (type === "TIME") {
256
+ switch (granularity) {
257
+ case "HOUR":
258
+ return `toStartOfHour(${field})`;
259
+ case "WEEK":
260
+ return `toStartOfWeek(${field})`;
261
+ case "MONTH":
262
+ return `toStartOfMonth(${field})`;
263
+ case "YEAR":
264
+ return `toStartOfYear(${field})`;
265
+ case "DAY":
266
+ default:
267
+ return `toStartOfDay(${field})`;
268
+ }
269
+ }
270
+ return field;
271
+ }
272
+ function buildFilterClauses(aggregation, params, values) {
273
+ const clauses = [];
274
+ const range = resolveDateRange(params);
275
+ if (range) {
276
+ values.dateFrom = range.from.toISOString();
277
+ values.dateTo = range.to.toISOString();
278
+ clauses.push(`timestamp >= {dateFrom} and timestamp < {dateTo}`);
279
+ }
280
+ aggregation.filters?.forEach((filter, index) => {
281
+ const key = `filter${index}`;
282
+ switch (filter.operator) {
283
+ case "eq":
284
+ values[key] = filter.value;
285
+ clauses.push(`${filter.field} = {${key}}`);
286
+ break;
287
+ case "neq":
288
+ values[key] = filter.value;
289
+ clauses.push(`${filter.field} != {${key}}`);
290
+ break;
291
+ case "gt":
292
+ values[key] = filter.value;
293
+ clauses.push(`${filter.field} > {${key}}`);
294
+ break;
295
+ case "gte":
296
+ values[key] = filter.value;
297
+ clauses.push(`${filter.field} >= {${key}}`);
298
+ break;
299
+ case "lt":
300
+ values[key] = filter.value;
301
+ clauses.push(`${filter.field} < {${key}}`);
302
+ break;
303
+ case "lte":
304
+ values[key] = filter.value;
305
+ clauses.push(`${filter.field} <= {${key}}`);
306
+ break;
307
+ case "contains":
308
+ values[key] = filter.value;
309
+ clauses.push(`${filter.field} LIKE '%' || {${key}} || '%'`);
310
+ break;
311
+ case "between": {
312
+ if (Array.isArray(filter.value) && filter.value.length >= 2) {
313
+ values[`${key}Start`] = filter.value[0];
314
+ values[`${key}End`] = filter.value[1];
315
+ clauses.push(`${filter.field} BETWEEN {${key}Start} AND {${key}End}`);
316
+ }
317
+ break;
318
+ }
319
+ case "in":
320
+ case "nin":
321
+ if (Array.isArray(filter.value)) {
322
+ const placeholders = [];
323
+ filter.value.forEach((value, valueIndex) => {
324
+ const valueKey = `${key}_${valueIndex}`;
325
+ values[valueKey] = value;
326
+ placeholders.push(`{${valueKey}}`);
327
+ });
328
+ if (placeholders.length) {
329
+ clauses.push(`${filter.field} ${filter.operator === "in" ? "IN" : "NOT IN"} (${placeholders.join(", ")})`);
330
+ }
331
+ }
332
+ break;
333
+ default:
334
+ break;
335
+ }
336
+ });
337
+ return clauses;
338
+ }
339
+ function resolveDateRange(params) {
340
+ const range = params.dateRange;
341
+ if (!range)
342
+ return null;
343
+ return { from: range.start, to: range.end };
344
+ }
345
+ function mapHogqlResult(result) {
346
+ if (!Array.isArray(result.results) || !Array.isArray(result.columns)) {
347
+ return { data: [], columns: [], rowCount: 0 };
348
+ }
349
+ const columns = result.columns.map((name) => ({
350
+ name,
351
+ type: "STRING"
352
+ }));
353
+ const data = result.results.map((row) => {
354
+ if (!Array.isArray(row))
355
+ return {};
356
+ const record = {};
357
+ result.columns?.forEach((column, index) => {
358
+ record[column] = row[index];
359
+ });
360
+ return record;
361
+ });
362
+ return {
363
+ data,
364
+ columns,
365
+ rowCount: data.length
366
+ };
367
+ }
368
+
369
+ // src/handlers/analytics.handlers.ts
370
+ import { web } from "@contractspec/lib.runtime-sandbox";
371
+ var { generateId } = web;
372
+ function rowToDashboard(row) {
373
+ return {
374
+ id: row.id,
375
+ projectId: row.projectId,
376
+ organizationId: row.organizationId,
377
+ name: row.name,
378
+ slug: row.slug,
379
+ description: row.description ?? undefined,
380
+ status: row.status,
381
+ refreshInterval: row.refreshInterval,
382
+ isPublic: row.isPublic === 1,
383
+ shareToken: row.shareToken ?? undefined,
384
+ createdAt: new Date(row.createdAt),
385
+ updatedAt: new Date(row.updatedAt)
386
+ };
387
+ }
388
+ function rowToWidget(row) {
389
+ return {
390
+ id: row.id,
391
+ dashboardId: row.dashboardId,
392
+ name: row.name,
393
+ type: row.type,
394
+ gridX: row.gridX,
395
+ gridY: row.gridY,
396
+ gridWidth: row.gridWidth,
397
+ gridHeight: row.gridHeight,
398
+ queryId: row.queryId ?? undefined,
399
+ config: row.config ? JSON.parse(row.config) : undefined,
400
+ createdAt: new Date(row.createdAt),
401
+ updatedAt: new Date(row.updatedAt)
402
+ };
403
+ }
404
+ function rowToQuery(row) {
405
+ return {
406
+ id: row.id,
407
+ projectId: row.projectId,
408
+ organizationId: row.organizationId,
409
+ name: row.name,
410
+ description: row.description ?? undefined,
411
+ type: row.type,
412
+ definition: JSON.parse(row.definition),
413
+ sql: row.sql ?? undefined,
414
+ cacheTtlSeconds: row.cacheTtlSeconds,
415
+ isShared: row.isShared === 1,
416
+ createdAt: new Date(row.createdAt),
417
+ updatedAt: new Date(row.updatedAt)
418
+ };
419
+ }
420
+ function createAnalyticsHandlers(db) {
421
+ async function listDashboards(input) {
422
+ const { projectId, status, search, limit = 20, offset = 0 } = input;
423
+ let whereClause = "WHERE projectId = ?";
424
+ const params = [projectId];
425
+ if (status && status !== "all") {
426
+ whereClause += " AND status = ?";
427
+ params.push(status);
428
+ }
429
+ if (search) {
430
+ whereClause += " AND (name LIKE ? OR description LIKE ?)";
431
+ params.push(`%${search}%`, `%${search}%`);
432
+ }
433
+ const countResult = (await db.query(`SELECT COUNT(*) as count FROM analytics_dashboard ${whereClause}`, params)).rows;
434
+ const total = countResult[0]?.count ?? 0;
435
+ const rows = (await db.query(`SELECT * FROM analytics_dashboard ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
436
+ return {
437
+ dashboards: rows.map(rowToDashboard),
438
+ total
439
+ };
440
+ }
441
+ async function createDashboard(input, context) {
442
+ const id = generateId("dash");
443
+ const now = new Date().toISOString();
444
+ await db.execute(`INSERT INTO analytics_dashboard (id, projectId, organizationId, name, slug, description, status, refreshInterval, isPublic, createdAt, updatedAt)
445
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
446
+ id,
447
+ context.projectId,
448
+ context.organizationId,
449
+ input.name,
450
+ input.slug,
451
+ input.description ?? null,
452
+ "DRAFT",
453
+ input.refreshInterval ?? "NONE",
454
+ 0,
455
+ now,
456
+ now
457
+ ]);
458
+ const rows = (await db.query(`SELECT * FROM analytics_dashboard WHERE id = ?`, [id])).rows;
459
+ return rowToDashboard(rows[0]);
460
+ }
461
+ async function getDashboard(input) {
462
+ let whereClause = "";
463
+ const params = [];
464
+ if (input.dashboardId) {
465
+ whereClause = "WHERE id = ?";
466
+ params.push(input.dashboardId);
467
+ } else if (input.slug) {
468
+ whereClause = "WHERE slug = ?";
469
+ params.push(input.slug);
470
+ } else if (input.shareToken) {
471
+ whereClause = "WHERE shareToken = ?";
472
+ params.push(input.shareToken);
473
+ } else {
474
+ return null;
475
+ }
476
+ const rows = (await db.query(`SELECT * FROM analytics_dashboard ${whereClause}`, params)).rows;
477
+ return rows[0] ? rowToDashboard(rows[0]) : null;
478
+ }
479
+ async function updateDashboard(dashboardId, updates) {
480
+ const now = new Date().toISOString();
481
+ const setClauses = ["updatedAt = ?"];
482
+ const params = [now];
483
+ if (updates.name !== undefined) {
484
+ setClauses.push("name = ?");
485
+ params.push(updates.name);
486
+ }
487
+ if (updates.description !== undefined) {
488
+ setClauses.push("description = ?");
489
+ params.push(updates.description);
490
+ }
491
+ if (updates.status !== undefined) {
492
+ setClauses.push("status = ?");
493
+ params.push(updates.status);
494
+ }
495
+ if (updates.refreshInterval !== undefined) {
496
+ setClauses.push("refreshInterval = ?");
497
+ params.push(updates.refreshInterval);
498
+ }
499
+ if (updates.isPublic !== undefined) {
500
+ setClauses.push("isPublic = ?");
501
+ params.push(updates.isPublic ? 1 : 0);
502
+ if (updates.isPublic) {
503
+ setClauses.push("shareToken = ?");
504
+ params.push(generateId("share"));
505
+ } else {
506
+ setClauses.push("shareToken = NULL");
507
+ }
508
+ }
509
+ params.push(dashboardId);
510
+ await db.execute(`UPDATE analytics_dashboard SET ${setClauses.join(", ")} WHERE id = ?`, params);
511
+ const rows = (await db.query(`SELECT * FROM analytics_dashboard WHERE id = ?`, [
512
+ dashboardId
513
+ ])).rows;
514
+ return rowToDashboard(rows[0]);
515
+ }
516
+ async function getWidgets(dashboardId) {
517
+ const rows = (await db.query(`SELECT * FROM analytics_widget WHERE dashboardId = ? ORDER BY gridY, gridX`, [dashboardId])).rows;
518
+ return rows.map(rowToWidget);
519
+ }
520
+ async function addWidget(input) {
521
+ const id = generateId("widget");
522
+ const now = new Date().toISOString();
523
+ await db.execute(`INSERT INTO analytics_widget (id, dashboardId, name, type, gridX, gridY, gridWidth, gridHeight, queryId, config, createdAt, updatedAt)
524
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
525
+ id,
526
+ input.dashboardId,
527
+ input.name,
528
+ input.type,
529
+ input.gridX ?? 0,
530
+ input.gridY ?? 0,
531
+ input.gridWidth ?? 6,
532
+ input.gridHeight ?? 4,
533
+ input.queryId ?? null,
534
+ input.config ? JSON.stringify(input.config) : null,
535
+ now,
536
+ now
537
+ ]);
538
+ const rows = (await db.query(`SELECT * FROM analytics_widget WHERE id = ?`, [id])).rows;
539
+ return rowToWidget(rows[0]);
540
+ }
541
+ async function updateWidget(widgetId, updates) {
542
+ const now = new Date().toISOString();
543
+ const setClauses = ["updatedAt = ?"];
544
+ const params = [now];
545
+ if (updates.name !== undefined) {
546
+ setClauses.push("name = ?");
547
+ params.push(updates.name);
548
+ }
549
+ if (updates.gridX !== undefined) {
550
+ setClauses.push("gridX = ?");
551
+ params.push(updates.gridX);
552
+ }
553
+ if (updates.gridY !== undefined) {
554
+ setClauses.push("gridY = ?");
555
+ params.push(updates.gridY);
556
+ }
557
+ if (updates.gridWidth !== undefined) {
558
+ setClauses.push("gridWidth = ?");
559
+ params.push(updates.gridWidth);
560
+ }
561
+ if (updates.gridHeight !== undefined) {
562
+ setClauses.push("gridHeight = ?");
563
+ params.push(updates.gridHeight);
564
+ }
565
+ if (updates.queryId !== undefined) {
566
+ setClauses.push("queryId = ?");
567
+ params.push(updates.queryId ?? null);
568
+ }
569
+ if (updates.config !== undefined) {
570
+ setClauses.push("config = ?");
571
+ params.push(updates.config ? JSON.stringify(updates.config) : null);
572
+ }
573
+ params.push(widgetId);
574
+ await db.execute(`UPDATE analytics_widget SET ${setClauses.join(", ")} WHERE id = ?`, params);
575
+ const rows = (await db.query(`SELECT * FROM analytics_widget WHERE id = ?`, [widgetId])).rows;
576
+ return rowToWidget(rows[0]);
577
+ }
578
+ async function deleteWidget(widgetId) {
579
+ await db.execute(`DELETE FROM analytics_widget WHERE id = ?`, [widgetId]);
580
+ }
581
+ async function listQueries(input) {
582
+ const { projectId, type, isShared, search, limit = 20, offset = 0 } = input;
583
+ let whereClause = "WHERE projectId = ?";
584
+ const params = [projectId];
585
+ if (type && type !== "all") {
586
+ whereClause += " AND type = ?";
587
+ params.push(type);
588
+ }
589
+ if (isShared !== undefined) {
590
+ whereClause += " AND isShared = ?";
591
+ params.push(isShared ? 1 : 0);
592
+ }
593
+ if (search) {
594
+ whereClause += " AND (name LIKE ? OR description LIKE ?)";
595
+ params.push(`%${search}%`, `%${search}%`);
596
+ }
597
+ const countResult = (await db.query(`SELECT COUNT(*) as count FROM analytics_query ${whereClause}`, params)).rows;
598
+ const total = countResult[0]?.count ?? 0;
599
+ const rows = (await db.query(`SELECT * FROM analytics_query ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
600
+ return {
601
+ queries: rows.map(rowToQuery),
602
+ total
603
+ };
604
+ }
605
+ async function createQuery(input, context) {
606
+ const id = generateId("query");
607
+ const now = new Date().toISOString();
608
+ await db.execute(`INSERT INTO analytics_query (id, projectId, organizationId, name, description, type, definition, sql, cacheTtlSeconds, isShared, createdAt, updatedAt)
609
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
610
+ id,
611
+ context.projectId,
612
+ context.organizationId,
613
+ input.name,
614
+ input.description ?? null,
615
+ input.type,
616
+ JSON.stringify(input.definition),
617
+ input.sql ?? null,
618
+ input.cacheTtlSeconds ?? 300,
619
+ input.isShared ? 1 : 0,
620
+ now,
621
+ now
622
+ ]);
623
+ const rows = (await db.query(`SELECT * FROM analytics_query WHERE id = ?`, [id])).rows;
624
+ return rowToQuery(rows[0]);
625
+ }
626
+ async function getQuery(queryId) {
627
+ const rows = (await db.query(`SELECT * FROM analytics_query WHERE id = ?`, [queryId])).rows;
628
+ return rows[0] ? rowToQuery(rows[0]) : null;
629
+ }
630
+ return {
631
+ listDashboards,
632
+ createDashboard,
633
+ getDashboard,
634
+ updateDashboard,
635
+ getWidgets,
636
+ addWidget,
637
+ updateWidget,
638
+ deleteWidget,
639
+ listQueries,
640
+ createQuery,
641
+ getQuery
642
+ };
643
+ }
644
+
645
+ // src/query/query.enum.ts
646
+ import { defineEnum } from "@contractspec/lib.schema";
647
+ var QueryTypeEnum = defineEnum("QueryType", [
648
+ "SQL",
649
+ "METRIC",
650
+ "AGGREGATION",
651
+ "CUSTOM"
652
+ ]);
653
+
654
+ // src/query/query.schema.ts
655
+ import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
656
+ var QueryModel = defineSchemaModel({
657
+ name: "QueryModel",
658
+ fields: {
659
+ id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
660
+ name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
661
+ description: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
662
+ type: { type: QueryTypeEnum, isOptional: false },
663
+ definition: { type: ScalarTypeEnum.JSON(), isOptional: false },
664
+ sql: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
665
+ cacheTtlSeconds: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
666
+ isShared: { type: ScalarTypeEnum.Boolean(), isOptional: false },
667
+ createdAt: { type: ScalarTypeEnum.DateTime(), isOptional: false }
668
+ }
669
+ });
670
+ var QueryResultModel = defineSchemaModel({
671
+ name: "QueryResultModel",
672
+ fields: {
673
+ queryId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
674
+ data: { type: ScalarTypeEnum.JSON(), isOptional: false },
675
+ columns: { type: ScalarTypeEnum.JSON(), isOptional: false },
676
+ rowCount: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
677
+ executionTimeMs: { type: ScalarTypeEnum.Int_unsecure(), isOptional: false },
678
+ cachedAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
679
+ error: { type: ScalarTypeEnum.String_unsecure(), isOptional: true }
680
+ }
681
+ });
682
+ var CreateQueryInputModel = defineSchemaModel({
683
+ name: "CreateQueryInput",
684
+ fields: {
685
+ name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
686
+ description: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
687
+ type: { type: QueryTypeEnum, isOptional: false },
688
+ definition: { type: ScalarTypeEnum.JSON(), isOptional: false },
689
+ sql: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
690
+ metricIds: {
691
+ type: ScalarTypeEnum.String_unsecure(),
692
+ isArray: true,
693
+ isOptional: true
694
+ },
695
+ cacheTtlSeconds: { type: ScalarTypeEnum.Int_unsecure(), isOptional: true },
696
+ isShared: { type: ScalarTypeEnum.Boolean(), isOptional: true }
697
+ }
698
+ });
699
+ var ExecuteQueryInputModel = defineSchemaModel({
700
+ name: "ExecuteQueryInput",
701
+ fields: {
702
+ queryId: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
703
+ parameters: { type: ScalarTypeEnum.JSON(), isOptional: true },
704
+ dateRange: { type: ScalarTypeEnum.JSON(), isOptional: true },
705
+ filters: { type: ScalarTypeEnum.JSON(), isOptional: true },
706
+ forceRefresh: { type: ScalarTypeEnum.Boolean(), isOptional: true }
707
+ }
708
+ });
709
+
710
+ // src/query/query.operation.ts
711
+ import {
712
+ defineCommand,
713
+ defineQuery
714
+ } from "@contractspec/lib.contracts/operations";
715
+ var OWNERS = ["@example.analytics-dashboard"];
716
+ var CreateQueryContract = defineCommand({
717
+ meta: {
718
+ key: "analytics.query.create",
719
+ version: "1.0.0",
720
+ stability: "stable",
721
+ owners: [...OWNERS],
722
+ tags: ["analytics", "query", "create"],
723
+ description: "Create a data query.",
724
+ goal: "Define reusable data queries.",
725
+ context: "Query builder."
726
+ },
727
+ io: { input: CreateQueryInputModel, output: QueryModel },
728
+ policy: { auth: "user" },
729
+ sideEffects: {
730
+ emits: [
731
+ {
732
+ key: "analytics.query.created",
733
+ version: "1.0.0",
734
+ stability: "stable",
735
+ owners: [...OWNERS],
736
+ tags: ["analytics", "query", "created"],
737
+ when: "Query created",
738
+ payload: QueryModel
739
+ }
740
+ ],
741
+ audit: ["analytics.query.created"]
742
+ },
743
+ acceptance: {
744
+ scenarios: [
745
+ {
746
+ key: "create-query-happy-path",
747
+ given: ["User is authenticated"],
748
+ when: ["User submits valid query definition"],
749
+ then: ["Query is created", "QueryCreated event is emitted"]
750
+ }
751
+ ],
752
+ examples: [
753
+ {
754
+ key: "create-sql-query",
755
+ input: {
756
+ name: "Monthly Revenue",
757
+ sql: "SELECT SUM(amount) FROM orders WHERE date >= :startDate"
758
+ },
759
+ output: { id: "query-123", name: "Monthly Revenue", type: "sql" }
760
+ }
761
+ ]
762
+ }
763
+ });
764
+ var ExecuteQueryContract = defineQuery({
765
+ meta: {
766
+ key: "analytics.query.execute",
767
+ version: "1.0.0",
768
+ stability: "stable",
769
+ owners: [...OWNERS],
770
+ tags: ["analytics", "query", "execute"],
771
+ description: "Execute a data query.",
772
+ goal: "Fetch data for visualizations.",
773
+ context: "Dashboard rendering."
774
+ },
775
+ io: { input: ExecuteQueryInputModel, output: QueryResultModel },
776
+ policy: { auth: "user" },
777
+ acceptance: {
778
+ scenarios: [
779
+ {
780
+ key: "execute-query-happy-path",
781
+ given: ["Query exists"],
782
+ when: ["User executes query with parameters"],
783
+ then: ["Query results are returned"]
784
+ }
785
+ ],
786
+ examples: [
787
+ {
788
+ key: "execute-with-params",
789
+ input: { queryId: "query-123", params: { startDate: "2025-01-01" } },
790
+ output: { columns: ["total"], rows: [{ total: 50000 }], rowCount: 1 }
791
+ }
792
+ ]
793
+ }
794
+ });
795
+ // src/ui/renderers/analytics.markdown.ts
796
+ var mockDashboards = [
797
+ {
798
+ id: "dash-1",
799
+ name: "Sales Overview",
800
+ slug: "sales-overview",
801
+ status: "PUBLISHED",
802
+ widgetCount: 8,
803
+ viewCount: 1250,
804
+ lastViewedAt: "2024-01-16T12:00:00Z"
805
+ },
806
+ {
807
+ id: "dash-2",
808
+ name: "User Engagement",
809
+ slug: "user-engagement",
810
+ status: "PUBLISHED",
811
+ widgetCount: 6,
812
+ viewCount: 890,
813
+ lastViewedAt: "2024-01-16T10:00:00Z"
814
+ },
815
+ {
816
+ id: "dash-3",
817
+ name: "Product Analytics",
818
+ slug: "product-analytics",
819
+ status: "PUBLISHED",
820
+ widgetCount: 10,
821
+ viewCount: 560,
822
+ lastViewedAt: "2024-01-15T14:00:00Z"
823
+ },
824
+ {
825
+ id: "dash-4",
826
+ name: "Finance Report",
827
+ slug: "finance-report",
828
+ status: "DRAFT",
829
+ widgetCount: 4,
830
+ viewCount: 0,
831
+ lastViewedAt: null
832
+ }
833
+ ];
834
+ var mockWidgets = [
835
+ {
836
+ id: "w-1",
837
+ dashboardId: "dash-1",
838
+ name: "Total Revenue",
839
+ type: "METRIC",
840
+ value: 125000,
841
+ change: 12.5
842
+ },
843
+ {
844
+ id: "w-2",
845
+ dashboardId: "dash-1",
846
+ name: "Active Users",
847
+ type: "METRIC",
848
+ value: 4500,
849
+ change: 8.2
850
+ },
851
+ {
852
+ id: "w-3",
853
+ dashboardId: "dash-1",
854
+ name: "Revenue Trend",
855
+ type: "LINE_CHART",
856
+ dataPoints: 30
857
+ },
858
+ {
859
+ id: "w-4",
860
+ dashboardId: "dash-1",
861
+ name: "Top Products",
862
+ type: "BAR_CHART",
863
+ dataPoints: 10
864
+ },
865
+ {
866
+ id: "w-5",
867
+ dashboardId: "dash-2",
868
+ name: "Daily Active Users",
869
+ type: "LINE_CHART",
870
+ dataPoints: 30
871
+ },
872
+ {
873
+ id: "w-6",
874
+ dashboardId: "dash-2",
875
+ name: "Session Duration",
876
+ type: "METRIC",
877
+ value: 245,
878
+ change: -3.1
879
+ }
880
+ ];
881
+ var mockQueries = [
882
+ {
883
+ id: "q-1",
884
+ name: "Monthly Revenue",
885
+ type: "AGGREGATION",
886
+ isShared: true,
887
+ executionCount: 1500
888
+ },
889
+ {
890
+ id: "q-2",
891
+ name: "User Growth",
892
+ type: "METRIC",
893
+ isShared: true,
894
+ executionCount: 890
895
+ },
896
+ {
897
+ id: "q-3",
898
+ name: "Product Sales",
899
+ type: "SQL",
900
+ isShared: false,
901
+ executionCount: 340
902
+ },
903
+ {
904
+ id: "q-4",
905
+ name: "Conversion Funnel",
906
+ type: "AGGREGATION",
907
+ isShared: true,
908
+ executionCount: 450
909
+ }
910
+ ];
911
+ function formatNumber(value) {
912
+ if (value >= 1e6) {
913
+ return `${(value / 1e6).toFixed(1)}M`;
914
+ }
915
+ if (value >= 1000) {
916
+ return `${(value / 1000).toFixed(1)}K`;
917
+ }
918
+ return value.toString();
919
+ }
920
+ function formatChange(change) {
921
+ const icon = change >= 0 ? "\uD83D\uDCC8" : "\uD83D\uDCC9";
922
+ const sign = change >= 0 ? "+" : "";
923
+ return `${icon} ${sign}${change.toFixed(1)}%`;
924
+ }
925
+ var analyticsDashboardMarkdownRenderer = {
926
+ target: "markdown",
927
+ render: async (desc) => {
928
+ if (desc.source.type !== "component" || desc.source.componentKey !== "AnalyticsDashboard") {
929
+ throw new Error("analyticsDashboardMarkdownRenderer: not AnalyticsDashboard");
930
+ }
931
+ const dashboards = mockDashboards;
932
+ const widgets = mockWidgets;
933
+ const queries = mockQueries;
934
+ const dashboard = dashboards[0];
935
+ if (!dashboard) {
936
+ return {
937
+ mimeType: "text/markdown",
938
+ body: `# No Dashboards
939
+
940
+ No dashboards available.`
941
+ };
942
+ }
943
+ const dashboardWidgets = widgets.filter((w) => w.dashboardId === dashboard.id);
944
+ const publishedDashboards = dashboards.filter((d) => d.status === "PUBLISHED");
945
+ const totalViews = dashboards.reduce((sum, d) => sum + d.viewCount, 0);
946
+ const sharedQueries = queries.filter((q) => q.isShared);
947
+ const lines = [
948
+ `# ${dashboard.name}`,
949
+ "",
950
+ "> Analytics dashboard overview",
951
+ "",
952
+ "## Key Metrics",
953
+ ""
954
+ ];
955
+ const metricWidgets = dashboardWidgets.filter((w) => w.type === "METRIC");
956
+ for (const widget of metricWidgets) {
957
+ const w = widget;
958
+ lines.push(`### ${w.name}`);
959
+ lines.push(`**${formatNumber(w.value)}** ${formatChange(w.change)}`);
960
+ lines.push("");
961
+ }
962
+ lines.push("## Visualizations");
963
+ lines.push("");
964
+ const chartWidgets = dashboardWidgets.filter((w) => w.type !== "METRIC");
965
+ for (const widget of chartWidgets) {
966
+ const w = widget;
967
+ lines.push(`- **${w.name}** (${w.type.replace("_", " ")}) - ${w.dataPoints} data points`);
968
+ }
969
+ lines.push("");
970
+ lines.push("## Dashboard Stats");
971
+ lines.push("");
972
+ lines.push("| Metric | Value |");
973
+ lines.push("|--------|-------|");
974
+ lines.push(`| Total Dashboards | ${dashboards.length} |`);
975
+ lines.push(`| Published | ${publishedDashboards.length} |`);
976
+ lines.push(`| Total Views | ${totalViews.toLocaleString()} |`);
977
+ lines.push(`| Shared Queries | ${sharedQueries.length} |`);
978
+ return {
979
+ mimeType: "text/markdown",
980
+ body: lines.join(`
981
+ `)
982
+ };
983
+ }
984
+ };
985
+ var dashboardListMarkdownRenderer = {
986
+ target: "markdown",
987
+ render: async (desc) => {
988
+ if (desc.source.type !== "component" || desc.source.componentKey !== "DashboardList") {
989
+ throw new Error("dashboardListMarkdownRenderer: not DashboardList");
990
+ }
991
+ const dashboards = mockDashboards;
992
+ const lines = [
993
+ "# Dashboards",
994
+ "",
995
+ "> Browse and manage analytics dashboards",
996
+ "",
997
+ "| Dashboard | Widgets | Views | Status | Last Viewed |",
998
+ "|-----------|---------|-------|--------|-------------|"
999
+ ];
1000
+ for (const dashboard of dashboards) {
1001
+ const lastViewed = dashboard.lastViewedAt ? new Date(dashboard.lastViewedAt).toLocaleDateString() : "Never";
1002
+ const statusIcon = dashboard.status === "PUBLISHED" ? "\uD83D\uDFE2" : "⚫";
1003
+ lines.push(`| [${dashboard.name}](/dashboards/${dashboard.slug}) | ${dashboard.widgetCount} | ${dashboard.viewCount.toLocaleString()} | ${statusIcon} ${dashboard.status} | ${lastViewed} |`);
1004
+ }
1005
+ lines.push("");
1006
+ lines.push("## Quick Actions");
1007
+ lines.push("");
1008
+ lines.push("- **Create Dashboard** - Start with a blank canvas");
1009
+ lines.push("- **Import Template** - Use a pre-built template");
1010
+ lines.push("- **Clone Dashboard** - Duplicate an existing dashboard");
1011
+ return {
1012
+ mimeType: "text/markdown",
1013
+ body: lines.join(`
1014
+ `)
1015
+ };
1016
+ }
1017
+ };
1018
+ var queryBuilderMarkdownRenderer = {
1019
+ target: "markdown",
1020
+ render: async (desc) => {
1021
+ if (desc.source.type !== "component" || desc.source.componentKey !== "QueryBuilder") {
1022
+ throw new Error("queryBuilderMarkdownRenderer: not QueryBuilder");
1023
+ }
1024
+ const queries = mockQueries;
1025
+ const lines = [
1026
+ "# Query Builder",
1027
+ "",
1028
+ "> Create and manage data queries",
1029
+ "",
1030
+ "## Saved Queries",
1031
+ "",
1032
+ "| Query | Type | Shared | Executions |",
1033
+ "|-------|------|--------|------------|"
1034
+ ];
1035
+ for (const query of queries) {
1036
+ const sharedIcon = query.isShared ? "\uD83C\uDF10" : "\uD83D\uDD12";
1037
+ lines.push(`| ${query.name} | ${query.type} | ${sharedIcon} | ${query.executionCount.toLocaleString()} |`);
1038
+ }
1039
+ lines.push("");
1040
+ lines.push("## Query Types");
1041
+ lines.push("");
1042
+ lines.push("### METRIC");
1043
+ lines.push("Query usage metrics from the metering system.");
1044
+ lines.push("");
1045
+ lines.push("### AGGREGATION");
1046
+ lines.push("Build aggregations with measures and dimensions without writing SQL.");
1047
+ lines.push("");
1048
+ lines.push("### SQL");
1049
+ lines.push("Write custom SQL queries for advanced analysis.");
1050
+ lines.push("");
1051
+ lines.push("## Features");
1052
+ lines.push("");
1053
+ lines.push("- Visual query builder");
1054
+ lines.push("- Auto-complete for fields and functions");
1055
+ lines.push("- Query validation and optimization");
1056
+ lines.push("- Result caching");
1057
+ lines.push("- Query sharing and collaboration");
1058
+ return {
1059
+ mimeType: "text/markdown",
1060
+ body: lines.join(`
1061
+ `)
1062
+ };
1063
+ }
1064
+ };
1065
+ // src/ui/hooks/useAnalyticsData.ts
1066
+ import { useCallback, useEffect, useState } from "react";
1067
+ import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
1068
+ "use client";
1069
+ function useAnalyticsData(projectId = "local-project") {
1070
+ const { handlers } = useTemplateRuntime();
1071
+ const analytics = handlers.analytics;
1072
+ const [dashboards, setDashboards] = useState([]);
1073
+ const [queries, setQueries] = useState([]);
1074
+ const [selectedDashboard, setSelectedDashboard] = useState(null);
1075
+ const [widgets, setWidgets] = useState([]);
1076
+ const [loading, setLoading] = useState(true);
1077
+ const [error, setError] = useState(null);
1078
+ const fetchData = useCallback(async () => {
1079
+ try {
1080
+ setLoading(true);
1081
+ setError(null);
1082
+ const [dashResult, queryResult] = await Promise.all([
1083
+ analytics.listDashboards({ projectId, limit: 100 }),
1084
+ analytics.listQueries({ projectId, limit: 100 })
1085
+ ]);
1086
+ setDashboards(dashResult.dashboards);
1087
+ setQueries(queryResult.queries);
1088
+ if (dashResult.dashboards.length > 0 && !selectedDashboard) {
1089
+ const first = dashResult.dashboards[0];
1090
+ if (first) {
1091
+ setSelectedDashboard(first);
1092
+ const dashboardWidgets = await analytics.getWidgets(first.id);
1093
+ setWidgets(dashboardWidgets);
1094
+ }
1095
+ }
1096
+ } catch (err) {
1097
+ setError(err instanceof Error ? err : new Error("Failed to load analytics"));
1098
+ } finally {
1099
+ setLoading(false);
1100
+ }
1101
+ }, [analytics, projectId, selectedDashboard]);
1102
+ useEffect(() => {
1103
+ fetchData();
1104
+ }, [fetchData]);
1105
+ const selectDashboard = useCallback(async (dashboard) => {
1106
+ setSelectedDashboard(dashboard);
1107
+ const dashboardWidgets = await analytics.getWidgets(dashboard.id);
1108
+ setWidgets(dashboardWidgets);
1109
+ }, [analytics]);
1110
+ const stats = {
1111
+ totalDashboards: dashboards.length,
1112
+ publishedDashboards: dashboards.filter((d) => d.status === "PUBLISHED").length,
1113
+ totalQueries: queries.length,
1114
+ sharedQueries: queries.filter((q) => q.isShared).length
1115
+ };
1116
+ return {
1117
+ dashboards,
1118
+ queries,
1119
+ selectedDashboard,
1120
+ widgets,
1121
+ loading,
1122
+ error,
1123
+ stats,
1124
+ refetch: fetchData,
1125
+ selectDashboard
1126
+ };
1127
+ }
1128
+
1129
+ // src/ui/AnalyticsDashboard.tsx
1130
+ import { useState as useState2 } from "react";
1131
+ import {
1132
+ Button,
1133
+ ErrorState,
1134
+ LoaderBlock,
1135
+ StatCard,
1136
+ StatCardGroup
1137
+ } from "@contractspec/lib.design-system";
1138
+ import { jsxDEV } from "react/jsx-dev-runtime";
1139
+ "use client";
1140
+ var STATUS_COLORS = {
1141
+ PUBLISHED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
1142
+ DRAFT: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
1143
+ ARCHIVED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
1144
+ };
1145
+ var WIDGET_ICONS = {
1146
+ LINE_CHART: "\uD83D\uDCC8",
1147
+ BAR_CHART: "\uD83D\uDCCA",
1148
+ PIE_CHART: "\uD83E\uDD67",
1149
+ AREA_CHART: "\uD83D\uDCC9",
1150
+ SCATTER_PLOT: "⚬",
1151
+ METRIC: "\uD83D\uDD22",
1152
+ TABLE: "\uD83D\uDCCB",
1153
+ HEATMAP: "\uD83D\uDDFA️",
1154
+ FUNNEL: "⏬",
1155
+ MAP: "\uD83C\uDF0D",
1156
+ TEXT: "\uD83D\uDCDD",
1157
+ EMBED: "\uD83D\uDD17"
1158
+ };
1159
+ var QUERY_TYPE_COLORS = {
1160
+ SQL: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",
1161
+ METRIC: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",
1162
+ AGGREGATION: "bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400",
1163
+ CUSTOM: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400"
1164
+ };
1165
+ function AnalyticsDashboard() {
1166
+ const [activeTab, setActiveTab] = useState2("dashboards");
1167
+ const {
1168
+ dashboards,
1169
+ queries,
1170
+ selectedDashboard,
1171
+ widgets,
1172
+ loading,
1173
+ error,
1174
+ stats,
1175
+ refetch,
1176
+ selectDashboard
1177
+ } = useAnalyticsData();
1178
+ const tabs = [
1179
+ { id: "dashboards", label: "Dashboards", icon: "\uD83D\uDCCA" },
1180
+ { id: "queries", label: "Queries", icon: "\uD83D\uDD0D" }
1181
+ ];
1182
+ if (loading) {
1183
+ return /* @__PURE__ */ jsxDEV(LoaderBlock, {
1184
+ label: "Loading Analytics..."
1185
+ }, undefined, false, undefined, this);
1186
+ }
1187
+ if (error) {
1188
+ return /* @__PURE__ */ jsxDEV(ErrorState, {
1189
+ title: "Failed to load Analytics",
1190
+ description: error.message,
1191
+ onRetry: refetch,
1192
+ retryLabel: "Retry"
1193
+ }, undefined, false, undefined, this);
1194
+ }
1195
+ return /* @__PURE__ */ jsxDEV("div", {
1196
+ className: "space-y-6",
1197
+ children: [
1198
+ /* @__PURE__ */ jsxDEV("div", {
1199
+ className: "flex items-center justify-between",
1200
+ children: [
1201
+ /* @__PURE__ */ jsxDEV("h2", {
1202
+ className: "text-2xl font-bold",
1203
+ children: "Analytics Dashboard"
1204
+ }, undefined, false, undefined, this),
1205
+ /* @__PURE__ */ jsxDEV(Button, {
1206
+ onClick: () => alert("Create dashboard modal"),
1207
+ children: [
1208
+ /* @__PURE__ */ jsxDEV("span", {
1209
+ className: "mr-2",
1210
+ children: "+"
1211
+ }, undefined, false, undefined, this),
1212
+ " New Dashboard"
1213
+ ]
1214
+ }, undefined, true, undefined, this)
1215
+ ]
1216
+ }, undefined, true, undefined, this),
1217
+ /* @__PURE__ */ jsxDEV(StatCardGroup, {
1218
+ children: [
1219
+ /* @__PURE__ */ jsxDEV(StatCard, {
1220
+ label: "Dashboards",
1221
+ value: stats.totalDashboards,
1222
+ hint: `${stats.publishedDashboards} published`
1223
+ }, undefined, false, undefined, this),
1224
+ /* @__PURE__ */ jsxDEV(StatCard, {
1225
+ label: "Queries",
1226
+ value: stats.totalQueries,
1227
+ hint: `${stats.sharedQueries} shared`
1228
+ }, undefined, false, undefined, this),
1229
+ /* @__PURE__ */ jsxDEV(StatCard, {
1230
+ label: "Widgets",
1231
+ value: widgets.length,
1232
+ hint: "on current dashboard"
1233
+ }, undefined, false, undefined, this)
1234
+ ]
1235
+ }, undefined, true, undefined, this),
1236
+ /* @__PURE__ */ jsxDEV("nav", {
1237
+ className: "bg-muted flex gap-1 rounded-lg p-1",
1238
+ role: "tablist",
1239
+ children: tabs.map((tab) => /* @__PURE__ */ jsxDEV(Button, {
1240
+ type: "button",
1241
+ role: "tab",
1242
+ "aria-selected": activeTab === tab.id,
1243
+ onClick: () => setActiveTab(tab.id),
1244
+ 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"}`,
1245
+ children: [
1246
+ /* @__PURE__ */ jsxDEV("span", {
1247
+ children: tab.icon
1248
+ }, undefined, false, undefined, this),
1249
+ tab.label
1250
+ ]
1251
+ }, tab.id, true, undefined, this))
1252
+ }, undefined, false, undefined, this),
1253
+ /* @__PURE__ */ jsxDEV("div", {
1254
+ className: "min-h-[400px]",
1255
+ role: "tabpanel",
1256
+ children: [
1257
+ activeTab === "dashboards" && /* @__PURE__ */ jsxDEV("div", {
1258
+ className: "space-y-6",
1259
+ children: [
1260
+ /* @__PURE__ */ jsxDEV("div", {
1261
+ className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1262
+ children: [
1263
+ dashboards.map((dashboard) => /* @__PURE__ */ jsxDEV("div", {
1264
+ onClick: () => selectDashboard(dashboard),
1265
+ 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"}`,
1266
+ role: "button",
1267
+ tabIndex: 0,
1268
+ onKeyDown: (e) => {
1269
+ if (e.key === "Enter" || e.key === " ")
1270
+ selectDashboard(dashboard);
1271
+ },
1272
+ children: [
1273
+ /* @__PURE__ */ jsxDEV("div", {
1274
+ className: "mb-2 flex items-center justify-between",
1275
+ children: [
1276
+ /* @__PURE__ */ jsxDEV("h3", {
1277
+ className: "font-medium",
1278
+ children: dashboard.name
1279
+ }, undefined, false, undefined, this),
1280
+ /* @__PURE__ */ jsxDEV("span", {
1281
+ className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${STATUS_COLORS[dashboard.status] ?? ""}`,
1282
+ children: dashboard.status
1283
+ }, undefined, false, undefined, this)
1284
+ ]
1285
+ }, undefined, true, undefined, this),
1286
+ /* @__PURE__ */ jsxDEV("p", {
1287
+ className: "text-muted-foreground mb-3 text-sm",
1288
+ children: dashboard.description
1289
+ }, undefined, false, undefined, this),
1290
+ /* @__PURE__ */ jsxDEV("div", {
1291
+ className: "text-muted-foreground flex items-center justify-between text-xs",
1292
+ children: [
1293
+ /* @__PURE__ */ jsxDEV("span", {
1294
+ children: [
1295
+ "/",
1296
+ dashboard.slug
1297
+ ]
1298
+ }, undefined, true, undefined, this),
1299
+ dashboard.isPublic && /* @__PURE__ */ jsxDEV("span", {
1300
+ className: "text-green-600 dark:text-green-400",
1301
+ children: "\uD83C\uDF10 Public"
1302
+ }, undefined, false, undefined, this)
1303
+ ]
1304
+ }, undefined, true, undefined, this)
1305
+ ]
1306
+ }, dashboard.id, true, undefined, this)),
1307
+ dashboards.length === 0 && /* @__PURE__ */ jsxDEV("div", {
1308
+ className: "text-muted-foreground col-span-full flex h-64 items-center justify-center",
1309
+ children: "No dashboards created yet"
1310
+ }, undefined, false, undefined, this)
1311
+ ]
1312
+ }, undefined, true, undefined, this),
1313
+ selectedDashboard && widgets.length > 0 && /* @__PURE__ */ jsxDEV("div", {
1314
+ children: [
1315
+ /* @__PURE__ */ jsxDEV("h3", {
1316
+ className: "mb-4 text-lg font-semibold",
1317
+ children: [
1318
+ 'Widgets in "',
1319
+ selectedDashboard.name,
1320
+ '"'
1321
+ ]
1322
+ }, undefined, true, undefined, this),
1323
+ /* @__PURE__ */ jsxDEV("div", {
1324
+ className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1325
+ children: widgets.map((widget) => /* @__PURE__ */ jsxDEV("div", {
1326
+ className: "border-border bg-card rounded-lg border p-4",
1327
+ children: [
1328
+ /* @__PURE__ */ jsxDEV("div", {
1329
+ className: "mb-2 flex items-center gap-2",
1330
+ children: [
1331
+ /* @__PURE__ */ jsxDEV("span", {
1332
+ className: "text-xl",
1333
+ children: WIDGET_ICONS[widget.type] ?? "\uD83D\uDCCA"
1334
+ }, undefined, false, undefined, this),
1335
+ /* @__PURE__ */ jsxDEV("span", {
1336
+ className: "font-medium",
1337
+ children: widget.name
1338
+ }, undefined, false, undefined, this)
1339
+ ]
1340
+ }, undefined, true, undefined, this),
1341
+ /* @__PURE__ */ jsxDEV("div", {
1342
+ className: "text-muted-foreground text-sm",
1343
+ children: widget.type.replace(/_/g, " ")
1344
+ }, undefined, false, undefined, this),
1345
+ /* @__PURE__ */ jsxDEV("div", {
1346
+ className: "text-muted-foreground mt-2 text-xs",
1347
+ children: [
1348
+ "Position: (",
1349
+ widget.gridX,
1350
+ ", ",
1351
+ widget.gridY,
1352
+ ") •",
1353
+ " ",
1354
+ widget.gridWidth,
1355
+ "x",
1356
+ widget.gridHeight
1357
+ ]
1358
+ }, undefined, true, undefined, this)
1359
+ ]
1360
+ }, widget.id, true, undefined, this))
1361
+ }, undefined, false, undefined, this)
1362
+ ]
1363
+ }, undefined, true, undefined, this)
1364
+ ]
1365
+ }, undefined, true, undefined, this),
1366
+ activeTab === "queries" && /* @__PURE__ */ jsxDEV("div", {
1367
+ className: "border-border rounded-lg border",
1368
+ children: /* @__PURE__ */ jsxDEV("table", {
1369
+ className: "w-full",
1370
+ children: [
1371
+ /* @__PURE__ */ jsxDEV("thead", {
1372
+ className: "border-border bg-muted/30 border-b",
1373
+ children: /* @__PURE__ */ jsxDEV("tr", {
1374
+ children: [
1375
+ /* @__PURE__ */ jsxDEV("th", {
1376
+ className: "px-4 py-3 text-left text-sm font-medium",
1377
+ children: "Query"
1378
+ }, undefined, false, undefined, this),
1379
+ /* @__PURE__ */ jsxDEV("th", {
1380
+ className: "px-4 py-3 text-left text-sm font-medium",
1381
+ children: "Type"
1382
+ }, undefined, false, undefined, this),
1383
+ /* @__PURE__ */ jsxDEV("th", {
1384
+ className: "px-4 py-3 text-left text-sm font-medium",
1385
+ children: "Cache TTL"
1386
+ }, undefined, false, undefined, this),
1387
+ /* @__PURE__ */ jsxDEV("th", {
1388
+ className: "px-4 py-3 text-left text-sm font-medium",
1389
+ children: "Shared"
1390
+ }, undefined, false, undefined, this)
1391
+ ]
1392
+ }, undefined, true, undefined, this)
1393
+ }, undefined, false, undefined, this),
1394
+ /* @__PURE__ */ jsxDEV("tbody", {
1395
+ className: "divide-border divide-y",
1396
+ children: [
1397
+ queries.map((query) => /* @__PURE__ */ jsxDEV("tr", {
1398
+ className: "hover:bg-muted/50",
1399
+ children: [
1400
+ /* @__PURE__ */ jsxDEV("td", {
1401
+ className: "px-4 py-3",
1402
+ children: [
1403
+ /* @__PURE__ */ jsxDEV("div", {
1404
+ className: "font-medium",
1405
+ children: query.name
1406
+ }, undefined, false, undefined, this),
1407
+ /* @__PURE__ */ jsxDEV("div", {
1408
+ className: "text-muted-foreground text-sm",
1409
+ children: query.description
1410
+ }, undefined, false, undefined, this)
1411
+ ]
1412
+ }, undefined, true, undefined, this),
1413
+ /* @__PURE__ */ jsxDEV("td", {
1414
+ className: "px-4 py-3",
1415
+ children: /* @__PURE__ */ jsxDEV("span", {
1416
+ className: `inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${QUERY_TYPE_COLORS[query.type] ?? ""}`,
1417
+ children: query.type
1418
+ }, undefined, false, undefined, this)
1419
+ }, undefined, false, undefined, this),
1420
+ /* @__PURE__ */ jsxDEV("td", {
1421
+ className: "text-muted-foreground px-4 py-3 text-sm",
1422
+ children: [
1423
+ query.cacheTtlSeconds,
1424
+ "s"
1425
+ ]
1426
+ }, undefined, true, undefined, this),
1427
+ /* @__PURE__ */ jsxDEV("td", {
1428
+ className: "px-4 py-3",
1429
+ children: query.isShared ? /* @__PURE__ */ jsxDEV("span", {
1430
+ className: "text-green-600 dark:text-green-400",
1431
+ children: "✓"
1432
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("span", {
1433
+ className: "text-muted-foreground",
1434
+ children: "—"
1435
+ }, undefined, false, undefined, this)
1436
+ }, undefined, false, undefined, this)
1437
+ ]
1438
+ }, query.id, true, undefined, this)),
1439
+ queries.length === 0 && /* @__PURE__ */ jsxDEV("tr", {
1440
+ children: /* @__PURE__ */ jsxDEV("td", {
1441
+ colSpan: 4,
1442
+ className: "text-muted-foreground px-4 py-8 text-center",
1443
+ children: "No queries saved"
1444
+ }, undefined, false, undefined, this)
1445
+ }, undefined, false, undefined, this)
1446
+ ]
1447
+ }, undefined, true, undefined, this)
1448
+ ]
1449
+ }, undefined, true, undefined, this)
1450
+ }, undefined, false, undefined, this)
1451
+ ]
1452
+ }, undefined, true, undefined, this)
1453
+ ]
1454
+ }, undefined, true, undefined, this);
1455
+ }
1456
+
1457
+ // src/ui/hooks/index.ts
1458
+ "use client";
1459
+ // src/query-engine/index.ts
1460
+ class InMemoryQueryCache {
1461
+ cache = new Map;
1462
+ async get(key) {
1463
+ const entry = this.cache.get(key);
1464
+ if (!entry)
1465
+ return null;
1466
+ if (entry.expiresAt < new Date) {
1467
+ this.cache.delete(key);
1468
+ return null;
1469
+ }
1470
+ return { ...entry.result, cached: true, cachedAt: entry.expiresAt };
1471
+ }
1472
+ async set(key, result, ttlSeconds) {
1473
+ const expiresAt = new Date(Date.now() + ttlSeconds * 1000);
1474
+ this.cache.set(key, { result, expiresAt });
1475
+ }
1476
+ async invalidate(pattern) {
1477
+ const regex = new RegExp(pattern);
1478
+ for (const key of this.cache.keys()) {
1479
+ if (regex.test(key)) {
1480
+ this.cache.delete(key);
1481
+ }
1482
+ }
1483
+ }
1484
+ }
1485
+
1486
+ class BasicQueryEngine {
1487
+ cache;
1488
+ constructor(cache) {
1489
+ this.cache = cache ?? new InMemoryQueryCache;
1490
+ }
1491
+ async execute(definition, params) {
1492
+ const startTime = Date.now();
1493
+ const validation = this.validateQuery(definition);
1494
+ if (!validation.valid) {
1495
+ return {
1496
+ data: [],
1497
+ columns: [],
1498
+ rowCount: 0,
1499
+ executionTimeMs: Date.now() - startTime,
1500
+ cached: false,
1501
+ error: validation.errors.join(", ")
1502
+ };
1503
+ }
1504
+ const cacheKey = this.buildCacheKey(definition, params);
1505
+ const cachedResult = await this.cache.get(cacheKey);
1506
+ if (cachedResult) {
1507
+ return cachedResult;
1508
+ }
1509
+ let result;
1510
+ switch (definition.type) {
1511
+ case "AGGREGATION":
1512
+ if (!definition.aggregation) {
1513
+ throw new Error("Aggregation definition is missing");
1514
+ }
1515
+ result = await this.executeAggregation(definition.aggregation, params);
1516
+ break;
1517
+ case "METRIC":
1518
+ if (!definition.metricIds) {
1519
+ throw new Error("Metric IDs are missing");
1520
+ }
1521
+ result = await this.executeMetric(definition.metricIds, params);
1522
+ break;
1523
+ case "SQL":
1524
+ if (!definition.sql) {
1525
+ throw new Error("SQL query is missing");
1526
+ }
1527
+ result = await this.executeSql(definition.sql, params);
1528
+ break;
1529
+ default:
1530
+ result = {
1531
+ data: [],
1532
+ columns: [],
1533
+ rowCount: 0,
1534
+ executionTimeMs: Date.now() - startTime,
1535
+ cached: false,
1536
+ error: `Unknown query type: ${definition.type}`
1537
+ };
1538
+ }
1539
+ result.executionTimeMs = Date.now() - startTime;
1540
+ result.cached = false;
1541
+ await this.cache.set(cacheKey, result, 300);
1542
+ return result;
1543
+ }
1544
+ validateQuery(definition) {
1545
+ const errors = [];
1546
+ if (!definition.type) {
1547
+ errors.push("Query type is required");
1548
+ }
1549
+ switch (definition.type) {
1550
+ case "SQL":
1551
+ if (!definition.sql) {
1552
+ errors.push("SQL query is required for SQL type");
1553
+ }
1554
+ break;
1555
+ case "METRIC":
1556
+ if (!definition.metricIds || definition.metricIds.length === 0) {
1557
+ errors.push("Metric IDs are required for METRIC type");
1558
+ }
1559
+ break;
1560
+ case "AGGREGATION":
1561
+ if (!definition.aggregation) {
1562
+ errors.push("Aggregation definition is required for AGGREGATION type");
1563
+ } else {
1564
+ if (!definition.aggregation.source) {
1565
+ errors.push("Aggregation source is required");
1566
+ }
1567
+ if (!definition.aggregation.measures || definition.aggregation.measures.length === 0) {
1568
+ errors.push("At least one measure is required");
1569
+ }
1570
+ }
1571
+ break;
1572
+ }
1573
+ return { valid: errors.length === 0, errors };
1574
+ }
1575
+ buildCacheKey(definition, params) {
1576
+ return JSON.stringify({ definition, params });
1577
+ }
1578
+ async executeAggregation(aggregation, params) {
1579
+ const columns = [
1580
+ ...aggregation.dimensions.map((d) => ({
1581
+ name: d.name,
1582
+ type: d.type === "NUMBER" ? "NUMBER" : d.type === "TIME" ? "DATE" : "STRING",
1583
+ label: d.name
1584
+ })),
1585
+ ...aggregation.measures.map((m) => ({
1586
+ name: m.name,
1587
+ type: "NUMBER",
1588
+ label: m.name,
1589
+ format: m.format
1590
+ }))
1591
+ ];
1592
+ const data = this.generateMockData(aggregation, params);
1593
+ return {
1594
+ data,
1595
+ columns,
1596
+ rowCount: data.length,
1597
+ executionTimeMs: 0,
1598
+ cached: false
1599
+ };
1600
+ }
1601
+ async executeMetric(metricIds, _params) {
1602
+ const data = metricIds.map((id) => ({
1603
+ metricId: id,
1604
+ value: Math.random() * 1000,
1605
+ change: (Math.random() - 0.5) * 20
1606
+ }));
1607
+ return {
1608
+ data,
1609
+ columns: [
1610
+ { name: "metricId", type: "STRING" },
1611
+ { name: "value", type: "NUMBER" },
1612
+ { name: "change", type: "NUMBER" }
1613
+ ],
1614
+ rowCount: data.length,
1615
+ executionTimeMs: 0,
1616
+ cached: false
1617
+ };
1618
+ }
1619
+ async executeSql(_sql, _params) {
1620
+ return {
1621
+ data: [],
1622
+ columns: [],
1623
+ rowCount: 0,
1624
+ executionTimeMs: 0,
1625
+ cached: false,
1626
+ error: "SQL execution not implemented in demo"
1627
+ };
1628
+ }
1629
+ generateMockData(aggregation, params) {
1630
+ const data = [];
1631
+ const rowCount = 10;
1632
+ const timeDimension = aggregation.dimensions.find((d) => d.type === "TIME");
1633
+ for (let i = 0;i < rowCount; i++) {
1634
+ const row = {};
1635
+ for (const dim of aggregation.dimensions) {
1636
+ if (dim.type === "TIME") {
1637
+ const date = new Date(params.dateRange?.start ?? new Date);
1638
+ date.setDate(date.getDate() + i);
1639
+ row[dim.name] = date.toISOString().split("T")[0];
1640
+ } else {
1641
+ row[dim.name] = `${dim.name}_${i % 5}`;
1642
+ }
1643
+ }
1644
+ for (const measure of aggregation.measures) {
1645
+ const baseValue = timeDimension ? 100 + i * 10 : Math.random() * 1000;
1646
+ const noise = (Math.random() - 0.5) * 20;
1647
+ row[measure.name] = Math.round((baseValue + noise) * 100) / 100;
1648
+ }
1649
+ data.push(row);
1650
+ }
1651
+ return data;
1652
+ }
1653
+ }
1654
+ function createQueryEngine(cache) {
1655
+ return new BasicQueryEngine(cache);
1656
+ }
1657
+ export {
1658
+ useAnalyticsData,
1659
+ queryBuilderMarkdownRenderer,
1660
+ dashboardListMarkdownRenderer,
1661
+ createQueryEngine,
1662
+ createPosthogQueryEngine,
1663
+ createAnalyticsHandlers,
1664
+ analyticsDashboardMarkdownRenderer,
1665
+ QueryTypeEnum,
1666
+ QueryResultModel,
1667
+ QueryModel,
1668
+ PosthogQueryEngine,
1669
+ InMemoryQueryCache,
1670
+ ExecuteQueryInputModel,
1671
+ ExecuteQueryContract,
1672
+ CreateQueryInputModel,
1673
+ CreateQueryContract,
1674
+ BasicQueryEngine,
1675
+ AnalyticsDashboardFeature,
1676
+ AnalyticsDashboard
1677
+ };