@contractspec/lib.example-shared-ui 6.0.16 → 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 (86) hide show
  1. package/.turbo/turbo-build.log +81 -81
  2. package/CHANGELOG.md +32 -0
  3. package/dist/EvolutionDashboard.js +1 -803
  4. package/dist/EvolutionSidebar.js +1 -531
  5. package/dist/LocalDataIndicator.js +1 -62
  6. package/dist/MarkdownView.js +1 -207
  7. package/dist/OverlayContextProvider.js +1 -202
  8. package/dist/PersonalizationInsights.js +1 -455
  9. package/dist/SaveToStudioButton.js +1 -73
  10. package/dist/SpecDrivenTemplateShell.js +1 -197
  11. package/dist/SpecEditorPanel.js +17 -358
  12. package/dist/TemplateShell.js +1 -189
  13. package/dist/browser/EvolutionDashboard.js +1 -803
  14. package/dist/browser/EvolutionSidebar.js +1 -531
  15. package/dist/browser/LocalDataIndicator.js +1 -62
  16. package/dist/browser/MarkdownView.js +1 -207
  17. package/dist/browser/OverlayContextProvider.js +1 -202
  18. package/dist/browser/PersonalizationInsights.js +1 -455
  19. package/dist/browser/SaveToStudioButton.js +1 -73
  20. package/dist/browser/SpecDrivenTemplateShell.js +1 -197
  21. package/dist/browser/SpecEditorPanel.js +17 -358
  22. package/dist/browser/TemplateShell.js +1 -189
  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 -1145
  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 -218
  30. package/dist/browser/hooks/useWorkflowComposer.js +24 -483
  31. package/dist/browser/index.js +40 -3110
  32. package/dist/browser/lib/component-registry.js +1 -42
  33. package/dist/browser/lib/runtime-context.js +1 -15
  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 -1145
  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 -218
  46. package/dist/hooks/useWorkflowComposer.js +24 -483
  47. package/dist/index.js +40 -3110
  48. package/dist/lib/component-registry.js +1 -42
  49. package/dist/lib/runtime-context.d.ts +2 -1
  50. package/dist/lib/runtime-context.js +1 -15
  51. package/dist/lib/singletons.test.d.ts +1 -0
  52. package/dist/markdown/formatPresentationName.js +1 -9
  53. package/dist/markdown/useMarkdownPresentation.js +1 -65
  54. package/dist/node/EvolutionDashboard.js +1 -803
  55. package/dist/node/EvolutionSidebar.js +1 -531
  56. package/dist/node/LocalDataIndicator.js +1 -62
  57. package/dist/node/MarkdownView.js +1 -207
  58. package/dist/node/OverlayContextProvider.js +1 -202
  59. package/dist/node/PersonalizationInsights.js +1 -455
  60. package/dist/node/SaveToStudioButton.js +1 -73
  61. package/dist/node/SpecDrivenTemplateShell.js +1 -197
  62. package/dist/node/SpecEditorPanel.js +17 -358
  63. package/dist/node/TemplateShell.js +1 -189
  64. package/dist/node/bundles/ExampleTemplateBundle.js +1 -85
  65. package/dist/node/bundles/index.js +1 -85
  66. package/dist/node/hooks/index.js +40 -1145
  67. package/dist/node/hooks/useBehaviorTracking.js +1 -157
  68. package/dist/node/hooks/useEvolution.js +1 -260
  69. package/dist/node/hooks/useRegistryTemplates.js +1 -31
  70. package/dist/node/hooks/useSpecContent.js +17 -218
  71. package/dist/node/hooks/useWorkflowComposer.js +24 -483
  72. package/dist/node/index.js +40 -3110
  73. package/dist/node/lib/component-registry.js +1 -42
  74. package/dist/node/lib/runtime-context.js +1 -15
  75. package/dist/node/markdown/formatPresentationName.js +1 -9
  76. package/dist/node/markdown/useMarkdownPresentation.js +1 -65
  77. package/dist/node/utils/fetchPresentationData.js +1 -15
  78. package/dist/node/utils/generateSpecFromTemplate.js +16 -62
  79. package/dist/node/utils/index.js +16 -76
  80. package/dist/utils/fetchPresentationData.js +1 -15
  81. package/dist/utils/generateSpecFromTemplate.js +16 -62
  82. package/dist/utils/index.js +16 -76
  83. package/package.json +14 -14
  84. package/src/lib/component-registry.tsx +16 -1
  85. package/src/lib/runtime-context.tsx +17 -3
  86. package/src/lib/singletons.test.ts +51 -0
