@contractspec/lib.example-shared-ui 6.0.17 → 6.0.18

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 (84) hide show
  1. package/.turbo/turbo-build.log +81 -81
  2. package/CHANGELOG.md +17 -0
  3. package/dist/EvolutionDashboard.js +1 -803
  4. package/dist/EvolutionSidebar.js +1 -531
  5. package/dist/LocalDataIndicator.js +1 -68
  6. package/dist/MarkdownView.js +1 -213
  7. package/dist/OverlayContextProvider.js +1 -202
  8. package/dist/PersonalizationInsights.js +1 -455
  9. package/dist/SaveToStudioButton.js +1 -79
  10. package/dist/SpecDrivenTemplateShell.js +1 -203
  11. package/dist/SpecEditorPanel.js +17 -364
  12. package/dist/TemplateShell.js +1 -195
  13. package/dist/browser/EvolutionDashboard.js +1 -803
  14. package/dist/browser/EvolutionSidebar.js +1 -531
  15. package/dist/browser/LocalDataIndicator.js +1 -68
  16. package/dist/browser/MarkdownView.js +1 -213
  17. package/dist/browser/OverlayContextProvider.js +1 -202
  18. package/dist/browser/PersonalizationInsights.js +1 -455
  19. package/dist/browser/SaveToStudioButton.js +1 -79
  20. package/dist/browser/SpecDrivenTemplateShell.js +1 -203
  21. package/dist/browser/SpecEditorPanel.js +17 -364
  22. package/dist/browser/TemplateShell.js +1 -195
  23. package/dist/browser/bundles/ExampleTemplateBundle.js +1 -85
  24. package/dist/browser/bundles/index.js +1 -85
  25. package/dist/browser/hooks/index.js +40 -1151
  26. package/dist/browser/hooks/useBehaviorTracking.js +1 -157
  27. package/dist/browser/hooks/useEvolution.js +1 -260
  28. package/dist/browser/hooks/useRegistryTemplates.js +1 -31
  29. package/dist/browser/hooks/useSpecContent.js +17 -224
  30. package/dist/browser/hooks/useWorkflowComposer.js +24 -483
  31. package/dist/browser/index.js +40 -3122
  32. package/dist/browser/lib/component-registry.js +1 -48
  33. package/dist/browser/lib/runtime-context.js +1 -21
  34. package/dist/browser/markdown/formatPresentationName.js +1 -9
  35. package/dist/browser/markdown/useMarkdownPresentation.js +1 -65
  36. package/dist/browser/utils/fetchPresentationData.js +1 -15
  37. package/dist/browser/utils/generateSpecFromTemplate.js +16 -62
  38. package/dist/browser/utils/index.js +16 -76
  39. package/dist/bundles/ExampleTemplateBundle.js +1 -85
  40. package/dist/bundles/index.js +1 -85
  41. package/dist/hooks/index.js +40 -1151
  42. package/dist/hooks/useBehaviorTracking.js +1 -157
  43. package/dist/hooks/useEvolution.js +1 -260
  44. package/dist/hooks/useRegistryTemplates.js +1 -31
  45. package/dist/hooks/useSpecContent.js +17 -224
  46. package/dist/hooks/useWorkflowComposer.js +24 -483
  47. package/dist/index.js +40 -3122
  48. package/dist/lib/component-registry.js +1 -48
  49. package/dist/lib/runtime-context.js +1 -21
  50. package/dist/markdown/formatPresentationName.js +1 -9
  51. package/dist/markdown/useMarkdownPresentation.js +1 -65
  52. package/dist/node/EvolutionDashboard.js +1 -803
  53. package/dist/node/EvolutionSidebar.js +1 -531
  54. package/dist/node/LocalDataIndicator.js +1 -68
  55. package/dist/node/MarkdownView.js +1 -213
  56. package/dist/node/OverlayContextProvider.js +1 -202
  57. package/dist/node/PersonalizationInsights.js +1 -455
  58. package/dist/node/SaveToStudioButton.js +1 -79
  59. package/dist/node/SpecDrivenTemplateShell.js +1 -203
  60. package/dist/node/SpecEditorPanel.js +17 -364
  61. package/dist/node/TemplateShell.js +1 -195
  62. package/dist/node/bundles/ExampleTemplateBundle.js +1 -85
  63. package/dist/node/bundles/index.js +1 -85
  64. package/dist/node/hooks/index.js +40 -1151
  65. package/dist/node/hooks/useBehaviorTracking.js +1 -157
  66. package/dist/node/hooks/useEvolution.js +1 -260
  67. package/dist/node/hooks/useRegistryTemplates.js +1 -31
  68. package/dist/node/hooks/useSpecContent.js +17 -224
  69. package/dist/node/hooks/useWorkflowComposer.js +24 -483
  70. package/dist/node/index.js +40 -3122
  71. package/dist/node/lib/component-registry.js +1 -48
  72. package/dist/node/lib/runtime-context.js +1 -21
  73. package/dist/node/markdown/formatPresentationName.js +1 -9
  74. package/dist/node/markdown/useMarkdownPresentation.js +1 -65
  75. package/dist/node/utils/fetchPresentationData.js +1 -15
  76. package/dist/node/utils/generateSpecFromTemplate.js +16 -62
  77. package/dist/node/utils/index.js +16 -76
  78. package/dist/utils/fetchPresentationData.js +1 -15
  79. package/dist/utils/generateSpecFromTemplate.js +16 -62
  80. package/dist/utils/index.js +16 -76
  81. package/package.json +13 -13
  82. package/src/lib/component-registry.tsx +2 -1
  83. package/src/lib/runtime-context.tsx +1 -1
  84. package/src/lib/singletons.test.ts +19 -22
@@ -1,2146 +1,5 @@
1
- // src/hooks/useEvolution.ts
2
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
- "use client";
4
- var EVOLUTION_STORAGE_KEY = "contractspec-evolution-data";
5
- function useEvolution(templateId) {
6
- const [usageStats, setUsageStats] = useState([]);
7
- const [anomalies, setAnomalies] = useState([]);
8
- const [suggestions, setSuggestions] = useState([]);
9
- const [hints, setHints] = useState([]);
10
- const [loading, setLoading] = useState(false);
11
- const metricsRef = useRef([]);
12
- const [operationCount, setOperationCount] = useState(0);
13
- useEffect(() => {
14
- try {
15
- const stored = localStorage.getItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
16
- if (stored) {
17
- const data = JSON.parse(stored);
18
- setSuggestions(data.suggestions.map((s) => ({
19
- ...s,
20
- createdAt: new Date(s.createdAt)
21
- })));
22
- }
23
- } catch {}
24
- }, [templateId]);
25
- useEffect(() => {
26
- try {
27
- localStorage.setItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`, JSON.stringify({ suggestions }));
28
- } catch {}
29
- }, [suggestions, templateId]);
30
- const trackOperation = useCallback((operationName, durationMs, success, errorCode) => {
31
- const sample = {
32
- operation: {
33
- name: operationName,
34
- version: "1.0.0",
35
- tenantId: "sandbox"
36
- },
37
- durationMs,
38
- success,
39
- timestamp: new Date,
40
- errorCode
41
- };
42
- metricsRef.current.push(sample);
43
- setOperationCount((prev) => prev + 1);
44
- }, []);
45
- const analyzeUsage = useCallback(() => {
46
- const samples = metricsRef.current;
47
- if (samples.length < 5)
48
- return;
49
- const groups = new Map;
50
- for (const sample of samples) {
51
- const key = `${sample.operation.name}.v${sample.operation.version}`;
52
- const arr = groups.get(key) ?? [];
53
- arr.push(sample);
54
- groups.set(key, arr);
55
- }
56
- const stats = [];
57
- const detectedAnomalies = [];
58
- groups.forEach((opSamples) => {
59
- if (opSamples.length < 3)
60
- return;
61
- const durations = opSamples.map((s) => s.durationMs).sort((a, b) => a - b);
62
- const errors = opSamples.filter((s) => !s.success);
63
- const totalCalls = opSamples.length;
64
- const errorRate = errors.length / totalCalls;
65
- const averageLatencyMs = durations.reduce((sum, value) => sum + value, 0) / totalCalls;
66
- const timestamps = opSamples.map((s) => s.timestamp.getTime());
67
- const firstSample = opSamples[0];
68
- if (!firstSample)
69
- return;
70
- const stat = {
71
- operation: firstSample.operation,
72
- totalCalls,
73
- successRate: 1 - errorRate,
74
- errorRate,
75
- averageLatencyMs,
76
- p95LatencyMs: percentile(durations, 0.95),
77
- p99LatencyMs: percentile(durations, 0.99),
78
- maxLatencyMs: Math.max(...durations),
79
- lastSeenAt: new Date(Math.max(...timestamps)),
80
- windowStart: new Date(Math.min(...timestamps)),
81
- windowEnd: new Date(Math.max(...timestamps)),
82
- topErrors: errors.reduce((acc, s) => {
83
- if (s.errorCode) {
84
- acc[s.errorCode] = (acc[s.errorCode] ?? 0) + 1;
85
- }
86
- return acc;
87
- }, {})
88
- };
89
- stats.push(stat);
90
- if (errorRate > 0.1) {
91
- detectedAnomalies.push({
92
- operation: stat.operation,
93
- severity: errorRate > 0.3 ? "high" : errorRate > 0.2 ? "medium" : "low",
94
- metric: "error-rate",
95
- description: `Error rate ${(errorRate * 100).toFixed(1)}% exceeds threshold`,
96
- detectedAt: new Date,
97
- threshold: 0.1,
98
- observedValue: errorRate
99
- });
100
- }
101
- if (stat.p99LatencyMs > 500) {
102
- detectedAnomalies.push({
103
- operation: stat.operation,
104
- severity: stat.p99LatencyMs > 1000 ? "high" : stat.p99LatencyMs > 750 ? "medium" : "low",
105
- metric: "latency",
106
- description: `P99 latency ${stat.p99LatencyMs.toFixed(0)}ms exceeds threshold`,
107
- detectedAt: new Date,
108
- threshold: 500,
109
- observedValue: stat.p99LatencyMs
110
- });
111
- }
112
- });
113
- setUsageStats(stats);
114
- setAnomalies(detectedAnomalies);
115
- const newHints = detectedAnomalies.map((anomaly) => ({
116
- operation: anomaly.operation,
117
- category: anomaly.metric === "latency" ? "performance" : "error-handling",
118
- summary: anomaly.metric === "latency" ? "Latency regression detected" : "Error spike detected",
119
- justification: anomaly.description,
120
- recommendedActions: anomaly.metric === "latency" ? [
121
- "Add caching layer",
122
- "Optimize database queries",
123
- "Consider pagination"
124
- ] : [
125
- "Add retry logic",
126
- "Improve error handling",
127
- "Add circuit breaker"
128
- ]
129
- }));
130
- setHints(newHints);
131
- }, []);
132
- const generateSuggestions = useCallback(async () => {
133
- if (anomalies.length === 0)
134
- return;
135
- setLoading(true);
136
- await new Promise((resolve) => setTimeout(resolve, 800));
137
- const newSuggestions = anomalies.map((anomaly) => ({
138
- id: `suggestion-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
139
- intent: {
140
- id: `intent-${anomaly.operation.name}`,
141
- type: anomaly.metric === "latency" ? "latency-regression" : anomaly.metric === "error-rate" ? "error-spike" : "throughput-drop",
142
- description: anomaly.description,
143
- operation: anomaly.operation,
144
- confidence: {
145
- score: anomaly.severity === "high" ? 0.9 : anomaly.severity === "medium" ? 0.7 : 0.5,
146
- sampleSize: usageStats.find((s) => s.operation.name === anomaly.operation.name)?.totalCalls ?? 0
147
- }
148
- },
149
- target: anomaly.operation,
150
- proposal: {
151
- summary: generateSuggestionSummary(anomaly),
152
- rationale: generateSuggestionRationale(anomaly),
153
- changeType: anomaly.metric === "error-rate" ? "policy-update" : "revision",
154
- recommendedActions: generateRecommendedActions(anomaly)
155
- },
156
- confidence: anomaly.severity === "high" ? 0.85 : anomaly.severity === "medium" ? 0.7 : 0.55,
157
- createdAt: new Date,
158
- createdBy: "ai-evolution-agent",
159
- status: "pending",
160
- priority: anomaly.severity
161
- }));
162
- setSuggestions((prev) => [...prev, ...newSuggestions]);
163
- setLoading(false);
164
- }, [anomalies, usageStats]);
165
- const approveSuggestion = useCallback((id, _notes) => {
166
- setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "approved" } : s));
167
- }, []);
168
- const rejectSuggestion = useCallback((id, _notes) => {
169
- setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "rejected" } : s));
170
- }, []);
171
- const clear = useCallback(() => {
172
- metricsRef.current = [];
173
- setOperationCount(0);
174
- setUsageStats([]);
175
- setAnomalies([]);
176
- setSuggestions([]);
177
- setHints([]);
178
- localStorage.removeItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
179
- }, [templateId]);
180
- return useMemo(() => ({
181
- usageStats,
182
- anomalies,
183
- suggestions,
184
- hints,
185
- loading,
186
- trackOperation,
187
- analyzeUsage,
188
- generateSuggestions,
189
- approveSuggestion,
190
- rejectSuggestion,
191
- clear,
192
- operationCount
193
- }), [
194
- usageStats,
195
- anomalies,
196
- suggestions,
197
- hints,
198
- loading,
199
- trackOperation,
200
- analyzeUsage,
201
- generateSuggestions,
202
- approveSuggestion,
203
- rejectSuggestion,
204
- clear,
205
- operationCount
206
- ]);
207
- }
208
- function percentile(values, p) {
209
- if (!values.length)
210
- return 0;
211
- if (values.length === 1)
212
- return values[0] ?? 0;
213
- const idx = Math.min(values.length - 1, Math.floor(p * values.length));
214
- return values[idx] ?? 0;
215
- }
216
- function generateSuggestionSummary(anomaly) {
217
- if (anomaly.metric === "latency") {
218
- return `Add caching and pagination to ${anomaly.operation.name} to reduce latency`;
219
- }
220
- if (anomaly.metric === "error-rate") {
221
- return `Add retry policy and circuit breaker to ${anomaly.operation.name}`;
222
- }
223
- return `Optimize ${anomaly.operation.name} for improved throughput`;
224
- }
225
- function generateSuggestionRationale(anomaly) {
226
- if (anomaly.metric === "latency") {
227
- return `The operation ${anomaly.operation.name} is experiencing P99 latency of ${anomaly.observedValue?.toFixed(0)}ms, which is above the recommended threshold of ${anomaly.threshold}ms. This can impact user experience and downstream operations.`;
228
- }
229
- if (anomaly.metric === "error-rate") {
230
- return `The error rate for ${anomaly.operation.name} is ${((anomaly.observedValue ?? 0) * 100).toFixed(1)}%, indicating potential issues with input validation, external dependencies, or resource limits.`;
231
- }
232
- return `Throughput for ${anomaly.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`;
233
- }
234
- function generateRecommendedActions(anomaly) {
235
- if (anomaly.metric === "latency") {
236
- return [
237
- "Add response caching for frequently accessed data",
238
- "Implement pagination for large result sets",
239
- "Optimize database queries with proper indexing",
240
- "Consider adding a GraphQL DataLoader for batching"
241
- ];
242
- }
243
- if (anomaly.metric === "error-rate") {
244
- return [
245
- "Add input validation at the contract level",
246
- "Implement retry policy with exponential backoff",
247
- "Add circuit breaker for external dependencies",
248
- "Enhance error logging for better debugging"
249
- ];
250
- }
251
- return [
252
- "Review resource allocation and scaling policies",
253
- "Check for upstream routing or load balancer issues",
254
- "Validate feature flag configurations",
255
- "Monitor dependency health metrics"
256
- ];
257
- }
258
-
259
- // src/EvolutionDashboard.tsx
260
- import { Button, LoaderBlock } from "@contractspec/lib.design-system";
261
- import { Badge } from "@contractspec/lib.ui-kit-web/ui/badge";
262
- import { Card } from "@contractspec/lib.ui-kit-web/ui/card";
263
- import { useCallback as useCallback2, useMemo as useMemo2 } from "react";
264
- import { jsxDEV } from "react/jsx-dev-runtime";
265
- "use client";
266
- function EvolutionDashboard({
267
- templateId,
268
- onLog
269
- }) {
270
- const {
271
- usageStats,
272
- anomalies,
273
- suggestions,
274
- hints,
275
- loading,
276
- trackOperation,
277
- analyzeUsage,
278
- generateSuggestions,
279
- approveSuggestion,
280
- rejectSuggestion,
281
- clear,
282
- operationCount
283
- } = useEvolution(templateId);
284
- const handleSimulateOperations = useCallback2(() => {
285
- const operations = [
286
- { name: `${templateId}.list`, duration: 150, success: true },
287
- { name: `${templateId}.list`, duration: 180, success: true },
288
- { name: `${templateId}.create`, duration: 350, success: true },
289
- {
290
- name: `${templateId}.create`,
291
- duration: 420,
292
- success: false,
293
- error: "VALIDATION_ERROR"
294
- },
295
- { name: `${templateId}.list`, duration: 200, success: true },
296
- { name: `${templateId}.get`, duration: 80, success: true },
297
- { name: `${templateId}.update`, duration: 280, success: true },
298
- { name: `${templateId}.list`, duration: 950, success: true },
299
- {
300
- name: `${templateId}.delete`,
301
- duration: 150,
302
- success: false,
303
- error: "NOT_FOUND"
304
- },
305
- { name: `${templateId}.create`, duration: 380, success: true }
306
- ];
307
- for (const op of operations) {
308
- trackOperation(op.name, op.duration, op.success, op.error);
309
- }
310
- onLog?.(`Simulated ${operations.length} operations`);
311
- setTimeout(() => {
312
- analyzeUsage();
313
- onLog?.("Analysis complete");
314
- }, 100);
315
- }, [templateId, trackOperation, analyzeUsage, onLog]);
316
- const handleGenerateSuggestions = useCallback2(async () => {
317
- await generateSuggestions();
318
- onLog?.("AI suggestions generated");
319
- }, [generateSuggestions, onLog]);
320
- const handleApproveSuggestion = useCallback2((id) => {
321
- approveSuggestion(id);
322
- onLog?.(`Suggestion ${id.slice(0, 8)} approved`);
323
- }, [approveSuggestion, onLog]);
324
- const handleRejectSuggestion = useCallback2((id) => {
325
- rejectSuggestion(id);
326
- onLog?.(`Suggestion ${id.slice(0, 8)} rejected`);
327
- }, [rejectSuggestion, onLog]);
328
- const handleClear = useCallback2(() => {
329
- clear();
330
- onLog?.("Evolution data cleared");
331
- }, [clear, onLog]);
332
- const pendingSuggestions = useMemo2(() => suggestions.filter((s) => s.status === "pending"), [suggestions]);
333
- return /* @__PURE__ */ jsxDEV("div", {
334
- className: "space-y-6",
335
- children: [
336
- /* @__PURE__ */ jsxDEV("div", {
337
- className: "flex items-center justify-between",
338
- children: [
339
- /* @__PURE__ */ jsxDEV("div", {
340
- children: [
341
- /* @__PURE__ */ jsxDEV("h2", {
342
- className: "font-semibold text-xl",
343
- children: "AI Evolution Engine"
344
- }, undefined, false, undefined, this),
345
- /* @__PURE__ */ jsxDEV("p", {
346
- className: "text-muted-foreground text-sm",
347
- children: "Analyze usage patterns and get AI-powered suggestions"
348
- }, undefined, false, undefined, this)
349
- ]
350
- }, undefined, true, undefined, this),
351
- /* @__PURE__ */ jsxDEV("div", {
352
- className: "flex items-center gap-2",
353
- children: [
354
- /* @__PURE__ */ jsxDEV(Badge, {
355
- variant: "secondary",
356
- children: [
357
- operationCount,
358
- " ops tracked"
359
- ]
360
- }, undefined, true, undefined, this),
361
- /* @__PURE__ */ jsxDEV(Button, {
362
- variant: "ghost",
363
- size: "sm",
364
- onPress: handleClear,
365
- children: "Clear"
366
- }, undefined, false, undefined, this)
367
- ]
368
- }, undefined, true, undefined, this)
369
- ]
370
- }, undefined, true, undefined, this),
371
- /* @__PURE__ */ jsxDEV(Card, {
372
- className: "p-4",
373
- children: [
374
- /* @__PURE__ */ jsxDEV("div", {
375
- className: "flex flex-wrap items-center gap-3",
376
- children: [
377
- /* @__PURE__ */ jsxDEV(Button, {
378
- variant: "default",
379
- size: "sm",
380
- onPress: handleSimulateOperations,
381
- children: "Simulate Operations"
382
- }, undefined, false, undefined, this),
383
- /* @__PURE__ */ jsxDEV(Button, {
384
- variant: "outline",
385
- size: "sm",
386
- onPress: analyzeUsage,
387
- disabled: operationCount < 5,
388
- children: "Analyze Usage"
389
- }, undefined, false, undefined, this),
390
- /* @__PURE__ */ jsxDEV(Button, {
391
- variant: "outline",
392
- size: "sm",
393
- onPress: handleGenerateSuggestions,
394
- disabled: anomalies.length === 0 || loading,
395
- children: loading ? "Generating..." : "Generate AI Suggestions"
396
- }, undefined, false, undefined, this)
397
- ]
398
- }, undefined, true, undefined, this),
399
- /* @__PURE__ */ jsxDEV("p", {
400
- className: "mt-2 text-muted-foreground text-xs",
401
- children: "Simulate sandbox operations, analyze patterns, and generate AI improvement suggestions."
402
- }, undefined, false, undefined, this)
403
- ]
404
- }, undefined, true, undefined, this),
405
- loading && /* @__PURE__ */ jsxDEV(LoaderBlock, {
406
- label: "Generating AI suggestions..."
407
- }, undefined, false, undefined, this),
408
- usageStats.length > 0 && /* @__PURE__ */ jsxDEV(Card, {
409
- className: "p-4",
410
- children: [
411
- /* @__PURE__ */ jsxDEV("h3", {
412
- className: "mb-3 font-semibold",
413
- children: "Usage Statistics"
414
- }, undefined, false, undefined, this),
415
- /* @__PURE__ */ jsxDEV("div", {
416
- className: "grid gap-3 md:grid-cols-2 lg:grid-cols-3",
417
- children: usageStats.map((stat) => /* @__PURE__ */ jsxDEV(UsageStatCard, {
418
- stat
419
- }, stat.operation.name, false, undefined, this))
420
- }, undefined, false, undefined, this)
421
- ]
422
- }, undefined, true, undefined, this),
423
- anomalies.length > 0 && /* @__PURE__ */ jsxDEV(Card, {
424
- className: "p-4",
425
- children: [
426
- /* @__PURE__ */ jsxDEV("div", {
427
- className: "mb-3 flex items-center justify-between",
428
- children: [
429
- /* @__PURE__ */ jsxDEV("h3", {
430
- className: "font-semibold",
431
- children: "Detected Anomalies"
432
- }, undefined, false, undefined, this),
433
- /* @__PURE__ */ jsxDEV(Badge, {
434
- variant: "secondary",
435
- className: "border-amber-500/30 bg-amber-500/20 text-amber-400",
436
- children: [
437
- anomalies.length,
438
- " issues"
439
- ]
440
- }, undefined, true, undefined, this)
441
- ]
442
- }, undefined, true, undefined, this),
443
- /* @__PURE__ */ jsxDEV("div", {
444
- className: "space-y-2",
445
- children: anomalies.map((anomaly, index) => /* @__PURE__ */ jsxDEV(AnomalyCard, {
446
- anomaly
447
- }, `${anomaly.operation.name}-${index}`, false, undefined, this))
448
- }, undefined, false, undefined, this)
449
- ]
450
- }, undefined, true, undefined, this),
451
- suggestions.length > 0 && /* @__PURE__ */ jsxDEV(Card, {
452
- className: "p-4",
453
- children: [
454
- /* @__PURE__ */ jsxDEV("div", {
455
- className: "mb-3 flex items-center justify-between",
456
- children: [
457
- /* @__PURE__ */ jsxDEV("h3", {
458
- className: "font-semibold",
459
- children: "AI Suggestions"
460
- }, undefined, false, undefined, this),
461
- /* @__PURE__ */ jsxDEV("div", {
462
- className: "flex items-center gap-2",
463
- children: pendingSuggestions.length > 0 && /* @__PURE__ */ jsxDEV(Badge, {
464
- variant: "secondary",
465
- className: "border-amber-500/30 bg-amber-500/20 text-amber-400",
466
- children: [
467
- pendingSuggestions.length,
468
- " pending"
469
- ]
470
- }, undefined, true, undefined, this)
471
- }, undefined, false, undefined, this)
472
- ]
473
- }, undefined, true, undefined, this),
474
- /* @__PURE__ */ jsxDEV("div", {
475
- className: "space-y-3",
476
- children: suggestions.map((suggestion) => /* @__PURE__ */ jsxDEV(SuggestionCard, {
477
- suggestion,
478
- onApprove: handleApproveSuggestion,
479
- onReject: handleRejectSuggestion
480
- }, suggestion.id, false, undefined, this))
481
- }, undefined, false, undefined, this)
482
- ]
483
- }, undefined, true, undefined, this),
484
- hints.length > 0 && /* @__PURE__ */ jsxDEV(Card, {
485
- className: "p-4",
486
- children: [
487
- /* @__PURE__ */ jsxDEV("h3", {
488
- className: "mb-3 font-semibold",
489
- children: "Optimization Hints"
490
- }, undefined, false, undefined, this),
491
- /* @__PURE__ */ jsxDEV("div", {
492
- className: "space-y-2",
493
- children: hints.map((hint, index) => /* @__PURE__ */ jsxDEV(HintCard, {
494
- hint
495
- }, `${hint.operation.name}-${index}`, false, undefined, this))
496
- }, undefined, false, undefined, this)
497
- ]
498
- }, undefined, true, undefined, this),
499
- usageStats.length === 0 && anomalies.length === 0 && suggestions.length === 0 && /* @__PURE__ */ jsxDEV(Card, {
500
- className: "p-8 text-center",
501
- children: /* @__PURE__ */ jsxDEV("p", {
502
- className: "text-muted-foreground",
503
- children: 'Click "Simulate Operations" to generate sample data for analysis.'
504
- }, undefined, false, undefined, this)
505
- }, undefined, false, undefined, this)
506
- ]
507
- }, undefined, true, undefined, this);
508
- }
509
- function UsageStatCard({ stat }) {
510
- return /* @__PURE__ */ jsxDEV("div", {
511
- className: "rounded-lg border border-violet-500/20 bg-violet-500/5 p-3",
512
- children: [
513
- /* @__PURE__ */ jsxDEV("div", {
514
- className: "mb-2 flex items-center justify-between",
515
- children: [
516
- /* @__PURE__ */ jsxDEV("span", {
517
- className: "font-medium font-mono text-sm",
518
- children: stat.operation.name
519
- }, undefined, false, undefined, this),
520
- /* @__PURE__ */ jsxDEV(Badge, {
521
- variant: stat.errorRate > 0.1 ? "destructive" : "default",
522
- className: stat.errorRate > 0.1 ? "" : "border-green-500/30 bg-green-500/20 text-green-400",
523
- children: [
524
- ((1 - stat.errorRate) * 100).toFixed(0),
525
- "% success"
526
- ]
527
- }, undefined, true, undefined, this)
528
- ]
529
- }, undefined, true, undefined, this),
530
- /* @__PURE__ */ jsxDEV("div", {
531
- className: "grid grid-cols-2 gap-2 text-xs",
532
- children: [
533
- /* @__PURE__ */ jsxDEV("div", {
534
- children: [
535
- /* @__PURE__ */ jsxDEV("span", {
536
- className: "text-muted-foreground",
537
- children: "Total Calls:"
538
- }, undefined, false, undefined, this),
539
- " ",
540
- /* @__PURE__ */ jsxDEV("span", {
541
- className: "font-medium",
542
- children: stat.totalCalls
543
- }, undefined, false, undefined, this)
544
- ]
545
- }, undefined, true, undefined, this),
546
- /* @__PURE__ */ jsxDEV("div", {
547
- children: [
548
- /* @__PURE__ */ jsxDEV("span", {
549
- className: "text-muted-foreground",
550
- children: "Avg Latency:"
551
- }, undefined, false, undefined, this),
552
- " ",
553
- /* @__PURE__ */ jsxDEV("span", {
554
- className: "font-medium",
555
- children: [
556
- stat.averageLatencyMs.toFixed(0),
557
- "ms"
558
- ]
559
- }, undefined, true, undefined, this)
560
- ]
561
- }, undefined, true, undefined, this),
562
- /* @__PURE__ */ jsxDEV("div", {
563
- children: [
564
- /* @__PURE__ */ jsxDEV("span", {
565
- className: "text-muted-foreground",
566
- children: "P95:"
567
- }, undefined, false, undefined, this),
568
- " ",
569
- /* @__PURE__ */ jsxDEV("span", {
570
- className: "font-medium",
571
- children: [
572
- stat.p95LatencyMs.toFixed(0),
573
- "ms"
574
- ]
575
- }, undefined, true, undefined, this)
576
- ]
577
- }, undefined, true, undefined, this),
578
- /* @__PURE__ */ jsxDEV("div", {
579
- children: [
580
- /* @__PURE__ */ jsxDEV("span", {
581
- className: "text-muted-foreground",
582
- children: "P99:"
583
- }, undefined, false, undefined, this),
584
- " ",
585
- /* @__PURE__ */ jsxDEV("span", {
586
- className: "font-medium",
587
- children: [
588
- stat.p99LatencyMs.toFixed(0),
589
- "ms"
590
- ]
591
- }, undefined, true, undefined, this)
592
- ]
593
- }, undefined, true, undefined, this)
594
- ]
595
- }, undefined, true, undefined, this)
596
- ]
597
- }, undefined, true, undefined, this);
598
- }
599
- function AnomalyCard({ anomaly }) {
600
- const severityColors = {
601
- low: "text-amber-400",
602
- medium: "text-orange-400",
603
- high: "text-red-400"
604
- };
605
- return /* @__PURE__ */ jsxDEV("div", {
606
- className: "flex items-center justify-between rounded-lg border border-amber-500/30 bg-amber-500/5 p-3",
607
- children: [
608
- /* @__PURE__ */ jsxDEV("div", {
609
- className: "flex items-center gap-3",
610
- children: [
611
- /* @__PURE__ */ jsxDEV("span", {
612
- className: `text-lg ${severityColors[anomaly.severity]}`,
613
- title: `${anomaly.severity} severity`,
614
- children: anomaly.severity === "high" ? "\uD83D\uDD34" : anomaly.severity === "medium" ? "\uD83D\uDFE0" : "\uD83D\uDFE1"
615
- }, undefined, false, undefined, this),
616
- /* @__PURE__ */ jsxDEV("div", {
617
- children: [
618
- /* @__PURE__ */ jsxDEV("p", {
619
- className: "font-medium text-sm",
620
- children: anomaly.description
621
- }, undefined, false, undefined, this),
622
- /* @__PURE__ */ jsxDEV("p", {
623
- className: "text-muted-foreground text-xs",
624
- children: [
625
- anomaly.operation.name,
626
- " • ",
627
- anomaly.metric
628
- ]
629
- }, undefined, true, undefined, this)
630
- ]
631
- }, undefined, true, undefined, this)
632
- ]
633
- }, undefined, true, undefined, this),
634
- /* @__PURE__ */ jsxDEV(Badge, {
635
- variant: anomaly.severity === "high" ? "destructive" : "secondary",
636
- className: anomaly.severity === "medium" ? "border-amber-500/30 bg-amber-500/20 text-amber-400" : "",
637
- children: anomaly.severity
638
- }, undefined, false, undefined, this)
639
- ]
640
- }, undefined, true, undefined, this);
641
- }
642
- function SuggestionCard({
643
- suggestion,
644
- onApprove,
645
- onReject
646
- }) {
647
- const getStatusStyles = (status) => {
648
- switch (status) {
649
- case "pending":
650
- return {
651
- variant: "secondary",
652
- className: "bg-amber-500/20 text-amber-400 border-amber-500/30"
653
- };
654
- case "approved":
655
- return {
656
- variant: "default",
657
- className: "bg-green-500/20 text-green-400 border-green-500/30"
658
- };
659
- case "rejected":
660
- return { variant: "destructive", className: "" };
661
- default:
662
- return { variant: "secondary", className: "" };
663
- }
664
- };
665
- const statusStyle = getStatusStyles(suggestion.status);
666
- return /* @__PURE__ */ jsxDEV("div", {
667
- className: "rounded-lg border border-violet-500/30 bg-violet-500/5 p-4",
668
- children: [
669
- /* @__PURE__ */ jsxDEV("div", {
670
- className: "mb-2 flex items-start justify-between",
671
- children: [
672
- /* @__PURE__ */ jsxDEV("div", {
673
- className: "flex-1",
674
- children: [
675
- /* @__PURE__ */ jsxDEV("div", {
676
- className: "flex items-center gap-2",
677
- children: [
678
- /* @__PURE__ */ jsxDEV("span", {
679
- className: "text-lg",
680
- children: suggestion.intent.type === "latency-regression" ? "⚡" : suggestion.intent.type === "error-spike" ? "\uD83D\uDD25" : "\uD83D\uDCC9"
681
- }, undefined, false, undefined, this),
682
- /* @__PURE__ */ jsxDEV("h4", {
683
- className: "font-medium",
684
- children: suggestion.proposal.summary
685
- }, undefined, false, undefined, this)
686
- ]
687
- }, undefined, true, undefined, this),
688
- /* @__PURE__ */ jsxDEV("p", {
689
- className: "mt-1 text-muted-foreground text-sm",
690
- children: suggestion.proposal.rationale
691
- }, undefined, false, undefined, this)
692
- ]
693
- }, undefined, true, undefined, this),
694
- /* @__PURE__ */ jsxDEV(Badge, {
695
- variant: statusStyle.variant,
696
- className: statusStyle.className,
697
- children: suggestion.status
698
- }, undefined, false, undefined, this)
699
- ]
700
- }, undefined, true, undefined, this),
701
- suggestion.proposal.recommendedActions && suggestion.proposal.recommendedActions.length > 0 && /* @__PURE__ */ jsxDEV("div", {
702
- className: "mt-3",
703
- children: [
704
- /* @__PURE__ */ jsxDEV("p", {
705
- className: "mb-1 font-semibold text-violet-400 text-xs uppercase",
706
- children: "Recommended Actions"
707
- }, undefined, false, undefined, this),
708
- /* @__PURE__ */ jsxDEV("ul", {
709
- className: "list-inside list-disc space-y-1 text-xs",
710
- children: suggestion.proposal.recommendedActions.slice(0, 3).map((action, i) => /* @__PURE__ */ jsxDEV("li", {
711
- children: action
712
- }, i, false, undefined, this))
713
- }, undefined, false, undefined, this)
714
- ]
715
- }, undefined, true, undefined, this),
716
- /* @__PURE__ */ jsxDEV("div", {
717
- className: "mt-3 flex items-center justify-between",
718
- children: [
719
- /* @__PURE__ */ jsxDEV("div", {
720
- className: "flex items-center gap-2 text-xs",
721
- children: [
722
- /* @__PURE__ */ jsxDEV("span", {
723
- className: "text-muted-foreground",
724
- children: [
725
- "Confidence: ",
726
- (suggestion.confidence * 100).toFixed(0),
727
- "%"
728
- ]
729
- }, undefined, true, undefined, this),
730
- /* @__PURE__ */ jsxDEV("span", {
731
- className: "text-muted-foreground",
732
- children: "•"
733
- }, undefined, false, undefined, this),
734
- /* @__PURE__ */ jsxDEV(Badge, {
735
- variant: "secondary",
736
- children: suggestion.priority
737
- }, undefined, false, undefined, this)
738
- ]
739
- }, undefined, true, undefined, this),
740
- suggestion.status === "pending" && /* @__PURE__ */ jsxDEV("div", {
741
- className: "flex items-center gap-2",
742
- children: [
743
- /* @__PURE__ */ jsxDEV(Button, {
744
- variant: "outline",
745
- size: "sm",
746
- onPress: () => onReject(suggestion.id),
747
- children: "Reject"
748
- }, undefined, false, undefined, this),
749
- /* @__PURE__ */ jsxDEV(Button, {
750
- variant: "default",
751
- size: "sm",
752
- onPress: () => onApprove(suggestion.id),
753
- children: "Approve"
754
- }, undefined, false, undefined, this)
755
- ]
756
- }, undefined, true, undefined, this)
757
- ]
758
- }, undefined, true, undefined, this)
759
- ]
760
- }, undefined, true, undefined, this);
761
- }
762
- function HintCard({ hint }) {
763
- const categoryIcons = {
764
- schema: "\uD83D\uDCD0",
765
- policy: "\uD83D\uDD12",
766
- performance: "⚡",
767
- "error-handling": "\uD83D\uDEE1️"
768
- };
769
- return /* @__PURE__ */ jsxDEV("div", {
770
- className: "rounded-lg border border-blue-500/20 bg-blue-500/5 p-3",
771
- children: /* @__PURE__ */ jsxDEV("div", {
772
- className: "flex items-start gap-3",
773
- children: [
774
- /* @__PURE__ */ jsxDEV("span", {
775
- className: "text-lg",
776
- children: categoryIcons[hint.category]
777
- }, undefined, false, undefined, this),
778
- /* @__PURE__ */ jsxDEV("div", {
779
- className: "flex-1",
780
- children: [
781
- /* @__PURE__ */ jsxDEV("p", {
782
- className: "font-medium",
783
- children: hint.summary
784
- }, undefined, false, undefined, this),
785
- /* @__PURE__ */ jsxDEV("p", {
786
- className: "mt-1 text-muted-foreground text-xs",
787
- children: hint.justification
788
- }, undefined, false, undefined, this),
789
- hint.recommendedActions.length > 0 && /* @__PURE__ */ jsxDEV("ul", {
790
- className: "mt-2 list-inside list-disc text-xs",
791
- children: hint.recommendedActions.slice(0, 2).map((action, i) => /* @__PURE__ */ jsxDEV("li", {
792
- children: action
793
- }, i, false, undefined, this))
794
- }, undefined, false, undefined, this)
795
- ]
796
- }, undefined, true, undefined, this)
797
- ]
798
- }, undefined, true, undefined, this)
799
- }, undefined, false, undefined, this);
800
- }
801
-
802
- // src/EvolutionSidebar.tsx
803
- import { Button as Button2 } from "@contractspec/lib.design-system";
804
- import { Badge as Badge2 } from "@contractspec/lib.ui-kit-web/ui/badge";
805
- import { Card as Card2 } from "@contractspec/lib.ui-kit-web/ui/card";
806
- import { useCallback as useCallback3, useMemo as useMemo3 } from "react";
807
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
808
- "use client";
809
- function EvolutionSidebar({
810
- templateId,
811
- expanded = false,
812
- onToggle,
813
- onLog,
814
- onOpenEvolution
815
- }) {
816
- const {
817
- anomalies,
818
- suggestions,
819
- loading,
820
- approveSuggestion,
821
- rejectSuggestion,
822
- operationCount
823
- } = useEvolution(templateId);
824
- const pendingSuggestions = useMemo3(() => suggestions.filter((s) => s.status === "pending"), [suggestions]);
825
- const topAnomalies = useMemo3(() => anomalies.sort((a, b) => {
826
- const severityOrder = { high: 0, medium: 1, low: 2 };
827
- return severityOrder[a.severity] - severityOrder[b.severity];
828
- }).slice(0, 3), [anomalies]);
829
- const handleApprove = useCallback3((id) => {
830
- approveSuggestion(id);
831
- onLog?.(`Approved suggestion ${id.slice(0, 8)}`);
832
- }, [approveSuggestion, onLog]);
833
- const handleReject = useCallback3((id) => {
834
- rejectSuggestion(id);
835
- onLog?.(`Rejected suggestion ${id.slice(0, 8)}`);
836
- }, [rejectSuggestion, onLog]);
837
- if (!expanded) {
838
- return /* @__PURE__ */ jsxDEV2("button", {
839
- onClick: onToggle,
840
- className: "flex items-center gap-2 rounded-lg border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-sm transition hover:bg-violet-500/20",
841
- type: "button",
842
- children: [
843
- /* @__PURE__ */ jsxDEV2("span", {
844
- children: "\uD83E\uDD16"
845
- }, undefined, false, undefined, this),
846
- /* @__PURE__ */ jsxDEV2("span", {
847
- children: "Evolution"
848
- }, undefined, false, undefined, this),
849
- pendingSuggestions.length > 0 && /* @__PURE__ */ jsxDEV2(Badge2, {
850
- variant: "secondary",
851
- className: "border-amber-500/30 bg-amber-500/20 text-amber-400",
852
- children: pendingSuggestions.length
853
- }, undefined, false, undefined, this),
854
- anomalies.length > 0 && pendingSuggestions.length === 0 && /* @__PURE__ */ jsxDEV2(Badge2, {
855
- variant: "destructive",
856
- children: anomalies.length
857
- }, undefined, false, undefined, this)
858
- ]
859
- }, undefined, true, undefined, this);
860
- }
861
- return /* @__PURE__ */ jsxDEV2(Card2, {
862
- className: "w-80 overflow-hidden",
863
- children: [
864
- /* @__PURE__ */ jsxDEV2("div", {
865
- className: "flex items-center justify-between border-violet-500/20 border-b bg-violet-500/5 px-3 py-2",
866
- children: [
867
- /* @__PURE__ */ jsxDEV2("div", {
868
- className: "flex items-center gap-2",
869
- children: [
870
- /* @__PURE__ */ jsxDEV2("span", {
871
- children: "\uD83E\uDD16"
872
- }, undefined, false, undefined, this),
873
- /* @__PURE__ */ jsxDEV2("span", {
874
- className: "font-semibold text-sm",
875
- children: "Evolution"
876
- }, undefined, false, undefined, this)
877
- ]
878
- }, undefined, true, undefined, this),
879
- /* @__PURE__ */ jsxDEV2("div", {
880
- className: "flex items-center gap-1",
881
- children: [
882
- onOpenEvolution && /* @__PURE__ */ jsxDEV2(Button2, {
883
- variant: "ghost",
884
- size: "sm",
885
- onPress: onOpenEvolution,
886
- children: "Expand"
887
- }, undefined, false, undefined, this),
888
- /* @__PURE__ */ jsxDEV2("button", {
889
- onClick: onToggle,
890
- className: "p-1 text-muted-foreground hover:text-foreground",
891
- type: "button",
892
- title: "Collapse",
893
- children: "✕"
894
- }, undefined, false, undefined, this)
895
- ]
896
- }, undefined, true, undefined, this)
897
- ]
898
- }, undefined, true, undefined, this),
899
- /* @__PURE__ */ jsxDEV2("div", {
900
- className: "max-h-96 overflow-y-auto p-3",
901
- children: [
902
- /* @__PURE__ */ jsxDEV2("div", {
903
- className: "mb-3 flex items-center justify-between text-xs",
904
- children: [
905
- /* @__PURE__ */ jsxDEV2("span", {
906
- className: "text-muted-foreground",
907
- children: [
908
- operationCount,
909
- " ops tracked"
910
- ]
911
- }, undefined, true, undefined, this),
912
- /* @__PURE__ */ jsxDEV2("div", {
913
- className: "flex items-center gap-2",
914
- children: [
915
- anomalies.length > 0 && /* @__PURE__ */ jsxDEV2(Badge2, {
916
- variant: "destructive",
917
- children: [
918
- anomalies.length,
919
- " anomalies"
920
- ]
921
- }, undefined, true, undefined, this),
922
- pendingSuggestions.length > 0 && /* @__PURE__ */ jsxDEV2(Badge2, {
923
- variant: "secondary",
924
- className: "border-amber-500/30 bg-amber-500/20 text-amber-400",
925
- children: [
926
- pendingSuggestions.length,
927
- " pending"
928
- ]
929
- }, undefined, true, undefined, this)
930
- ]
931
- }, undefined, true, undefined, this)
932
- ]
933
- }, undefined, true, undefined, this),
934
- loading && /* @__PURE__ */ jsxDEV2("div", {
935
- className: "py-4 text-center text-muted-foreground text-sm",
936
- children: "Generating suggestions..."
937
- }, undefined, false, undefined, this),
938
- topAnomalies.length > 0 && /* @__PURE__ */ jsxDEV2("div", {
939
- className: "mb-4",
940
- children: [
941
- /* @__PURE__ */ jsxDEV2("p", {
942
- className: "mb-2 font-semibold text-violet-400 text-xs uppercase",
943
- children: "Top Issues"
944
- }, undefined, false, undefined, this),
945
- /* @__PURE__ */ jsxDEV2("div", {
946
- className: "space-y-2",
947
- children: topAnomalies.map((anomaly, index) => /* @__PURE__ */ jsxDEV2("div", {
948
- className: "rounded border border-amber-500/20 bg-amber-500/5 p-2 text-xs",
949
- children: [
950
- /* @__PURE__ */ jsxDEV2("div", {
951
- className: "flex items-center gap-2",
952
- children: [
953
- /* @__PURE__ */ jsxDEV2("span", {
954
- children: anomaly.severity === "high" ? "\uD83D\uDD34" : anomaly.severity === "medium" ? "\uD83D\uDFE0" : "\uD83D\uDFE1"
955
- }, undefined, false, undefined, this),
956
- /* @__PURE__ */ jsxDEV2("span", {
957
- className: "truncate font-medium",
958
- children: anomaly.operation.name
959
- }, undefined, false, undefined, this)
960
- ]
961
- }, undefined, true, undefined, this),
962
- /* @__PURE__ */ jsxDEV2("p", {
963
- className: "mt-1 truncate text-muted-foreground",
964
- children: anomaly.description
965
- }, undefined, false, undefined, this)
966
- ]
967
- }, `${anomaly.operation.name}-${index}`, true, undefined, this))
968
- }, undefined, false, undefined, this)
969
- ]
970
- }, undefined, true, undefined, this),
971
- pendingSuggestions.length > 0 && /* @__PURE__ */ jsxDEV2("div", {
972
- children: [
973
- /* @__PURE__ */ jsxDEV2("p", {
974
- className: "mb-2 font-semibold text-violet-400 text-xs uppercase",
975
- children: "Pending Suggestions"
976
- }, undefined, false, undefined, this),
977
- /* @__PURE__ */ jsxDEV2("div", {
978
- className: "space-y-2",
979
- children: [
980
- pendingSuggestions.slice(0, 3).map((suggestion) => /* @__PURE__ */ jsxDEV2(CompactSuggestionCard, {
981
- suggestion,
982
- onApprove: handleApprove,
983
- onReject: handleReject
984
- }, suggestion.id, false, undefined, this)),
985
- pendingSuggestions.length > 3 && /* @__PURE__ */ jsxDEV2("p", {
986
- className: "text-center text-muted-foreground text-xs",
987
- children: [
988
- "+",
989
- pendingSuggestions.length - 3,
990
- " more suggestions"
991
- ]
992
- }, undefined, true, undefined, this)
993
- ]
994
- }, undefined, true, undefined, this)
995
- ]
996
- }, undefined, true, undefined, this),
997
- anomalies.length === 0 && pendingSuggestions.length === 0 && !loading && /* @__PURE__ */ jsxDEV2("div", {
998
- className: "py-4 text-center text-muted-foreground text-xs",
999
- children: "No issues detected. Keep coding!"
1000
- }, undefined, false, undefined, this)
1001
- ]
1002
- }, undefined, true, undefined, this),
1003
- onOpenEvolution && /* @__PURE__ */ jsxDEV2("div", {
1004
- className: "border-violet-500/20 border-t p-2",
1005
- children: /* @__PURE__ */ jsxDEV2(Button2, {
1006
- variant: "ghost",
1007
- size: "sm",
1008
- className: "w-full",
1009
- onPress: onOpenEvolution,
1010
- children: "Open Evolution Dashboard →"
1011
- }, undefined, false, undefined, this)
1012
- }, undefined, false, undefined, this)
1013
- ]
1014
- }, undefined, true, undefined, this);
1015
- }
1016
- function CompactSuggestionCard({
1017
- suggestion,
1018
- onApprove,
1019
- onReject
1020
- }) {
1021
- return /* @__PURE__ */ jsxDEV2("div", {
1022
- className: "rounded border border-violet-500/20 bg-violet-500/5 p-2",
1023
- children: [
1024
- /* @__PURE__ */ jsxDEV2("div", {
1025
- className: "flex items-start justify-between gap-2",
1026
- children: /* @__PURE__ */ jsxDEV2("div", {
1027
- className: "min-w-0 flex-1",
1028
- children: [
1029
- /* @__PURE__ */ jsxDEV2("p", {
1030
- className: "truncate font-medium text-xs",
1031
- children: suggestion.proposal.summary
1032
- }, undefined, false, undefined, this),
1033
- /* @__PURE__ */ jsxDEV2("div", {
1034
- className: "mt-1 flex items-center gap-2 text-xs",
1035
- children: [
1036
- /* @__PURE__ */ jsxDEV2(Badge2, {
1037
- variant: "secondary",
1038
- children: suggestion.priority
1039
- }, undefined, false, undefined, this),
1040
- /* @__PURE__ */ jsxDEV2("span", {
1041
- className: "text-muted-foreground",
1042
- children: [
1043
- (suggestion.confidence * 100).toFixed(0),
1044
- "%"
1045
- ]
1046
- }, undefined, true, undefined, this)
1047
- ]
1048
- }, undefined, true, undefined, this)
1049
- ]
1050
- }, undefined, true, undefined, this)
1051
- }, undefined, false, undefined, this),
1052
- /* @__PURE__ */ jsxDEV2("div", {
1053
- className: "mt-2 flex justify-end gap-1",
1054
- children: [
1055
- /* @__PURE__ */ jsxDEV2("button", {
1056
- onClick: () => onReject(suggestion.id),
1057
- className: "rounded px-2 py-0.5 text-red-400 text-xs hover:bg-red-400/10",
1058
- type: "button",
1059
- children: "Reject"
1060
- }, undefined, false, undefined, this),
1061
- /* @__PURE__ */ jsxDEV2("button", {
1062
- onClick: () => onApprove(suggestion.id),
1063
- className: "rounded bg-violet-500/20 px-2 py-0.5 text-violet-400 text-xs hover:bg-violet-500/30",
1064
- type: "button",
1065
- children: "Approve"
1066
- }, undefined, false, undefined, this)
1067
- ]
1068
- }, undefined, true, undefined, this)
1069
- ]
1070
- }, undefined, true, undefined, this);
1071
- }
1072
-
1073
- // src/lib/runtime-context.tsx
1074
- import { createContext, useContext } from "react";
1075
- "use client";
1076
- var TEMPLATE_RUNTIME_CONTEXT_KEY = Symbol.for("@contractspec/lib.example-shared-ui/template-runtime-context");
1077
- function getTemplateRuntimeContextSingleton() {
1078
- const store = globalThis;
1079
- store[TEMPLATE_RUNTIME_CONTEXT_KEY] ??= createContext(null);
1080
- return store[TEMPLATE_RUNTIME_CONTEXT_KEY];
1081
- }
1082
- var TemplateRuntimeContext = getTemplateRuntimeContextSingleton();
1083
- function useTemplateRuntime() {
1084
- const context = useContext(TemplateRuntimeContext);
1085
- if (!context) {
1086
- throw new Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");
1087
- }
1088
- return context;
1089
- }
1090
-
1091
- // src/LocalDataIndicator.tsx
1092
- import { RefreshCw, Shield } from "lucide-react";
1093
- import { useState as useState2 } from "react";
1094
- import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1095
- "use client";
1096
- function LocalDataIndicator() {
1097
- const { projectId, templateId, template, installer } = useTemplateRuntime();
1098
- const [isResetting, setIsResetting] = useState2(false);
1099
- const handleReset = async () => {
1100
- setIsResetting(true);
1101
- try {
1102
- await installer.install(templateId, { projectId });
1103
- } finally {
1104
- setIsResetting(false);
1105
- }
1106
- };
1107
- return /* @__PURE__ */ jsxDEV3("div", {
1108
- className: "inline-flex items-center gap-2 rounded-full border border-border bg-muted/40 px-3 py-1 text-muted-foreground text-xs",
1109
- children: [
1110
- /* @__PURE__ */ jsxDEV3(Shield, {
1111
- className: "h-3.5 w-3.5 text-violet-400"
1112
- }, undefined, false, undefined, this),
1113
- /* @__PURE__ */ jsxDEV3("span", {
1114
- children: [
1115
- "Local runtime ·",
1116
- " ",
1117
- /* @__PURE__ */ jsxDEV3("span", {
1118
- className: "font-semibold text-foreground",
1119
- children: template.name
1120
- }, undefined, false, undefined, this)
1121
- ]
1122
- }, undefined, true, undefined, this),
1123
- /* @__PURE__ */ jsxDEV3("button", {
1124
- type: "button",
1125
- className: "inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-semibold text-[11px] text-muted-foreground hover:text-foreground",
1126
- onClick: handleReset,
1127
- disabled: isResetting,
1128
- children: [
1129
- /* @__PURE__ */ jsxDEV3(RefreshCw, {
1130
- className: "h-3 w-3"
1131
- }, undefined, false, undefined, this),
1132
- isResetting ? "Resetting…" : "Reset data"
1133
- ]
1134
- }, undefined, true, undefined, this)
1135
- ]
1136
- }, undefined, true, undefined, this);
1137
- }
1138
-
1139
- // src/markdown/formatPresentationName.ts
1140
- function formatPresentationName(name) {
1141
- const parts = name.split(".");
1142
- const lastPart = parts[parts.length - 1] ?? name;
1143
- return lastPart.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1144
- }
1145
-
1146
- // src/markdown/useMarkdownPresentation.ts
1147
- import { useCallback as useCallback4, useEffect as useEffect2, useState as useState3 } from "react";
1148
- "use client";
1149
- function useMarkdownPresentation({
1150
- engine,
1151
- fetchData,
1152
- presentationId,
1153
- presentations,
1154
- resolvePresentation,
1155
- templateId
1156
- }) {
1157
- const [selectedPresentation, setSelectedPresentation] = useState3("");
1158
- const [markdownContent, setMarkdownContent] = useState3("");
1159
- const [loading, setLoading] = useState3(false);
1160
- const [error, setError] = useState3(null);
1161
- useEffect2(() => {
1162
- if (presentationId && presentations.includes(presentationId)) {
1163
- setSelectedPresentation(presentationId);
1164
- return;
1165
- }
1166
- if (presentations.length === 0) {
1167
- setSelectedPresentation("");
1168
- return;
1169
- }
1170
- if (!presentations.includes(selectedPresentation)) {
1171
- setSelectedPresentation(presentations[0] ?? "");
1172
- }
1173
- }, [presentationId, presentations, selectedPresentation, templateId]);
1174
- const renderMarkdown = useCallback4(async () => {
1175
- if (!selectedPresentation || !engine)
1176
- return;
1177
- setLoading(true);
1178
- setError(null);
1179
- try {
1180
- if (!resolvePresentation) {
1181
- throw new Error("resolvePresentation not available in runtime context");
1182
- }
1183
- const descriptor = resolvePresentation(selectedPresentation);
1184
- if (!descriptor) {
1185
- throw new Error(`Presentation descriptor not found: ${selectedPresentation}`);
1186
- }
1187
- const dataResult = await fetchData(selectedPresentation);
1188
- const result = await engine.render("markdown", descriptor, { data: dataResult.data });
1189
- setMarkdownContent(result.body);
1190
- } catch (err) {
1191
- setError(err instanceof Error ? err : new Error("Failed to render markdown"));
1192
- } finally {
1193
- setLoading(false);
1194
- }
1195
- }, [engine, fetchData, resolvePresentation, selectedPresentation]);
1196
- useEffect2(() => {
1197
- renderMarkdown();
1198
- }, [renderMarkdown]);
1199
- return {
1200
- error,
1201
- loading,
1202
- markdownContent,
1203
- renderMarkdown,
1204
- selectedPresentation,
1205
- setSelectedPresentation
1206
- };
1207
- }
1208
-
1209
- // src/MarkdownView.tsx
1210
- import {
1211
- Button as Button3,
1212
- ErrorState,
1213
- LoaderBlock as LoaderBlock2,
1214
- MarkdownRenderer
1215
- } from "@contractspec/lib.design-system";
1216
- import { Badge as Badge3 } from "@contractspec/lib.ui-kit-web/ui/badge";
1217
- import { Card as Card3 } from "@contractspec/lib.ui-kit-web/ui/card";
1218
- import { useCallback as useCallback5 } from "react";
1219
- import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
1220
- "use client";
1221
- function MarkdownView({
1222
- templateId: propTemplateId,
1223
- presentationId,
1224
- className
1225
- }) {
1226
- const {
1227
- engine,
1228
- template,
1229
- templateId: contextTemplateId,
1230
- resolvePresentation,
1231
- fetchData
1232
- } = useTemplateRuntime();
1233
- const templateId = propTemplateId ?? contextTemplateId;
1234
- const presentations = template?.presentations ?? [];
1235
- const {
1236
- error,
1237
- loading,
1238
- markdownContent,
1239
- renderMarkdown,
1240
- selectedPresentation,
1241
- setSelectedPresentation
1242
- } = useMarkdownPresentation({
1243
- engine,
1244
- fetchData,
1245
- presentationId,
1246
- presentations,
1247
- resolvePresentation,
1248
- templateId
1249
- });
1250
- if (!presentations.length) {
1251
- return /* @__PURE__ */ jsxDEV4(Card3, {
1252
- className,
1253
- children: /* @__PURE__ */ jsxDEV4("div", {
1254
- className: "p-6 text-center",
1255
- children: /* @__PURE__ */ jsxDEV4("p", {
1256
- className: "text-muted-foreground",
1257
- children: "No presentations available for this template."
1258
- }, undefined, false, undefined, this)
1259
- }, undefined, false, undefined, this)
1260
- }, undefined, false, undefined, this);
1261
- }
1262
- const handleCopy = useCallback5(() => {
1263
- if (markdownContent) {
1264
- navigator.clipboard.writeText(markdownContent);
1265
- }
1266
- }, [markdownContent]);
1267
- return /* @__PURE__ */ jsxDEV4("div", {
1268
- className,
1269
- children: [
1270
- /* @__PURE__ */ jsxDEV4("div", {
1271
- className: "mb-4 flex flex-wrap items-center gap-2",
1272
- children: [
1273
- /* @__PURE__ */ jsxDEV4("span", {
1274
- className: "font-medium text-muted-foreground text-sm",
1275
- children: "Presentation:"
1276
- }, undefined, false, undefined, this),
1277
- presentations.map((name) => /* @__PURE__ */ jsxDEV4(Button3, {
1278
- variant: selectedPresentation === name ? "default" : "outline",
1279
- size: "sm",
1280
- onPress: () => setSelectedPresentation(name),
1281
- children: formatPresentationName(name)
1282
- }, name, false, undefined, this)),
1283
- /* @__PURE__ */ jsxDEV4("div", {
1284
- className: "ml-auto flex items-center gap-2",
1285
- children: [
1286
- /* @__PURE__ */ jsxDEV4(Badge3, {
1287
- variant: "secondary",
1288
- children: "LLM-friendly"
1289
- }, undefined, false, undefined, this),
1290
- /* @__PURE__ */ jsxDEV4(Button3, {
1291
- variant: "outline",
1292
- size: "sm",
1293
- onPress: handleCopy,
1294
- disabled: !markdownContent || loading,
1295
- children: "Copy"
1296
- }, undefined, false, undefined, this)
1297
- ]
1298
- }, undefined, true, undefined, this)
1299
- ]
1300
- }, undefined, true, undefined, this),
1301
- /* @__PURE__ */ jsxDEV4(Card3, {
1302
- className: "overflow-hidden",
1303
- children: [
1304
- loading && /* @__PURE__ */ jsxDEV4(LoaderBlock2, {
1305
- label: "Rendering markdown..."
1306
- }, undefined, false, undefined, this),
1307
- error && /* @__PURE__ */ jsxDEV4(ErrorState, {
1308
- title: "Render failed",
1309
- description: error.message,
1310
- onRetry: renderMarkdown,
1311
- retryLabel: "Retry"
1312
- }, undefined, false, undefined, this),
1313
- !loading && !error && markdownContent && /* @__PURE__ */ jsxDEV4("div", {
1314
- className: "p-6",
1315
- children: /* @__PURE__ */ jsxDEV4(MarkdownRenderer, {
1316
- content: markdownContent
1317
- }, undefined, false, undefined, this)
1318
- }, undefined, false, undefined, this),
1319
- !loading && !error && !markdownContent && /* @__PURE__ */ jsxDEV4("div", {
1320
- className: "p-6 text-center",
1321
- children: /* @__PURE__ */ jsxDEV4("p", {
1322
- className: "text-muted-foreground",
1323
- children: "Select a presentation to view its markdown output."
1324
- }, undefined, false, undefined, this)
1325
- }, undefined, false, undefined, this)
1326
- ]
1327
- }, undefined, true, undefined, this)
1328
- ]
1329
- }, undefined, true, undefined, this);
1330
- }
1331
-
1332
- // src/OverlayContextProvider.tsx
1333
- import * as React from "react";
1334
- import { useContext as useContext2, useMemo as useMemo4 } from "react";
1335
- import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
1336
- "use client";
1337
- var OverlayContext = React.createContext(null);
1338
- function OverlayContextProvider({
1339
- templateId,
1340
- role = "user",
1341
- device = "desktop",
1342
- children
1343
- }) {
1344
- const overlays = useMemo4(() => getTemplateOverlays(templateId, role), [templateId, role]);
1345
- const activeOverlays = useMemo4(() => {
1346
- return overlays.filter((overlay) => {
1347
- const conditions = overlay.conditions;
1348
- if (!conditions)
1349
- return true;
1350
- if (conditions.role && !conditions.role.includes(role)) {
1351
- return false;
1352
- }
1353
- if (conditions.device && conditions.device !== "any" && conditions.device !== device) {
1354
- return false;
1355
- }
1356
- return true;
1357
- });
1358
- }, [overlays, role, device]);
1359
- const overlayMap = useMemo4(() => {
1360
- const map = new Map;
1361
- for (const overlay of activeOverlays) {
1362
- map.set(overlay.target, overlay);
1363
- }
1364
- return map;
1365
- }, [activeOverlays]);
1366
- const applyOverlay = useMemo4(() => (path, target) => {
1367
- const overlay = overlayMap.get(path);
1368
- if (!overlay)
1369
- return target;
1370
- let result = { ...target };
1371
- for (const mod of overlay.modifications) {
1372
- switch (mod.op) {
1373
- case "hide":
1374
- result = { ...result, hidden: true };
1375
- break;
1376
- case "relabel":
1377
- result = { ...result, label: mod.label };
1378
- break;
1379
- case "reorder":
1380
- result = { ...result, position: mod.position };
1381
- break;
1382
- case "restyle":
1383
- result = {
1384
- ...result,
1385
- className: mod.className,
1386
- variant: mod.variant
1387
- };
1388
- break;
1389
- case "set-default":
1390
- result = { ...result, defaultValue: mod.value };
1391
- break;
1392
- }
1393
- }
1394
- return result;
1395
- }, [overlayMap]);
1396
- const isHidden = useMemo4(() => (path) => {
1397
- const overlay = overlayMap.get(path);
1398
- return overlay?.modifications.some((m) => m.op === "hide") ?? false;
1399
- }, [overlayMap]);
1400
- const getLabel = useMemo4(() => (path, defaultLabel) => {
1401
- const overlay = overlayMap.get(path);
1402
- const relabel = overlay?.modifications.find((m) => m.op === "relabel");
1403
- return relabel && relabel.op === "relabel" ? relabel.label : defaultLabel;
1404
- }, [overlayMap]);
1405
- const getPosition = useMemo4(() => (path, defaultPosition) => {
1406
- const overlay = overlayMap.get(path);
1407
- const reorder = overlay?.modifications.find((m) => m.op === "reorder");
1408
- return reorder && reorder.op === "reorder" ? reorder.position : defaultPosition;
1409
- }, [overlayMap]);
1410
- const getStyle = useMemo4(() => (path) => {
1411
- const overlay = overlayMap.get(path);
1412
- const restyle = overlay?.modifications.find((m) => m.op === "restyle");
1413
- if (restyle && restyle.op === "restyle") {
1414
- return {
1415
- className: restyle.className,
1416
- variant: restyle.variant
1417
- };
1418
- }
1419
- return {};
1420
- }, [overlayMap]);
1421
- const getDefault = useMemo4(() => (path, defaultValue) => {
1422
- const overlay = overlayMap.get(path);
1423
- const setDefault = overlay?.modifications.find((m) => m.op === "set-default");
1424
- return setDefault && setDefault.op === "set-default" ? setDefault.value : defaultValue;
1425
- }, [overlayMap]);
1426
- const value = useMemo4(() => ({
1427
- overlays: activeOverlays,
1428
- applyOverlay,
1429
- isHidden,
1430
- getLabel,
1431
- getPosition,
1432
- getStyle,
1433
- getDefault,
1434
- role,
1435
- device
1436
- }), [
1437
- activeOverlays,
1438
- applyOverlay,
1439
- isHidden,
1440
- getLabel,
1441
- getPosition,
1442
- getStyle,
1443
- getDefault,
1444
- role,
1445
- device
1446
- ]);
1447
- return /* @__PURE__ */ jsxDEV5(OverlayContext.Provider, {
1448
- value,
1449
- children
1450
- }, undefined, false, undefined, this);
1451
- }
1452
- function useOverlayContext() {
1453
- const context = useContext2(OverlayContext);
1454
- if (!context) {
1455
- throw new Error("useOverlayContext must be used within an OverlayContextProvider");
1456
- }
1457
- return context;
1458
- }
1459
- function useIsInOverlayContext() {
1460
- return useContext2(OverlayContext) !== null;
1461
- }
1462
- function getTemplateOverlays(templateId, _role) {
1463
- const templateOverlays = {
1464
- "crm-pipeline": [
1465
- {
1466
- id: "crm-hide-internal-fields",
1467
- target: "deal.internalNotes",
1468
- modifications: [{ op: "hide" }],
1469
- conditions: { role: ["viewer", "user"] }
1470
- },
1471
- {
1472
- id: "crm-relabel-value",
1473
- target: "deal.value",
1474
- modifications: [{ op: "relabel", label: "Deal Amount" }]
1475
- }
1476
- ],
1477
- "saas-boilerplate": [
1478
- {
1479
- id: "saas-hide-billing",
1480
- target: "settings.billing",
1481
- modifications: [{ op: "hide" }],
1482
- conditions: { role: ["viewer"] }
1483
- },
1484
- {
1485
- id: "saas-restyle-plan",
1486
- target: "settings.plan",
1487
- modifications: [{ op: "restyle", variant: "premium" }],
1488
- conditions: { role: ["admin"] }
1489
- }
1490
- ],
1491
- "agent-console": [
1492
- {
1493
- id: "agent-hide-cost",
1494
- target: "run.cost",
1495
- modifications: [{ op: "hide" }],
1496
- conditions: { role: ["viewer"] }
1497
- },
1498
- {
1499
- id: "agent-relabel-tokens",
1500
- target: "run.tokens",
1501
- modifications: [{ op: "relabel", label: "Token Usage" }]
1502
- }
1503
- ],
1504
- "todos-app": [
1505
- {
1506
- id: "todos-hide-assignee",
1507
- target: "task.assignee",
1508
- modifications: [{ op: "hide" }],
1509
- conditions: { device: "mobile" }
1510
- }
1511
- ],
1512
- "messaging-app": [
1513
- {
1514
- id: "messaging-reorder-timestamp",
1515
- target: "message.timestamp",
1516
- modifications: [{ op: "reorder", position: 0 }]
1517
- }
1518
- ],
1519
- "recipe-app-i18n": [
1520
- {
1521
- id: "recipe-relabel-servings",
1522
- target: "recipe.servings",
1523
- modifications: [{ op: "relabel", label: "Portions" }]
1524
- }
1525
- ]
1526
- };
1527
- return templateOverlays[templateId] ?? [];
1528
- }
1529
-
1530
- // src/hooks/useBehaviorTracking.ts
1531
- import { useCallback as useCallback6, useEffect as useEffect3, useMemo as useMemo5, useRef as useRef2, useState as useState4 } from "react";
1532
- "use client";
1533
- var BEHAVIOR_STORAGE_KEY = "contractspec-behavior-data";
1534
- var ALL_FEATURES = [
1535
- "playground",
1536
- "specs",
1537
- "builder",
1538
- "markdown",
1539
- "evolution",
1540
- "canvas_add",
1541
- "canvas_delete",
1542
- "spec_save",
1543
- "spec_validate",
1544
- "ai_suggestions"
1545
- ];
1546
- function useBehaviorTracking(templateId) {
1547
- const [events, setEvents] = useState4([]);
1548
- const sessionStartRef = useRef2(new Date);
1549
- const [eventCount, setEventCount] = useState4(0);
1550
- useEffect3(() => {
1551
- try {
1552
- const stored = localStorage.getItem(BEHAVIOR_STORAGE_KEY);
1553
- if (stored) {
1554
- const data = JSON.parse(stored);
1555
- setEvents(data.events.map((e) => ({
1556
- ...e,
1557
- timestamp: new Date(e.timestamp)
1558
- })));
1559
- sessionStartRef.current = new Date(data.sessionStart);
1560
- }
1561
- } catch {}
1562
- }, []);
1563
- useEffect3(() => {
1564
- if (events.length > 0) {
1565
- try {
1566
- localStorage.setItem(BEHAVIOR_STORAGE_KEY, JSON.stringify({
1567
- events: events.map((e) => ({
1568
- ...e,
1569
- timestamp: e.timestamp.toISOString()
1570
- })),
1571
- sessionStart: sessionStartRef.current.toISOString()
1572
- }));
1573
- } catch {}
1574
- }
1575
- }, [events]);
1576
- const trackEvent = useCallback6((type, metadata) => {
1577
- const event = {
1578
- type,
1579
- timestamp: new Date,
1580
- templateId,
1581
- metadata
1582
- };
1583
- setEvents((prev) => [...prev, event]);
1584
- setEventCount((prev) => prev + 1);
1585
- }, [templateId]);
1586
- const getEventsByType = useCallback6((type) => {
1587
- return events.filter((e) => e.type === type);
1588
- }, [events]);
1589
- const getSummary = useCallback6(() => {
1590
- const now = new Date;
1591
- const sessionDuration = now.getTime() - sessionStartRef.current.getTime();
1592
- const templateCounts = new Map;
1593
- for (const event of events) {
1594
- const count = templateCounts.get(event.templateId) ?? 0;
1595
- templateCounts.set(event.templateId, count + 1);
1596
- }
1597
- const mostUsedTemplates = Array.from(templateCounts.entries()).map(([templateId2, count]) => ({ templateId: templateId2, count })).sort((a, b) => b.count - a.count).slice(0, 3);
1598
- const modeCounts = new Map;
1599
- for (const event of events) {
1600
- if (event.type === "mode_change" && event.metadata?.mode) {
1601
- const mode = event.metadata.mode;
1602
- const count = modeCounts.get(mode) ?? 0;
1603
- modeCounts.set(mode, count + 1);
1604
- }
1605
- }
1606
- const mostUsedModes = Array.from(modeCounts.entries()).map(([mode, count]) => ({ mode, count })).sort((a, b) => b.count - a.count);
1607
- const featuresUsed = new Set;
1608
- for (const event of events) {
1609
- if (event.type === "mode_change" && event.metadata?.mode) {
1610
- featuresUsed.add(event.metadata.mode);
1611
- }
1612
- if (event.type === "feature_usage" && event.metadata?.feature) {
1613
- featuresUsed.add(event.metadata.feature);
1614
- }
1615
- if (event.type === "canvas_interaction") {
1616
- const action = event.metadata?.action;
1617
- if (action === "add")
1618
- featuresUsed.add("canvas_add");
1619
- if (action === "delete")
1620
- featuresUsed.add("canvas_delete");
1621
- }
1622
- if (event.type === "spec_edit") {
1623
- const action = event.metadata?.action;
1624
- if (action === "save")
1625
- featuresUsed.add("spec_save");
1626
- if (action === "validate")
1627
- featuresUsed.add("spec_validate");
1628
- }
1629
- }
1630
- const unusedFeatures = ALL_FEATURES.filter((f) => !featuresUsed.has(f));
1631
- const errorCount = events.filter((e) => e.type === "error").length;
1632
- const recommendations = generateRecommendations(Array.from(featuresUsed), unusedFeatures, mostUsedModes, events.length);
1633
- return {
1634
- totalEvents: events.length,
1635
- sessionDuration,
1636
- mostUsedTemplates,
1637
- mostUsedModes,
1638
- featuresUsed: Array.from(featuresUsed),
1639
- unusedFeatures,
1640
- errorCount,
1641
- recommendations
1642
- };
1643
- }, [events]);
1644
- const clear = useCallback6(() => {
1645
- setEvents([]);
1646
- setEventCount(0);
1647
- sessionStartRef.current = new Date;
1648
- localStorage.removeItem(BEHAVIOR_STORAGE_KEY);
1649
- }, []);
1650
- return useMemo5(() => ({
1651
- trackEvent,
1652
- getSummary,
1653
- getEventsByType,
1654
- eventCount,
1655
- sessionStart: sessionStartRef.current,
1656
- clear
1657
- }), [trackEvent, getSummary, getEventsByType, eventCount, clear]);
1658
- }
1659
- function generateRecommendations(featuresUsed, unusedFeatures, mostUsedModes, totalEvents) {
1660
- const recommendations = [];
1661
- if (unusedFeatures.includes("evolution")) {
1662
- recommendations.push("Try the AI Evolution mode to get automated improvement suggestions");
1663
- }
1664
- if (unusedFeatures.includes("markdown")) {
1665
- recommendations.push("Use Markdown preview to see documentation for your specs");
1666
- }
1667
- if (unusedFeatures.includes("builder")) {
1668
- recommendations.push("Explore the Visual Builder to design your UI components");
1669
- }
1670
- if (!featuresUsed.includes("spec_validate") && featuresUsed.includes("specs")) {
1671
- recommendations.push("Don't forget to validate your specs before saving");
1672
- }
1673
- if (featuresUsed.includes("evolution") && !featuresUsed.includes("ai_suggestions")) {
1674
- recommendations.push("Generate AI suggestions to get actionable improvement recommendations");
1675
- }
1676
- if (totalEvents > 50) {
1677
- recommendations.push("Great engagement! Consider saving your work regularly");
1678
- }
1679
- if (mostUsedModes.length === 1) {
1680
- recommendations.push("Try different modes to explore all sandbox capabilities");
1681
- }
1682
- return recommendations;
1683
- }
1684
-
1685
- // src/PersonalizationInsights.tsx
1686
- import { Button as Button4 } from "@contractspec/lib.design-system";
1687
- import { Badge as Badge4 } from "@contractspec/lib.ui-kit-web/ui/badge";
1688
- import { Card as Card4 } from "@contractspec/lib.ui-kit-web/ui/card";
1689
- import { useCallback as useCallback7, useMemo as useMemo6, useState as useState5 } from "react";
1690
- import { jsxDEV as jsxDEV6 } from "react/jsx-dev-runtime";
1691
- "use client";
1692
- function PersonalizationInsights({
1693
- templateId,
1694
- collapsed = false,
1695
- onToggle
1696
- }) {
1697
- const { getSummary, eventCount, clear, sessionStart } = useBehaviorTracking(templateId);
1698
- const [showDetails, setShowDetails] = useState5(false);
1699
- const summary = useMemo6(() => getSummary(), [getSummary]);
1700
- const formatDuration = useCallback7((ms) => {
1701
- const seconds = Math.floor(ms / 1000);
1702
- const minutes = Math.floor(seconds / 60);
1703
- const hours = Math.floor(minutes / 60);
1704
- if (hours > 0) {
1705
- return `${hours}h ${minutes % 60}m`;
1706
- }
1707
- if (minutes > 0) {
1708
- return `${minutes}m ${seconds % 60}s`;
1709
- }
1710
- return `${seconds}s`;
1711
- }, []);
1712
- const handleClear = useCallback7(() => {
1713
- clear();
1714
- }, [clear]);
1715
- if (collapsed) {
1716
- return /* @__PURE__ */ jsxDEV6("button", {
1717
- onClick: onToggle,
1718
- className: "flex items-center gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2 text-sm transition hover:bg-blue-500/20",
1719
- type: "button",
1720
- children: [
1721
- /* @__PURE__ */ jsxDEV6("span", {
1722
- children: "\uD83D\uDCCA"
1723
- }, undefined, false, undefined, this),
1724
- /* @__PURE__ */ jsxDEV6("span", {
1725
- children: "Insights"
1726
- }, undefined, false, undefined, this),
1727
- /* @__PURE__ */ jsxDEV6(Badge4, {
1728
- variant: "secondary",
1729
- children: eventCount
1730
- }, undefined, false, undefined, this)
1731
- ]
1732
- }, undefined, true, undefined, this);
1733
- }
1734
- return /* @__PURE__ */ jsxDEV6(Card4, {
1735
- className: "overflow-hidden",
1736
- children: [
1737
- /* @__PURE__ */ jsxDEV6("div", {
1738
- className: "flex items-center justify-between border-blue-500/20 border-b bg-blue-500/5 px-4 py-3",
1739
- children: [
1740
- /* @__PURE__ */ jsxDEV6("div", {
1741
- className: "flex items-center gap-2",
1742
- children: [
1743
- /* @__PURE__ */ jsxDEV6("span", {
1744
- children: "\uD83D\uDCCA"
1745
- }, undefined, false, undefined, this),
1746
- /* @__PURE__ */ jsxDEV6("span", {
1747
- className: "font-semibold",
1748
- children: "Personalization Insights"
1749
- }, undefined, false, undefined, this)
1750
- ]
1751
- }, undefined, true, undefined, this),
1752
- /* @__PURE__ */ jsxDEV6("div", {
1753
- className: "flex items-center gap-2",
1754
- children: [
1755
- /* @__PURE__ */ jsxDEV6(Button4, {
1756
- variant: "ghost",
1757
- size: "sm",
1758
- onPress: () => setShowDetails(!showDetails),
1759
- children: showDetails ? "Hide Details" : "Show Details"
1760
- }, undefined, false, undefined, this),
1761
- onToggle && /* @__PURE__ */ jsxDEV6("button", {
1762
- onClick: onToggle,
1763
- className: "p-1 text-muted-foreground hover:text-foreground",
1764
- type: "button",
1765
- title: "Collapse",
1766
- children: "✕"
1767
- }, undefined, false, undefined, this)
1768
- ]
1769
- }, undefined, true, undefined, this)
1770
- ]
1771
- }, undefined, true, undefined, this),
1772
- /* @__PURE__ */ jsxDEV6("div", {
1773
- className: "p-4",
1774
- children: [
1775
- /* @__PURE__ */ jsxDEV6("div", {
1776
- className: "mb-4 grid grid-cols-2 gap-3 md:grid-cols-4",
1777
- children: [
1778
- /* @__PURE__ */ jsxDEV6(StatCard, {
1779
- label: "Session Time",
1780
- value: formatDuration(summary.sessionDuration),
1781
- icon: "⏱️"
1782
- }, undefined, false, undefined, this),
1783
- /* @__PURE__ */ jsxDEV6(StatCard, {
1784
- label: "Events Tracked",
1785
- value: summary.totalEvents.toString(),
1786
- icon: "\uD83D\uDCC8"
1787
- }, undefined, false, undefined, this),
1788
- /* @__PURE__ */ jsxDEV6(StatCard, {
1789
- label: "Features Used",
1790
- value: `${summary.featuresUsed.length}/${summary.featuresUsed.length + summary.unusedFeatures.length}`,
1791
- icon: "✨"
1792
- }, undefined, false, undefined, this),
1793
- /* @__PURE__ */ jsxDEV6(StatCard, {
1794
- label: "Errors",
1795
- value: summary.errorCount.toString(),
1796
- icon: "⚠️",
1797
- variant: summary.errorCount > 0 ? "warning" : "success"
1798
- }, undefined, false, undefined, this)
1799
- ]
1800
- }, undefined, true, undefined, this),
1801
- summary.recommendations.length > 0 && /* @__PURE__ */ jsxDEV6("div", {
1802
- className: "mb-4",
1803
- children: [
1804
- /* @__PURE__ */ jsxDEV6("h4", {
1805
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1806
- children: "Recommendations"
1807
- }, undefined, false, undefined, this),
1808
- /* @__PURE__ */ jsxDEV6("ul", {
1809
- className: "space-y-1",
1810
- children: summary.recommendations.map((rec, index) => /* @__PURE__ */ jsxDEV6("li", {
1811
- className: "flex items-start gap-2 text-sm",
1812
- children: [
1813
- /* @__PURE__ */ jsxDEV6("span", {
1814
- className: "text-blue-400",
1815
- children: "\uD83D\uDCA1"
1816
- }, undefined, false, undefined, this),
1817
- /* @__PURE__ */ jsxDEV6("span", {
1818
- children: rec
1819
- }, undefined, false, undefined, this)
1820
- ]
1821
- }, index, true, undefined, this))
1822
- }, undefined, false, undefined, this)
1823
- ]
1824
- }, undefined, true, undefined, this),
1825
- summary.unusedFeatures.length > 0 && /* @__PURE__ */ jsxDEV6("div", {
1826
- className: "mb-4",
1827
- children: [
1828
- /* @__PURE__ */ jsxDEV6("h4", {
1829
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1830
- children: "Try These Features"
1831
- }, undefined, false, undefined, this),
1832
- /* @__PURE__ */ jsxDEV6("div", {
1833
- className: "flex flex-wrap gap-2",
1834
- children: summary.unusedFeatures.slice(0, 5).map((feature) => /* @__PURE__ */ jsxDEV6(Badge4, {
1835
- variant: "secondary",
1836
- children: formatFeatureName(feature)
1837
- }, feature, false, undefined, this))
1838
- }, undefined, false, undefined, this)
1839
- ]
1840
- }, undefined, true, undefined, this),
1841
- showDetails && /* @__PURE__ */ jsxDEV6(DetailedInsights, {
1842
- summary,
1843
- sessionStart
1844
- }, undefined, false, undefined, this),
1845
- /* @__PURE__ */ jsxDEV6("div", {
1846
- className: "mt-4 flex justify-end border-blue-500/10 border-t pt-4",
1847
- children: /* @__PURE__ */ jsxDEV6(Button4, {
1848
- variant: "ghost",
1849
- size: "sm",
1850
- onPress: handleClear,
1851
- children: "Clear Data"
1852
- }, undefined, false, undefined, this)
1853
- }, undefined, false, undefined, this)
1854
- ]
1855
- }, undefined, true, undefined, this)
1856
- ]
1857
- }, undefined, true, undefined, this);
1858
- }
1859
- function StatCard({
1860
- label,
1861
- value,
1862
- icon,
1863
- variant = "default"
1864
- }) {
1865
- const bgColors = {
1866
- default: "bg-blue-500/5 border-blue-500/20",
1867
- warning: "bg-amber-500/5 border-amber-500/20",
1868
- success: "bg-green-500/5 border-green-500/20"
1869
- };
1870
- return /* @__PURE__ */ jsxDEV6("div", {
1871
- className: `rounded-lg border p-3 text-center ${bgColors[variant]}`,
1872
- children: [
1873
- /* @__PURE__ */ jsxDEV6("div", {
1874
- className: "mb-1 text-lg",
1875
- children: icon
1876
- }, undefined, false, undefined, this),
1877
- /* @__PURE__ */ jsxDEV6("div", {
1878
- className: "font-bold text-lg",
1879
- children: value
1880
- }, undefined, false, undefined, this),
1881
- /* @__PURE__ */ jsxDEV6("div", {
1882
- className: "text-muted-foreground text-xs",
1883
- children: label
1884
- }, undefined, false, undefined, this)
1885
- ]
1886
- }, undefined, true, undefined, this);
1887
- }
1888
- function DetailedInsights({
1889
- summary,
1890
- sessionStart
1891
- }) {
1892
- return /* @__PURE__ */ jsxDEV6("div", {
1893
- className: "mt-4 space-y-4 border-blue-500/10 border-t pt-4",
1894
- children: [
1895
- summary.mostUsedTemplates.length > 0 && /* @__PURE__ */ jsxDEV6("div", {
1896
- children: [
1897
- /* @__PURE__ */ jsxDEV6("h4", {
1898
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1899
- children: "Most Used Templates"
1900
- }, undefined, false, undefined, this),
1901
- /* @__PURE__ */ jsxDEV6("div", {
1902
- className: "space-y-1",
1903
- children: summary.mostUsedTemplates.map(({ templateId, count }) => /* @__PURE__ */ jsxDEV6("div", {
1904
- className: "flex items-center justify-between text-sm",
1905
- children: [
1906
- /* @__PURE__ */ jsxDEV6("span", {
1907
- children: formatTemplateId(templateId)
1908
- }, undefined, false, undefined, this),
1909
- /* @__PURE__ */ jsxDEV6("span", {
1910
- className: "text-muted-foreground",
1911
- children: [
1912
- count,
1913
- " events"
1914
- ]
1915
- }, undefined, true, undefined, this)
1916
- ]
1917
- }, templateId, true, undefined, this))
1918
- }, undefined, false, undefined, this)
1919
- ]
1920
- }, undefined, true, undefined, this),
1921
- summary.mostUsedModes.length > 0 && /* @__PURE__ */ jsxDEV6("div", {
1922
- children: [
1923
- /* @__PURE__ */ jsxDEV6("h4", {
1924
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1925
- children: "Mode Usage"
1926
- }, undefined, false, undefined, this),
1927
- /* @__PURE__ */ jsxDEV6("div", {
1928
- className: "space-y-1",
1929
- children: summary.mostUsedModes.map(({ mode, count }) => /* @__PURE__ */ jsxDEV6("div", {
1930
- className: "flex items-center justify-between text-sm",
1931
- children: [
1932
- /* @__PURE__ */ jsxDEV6("span", {
1933
- children: formatFeatureName(mode)
1934
- }, undefined, false, undefined, this),
1935
- /* @__PURE__ */ jsxDEV6("span", {
1936
- className: "text-muted-foreground",
1937
- children: [
1938
- count,
1939
- " switches"
1940
- ]
1941
- }, undefined, true, undefined, this)
1942
- ]
1943
- }, mode, true, undefined, this))
1944
- }, undefined, false, undefined, this)
1945
- ]
1946
- }, undefined, true, undefined, this),
1947
- /* @__PURE__ */ jsxDEV6("div", {
1948
- children: [
1949
- /* @__PURE__ */ jsxDEV6("h4", {
1950
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1951
- children: "Features Used"
1952
- }, undefined, false, undefined, this),
1953
- /* @__PURE__ */ jsxDEV6("div", {
1954
- className: "flex flex-wrap gap-2",
1955
- children: summary.featuresUsed.map((feature) => /* @__PURE__ */ jsxDEV6(Badge4, {
1956
- variant: "default",
1957
- className: "border-green-500/30 bg-green-500/20 text-green-400",
1958
- children: [
1959
- "✓ ",
1960
- formatFeatureName(feature)
1961
- ]
1962
- }, feature, true, undefined, this))
1963
- }, undefined, false, undefined, this)
1964
- ]
1965
- }, undefined, true, undefined, this),
1966
- /* @__PURE__ */ jsxDEV6("div", {
1967
- className: "text-muted-foreground text-xs",
1968
- children: [
1969
- "Session started: ",
1970
- sessionStart.toLocaleString()
1971
- ]
1972
- }, undefined, true, undefined, this)
1973
- ]
1974
- }, undefined, true, undefined, this);
1975
- }
1976
- function formatFeatureName(feature) {
1977
- return feature.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
1978
- }
1979
- function formatTemplateId(id) {
1980
- return id.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
1981
- }
1982
-
1983
- // src/SaveToStudioButton.tsx
1984
- import { Sparkles } from "lucide-react";
1985
- import { useState as useState6 } from "react";
1986
- import { jsxDEV as jsxDEV7 } from "react/jsx-dev-runtime";
1987
- "use client";
1988
- function SaveToStudioButton({
1989
- organizationId = "demo-org",
1990
- projectName,
1991
- endpoint,
1992
- token
1993
- }) {
1994
- const { installer, templateId, template } = useTemplateRuntime();
1995
- const [status, setStatus] = useState6("idle");
1996
- const [error, setError] = useState6(null);
1997
- const handleSave = async () => {
1998
- setStatus("saving");
1999
- setError(null);
2000
- try {
2001
- await installer.saveToStudio({
2002
- templateId,
2003
- projectName: projectName ?? `${template.name} demo`,
2004
- organizationId,
2005
- endpoint,
2006
- token
2007
- });
2008
- setStatus("saved");
2009
- setTimeout(() => setStatus("idle"), 3000);
2010
- } catch (err) {
2011
- setStatus("error");
2012
- setError(err instanceof Error ? err.message : "Unknown error");
2013
- }
2014
- };
2015
- return /* @__PURE__ */ jsxDEV7("div", {
2016
- className: "flex flex-col items-end gap-1",
2017
- children: [
2018
- /* @__PURE__ */ jsxDEV7("button", {
2019
- type: "button",
2020
- className: "btn-primary inline-flex items-center gap-2 text-sm",
2021
- onClick: handleSave,
2022
- disabled: status === "saving",
2023
- children: [
2024
- /* @__PURE__ */ jsxDEV7(Sparkles, {
2025
- className: "h-4 w-4"
2026
- }, undefined, false, undefined, this),
2027
- status === "saving" ? "Publishing…" : "Save to Studio"
2028
- ]
2029
- }, undefined, true, undefined, this),
2030
- status === "error" && error ? /* @__PURE__ */ jsxDEV7("p", {
2031
- className: "text-destructive text-xs",
2032
- children: error
2033
- }, undefined, false, undefined, this) : null,
2034
- status === "saved" ? /* @__PURE__ */ jsxDEV7("p", {
2035
- className: "text-emerald-400 text-xs",
2036
- children: "Template sent to Studio."
2037
- }, undefined, false, undefined, this) : null
2038
- ]
2039
- }, undefined, true, undefined, this);
2040
- }
2041
-
2042
- // src/SpecDrivenTemplateShell.tsx
2043
- import {
2044
- BundleProvider,
2045
- BundleRenderer
2046
- } from "@contractspec/lib.surface-runtime/react";
2047
- import { jsxDEV as jsxDEV8 } from "react/jsx-dev-runtime";
2048
- function SpecDrivenTemplateShell({
2049
- plan,
2050
- title,
2051
- description,
2052
- sidebar,
2053
- actions,
2054
- showSaveAction = true,
2055
- saveProps,
2056
- children
2057
- }) {
2058
- const headerContent = /* @__PURE__ */ jsxDEV8("header", {
2059
- className: "rounded-2xl border border-border bg-card p-6 shadow-sm",
2060
- children: [
2061
- /* @__PURE__ */ jsxDEV8("div", {
2062
- className: "flex flex-wrap items-center justify-between gap-4",
2063
- children: [
2064
- /* @__PURE__ */ jsxDEV8("div", {
2065
- children: [
2066
- /* @__PURE__ */ jsxDEV8("p", {
2067
- className: "font-semibold text-muted-foreground text-sm uppercase tracking-wide",
2068
- children: "ContractSpec Templates"
2069
- }, undefined, false, undefined, this),
2070
- /* @__PURE__ */ jsxDEV8("h1", {
2071
- className: "font-bold text-3xl",
2072
- children: title
2073
- }, undefined, false, undefined, this),
2074
- description ? /* @__PURE__ */ jsxDEV8("p", {
2075
- className: "mt-2 max-w-2xl text-muted-foreground text-sm",
2076
- children: description
2077
- }, undefined, false, undefined, this) : null
2078
- ]
2079
- }, undefined, true, undefined, this),
2080
- /* @__PURE__ */ jsxDEV8("div", {
2081
- className: "flex flex-col items-end gap-2",
2082
- children: [
2083
- /* @__PURE__ */ jsxDEV8(LocalDataIndicator, {}, undefined, false, undefined, this),
2084
- showSaveAction ? /* @__PURE__ */ jsxDEV8(SaveToStudioButton, {
2085
- ...saveProps
2086
- }, undefined, false, undefined, this) : null
2087
- ]
2088
- }, undefined, true, undefined, this)
2089
- ]
2090
- }, undefined, true, undefined, this),
2091
- actions ? /* @__PURE__ */ jsxDEV8("div", {
2092
- className: "mt-4",
2093
- children: actions
2094
- }, undefined, false, undefined, this) : null
2095
- ]
2096
- }, undefined, true, undefined, this);
2097
- const slotContent = {
2098
- header: headerContent,
2099
- primary: /* @__PURE__ */ jsxDEV8("main", {
2100
- className: "space-y-4 p-2",
2101
- children
2102
- }, undefined, false, undefined, this)
2103
- };
2104
- if (sidebar != null) {
2105
- slotContent.sidebar = /* @__PURE__ */ jsxDEV8("aside", {
2106
- className: "rounded-2xl border border-border bg-card p-4",
2107
- children: sidebar
2108
- }, undefined, false, undefined, this);
2109
- }
2110
- return /* @__PURE__ */ jsxDEV8(BundleProvider, {
2111
- plan,
2112
- children: /* @__PURE__ */ jsxDEV8(BundleRenderer, {
2113
- slotContent
2114
- }, undefined, false, undefined, this)
2115
- }, undefined, false, undefined, this);
2116
- }
2117
-
2118
- // src/utils/generateSpecFromTemplate.ts
2119
- function generateSpecFromTemplate(template) {
2120
- const templateId = template?.id ?? "unknown";
2121
- if (!template) {
2122
- return generateDefaultSpec(templateId);
2123
- }
2124
- switch (templateId) {
2125
- case "crm-pipeline":
2126
- return generateCrmPipelineSpec(template.schema.contracts);
2127
- case "saas-boilerplate":
2128
- return generateSaasBoilerplateSpec(template.schema.contracts);
2129
- case "agent-console":
2130
- return generateAgentConsoleSpec(template.schema.contracts);
2131
- case "todos-app":
2132
- return generateTodosSpec(template.schema.contracts);
2133
- case "messaging-app":
2134
- return generateMessagingSpec(template.schema.contracts);
2135
- case "recipe-app-i18n":
2136
- return generateRecipeSpec(template.schema.contracts);
2137
- default:
2138
- return generateDefaultSpec(templateId);
2139
- }
2140
- }
2141
- function generateCrmPipelineSpec(contracts) {
2142
- return `// CRM Pipeline Specs
2143
- // Contracts: ${contracts.join(", ")}
1
+ import{useCallback as d,useEffect as B0,useMemo as $1,useRef as N1,useState as m}from"react";var D0="contractspec-evolution-data";function q0($){let[N,q]=m([]),[J,X]=m([]),[K,z]=m([]),[U,w]=m([]),[V,f]=m(!1),F=N1([]),[Y,b]=m(0);B0(()=>{try{let P=localStorage.getItem(`${D0}-${$}`);if(P){let G=JSON.parse(P);z(G.suggestions.map((M)=>({...M,createdAt:new Date(M.createdAt)})))}}catch{}},[$]),B0(()=>{try{localStorage.setItem(`${D0}-${$}`,JSON.stringify({suggestions:K}))}catch{}},[K,$]);let W=d((P,G,M,E)=>{let u={operation:{name:P,version:"1.0.0",tenantId:"sandbox"},durationMs:G,success:M,timestamp:new Date,errorCode:E};F.current.push(u),b((B)=>B+1)},[]),Q=d(()=>{let P=F.current;if(P.length<5)return;let G=new Map;for(let B of P){let y=`${B.operation.name}.v${B.operation.version}`,a=G.get(y)??[];a.push(B),G.set(y,a)}let M=[],E=[];G.forEach((B)=>{if(B.length<3)return;let y=B.map((k)=>k.durationMs).sort((k,x)=>k-x),a=B.filter((k)=>!k.success),F0=B.length,j=a.length/F0,e0=y.reduce((k,x)=>k+x,0)/F0,Y0=B.map((k)=>k.timestamp.getTime()),O0=B[0];if(!O0)return;let c={operation:O0.operation,totalCalls:F0,successRate:1-j,errorRate:j,averageLatencyMs:e0,p95LatencyMs:L0(y,0.95),p99LatencyMs:L0(y,0.99),maxLatencyMs:Math.max(...y),lastSeenAt:new Date(Math.max(...Y0)),windowStart:new Date(Math.min(...Y0)),windowEnd:new Date(Math.max(...Y0)),topErrors:a.reduce((k,x)=>{if(x.errorCode)k[x.errorCode]=(k[x.errorCode]??0)+1;return k},{})};if(M.push(c),j>0.1)E.push({operation:c.operation,severity:j>0.3?"high":j>0.2?"medium":"low",metric:"error-rate",description:`Error rate ${(j*100).toFixed(1)}% exceeds threshold`,detectedAt:new Date,threshold:0.1,observedValue:j});if(c.p99LatencyMs>500)E.push({operation:c.operation,severity:c.p99LatencyMs>1000?"high":c.p99LatencyMs>750?"medium":"low",metric:"latency",description:`P99 latency ${c.p99LatencyMs.toFixed(0)}ms exceeds threshold`,detectedAt:new Date,threshold:500,observedValue:c.p99LatencyMs})}),q(M),X(E);let u=E.map((B)=>({operation:B.operation,category:B.metric==="latency"?"performance":"error-handling",summary:B.metric==="latency"?"Latency regression detected":"Error spike detected",justification:B.description,recommendedActions:B.metric==="latency"?["Add caching layer","Optimize database queries","Consider pagination"]:["Add retry logic","Improve error handling","Add circuit breaker"]}));w(u)},[]),H=d(async()=>{if(J.length===0)return;f(!0),await new Promise((G)=>setTimeout(G,800));let P=J.map((G)=>({id:`suggestion-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,intent:{id:`intent-${G.operation.name}`,type:G.metric==="latency"?"latency-regression":G.metric==="error-rate"?"error-spike":"throughput-drop",description:G.description,operation:G.operation,confidence:{score:G.severity==="high"?0.9:G.severity==="medium"?0.7:0.5,sampleSize:N.find((M)=>M.operation.name===G.operation.name)?.totalCalls??0}},target:G.operation,proposal:{summary:q1(G),rationale:P1(G),changeType:G.metric==="error-rate"?"policy-update":"revision",recommendedActions:J1(G)},confidence:G.severity==="high"?0.85:G.severity==="medium"?0.7:0.55,createdAt:new Date,createdBy:"ai-evolution-agent",status:"pending",priority:G.severity}));z((G)=>[...G,...P]),f(!1)},[J,N]),Z=d((P,G)=>{z((M)=>M.map((E)=>E.id===P?{...E,status:"approved"}:E))},[]),A=d((P,G)=>{z((M)=>M.map((E)=>E.id===P?{...E,status:"rejected"}:E))},[]),L=d(()=>{F.current=[],b(0),q([]),X([]),z([]),w([]),localStorage.removeItem(`${D0}-${$}`)},[$]);return $1(()=>({usageStats:N,anomalies:J,suggestions:K,hints:U,loading:V,trackOperation:W,analyzeUsage:Q,generateSuggestions:H,approveSuggestion:Z,rejectSuggestion:A,clear:L,operationCount:Y}),[N,J,K,U,V,W,Q,H,Z,A,L,Y])}function L0($,N){if(!$.length)return 0;if($.length===1)return $[0]??0;let q=Math.min($.length-1,Math.floor(N*$.length));return $[q]??0}function q1($){if($.metric==="latency")return`Add caching and pagination to ${$.operation.name} to reduce latency`;if($.metric==="error-rate")return`Add retry policy and circuit breaker to ${$.operation.name}`;return`Optimize ${$.operation.name} for improved throughput`}function P1($){if($.metric==="latency")return`The operation ${$.operation.name} is experiencing P99 latency of ${$.observedValue?.toFixed(0)}ms, which is above the recommended threshold of ${$.threshold}ms. This can impact user experience and downstream operations.`;if($.metric==="error-rate")return`The error rate for ${$.operation.name} is ${(($.observedValue??0)*100).toFixed(1)}%, indicating potential issues with input validation, external dependencies, or resource limits.`;return`Throughput for ${$.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`}function J1($){if($.metric==="latency")return["Add response caching for frequently accessed data","Implement pagination for large result sets","Optimize database queries with proper indexing","Consider adding a GraphQL DataLoader for batching"];if($.metric==="error-rate")return["Add input validation at the contract level","Implement retry policy with exponential backoff","Add circuit breaker for external dependencies","Enhance error logging for better debugging"];return["Review resource allocation and scaling policies","Check for upstream routing or load balancer issues","Validate feature flag configurations","Monitor dependency health metrics"]}import{Button as n,LoaderBlock as Z1}from"@contractspec/lib.design-system";import{Badge as g}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as l}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as t,useMemo as Q1}from"react";import{jsx as D,jsxs as _}from"react/jsx-runtime";function K2({templateId:$,onLog:N}){let{usageStats:q,anomalies:J,suggestions:X,hints:K,loading:z,trackOperation:U,analyzeUsage:w,generateSuggestions:V,approveSuggestion:f,rejectSuggestion:F,clear:Y,operationCount:b}=q0($),W=t(()=>{let P=[{name:`${$}.list`,duration:150,success:!0},{name:`${$}.list`,duration:180,success:!0},{name:`${$}.create`,duration:350,success:!0},{name:`${$}.create`,duration:420,success:!1,error:"VALIDATION_ERROR"},{name:`${$}.list`,duration:200,success:!0},{name:`${$}.get`,duration:80,success:!0},{name:`${$}.update`,duration:280,success:!0},{name:`${$}.list`,duration:950,success:!0},{name:`${$}.delete`,duration:150,success:!1,error:"NOT_FOUND"},{name:`${$}.create`,duration:380,success:!0}];for(let G of P)U(G.name,G.duration,G.success,G.error);N?.(`Simulated ${P.length} operations`),setTimeout(()=>{w(),N?.("Analysis complete")},100)},[$,U,w,N]),Q=t(async()=>{await V(),N?.("AI suggestions generated")},[V,N]),H=t((P)=>{f(P),N?.(`Suggestion ${P.slice(0,8)} approved`)},[f,N]),Z=t((P)=>{F(P),N?.(`Suggestion ${P.slice(0,8)} rejected`)},[F,N]),A=t(()=>{Y(),N?.("Evolution data cleared")},[Y,N]),L=Q1(()=>X.filter((P)=>P.status==="pending"),[X]);return _("div",{className:"space-y-6",children:[_("div",{className:"flex items-center justify-between",children:[_("div",{children:[D("h2",{className:"font-semibold text-xl",children:"AI Evolution Engine"}),D("p",{className:"text-muted-foreground text-sm",children:"Analyze usage patterns and get AI-powered suggestions"})]}),_("div",{className:"flex items-center gap-2",children:[_(g,{variant:"secondary",children:[b," ops tracked"]}),D(n,{variant:"ghost",size:"sm",onPress:A,children:"Clear"})]})]}),_(l,{className:"p-4",children:[_("div",{className:"flex flex-wrap items-center gap-3",children:[D(n,{variant:"default",size:"sm",onPress:W,children:"Simulate Operations"}),D(n,{variant:"outline",size:"sm",onPress:w,disabled:b<5,children:"Analyze Usage"}),D(n,{variant:"outline",size:"sm",onPress:Q,disabled:J.length===0||z,children:z?"Generating...":"Generate AI Suggestions"})]}),D("p",{className:"mt-2 text-muted-foreground text-xs",children:"Simulate sandbox operations, analyze patterns, and generate AI improvement suggestions."})]}),z&&D(Z1,{label:"Generating AI suggestions..."}),q.length>0&&_(l,{className:"p-4",children:[D("h3",{className:"mb-3 font-semibold",children:"Usage Statistics"}),D("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:q.map((P)=>D(X1,{stat:P},P.operation.name))})]}),J.length>0&&_(l,{className:"p-4",children:[_("div",{className:"mb-3 flex items-center justify-between",children:[D("h3",{className:"font-semibold",children:"Detected Anomalies"}),_(g,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[J.length," issues"]})]}),D("div",{className:"space-y-2",children:J.map((P,G)=>D(z1,{anomaly:P},`${P.operation.name}-${G}`))})]}),X.length>0&&_(l,{className:"p-4",children:[_("div",{className:"mb-3 flex items-center justify-between",children:[D("h3",{className:"font-semibold",children:"AI Suggestions"}),D("div",{className:"flex items-center gap-2",children:L.length>0&&_(g,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[L.length," pending"]})})]}),D("div",{className:"space-y-3",children:X.map((P)=>D(H1,{suggestion:P,onApprove:H,onReject:Z},P.id))})]}),K.length>0&&_(l,{className:"p-4",children:[D("h3",{className:"mb-3 font-semibold",children:"Optimization Hints"}),D("div",{className:"space-y-2",children:K.map((P,G)=>D(G1,{hint:P},`${P.operation.name}-${G}`))})]}),q.length===0&&J.length===0&&X.length===0&&D(l,{className:"p-8 text-center",children:D("p",{className:"text-muted-foreground",children:'Click "Simulate Operations" to generate sample data for analysis.'})})]})}function X1({stat:$}){return _("div",{className:"rounded-lg border border-violet-500/20 bg-violet-500/5 p-3",children:[_("div",{className:"mb-2 flex items-center justify-between",children:[D("span",{className:"font-medium font-mono text-sm",children:$.operation.name}),_(g,{variant:$.errorRate>0.1?"destructive":"default",className:$.errorRate>0.1?"":"border-green-500/30 bg-green-500/20 text-green-400",children:[((1-$.errorRate)*100).toFixed(0),"% success"]})]}),_("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[_("div",{children:[D("span",{className:"text-muted-foreground",children:"Total Calls:"})," ",D("span",{className:"font-medium",children:$.totalCalls})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"Avg Latency:"})," ",_("span",{className:"font-medium",children:[$.averageLatencyMs.toFixed(0),"ms"]})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"P95:"})," ",_("span",{className:"font-medium",children:[$.p95LatencyMs.toFixed(0),"ms"]})]}),_("div",{children:[D("span",{className:"text-muted-foreground",children:"P99:"})," ",_("span",{className:"font-medium",children:[$.p99LatencyMs.toFixed(0),"ms"]})]})]})]})}function z1({anomaly:$}){return _("div",{className:"flex items-center justify-between rounded-lg border border-amber-500/30 bg-amber-500/5 p-3",children:[_("div",{className:"flex items-center gap-3",children:[D("span",{className:`text-lg ${{low:"text-amber-400",medium:"text-orange-400",high:"text-red-400"}[$.severity]}`,title:`${$.severity} severity`,children:$.severity==="high"?"\uD83D\uDD34":$.severity==="medium"?"\uD83D\uDFE0":"\uD83D\uDFE1"}),_("div",{children:[D("p",{className:"font-medium text-sm",children:$.description}),_("p",{className:"text-muted-foreground text-xs",children:[$.operation.name," • ",$.metric]})]})]}),D(g,{variant:$.severity==="high"?"destructive":"secondary",className:$.severity==="medium"?"border-amber-500/30 bg-amber-500/20 text-amber-400":"",children:$.severity})]})}function H1({suggestion:$,onApprove:N,onReject:q}){let X=((K)=>{switch(K){case"pending":return{variant:"secondary",className:"bg-amber-500/20 text-amber-400 border-amber-500/30"};case"approved":return{variant:"default",className:"bg-green-500/20 text-green-400 border-green-500/30"};case"rejected":return{variant:"destructive",className:""};default:return{variant:"secondary",className:""}}})($.status);return _("div",{className:"rounded-lg border border-violet-500/30 bg-violet-500/5 p-4",children:[_("div",{className:"mb-2 flex items-start justify-between",children:[_("div",{className:"flex-1",children:[_("div",{className:"flex items-center gap-2",children:[D("span",{className:"text-lg",children:$.intent.type==="latency-regression"?"⚡":$.intent.type==="error-spike"?"\uD83D\uDD25":"\uD83D\uDCC9"}),D("h4",{className:"font-medium",children:$.proposal.summary})]}),D("p",{className:"mt-1 text-muted-foreground text-sm",children:$.proposal.rationale})]}),D(g,{variant:X.variant,className:X.className,children:$.status})]}),$.proposal.recommendedActions&&$.proposal.recommendedActions.length>0&&_("div",{className:"mt-3",children:[D("p",{className:"mb-1 font-semibold text-violet-400 text-xs uppercase",children:"Recommended Actions"}),D("ul",{className:"list-inside list-disc space-y-1 text-xs",children:$.proposal.recommendedActions.slice(0,3).map((K,z)=>D("li",{children:K},z))})]}),_("div",{className:"mt-3 flex items-center justify-between",children:[_("div",{className:"flex items-center gap-2 text-xs",children:[_("span",{className:"text-muted-foreground",children:["Confidence: ",($.confidence*100).toFixed(0),"%"]}),D("span",{className:"text-muted-foreground",children:"•"}),D(g,{variant:"secondary",children:$.priority})]}),$.status==="pending"&&_("div",{className:"flex items-center gap-2",children:[D(n,{variant:"outline",size:"sm",onPress:()=>q($.id),children:"Reject"}),D(n,{variant:"default",size:"sm",onPress:()=>N($.id),children:"Approve"})]})]})]})}function G1({hint:$}){return D("div",{className:"rounded-lg border border-blue-500/20 bg-blue-500/5 p-3",children:_("div",{className:"flex items-start gap-3",children:[D("span",{className:"text-lg",children:{schema:"\uD83D\uDCD0",policy:"\uD83D\uDD12",performance:"⚡","error-handling":"\uD83D\uDEE1️"}[$.category]}),_("div",{className:"flex-1",children:[D("p",{className:"font-medium",children:$.summary}),D("p",{className:"mt-1 text-muted-foreground text-xs",children:$.justification}),$.recommendedActions.length>0&&D("ul",{className:"mt-2 list-inside list-disc text-xs",children:$.recommendedActions.slice(0,2).map((q,J)=>D("li",{children:q},J))})]})]})})}import{Button as E0}from"@contractspec/lib.design-system";import{Badge as s}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as K1}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as k0,useMemo as C0}from"react";import{jsx as h,jsxs as T}from"react/jsx-runtime";function U2({templateId:$,expanded:N=!1,onToggle:q,onLog:J,onOpenEvolution:X}){let{anomalies:K,suggestions:z,loading:U,approveSuggestion:w,rejectSuggestion:V,operationCount:f}=q0($),F=C0(()=>z.filter((Q)=>Q.status==="pending"),[z]),Y=C0(()=>K.sort((Q,H)=>{let Z={high:0,medium:1,low:2};return Z[Q.severity]-Z[H.severity]}).slice(0,3),[K]),b=k0((Q)=>{w(Q),J?.(`Approved suggestion ${Q.slice(0,8)}`)},[w,J]),W=k0((Q)=>{V(Q),J?.(`Rejected suggestion ${Q.slice(0,8)}`)},[V,J]);if(!N)return T("button",{onClick:q,className:"flex items-center gap-2 rounded-lg border border-violet-500/30 bg-violet-500/10 px-3 py-2 text-sm transition hover:bg-violet-500/20",type:"button",children:[h("span",{children:"\uD83E\uDD16"}),h("span",{children:"Evolution"}),F.length>0&&h(s,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:F.length}),K.length>0&&F.length===0&&h(s,{variant:"destructive",children:K.length})]});return T(K1,{className:"w-80 overflow-hidden",children:[T("div",{className:"flex items-center justify-between border-violet-500/20 border-b bg-violet-500/5 px-3 py-2",children:[T("div",{className:"flex items-center gap-2",children:[h("span",{children:"\uD83E\uDD16"}),h("span",{className:"font-semibold text-sm",children:"Evolution"})]}),T("div",{className:"flex items-center gap-1",children:[X&&h(E0,{variant:"ghost",size:"sm",onPress:X,children:"Expand"}),h("button",{onClick:q,className:"p-1 text-muted-foreground hover:text-foreground",type:"button",title:"Collapse",children:"✕"})]})]}),T("div",{className:"max-h-96 overflow-y-auto p-3",children:[T("div",{className:"mb-3 flex items-center justify-between text-xs",children:[T("span",{className:"text-muted-foreground",children:[f," ops tracked"]}),T("div",{className:"flex items-center gap-2",children:[K.length>0&&T(s,{variant:"destructive",children:[K.length," anomalies"]}),F.length>0&&T(s,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:[F.length," pending"]})]})]}),U&&h("div",{className:"py-4 text-center text-muted-foreground text-sm",children:"Generating suggestions..."}),Y.length>0&&T("div",{className:"mb-4",children:[h("p",{className:"mb-2 font-semibold text-violet-400 text-xs uppercase",children:"Top Issues"}),h("div",{className:"space-y-2",children:Y.map((Q,H)=>T("div",{className:"rounded border border-amber-500/20 bg-amber-500/5 p-2 text-xs",children:[T("div",{className:"flex items-center gap-2",children:[h("span",{children:Q.severity==="high"?"\uD83D\uDD34":Q.severity==="medium"?"\uD83D\uDFE0":"\uD83D\uDFE1"}),h("span",{className:"truncate font-medium",children:Q.operation.name})]}),h("p",{className:"mt-1 truncate text-muted-foreground",children:Q.description})]},`${Q.operation.name}-${H}`))})]}),F.length>0&&T("div",{children:[h("p",{className:"mb-2 font-semibold text-violet-400 text-xs uppercase",children:"Pending Suggestions"}),T("div",{className:"space-y-2",children:[F.slice(0,3).map((Q)=>h(V1,{suggestion:Q,onApprove:b,onReject:W},Q.id)),F.length>3&&T("p",{className:"text-center text-muted-foreground text-xs",children:["+",F.length-3," more suggestions"]})]})]}),K.length===0&&F.length===0&&!U&&h("div",{className:"py-4 text-center text-muted-foreground text-xs",children:"No issues detected. Keep coding!"})]}),X&&h("div",{className:"border-violet-500/20 border-t p-2",children:h(E0,{variant:"ghost",size:"sm",className:"w-full",onPress:X,children:"Open Evolution Dashboard →"})})]})}function V1({suggestion:$,onApprove:N,onReject:q}){return T("div",{className:"rounded border border-violet-500/20 bg-violet-500/5 p-2",children:[h("div",{className:"flex items-start justify-between gap-2",children:T("div",{className:"min-w-0 flex-1",children:[h("p",{className:"truncate font-medium text-xs",children:$.proposal.summary}),T("div",{className:"mt-1 flex items-center gap-2 text-xs",children:[h(s,{variant:"secondary",children:$.priority}),T("span",{className:"text-muted-foreground",children:[($.confidence*100).toFixed(0),"%"]})]})]})}),T("div",{className:"mt-2 flex justify-end gap-1",children:[h("button",{onClick:()=>q($.id),className:"rounded px-2 py-0.5 text-red-400 text-xs hover:bg-red-400/10",type:"button",children:"Reject"}),h("button",{onClick:()=>N($.id),className:"rounded bg-violet-500/20 px-2 py-0.5 text-violet-400 text-xs hover:bg-violet-500/30",type:"button",children:"Approve"})]})]})}import{createContext as F1,useContext as Y1}from"react";var I0=Symbol.for("@contractspec/lib.example-shared-ui/template-runtime-context");function D1(){let $=globalThis;return $[I0]??=F1(null),$[I0]}var f1=D1();function r(){let $=Y1(f1);if(!$)throw Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");return $}import{RefreshCw as W1,Shield as _1}from"lucide-react";import{useState as U1}from"react";import{jsx as f0,jsxs as W0}from"react/jsx-runtime";function P0(){let{projectId:$,templateId:N,template:q,installer:J}=r(),[X,K]=U1(!1),z=async()=>{K(!0);try{await J.install(N,{projectId:$})}finally{K(!1)}};return W0("div",{className:"inline-flex items-center gap-2 rounded-full border border-border bg-muted/40 px-3 py-1 text-muted-foreground text-xs",children:[f0(_1,{className:"h-3.5 w-3.5 text-violet-400"}),W0("span",{children:["Local runtime ·"," ",f0("span",{className:"font-semibold text-foreground",children:q.name})]}),W0("button",{type:"button",className:"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 font-semibold text-[11px] text-muted-foreground hover:text-foreground",onClick:z,disabled:X,children:[f0(W1,{className:"h-3 w-3"}),X?"Resetting…":"Reset data"]})]})}function S0($){let N=$.split(".");return(N[N.length-1]??$).split("-").map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}import{useCallback as A1,useEffect as v0,useState as J0}from"react";function y0({engine:$,fetchData:N,presentationId:q,presentations:J,resolvePresentation:X,templateId:K}){let[z,U]=J0(""),[w,V]=J0(""),[f,F]=J0(!1),[Y,b]=J0(null);v0(()=>{if(q&&J.includes(q)){U(q);return}if(J.length===0){U("");return}if(!J.includes(z))U(J[0]??"")},[q,J,z,K]);let W=A1(async()=>{if(!z||!$)return;F(!0),b(null);try{if(!X)throw Error("resolvePresentation not available in runtime context");let Q=X(z);if(!Q)throw Error(`Presentation descriptor not found: ${z}`);let H=await N(z),Z=await $.render("markdown",Q,{data:H.data});V(Z.body)}catch(Q){b(Q instanceof Error?Q:Error("Failed to render markdown"))}finally{F(!1)}},[$,N,X,z]);return v0(()=>{W()},[W]),{error:Y,loading:f,markdownContent:w,renderMarkdown:W,selectedPresentation:z,setSelectedPresentation:U}}import{Button as c0,ErrorState as w1,LoaderBlock as b1,MarkdownRenderer as R1}from"@contractspec/lib.design-system";import{Badge as h1}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as r0}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as M1}from"react";import{jsx as C,jsxs as Z0}from"react/jsx-runtime";function i2({templateId:$,presentationId:N,className:q}){let{engine:J,template:X,templateId:K,resolvePresentation:z,fetchData:U}=r(),w=$??K,V=X?.presentations??[],{error:f,loading:F,markdownContent:Y,renderMarkdown:b,selectedPresentation:W,setSelectedPresentation:Q}=y0({engine:J,fetchData:U,presentationId:N,presentations:V,resolvePresentation:z,templateId:w});if(!V.length)return C(r0,{className:q,children:C("div",{className:"p-6 text-center",children:C("p",{className:"text-muted-foreground",children:"No presentations available for this template."})})});let H=M1(()=>{if(Y)navigator.clipboard.writeText(Y)},[Y]);return Z0("div",{className:q,children:[Z0("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[C("span",{className:"font-medium text-muted-foreground text-sm",children:"Presentation:"}),V.map((Z)=>C(c0,{variant:W===Z?"default":"outline",size:"sm",onPress:()=>Q(Z),children:S0(Z)},Z)),Z0("div",{className:"ml-auto flex items-center gap-2",children:[C(h1,{variant:"secondary",children:"LLM-friendly"}),C(c0,{variant:"outline",size:"sm",onPress:H,disabled:!Y||F,children:"Copy"})]})]}),Z0(r0,{className:"overflow-hidden",children:[F&&C(b1,{label:"Rendering markdown..."}),f&&C(w1,{title:"Render failed",description:f.message,onRetry:b,retryLabel:"Retry"}),!F&&!f&&Y&&C("div",{className:"p-6",children:C(R1,{content:Y})}),!F&&!f&&!Y&&C("div",{className:"p-6 text-center",children:C("p",{className:"text-muted-foreground",children:"Select a presentation to view its markdown output."})})]})]})}import*as i0 from"react";import{useContext as j0,useMemo as I}from"react";import{jsx as O1}from"react/jsx-runtime";var _0=i0.createContext(null);function p2({templateId:$,role:N="user",device:q="desktop",children:J}){let X=I(()=>T1($,N),[$,N]),K=I(()=>{return X.filter((W)=>{let Q=W.conditions;if(!Q)return!0;if(Q.role&&!Q.role.includes(N))return!1;if(Q.device&&Q.device!=="any"&&Q.device!==q)return!1;return!0})},[X,N,q]),z=I(()=>{let W=new Map;for(let Q of K)W.set(Q.target,Q);return W},[K]),U=I(()=>(W,Q)=>{let H=z.get(W);if(!H)return Q;let Z={...Q};for(let A of H.modifications)switch(A.op){case"hide":Z={...Z,hidden:!0};break;case"relabel":Z={...Z,label:A.label};break;case"reorder":Z={...Z,position:A.position};break;case"restyle":Z={...Z,className:A.className,variant:A.variant};break;case"set-default":Z={...Z,defaultValue:A.value};break}return Z},[z]),w=I(()=>(W)=>{return z.get(W)?.modifications.some((H)=>H.op==="hide")??!1},[z]),V=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="relabel");return Z&&Z.op==="relabel"?Z.label:Q},[z]),f=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="reorder");return Z&&Z.op==="reorder"?Z.position:Q},[z]),F=I(()=>(W)=>{let H=z.get(W)?.modifications.find((Z)=>Z.op==="restyle");if(H&&H.op==="restyle")return{className:H.className,variant:H.variant};return{}},[z]),Y=I(()=>(W,Q)=>{let Z=z.get(W)?.modifications.find((A)=>A.op==="set-default");return Z&&Z.op==="set-default"?Z.value:Q},[z]),b=I(()=>({overlays:K,applyOverlay:U,isHidden:w,getLabel:V,getPosition:f,getStyle:F,getDefault:Y,role:N,device:q}),[K,U,w,V,f,F,Y,N,q]);return O1(_0.Provider,{value:b,children:J})}function u2(){let $=j0(_0);if(!$)throw Error("useOverlayContext must be used within an OverlayContextProvider");return $}function d2(){return j0(_0)!==null}function T1($,N){return{"crm-pipeline":[{id:"crm-hide-internal-fields",target:"deal.internalNotes",modifications:[{op:"hide"}],conditions:{role:["viewer","user"]}},{id:"crm-relabel-value",target:"deal.value",modifications:[{op:"relabel",label:"Deal Amount"}]}],"saas-boilerplate":[{id:"saas-hide-billing",target:"settings.billing",modifications:[{op:"hide"}],conditions:{role:["viewer"]}},{id:"saas-restyle-plan",target:"settings.plan",modifications:[{op:"restyle",variant:"premium"}],conditions:{role:["admin"]}}],"agent-console":[{id:"agent-hide-cost",target:"run.cost",modifications:[{op:"hide"}],conditions:{role:["viewer"]}},{id:"agent-relabel-tokens",target:"run.tokens",modifications:[{op:"relabel",label:"Token Usage"}]}],"todos-app":[{id:"todos-hide-assignee",target:"task.assignee",modifications:[{op:"hide"}],conditions:{device:"mobile"}}],"messaging-app":[{id:"messaging-reorder-timestamp",target:"message.timestamp",modifications:[{op:"reorder",position:0}]}],"recipe-app-i18n":[{id:"recipe-relabel-servings",target:"recipe.servings",modifications:[{op:"relabel",label:"Portions"}]}]}[$]??[]}import{useCallback as Q0,useEffect as x0,useMemo as B1,useRef as L1,useState as g0}from"react";var U0="contractspec-behavior-data",E1=["playground","specs","builder","markdown","evolution","canvas_add","canvas_delete","spec_save","spec_validate","ai_suggestions"];function p0($){let[N,q]=g0([]),J=L1(new Date),[X,K]=g0(0);x0(()=>{try{let f=localStorage.getItem(U0);if(f){let F=JSON.parse(f);q(F.events.map((Y)=>({...Y,timestamp:new Date(Y.timestamp)}))),J.current=new Date(F.sessionStart)}}catch{}},[]),x0(()=>{if(N.length>0)try{localStorage.setItem(U0,JSON.stringify({events:N.map((f)=>({...f,timestamp:f.timestamp.toISOString()})),sessionStart:J.current.toISOString()}))}catch{}},[N]);let z=Q0((f,F)=>{let Y={type:f,timestamp:new Date,templateId:$,metadata:F};q((b)=>[...b,Y]),K((b)=>b+1)},[$]),U=Q0((f)=>{return N.filter((F)=>F.type===f)},[N]),w=Q0(()=>{let F=new Date().getTime()-J.current.getTime(),Y=new Map;for(let P of N){let G=Y.get(P.templateId)??0;Y.set(P.templateId,G+1)}let b=Array.from(Y.entries()).map(([P,G])=>({templateId:P,count:G})).sort((P,G)=>G.count-P.count).slice(0,3),W=new Map;for(let P of N)if(P.type==="mode_change"&&P.metadata?.mode){let G=P.metadata.mode,M=W.get(G)??0;W.set(G,M+1)}let Q=Array.from(W.entries()).map(([P,G])=>({mode:P,count:G})).sort((P,G)=>G.count-P.count),H=new Set;for(let P of N){if(P.type==="mode_change"&&P.metadata?.mode)H.add(P.metadata.mode);if(P.type==="feature_usage"&&P.metadata?.feature)H.add(P.metadata.feature);if(P.type==="canvas_interaction"){let G=P.metadata?.action;if(G==="add")H.add("canvas_add");if(G==="delete")H.add("canvas_delete")}if(P.type==="spec_edit"){let G=P.metadata?.action;if(G==="save")H.add("spec_save");if(G==="validate")H.add("spec_validate")}}let Z=E1.filter((P)=>!H.has(P)),A=N.filter((P)=>P.type==="error").length,L=k1(Array.from(H),Z,Q,N.length);return{totalEvents:N.length,sessionDuration:F,mostUsedTemplates:b,mostUsedModes:Q,featuresUsed:Array.from(H),unusedFeatures:Z,errorCount:A,recommendations:L}},[N]),V=Q0(()=>{q([]),K(0),J.current=new Date,localStorage.removeItem(U0)},[]);return B1(()=>({trackEvent:z,getSummary:w,getEventsByType:U,eventCount:X,sessionStart:J.current,clear:V}),[z,w,U,X,V])}function k1($,N,q,J){let X=[];if(N.includes("evolution"))X.push("Try the AI Evolution mode to get automated improvement suggestions");if(N.includes("markdown"))X.push("Use Markdown preview to see documentation for your specs");if(N.includes("builder"))X.push("Explore the Visual Builder to design your UI components");if(!$.includes("spec_validate")&&$.includes("specs"))X.push("Don't forget to validate your specs before saving");if($.includes("evolution")&&!$.includes("ai_suggestions"))X.push("Generate AI suggestions to get actionable improvement recommendations");if(J>50)X.push("Great engagement! Consider saving your work regularly");if(q.length===1)X.push("Try different modes to explore all sandbox capabilities");return X}import{Button as u0}from"@contractspec/lib.design-system";import{Badge as A0}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as C1}from"@contractspec/lib.ui-kit-web/ui/card";import{useCallback as d0,useMemo as I1,useState as S1}from"react";import{jsx as R,jsxs as O}from"react/jsx-runtime";function N4({templateId:$,collapsed:N=!1,onToggle:q}){let{getSummary:J,eventCount:X,clear:K,sessionStart:z}=p0($),[U,w]=S1(!1),V=I1(()=>J(),[J]),f=d0((Y)=>{let b=Math.floor(Y/1000),W=Math.floor(b/60),Q=Math.floor(W/60);if(Q>0)return`${Q}h ${W%60}m`;if(W>0)return`${W}m ${b%60}s`;return`${b}s`},[]),F=d0(()=>{K()},[K]);if(N)return O("button",{onClick:q,className:"flex items-center gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-3 py-2 text-sm transition hover:bg-blue-500/20",type:"button",children:[R("span",{children:"\uD83D\uDCCA"}),R("span",{children:"Insights"}),R(A0,{variant:"secondary",children:X})]});return O(C1,{className:"overflow-hidden",children:[O("div",{className:"flex items-center justify-between border-blue-500/20 border-b bg-blue-500/5 px-4 py-3",children:[O("div",{className:"flex items-center gap-2",children:[R("span",{children:"\uD83D\uDCCA"}),R("span",{className:"font-semibold",children:"Personalization Insights"})]}),O("div",{className:"flex items-center gap-2",children:[R(u0,{variant:"ghost",size:"sm",onPress:()=>w(!U),children:U?"Hide Details":"Show Details"}),q&&R("button",{onClick:q,className:"p-1 text-muted-foreground hover:text-foreground",type:"button",title:"Collapse",children:"✕"})]})]}),O("div",{className:"p-4",children:[O("div",{className:"mb-4 grid grid-cols-2 gap-3 md:grid-cols-4",children:[R(X0,{label:"Session Time",value:f(V.sessionDuration),icon:"⏱️"}),R(X0,{label:"Events Tracked",value:V.totalEvents.toString(),icon:"\uD83D\uDCC8"}),R(X0,{label:"Features Used",value:`${V.featuresUsed.length}/${V.featuresUsed.length+V.unusedFeatures.length}`,icon:"✨"}),R(X0,{label:"Errors",value:V.errorCount.toString(),icon:"⚠️",variant:V.errorCount>0?"warning":"success"})]}),V.recommendations.length>0&&O("div",{className:"mb-4",children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Recommendations"}),R("ul",{className:"space-y-1",children:V.recommendations.map((Y,b)=>O("li",{className:"flex items-start gap-2 text-sm",children:[R("span",{className:"text-blue-400",children:"\uD83D\uDCA1"}),R("span",{children:Y})]},b))})]}),V.unusedFeatures.length>0&&O("div",{className:"mb-4",children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Try These Features"}),R("div",{className:"flex flex-wrap gap-2",children:V.unusedFeatures.slice(0,5).map((Y)=>R(A0,{variant:"secondary",children:w0(Y)},Y))})]}),U&&R(v1,{summary:V,sessionStart:z}),R("div",{className:"mt-4 flex justify-end border-blue-500/10 border-t pt-4",children:R(u0,{variant:"ghost",size:"sm",onPress:F,children:"Clear Data"})})]})]})}function X0({label:$,value:N,icon:q,variant:J="default"}){return O("div",{className:`rounded-lg border p-3 text-center ${{default:"bg-blue-500/5 border-blue-500/20",warning:"bg-amber-500/5 border-amber-500/20",success:"bg-green-500/5 border-green-500/20"}[J]}`,children:[R("div",{className:"mb-1 text-lg",children:q}),R("div",{className:"font-bold text-lg",children:N}),R("div",{className:"text-muted-foreground text-xs",children:$})]})}function v1({summary:$,sessionStart:N}){return O("div",{className:"mt-4 space-y-4 border-blue-500/10 border-t pt-4",children:[$.mostUsedTemplates.length>0&&O("div",{children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Most Used Templates"}),R("div",{className:"space-y-1",children:$.mostUsedTemplates.map(({templateId:q,count:J})=>O("div",{className:"flex items-center justify-between text-sm",children:[R("span",{children:y1(q)}),O("span",{className:"text-muted-foreground",children:[J," events"]})]},q))})]}),$.mostUsedModes.length>0&&O("div",{children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Mode Usage"}),R("div",{className:"space-y-1",children:$.mostUsedModes.map(({mode:q,count:J})=>O("div",{className:"flex items-center justify-between text-sm",children:[R("span",{children:w0(q)}),O("span",{className:"text-muted-foreground",children:[J," switches"]})]},q))})]}),O("div",{children:[R("h4",{className:"mb-2 font-semibold text-blue-400 text-xs uppercase",children:"Features Used"}),R("div",{className:"flex flex-wrap gap-2",children:$.featuresUsed.map((q)=>O(A0,{variant:"default",className:"border-green-500/30 bg-green-500/20 text-green-400",children:["✓ ",w0(q)]},q))})]}),O("div",{className:"text-muted-foreground text-xs",children:["Session started: ",N.toLocaleString()]})]})}function w0($){return $.replace(/_/g," ").replace(/\b\w/g,(N)=>N.toUpperCase())}function y1($){return $.replace(/-/g," ").replace(/\b\w/g,(N)=>N.toUpperCase())}import{Sparkles as c1}from"lucide-react";import{useState as m0}from"react";import{jsx as b0,jsxs as l0}from"react/jsx-runtime";function z0({organizationId:$="demo-org",projectName:N,endpoint:q,token:J}){let{installer:X,templateId:K,template:z}=r(),[U,w]=m0("idle"),[V,f]=m0(null);return l0("div",{className:"flex flex-col items-end gap-1",children:[l0("button",{type:"button",className:"btn-primary inline-flex items-center gap-2 text-sm",onClick:async()=>{w("saving"),f(null);try{await X.saveToStudio({templateId:K,projectName:N??`${z.name} demo`,organizationId:$,endpoint:q,token:J}),w("saved"),setTimeout(()=>w("idle"),3000)}catch(Y){w("error"),f(Y instanceof Error?Y.message:"Unknown error")}},disabled:U==="saving",children:[b0(c1,{className:"h-4 w-4"}),U==="saving"?"Publishing…":"Save to Studio"]}),U==="error"&&V?b0("p",{className:"text-destructive text-xs",children:V}):null,U==="saved"?b0("p",{className:"text-emerald-400 text-xs",children:"Template sent to Studio."}):null]})}import{BundleProvider as r1,BundleRenderer as i1}from"@contractspec/lib.surface-runtime/react";import{jsx as S,jsxs as H0}from"react/jsx-runtime";function V4({plan:$,title:N,description:q,sidebar:J,actions:X,showSaveAction:K=!0,saveProps:z,children:U}){let V={header:H0("header",{className:"rounded-2xl border border-border bg-card p-6 shadow-sm",children:[H0("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[H0("div",{children:[S("p",{className:"font-semibold text-muted-foreground text-sm uppercase tracking-wide",children:"ContractSpec Templates"}),S("h1",{className:"font-bold text-3xl",children:N}),q?S("p",{className:"mt-2 max-w-2xl text-muted-foreground text-sm",children:q}):null]}),H0("div",{className:"flex flex-col items-end gap-2",children:[S(P0,{}),K?S(z0,{...z}):null]})]}),X?S("div",{className:"mt-4",children:X}):null]}),primary:S("main",{className:"space-y-4 p-2",children:U})};if(J!=null)V.sidebar=S("aside",{className:"rounded-2xl border border-border bg-card p-4",children:J});return S(r1,{plan:$,children:S(i1,{slotContent:V})})}function e($){let N=$?.id??"unknown";if(!$)return n0(N);switch(N){case"crm-pipeline":return j1($.schema.contracts);case"saas-boilerplate":return x1($.schema.contracts);case"agent-console":return g1($.schema.contracts);case"todos-app":return p1($.schema.contracts);case"messaging-app":return u1($.schema.contracts);case"recipe-app-i18n":return d1($.schema.contracts);default:return n0(N)}}function j1($){return`// CRM Pipeline Specs
2
+ // Contracts: ${$.join(", ")}
2144
3
 
2145
4
  contractSpec("crm.deal.updateStage.v1", {
2146
5
  goal: "Move a deal to a different pipeline stage",
@@ -2209,11 +68,8 @@ contractSpec("crm.contact.list.v1", {
2209
68
  hasMore: "boolean"
2210
69
  }
2211
70
  }
2212
- });`;
2213
- }
2214
- function generateSaasBoilerplateSpec(contracts) {
2215
- return `// SaaS Boilerplate Specs
2216
- // Contracts: ${contracts.join(", ")}
71
+ });`}function x1($){return`// SaaS Boilerplate Specs
72
+ // Contracts: ${$.join(", ")}
2217
73
 
2218
74
  contractSpec("saas.project.create.v1", {
2219
75
  goal: "Create a new project in an organization",
@@ -2276,11 +132,8 @@ contractSpec("saas.settings.update.v1", {
2276
132
  }
2277
133
  },
2278
134
  events: ["settings.updated"]
2279
- });`;
2280
- }
2281
- function generateAgentConsoleSpec(contracts) {
2282
- return `// Agent Console Specs
2283
- // Contracts: ${contracts.join(", ")}
135
+ });`}function g1($){return`// Agent Console Specs
136
+ // Contracts: ${$.join(", ")}
2284
137
 
2285
138
  contractSpec("agent.run.execute.v1", {
2286
139
  goal: "Execute an agent run with specified tools",
@@ -2346,11 +199,8 @@ contractSpec("agent.agent.create.v1", {
2346
199
  }
2347
200
  },
2348
201
  events: ["agent.created"]
2349
- });`;
2350
- }
2351
- function generateTodosSpec(contracts) {
2352
- return `// To-dos App Specs
2353
- // Contracts: ${contracts.join(", ")}
202
+ });`}function p1($){return`// To-dos App Specs
203
+ // Contracts: ${$.join(", ")}
2354
204
 