@@ -1,2140 +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 TemplateRuntimeContext = createContext(null);
1077
- function useTemplateRuntime() {
1078
- const context = useContext(TemplateRuntimeContext);
1079
- if (!context) {
1080
- throw new Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");
1081
- }
1082
- return context;
1083
- }
1084
-
1085
- // src/LocalDataIndicator.tsx
1086
- import { RefreshCw, Shield } from "lucide-react";
1087
- import { useState as useState2 } from "react";
1088
- import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1089
- "use client";
1090
- function LocalDataIndicator() {
1091
- const { projectId, templateId, template, installer } = useTemplateRuntime();
1092
- const [isResetting, setIsResetting] = useState2(false);
1093
- const handleReset = async () => {
1094
- setIsResetting(true);
1095
- try {
1096
- await installer.install(templateId, { projectId });
1097
- } finally {
1098
- setIsResetting(false);
1099
- }
1100
- };
1101
- return /* @__PURE__ */ jsxDEV3("div", {
1102
- className: "inline-flex items-center gap-2 rounded-full border border-border bg-muted/40 px-3 py-1 text-muted-foreground text-xs",
1103
- children: [
1104
- /* @__PURE__ */ jsxDEV3(Shield, {
1105
- className: "h-3.5 w-3.5 text-violet-400"
1106
- }, undefined, false, undefined, this),
1107
- /* @__PURE__ */ jsxDEV3("span", {
1108
- children: [
1109
- "Local runtime ·",
1110
- " ",
1111
- /* @__PURE__ */ jsxDEV3("span", {
1112
- className: "font-semibold text-foreground",
1113
- children: template.name
1114
- }, undefined, false, undefined, this)
1115
- ]
1116
- }, undefined, true, undefined, this),
1117
- /* @__PURE__ */ jsxDEV3("button", {
1118
- type: "button",
1119
- 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",
1120
- onClick: handleReset,
1121
- disabled: isResetting,
1122
- children: [
1123
- /* @__PURE__ */ jsxDEV3(RefreshCw, {
1124
- className: "h-3 w-3"
1125
- }, undefined, false, undefined, this),
1126
- isResetting ? "Resetting…" : "Reset data"
1127
- ]
1128
- }, undefined, true, undefined, this)
1129
- ]
1130
- }, undefined, true, undefined, this);
1131
- }
1132
-
1133
- // src/markdown/formatPresentationName.ts
1134
- function formatPresentationName(name) {
1135
- const parts = name.split(".");
1136
- const lastPart = parts[parts.length - 1] ?? name;
1137
- return lastPart.split("-").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1138
- }
1139
-
1140
- // src/markdown/useMarkdownPresentation.ts
1141
- import { useCallback as useCallback4, useEffect as useEffect2, useState as useState3 } from "react";
1142
- "use client";
1143
- function useMarkdownPresentation({
1144
- engine,
1145
- fetchData,
1146
- presentationId,
1147
- presentations,
1148
- resolvePresentation,
1149
- templateId
1150
- }) {
1151
- const [selectedPresentation, setSelectedPresentation] = useState3("");
1152
- const [markdownContent, setMarkdownContent] = useState3("");
1153
- const [loading, setLoading] = useState3(false);
1154
- const [error, setError] = useState3(null);
1155
- useEffect2(() => {
1156
- if (presentationId && presentations.includes(presentationId)) {
1157
- setSelectedPresentation(presentationId);
1158
- return;
1159
- }
1160
- if (presentations.length === 0) {
1161
- setSelectedPresentation("");
1162
- return;
1163
- }
1164
- if (!presentations.includes(selectedPresentation)) {
1165
- setSelectedPresentation(presentations[0] ?? "");
1166
- }
1167
- }, [presentationId, presentations, selectedPresentation, templateId]);
1168
- const renderMarkdown = useCallback4(async () => {
1169
- if (!selectedPresentation || !engine)
1170
- return;
1171
- setLoading(true);
1172
- setError(null);
1173
- try {
1174
- if (!resolvePresentation) {
1175
- throw new Error("resolvePresentation not available in runtime context");
1176
- }
1177
- const descriptor = resolvePresentation(selectedPresentation);
1178
- if (!descriptor) {
1179
- throw new Error(`Presentation descriptor not found: ${selectedPresentation}`);
1180
- }
1181
- const dataResult = await fetchData(selectedPresentation);
1182
- const result = await engine.render("markdown", descriptor, { data: dataResult.data });
1183
- setMarkdownContent(result.body);
1184
- } catch (err) {
1185
- setError(err instanceof Error ? err : new Error("Failed to render markdown"));
1186
- } finally {
1187
- setLoading(false);
1188
- }
1189
- }, [engine, fetchData, resolvePresentation, selectedPresentation]);
1190
- useEffect2(() => {
1191
- renderMarkdown();
1192
- }, [renderMarkdown]);
1193
- return {
1194
- error,
1195
- loading,
1196
- markdownContent,
1197
- renderMarkdown,
1198
- selectedPresentation,
1199
- setSelectedPresentation
1200
- };
1201
- }
1202
-
1203
- // src/MarkdownView.tsx
1204
- import {
1205
- Button as Button3,
1206
- ErrorState,
1207
- LoaderBlock as LoaderBlock2,
1208
- MarkdownRenderer
1209
- } from "@contractspec/lib.design-system";
1210
- import { Badge as Badge3 } from "@contractspec/lib.ui-kit-web/ui/badge";
1211
- import { Card as Card3 } from "@contractspec/lib.ui-kit-web/ui/card";
1212
- import { useCallback as useCallback5 } from "react";
1213
- import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
1214
- "use client";
1215
- function MarkdownView({
1216
- templateId: propTemplateId,
1217
- presentationId,
1218
- className
1219
- }) {
1220
- const {
1221
- engine,
1222
- template,
1223
- templateId: contextTemplateId,
1224
- resolvePresentation,
1225
- fetchData
1226
- } = useTemplateRuntime();
1227
- const templateId = propTemplateId ?? contextTemplateId;
1228
- const presentations = template?.presentations ?? [];
1229
- const {
1230
- error,
1231
- loading,
1232
- markdownContent,
1233
- renderMarkdown,
1234
- selectedPresentation,
1235
- setSelectedPresentation
1236
- } = useMarkdownPresentation({
1237
- engine,
1238
- fetchData,
1239
- presentationId,
1240
- presentations,
1241
- resolvePresentation,
1242
- templateId
1243
- });
1244
- if (!presentations.length) {
1245
- return /* @__PURE__ */ jsxDEV4(Card3, {
1246
- className,
1247
- children: /* @__PURE__ */ jsxDEV4("div", {
1248
- className: "p-6 text-center",
1249
- children: /* @__PURE__ */ jsxDEV4("p", {
1250
- className: "text-muted-foreground",
1251
- children: "No presentations available for this template."
1252
- }, undefined, false, undefined, this)
1253
- }, undefined, false, undefined, this)
1254
- }, undefined, false, undefined, this);
1255
- }
1256
- const handleCopy = useCallback5(() => {
1257
- if (markdownContent) {
1258
- navigator.clipboard.writeText(markdownContent);
1259
- }
1260
- }, [markdownContent]);
1261
- return /* @__PURE__ */ jsxDEV4("div", {
1262
- className,
1263
- children: [
1264
- /* @__PURE__ */ jsxDEV4("div", {
1265
- className: "mb-4 flex flex-wrap items-center gap-2",
1266
- children: [
1267
- /* @__PURE__ */ jsxDEV4("span", {
1268
- className: "font-medium text-muted-foreground text-sm",
1269
- children: "Presentation:"
1270
- }, undefined, false, undefined, this),
1271
- presentations.map((name) => /* @__PURE__ */ jsxDEV4(Button3, {
1272
- variant: selectedPresentation === name ? "default" : "outline",
1273
- size: "sm",
1274
- onPress: () => setSelectedPresentation(name),
1275
- children: formatPresentationName(name)
1276
- }, name, false, undefined, this)),
1277
- /* @__PURE__ */ jsxDEV4("div", {
1278
- className: "ml-auto flex items-center gap-2",
1279
- children: [
1280
- /* @__PURE__ */ jsxDEV4(Badge3, {
1281
- variant: "secondary",
1282
- children: "LLM-friendly"
1283
- }, undefined, false, undefined, this),
1284
- /* @__PURE__ */ jsxDEV4(Button3, {
1285
- variant: "outline",
1286
- size: "sm",
1287
- onPress: handleCopy,
1288
- disabled: !markdownContent || loading,
1289
- children: "Copy"
1290
- }, undefined, false, undefined, this)
1291
- ]
1292
- }, undefined, true, undefined, this)
1293
- ]
1294
- }, undefined, true, undefined, this),
1295
- /* @__PURE__ */ jsxDEV4(Card3, {
1296
- className: "overflow-hidden",
1297
- children: [
1298
- loading && /* @__PURE__ */ jsxDEV4(LoaderBlock2, {
1299
- label: "Rendering markdown..."
1300
- }, undefined, false, undefined, this),
1301
- error && /* @__PURE__ */ jsxDEV4(ErrorState, {
1302
- title: "Render failed",
1303
- description: error.message,
1304
- onRetry: renderMarkdown,
1305
- retryLabel: "Retry"
1306
- }, undefined, false, undefined, this),
1307
- !loading && !error && markdownContent && /* @__PURE__ */ jsxDEV4("div", {
1308
- className: "p-6",
1309
- children: /* @__PURE__ */ jsxDEV4(MarkdownRenderer, {
1310
- content: markdownContent
1311
- }, undefined, false, undefined, this)
1312
- }, undefined, false, undefined, this),
1313
- !loading && !error && !markdownContent && /* @__PURE__ */ jsxDEV4("div", {
1314
- className: "p-6 text-center",
1315
- children: /* @__PURE__ */ jsxDEV4("p", {
1316
- className: "text-muted-foreground",
1317
- children: "Select a presentation to view its markdown output."
1318
- }, undefined, false, undefined, this)
1319
- }, undefined, false, undefined, this)
1320
- ]
1321
- }, undefined, true, undefined, this)
1322
- ]
1323
- }, undefined, true, undefined, this);
1324
- }
1325
-
1326
- // src/OverlayContextProvider.tsx
1327
- import * as React from "react";
1328
- import { useContext as useContext2, useMemo as useMemo4 } from "react";
1329
- import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
1330
- "use client";
1331
- var OverlayContext = React.createContext(null);
1332
- function OverlayContextProvider({
1333
- templateId,
1334
- role = "user",
1335
- device = "desktop",
1336
- children
1337
- }) {
1338
- const overlays = useMemo4(() => getTemplateOverlays(templateId, role), [templateId, role]);
1339
- const activeOverlays = useMemo4(() => {
1340
- return overlays.filter((overlay) => {
1341
- const conditions = overlay.conditions;
1342
- if (!conditions)
1343
- return true;
1344
- if (conditions.role && !conditions.role.includes(role)) {
1345
- return false;
1346
- }
1347
- if (conditions.device && conditions.device !== "any" && conditions.device !== device) {
1348
- return false;
1349
- }
1350
- return true;
1351
- });
1352
- }, [overlays, role, device]);
1353
- const overlayMap = useMemo4(() => {
1354
- const map = new Map;
1355
- for (const overlay of activeOverlays) {
1356
- map.set(overlay.target, overlay);
1357
- }
1358
- return map;
1359
- }, [activeOverlays]);
1360
- const applyOverlay = useMemo4(() => (path, target) => {
1361
- const overlay = overlayMap.get(path);
1362
- if (!overlay)
1363
- return target;
1364
- let result = { ...target };
1365
- for (const mod of overlay.modifications) {
1366
- switch (mod.op) {
1367
- case "hide":
1368
- result = { ...result, hidden: true };
1369
- break;
1370
- case "relabel":
1371
- result = { ...result, label: mod.label };
1372
- break;
1373
- case "reorder":
1374
- result = { ...result, position: mod.position };
1375
- break;
1376
- case "restyle":
1377
- result = {
1378
- ...result,
1379
- className: mod.className,
1380
- variant: mod.variant
1381
- };
1382
- break;
1383
- case "set-default":
1384
- result = { ...result, defaultValue: mod.value };
1385
- break;
1386
- }
1387
- }
1388
- return result;
1389
- }, [overlayMap]);
1390
- const isHidden = useMemo4(() => (path) => {
1391
- const overlay = overlayMap.get(path);
1392
- return overlay?.modifications.some((m) => m.op === "hide") ?? false;
1393
- }, [overlayMap]);
1394
- const getLabel = useMemo4(() => (path, defaultLabel) => {
1395
- const overlay = overlayMap.get(path);
1396
- const relabel = overlay?.modifications.find((m) => m.op === "relabel");
1397
- return relabel && relabel.op === "relabel" ? relabel.label : defaultLabel;
1398
- }, [overlayMap]);
1399
- const getPosition = useMemo4(() => (path, defaultPosition) => {
1400
- const overlay = overlayMap.get(path);
1401
- const reorder = overlay?.modifications.find((m) => m.op === "reorder");
1402
- return reorder && reorder.op === "reorder" ? reorder.position : defaultPosition;
1403
- }, [overlayMap]);
1404
- const getStyle = useMemo4(() => (path) => {
1405
- const overlay = overlayMap.get(path);
1406
- const restyle = overlay?.modifications.find((m) => m.op === "restyle");
1407
- if (restyle && restyle.op === "restyle") {
1408
- return {
1409
- className: restyle.className,
1410
- variant: restyle.variant
1411
- };
1412
- }
1413
- return {};
1414
- }, [overlayMap]);
1415
- const getDefault = useMemo4(() => (path, defaultValue) => {
1416
- const overlay = overlayMap.get(path);
1417
- const setDefault = overlay?.modifications.find((m) => m.op === "set-default");
1418
- return setDefault && setDefault.op === "set-default" ? setDefault.value : defaultValue;
1419
- }, [overlayMap]);
1420
- const value = useMemo4(() => ({
1421
- overlays: activeOverlays,
1422
- applyOverlay,
1423
- isHidden,
1424
- getLabel,
1425
- getPosition,
1426
- getStyle,
1427
- getDefault,
1428
- role,
1429
- device
1430
- }), [
1431
- activeOverlays,
1432
- applyOverlay,
1433
- isHidden,
1434
- getLabel,
1435
- getPosition,
1436
- getStyle,
1437
- getDefault,
1438
- role,
1439
- device
1440
- ]);
1441
- return /* @__PURE__ */ jsxDEV5(OverlayContext.Provider, {
1442
- value,
1443
- children
1444
- }, undefined, false, undefined, this);
1445
- }
1446
- function useOverlayContext() {
1447
- const context = useContext2(OverlayContext);
1448
- if (!context) {
1449
- throw new Error("useOverlayContext must be used within an OverlayContextProvider");
1450
- }
1451
- return context;
1452
- }
1453
- function useIsInOverlayContext() {
1454
- return useContext2(OverlayContext) !== null;
1455
- }
1456
- function getTemplateOverlays(templateId, _role) {
1457
- const templateOverlays = {
1458
- "crm-pipeline": [
1459
- {
1460
- id: "crm-hide-internal-fields",
1461
- target: "deal.internalNotes",
1462
- modifications: [{ op: "hide" }],
1463
- conditions: { role: ["viewer", "user"] }
1464
- },
1465
- {
1466
- id: "crm-relabel-value",
1467
- target: "deal.value",
1468
- modifications: [{ op: "relabel", label: "Deal Amount" }]
1469
- }
1470
- ],
1471
- "saas-boilerplate": [
1472
- {
1473
- id: "saas-hide-billing",
1474
- target: "settings.billing",
1475
- modifications: [{ op: "hide" }],
1476
- conditions: { role: ["viewer"] }
1477
- },
1478
- {
1479
- id: "saas-restyle-plan",
1480
- target: "settings.plan",
1481
- modifications: [{ op: "restyle", variant: "premium" }],
1482
- conditions: { role: ["admin"] }
1483
- }
1484
- ],
1485
- "agent-console": [
1486
- {
1487
- id: "agent-hide-cost",
1488
- target: "run.cost",
1489
- modifications: [{ op: "hide" }],
1490
- conditions: { role: ["viewer"] }
1491
- },
1492
- {
1493
- id: "agent-relabel-tokens",
1494
- target: "run.tokens",
1495
- modifications: [{ op: "relabel", label: "Token Usage" }]
1496
- }
1497
- ],
1498
- "todos-app": [
1499
- {
1500
- id: "todos-hide-assignee",
1501
- target: "task.assignee",
1502
- modifications: [{ op: "hide" }],
1503
- conditions: { device: "mobile" }
1504
- }
1505
- ],
1506
- "messaging-app": [
1507
- {
1508
- id: "messaging-reorder-timestamp",
1509
- target: "message.timestamp",
1510
- modifications: [{ op: "reorder", position: 0 }]
1511
- }
1512
- ],
1513
- "recipe-app-i18n": [
1514
- {
1515
- id: "recipe-relabel-servings",
1516
- target: "recipe.servings",
1517
- modifications: [{ op: "relabel", label: "Portions" }]
1518
- }
1519
- ]
1520
- };
1521
- return templateOverlays[templateId] ?? [];
1522
- }
1523
-
1524
- // src/hooks/useBehaviorTracking.ts
1525
- import { useCallback as useCallback6, useEffect as useEffect3, useMemo as useMemo5, useRef as useRef2, useState as useState4 } from "react";
1526
- "use client";
1527
- var BEHAVIOR_STORAGE_KEY = "contractspec-behavior-data";
1528
- var ALL_FEATURES = [
1529
- "playground",
1530
- "specs",
1531
- "builder",
1532
- "markdown",
1533
- "evolution",
1534
- "canvas_add",
1535
- "canvas_delete",
1536
- "spec_save",
1537
- "spec_validate",
1538
- "ai_suggestions"
1539
- ];
1540
- function useBehaviorTracking(templateId) {
1541
- const [events, setEvents] = useState4([]);
1542
- const sessionStartRef = useRef2(new Date);
1543
- const [eventCount, setEventCount] = useState4(0);
1544
- useEffect3(() => {
1545
- try {
1546
- const stored = localStorage.getItem(BEHAVIOR_STORAGE_KEY);
1547
- if (stored) {
1548
- const data = JSON.parse(stored);
1549
- setEvents(data.events.map((e) => ({
1550
- ...e,
1551
- timestamp: new Date(e.timestamp)
1552
- })));
1553
- sessionStartRef.current = new Date(data.sessionStart);
1554
- }
1555
- } catch {}
1556
- }, []);
1557
- useEffect3(() => {
1558
- if (events.length > 0) {
1559
- try {
1560
- localStorage.setItem(BEHAVIOR_STORAGE_KEY, JSON.stringify({
1561
- events: events.map((e) => ({
1562
- ...e,
1563
- timestamp: e.timestamp.toISOString()
1564
- })),
1565
- sessionStart: sessionStartRef.current.toISOString()
1566
- }));
1567
- } catch {}
1568
- }
1569
- }, [events]);
1570
- const trackEvent = useCallback6((type, metadata) => {
1571
- const event = {
1572
- type,
1573
- timestamp: new Date,
1574
- templateId,
1575
- metadata
1576
- };
1577
- setEvents((prev) => [...prev, event]);
1578
- setEventCount((prev) => prev + 1);
1579
- }, [templateId]);
1580
- const getEventsByType = useCallback6((type) => {
1581
- return events.filter((e) => e.type === type);
1582
- }, [events]);
1583
- const getSummary = useCallback6(() => {
1584
- const now = new Date;
1585
- const sessionDuration = now.getTime() - sessionStartRef.current.getTime();
1586
- const templateCounts = new Map;
1587
- for (const event of events) {
1588
- const count = templateCounts.get(event.templateId) ?? 0;
1589
- templateCounts.set(event.templateId, count + 1);
1590
- }
1591
- const mostUsedTemplates = Array.from(templateCounts.entries()).map(([templateId2, count]) => ({ templateId: templateId2, count })).sort((a, b) => b.count - a.count).slice(0, 3);
1592
- const modeCounts = new Map;
1593
- for (const event of events) {
1594
- if (event.type === "mode_change" && event.metadata?.mode) {
1595
- const mode = event.metadata.mode;
1596
- const count = modeCounts.get(mode) ?? 0;
1597
- modeCounts.set(mode, count + 1);
1598
- }
1599
- }
1600
- const mostUsedModes = Array.from(modeCounts.entries()).map(([mode, count]) => ({ mode, count })).sort((a, b) => b.count - a.count);
1601
- const featuresUsed = new Set;
1602
- for (const event of events) {
1603
- if (event.type === "mode_change" && event.metadata?.mode) {
1604
- featuresUsed.add(event.metadata.mode);
1605
- }
1606
- if (event.type === "feature_usage" && event.metadata?.feature) {
1607
- featuresUsed.add(event.metadata.feature);
1608
- }
1609
- if (event.type === "canvas_interaction") {
1610
- const action = event.metadata?.action;
1611
- if (action === "add")
1612
- featuresUsed.add("canvas_add");
1613
- if (action === "delete")
1614
- featuresUsed.add("canvas_delete");
1615
- }
1616
- if (event.type === "spec_edit") {
1617
- const action = event.metadata?.action;
1618
- if (action === "save")
1619
- featuresUsed.add("spec_save");
1620
- if (action === "validate")
1621
- featuresUsed.add("spec_validate");
1622
- }
1623
- }
1624
- const unusedFeatures = ALL_FEATURES.filter((f) => !featuresUsed.has(f));
1625
- const errorCount = events.filter((e) => e.type === "error").length;
1626
- const recommendations = generateRecommendations(Array.from(featuresUsed), unusedFeatures, mostUsedModes, events.length);
1627
- return {
1628
- totalEvents: events.length,
1629
- sessionDuration,
1630
- mostUsedTemplates,
1631
- mostUsedModes,
1632
- featuresUsed: Array.from(featuresUsed),
1633
- unusedFeatures,
1634
- errorCount,
1635
- recommendations
1636
- };
1637
- }, [events]);
1638
- const clear = useCallback6(() => {
1639
- setEvents([]);
1640
- setEventCount(0);
1641
- sessionStartRef.current = new Date;
1642
- localStorage.removeItem(BEHAVIOR_STORAGE_KEY);
1643
- }, []);
1644
- return useMemo5(() => ({
1645
- trackEvent,
1646
- getSummary,
1647
- getEventsByType,
1648
- eventCount,
1649
- sessionStart: sessionStartRef.current,
1650
- clear
1651
- }), [trackEvent, getSummary, getEventsByType, eventCount, clear]);
1652
- }
1653
- function generateRecommendations(featuresUsed, unusedFeatures, mostUsedModes, totalEvents) {
1654
- const recommendations = [];
1655
- if (unusedFeatures.includes("evolution")) {
1656
- recommendations.push("Try the AI Evolution mode to get automated improvement suggestions");
1657
- }
1658
- if (unusedFeatures.includes("markdown")) {
1659
- recommendations.push("Use Markdown preview to see documentation for your specs");
1660
- }
1661
- if (unusedFeatures.includes("builder")) {
1662
- recommendations.push("Explore the Visual Builder to design your UI components");
1663
- }
1664
- if (!featuresUsed.includes("spec_validate") && featuresUsed.includes("specs")) {
1665
- recommendations.push("Don't forget to validate your specs before saving");
1666
- }
1667
- if (featuresUsed.includes("evolution") && !featuresUsed.includes("ai_suggestions")) {
1668
- recommendations.push("Generate AI suggestions to get actionable improvement recommendations");
1669
- }
1670
- if (totalEvents > 50) {
1671
- recommendations.push("Great engagement! Consider saving your work regularly");
1672
- }
1673
- if (mostUsedModes.length === 1) {
1674
- recommendations.push("Try different modes to explore all sandbox capabilities");
1675
- }
1676
- return recommendations;
1677
- }
1678
-
1679
- // src/PersonalizationInsights.tsx
1680
- import { Button as Button4 } from "@contractspec/lib.design-system";
1681
- import { Badge as Badge4 } from "@contractspec/lib.ui-kit-web/ui/badge";
1682
- import { Card as Card4 } from "@contractspec/lib.ui-kit-web/ui/card";
1683
- import { useCallback as useCallback7, useMemo as useMemo6, useState as useState5 } from "react";
1684
- import { jsxDEV as jsxDEV6 } from "react/jsx-dev-runtime";
1685
- "use client";
1686
- function PersonalizationInsights({
1687
- templateId,
1688
- collapsed = false,
1689
- onToggle
1690
- }) {
1691
- const { getSummary, eventCount, clear, sessionStart } = useBehaviorTracking(templateId);
1692
- const [showDetails, setShowDetails] = useState5(false);
1693
- const summary = useMemo6(() => getSummary(), [getSummary]);
1694
- const formatDuration = useCallback7((ms) => {
1695
- const seconds = Math.floor(ms / 1000);
1696
- const minutes = Math.floor(seconds / 60);
1697
- const hours = Math.floor(minutes / 60);
1698
- if (hours > 0) {
1699
- return `${hours}h ${minutes % 60}m`;
1700
- }
1701
- if (minutes > 0) {
1702
- return `${minutes}m ${seconds % 60}s`;
1703
- }
1704
- return `${seconds}s`;
1705
- }, []);
1706
- const handleClear = useCallback7(() => {
1707
- clear();
1708
- }, [clear]);
1709
- if (collapsed) {
1710
- return /* @__PURE__ */ jsxDEV6("button", {
1711
- onClick: onToggle,
1712
- 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",
1713
- type: "button",
1714
- children: [
1715
- /* @__PURE__ */ jsxDEV6("span", {
1716
- children: "\uD83D\uDCCA"
1717
- }, undefined, false, undefined, this),
1718
- /* @__PURE__ */ jsxDEV6("span", {
1719
- children: "Insights"
1720
- }, undefined, false, undefined, this),
1721
- /* @__PURE__ */ jsxDEV6(Badge4, {
1722
- variant: "secondary",
1723
- children: eventCount
1724
- }, undefined, false, undefined, this)
1725
- ]
1726
- }, undefined, true, undefined, this);
1727
- }
1728
- return /* @__PURE__ */ jsxDEV6(Card4, {
1729
- className: "overflow-hidden",
1730
- children: [
1731
- /* @__PURE__ */ jsxDEV6("div", {
1732
- className: "flex items-center justify-between border-blue-500/20 border-b bg-blue-500/5 px-4 py-3",
1733
- children: [
1734
- /* @__PURE__ */ jsxDEV6("div", {
1735
- className: "flex items-center gap-2",
1736
- children: [
1737
- /* @__PURE__ */ jsxDEV6("span", {
1738
- children: "\uD83D\uDCCA"
1739
- }, undefined, false, undefined, this),
1740
- /* @__PURE__ */ jsxDEV6("span", {
1741
- className: "font-semibold",
1742
- children: "Personalization Insights"
1743
- }, undefined, false, undefined, this)
1744
- ]
1745
- }, undefined, true, undefined, this),
1746
- /* @__PURE__ */ jsxDEV6("div", {
1747
- className: "flex items-center gap-2",
1748
- children: [
1749
- /* @__PURE__ */ jsxDEV6(Button4, {
1750
- variant: "ghost",
1751
- size: "sm",
1752
- onPress: () => setShowDetails(!showDetails),
1753
- children: showDetails ? "Hide Details" : "Show Details"
1754
- }, undefined, false, undefined, this),
1755
- onToggle && /* @__PURE__ */ jsxDEV6("button", {
1756
- onClick: onToggle,
1757
- className: "p-1 text-muted-foreground hover:text-foreground",
1758
- type: "button",
1759
- title: "Collapse",
1760
- children: "✕"
1761
- }, undefined, false, undefined, this)
1762
- ]
1763
- }, undefined, true, undefined, this)
1764
- ]
1765
- }, undefined, true, undefined, this),
1766
- /* @__PURE__ */ jsxDEV6("div", {
1767
- className: "p-4",
1768
- children: [
1769
- /* @__PURE__ */ jsxDEV6("div", {
1770
- className: "mb-4 grid grid-cols-2 gap-3 md:grid-cols-4",
1771
- children: [
1772
- /* @__PURE__ */ jsxDEV6(StatCard, {
1773
- label: "Session Time",
1774
- value: formatDuration(summary.sessionDuration),
1775
- icon: "⏱️"
1776
- }, undefined, false, undefined, this),
1777
- /* @__PURE__ */ jsxDEV6(StatCard, {
1778
- label: "Events Tracked",
1779
- value: summary.totalEvents.toString(),
1780
- icon: "\uD83D\uDCC8"
1781
- }, undefined, false, undefined, this),
1782
- /* @__PURE__ */ jsxDEV6(StatCard, {
1783
- label: "Features Used",
1784
- value: `${summary.featuresUsed.length}/${summary.featuresUsed.length + summary.unusedFeatures.length}`,
1785
- icon: "✨"
1786
- }, undefined, false, undefined, this),
1787
- /* @__PURE__ */ jsxDEV6(StatCard, {
1788
- label: "Errors",
1789
- value: summary.errorCount.toString(),
1790
- icon: "⚠️",
1791
- variant: summary.errorCount > 0 ? "warning" : "success"
1792
- }, undefined, false, undefined, this)
1793
- ]
1794
- }, undefined, true, undefined, this),
1795
- summary.recommendations.length > 0 && /* @__PURE__ */ jsxDEV6("div", {
1796
- className: "mb-4",
1797
- children: [
1798
- /* @__PURE__ */ jsxDEV6("h4", {
1799
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1800
- children: "Recommendations"
1801
- }, undefined, false, undefined, this),
1802
- /* @__PURE__ */ jsxDEV6("ul", {
1803
- className: "space-y-1",
1804
- children: summary.recommendations.map((rec, index) => /* @__PURE__ */ jsxDEV6("li", {
1805
- className: "flex items-start gap-2 text-sm",
1806
- children: [
1807
- /* @__PURE__ */ jsxDEV6("span", {
1808
- className: "text-blue-400",
1809
- children: "\uD83D\uDCA1"
1810
- }, undefined, false, undefined, this),
1811
- /* @__PURE__ */ jsxDEV6("span", {
1812
- children: rec
1813
- }, undefined, false, undefined, this)
1814
- ]
1815
- }, index, true, undefined, this))
1816
- }, undefined, false, undefined, this)
1817
- ]
1818
- }, undefined, true, undefined, this),
1819
- summary.unusedFeatures.length > 0 && /* @__PURE__ */ jsxDEV6("div", {
1820
- className: "mb-4",
1821
- children: [
1822
- /* @__PURE__ */ jsxDEV6("h4", {
1823
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1824
- children: "Try These Features"
1825
- }, undefined, false, undefined, this),
1826
- /* @__PURE__ */ jsxDEV6("div", {
1827
- className: "flex flex-wrap gap-2",
1828
- children: summary.unusedFeatures.slice(0, 5).map((feature) => /* @__PURE__ */ jsxDEV6(Badge4, {
1829
- variant: "secondary",
1830
- children: formatFeatureName(feature)
1831
- }, feature, false, undefined, this))
1832
- }, undefined, false, undefined, this)
1833
- ]
1834
- }, undefined, true, undefined, this),
1835
- showDetails && /* @__PURE__ */ jsxDEV6(DetailedInsights, {
1836
- summary,
1837
- sessionStart
1838
- }, undefined, false, undefined, this),
1839
- /* @__PURE__ */ jsxDEV6("div", {
1840
- className: "mt-4 flex justify-end border-blue-500/10 border-t pt-4",
1841
- children: /* @__PURE__ */ jsxDEV6(Button4, {
1842
- variant: "ghost",
1843
- size: "sm",
1844
- onPress: handleClear,
1845
- children: "Clear Data"
1846
- }, undefined, false, undefined, this)
1847
- }, undefined, false, undefined, this)
1848
- ]
1849
- }, undefined, true, undefined, this)
1850
- ]
1851
- }, undefined, true, undefined, this);
1852
- }
1853
- function StatCard({
1854
- label,
1855
- value,
1856
- icon,
1857
- variant = "default"
1858
- }) {
1859
- const bgColors = {
1860
- default: "bg-blue-500/5 border-blue-500/20",
1861
- warning: "bg-amber-500/5 border-amber-500/20",
1862
- success: "bg-green-500/5 border-green-500/20"
1863
- };
1864
- return /* @__PURE__ */ jsxDEV6("div", {
1865
- className: `rounded-lg border p-3 text-center ${bgColors[variant]}`,
1866
- children: [
1867
- /* @__PURE__ */ jsxDEV6("div", {
1868
- className: "mb-1 text-lg",
1869
- children: icon
1870
- }, undefined, false, undefined, this),
1871
- /* @__PURE__ */ jsxDEV6("div", {
1872
- className: "font-bold text-lg",
1873
- children: value
1874
- }, undefined, false, undefined, this),
1875
- /* @__PURE__ */ jsxDEV6("div", {
1876
- className: "text-muted-foreground text-xs",
1877
- children: label
1878
- }, undefined, false, undefined, this)
1879
- ]
1880
- }, undefined, true, undefined, this);
1881
- }
1882
- function DetailedInsights({
1883
- summary,
1884
- sessionStart
1885
- }) {
1886
- return /* @__PURE__ */ jsxDEV6("div", {
1887
- className: "mt-4 space-y-4 border-blue-500/10 border-t pt-4",
1888
- children: [
1889
- summary.mostUsedTemplates.length > 0 && /* @__PURE__ */ jsxDEV6("div", {
1890
- children: [
1891
- /* @__PURE__ */ jsxDEV6("h4", {
1892
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1893
- children: "Most Used Templates"
1894
- }, undefined, false, undefined, this),
1895
- /* @__PURE__ */ jsxDEV6("div", {
1896
- className: "space-y-1",
1897
- children: summary.mostUsedTemplates.map(({ templateId, count }) => /* @__PURE__ */ jsxDEV6("div", {
1898
- className: "flex items-center justify-between text-sm",
1899
- children: [
1900
- /* @__PURE__ */ jsxDEV6("span", {
1901
- children: formatTemplateId(templateId)
1902
- }, undefined, false, undefined, this),
1903
- /* @__PURE__ */ jsxDEV6("span", {
1904
- className: "text-muted-foreground",
1905
- children: [
1906
- count,
1907
- " events"
1908
- ]
1909
- }, undefined, true, undefined, this)
1910
- ]
1911
- }, templateId, true, undefined, this))
1912
- }, undefined, false, undefined, this)
1913
- ]
1914
- }, undefined, true, undefined, this),
1915
- summary.mostUsedModes.length > 0 && /* @__PURE__ */ jsxDEV6("div", {
1916
- children: [
1917
- /* @__PURE__ */ jsxDEV6("h4", {
1918
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1919
- children: "Mode Usage"
1920
- }, undefined, false, undefined, this),
1921
- /* @__PURE__ */ jsxDEV6("div", {
1922
- className: "space-y-1",
1923
- children: summary.mostUsedModes.map(({ mode, count }) => /* @__PURE__ */ jsxDEV6("div", {
1924
- className: "flex items-center justify-between text-sm",
1925
- children: [
1926
- /* @__PURE__ */ jsxDEV6("span", {
1927
- children: formatFeatureName(mode)
1928
- }, undefined, false, undefined, this),
1929
- /* @__PURE__ */ jsxDEV6("span", {
1930
- className: "text-muted-foreground",
1931
- children: [
1932
- count,
1933
- " switches"
1934
- ]
1935
- }, undefined, true, undefined, this)
1936
- ]
1937
- }, mode, true, undefined, this))
1938
- }, undefined, false, undefined, this)
1939
- ]
1940
- }, undefined, true, undefined, this),
1941
- /* @__PURE__ */ jsxDEV6("div", {
1942
- children: [
1943
- /* @__PURE__ */ jsxDEV6("h4", {
1944
- className: "mb-2 font-semibold text-blue-400 text-xs uppercase",
1945
- children: "Features Used"
1946
- }, undefined, false, undefined, this),
1947
- /* @__PURE__ */ jsxDEV6("div", {
1948
- className: "flex flex-wrap gap-2",
1949
- children: summary.featuresUsed.map((feature) => /* @__PURE__ */ jsxDEV6(Badge4, {
1950
- variant: "default",
1951
- className: "border-green-500/30 bg-green-500/20 text-green-400",
1952
- children: [
1953
- "✓ ",
1954
- formatFeatureName(feature)
1955
- ]
1956
- }, feature, true, undefined, this))
1957
- }, undefined, false, undefined, this)
1958
- ]
1959
- }, undefined, true, undefined, this),
1960
- /* @__PURE__ */ jsxDEV6("div", {
1961
- className: "text-muted-foreground text-xs",
1962
- children: [
1963
- "Session started: ",
1964
- sessionStart.toLocaleString()
1965
- ]
1966
- }, undefined, true, undefined, this)
1967
- ]
1968
- }, undefined, true, undefined, this);
1969
- }
1970
- function formatFeatureName(feature) {
1971
- return feature.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
1972
- }
1973
- function formatTemplateId(id) {
1974
- return id.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
1975
- }
1976
-
1977
- // src/SaveToStudioButton.tsx
1978
- import { Sparkles } from "lucide-react";
1979
- import { useState as useState6 } from "react";
1980
- import { jsxDEV as jsxDEV7 } from "react/jsx-dev-runtime";
1981
- "use client";
1982
- function SaveToStudioButton({
1983
- organizationId = "demo-org",
1984
- projectName,
1985
- endpoint,
1986
- token
1987
- }) {
1988
- const { installer, templateId, template } = useTemplateRuntime();
1989
- const [status, setStatus] = useState6("idle");
1990
- const [error, setError] = useState6(null);
1991
- const handleSave = async () => {
1992
- setStatus("saving");
1993
- setError(null);
1994
- try {
1995
- await installer.saveToStudio({
1996
- templateId,
1997
- projectName: projectName ?? `${template.name} demo`,
1998
- organizationId,
1999
- endpoint,
2000
- token
2001
- });
2002
- setStatus("saved");
2003
- setTimeout(() => setStatus("idle"), 3000);
2004
- } catch (err) {
2005
- setStatus("error");
2006
- setError(err instanceof Error ? err.message : "Unknown error");
2007
- }
2008
- };
2009
- return /* @__PURE__ */ jsxDEV7("div", {
2010
- className: "flex flex-col items-end gap-1",
2011
- children: [
2012
- /* @__PURE__ */ jsxDEV7("button", {
2013
- type: "button",
2014
- className: "btn-primary inline-flex items-center gap-2 text-sm",
2015
- onClick: handleSave,
2016
- disabled: status === "saving",
2017
- children: [
2018
- /* @__PURE__ */ jsxDEV7(Sparkles, {
2019
- className: "h-4 w-4"
2020
- }, undefined, false, undefined, this),
2021
- status === "saving" ? "Publishing…" : "Save to Studio"
2022
- ]
2023
- }, undefined, true, undefined, this),
2024
- status === "error" && error ? /* @__PURE__ */ jsxDEV7("p", {
2025
- className: "text-destructive text-xs",
2026
- children: error
2027
- }, undefined, false, undefined, this) : null,
2028
- status === "saved" ? /* @__PURE__ */ jsxDEV7("p", {
2029
- className: "text-emerald-400 text-xs",
2030
- children: "Template sent to Studio."
2031
- }, undefined, false, undefined, this) : null
2032
- ]
2033
- }, undefined, true, undefined, this);
2034
- }
2035
-
2036
- // src/SpecDrivenTemplateShell.tsx
2037
- import {
2038
- BundleProvider,
2039
- BundleRenderer
2040
- } from "@contractspec/lib.surface-runtime/react";
2041
- import { jsxDEV as jsxDEV8 } from "react/jsx-dev-runtime";
2042
- function SpecDrivenTemplateShell({
2043
- plan,
2044
- title,
2045
- description,
2046
- sidebar,
2047
- actions,
2048
- showSaveAction = true,
2049
- saveProps,
2050
- children
2051
- }) {
2052
- const headerContent = /* @__PURE__ */ jsxDEV8("header", {
2053
- className: "rounded-2xl border border-border bg-card p-6 shadow-sm",
2054
- children: [
2055
- /* @__PURE__ */ jsxDEV8("div", {
2056
- className: "flex flex-wrap items-center justify-between gap-4",
2057
- children: [
2058
- /* @__PURE__ */ jsxDEV8("div", {
2059
- children: [
2060
- /* @__PURE__ */ jsxDEV8("p", {
2061
- className: "font-semibold text-muted-foreground text-sm uppercase tracking-wide",
2062
- children: "ContractSpec Templates"
2063
- }, undefined, false, undefined, this),
2064
- /* @__PURE__ */ jsxDEV8("h1", {
2065
- className: "font-bold text-3xl",
2066
- children: title
2067
- }, undefined, false, undefined, this),
2068
- description ? /* @__PURE__ */ jsxDEV8("p", {
2069
- className: "mt-2 max-w-2xl text-muted-foreground text-sm",
2070
- children: description
2071
- }, undefined, false, undefined, this) : null
2072
- ]
2073
- }, undefined, true, undefined, this),
2074
- /* @__PURE__ */ jsxDEV8("div", {
2075
- className: "flex flex-col items-end gap-2",
2076
- children: [
2077
- /* @__PURE__ */ jsxDEV8(LocalDataIndicator, {}, undefined, false, undefined, this),
2078
- showSaveAction ? /* @__PURE__ */ jsxDEV8(SaveToStudioButton, {
2079
- ...saveProps
2080
- }, undefined, false, undefined, this) : null
2081
- ]
2082
- }, undefined, true, undefined, this)
2083
- ]
2084
- }, undefined, true, undefined, this),
2085
- actions ? /* @__PURE__ */ jsxDEV8("div", {
2086
- className: "mt-4",
2087
- children: actions
2088
- }, undefined, false, undefined, this) : null
2089
- ]
2090
- }, undefined, true, undefined, this);
2091
- const slotContent = {
2092
- header: headerContent,
2093
- primary: /* @__PURE__ */ jsxDEV8("main", {
2094
- className: "space-y-4 p-2",
2095
- children
2096
- }, undefined, false, undefined, this)
2097
- };
2098
- if (sidebar != null) {
2099
- slotContent.sidebar = /* @__PURE__ */ jsxDEV8("aside", {
2100
- className: "rounded-2xl border border-border bg-card p-4",
2101
- children: sidebar
2102
- }, undefined, false, undefined, this);
2103
- }
2104
- return /* @__PURE__ */ jsxDEV8(BundleProvider, {
2105
- plan,
2106
- children: /* @__PURE__ */ jsxDEV8(BundleRenderer, {
2107
- slotContent
2108
- }, undefined, false, undefined, this)
2109
- }, undefined, false, undefined, this);
2110
- }
2111
-
2112
- // src/utils/generateSpecFromTemplate.ts
2113
- function generateSpecFromTemplate(template) {
2114
- const templateId = template?.id ?? "unknown";
2115
- if (!template) {
2116
- return generateDefaultSpec(templateId);
2117
- }
2118
- switch (templateId) {
2119
- case "crm-pipeline":
2120
- return generateCrmPipelineSpec(template.schema.contracts);
2121
- case "saas-boilerplate":
2122
- return generateSaasBoilerplateSpec(template.schema.contracts);
2123
- case "agent-console":
2124
- return generateAgentConsoleSpec(template.schema.contracts);
2125
- case "todos-app":
2126
- return generateTodosSpec(template.schema.contracts);
2127
- case "messaging-app":
2128
- return generateMessagingSpec(template.schema.contracts);
2129
- case "recipe-app-i18n":
2130
- return generateRecipeSpec(template.schema.contracts);
2131
- default:
2132
- return generateDefaultSpec(templateId);
2133
- }
2134
- }
2135
- function generateCrmPipelineSpec(contracts) {
2136
- return `// CRM Pipeline Specs
2137
- // 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(", ")}
2138
3
 
2139
4
  contractSpec("crm.deal.updateStage.v1", {
2140
5
  goal: "Move a deal to a different pipeline stage",
@@ -2203,11 +68,8 @@ contractSpec("crm.contact.list.v1", {
2203
68
  hasMore: "boolean"
2204
69
  }
2205
70
  }
2206
- });`;
2207
- }
2208
- function generateSaasBoilerplateSpec(contracts) {
2209
- return `// SaaS Boilerplate Specs
2210
- // Contracts: ${contracts.join(", ")}
71
+ });`}function x1($){return`// SaaS Boilerplate Specs
72
+ // Contracts: ${$.join(", ")}
2211
73
 
2212
74
  contractSpec("saas.project.create.v1", {
2213
75
  goal: "Create a new project in an organization",
@@ -2270,11 +132,8 @@ contractSpec("saas.settings.update.v1", {
2270
132
  }
2271
133
  },
2272
134
  events: ["settings.updated"]
2273
- });`;
2274
- }
2275
- function generateAgentConsoleSpec(contracts) {
2276
- return `// Agent Console Specs
2277
- // Contracts: ${contracts.join(", ")}
135
+ });`}function g1($){return`// Agent Console Specs
136
+ // Contracts: ${$.join(", ")}
2278
137
 
2279
138
  contractSpec("agent.run.execute.v1", {
2280
139
  goal: "Execute an agent run with specified tools",
@@ -2340,11 +199,8 @@ contractSpec("agent.agent.create.v1", {
2340
199
  }
2341
200
  },
2342
201
  events: ["agent.created"]
2343
- });`;
2344
- }
2345
- function generateTodosSpec(contracts) {
2346
- return `// To-dos App Specs
2347
- // Contracts: ${contracts.join(", ")}
202
+ });`}function p1($){return`// To-dos App Specs
203
+ // Contracts: ${$.join(", ")}
2348
204
 
2349
205
  contractSpec("tasks.board.v1", {
2350
206
  goal: "Assign and approve craft work",
@@ -2403,11 +259,8 @@ contractSpec("tasks.complete.v1", {
2403
259
  }
2404
260
  },
2405
261
  events: ["task.completed"]
2406
- });`;
2407
- }
2408
- function generateMessagingSpec(contracts) {
2409
- return `// Messaging App Specs
2410
- // Contracts: ${contracts.join(", ")}
262
+ });`}function u1($){return`// Messaging App Specs
263
+ // Contracts: ${$.join(", ")}
2411
264
 
2412
265
  contractSpec("messaging.send.v1", {
2413
266
  goal: "Deliver intent-rich updates",
@@ -2460,11 +313,8 @@ contractSpec("messaging.read.v1", {
2460
313
  }
2461
314
  },
2462
315
  events: ["message.read"]
2463
- });`;
2464
- }
2465
- function generateRecipeSpec(contracts) {
2466
- return `// Recipe App (i18n) Specs
2467
- // Contracts: ${contracts.join(", ")}
316
+ });`}function d1($){return`// Recipe App (i18n) Specs
317
+ // Contracts: ${$.join(", ")}
2468
318
 
2469
319
  contractSpec("recipes.lookup.v1", {
2470
320
  goal: "Serve bilingual rituals",
@@ -2511,13 +361,10 @@ contractSpec("recipes.favorite.toggle.v1", {
2511
361
  }
2512
362
  },
2513
363
  events: ["recipe.favorited", "recipe.unfavorited"]
2514
- });`;
2515
- }
2516
- function generateDefaultSpec(templateId) {
2517
- return `// ${templateId} Specs
364
+ });`}function n0($){return`// ${$} Specs
2518
365
 
2519
- contractSpec("${templateId}.main.v1", {
2520
- goal: "Main operation for ${templateId}",
366
+ contractSpec("${$}.main.v1", {
367
+ goal: "Main operation for ${$}",
2521
368
  transport: { gql: { query: "main" } },
2522
369
  io: {
2523
370
  input: {
@@ -2527,955 +374,38 @@ contractSpec("${templateId}.main.v1", {
2527
374
  result: "unknown"
2528
375
  }
2529
376
  }
2530
- });`;
2531
- }
2532
-
2533
- // src/hooks/useSpecContent.ts
2534
- import { useCallback as useCallback8, useEffect as useEffect4, useState as useState7 } from "react";
2535
- "use client";
2536
- var SPEC_STORAGE_KEY = "contractspec-spec-content";
2537
- function useSpecContent(templateId) {
2538
- const { template } = useTemplateRuntime();
2539
- const [content, setContentState] = useState7("");
2540
- const [savedContent, setSavedContent] = useState7("");
2541
- const [loading, setLoading] = useState7(true);
2542
- const [validation, setValidation] = useState7(null);
2543
- const [lastSaved, setLastSaved] = useState7(null);
2544
- useEffect4(() => {
2545
- setLoading(true);
2546
- try {
2547
- const stored = localStorage.getItem(`${SPEC_STORAGE_KEY}-${templateId}`);
2548
- if (stored) {
2549
- const parsed = JSON.parse(stored);
2550
- if (parsed.content) {
2551
- setContentState(parsed.content);
2552
- setSavedContent(parsed.content);
2553
- setLastSaved(parsed.savedAt);
2554
- } else {
2555
- const generated = generateSpecFromTemplate(template);
2556
- setContentState(generated);
2557
- setSavedContent(generated);
2558
- }
2559
- } else {
2560
- const generated = generateSpecFromTemplate(template);
2561
- setContentState(generated);
2562
- setSavedContent(generated);
2563
- }
2564
- } catch {
2565
- const generated = generateSpecFromTemplate(template);
2566
- setContentState(generated);
2567
- setSavedContent(generated);
2568
- }
2569
- setLoading(false);
2570
- }, [templateId]);
2571
- const setContent = useCallback8((newContent) => {
2572
- setContentState(newContent);
2573
- setValidation(null);
2574
- }, []);
2575
- const save = useCallback8(() => {
2576
- try {
2577
- const savedAt = new Date().toISOString();
2578
- localStorage.setItem(`${SPEC_STORAGE_KEY}-${templateId}`, JSON.stringify({
2579
- content,
2580
- savedAt
2581
- }));
2582
- setSavedContent(content);
2583
- setLastSaved(savedAt);
2584
- } catch {}
2585
- }, [content, templateId]);
2586
- const validate = useCallback8(() => {
2587
- const errors = [];
2588
- const lines = content.split(`
2589
- `);
2590
- if (!content.includes("contractSpec(")) {
2591
- errors.push({
2592
- line: 1,
2593
- message: "Spec must contain a contractSpec() definition",
2594
- severity: "error"
2595
- });
2596
- }
2597
- if (!content.includes("goal:")) {
2598
- errors.push({
2599
- line: 1,
2600
- message: "Spec should have a goal field",
2601
- severity: "warning"
2602
- });
2603
- }
2604
- if (!content.includes("io:")) {
2605
- errors.push({
2606
- line: 1,
2607
- message: "Spec should define io (input/output)",
2608
- severity: "warning"
2609
- });
2610
- }
2611
- const openBraces = (content.match(/{/g) ?? []).length;
2612
- const closeBraces = (content.match(/}/g) ?? []).length;
2613
- if (openBraces !== closeBraces) {
2614
- errors.push({
2615
- line: lines.length,
2616
- message: `Unbalanced braces: ${openBraces} opening, ${closeBraces} closing`,
2617
- severity: "error"
2618
- });
2619
- }
2620
- const openParens = (content.match(/\(/g) ?? []).length;
2621
- const closeParens = (content.match(/\)/g) ?? []).length;
2622
- if (openParens !== closeParens) {
2623
- errors.push({
2624
- line: lines.length,
2625
- message: `Unbalanced parentheses: ${openParens} opening, ${closeParens} closing`,
2626
- severity: "error"
2627
- });
2628
- }
2629
- lines.forEach((line, index) => {
2630
- const singleQuotes = (line.match(/'/g) ?? []).length;
2631
- const doubleQuotes = (line.match(/"/g) ?? []).length;
2632
- if (singleQuotes % 2 !== 0) {
2633
- errors.push({
2634
- line: index + 1,
2635
- message: "Unclosed single quote",
2636
- severity: "error"
2637
- });
2638
- }
2639
- if (doubleQuotes % 2 !== 0) {
2640
- errors.push({
2641
- line: index + 1,
2642
- message: "Unclosed double quote",
2643
- severity: "error"
2644
- });
2645
- }
2646
- });
2647
- const result = {
2648
- valid: errors.filter((e) => e.severity === "error").length === 0,
2649
- errors
2650
- };
2651
- setValidation(result);
2652
- return result;
2653
- }, [content]);
2654
- const reset = useCallback8(() => {
2655
- const generated = generateSpecFromTemplate(template);
2656
- setContentState(generated);
2657
- setSavedContent(generated);
2658
- setValidation(null);
2659
- setLastSaved(null);
2660
- try {
2661
- localStorage.removeItem(`${SPEC_STORAGE_KEY}-${templateId}`);
2662
- } catch {}
2663
- }, [templateId]);
2664
- return {
2665
- content,
2666
- loading,
2667
- isDirty: content !== savedContent,
2668
- validation,
2669
- setContent,
2670
- save,
2671
- validate,
2672
- reset,
2673
- lastSaved
2674
- };
2675
- }
2676
-
2677
- // src/SpecEditorPanel.tsx
2678
- import { Button as Button5, LoaderBlock as LoaderBlock3 } from "@contractspec/lib.design-system";
2679
- import { Badge as Badge5 } from "@contractspec/lib.ui-kit-web/ui/badge";
2680
- import { useCallback as useCallback9, useEffect as useEffect5 } from "react";
2681
- import { jsxDEV as jsxDEV9 } from "react/jsx-dev-runtime";
2682
- "use client";
2683
- function SpecEditorPanel({
2684
- templateId,
2685
- SpecEditor,
2686
- onLog
2687
- }) {
2688
- const {
2689
- content,
2690
- loading,
2691
- isDirty,
2692
- validation,
2693
- setContent,
2694
- save,
2695
- validate,
2696
- reset,
2697
- lastSaved
2698
- } = useSpecContent(templateId);
2699
- useEffect5(() => {
2700
- if (!loading && content) {
2701
- onLog?.(`Spec loaded for ${templateId}`);
2702
- }
2703
- }, [loading, content, templateId, onLog]);
2704
- const handleSave = useCallback9(() => {
2705
- save();
2706
- onLog?.("Spec saved locally");
2707
- }, [save, onLog]);
2708
- const handleValidate = useCallback9(() => {
2709
- const result = validate();
2710
- if (result.valid) {
2711
- onLog?.("Spec validation passed");
2712
- } else {
2713
- const errorCount = result.errors.filter((e) => e.severity === "error").length;
2714
- const warnCount = result.errors.filter((e) => e.severity === "warning").length;
2715
- onLog?.(`Spec validation: ${errorCount} errors, ${warnCount} warnings`);
2716
- }
2717
- }, [validate, onLog]);
2718
- const handleReset = useCallback9(() => {
2719
- reset();
2720
- onLog?.("Spec reset to template defaults");
2721
- }, [reset, onLog]);
2722
- if (loading) {
2723
- return /* @__PURE__ */ jsxDEV9(LoaderBlock3, {
2724
- label: "Loading spec..."
2725
- }, undefined, false, undefined, this);
2726
- }
2727
- return /* @__PURE__ */ jsxDEV9("div", {
2728
- className: "space-y-4",
2729
- children: [
2730
- /* @__PURE__ */ jsxDEV9("div", {
2731
- className: "flex items-center justify-between",
2732
- children: [
2733
- /* @__PURE__ */ jsxDEV9("div", {
2734
- className: "flex items-center gap-2",
2735
- children: [
2736
- /* @__PURE__ */ jsxDEV9(Button5, {
2737
- variant: "default",
2738
- size: "sm",
2739
- onClick: handleSave,
2740
- children: "Save"
2741
- }, undefined, false, undefined, this),
2742
- /* @__PURE__ */ jsxDEV9(Button5, {
2743
- variant: "outline",
2744
- size: "sm",
2745
- onClick: handleValidate,
2746
- children: "Validate"
2747
- }, undefined, false, undefined, this),
2748
- isDirty && /* @__PURE__ */ jsxDEV9(Badge5, {
2749
- variant: "secondary",
2750
- className: "border-amber-500/30 bg-amber-500/20 text-amber-400",
2751
- children: "Unsaved changes"
2752
- }, undefined, false, undefined, this),
2753
- validation && /* @__PURE__ */ jsxDEV9(Badge5, {
2754
- variant: validation.valid ? "default" : "destructive",
2755
- className: validation.valid ? "border-green-500/30 bg-green-500/20 text-green-400" : "",
2756
- children: validation.valid ? "Valid" : `${validation.errors.filter((e) => e.severity === "error").length} errors`
2757
- }, undefined, false, undefined, this)
2758
- ]
2759
- }, undefined, true, undefined, this),
2760
- /* @__PURE__ */ jsxDEV9("div", {
2761
- className: "flex items-center gap-2",
2762
- children: [
2763
- lastSaved && /* @__PURE__ */ jsxDEV9("span", {
2764
- className: "text-muted-foreground text-xs",
2765
- children: [
2766
- "Last saved: ",
2767
- new Date(lastSaved).toLocaleTimeString()
2768
- ]
2769
- }, undefined, true, undefined, this),
2770
- /* @__PURE__ */ jsxDEV9(Button5, {
2771
- variant: "ghost",
2772
- size: "sm",
2773
- onPress: handleReset,
2774
- children: "Reset"
2775
- }, undefined, false, undefined, this)
2776
- ]
2777
- }, undefined, true, undefined, this)
2778
- ]
2779
- }, undefined, true, undefined, this),
2780
- validation && validation.errors.length > 0 && /* @__PURE__ */ jsxDEV9("div", {
2781
- className: "rounded-lg border border-amber-500/50 bg-amber-500/10 p-3",
2782
- children: [
2783
- /* @__PURE__ */ jsxDEV9("p", {
2784
- className: "mb-2 font-semibold text-amber-400 text-xs uppercase",
2785
- children: "Validation Issues"
2786
- }, undefined, false, undefined, this),
2787
- /* @__PURE__ */ jsxDEV9("ul", {
2788
- className: "space-y-1",
2789
- children: validation.errors.map((error, index) => /* @__PURE__ */ jsxDEV9("li", {
2790
- className: `text-xs ${error.severity === "error" ? "text-red-400" : "text-amber-400"}`,
2791
- children: [
2792
- "Line ",
2793
- error.line,
2794
- ": ",
2795
- error.message
2796
- ]
2797
- }, `${error.line}-${error.message}-${index}`, true, undefined, this))
2798
- }, undefined, false, undefined, this)
2799
- ]
2800
- }, undefined, true, undefined, this),
2801
- /* @__PURE__ */ jsxDEV9("div", {
2802
- className: "rounded-2xl border border-border bg-card p-4",
2803
- children: /* @__PURE__ */ jsxDEV9(SpecEditor, {
2804
- projectId: "sandbox",
2805
- type: "CAPABILITY",
2806
- content,
2807
- onChange: setContent,
2808
- metadata: { template: templateId },
2809
- onSave: handleSave,
2810
- onValidate: handleValidate
2811
- }, undefined, false, undefined, this)
2812
- }, undefined, false, undefined, this)
2813
- ]
2814
- }, undefined, true, undefined, this);
2815
- }
2816
-
2817
- // src/TemplateShell.tsx
2818
- import { jsxDEV as jsxDEV10 } from "react/jsx-dev-runtime";
2819
- var TemplateShell = ({
2820
- title,
2821
- description,
2822
- sidebar,
2823
- actions,
2824
- showSaveAction = true,
2825
- saveProps,
2826
- children
2827
- }) => /* @__PURE__ */ jsxDEV10("div", {
2828
- className: "space-y-6",
2829
- children: [
2830
- /* @__PURE__ */ jsxDEV10("header", {
2831
- className: "rounded-2xl border border-border bg-card p-6 shadow-sm",
2832
- children: [
2833
- /* @__PURE__ */ jsxDEV10("div", {
2834
- className: "flex flex-wrap items-center justify-between gap-4",
2835
- children: [
2836
- /* @__PURE__ */ jsxDEV10("div", {
2837
- children: [
2838
- /* @__PURE__ */ jsxDEV10("p", {
2839
- className: "font-semibold text-muted-foreground text-sm uppercase tracking-wide",
2840
- children: "ContractSpec Templates"
2841
- }, undefined, false, undefined, this),
2842
- /* @__PURE__ */ jsxDEV10("h1", {
2843
- className: "font-bold text-3xl",
2844
- children: title
2845
- }, undefined, false, undefined, this),
2846
- description ? /* @__PURE__ */ jsxDEV10("p", {
2847
- className: "mt-2 max-w-2xl text-muted-foreground text-sm",
2848
- children: description
2849
- }, undefined, false, undefined, this) : null
2850
- ]
2851
- }, undefined, true, undefined, this),
2852
- /* @__PURE__ */ jsxDEV10("div", {
2853
- className: "flex flex-col items-end gap-2",
2854
- children: [
2855
- /* @__PURE__ */ jsxDEV10(LocalDataIndicator, {}, undefined, false, undefined, this),
2856
- showSaveAction ? /* @__PURE__ */ jsxDEV10(SaveToStudioButton, {
2857
- ...saveProps
2858
- }, undefined, false, undefined, this) : null
2859
- ]
2860
- }, undefined, true, undefined, this)
2861
- ]
2862
- }, undefined, true, undefined, this),
2863
- actions ? /* @__PURE__ */ jsxDEV10("div", {
2864
- className: "mt-4",
2865
- children: actions
2866
- }, undefined, false, undefined, this) : null
2867
- ]
2868
- }, undefined, true, undefined, this),
2869
- /* @__PURE__ */ jsxDEV10("div", {
2870
- className: sidebar ? "grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]" : "w-full",
2871
- children: [
2872
- /* @__PURE__ */ jsxDEV10("main", {
2873
- className: "space-y-4 p-2",
2874
- children
2875
- }, undefined, false, undefined, this),
2876
- sidebar ? /* @__PURE__ */ jsxDEV10("aside", {
2877
- className: "rounded-2xl border border-border bg-card p-4",
2878
- children: sidebar
2879
- }, undefined, false, undefined, this) : null
2880
- ]
2881
- }, undefined, true, undefined, this)
2882
- ]
2883
- }, undefined, true, undefined, this);
2884
-
2885
- // src/hooks/useRegistryTemplates.ts
2886
- import { useQuery } from "@tanstack/react-query";
2887
- function useRegistryTemplates() {
2888
- return useQuery({
2889
- queryKey: ["registryTemplates"],
2890
- queryFn: async () => {
2891
- const registryUrl = process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL ?? "";
2892
- if (!registryUrl)
2893
- return [];
2894
- const res = await fetch(`${registryUrl.replace(/\/$/, "")}/r/contractspec.json`, {
2895
- method: "GET",
2896
- headers: { Accept: "application/json" }
2897
- });
2898
- if (!res.ok)
2899
- return [];
2900
- const json = await res.json();
2901
- const items = json.items ?? [];
2902
- return items.filter((i) => i.type === "contractspec:template").map((i) => ({
2903
- id: i.name,
2904
- name: i.title ?? i.name,
2905
- description: i.description,
2906
- tags: i.meta?.tags ?? [],
2907
- source: "registry",
2908
- registryUrl
2909
- }));
2910
- }
2911
- });
2912
- }
2913
-
2914
- // src/hooks/useWorkflowComposer.ts
2915
- import { useCallback as useCallback10, useEffect as useEffect6, useMemo as useMemo7, useState as useState8 } from "react";
2916
- "use client";
2917
- function useWorkflowComposer(templateId) {
2918
- const [selectedWorkflow, setSelectedWorkflow] = useState8(null);
2919
- const [extensions, setExtensions] = useState8([]);
2920
- const [loading, _setLoading] = useState8(false);
2921
- const [error, _setError] = useState8(null);
2922
- const baseWorkflows = useMemo7(() => getTemplateWorkflows(templateId), [templateId]);
2923
- useEffect6(() => {
2924
- const firstWorkflow = baseWorkflows[0];
2925
- if (baseWorkflows.length > 0 && !selectedWorkflow && firstWorkflow) {
2926
- setSelectedWorkflow(firstWorkflow.meta.key);
2927
- }
2928
- }, [baseWorkflows, selectedWorkflow]);
2929
- const currentBase = useMemo7(() => {
2930
- return baseWorkflows.find((w) => w.meta.key === selectedWorkflow) ?? null;
2931
- }, [baseWorkflows, selectedWorkflow]);
2932
- const compose = useCallback10((scope) => {
2933
- if (!currentBase)
2934
- return null;
2935
- const applicableExtensions = extensions.filter((ext) => ext.workflow === currentBase.meta.key).filter((ext) => matchesScope(ext, scope)).sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
2936
- if (applicableExtensions.length === 0) {
2937
- return currentBase;
2938
- }
2939
- let composedWorkflow = { ...currentBase, steps: [...currentBase.steps] };
2940
- for (const extension of applicableExtensions) {
2941
- composedWorkflow = applyExtension(composedWorkflow, extension);
2942
- }
2943
- return composedWorkflow;
2944
- }, [currentBase, extensions]);
2945
- const workflow = useMemo7(() => compose(), [compose]);
2946
- const selectWorkflow = useCallback10((workflowName) => {
2947
- setSelectedWorkflow(workflowName);
2948
- }, []);
2949
- const addExtension = useCallback10((extension) => {
2950
- setExtensions((prev) => [...prev, extension]);
2951
- }, []);
2952
- const removeExtension = useCallback10((workflowName, index) => {
2953
- setExtensions((prev) => {
2954
- const forWorkflow = prev.filter((e) => e.workflow === workflowName);
2955
- const others = prev.filter((e) => e.workflow !== workflowName);
2956
- forWorkflow.splice(index, 1);
2957
- return [...others, ...forWorkflow];
2958
- });
2959
- }, []);
2960
- const generateSpecCode = useCallback10(() => {
2961
- const composed = workflow;
2962
- if (!composed) {
2963
- return "// No workflow selected";
2964
- }
2965
- const stepsCode = composed.steps.map((step) => ` {
2966
- id: '${step.id}',
2967
- name: '${step.name}',
2968
- type: '${step.type}',${step.description ? `
2969
- description: '${step.description}',` : ""}${step.next ? `
2970
- next: ${JSON.stringify(step.next)},` : ""}${step.condition ? `
2971
- condition: '${step.condition}',` : ""}${step.timeout ? `
2972
- timeout: ${step.timeout},` : ""}${step.retries ? `
2973
- retries: ${step.retries},` : ""}${step.onError ? `
2974
- 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}',`:""}
2975
388
  }`).join(`,
2976
- `);
2977
- const extensionsCode = extensions.length > 0 ? `
389
+ `),L=J.length>0?`
2978
390
 
2979
391
  // Extensions applied:
2980
- ${extensions.map((ext) => `// - ${ext.workflow} (priority: ${ext.priority ?? 0})${ext.customSteps?.length ? ` +${ext.customSteps.length} steps` : ""}${ext.hiddenSteps?.length ? ` -${ext.hiddenSteps.length} hidden` : ""}`).join(`
2981
- `)}` : "";
2982
- return `// Workflow Spec: ${composed.meta.key} v${composed.meta.version}
2983
- // Generated from ${templateId} template
2984
- ${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}
2985
396
 
2986
397
  import { workflowSpec } from '@contractspec/lib.contracts-spec/workflow';
2987
398
 
2988
- export const ${toCamelCase(composed.meta.key)}Workflow = workflowSpec({
399
+ export const ${e1(Z.meta.key)}Workflow = workflowSpec({
2989
400
  meta: {
2990
- key: '${composed.meta.key}',
2991
- version: ${composed.meta.version},${composed.meta.description ? `
2992
- description: '${composed.meta.description}',` : ""}
401
+ key: '${Z.meta.key}',
402
+ version: ${Z.meta.version},${Z.meta.description?`
403
+ description: '${Z.meta.description}',`:""}
2993
404
  },
2994
- start: '${composed.start}',
405
+ start: '${Z.start}',
2995
406
  steps: [
2996
- ${stepsCode}
2997
- ],${composed.context ? `
2998
- context: ${JSON.stringify(composed.context, null, 2)},` : ""}
407
+ ${A}
408
+ ],${Z.context?`
409
+ context: ${JSON.stringify(Z.context,null,2)},`:""}
2999
410
  });
3000
- `;
3001
- }, [workflow, extensions, templateId]);
3002
- return {
3003
- workflow,
3004
- baseWorkflows,
3005
- extensions,
3006
- selectWorkflow,
3007
- addExtension,
3008
- removeExtension,
3009
- compose,
3010
- generateSpecCode,
3011
- loading,
3012
- error
3013
- };
3014
- }
3015
- function matchesScope(extension, scope) {
3016
- if (!scope)
3017
- return true;
3018
- if (extension.tenantId && extension.tenantId !== scope.tenantId) {
3019
- return false;
3020
- }
3021
- if (extension.role && extension.role !== scope.role) {
3022
- return false;
3023
- }
3024
- if (extension.device && extension.device !== scope.device) {
3025
- return false;
3026
- }
3027
- return true;
3028
- }
3029
- function applyExtension(workflow, extension) {
3030
- let steps = [...workflow.steps];
3031
- if (extension.hiddenSteps) {
3032
- steps = steps.filter((s) => !extension.hiddenSteps?.includes(s.id));
3033
- }
3034
- if (extension.customSteps) {
3035
- for (const injection of extension.customSteps) {
3036
- const stepToInject = {
3037
- ...injection.inject,
3038
- id: injection.id ?? injection.inject.id
3039
- };
3040
- if (injection.after) {
3041
- const afterIndex = steps.findIndex((s) => s.id === injection.after);
3042
- if (afterIndex !== -1) {
3043
- steps.splice(afterIndex + 1, 0, stepToInject);
3044
- }
3045
- } else if (injection.before) {
3046
- const beforeIndex = steps.findIndex((s) => s.id === injection.before);
3047
- if (beforeIndex !== -1) {
3048
- steps.splice(beforeIndex, 0, stepToInject);
3049
- }
3050
- } else {
3051
- steps.push(stepToInject);
3052
- }
3053
- }
3054
- }
3055
- return { ...workflow, steps };
3056
- }
3057
- function toCamelCase(str) {
3058
- return str.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toLowerCase());
3059
- }
3060
- function getTemplateWorkflows(templateId) {
3061
- const templateWorkflows = {
3062
- "crm-pipeline": [
3063
- {
3064
- meta: {
3065
- key: "deal.qualification",
3066
- version: "1.0.0",
3067
- description: "Deal qualification workflow"
3068
- },
3069
- start: "lead-received",
3070
- steps: [
3071
- {
3072
- id: "lead-received",
3073
- name: "Lead Received",
3074
- type: "action",
3075
- description: "New lead enters the pipeline",
3076
- next: "qualify-lead"
3077
- },
3078
- {
3079
- id: "qualify-lead",
3080
- name: "Qualify Lead",
3081
- type: "decision",
3082
- description: "Determine if lead meets qualification criteria",
3083
- next: ["qualified", "disqualified"],
3084
- condition: "lead.score >= threshold"
3085
- },
3086
- {
3087
- id: "qualified",
3088
- name: "Lead Qualified",
3089
- type: "action",
3090
- next: "assign-rep"
3091
- },
3092
- {
3093
- id: "disqualified",
3094
- name: "Lead Disqualified",
3095
- type: "end"
3096
- },
3097
- {
3098
- id: "assign-rep",
3099
- name: "Assign Sales Rep",
3100
- type: "action",
3101
- next: "complete"
3102
- },
3103
- {
3104
- id: "complete",
3105
- name: "Workflow Complete",
3106
- type: "end"
3107
- }
3108
- ]
3109
- },
3110
- {
3111
- meta: {
3112
- key: "deal.closing",
3113
- version: "1.0.0",
3114
- description: "Deal closing workflow"
3115
- },
3116
- start: "proposal-sent",
3117
- steps: [
3118
- {
3119
- id: "proposal-sent",
3120
- name: "Proposal Sent",
3121
- type: "action",
3122
- next: "wait-response"
3123
- },
3124
- {
3125
- id: "wait-response",
3126
- name: "Wait for Response",
3127
- type: "wait",
3128
- timeout: 604800000,
3129
- next: "negotiate",
3130
- onError: "follow-up"
3131
- },
3132
- {
3133
- id: "follow-up",
3134
- name: "Follow Up",
3135
- type: "action",
3136
- next: "wait-response",
3137
- retries: 3
3138
- },
3139
- {
3140
- id: "negotiate",
3141
- name: "Negotiation",
3142
- type: "action",
3143
- next: "finalize"
3144
- },
3145
- {
3146
- id: "finalize",
3147
- name: "Finalize Deal",
3148
- type: "decision",
3149
- next: ["won", "lost"],
3150
- condition: "deal.accepted"
3151
- },
3152
- {
3153
- id: "won",
3154
- name: "Deal Won",
3155
- type: "end"
3156
- },
3157
- {
3158
- id: "lost",
3159
- name: "Deal Lost",
3160
- type: "end"
3161
- }
3162
- ]
3163
- }
3164
- ],
3165
- "saas-boilerplate": [
3166
- {
3167
- meta: {
3168
- key: "user.onboarding",
3169
- version: "1.0.0",
3170
- description: "User onboarding workflow"
3171
- },
3172
- start: "signup",
3173
- steps: [
3174
- {
3175
- id: "signup",
3176
- name: "User Signup",
3177
- type: "action",
3178
- next: "verify-email"
3179
- },
3180
- {
3181
- id: "verify-email",
3182
- name: "Verify Email",
3183
- type: "wait",
3184
- timeout: 86400000,
3185
- next: "profile-setup",
3186
- onError: "resend-verification"
3187
- },
3188
- {
3189
- id: "resend-verification",
3190
- name: "Resend Verification",
3191
- type: "action",
3192
- next: "verify-email",
3193
- retries: 2
3194
- },
3195
- {
3196
- id: "profile-setup",
3197
- name: "Setup Profile",
3198
- type: "action",
3199
- next: "onboarding-tour"
3200
- },
3201
- {
3202
- id: "onboarding-tour",
3203
- name: "Onboarding Tour",
3204
- type: "action",
3205
- next: "complete"
3206
- },
3207
- {
3208
- id: "complete",
3209
- name: "Onboarding Complete",
3210
- type: "end"
3211
- }
3212
- ]
3213
- }
3214
- ],
3215
- "agent-console": [
3216
- {
3217
- meta: {
3218
- key: "agent.execution",
3219
- version: "1.0.0",
3220
- description: "Agent execution workflow"
3221
- },
3222
- start: "receive-task",
3223
- steps: [
3224
- {
3225
- id: "receive-task",
3226
- name: "Receive Task",
3227
- type: "action",
3228
- next: "plan-execution"
3229
- },
3230
- {
3231
- id: "plan-execution",
3232
- name: "Plan Execution",
3233
- type: "action",
3234
- next: "execute-steps"
3235
- },
3236
- {
3237
- id: "execute-steps",
3238
- name: "Execute Steps",
3239
- type: "parallel",
3240
- next: ["tool-call", "observe", "reason"]
3241
- },
3242
- {
3243
- id: "tool-call",
3244
- name: "Tool Call",
3245
- type: "action",
3246
- next: "evaluate"
3247
- },
3248
- {
3249
- id: "observe",
3250
- name: "Observe",
3251
- type: "action",
3252
- next: "evaluate"
3253
- },
3254
- {
3255
- id: "reason",
3256
- name: "Reason",
3257
- type: "action",
3258
- next: "evaluate"
3259
- },
3260
- {
3261
- id: "evaluate",
3262
- name: "Evaluate Result",
3263
- type: "decision",
3264
- condition: "task.isComplete",
3265
- next: ["complete", "execute-steps"]
3266
- },
3267
- {
3268
- id: "complete",
3269
- name: "Task Complete",
3270
- type: "end"
3271
- }
3272
- ]
3273
- }
3274
- ],
3275
- "todos-app": [
3276
- {
3277
- meta: {
3278
- key: "task.lifecycle",
3279
- version: "1.0.0",
3280
- description: "Task lifecycle workflow"
3281
- },
3282
- start: "created",
3283
- steps: [
3284
- {
3285
- id: "created",
3286
- name: "Task Created",
3287
- type: "action",
3288
- next: "in-progress"
3289
- },
3290
- {
3291
- id: "in-progress",
3292
- name: "In Progress",
3293
- type: "action",
3294
- next: "review"
3295
- },
3296
- {
3297
- id: "review",
3298
- name: "Review",
3299
- type: "decision",
3300
- condition: "task.approved",
3301
- next: ["done", "in-progress"]
3302
- },
3303
- {
3304
- id: "done",
3305
- name: "Done",
3306
- type: "end"
3307
- }
3308
- ]
3309
- }
3310
- ],
3311
- "messaging-app": [
3312
- {
3313
- meta: {
3314
- key: "message.delivery",
3315
- version: "1.0.0",
3316
- description: "Message delivery workflow"
3317
- },
3318
- start: "compose",
3319
- steps: [
3320
- {
3321
- id: "compose",
3322
- name: "Compose Message",
3323
- type: "action",
3324
- next: "send"
3325
- },
3326
- {
3327
- id: "send",
3328
- name: "Send Message",
3329
- type: "action",
3330
- next: "deliver"
3331
- },
3332
- {
3333
- id: "deliver",
3334
- name: "Deliver",
3335
- type: "decision",
3336
- condition: "recipient.online",
3337
- next: ["delivered", "queue"]
3338
- },
3339
- {
3340
- id: "queue",
3341
- name: "Queue for Delivery",
3342
- type: "wait",
3343
- next: "deliver"
3344
- },
3345
- {
3346
- id: "delivered",
3347
- name: "Message Delivered",
3348
- type: "action",
3349
- next: "read"
3350
- },
3351
- {
3352
- id: "read",
3353
- name: "Message Read",
3354
- type: "end"
3355
- }
3356
- ]
3357
- }
3358
- ],
3359
- "recipe-app-i18n": [
3360
- {
3361
- meta: {
3362
- key: "recipe.creation",
3363
- version: "1.0.0",
3364
- description: "Recipe creation workflow"
3365
- },
3366
- start: "draft",
3367
- steps: [
3368
- {
3369
- id: "draft",
3370
- name: "Draft Recipe",
3371
- type: "action",
3372
- next: "add-ingredients"
3373
- },
3374
- {
3375
- id: "add-ingredients",
3376
- name: "Add Ingredients",
3377
- type: "action",
3378
- next: "add-steps"
3379
- },
3380
- {
3381
- id: "add-steps",
3382
- name: "Add Steps",
3383
- type: "action",
3384
- next: "review"
3385
- },
3386
- {
3387
- id: "review",
3388
- name: "Review Recipe",
3389
- type: "decision",
3390
- condition: "recipe.isComplete",
3391
- next: ["publish", "draft"]
3392
- },
3393
- {
3394
- id: "publish",
3395
- name: "Publish Recipe",
3396
- type: "end"
3397
- }
3398
- ]
3399
- }
3400
- ]
3401
- };
3402
- return templateWorkflows[templateId] ?? [];
3403
- }
3404
- // src/lib/component-registry.tsx
3405
- import { useEffect as useEffect7, useState as useState9 } from "react";
3406
- "use client";
3407
-
3408
- class TemplateComponentRegistry {
3409
- components = new Map;
3410
- listeners = new Set;
3411
- register(templateId, registration) {
3412
- this.components.set(templateId, registration);
3413
- this.listeners.forEach((l) => l(templateId));
3414
- }
3415
- get(templateId) {
3416
- return this.components.get(templateId);
3417
- }
3418
- subscribe(listener) {
3419
- this.listeners.add(listener);
3420
- return () => {
3421
- this.listeners.delete(listener);
3422
- };
3423
- }
3424
- }
3425
- var templateComponentRegistry = new TemplateComponentRegistry;
3426
- function registerTemplateComponents(templateId, components) {
3427
- templateComponentRegistry.register(templateId, components);
3428
- }
3429
- function useTemplateComponents(templateId) {
3430
- const [components, setComponents] = useState9(() => templateComponentRegistry.get(templateId));
3431
- useEffect7(() => {
3432
- return templateComponentRegistry.subscribe((updatedId) => {
3433
- if (updatedId === templateId) {
3434
- setComponents(templateComponentRegistry.get(templateId));
3435
- }
3436
- });
3437
- }, [templateId]);
3438
- return components;
3439
- }
3440
- // src/utils/fetchPresentationData.ts
3441
- async function fetchPresentationData(_presentationName, _templateId) {
3442
- throw new Error("fetchPresentationData is deprecated. Use fetchData from TemplateRuntimeContext.");
3443
- }
3444
- function hasPresentationDataFetcher(_presentationName) {
3445
- return false;
3446
- }
3447
- function getRegisteredPresentationFetchers() {
3448
- return [];
3449
- }
3450
- // src/index.ts
3451
- import { MarkdownRenderer as MarkdownRenderer2 } from "@contractspec/lib.design-system";
3452
- export {
3453
- useWorkflowComposer,
3454
- useTemplateRuntime,
3455
- useTemplateComponents,
3456
- useSpecContent,
3457
- useRegistryTemplates,
3458
- useOverlayContext,
3459
- useIsInOverlayContext,
3460
- useEvolution,
3461
- useBehaviorTracking,
3462
- templateComponentRegistry,
3463
- registerTemplateComponents,
3464
- hasPresentationDataFetcher,
3465
- getRegisteredPresentationFetchers,
3466
- generateSpecFromTemplate,
3467
- fetchPresentationData,
3468
- TemplateShell,
3469
- TemplateRuntimeContext,
3470
- TemplateComponentRegistry,
3471
- SpecEditorPanel,
3472
- SpecDrivenTemplateShell,
3473
- SaveToStudioButton,
3474
- PersonalizationInsights,
3475
- OverlayContextProvider,
3476
- MarkdownView,
3477
- MarkdownRenderer2 as MarkdownRenderer,
3478
- LocalDataIndicator,
3479
- EvolutionSidebar,
3480
- EvolutionDashboard
3481
- };
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};