2355
205
  contractSpec("tasks.board.v1", {
2356
206
  goal: "Assign and approve craft work",
@@ -2409,11 +259,8 @@ contractSpec("tasks.complete.v1", {
2409
259
  }
2410
260
  },
2411
261
  events: ["task.completed"]
2412
- });`;
2413
- }
2414
- function generateMessagingSpec(contracts) {
2415
- return `// Messaging App Specs
2416
- // Contracts: ${contracts.join(", ")}
262
+ });`}function u1($){return`// Messaging App Specs
263
+ // Contracts: ${$.join(", ")}
2417
264
 
2418
265
  contractSpec("messaging.send.v1", {
2419
266
  goal: "Deliver intent-rich updates",
@@ -2466,11 +313,8 @@ contractSpec("messaging.read.v1", {
2466
313
  }
2467
314
  },
2468
315
  events: ["message.read"]
2469
- });`;
2470
- }
2471
- function generateRecipeSpec(contracts) {
2472
- return `// Recipe App (i18n) Specs
2473
- // Contracts: ${contracts.join(", ")}
316
+ });`}function d1($){return`// Recipe App (i18n) Specs
317
+ // Contracts: ${$.join(", ")}
2474
318
 
2475
319
  contractSpec("recipes.lookup.v1", {
2476
320
  goal: "Serve bilingual rituals",
@@ -2517,13 +361,10 @@ contractSpec("recipes.favorite.toggle.v1", {
2517
361
  }
2518
362
  },
2519
363
  events: ["recipe.favorited", "recipe.unfavorited"]
2520
- });`;
2521
- }
2522
- function generateDefaultSpec(templateId) {
2523
- return `// ${templateId} Specs
364
+ });`}function n0($){return`// ${$} Specs
2524
365
 
2525
- contractSpec("${templateId}.main.v1", {
2526
- goal: "Main operation for ${templateId}",
366
+ contractSpec("${$}.main.v1", {
367
+ goal: "Main operation for ${$}",
2527
368
  transport: { gql: { query: "main" } },
2528
369
  io: {
2529
370
  input: {
@@ -2533,961 +374,38 @@ contractSpec("${templateId}.main.v1", {
2533
374
  result: "unknown"
2534
375
  }
2535
376
  }
2536
- });`;
2537
- }
2538
-
2539
- // src/hooks/useSpecContent.ts
2540
- import { useCallback as useCallback8, useEffect as useEffect4, useState as useState7 } from "react";
2541
- "use client";
2542
- var SPEC_STORAGE_KEY = "contractspec-spec-content";
2543
- function useSpecContent(templateId) {
2544
- const { template } = useTemplateRuntime();
2545
- const [content, setContentState] = useState7("");
2546
- const [savedContent, setSavedContent] = useState7("");
2547
- const [loading, setLoading] = useState7(true);
2548
- const [validation, setValidation] = useState7(null);
2549
- const [lastSaved, setLastSaved] = useState7(null);
2550
- useEffect4(() => {
2551
- setLoading(true);
2552
- try {
2553
- const stored = localStorage.getItem(`${SPEC_STORAGE_KEY}-${templateId}`);
2554
- if (stored) {
2555
- const parsed = JSON.parse(stored);
2556
- if (parsed.content) {
2557
- setContentState(parsed.content);
2558
- setSavedContent(parsed.content);
2559
- setLastSaved(parsed.savedAt);
2560
- } else {
2561
- const generated = generateSpecFromTemplate(template);
2562
- setContentState(generated);
2563
- setSavedContent(generated);
2564
- }
2565
- } else {
2566
- const generated = generateSpecFromTemplate(template);
2567
- setContentState(generated);
2568
- setSavedContent(generated);
2569
- }
2570
- } catch {
2571
- const generated = generateSpecFromTemplate(template);
2572
- setContentState(generated);
2573
- setSavedContent(generated);
2574
- }
2575
- setLoading(false);
2576
- }, [templateId]);
2577
- const setContent = useCallback8((newContent) => {
2578
- setContentState(newContent);
2579
- setValidation(null);
2580
- }, []);
2581
- const save = useCallback8(() => {
2582
- try {
2583
- const savedAt = new Date().toISOString();
2584
- localStorage.setItem(`${SPEC_STORAGE_KEY}-${templateId}`, JSON.stringify({
2585
- content,
2586
- savedAt
2587
- }));
2588
- setSavedContent(content);
2589
- setLastSaved(savedAt);
2590
- } catch {}
2591
- }, [content, templateId]);
2592
- const validate = useCallback8(() => {
2593
- const errors = [];
2594
- const lines = content.split(`
2595
- `);
2596
- if (!content.includes("contractSpec(")) {
2597
- errors.push({
2598
- line: 1,
2599
- message: "Spec must contain a contractSpec() definition",
2600
- severity: "error"
2601
- });
2602
- }
2603
- if (!content.includes("goal:")) {
2604
- errors.push({
2605
- line: 1,
2606
- message: "Spec should have a goal field",
2607
- severity: "warning"
2608
- });
2609
- }
2610
- if (!content.includes("io:")) {
2611
- errors.push({
2612
- line: 1,
2613
- message: "Spec should define io (input/output)",
2614
- severity: "warning"
2615
- });
2616
- }
2617
- const openBraces = (content.match(/{/g) ?? []).length;
2618
- const closeBraces = (content.match(/}/g) ?? []).length;
2619
- if (openBraces !== closeBraces) {
2620
- errors.push({
2621
- line: lines.length,
2622
- message: `Unbalanced braces: ${openBraces} opening, ${closeBraces} closing`,
2623
- severity: "error"
2624
- });
2625
- }
2626
- const openParens = (content.match(/\(/g) ?? []).length;
2627
- const closeParens = (content.match(/\)/g) ?? []).length;
2628
- if (openParens !== closeParens) {
2629
- errors.push({
2630
- line: lines.length,
2631
- message: `Unbalanced parentheses: ${openParens} opening, ${closeParens} closing`,
2632
- severity: "error"
2633
- });
2634
- }
2635
- lines.forEach((line, index) => {
2636
- const singleQuotes = (line.match(/'/g) ?? []).length;
2637
- const doubleQuotes = (line.match(/"/g) ?? []).length;
2638
- if (singleQuotes % 2 !== 0) {
2639
- errors.push({
2640
- line: index + 1,
2641
- message: "Unclosed single quote",
2642
- severity: "error"
2643
- });
2644
- }
2645
- if (doubleQuotes % 2 !== 0) {
2646
- errors.push({
2647
- line: index + 1,
2648
- message: "Unclosed double quote",
2649
- severity: "error"
2650
- });
2651
- }
2652
- });
2653
- const result = {
2654
- valid: errors.filter((e) => e.severity === "error").length === 0,
2655
- errors
2656
- };
2657
- setValidation(result);
2658
- return result;
2659
- }, [content]);
2660
- const reset = useCallback8(() => {
2661
- const generated = generateSpecFromTemplate(template);
2662
- setContentState(generated);
2663
- setSavedContent(generated);
2664
- setValidation(null);
2665
- setLastSaved(null);
2666
- try {
2667
- localStorage.removeItem(`${SPEC_STORAGE_KEY}-${templateId}`);
2668
- } catch {}
2669
- }, [templateId]);
2670
- return {
2671
- content,
2672
- loading,
2673
- isDirty: content !== savedContent,
2674
- validation,
2675
- setContent,
2676
- save,
2677
- validate,
2678
- reset,
2679
- lastSaved
2680
- };
2681
- }
2682
-
2683
- // src/SpecEditorPanel.tsx
2684
- import { Button as Button5, LoaderBlock as LoaderBlock3 } from "@contractspec/lib.design-system";
2685
- import { Badge as Badge5 } from "@contractspec/lib.ui-kit-web/ui/badge";
2686
- import { useCallback as useCallback9, useEffect as useEffect5 } from "react";
2687
- import { jsxDEV as jsxDEV9 } from "react/jsx-dev-runtime";
2688
- "use client";
2689
- function SpecEditorPanel({
2690
- templateId,
2691
- SpecEditor,
2692
- onLog
2693
- }) {
2694
- const {
2695
- content,
2696
- loading,
2697
- isDirty,
2698
- validation,
2699
- setContent,
2700
- save,
2701
- validate,
2702
- reset,
2703
- lastSaved
2704
- } = useSpecContent(templateId);
2705
- useEffect5(() => {
2706
- if (!loading && content) {
2707
- onLog?.(`Spec loaded for ${templateId}`);
2708
- }
2709
- }, [loading, content, templateId, onLog]);
2710
- const handleSave = useCallback9(() => {
2711
- save();
2712
- onLog?.("Spec saved locally");
2713
- }, [save, onLog]);
2714
- const handleValidate = useCallback9(() => {
2715
- const result = validate();
2716
- if (result.valid) {
2717
- onLog?.("Spec validation passed");
2718
- } else {
2719
- const errorCount = result.errors.filter((e) => e.severity === "error").length;
2720
- const warnCount = result.errors.filter((e) => e.severity === "warning").length;
2721
- onLog?.(`Spec validation: ${errorCount} errors, ${warnCount} warnings`);
2722
- }
2723
- }, [validate, onLog]);
2724
- const handleReset = useCallback9(() => {
2725
- reset();
2726
- onLog?.("Spec reset to template defaults");
2727
- }, [reset, onLog]);
2728
- if (loading) {
2729
- return /* @__PURE__ */ jsxDEV9(LoaderBlock3, {
2730
- label: "Loading spec..."
2731
- }, undefined, false, undefined, this);
2732
- }
2733
- return /* @__PURE__ */ jsxDEV9("div", {
2734
- className: "space-y-4",
2735
- children: [
2736
- /* @__PURE__ */ jsxDEV9("div", {
2737
- className: "flex items-center justify-between",
2738
- children: [
2739
- /* @__PURE__ */ jsxDEV9("div", {
2740
- className: "flex items-center gap-2",
2741
- children: [
2742
- /* @__PURE__ */ jsxDEV9(Button5, {
2743
- variant: "default",
2744
- size: "sm",
2745
- onClick: handleSave,
2746
- children: "Save"
2747
- }, undefined, false, undefined, this),
2748
- /* @__PURE__ */ jsxDEV9(Button5, {
2749
- variant: "outline",
2750
- size: "sm",
2751
- onClick: handleValidate,
2752
- children: "Validate"
2753
- }, undefined, false, undefined, this),
2754
- isDirty && /* @__PURE__ */ jsxDEV9(Badge5, {
2755
- variant: "secondary",
2756
- className: "border-amber-500/30 bg-amber-500/20 text-amber-400",
2757
- children: "Unsaved changes"
2758
- }, undefined, false, undefined, this),
2759
- validation && /* @__PURE__ */ jsxDEV9(Badge5, {
2760
- variant: validation.valid ? "default" : "destructive",
2761
- className: validation.valid ? "border-green-500/30 bg-green-500/20 text-green-400" : "",
2762
- children: validation.valid ? "Valid" : `${validation.errors.filter((e) => e.severity === "error").length} errors`
2763
- }, undefined, false, undefined, this)
2764
- ]
2765
- }, undefined, true, undefined, this),
2766
- /* @__PURE__ */ jsxDEV9("div", {
2767
- className: "flex items-center gap-2",
2768
- children: [
2769
- lastSaved && /* @__PURE__ */ jsxDEV9("span", {
2770
- className: "text-muted-foreground text-xs",
2771
- children: [
2772
- "Last saved: ",
2773
- new Date(lastSaved).toLocaleTimeString()
2774
- ]
2775
- }, undefined, true, undefined, this),
2776
- /* @__PURE__ */ jsxDEV9(Button5, {
2777
- variant: "ghost",
2778
- size: "sm",
2779
- onPress: handleReset,
2780
- children: "Reset"
2781
- }, undefined, false, undefined, this)
2782
- ]
2783
- }, undefined, true, undefined, this)
2784
- ]
2785
- }, undefined, true, undefined, this),
2786
- validation && validation.errors.length > 0 && /* @__PURE__ */ jsxDEV9("div", {
2787
- className: "rounded-lg border border-amber-500/50 bg-amber-500/10 p-3",
2788
- children: [
2789
- /* @__PURE__ */ jsxDEV9("p", {
2790
- className: "mb-2 font-semibold text-amber-400 text-xs uppercase",
2791
- children: "Validation Issues"
2792
- }, undefined, false, undefined, this),
2793
- /* @__PURE__ */ jsxDEV9("ul", {
2794
- className: "space-y-1",
2795
- children: validation.errors.map((error, index) => /* @__PURE__ */ jsxDEV9("li", {
2796
- className: `text-xs ${error.severity === "error" ? "text-red-400" : "text-amber-400"}`,
2797
- children: [
2798
- "Line ",
2799
- error.line,
2800
- ": ",
2801
- error.message
2802
- ]
2803
- }, `${error.line}-${error.message}-${index}`, true, undefined, this))
2804
- }, undefined, false, undefined, this)
2805
- ]
2806
- }, undefined, true, undefined, this),
2807
- /* @__PURE__ */ jsxDEV9("div", {
2808
- className: "rounded-2xl border border-border bg-card p-4",
2809
- children: /* @__PURE__ */ jsxDEV9(SpecEditor, {
2810
- projectId: "sandbox",
2811
- type: "CAPABILITY",
2812
- content,
2813
- onChange: setContent,
2814
- metadata: { template: templateId },
2815
- onSave: handleSave,
2816
- onValidate: handleValidate
2817
- }, undefined, false, undefined, this)
2818
- }, undefined, false, undefined, this)
2819
- ]
2820
- }, undefined, true, undefined, this);
2821
- }
2822
-
2823
- // src/TemplateShell.tsx
2824
- import { jsxDEV as jsxDEV10 } from "react/jsx-dev-runtime";
2825
- var TemplateShell = ({
2826
- title,
2827
- description,
2828
- sidebar,
2829
- actions,
2830
- showSaveAction = true,
2831
- saveProps,
2832
- children
2833
- }) => /* @__PURE__ */ jsxDEV10("div", {
2834
- className: "space-y-6",
2835
- children: [
2836
- /* @__PURE__ */ jsxDEV10("header", {
2837
- className: "rounded-2xl border border-border bg-card p-6 shadow-sm",
2838
- children: [
2839
- /* @__PURE__ */ jsxDEV10("div", {
2840
- className: "flex flex-wrap items-center justify-between gap-4",
2841
- children: [
2842
- /* @__PURE__ */ jsxDEV10("div", {
2843
- children: [
2844
- /* @__PURE__ */ jsxDEV10("p", {
2845
- className: "font-semibold text-muted-foreground text-sm uppercase tracking-wide",
2846
- children: "ContractSpec Templates"
2847
- }, undefined, false, undefined, this),
2848
- /* @__PURE__ */ jsxDEV10("h1", {
2849
- className: "font-bold text-3xl",
2850
- children: title
2851
- }, undefined, false, undefined, this),
2852
- description ? /* @__PURE__ */ jsxDEV10("p", {
2853
- className: "mt-2 max-w-2xl text-muted-foreground text-sm",
2854
- children: description
2855
- }, undefined, false, undefined, this) : null
2856
- ]
2857
- }, undefined, true, undefined, this),
2858
- /* @__PURE__ */ jsxDEV10("div", {
2859
- className: "flex flex-col items-end gap-2",
2860
- children: [
2861
- /* @__PURE__ */ jsxDEV10(LocalDataIndicator, {}, undefined, false, undefined, this),
2862
- showSaveAction ? /* @__PURE__ */ jsxDEV10(SaveToStudioButton, {
2863
- ...saveProps
2864
- }, undefined, false, undefined, this) : null
2865
- ]
2866
- }, undefined, true, undefined, this)
2867
- ]
2868
- }, undefined, true, undefined, this),
2869
- actions ? /* @__PURE__ */ jsxDEV10("div", {
2870
- className: "mt-4",
2871
- children: actions
2872
- }, undefined, false, undefined, this) : null
2873
- ]
2874
- }, undefined, true, undefined, this),
2875
- /* @__PURE__ */ jsxDEV10("div", {
2876
- className: sidebar ? "grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]" : "w-full",
2877
- children: [
2878
- /* @__PURE__ */ jsxDEV10("main", {
2879
- className: "space-y-4 p-2",
2880
- children
2881
- }, undefined, false, undefined, this),
2882
- sidebar ? /* @__PURE__ */ jsxDEV10("aside", {
2883
- className: "rounded-2xl border border-border bg-card p-4",
2884
- children: sidebar
2885
- }, undefined, false, undefined, this) : null
2886
- ]
2887
- }, undefined, true, undefined, this)
2888
- ]
2889
- }, undefined, true, undefined, this);
2890
-
2891
- // src/hooks/useRegistryTemplates.ts
2892
- import { useQuery } from "@tanstack/react-query";
2893
- function useRegistryTemplates() {
2894
- return useQuery({
2895
- queryKey: ["registryTemplates"],
2896
- queryFn: async () => {
2897
- const registryUrl = process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL ?? "";
2898
- if (!registryUrl)
2899
- return [];
2900
- const res = await fetch(`${registryUrl.replace(/\/$/, "")}/r/contractspec.json`, {
2901
- method: "GET",
2902
- headers: { Accept: "application/json" }
2903
- });
2904
- if (!res.ok)
2905
- return [];
2906
- const json = await res.json();
2907
- const items = json.items ?? [];
2908
- return items.filter((i) => i.type === "contractspec:template").map((i) => ({
2909
- id: i.name,
2910
- name: i.title ?? i.name,
2911
- description: i.description,
2912
- tags: i.meta?.tags ?? [],
2913
- source: "registry",
2914
- registryUrl
2915
- }));
2916
- }
2917
- });
2918
- }
2919
-
2920
- // src/hooks/useWorkflowComposer.ts
2921
- import { useCallback as useCallback10, useEffect as useEffect6, useMemo as useMemo7, useState as useState8 } from "react";
2922
- "use client";
2923
- function useWorkflowComposer(templateId) {
2924
- const [selectedWorkflow, setSelectedWorkflow] = useState8(null);
2925
- const [extensions, setExtensions] = useState8([]);
2926
- const [loading, _setLoading] = useState8(false);
2927
- const [error, _setError] = useState8(null);
2928
- const baseWorkflows = useMemo7(() => getTemplateWorkflows(templateId), [templateId]);
2929
- useEffect6(() => {
2930
- const firstWorkflow = baseWorkflows[0];
2931
- if (baseWorkflows.length > 0 && !selectedWorkflow && firstWorkflow) {
2932
- setSelectedWorkflow(firstWorkflow.meta.key);
2933
- }
2934
- }, [baseWorkflows, selectedWorkflow]);
2935
- const currentBase = useMemo7(() => {
2936
- return baseWorkflows.find((w) => w.meta.key === selectedWorkflow) ?? null;
2937
- }, [baseWorkflows, selectedWorkflow]);
2938
- const compose = useCallback10((scope) => {
2939
- if (!currentBase)
2940
- return null;
2941
- const applicableExtensions = extensions.filter((ext) => ext.workflow === currentBase.meta.key).filter((ext) => matchesScope(ext, scope)).sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
2942
- if (applicableExtensions.length === 0) {
2943
- return currentBase;
2944
- }
2945
- let composedWorkflow = { ...currentBase, steps: [...currentBase.steps] };
2946
- for (const extension of applicableExtensions) {
2947
- composedWorkflow = applyExtension(composedWorkflow, extension);
2948
- }
2949
- return composedWorkflow;
2950
- }, [currentBase, extensions]);
2951
- const workflow = useMemo7(() => compose(), [compose]);
2952
- const selectWorkflow = useCallback10((workflowName) => {
2953
- setSelectedWorkflow(workflowName);
2954
- }, []);
2955
- const addExtension = useCallback10((extension) => {
2956
- setExtensions((prev) => [...prev, extension]);
2957
- }, []);
2958
- const removeExtension = useCallback10((workflowName, index) => {
2959
- setExtensions((prev) => {
2960
- const forWorkflow = prev.filter((e) => e.workflow === workflowName);
2961
- const others = prev.filter((e) => e.workflow !== workflowName);
2962
- forWorkflow.splice(index, 1);
2963
- return [...others, ...forWorkflow];
2964
- });
2965
- }, []);
2966
- const generateSpecCode = useCallback10(() => {
2967
- const composed = workflow;
2968
- if (!composed) {
2969
- return "// No workflow selected";
2970
- }
2971
- const stepsCode = composed.steps.map((step) => ` {
2972
- id: '${step.id}',
2973
- name: '${step.name}',
2974
- type: '${step.type}',${step.description ? `
2975
- description: '${step.description}',` : ""}${step.next ? `
2976
- next: ${JSON.stringify(step.next)},` : ""}${step.condition ? `
2977
- condition: '${step.condition}',` : ""}${step.timeout ? `
2978
- timeout: ${step.timeout},` : ""}${step.retries ? `
2979
- retries: ${step.retries},` : ""}${step.onError ? `
2980
- onError: '${step.onError}',` : ""}
377
+ });`}import{useCallback as G0,useEffect as m1,useState as $0}from"react";var R0="contractspec-spec-content";function o0($){let{template:N}=r(),[q,J]=$0(""),[X,K]=$0(""),[z,U]=$0(!0),[w,V]=$0(null),[f,F]=$0(null);m1(()=>{U(!0);try{let H=localStorage.getItem(`${R0}-${$}`);if(H){let Z=JSON.parse(H);if(Z.content)J(Z.content),K(Z.content),F(Z.savedAt);else{let A=e(N);J(A),K(A)}}else{let Z=e(N);J(Z),K(Z)}}catch{let H=e(N);J(H),K(H)}U(!1)},[$]);let Y=G0((H)=>{J(H),V(null)},[]),b=G0(()=>{try{let H=new Date().toISOString();localStorage.setItem(`${R0}-${$}`,JSON.stringify({content:q,savedAt:H})),K(q),F(H)}catch{}},[q,$]),W=G0(()=>{let H=[],Z=q.split(`
378
+ `);if(!q.includes("contractSpec("))H.push({line:1,message:"Spec must contain a contractSpec() definition",severity:"error"});if(!q.includes("goal:"))H.push({line:1,message:"Spec should have a goal field",severity:"warning"});if(!q.includes("io:"))H.push({line:1,message:"Spec should define io (input/output)",severity:"warning"});let A=(q.match(/{/g)??[]).length,L=(q.match(/}/g)??[]).length;if(A!==L)H.push({line:Z.length,message:`Unbalanced braces: ${A} opening, ${L} closing`,severity:"error"});let P=(q.match(/\(/g)??[]).length,G=(q.match(/\)/g)??[]).length;if(P!==G)H.push({line:Z.length,message:`Unbalanced parentheses: ${P} opening, ${G} closing`,severity:"error"});Z.forEach((E,u)=>{let B=(E.match(/'/g)??[]).length,y=(E.match(/"/g)??[]).length;if(B%2!==0)H.push({line:u+1,message:"Unclosed single quote",severity:"error"});if(y%2!==0)H.push({line:u+1,message:"Unclosed double quote",severity:"error"})});let M={valid:H.filter((E)=>E.severity==="error").length===0,errors:H};return V(M),M},[q]),Q=G0(()=>{let H=e(N);J(H),K(H),V(null),F(null);try{localStorage.removeItem(`${R0}-${$}`)}catch{}},[$]);return{content:q,loading:z,isDirty:q!==X,validation:w,setContent:Y,save:b,validate:W,reset:Q,lastSaved:f}}import{Button as h0,LoaderBlock as l1}from"@contractspec/lib.design-system";import{Badge as a0}from"@contractspec/lib.ui-kit-web/ui/badge";import{useCallback as M0,useEffect as n1}from"react";import{jsx as v,jsxs as p}from"react/jsx-runtime";function h4({templateId:$,SpecEditor:N,onLog:q}){let{content:J,loading:X,isDirty:K,validation:z,setContent:U,save:w,validate:V,reset:f,lastSaved:F}=o0($);n1(()=>{if(!X&&J)q?.(`Spec loaded for ${$}`)},[X,J,$,q]);let Y=M0(()=>{w(),q?.("Spec saved locally")},[w,q]),b=M0(()=>{let Q=V();if(Q.valid)q?.("Spec validation passed");else{let H=Q.errors.filter((A)=>A.severity==="error").length,Z=Q.errors.filter((A)=>A.severity==="warning").length;q?.(`Spec validation: ${H} errors, ${Z} warnings`)}},[V,q]),W=M0(()=>{f(),q?.("Spec reset to template defaults")},[f,q]);if(X)return v(l1,{label:"Loading spec..."});return p("div",{className:"space-y-4",children:[p("div",{className:"flex items-center justify-between",children:[p("div",{className:"flex items-center gap-2",children:[v(h0,{variant:"default",size:"sm",onClick:Y,children:"Save"}),v(h0,{variant:"outline",size:"sm",onClick:b,children:"Validate"}),K&&v(a0,{variant:"secondary",className:"border-amber-500/30 bg-amber-500/20 text-amber-400",children:"Unsaved changes"}),z&&v(a0,{variant:z.valid?"default":"destructive",className:z.valid?"border-green-500/30 bg-green-500/20 text-green-400":"",children:z.valid?"Valid":`${z.errors.filter((Q)=>Q.severity==="error").length} errors`})]}),p("div",{className:"flex items-center gap-2",children:[F&&p("span",{className:"text-muted-foreground text-xs",children:["Last saved: ",new Date(F).toLocaleTimeString()]}),v(h0,{variant:"ghost",size:"sm",onPress:W,children:"Reset"})]})]}),z&&z.errors.length>0&&p("div",{className:"rounded-lg border border-amber-500/50 bg-amber-500/10 p-3",children:[v("p",{className:"mb-2 font-semibold text-amber-400 text-xs uppercase",children:"Validation Issues"}),v("ul",{className:"space-y-1",children:z.errors.map((Q,H)=>p("li",{className:`text-xs ${Q.severity==="error"?"text-red-400":"text-amber-400"}`,children:["Line ",Q.line,": ",Q.message]},`${Q.line}-${Q.message}-${H}`))})]}),v("div",{className:"rounded-2xl border border-border bg-card p-4",children:v(N,{projectId:"sandbox",type:"CAPABILITY",content:J,onChange:U,metadata:{template:$},onSave:Y,onValidate:b})})]})}import{jsx as i,jsxs as o}from"react/jsx-runtime";var L4=({title:$,description:N,sidebar:q,actions:J,showSaveAction:X=!0,saveProps:K,children:z})=>o("div",{className:"space-y-6",children:[o("header",{className:"rounded-2xl border border-border bg-card p-6 shadow-sm",children:[o("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[o("div",{children:[i("p",{className:"font-semibold text-muted-foreground text-sm uppercase tracking-wide",children:"ContractSpec Templates"}),i("h1",{className:"font-bold text-3xl",children:$}),N?i("p",{className:"mt-2 max-w-2xl text-muted-foreground text-sm",children:N}):null]}),o("div",{className:"flex flex-col items-end gap-2",children:[i(P0,{}),X?i(z0,{...K}):null]})]}),J?i("div",{className:"mt-4",children:J}):null]}),o("div",{className:q?"grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]":"w-full",children:[i("main",{className:"space-y-4 p-2",children:z}),q?i("aside",{className:"rounded-2xl border border-border bg-card p-4",children:q}):null]})]});import{useQuery as o1}from"@tanstack/react-query";function I4(){return o1({queryKey:["registryTemplates"],queryFn:async()=>{let $=process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL??"";if(!$)return[];let N=await fetch(`${$.replace(/\/$/,"")}/r/contractspec.json`,{method:"GET",headers:{Accept:"application/json"}});if(!N.ok)return[];return((await N.json()).items??[]).filter((X)=>X.type==="contractspec:template").map((X)=>({id:X.name,name:X.title??X.name,description:X.description,tags:X.meta?.tags??[],source:"registry",registryUrl:$}))}})}import{useCallback as N0,useEffect as a1,useMemo as T0,useState as K0}from"react";function y4($){let[N,q]=K0(null),[J,X]=K0([]),[K,z]=K0(!1),[U,w]=K0(null),V=T0(()=>$2($),[$]);a1(()=>{let Z=V[0];if(V.length>0&&!N&&Z)q(Z.meta.key)},[V,N]);let f=T0(()=>{return V.find((Z)=>Z.meta.key===N)??null},[V,N]),F=N0((Z)=>{if(!f)return null;let A=J.filter((P)=>P.workflow===f.meta.key).filter((P)=>t1(P,Z)).sort((P,G)=>(P.priority??0)-(G.priority??0));if(A.length===0)return f;let L={...f,steps:[...f.steps]};for(let P of A)L=s1(L,P);return L},[f,J]),Y=T0(()=>F(),[F]),b=N0((Z)=>{q(Z)},[]),W=N0((Z)=>{X((A)=>[...A,Z])},[]),Q=N0((Z,A)=>{X((L)=>{let P=L.filter((M)=>M.workflow===Z),G=L.filter((M)=>M.workflow!==Z);return P.splice(A,1),[...G,...P]})},[]),H=N0(()=>{let Z=Y;if(!Z)return"// No workflow selected";let A=Z.steps.map((P)=>` {
379
+ id: '${P.id}',
380
+ name: '${P.name}',
381
+ type: '${P.type}',${P.description?`
382
+ description: '${P.description}',`:""}${P.next?`
383
+ next: ${JSON.stringify(P.next)},`:""}${P.condition?`
384
+ condition: '${P.condition}',`:""}${P.timeout?`
385
+ timeout: ${P.timeout},`:""}${P.retries?`
386
+ retries: ${P.retries},`:""}${P.onError?`
387
+ onError: '${P.onError}',`:""}
2981
388
  }`).join(`,
2982
- `);
2983
- const extensionsCode = extensions.length > 0 ? `
389
+ `),L=J.length>0?`
2984
390
 
2985
391
  // Extensions applied:
2986
- ${extensions.map((ext) => `// - ${ext.workflow} (priority: ${ext.priority ?? 0})${ext.customSteps?.length ? ` +${ext.customSteps.length} steps` : ""}${ext.hiddenSteps?.length ? ` -${ext.hiddenSteps.length} hidden` : ""}`).join(`
2987
- `)}` : "";
2988
- return `// Workflow Spec: ${composed.meta.key} v${composed.meta.version}
2989
- // Generated from ${templateId} template
2990
- ${extensionsCode}
392
+ ${J.map((P)=>`// - ${P.workflow} (priority: ${P.priority??0})${P.customSteps?.length?` +${P.customSteps.length} steps`:""}${P.hiddenSteps?.length?` -${P.hiddenSteps.length} hidden`:""}`).join(`
393
+ `)}`:"";return`// Workflow Spec: ${Z.meta.key} v${Z.meta.version}
394
+ // Generated from ${$} template
395
+ ${L}
2991
396
 
2992
397
  import { workflowSpec } from '@contractspec/lib.contracts-spec/workflow';
2993
398
 
2994
- export const ${toCamelCase(composed.meta.key)}Workflow = workflowSpec({
399
+ export const ${e1(Z.meta.key)}Workflow = workflowSpec({
2995
400
  meta: {
2996
- key: '${composed.meta.key}',
2997
- version: ${composed.meta.version},${composed.meta.description ? `
2998
- description: '${composed.meta.description}',` : ""}
401
+ key: '${Z.meta.key}',
402
+ version: ${Z.meta.version},${Z.meta.description?`
403
+ description: '${Z.meta.description}',`:""}
2999
404
  },
3000
- start: '${composed.start}',
405
+ start: '${Z.start}',
3001
406
  steps: [
3002
- ${stepsCode}
3003
- ],${composed.context ? `
3004
- context: ${JSON.stringify(composed.context, null, 2)},` : ""}
407
+ ${A}
408
+ ],${Z.context?`
409
+ context: ${JSON.stringify(Z.context,null,2)},`:""}
3005
410
  });
3006
- `;
3007
- }, [workflow, extensions, templateId]);
3008
- return {
3009
- workflow,
3010
- baseWorkflows,
3011
- extensions,
3012
- selectWorkflow,
3013
- addExtension,
3014
- removeExtension,
3015
- compose,
3016
- generateSpecCode,
3017
- loading,
3018
- error
3019
- };
3020
- }
3021
- function matchesScope(extension, scope) {
3022
- if (!scope)
3023
- return true;
3024
- if (extension.tenantId && extension.tenantId !== scope.tenantId) {
3025
- return false;
3026
- }
3027
- if (extension.role && extension.role !== scope.role) {
3028
- return false;
3029
- }
3030
- if (extension.device && extension.device !== scope.device) {
3031
- return false;
3032
- }
3033
- return true;
3034
- }
3035
- function applyExtension(workflow, extension) {
3036
- let steps = [...workflow.steps];
3037
- if (extension.hiddenSteps) {
3038
- steps = steps.filter((s) => !extension.hiddenSteps?.includes(s.id));
3039
- }
3040
- if (extension.customSteps) {
3041
- for (const injection of extension.customSteps) {
3042
- const stepToInject = {
3043
- ...injection.inject,
3044
- id: injection.id ?? injection.inject.id
3045
- };
3046
- if (injection.after) {
3047
- const afterIndex = steps.findIndex((s) => s.id === injection.after);
3048
- if (afterIndex !== -1) {
3049
- steps.splice(afterIndex + 1, 0, stepToInject);
3050
- }
3051
- } else if (injection.before) {
3052
- const beforeIndex = steps.findIndex((s) => s.id === injection.before);
3053
- if (beforeIndex !== -1) {
3054
- steps.splice(beforeIndex, 0, stepToInject);
3055
- }
3056
- } else {
3057
- steps.push(stepToInject);
3058
- }
3059
- }
3060
- }
3061
- return { ...workflow, steps };
3062
- }
3063
- function toCamelCase(str) {
3064
- return str.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toLowerCase());
3065
- }
3066
- function getTemplateWorkflows(templateId) {
3067
- const templateWorkflows = {
3068
- "crm-pipeline": [
3069
- {
3070
- meta: {
3071
- key: "deal.qualification",
3072
- version: "1.0.0",
3073
- description: "Deal qualification workflow"
3074
- },
3075
- start: "lead-received",
3076
- steps: [
3077
- {
3078
- id: "lead-received",
3079
- name: "Lead Received",
3080
- type: "action",
3081
- description: "New lead enters the pipeline",
3082
- next: "qualify-lead"
3083
- },
3084
- {
3085
- id: "qualify-lead",
3086
- name: "Qualify Lead",
3087
- type: "decision",
3088
- description: "Determine if lead meets qualification criteria",
3089
- next: ["qualified", "disqualified"],
3090
- condition: "lead.score >= threshold"
3091
- },
3092
- {
3093
- id: "qualified",
3094
- name: "Lead Qualified",
3095
- type: "action",
3096
- next: "assign-rep"
3097
- },
3098
- {
3099
- id: "disqualified",
3100
- name: "Lead Disqualified",
3101
- type: "end"
3102
- },
3103
- {
3104
- id: "assign-rep",
3105
- name: "Assign Sales Rep",
3106
- type: "action",
3107
- next: "complete"
3108
- },
3109
- {
3110
- id: "complete",
3111
- name: "Workflow Complete",
3112
- type: "end"
3113
- }
3114
- ]
3115
- },
3116
- {
3117
- meta: {
3118
- key: "deal.closing",
3119
- version: "1.0.0",
3120
- description: "Deal closing workflow"
3121
- },
3122
- start: "proposal-sent",
3123
- steps: [
3124
- {
3125
- id: "proposal-sent",
3126
- name: "Proposal Sent",
3127
- type: "action",
3128
- next: "wait-response"
3129
- },
3130
- {
3131
- id: "wait-response",
3132
- name: "Wait for Response",
3133
- type: "wait",
3134
- timeout: 604800000,
3135
- next: "negotiate",
3136
- onError: "follow-up"
3137
- },
3138
- {
3139
- id: "follow-up",
3140
- name: "Follow Up",
3141
- type: "action",
3142
- next: "wait-response",
3143
- retries: 3
3144
- },
3145
- {
3146
- id: "negotiate",
3147
- name: "Negotiation",
3148
- type: "action",
3149
- next: "finalize"
3150
- },
3151
- {
3152
- id: "finalize",
3153
- name: "Finalize Deal",
3154
- type: "decision",
3155
- next: ["won", "lost"],
3156
- condition: "deal.accepted"
3157
- },
3158
- {
3159
- id: "won",
3160
- name: "Deal Won",
3161
- type: "end"
3162
- },
3163
- {
3164
- id: "lost",
3165
- name: "Deal Lost",
3166
- type: "end"
3167
- }
3168
- ]
3169
- }
3170
- ],
3171
- "saas-boilerplate": [
3172
- {
3173
- meta: {
3174
- key: "user.onboarding",
3175
- version: "1.0.0",
3176
- description: "User onboarding workflow"
3177
- },
3178
- start: "signup",
3179
- steps: [
3180
- {
3181
- id: "signup",
3182
- name: "User Signup",
3183
- type: "action",
3184
- next: "verify-email"
3185
- },
3186
- {
3187
- id: "verify-email",
3188
- name: "Verify Email",
3189
- type: "wait",
3190
- timeout: 86400000,
3191
- next: "profile-setup",
3192
- onError: "resend-verification"
3193
- },
3194
- {
3195
- id: "resend-verification",
3196
- name: "Resend Verification",
3197
- type: "action",
3198
- next: "verify-email",
3199
- retries: 2
3200
- },
3201
- {
3202
- id: "profile-setup",
3203
- name: "Setup Profile",
3204
- type: "action",
3205
- next: "onboarding-tour"
3206
- },
3207
- {
3208
- id: "onboarding-tour",
3209
- name: "Onboarding Tour",
3210
- type: "action",
3211
- next: "complete"
3212
- },
3213
- {
3214
- id: "complete",
3215
- name: "Onboarding Complete",
3216
- type: "end"
3217
- }
3218
- ]
3219
- }
3220
- ],
3221
- "agent-console": [
3222
- {
3223
- meta: {
3224
- key: "agent.execution",
3225
- version: "1.0.0",
3226
- description: "Agent execution workflow"
3227
- },
3228
- start: "receive-task",
3229
- steps: [
3230
- {
3231
- id: "receive-task",
3232
- name: "Receive Task",
3233
- type: "action",
3234
- next: "plan-execution"
3235
- },
3236
- {
3237
- id: "plan-execution",
3238
- name: "Plan Execution",
3239
- type: "action",
3240
- next: "execute-steps"
3241
- },
3242
- {
3243
- id: "execute-steps",
3244
- name: "Execute Steps",
3245
- type: "parallel",
3246
- next: ["tool-call", "observe", "reason"]
3247
- },
3248
- {
3249
- id: "tool-call",
3250
- name: "Tool Call",
3251
- type: "action",
3252
- next: "evaluate"
3253
- },
3254
- {
3255
- id: "observe",
3256
- name: "Observe",
3257
- type: "action",
3258
- next: "evaluate"
3259
- },
3260
- {
3261
- id: "reason",
3262
- name: "Reason",
3263
- type: "action",
3264
- next: "evaluate"
3265
- },
3266
- {
3267
- id: "evaluate",
3268
- name: "Evaluate Result",
3269
- type: "decision",
3270
- condition: "task.isComplete",
3271
- next: ["complete", "execute-steps"]
3272
- },
3273
- {
3274
- id: "complete",
3275
- name: "Task Complete",
3276
- type: "end"
3277
- }
3278
- ]
3279
- }
3280
- ],
3281
- "todos-app": [
3282
- {
3283
- meta: {
3284
- key: "task.lifecycle",
3285
- version: "1.0.0",
3286
- description: "Task lifecycle workflow"
3287
- },
3288
- start: "created",
3289
- steps: [
3290
- {
3291
- id: "created",
3292
- name: "Task Created",
3293
- type: "action",
3294
- next: "in-progress"
3295
- },
3296
- {
3297
- id: "in-progress",
3298
- name: "In Progress",
3299
- type: "action",
3300
- next: "review"
3301
- },
3302
- {
3303
- id: "review",
3304
- name: "Review",
3305
- type: "decision",
3306
- condition: "task.approved",
3307
- next: ["done", "in-progress"]
3308
- },
3309
- {
3310
- id: "done",
3311
- name: "Done",
3312
- type: "end"
3313
- }
3314
- ]
3315
- }
3316
- ],
3317
- "messaging-app": [
3318
- {
3319
- meta: {
3320
- key: "message.delivery",
3321
- version: "1.0.0",
3322
- description: "Message delivery workflow"
3323
- },
3324
- start: "compose",
3325
- steps: [
3326
- {
3327
- id: "compose",
3328
- name: "Compose Message",
3329
- type: "action",
3330
- next: "send"
3331
- },
3332
- {
3333
- id: "send",
3334
- name: "Send Message",
3335
- type: "action",
3336
- next: "deliver"
3337
- },
3338
- {
3339
- id: "deliver",
3340
- name: "Deliver",
3341
- type: "decision",
3342
- condition: "recipient.online",
3343
- next: ["delivered", "queue"]
3344
- },
3345
- {
3346
- id: "queue",
3347
- name: "Queue for Delivery",
3348
- type: "wait",
3349
- next: "deliver"
3350
- },
3351
- {
3352
- id: "delivered",
3353
- name: "Message Delivered",
3354
- type: "action",
3355
- next: "read"
3356
- },
3357
- {
3358
- id: "read",
3359
- name: "Message Read",
3360
- type: "end"
3361
- }
3362
- ]
3363
- }
3364
- ],
3365
- "recipe-app-i18n": [
3366
- {
3367
- meta: {
3368
- key: "recipe.creation",
3369
- version: "1.0.0",
3370
- description: "Recipe creation workflow"
3371
- },
3372
- start: "draft",
3373
- steps: [
3374
- {
3375
- id: "draft",
3376
- name: "Draft Recipe",
3377
- type: "action",
3378
- next: "add-ingredients"
3379
- },
3380
- {
3381
- id: "add-ingredients",
3382
- name: "Add Ingredients",
3383
- type: "action",
3384
- next: "add-steps"
3385
- },
3386
- {
3387
- id: "add-steps",
3388
- name: "Add Steps",
3389
- type: "action",
3390
- next: "review"
3391
- },
3392
- {
3393
- id: "review",
3394
- name: "Review Recipe",
3395
- type: "decision",
3396
- condition: "recipe.isComplete",
3397
- next: ["publish", "draft"]
3398
- },
3399
- {
3400
- id: "publish",
3401
- name: "Publish Recipe",
3402
- type: "end"
3403
- }
3404
- ]
3405
- }
3406
- ]
3407
- };
3408
- return templateWorkflows[templateId] ?? [];
3409
- }
3410
- // src/lib/component-registry.tsx
3411
- import { useEffect as useEffect7, useState as useState9 } from "react";
3412
- "use client";
3413
-
3414
- class TemplateComponentRegistry {
3415
- components = new Map;
3416
- listeners = new Set;
3417
- register(templateId, registration) {
3418
- this.components.set(templateId, registration);
3419
- this.listeners.forEach((l) => l(templateId));
3420
- }
3421
- get(templateId) {
3422
- return this.components.get(templateId);
3423
- }
3424
- subscribe(listener) {
3425
- this.listeners.add(listener);
3426
- return () => {
3427
- this.listeners.delete(listener);
3428
- };
3429
- }
3430
- }
3431
- var TEMPLATE_COMPONENT_REGISTRY_KEY = Symbol.for("@contractspec/lib.example-shared-ui/template-component-registry");
3432
- function getTemplateComponentRegistrySingleton() {
3433
- const store = globalThis;
3434
- store[TEMPLATE_COMPONENT_REGISTRY_KEY] ??= new TemplateComponentRegistry;
3435
- return store[TEMPLATE_COMPONENT_REGISTRY_KEY];
3436
- }
3437
- var templateComponentRegistry = getTemplateComponentRegistrySingleton();
3438
- function registerTemplateComponents(templateId, components) {
3439
- templateComponentRegistry.register(templateId, components);
3440
- }
3441
- function useTemplateComponents(templateId) {
3442
- const [components, setComponents] = useState9(() => templateComponentRegistry.get(templateId));
3443
- useEffect7(() => {
3444
- return templateComponentRegistry.subscribe((updatedId) => {
3445
- if (updatedId === templateId) {
3446
- setComponents(templateComponentRegistry.get(templateId));
3447
- }
3448
- });
3449
- }, [templateId]);
3450
- return components;
3451
- }
3452
- // src/utils/fetchPresentationData.ts
3453
- async function fetchPresentationData(_presentationName, _templateId) {
3454
- throw new Error("fetchPresentationData is deprecated. Use fetchData from TemplateRuntimeContext.");
3455
- }
3456
- function hasPresentationDataFetcher(_presentationName) {
3457
- return false;
3458
- }
3459
- function getRegisteredPresentationFetchers() {
3460
- return [];
3461
- }
3462
- // src/index.ts
3463
- import { MarkdownRenderer as MarkdownRenderer2 } from "@contractspec/lib.design-system";
3464
- export {
3465
- useWorkflowComposer,
3466
- useTemplateRuntime,
3467
- useTemplateComponents,
3468
- useSpecContent,
3469
- useRegistryTemplates,
3470
- useOverlayContext,
3471
- useIsInOverlayContext,
3472
- useEvolution,
3473
- useBehaviorTracking,
3474
- templateComponentRegistry,
3475
- registerTemplateComponents,
3476
- hasPresentationDataFetcher,
3477
- getRegisteredPresentationFetchers,
3478
- generateSpecFromTemplate,
3479
- fetchPresentationData,
3480
- TemplateShell,
3481
- TemplateRuntimeContext,
3482
- TemplateComponentRegistry,
3483
- SpecEditorPanel,
3484
- SpecDrivenTemplateShell,
3485
- SaveToStudioButton,
3486
- PersonalizationInsights,
3487
- OverlayContextProvider,
3488
- MarkdownView,
3489
- MarkdownRenderer2 as MarkdownRenderer,
3490
- LocalDataIndicator,
3491
- EvolutionSidebar,
3492
- EvolutionDashboard
3493
- };
411
+ `},[Y,J,$]);return{workflow:Y,baseWorkflows:V,extensions:J,selectWorkflow:b,addExtension:W,removeExtension:Q,compose:F,generateSpecCode:H,loading:K,error:U}}function t1($,N){if(!N)return!0;if($.tenantId&&$.tenantId!==N.tenantId)return!1;if($.role&&$.role!==N.role)return!1;if($.device&&$.device!==N.device)return!1;return!0}function s1($,N){let q=[...$.steps];if(N.hiddenSteps)q=q.filter((J)=>!N.hiddenSteps?.includes(J.id));if(N.customSteps)for(let J of N.customSteps){let X={...J.inject,id:J.id??J.inject.id};if(J.after){let K=q.findIndex((z)=>z.id===J.after);if(K!==-1)q.splice(K+1,0,X)}else if(J.before){let K=q.findIndex((z)=>z.id===J.before);if(K!==-1)q.splice(K,0,X)}else q.push(X)}return{...$,steps:q}}function e1($){return $.replace(/[^a-zA-Z0-9]+(.)/g,(N,q)=>q.toUpperCase()).replace(/^./,(N)=>N.toLowerCase())}function $2($){return{"crm-pipeline":[{meta:{key:"deal.qualification",version:"1.0.0",description:"Deal qualification workflow"},start:"lead-received",steps:[{id:"lead-received",name:"Lead Received",type:"action",description:"New lead enters the pipeline",next:"qualify-lead"},{id:"qualify-lead",name:"Qualify Lead",type:"decision",description:"Determine if lead meets qualification criteria",next:["qualified","disqualified"],condition:"lead.score >= threshold"},{id:"qualified",name:"Lead Qualified",type:"action",next:"assign-rep"},{id:"disqualified",name:"Lead Disqualified",type:"end"},{id:"assign-rep",name:"Assign Sales Rep",type:"action",next:"complete"},{id:"complete",name:"Workflow Complete",type:"end"}]},{meta:{key:"deal.closing",version:"1.0.0",description:"Deal closing workflow"},start:"proposal-sent",steps:[{id:"proposal-sent",name:"Proposal Sent",type:"action",next:"wait-response"},{id:"wait-response",name:"Wait for Response",type:"wait",timeout:604800000,next:"negotiate",onError:"follow-up"},{id:"follow-up",name:"Follow Up",type:"action",next:"wait-response",retries:3},{id:"negotiate",name:"Negotiation",type:"action",next:"finalize"},{id:"finalize",name:"Finalize Deal",type:"decision",next:["won","lost"],condition:"deal.accepted"},{id:"won",name:"Deal Won",type:"end"},{id:"lost",name:"Deal Lost",type:"end"}]}],"saas-boilerplate":[{meta:{key:"user.onboarding",version:"1.0.0",description:"User onboarding workflow"},start:"signup",steps:[{id:"signup",name:"User Signup",type:"action",next:"verify-email"},{id:"verify-email",name:"Verify Email",type:"wait",timeout:86400000,next:"profile-setup",onError:"resend-verification"},{id:"resend-verification",name:"Resend Verification",type:"action",next:"verify-email",retries:2},{id:"profile-setup",name:"Setup Profile",type:"action",next:"onboarding-tour"},{id:"onboarding-tour",name:"Onboarding Tour",type:"action",next:"complete"},{id:"complete",name:"Onboarding Complete",type:"end"}]}],"agent-console":[{meta:{key:"agent.execution",version:"1.0.0",description:"Agent execution workflow"},start:"receive-task",steps:[{id:"receive-task",name:"Receive Task",type:"action",next:"plan-execution"},{id:"plan-execution",name:"Plan Execution",type:"action",next:"execute-steps"},{id:"execute-steps",name:"Execute Steps",type:"parallel",next:["tool-call","observe","reason"]},{id:"tool-call",name:"Tool Call",type:"action",next:"evaluate"},{id:"observe",name:"Observe",type:"action",next:"evaluate"},{id:"reason",name:"Reason",type:"action",next:"evaluate"},{id:"evaluate",name:"Evaluate Result",type:"decision",condition:"task.isComplete",next:["complete","execute-steps"]},{id:"complete",name:"Task Complete",type:"end"}]}],"todos-app":[{meta:{key:"task.lifecycle",version:"1.0.0",description:"Task lifecycle workflow"},start:"created",steps:[{id:"created",name:"Task Created",type:"action",next:"in-progress"},{id:"in-progress",name:"In Progress",type:"action",next:"review"},{id:"review",name:"Review",type:"decision",condition:"task.approved",next:["done","in-progress"]},{id:"done",name:"Done",type:"end"}]}],"messaging-app":[{meta:{key:"message.delivery",version:"1.0.0",description:"Message delivery workflow"},start:"compose",steps:[{id:"compose",name:"Compose Message",type:"action",next:"send"},{id:"send",name:"Send Message",type:"action",next:"deliver"},{id:"deliver",name:"Deliver",type:"decision",condition:"recipient.online",next:["delivered","queue"]},{id:"queue",name:"Queue for Delivery",type:"wait",next:"deliver"},{id:"delivered",name:"Message Delivered",type:"action",next:"read"},{id:"read",name:"Message Read",type:"end"}]}],"recipe-app-i18n":[{meta:{key:"recipe.creation",version:"1.0.0",description:"Recipe creation workflow"},start:"draft",steps:[{id:"draft",name:"Draft Recipe",type:"action",next:"add-ingredients"},{id:"add-ingredients",name:"Add Ingredients",type:"action",next:"add-steps"},{id:"add-steps",name:"Add Steps",type:"action",next:"review"},{id:"review",name:"Review Recipe",type:"decision",condition:"recipe.isComplete",next:["publish","draft"]},{id:"publish",name:"Publish Recipe",type:"end"}]}]}[$]??[]}import{useEffect as N2,useState as q2}from"react";class s0{components=new Map;listeners=new Set;register($,N){this.components.set($,N),this.listeners.forEach((q)=>q($))}get($){return this.components.get($)}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}}var t0=Symbol.for("@contractspec/lib.example-shared-ui/template-component-registry");function P2(){let $=globalThis;return $[t0]??=new s0,$[t0]}var V0=P2();function m4($,N){V0.register($,N)}function l4($){let[N,q]=q2(()=>V0.get($));return N2(()=>{return V0.subscribe((J)=>{if(J===$)q(V0.get($))})},[$]),N}async function o4($,N){throw Error("fetchPresentationData is deprecated. Use fetchData from TemplateRuntimeContext.")}function a4($){return!1}function t4(){return[]}import{MarkdownRenderer as J3}from"@contractspec/lib.design-system";export{y4 as useWorkflowComposer,r as useTemplateRuntime,l4 as useTemplateComponents,o0 as useSpecContent,I4 as useRegistryTemplates,u2 as useOverlayContext,d2 as useIsInOverlayContext,q0 as useEvolution,p0 as useBehaviorTracking,V0 as templateComponentRegistry,m4 as registerTemplateComponents,a4 as hasPresentationDataFetcher,t4 as getRegisteredPresentationFetchers,e as generateSpecFromTemplate,o4 as fetchPresentationData,L4 as TemplateShell,f1 as TemplateRuntimeContext,s0 as TemplateComponentRegistry,h4 as SpecEditorPanel,V4 as SpecDrivenTemplateShell,z0 as SaveToStudioButton,N4 as PersonalizationInsights,p2 as OverlayContextProvider,i2 as MarkdownView,J3 as MarkdownRenderer,P0 as LocalDataIndicator,U2 as EvolutionSidebar,K2 as EvolutionDashboard};