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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/.turbo/turbo-build.log +81 -81
  2. package/CHANGELOG.md +28 -0
  3. package/dist/EvolutionDashboard.js +1 -803
  4. package/dist/EvolutionSidebar.js +1 -531
  5. package/dist/LocalDataIndicator.js +1 -68
  6. package/dist/MarkdownView.js +1 -213
  7. package/dist/OverlayContextProvider.js +1 -202
  8. package/dist/PersonalizationInsights.js +1 -455
  9. package/dist/SaveToStudioButton.js +1 -79
  10. package/dist/SpecDrivenTemplateShell.js +1 -203
  11. package/dist/SpecEditorPanel.js +17 -364
  12. package/dist/TemplateShell.js +1 -195
  13. package/dist/browser/EvolutionDashboard.js +1 -803
  14. package/dist/browser/EvolutionSidebar.js +1 -531
  15. package/dist/browser/LocalDataIndicator.js +1 -68
  16. package/dist/browser/MarkdownView.js +1 -213
  17. package/dist/browser/OverlayContextProvider.js +1 -202
  18. package/dist/browser/PersonalizationInsights.js +1 -455
  19. package/dist/browser/SaveToStudioButton.js +1 -79
  20. package/dist/browser/SpecDrivenTemplateShell.js +1 -203
  21. package/dist/browser/SpecEditorPanel.js +17 -364
  22. package/dist/browser/TemplateShell.js +1 -195
  23. package/dist/browser/bundles/ExampleTemplateBundle.js +1 -85
  24. package/dist/browser/bundles/index.js +1 -85
  25. package/dist/browser/hooks/index.js +40 -1151
  26. package/dist/browser/hooks/useBehaviorTracking.js +1 -157
  27. package/dist/browser/hooks/useEvolution.js +1 -260
  28. package/dist/browser/hooks/useRegistryTemplates.js +1 -31
  29. package/dist/browser/hooks/useSpecContent.js +17 -224
  30. package/dist/browser/hooks/useWorkflowComposer.js +24 -483
  31. package/dist/browser/index.js +40 -3122
  32. package/dist/browser/lib/component-registry.js +1 -48
  33. package/dist/browser/lib/runtime-context.js +1 -21
  34. package/dist/browser/markdown/formatPresentationName.js +1 -9
  35. package/dist/browser/markdown/useMarkdownPresentation.js +1 -65
  36. package/dist/browser/utils/fetchPresentationData.js +1 -15
  37. package/dist/browser/utils/generateSpecFromTemplate.js +16 -62
  38. package/dist/browser/utils/index.js +16 -76
  39. package/dist/bundles/ExampleTemplateBundle.js +1 -85
  40. package/dist/bundles/index.js +1 -85
  41. package/dist/hooks/index.js +40 -1151
  42. package/dist/hooks/useBehaviorTracking.js +1 -157
  43. package/dist/hooks/useEvolution.js +1 -260
  44. package/dist/hooks/useRegistryTemplates.js +1 -31
  45. package/dist/hooks/useSpecContent.js +17 -224
  46. package/dist/hooks/useWorkflowComposer.js +24 -483
  47. package/dist/index.js +40 -3122
  48. package/dist/lib/component-registry.js +1 -48
  49. package/dist/lib/runtime-context.js +1 -21
  50. package/dist/markdown/formatPresentationName.js +1 -9
  51. package/dist/markdown/useMarkdownPresentation.js +1 -65
  52. package/dist/node/EvolutionDashboard.js +1 -803
  53. package/dist/node/EvolutionSidebar.js +1 -531
  54. package/dist/node/LocalDataIndicator.js +1 -68
  55. package/dist/node/MarkdownView.js +1 -213
  56. package/dist/node/OverlayContextProvider.js +1 -202
  57. package/dist/node/PersonalizationInsights.js +1 -455
  58. package/dist/node/SaveToStudioButton.js +1 -79
  59. package/dist/node/SpecDrivenTemplateShell.js +1 -203
  60. package/dist/node/SpecEditorPanel.js +17 -364
  61. package/dist/node/TemplateShell.js +1 -195
  62. package/dist/node/bundles/ExampleTemplateBundle.js +1 -85
  63. package/dist/node/bundles/index.js +1 -85
  64. package/dist/node/hooks/index.js +40 -1151
  65. package/dist/node/hooks/useBehaviorTracking.js +1 -157
  66. package/dist/node/hooks/useEvolution.js +1 -260
  67. package/dist/node/hooks/useRegistryTemplates.js +1 -31
  68. package/dist/node/hooks/useSpecContent.js +17 -224
  69. package/dist/node/hooks/useWorkflowComposer.js +24 -483
  70. package/dist/node/index.js +40 -3122
  71. package/dist/node/lib/component-registry.js +1 -48
  72. package/dist/node/lib/runtime-context.js +1 -21
  73. package/dist/node/markdown/formatPresentationName.js +1 -9
  74. package/dist/node/markdown/useMarkdownPresentation.js +1 -65
  75. package/dist/node/utils/fetchPresentationData.js +1 -15
  76. package/dist/node/utils/generateSpecFromTemplate.js +16 -62
  77. package/dist/node/utils/index.js +16 -76
  78. package/dist/utils/fetchPresentationData.js +1 -15
  79. package/dist/utils/generateSpecFromTemplate.js +16 -62
  80. package/dist/utils/index.js +16 -76
  81. package/package.json +13 -13
  82. package/src/lib/component-registry.tsx +2 -1
  83. package/src/lib/runtime-context.tsx +1 -1
  84. package/src/lib/singletons.test.ts +19 -22
@@ -1,461 +1,6 @@
1
1
  // @bun
2
- // src/hooks/useEvolution.ts
3
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
- "use client";
5
- var EVOLUTION_STORAGE_KEY = "contractspec-evolution-data";
6
- function useEvolution(templateId) {
7
- const [usageStats, setUsageStats] = useState([]);
8
- const [anomalies, setAnomalies] = useState([]);
9
- const [suggestions, setSuggestions] = useState([]);
10
- const [hints, setHints] = useState([]);
11
- const [loading, setLoading] = useState(false);
12
- const metricsRef = useRef([]);
13
- const [operationCount, setOperationCount] = useState(0);
14
- useEffect(() => {
15
- try {
16
- const stored = localStorage.getItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
17
- if (stored) {
18
- const data = JSON.parse(stored);
19
- setSuggestions(data.suggestions.map((s) => ({
20
- ...s,
21
- createdAt: new Date(s.createdAt)
22
- })));
23
- }
24
- } catch {}
25
- }, [templateId]);
26
- useEffect(() => {
27
- try {
28
- localStorage.setItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`, JSON.stringify({ suggestions }));
29
- } catch {}
30
- }, [suggestions, templateId]);
31
- const trackOperation = useCallback((operationName, durationMs, success, errorCode) => {
32
- const sample = {
33
- operation: {
34
- name: operationName,
35
- version: "1.0.0",
36
- tenantId: "sandbox"
37
- },
38
- durationMs,
39
- success,
40
- timestamp: new Date,
41
- errorCode
42
- };
43
- metricsRef.current.push(sample);
44
- setOperationCount((prev) => prev + 1);
45
- }, []);
46
- const analyzeUsage = useCallback(() => {
47
- const samples = metricsRef.current;
48
- if (samples.length < 5)
49
- return;
50
- const groups = new Map;
51
- for (const sample of samples) {
52
- const key = `${sample.operation.name}.v${sample.operation.version}`;
53
- const arr = groups.get(key) ?? [];
54
- arr.push(sample);
55
- groups.set(key, arr);
56
- }
57
- const stats = [];
58
- const detectedAnomalies = [];
59
- groups.forEach((opSamples) => {
60
- if (opSamples.length < 3)
61
- return;
62
- const durations = opSamples.map((s) => s.durationMs).sort((a, b) => a - b);
63
- const errors = opSamples.filter((s) => !s.success);
64
- const totalCalls = opSamples.length;
65
- const errorRate = errors.length / totalCalls;
66
- const averageLatencyMs = durations.reduce((sum, value) => sum + value, 0) / totalCalls;
67
- const timestamps = opSamples.map((s) => s.timestamp.getTime());
68
- const firstSample = opSamples[0];
69
- if (!firstSample)
70
- return;
71
- const stat = {
72
- operation: firstSample.operation,
73
- totalCalls,
74
- successRate: 1 - errorRate,
75
- errorRate,
76
- averageLatencyMs,
77
- p95LatencyMs: percentile(durations, 0.95),
78
- p99LatencyMs: percentile(durations, 0.99),
79
- maxLatencyMs: Math.max(...durations),
80
- lastSeenAt: new Date(Math.max(...timestamps)),
81
- windowStart: new Date(Math.min(...timestamps)),
82
- windowEnd: new Date(Math.max(...timestamps)),
83
- topErrors: errors.reduce((acc, s) => {
84
- if (s.errorCode) {
85
- acc[s.errorCode] = (acc[s.errorCode] ?? 0) + 1;
86
- }
87
- return acc;
88
- }, {})
89
- };
90
- stats.push(stat);
91
- if (errorRate > 0.1) {
92
- detectedAnomalies.push({
93
- operation: stat.operation,
94
- severity: errorRate > 0.3 ? "high" : errorRate > 0.2 ? "medium" : "low",
95
- metric: "error-rate",
96
- description: `Error rate ${(errorRate * 100).toFixed(1)}% exceeds threshold`,
97
- detectedAt: new Date,
98
- threshold: 0.1,
99
- observedValue: errorRate
100
- });
101
- }
102
- if (stat.p99LatencyMs > 500) {
103
- detectedAnomalies.push({
104
- operation: stat.operation,
105
- severity: stat.p99LatencyMs > 1000 ? "high" : stat.p99LatencyMs > 750 ? "medium" : "low",
106
- metric: "latency",
107
- description: `P99 latency ${stat.p99LatencyMs.toFixed(0)}ms exceeds threshold`,
108
- detectedAt: new Date,
109
- threshold: 500,
110
- observedValue: stat.p99LatencyMs
111
- });
112
- }
113
- });
114
- setUsageStats(stats);
115
- setAnomalies(detectedAnomalies);
116
- const newHints = detectedAnomalies.map((anomaly) => ({
117
- operation: anomaly.operation,
118
- category: anomaly.metric === "latency" ? "performance" : "error-handling",
119
- summary: anomaly.metric === "latency" ? "Latency regression detected" : "Error spike detected",
120
- justification: anomaly.description,
121
- recommendedActions: anomaly.metric === "latency" ? [
122
- "Add caching layer",
123
- "Optimize database queries",
124
- "Consider pagination"
125
- ] : [
126
- "Add retry logic",
127
- "Improve error handling",
128
- "Add circuit breaker"
129
- ]
130
- }));
131
- setHints(newHints);
132
- }, []);
133
- const generateSuggestions = useCallback(async () => {
134
- if (anomalies.length === 0)
135
- return;
136
- setLoading(true);
137
- await new Promise((resolve) => setTimeout(resolve, 800));
138
- const newSuggestions = anomalies.map((anomaly) => ({
139
- id: `suggestion-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
140
- intent: {
141
- id: `intent-${anomaly.operation.name}`,
142
- type: anomaly.metric === "latency" ? "latency-regression" : anomaly.metric === "error-rate" ? "error-spike" : "throughput-drop",
143
- description: anomaly.description,
144
- operation: anomaly.operation,
145
- confidence: {
146
- score: anomaly.severity === "high" ? 0.9 : anomaly.severity === "medium" ? 0.7 : 0.5,
147
- sampleSize: usageStats.find((s) => s.operation.name === anomaly.operation.name)?.totalCalls ?? 0
148
- }
149
- },
150
- target: anomaly.operation,
151
- proposal: {
152
- summary: generateSuggestionSummary(anomaly),
153
- rationale: generateSuggestionRationale(anomaly),
154
- changeType: anomaly.metric === "error-rate" ? "policy-update" : "revision",
155
- recommendedActions: generateRecommendedActions(anomaly)
156
- },
157
- confidence: anomaly.severity === "high" ? 0.85 : anomaly.severity === "medium" ? 0.7 : 0.55,
158
- createdAt: new Date,
159
- createdBy: "ai-evolution-agent",
160
- status: "pending",
161
- priority: anomaly.severity
162
- }));
163
- setSuggestions((prev) => [...prev, ...newSuggestions]);
164
- setLoading(false);
165
- }, [anomalies, usageStats]);
166
- const approveSuggestion = useCallback((id, _notes) => {
167
- setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "approved" } : s));
168
- }, []);
169
- const rejectSuggestion = useCallback((id, _notes) => {
170
- setSuggestions((prev) => prev.map((s) => s.id === id ? { ...s, status: "rejected" } : s));
171
- }, []);
172
- const clear = useCallback(() => {
173
- metricsRef.current = [];
174
- setOperationCount(0);
175
- setUsageStats([]);
176
- setAnomalies([]);
177
- setSuggestions([]);
178
- setHints([]);
179
- localStorage.removeItem(`${EVOLUTION_STORAGE_KEY}-${templateId}`);
180
- }, [templateId]);
181
- return useMemo(() => ({
182
- usageStats,
183
- anomalies,
184
- suggestions,
185
- hints,
186
- loading,
187
- trackOperation,
188
- analyzeUsage,
189
- generateSuggestions,
190
- approveSuggestion,
191
- rejectSuggestion,
192
- clear,
193
- operationCount
194
- }), [
195
- usageStats,
196
- anomalies,
197
- suggestions,
198
- hints,
199
- loading,
200
- trackOperation,
201
- analyzeUsage,
202
- generateSuggestions,
203
- approveSuggestion,
204
- rejectSuggestion,
205
- clear,
206
- operationCount
207
- ]);
208
- }
209
- function percentile(values, p) {
210
- if (!values.length)
211
- return 0;
212
- if (values.length === 1)
213
- return values[0] ?? 0;
214
- const idx = Math.min(values.length - 1, Math.floor(p * values.length));
215
- return values[idx] ?? 0;
216
- }
217
- function generateSuggestionSummary(anomaly) {
218
- if (anomaly.metric === "latency") {
219
- return `Add caching and pagination to ${anomaly.operation.name} to reduce latency`;
220
- }
221
- if (anomaly.metric === "error-rate") {
222
- return `Add retry policy and circuit breaker to ${anomaly.operation.name}`;
223
- }
224
- return `Optimize ${anomaly.operation.name} for improved throughput`;
225
- }
226
- function generateSuggestionRationale(anomaly) {
227
- if (anomaly.metric === "latency") {
228
- 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.`;
229
- }
230
- if (anomaly.metric === "error-rate") {
231
- 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.`;
232
- }
233
- return `Throughput for ${anomaly.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`;
234
- }
235
- function generateRecommendedActions(anomaly) {
236
- if (anomaly.metric === "latency") {
237
- return [
238
- "Add response caching for frequently accessed data",
239
- "Implement pagination for large result sets",
240
- "Optimize database queries with proper indexing",
241
- "Consider adding a GraphQL DataLoader for batching"
242
- ];
243
- }
244
- if (anomaly.metric === "error-rate") {
245
- return [
246
- "Add input validation at the contract level",
247
- "Implement retry policy with exponential backoff",
248
- "Add circuit breaker for external dependencies",
249
- "Enhance error logging for better debugging"
250
- ];
251
- }
252
- return [
253
- "Review resource allocation and scaling policies",
254
- "Check for upstream routing or load balancer issues",
255
- "Validate feature flag configurations",
256
- "Monitor dependency health metrics"
257
- ];
258
- }
259
-
260
- // src/lib/runtime-context.tsx
261
- import { createContext, useContext } from "react";
262
- "use client";
263
- var TEMPLATE_RUNTIME_CONTEXT_KEY = Symbol.for("@contractspec/lib.example-shared-ui/template-runtime-context");
264
- function getTemplateRuntimeContextSingleton() {
265
- const store = globalThis;
266
- store[TEMPLATE_RUNTIME_CONTEXT_KEY] ??= createContext(null);
267
- return store[TEMPLATE_RUNTIME_CONTEXT_KEY];
268
- }
269
- var TemplateRuntimeContext = getTemplateRuntimeContextSingleton();
270
- function useTemplateRuntime() {
271
- const context = useContext(TemplateRuntimeContext);
272
- if (!context) {
273
- throw new Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");
274
- }
275
- return context;
276
- }
277
-
278
- // src/hooks/useBehaviorTracking.ts
279
- import { useCallback as useCallback2, useEffect as useEffect2, useMemo as useMemo2, useRef as useRef2, useState as useState2 } from "react";
280
- "use client";
281
- var BEHAVIOR_STORAGE_KEY = "contractspec-behavior-data";
282
- var ALL_FEATURES = [
283
- "playground",
284
- "specs",
285
- "builder",
286
- "markdown",
287
- "evolution",
288
- "canvas_add",
289
- "canvas_delete",
290
- "spec_save",
291
- "spec_validate",
292
- "ai_suggestions"
293
- ];
294
- function useBehaviorTracking(templateId) {
295
- const [events, setEvents] = useState2([]);
296
- const sessionStartRef = useRef2(new Date);
297
- const [eventCount, setEventCount] = useState2(0);
298
- useEffect2(() => {
299
- try {
300
- const stored = localStorage.getItem(BEHAVIOR_STORAGE_KEY);
301
- if (stored) {
302
- const data = JSON.parse(stored);
303
- setEvents(data.events.map((e) => ({
304
- ...e,
305
- timestamp: new Date(e.timestamp)
306
- })));
307
- sessionStartRef.current = new Date(data.sessionStart);
308
- }
309
- } catch {}
310
- }, []);
311
- useEffect2(() => {
312
- if (events.length > 0) {
313
- try {
314
- localStorage.setItem(BEHAVIOR_STORAGE_KEY, JSON.stringify({
315
- events: events.map((e) => ({
316
- ...e,
317
- timestamp: e.timestamp.toISOString()
318
- })),
319
- sessionStart: sessionStartRef.current.toISOString()
320
- }));
321
- } catch {}
322
- }
323
- }, [events]);
324
- const trackEvent = useCallback2((type, metadata) => {
325
- const event = {
326
- type,
327
- timestamp: new Date,
328
- templateId,
329
- metadata
330
- };
331
- setEvents((prev) => [...prev, event]);
332
- setEventCount((prev) => prev + 1);
333
- }, [templateId]);
334
- const getEventsByType = useCallback2((type) => {
335
- return events.filter((e) => e.type === type);
336
- }, [events]);
337
- const getSummary = useCallback2(() => {
338
- const now = new Date;
339
- const sessionDuration = now.getTime() - sessionStartRef.current.getTime();
340
- const templateCounts = new Map;
341
- for (const event of events) {
342
- const count = templateCounts.get(event.templateId) ?? 0;
343
- templateCounts.set(event.templateId, count + 1);
344
- }
345
- const mostUsedTemplates = Array.from(templateCounts.entries()).map(([templateId2, count]) => ({ templateId: templateId2, count })).sort((a, b) => b.count - a.count).slice(0, 3);
346
- const modeCounts = new Map;
347
- for (const event of events) {
348
- if (event.type === "mode_change" && event.metadata?.mode) {
349
- const mode = event.metadata.mode;
350
- const count = modeCounts.get(mode) ?? 0;
351
- modeCounts.set(mode, count + 1);
352
- }
353
- }
354
- const mostUsedModes = Array.from(modeCounts.entries()).map(([mode, count]) => ({ mode, count })).sort((a, b) => b.count - a.count);
355
- const featuresUsed = new Set;
356
- for (const event of events) {
357
- if (event.type === "mode_change" && event.metadata?.mode) {
358
- featuresUsed.add(event.metadata.mode);
359
- }
360
- if (event.type === "feature_usage" && event.metadata?.feature) {
361
- featuresUsed.add(event.metadata.feature);
362
- }
363
- if (event.type === "canvas_interaction") {
364
- const action = event.metadata?.action;
365
- if (action === "add")
366
- featuresUsed.add("canvas_add");
367
- if (action === "delete")
368
- featuresUsed.add("canvas_delete");
369
- }
370
- if (event.type === "spec_edit") {
371
- const action = event.metadata?.action;
372
- if (action === "save")
373
- featuresUsed.add("spec_save");
374
- if (action === "validate")
375
- featuresUsed.add("spec_validate");
376
- }
377
- }
378
- const unusedFeatures = ALL_FEATURES.filter((f) => !featuresUsed.has(f));
379
- const errorCount = events.filter((e) => e.type === "error").length;
380
- const recommendations = generateRecommendations(Array.from(featuresUsed), unusedFeatures, mostUsedModes, events.length);
381
- return {
382
- totalEvents: events.length,
383
- sessionDuration,
384
- mostUsedTemplates,
385
- mostUsedModes,
386
- featuresUsed: Array.from(featuresUsed),
387
- unusedFeatures,
388
- errorCount,
389
- recommendations
390
- };
391
- }, [events]);
392
- const clear = useCallback2(() => {
393
- setEvents([]);
394
- setEventCount(0);
395
- sessionStartRef.current = new Date;
396
- localStorage.removeItem(BEHAVIOR_STORAGE_KEY);
397
- }, []);
398
- return useMemo2(() => ({
399
- trackEvent,
400
- getSummary,
401
- getEventsByType,
402
- eventCount,
403
- sessionStart: sessionStartRef.current,
404
- clear
405
- }), [trackEvent, getSummary, getEventsByType, eventCount, clear]);
406
- }
407
- function generateRecommendations(featuresUsed, unusedFeatures, mostUsedModes, totalEvents) {
408
- const recommendations = [];
409
- if (unusedFeatures.includes("evolution")) {
410
- recommendations.push("Try the AI Evolution mode to get automated improvement suggestions");
411
- }
412
- if (unusedFeatures.includes("markdown")) {
413
- recommendations.push("Use Markdown preview to see documentation for your specs");
414
- }
415
- if (unusedFeatures.includes("builder")) {
416
- recommendations.push("Explore the Visual Builder to design your UI components");
417
- }
418
- if (!featuresUsed.includes("spec_validate") && featuresUsed.includes("specs")) {
419
- recommendations.push("Don't forget to validate your specs before saving");
420
- }
421
- if (featuresUsed.includes("evolution") && !featuresUsed.includes("ai_suggestions")) {
422
- recommendations.push("Generate AI suggestions to get actionable improvement recommendations");
423
- }
424
- if (totalEvents > 50) {
425
- recommendations.push("Great engagement! Consider saving your work regularly");
426
- }
427
- if (mostUsedModes.length === 1) {
428
- recommendations.push("Try different modes to explore all sandbox capabilities");
429
- }
430
- return recommendations;
431
- }
432
-
433
- // src/utils/generateSpecFromTemplate.ts
434
- function generateSpecFromTemplate(template) {
435
- const templateId = template?.id ?? "unknown";
436
- if (!template) {
437
- return generateDefaultSpec(templateId);
438
- }
439
- switch (templateId) {
440
- case "crm-pipeline":
441
- return generateCrmPipelineSpec(template.schema.contracts);
442
- case "saas-boilerplate":
443
- return generateSaasBoilerplateSpec(template.schema.contracts);
444
- case "agent-console":
445
- return generateAgentConsoleSpec(template.schema.contracts);
446
- case "todos-app":
447
- return generateTodosSpec(template.schema.contracts);
448
- case "messaging-app":
449
- return generateMessagingSpec(template.schema.contracts);
450
- case "recipe-app-i18n":
451
- return generateRecipeSpec(template.schema.contracts);
452
- default:
453
- return generateDefaultSpec(templateId);
454
- }
455
- }
456
- function generateCrmPipelineSpec(contracts) {
457
- return `// CRM Pipeline Specs
458
- // Contracts: ${contracts.join(", ")}
2
+ import{useCallback as k,useEffect as l,useMemo as $q,useRef as Jq,useState as x}from"react";var c="contractspec-evolution-data";function bq(q){let[Z,X]=x([]),[z,D]=x([]),[H,B]=x([]),[_,T]=x([]),[L,j]=x(!1),G=Jq([]),[F,W]=x(0);l(()=>{try{let $=localStorage.getItem(`${c}-${q}`);if($){let J=JSON.parse($);B(J.suggestions.map((P)=>({...P,createdAt:new Date(P.createdAt)})))}}catch{}},[q]),l(()=>{try{localStorage.setItem(`${c}-${q}`,JSON.stringify({suggestions:H}))}catch{}},[H,q]);let O=k(($,J,P,Y)=>{let E={operation:{name:$,version:"1.0.0",tenantId:"sandbox"},durationMs:J,success:P,timestamp:new Date,errorCode:Y};G.current.push(E),W((V)=>V+1)},[]),A=k(()=>{let $=G.current;if($.length<5)return;let J=new Map;for(let V of $){let U=`${V.operation.name}.v${V.operation.version}`,I=J.get(U)??[];I.push(V),J.set(U,I)}let P=[],Y=[];J.forEach((V)=>{if(V.length<3)return;let U=V.map((M)=>M.durationMs).sort((M,w)=>M-w),I=V.filter((M)=>!M.success),i=V.length,b=I.length/i,qq=U.reduce((M,w)=>M+w,0)/i,u=V.map((M)=>M.timestamp.getTime()),m=V[0];if(!m)return;let R={operation:m.operation,totalCalls:i,successRate:1-b,errorRate:b,averageLatencyMs:qq,p95LatencyMs:n(U,0.95),p99LatencyMs:n(U,0.99),maxLatencyMs:Math.max(...U),lastSeenAt:new Date(Math.max(...u)),windowStart:new Date(Math.min(...u)),windowEnd:new Date(Math.max(...u)),topErrors:I.reduce((M,w)=>{if(w.errorCode)M[w.errorCode]=(M[w.errorCode]??0)+1;return M},{})};if(P.push(R),b>0.1)Y.push({operation:R.operation,severity:b>0.3?"high":b>0.2?"medium":"low",metric:"error-rate",description:`Error rate ${(b*100).toFixed(1)}% exceeds threshold`,detectedAt:new Date,threshold:0.1,observedValue:b});if(R.p99LatencyMs>500)Y.push({operation:R.operation,severity:R.p99LatencyMs>1000?"high":R.p99LatencyMs>750?"medium":"low",metric:"latency",description:`P99 latency ${R.p99LatencyMs.toFixed(0)}ms exceeds threshold`,detectedAt:new Date,threshold:500,observedValue:R.p99LatencyMs})}),X(P),D(Y);let E=Y.map((V)=>({operation:V.operation,category:V.metric==="latency"?"performance":"error-handling",summary:V.metric==="latency"?"Latency regression detected":"Error spike detected",justification:V.description,recommendedActions:V.metric==="latency"?["Add caching layer","Optimize database queries","Consider pagination"]:["Add retry logic","Improve error handling","Add circuit breaker"]}));T(E)},[]),h=k(async()=>{if(z.length===0)return;j(!0),await new Promise((J)=>setTimeout(J,800));let $=z.map((J)=>({id:`suggestion-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,intent:{id:`intent-${J.operation.name}`,type:J.metric==="latency"?"latency-regression":J.metric==="error-rate"?"error-spike":"throughput-drop",description:J.description,operation:J.operation,confidence:{score:J.severity==="high"?0.9:J.severity==="medium"?0.7:0.5,sampleSize:Z.find((P)=>P.operation.name===J.operation.name)?.totalCalls??0}},target:J.operation,proposal:{summary:Zq(J),rationale:Qq(J),changeType:J.metric==="error-rate"?"policy-update":"revision",recommendedActions:Xq(J)},confidence:J.severity==="high"?0.85:J.severity==="medium"?0.7:0.55,createdAt:new Date,createdBy:"ai-evolution-agent",status:"pending",priority:J.severity}));B((J)=>[...J,...$]),j(!1)},[z,Z]),Q=k(($,J)=>{B((P)=>P.map((Y)=>Y.id===$?{...Y,status:"approved"}:Y))},[]),K=k(($,J)=>{B((P)=>P.map((Y)=>Y.id===$?{...Y,status:"rejected"}:Y))},[]),N=k(()=>{G.current=[],W(0),X([]),D([]),B([]),T([]),localStorage.removeItem(`${c}-${q}`)},[q]);return $q(()=>({usageStats:Z,anomalies:z,suggestions:H,hints:_,loading:L,trackOperation:O,analyzeUsage:A,generateSuggestions:h,approveSuggestion:Q,rejectSuggestion:K,clear:N,operationCount:F}),[Z,z,H,_,L,O,A,h,Q,K,N,F])}function n(q,Z){if(!q.length)return 0;if(q.length===1)return q[0]??0;let X=Math.min(q.length-1,Math.floor(Z*q.length));return q[X]??0}function Zq(q){if(q.metric==="latency")return`Add caching and pagination to ${q.operation.name} to reduce latency`;if(q.metric==="error-rate")return`Add retry policy and circuit breaker to ${q.operation.name}`;return`Optimize ${q.operation.name} for improved throughput`}function Qq(q){if(q.metric==="latency")return`The operation ${q.operation.name} is experiencing P99 latency of ${q.observedValue?.toFixed(0)}ms, which is above the recommended threshold of ${q.threshold}ms. This can impact user experience and downstream operations.`;if(q.metric==="error-rate")return`The error rate for ${q.operation.name} is ${((q.observedValue??0)*100).toFixed(1)}%, indicating potential issues with input validation, external dependencies, or resource limits.`;return`Throughput for ${q.operation.name} has dropped significantly, suggesting potential bottlenecks or reduced demand that should be investigated.`}function Xq(q){if(q.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(q.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{createContext as zq,useContext as hq}from"react";var o=Symbol.for("@contractspec/lib.example-shared-ui/template-runtime-context");function Dq(){let q=globalThis;return q[o]??=zq(null),q[o]}var Hq=Dq();function s(){let q=hq(Hq);if(!q)throw Error("useTemplateRuntime must be used within a TemplateRuntimeProvider");return q}import{useCallback as f,useEffect as a,useMemo as jq,useRef as Pq,useState as t}from"react";var d="contractspec-behavior-data",Gq=["playground","specs","builder","markdown","evolution","canvas_add","canvas_delete","spec_save","spec_validate","ai_suggestions"];function Iq(q){let[Z,X]=t([]),z=Pq(new Date),[D,H]=t(0);a(()=>{try{let j=localStorage.getItem(d);if(j){let G=JSON.parse(j);X(G.events.map((F)=>({...F,timestamp:new Date(F.timestamp)}))),z.current=new Date(G.sessionStart)}}catch{}},[]),a(()=>{if(Z.length>0)try{localStorage.setItem(d,JSON.stringify({events:Z.map((j)=>({...j,timestamp:j.timestamp.toISOString()})),sessionStart:z.current.toISOString()}))}catch{}},[Z]);let B=f((j,G)=>{let F={type:j,timestamp:new Date,templateId:q,metadata:G};X((W)=>[...W,F]),H((W)=>W+1)},[q]),_=f((j)=>{return Z.filter((G)=>G.type===j)},[Z]),T=f(()=>{let G=new Date().getTime()-z.current.getTime(),F=new Map;for(let $ of Z){let J=F.get($.templateId)??0;F.set($.templateId,J+1)}let W=Array.from(F.entries()).map(([$,J])=>({templateId:$,count:J})).sort(($,J)=>J.count-$.count).slice(0,3),O=new Map;for(let $ of Z)if($.type==="mode_change"&&$.metadata?.mode){let J=$.metadata.mode,P=O.get(J)??0;O.set(J,P+1)}let A=Array.from(O.entries()).map(([$,J])=>({mode:$,count:J})).sort(($,J)=>J.count-$.count),h=new Set;for(let $ of Z){if($.type==="mode_change"&&$.metadata?.mode)h.add($.metadata.mode);if($.type==="feature_usage"&&$.metadata?.feature)h.add($.metadata.feature);if($.type==="canvas_interaction"){let J=$.metadata?.action;if(J==="add")h.add("canvas_add");if(J==="delete")h.add("canvas_delete")}if($.type==="spec_edit"){let J=$.metadata?.action;if(J==="save")h.add("spec_save");if(J==="validate")h.add("spec_validate")}}let Q=Gq.filter(($)=>!h.has($)),K=Z.filter(($)=>$.type==="error").length,N=Vq(Array.from(h),Q,A,Z.length);return{totalEvents:Z.length,sessionDuration:G,mostUsedTemplates:W,mostUsedModes:A,featuresUsed:Array.from(h),unusedFeatures:Q,errorCount:K,recommendations:N}},[Z]),L=f(()=>{X([]),H(0),z.current=new Date,localStorage.removeItem(d)},[]);return jq(()=>({trackEvent:B,getSummary:T,getEventsByType:_,eventCount:D,sessionStart:z.current,clear:L}),[B,T,_,D,L])}function Vq(q,Z,X,z){let D=[];if(Z.includes("evolution"))D.push("Try the AI Evolution mode to get automated improvement suggestions");if(Z.includes("markdown"))D.push("Use Markdown preview to see documentation for your specs");if(Z.includes("builder"))D.push("Explore the Visual Builder to design your UI components");if(!q.includes("spec_validate")&&q.includes("specs"))D.push("Don't forget to validate your specs before saving");if(q.includes("evolution")&&!q.includes("ai_suggestions"))D.push("Generate AI suggestions to get actionable improvement recommendations");if(z>50)D.push("Great engagement! Consider saving your work regularly");if(X.length===1)D.push("Try different modes to explore all sandbox capabilities");return D}function C(q){let Z=q?.id??"unknown";if(!q)return e(Z);switch(Z){case"crm-pipeline":return Kq(q.schema.contracts);case"saas-boilerplate":return Yq(q.schema.contracts);case"agent-console":return Fq(q.schema.contracts);case"todos-app":return Lq(q.schema.contracts);case"messaging-app":return Nq(q.schema.contracts);case"recipe-app-i18n":return Bq(q.schema.contracts);default:return e(Z)}}function Kq(q){return`// CRM Pipeline Specs
3
+ // Contracts: ${q.join(", ")}
459
4
 
460
5
  contractSpec("crm.deal.updateStage.v1", {
461
6
  goal: "Move a deal to a different pipeline stage",
@@ -524,11 +69,8 @@ contractSpec("crm.contact.list.v1", {
524
69
  hasMore: "boolean"
525
70
  }
526
71
  }
527
- });`;
528
- }
529
- function generateSaasBoilerplateSpec(contracts) {
530
- return `// SaaS Boilerplate Specs
531
- // Contracts: ${contracts.join(", ")}
72
+ });`}function Yq(q){return`// SaaS Boilerplate Specs
73
+ // Contracts: ${q.join(", ")}
532
74
 
533
75
  contractSpec("saas.project.create.v1", {
534
76
  goal: "Create a new project in an organization",
@@ -591,11 +133,8 @@ contractSpec("saas.settings.update.v1", {
591
133
  }
592
134
  },
593
135
  events: ["settings.updated"]
594
- });`;
595
- }
596
- function generateAgentConsoleSpec(contracts) {
597
- return `// Agent Console Specs
598
- // Contracts: ${contracts.join(", ")}
136
+ });`}function Fq(q){return`// Agent Console Specs
137
+ // Contracts: ${q.join(", ")}
599
138
 
600
139
  contractSpec("agent.run.execute.v1", {
601
140
  goal: "Execute an agent run with specified tools",
@@ -661,11 +200,8 @@ contractSpec("agent.agent.create.v1", {
661
200
  }
662
201
  },
663
202
  events: ["agent.created"]
664
- });`;
665
- }
666
- function generateTodosSpec(contracts) {
667
- return `// To-dos App Specs
668
- // Contracts: ${contracts.join(", ")}
203
+ });`}function Lq(q){return`// To-dos App Specs
204
+ // Contracts: ${q.join(", ")}
669
205
 
670
206
  contractSpec("tasks.board.v1", {
671
207
  goal: "Assign and approve craft work",
@@ -724,11 +260,8 @@ contractSpec("tasks.complete.v1", {
724
260
  }
725
261
  },
726
262
  events: ["task.completed"]
727
- });`;
728
- }
729
- function generateMessagingSpec(contracts) {
730
- return `// Messaging App Specs
731
- // Contracts: ${contracts.join(", ")}
263
+ });`}function Nq(q){return`// Messaging App Specs
264
+ // Contracts: ${q.join(", ")}
732
265
 
733
266
  contractSpec("messaging.send.v1", {
734
267
  goal: "Deliver intent-rich updates",
@@ -781,11 +314,8 @@ contractSpec("messaging.read.v1", {
781
314
  }
782
315
  },
783
316
  events: ["message.read"]
784
- });`;
785
- }
786
- function generateRecipeSpec(contracts) {
787
- return `// Recipe App (i18n) Specs
788
- // Contracts: ${contracts.join(", ")}
317
+ });`}function Bq(q){return`// Recipe App (i18n) Specs
318
+ // Contracts: ${q.join(", ")}
789
319
 
790
320
  contractSpec("recipes.lookup.v1", {
791
321
  goal: "Serve bilingual rituals",
@@ -832,13 +362,10 @@ contractSpec("recipes.favorite.toggle.v1", {
832
362
  }
833
363
  },
834
364
  events: ["recipe.favorited", "recipe.unfavorited"]
835
- });`;
836
- }
837
- function generateDefaultSpec(templateId) {
838
- return `// ${templateId} Specs
365
+ });`}function e(q){return`// ${q} Specs
839
366
 
840
- contractSpec("${templateId}.main.v1", {
841
- goal: "Main operation for ${templateId}",
367
+ contractSpec("${q}.main.v1", {
368
+ goal: "Main operation for ${q}",
842
369
  transport: { gql: { query: "main" } },
843
370
  io: {
844
371
  input: {
@@ -848,676 +375,38 @@ contractSpec("${templateId}.main.v1", {
848
375
  result: "unknown"
849
376
  }
850
377
  }
851
- });`;
852
- }
853
-
854
- // src/hooks/useSpecContent.ts
855
- import { useCallback as useCallback3, useEffect as useEffect3, useState as useState3 } from "react";
856
- "use client";
857
- var SPEC_STORAGE_KEY = "contractspec-spec-content";
858
- function useSpecContent(templateId) {
859
- const { template } = useTemplateRuntime();
860
- const [content, setContentState] = useState3("");
861
- const [savedContent, setSavedContent] = useState3("");
862
- const [loading, setLoading] = useState3(true);
863
- const [validation, setValidation] = useState3(null);
864
- const [lastSaved, setLastSaved] = useState3(null);
865
- useEffect3(() => {
866
- setLoading(true);
867
- try {
868
- const stored = localStorage.getItem(`${SPEC_STORAGE_KEY}-${templateId}`);
869
- if (stored) {
870
- const parsed = JSON.parse(stored);
871
- if (parsed.content) {
872
- setContentState(parsed.content);
873
- setSavedContent(parsed.content);
874
- setLastSaved(parsed.savedAt);
875
- } else {
876
- const generated = generateSpecFromTemplate(template);
877
- setContentState(generated);
878
- setSavedContent(generated);
879
- }
880
- } else {
881
- const generated = generateSpecFromTemplate(template);
882
- setContentState(generated);
883
- setSavedContent(generated);
884
- }
885
- } catch {
886
- const generated = generateSpecFromTemplate(template);
887
- setContentState(generated);
888
- setSavedContent(generated);
889
- }
890
- setLoading(false);
891
- }, [templateId]);
892
- const setContent = useCallback3((newContent) => {
893
- setContentState(newContent);
894
- setValidation(null);
895
- }, []);
896
- const save = useCallback3(() => {
897
- try {
898
- const savedAt = new Date().toISOString();
899
- localStorage.setItem(`${SPEC_STORAGE_KEY}-${templateId}`, JSON.stringify({
900
- content,
901
- savedAt
902
- }));
903
- setSavedContent(content);
904
- setLastSaved(savedAt);
905
- } catch {}
906
- }, [content, templateId]);
907
- const validate = useCallback3(() => {
908
- const errors = [];
909
- const lines = content.split(`
910
- `);
911
- if (!content.includes("contractSpec(")) {
912
- errors.push({
913
- line: 1,
914
- message: "Spec must contain a contractSpec() definition",
915
- severity: "error"
916
- });
917
- }
918
- if (!content.includes("goal:")) {
919
- errors.push({
920
- line: 1,
921
- message: "Spec should have a goal field",
922
- severity: "warning"
923
- });
924
- }
925
- if (!content.includes("io:")) {
926
- errors.push({
927
- line: 1,
928
- message: "Spec should define io (input/output)",
929
- severity: "warning"
930
- });
931
- }
932
- const openBraces = (content.match(/{/g) ?? []).length;
933
- const closeBraces = (content.match(/}/g) ?? []).length;
934
- if (openBraces !== closeBraces) {
935
- errors.push({
936
- line: lines.length,
937
- message: `Unbalanced braces: ${openBraces} opening, ${closeBraces} closing`,
938
- severity: "error"
939
- });
940
- }
941
- const openParens = (content.match(/\(/g) ?? []).length;
942
- const closeParens = (content.match(/\)/g) ?? []).length;
943
- if (openParens !== closeParens) {
944
- errors.push({
945
- line: lines.length,
946
- message: `Unbalanced parentheses: ${openParens} opening, ${closeParens} closing`,
947
- severity: "error"
948
- });
949
- }
950
- lines.forEach((line, index) => {
951
- const singleQuotes = (line.match(/'/g) ?? []).length;
952
- const doubleQuotes = (line.match(/"/g) ?? []).length;
953
- if (singleQuotes % 2 !== 0) {
954
- errors.push({
955
- line: index + 1,
956
- message: "Unclosed single quote",
957
- severity: "error"
958
- });
959
- }
960
- if (doubleQuotes % 2 !== 0) {
961
- errors.push({
962
- line: index + 1,
963
- message: "Unclosed double quote",
964
- severity: "error"
965
- });
966
- }
967
- });
968
- const result = {
969
- valid: errors.filter((e) => e.severity === "error").length === 0,
970
- errors
971
- };
972
- setValidation(result);
973
- return result;
974
- }, [content]);
975
- const reset = useCallback3(() => {
976
- const generated = generateSpecFromTemplate(template);
977
- setContentState(generated);
978
- setSavedContent(generated);
979
- setValidation(null);
980
- setLastSaved(null);
981
- try {
982
- localStorage.removeItem(`${SPEC_STORAGE_KEY}-${templateId}`);
983
- } catch {}
984
- }, [templateId]);
985
- return {
986
- content,
987
- loading,
988
- isDirty: content !== savedContent,
989
- validation,
990
- setContent,
991
- save,
992
- validate,
993
- reset,
994
- lastSaved
995
- };
996
- }
997
-
998
- // src/hooks/useRegistryTemplates.ts
999
- import { useQuery } from "@tanstack/react-query";
1000
- function useRegistryTemplates() {
1001
- return useQuery({
1002
- queryKey: ["registryTemplates"],
1003
- queryFn: async () => {
1004
- const registryUrl = process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL ?? "";
1005
- if (!registryUrl)
1006
- return [];
1007
- const res = await fetch(`${registryUrl.replace(/\/$/, "")}/r/contractspec.json`, {
1008
- method: "GET",
1009
- headers: { Accept: "application/json" }
1010
- });
1011
- if (!res.ok)
1012
- return [];
1013
- const json = await res.json();
1014
- const items = json.items ?? [];
1015
- return items.filter((i) => i.type === "contractspec:template").map((i) => ({
1016
- id: i.name,
1017
- name: i.title ?? i.name,
1018
- description: i.description,
1019
- tags: i.meta?.tags ?? [],
1020
- source: "registry",
1021
- registryUrl
1022
- }));
1023
- }
1024
- });
1025
- }
1026
-
1027
- // src/hooks/useWorkflowComposer.ts
1028
- import { useCallback as useCallback4, useEffect as useEffect4, useMemo as useMemo3, useState as useState4 } from "react";
1029
- "use client";
1030
- function useWorkflowComposer(templateId) {
1031
- const [selectedWorkflow, setSelectedWorkflow] = useState4(null);
1032
- const [extensions, setExtensions] = useState4([]);
1033
- const [loading, _setLoading] = useState4(false);
1034
- const [error, _setError] = useState4(null);
1035
- const baseWorkflows = useMemo3(() => getTemplateWorkflows(templateId), [templateId]);
1036
- useEffect4(() => {
1037
- const firstWorkflow = baseWorkflows[0];
1038
- if (baseWorkflows.length > 0 && !selectedWorkflow && firstWorkflow) {
1039
- setSelectedWorkflow(firstWorkflow.meta.key);
1040
- }
1041
- }, [baseWorkflows, selectedWorkflow]);
1042
- const currentBase = useMemo3(() => {
1043
- return baseWorkflows.find((w) => w.meta.key === selectedWorkflow) ?? null;
1044
- }, [baseWorkflows, selectedWorkflow]);
1045
- const compose = useCallback4((scope) => {
1046
- if (!currentBase)
1047
- return null;
1048
- const applicableExtensions = extensions.filter((ext) => ext.workflow === currentBase.meta.key).filter((ext) => matchesScope(ext, scope)).sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
1049
- if (applicableExtensions.length === 0) {
1050
- return currentBase;
1051
- }
1052
- let composedWorkflow = { ...currentBase, steps: [...currentBase.steps] };
1053
- for (const extension of applicableExtensions) {
1054
- composedWorkflow = applyExtension(composedWorkflow, extension);
1055
- }
1056
- return composedWorkflow;
1057
- }, [currentBase, extensions]);
1058
- const workflow = useMemo3(() => compose(), [compose]);
1059
- const selectWorkflow = useCallback4((workflowName) => {
1060
- setSelectedWorkflow(workflowName);
1061
- }, []);
1062
- const addExtension = useCallback4((extension) => {
1063
- setExtensions((prev) => [...prev, extension]);
1064
- }, []);
1065
- const removeExtension = useCallback4((workflowName, index) => {
1066
- setExtensions((prev) => {
1067
- const forWorkflow = prev.filter((e) => e.workflow === workflowName);
1068
- const others = prev.filter((e) => e.workflow !== workflowName);
1069
- forWorkflow.splice(index, 1);
1070
- return [...others, ...forWorkflow];
1071
- });
1072
- }, []);
1073
- const generateSpecCode = useCallback4(() => {
1074
- const composed = workflow;
1075
- if (!composed) {
1076
- return "// No workflow selected";
1077
- }
1078
- const stepsCode = composed.steps.map((step) => ` {
1079
- id: '${step.id}',
1080
- name: '${step.name}',
1081
- type: '${step.type}',${step.description ? `
1082
- description: '${step.description}',` : ""}${step.next ? `
1083
- next: ${JSON.stringify(step.next)},` : ""}${step.condition ? `
1084
- condition: '${step.condition}',` : ""}${step.timeout ? `
1085
- timeout: ${step.timeout},` : ""}${step.retries ? `
1086
- retries: ${step.retries},` : ""}${step.onError ? `
1087
- onError: '${step.onError}',` : ""}
378
+ });`}import{useCallback as v,useEffect as Mq,useState as g}from"react";var p="contractspec-spec-content";function Sq(q){let{template:Z}=s(),[X,z]=g(""),[D,H]=g(""),[B,_]=g(!0),[T,L]=g(null),[j,G]=g(null);Mq(()=>{_(!0);try{let h=localStorage.getItem(`${p}-${q}`);if(h){let Q=JSON.parse(h);if(Q.content)z(Q.content),H(Q.content),G(Q.savedAt);else{let K=C(Z);z(K),H(K)}}else{let Q=C(Z);z(Q),H(Q)}}catch{let h=C(Z);z(h),H(h)}_(!1)},[q]);let F=v((h)=>{z(h),L(null)},[]),W=v(()=>{try{let h=new Date().toISOString();localStorage.setItem(`${p}-${q}`,JSON.stringify({content:X,savedAt:h})),H(X),G(h)}catch{}},[X,q]),O=v(()=>{let h=[],Q=X.split(`
379
+ `);if(!X.includes("contractSpec("))h.push({line:1,message:"Spec must contain a contractSpec() definition",severity:"error"});if(!X.includes("goal:"))h.push({line:1,message:"Spec should have a goal field",severity:"warning"});if(!X.includes("io:"))h.push({line:1,message:"Spec should define io (input/output)",severity:"warning"});let K=(X.match(/{/g)??[]).length,N=(X.match(/}/g)??[]).length;if(K!==N)h.push({line:Q.length,message:`Unbalanced braces: ${K} opening, ${N} closing`,severity:"error"});let $=(X.match(/\(/g)??[]).length,J=(X.match(/\)/g)??[]).length;if($!==J)h.push({line:Q.length,message:`Unbalanced parentheses: ${$} opening, ${J} closing`,severity:"error"});Q.forEach((Y,E)=>{let V=(Y.match(/'/g)??[]).length,U=(Y.match(/"/g)??[]).length;if(V%2!==0)h.push({line:E+1,message:"Unclosed single quote",severity:"error"});if(U%2!==0)h.push({line:E+1,message:"Unclosed double quote",severity:"error"})});let P={valid:h.filter((Y)=>Y.severity==="error").length===0,errors:h};return L(P),P},[X]),A=v(()=>{let h=C(Z);z(h),H(h),L(null),G(null);try{localStorage.removeItem(`${p}-${q}`)}catch{}},[q]);return{content:X,loading:B,isDirty:X!==D,validation:T,setContent:F,save:W,validate:O,reset:A,lastSaved:j}}import{useQuery as Wq}from"@tanstack/react-query";function cq(){return Wq({queryKey:["registryTemplates"],queryFn:async()=>{let q=process.env.NEXT_PUBLIC_CONTRACTSPEC_REGISTRY_URL??"";if(!q)return[];let Z=await fetch(`${q.replace(/\/$/,"")}/r/contractspec.json`,{method:"GET",headers:{Accept:"application/json"}});if(!Z.ok)return[];return((await Z.json()).items??[]).filter((D)=>D.type==="contractspec:template").map((D)=>({id:D.name,name:D.title??D.name,description:D.description,tags:D.meta?.tags??[],source:"registry",registryUrl:q}))}})}import{useCallback as y,useEffect as _q,useMemo as r,useState as S}from"react";function rq(q){let[Z,X]=S(null),[z,D]=S([]),[H,B]=S(!1),[_,T]=S(null),L=r(()=>Tq(q),[q]);_q(()=>{let Q=L[0];if(L.length>0&&!Z&&Q)X(Q.meta.key)},[L,Z]);let j=r(()=>{return L.find((Q)=>Q.meta.key===Z)??null},[L,Z]),G=y((Q)=>{if(!j)return null;let K=z.filter(($)=>$.workflow===j.meta.key).filter(($)=>Oq($,Q)).sort(($,J)=>($.priority??0)-(J.priority??0));if(K.length===0)return j;let N={...j,steps:[...j.steps]};for(let $ of K)N=Aq(N,$);return N},[j,z]),F=r(()=>G(),[G]),W=y((Q)=>{X(Q)},[]),O=y((Q)=>{D((K)=>[...K,Q])},[]),A=y((Q,K)=>{D((N)=>{let $=N.filter((P)=>P.workflow===Q),J=N.filter((P)=>P.workflow!==Q);return $.splice(K,1),[...J,...$]})},[]),h=y(()=>{let Q=F;if(!Q)return"// No workflow selected";let K=Q.steps.map(($)=>` {
380
+ id: '${$.id}',
381
+ name: '${$.name}',
382
+ type: '${$.type}',${$.description?`
383
+ description: '${$.description}',`:""}${$.next?`
384
+ next: ${JSON.stringify($.next)},`:""}${$.condition?`
385
+ condition: '${$.condition}',`:""}${$.timeout?`
386
+ timeout: ${$.timeout},`:""}${$.retries?`
387
+ retries: ${$.retries},`:""}${$.onError?`
388
+ onError: '${$.onError}',`:""}
1088
389
  }`).join(`,
1089
- `);
1090
- const extensionsCode = extensions.length > 0 ? `
390
+ `),N=z.length>0?`
1091
391
 
1092
392
  // Extensions applied:
1093
- ${extensions.map((ext) => `// - ${ext.workflow} (priority: ${ext.priority ?? 0})${ext.customSteps?.length ? ` +${ext.customSteps.length} steps` : ""}${ext.hiddenSteps?.length ? ` -${ext.hiddenSteps.length} hidden` : ""}`).join(`
1094
- `)}` : "";
1095
- return `// Workflow Spec: ${composed.meta.key} v${composed.meta.version}
1096
- // Generated from ${templateId} template
1097
- ${extensionsCode}
393
+ ${z.map(($)=>`// - ${$.workflow} (priority: ${$.priority??0})${$.customSteps?.length?` +${$.customSteps.length} steps`:""}${$.hiddenSteps?.length?` -${$.hiddenSteps.length} hidden`:""}`).join(`
394
+ `)}`:"";return`// Workflow Spec: ${Q.meta.key} v${Q.meta.version}
395
+ // Generated from ${q} template
396
+ ${N}
1098
397
 
1099
398
  import { workflowSpec } from '@contractspec/lib.contracts-spec/workflow';
1100
399
 
1101
- export const ${toCamelCase(composed.meta.key)}Workflow = workflowSpec({
400
+ export const ${Uq(Q.meta.key)}Workflow = workflowSpec({
1102
401
  meta: {
1103
- key: '${composed.meta.key}',
1104
- version: ${composed.meta.version},${composed.meta.description ? `
1105
- description: '${composed.meta.description}',` : ""}
402
+ key: '${Q.meta.key}',
403
+ version: ${Q.meta.version},${Q.meta.description?`
404
+ description: '${Q.meta.description}',`:""}
1106
405
  },
1107
- start: '${composed.start}',
406
+ start: '${Q.start}',
1108
407
  steps: [
1109
- ${stepsCode}
1110
- ],${composed.context ? `
1111
- context: ${JSON.stringify(composed.context, null, 2)},` : ""}
408
+ ${K}
409
+ ],${Q.context?`
410
+ context: ${JSON.stringify(Q.context,null,2)},`:""}
1112
411
  });
1113
- `;
1114
- }, [workflow, extensions, templateId]);
1115
- return {
1116
- workflow,
1117
- baseWorkflows,
1118
- extensions,
1119
- selectWorkflow,
1120
- addExtension,
1121
- removeExtension,
1122
- compose,
1123
- generateSpecCode,
1124
- loading,
1125
- error
1126
- };
1127
- }
1128
- function matchesScope(extension, scope) {
1129
- if (!scope)
1130
- return true;
1131
- if (extension.tenantId && extension.tenantId !== scope.tenantId) {
1132
- return false;
1133
- }
1134
- if (extension.role && extension.role !== scope.role) {
1135
- return false;
1136
- }
1137
- if (extension.device && extension.device !== scope.device) {
1138
- return false;
1139
- }
1140
- return true;
1141
- }
1142
- function applyExtension(workflow, extension) {
1143
- let steps = [...workflow.steps];
1144
- if (extension.hiddenSteps) {
1145
- steps = steps.filter((s) => !extension.hiddenSteps?.includes(s.id));
1146
- }
1147
- if (extension.customSteps) {
1148
- for (const injection of extension.customSteps) {
1149
- const stepToInject = {
1150
- ...injection.inject,
1151
- id: injection.id ?? injection.inject.id
1152
- };
1153
- if (injection.after) {
1154
- const afterIndex = steps.findIndex((s) => s.id === injection.after);
1155
- if (afterIndex !== -1) {
1156
- steps.splice(afterIndex + 1, 0, stepToInject);
1157
- }
1158
- } else if (injection.before) {
1159
- const beforeIndex = steps.findIndex((s) => s.id === injection.before);
1160
- if (beforeIndex !== -1) {
1161
- steps.splice(beforeIndex, 0, stepToInject);
1162
- }
1163
- } else {
1164
- steps.push(stepToInject);
1165
- }
1166
- }
1167
- }
1168
- return { ...workflow, steps };
1169
- }
1170
- function toCamelCase(str) {
1171
- return str.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase()).replace(/^./, (c) => c.toLowerCase());
1172
- }
1173
- function getTemplateWorkflows(templateId) {
1174
- const templateWorkflows = {
1175
- "crm-pipeline": [
1176
- {
1177
- meta: {
1178
- key: "deal.qualification",
1179
- version: "1.0.0",
1180
- description: "Deal qualification workflow"
1181
- },
1182
- start: "lead-received",
1183
- steps: [
1184
- {
1185
- id: "lead-received",
1186
- name: "Lead Received",
1187
- type: "action",
1188
- description: "New lead enters the pipeline",
1189
- next: "qualify-lead"
1190
- },
1191
- {
1192
- id: "qualify-lead",
1193
- name: "Qualify Lead",
1194
- type: "decision",
1195
- description: "Determine if lead meets qualification criteria",
1196
- next: ["qualified", "disqualified"],
1197
- condition: "lead.score >= threshold"
1198
- },
1199
- {
1200
- id: "qualified",
1201
- name: "Lead Qualified",
1202
- type: "action",
1203
- next: "assign-rep"
1204
- },
1205
- {
1206
- id: "disqualified",
1207
- name: "Lead Disqualified",
1208
- type: "end"
1209
- },
1210
- {
1211
- id: "assign-rep",
1212
- name: "Assign Sales Rep",
1213
- type: "action",
1214
- next: "complete"
1215
- },
1216
- {
1217
- id: "complete",
1218
- name: "Workflow Complete",
1219
- type: "end"
1220
- }
1221
- ]
1222
- },
1223
- {
1224
- meta: {
1225
- key: "deal.closing",
1226
- version: "1.0.0",
1227
- description: "Deal closing workflow"
1228
- },
1229
- start: "proposal-sent",
1230
- steps: [
1231
- {
1232
- id: "proposal-sent",
1233
- name: "Proposal Sent",
1234
- type: "action",
1235
- next: "wait-response"
1236
- },
1237
- {
1238
- id: "wait-response",
1239
- name: "Wait for Response",
1240
- type: "wait",
1241
- timeout: 604800000,
1242
- next: "negotiate",
1243
- onError: "follow-up"
1244
- },
1245
- {
1246
- id: "follow-up",
1247
- name: "Follow Up",
1248
- type: "action",
1249
- next: "wait-response",
1250
- retries: 3
1251
- },
1252
- {
1253
- id: "negotiate",
1254
- name: "Negotiation",
1255
- type: "action",
1256
- next: "finalize"
1257
- },
1258
- {
1259
- id: "finalize",
1260
- name: "Finalize Deal",
1261
- type: "decision",
1262
- next: ["won", "lost"],
1263
- condition: "deal.accepted"
1264
- },
1265
- {
1266
- id: "won",
1267
- name: "Deal Won",
1268
- type: "end"
1269
- },
1270
- {
1271
- id: "lost",
1272
- name: "Deal Lost",
1273
- type: "end"
1274
- }
1275
- ]
1276
- }
1277
- ],
1278
- "saas-boilerplate": [
1279
- {
1280
- meta: {
1281
- key: "user.onboarding",
1282
- version: "1.0.0",
1283
- description: "User onboarding workflow"
1284
- },
1285
- start: "signup",
1286
- steps: [
1287
- {
1288
- id: "signup",
1289
- name: "User Signup",
1290
- type: "action",
1291
- next: "verify-email"
1292
- },
1293
- {
1294
- id: "verify-email",
1295
- name: "Verify Email",
1296
- type: "wait",
1297
- timeout: 86400000,
1298
- next: "profile-setup",
1299
- onError: "resend-verification"
1300
- },
1301
- {
1302
- id: "resend-verification",
1303
- name: "Resend Verification",
1304
- type: "action",
1305
- next: "verify-email",
1306
- retries: 2
1307
- },
1308
- {
1309
- id: "profile-setup",
1310
- name: "Setup Profile",
1311
- type: "action",
1312
- next: "onboarding-tour"
1313
- },
1314
- {
1315
- id: "onboarding-tour",
1316
- name: "Onboarding Tour",
1317
- type: "action",
1318
- next: "complete"
1319
- },
1320
- {
1321
- id: "complete",
1322
- name: "Onboarding Complete",
1323
- type: "end"
1324
- }
1325
- ]
1326
- }
1327
- ],
1328
- "agent-console": [
1329
- {
1330
- meta: {
1331
- key: "agent.execution",
1332
- version: "1.0.0",
1333
- description: "Agent execution workflow"
1334
- },
1335
- start: "receive-task",
1336
- steps: [
1337
- {
1338
- id: "receive-task",
1339
- name: "Receive Task",
1340
- type: "action",
1341
- next: "plan-execution"
1342
- },
1343
- {
1344
- id: "plan-execution",
1345
- name: "Plan Execution",
1346
- type: "action",
1347
- next: "execute-steps"
1348
- },
1349
- {
1350
- id: "execute-steps",
1351
- name: "Execute Steps",
1352
- type: "parallel",
1353
- next: ["tool-call", "observe", "reason"]
1354
- },
1355
- {
1356
- id: "tool-call",
1357
- name: "Tool Call",
1358
- type: "action",
1359
- next: "evaluate"
1360
- },
1361
- {
1362
- id: "observe",
1363
- name: "Observe",
1364
- type: "action",
1365
- next: "evaluate"
1366
- },
1367
- {
1368
- id: "reason",
1369
- name: "Reason",
1370
- type: "action",
1371
- next: "evaluate"
1372
- },
1373
- {
1374
- id: "evaluate",
1375
- name: "Evaluate Result",
1376
- type: "decision",
1377
- condition: "task.isComplete",
1378
- next: ["complete", "execute-steps"]
1379
- },
1380
- {
1381
- id: "complete",
1382
- name: "Task Complete",
1383
- type: "end"
1384
- }
1385
- ]
1386
- }
1387
- ],
1388
- "todos-app": [
1389
- {
1390
- meta: {
1391
- key: "task.lifecycle",
1392
- version: "1.0.0",
1393
- description: "Task lifecycle workflow"
1394
- },
1395
- start: "created",
1396
- steps: [
1397
- {
1398
- id: "created",
1399
- name: "Task Created",
1400
- type: "action",
1401
- next: "in-progress"
1402
- },
1403
- {
1404
- id: "in-progress",
1405
- name: "In Progress",
1406
- type: "action",
1407
- next: "review"
1408
- },
1409
- {
1410
- id: "review",
1411
- name: "Review",
1412
- type: "decision",
1413
- condition: "task.approved",
1414
- next: ["done", "in-progress"]
1415
- },
1416
- {
1417
- id: "done",
1418
- name: "Done",
1419
- type: "end"
1420
- }
1421
- ]
1422
- }
1423
- ],
1424
- "messaging-app": [
1425
- {
1426
- meta: {
1427
- key: "message.delivery",
1428
- version: "1.0.0",
1429
- description: "Message delivery workflow"
1430
- },
1431
- start: "compose",
1432
- steps: [
1433
- {
1434
- id: "compose",
1435
- name: "Compose Message",
1436
- type: "action",
1437
- next: "send"
1438
- },
1439
- {
1440
- id: "send",
1441
- name: "Send Message",
1442
- type: "action",
1443
- next: "deliver"
1444
- },
1445
- {
1446
- id: "deliver",
1447
- name: "Deliver",
1448
- type: "decision",
1449
- condition: "recipient.online",
1450
- next: ["delivered", "queue"]
1451
- },
1452
- {
1453
- id: "queue",
1454
- name: "Queue for Delivery",
1455
- type: "wait",
1456
- next: "deliver"
1457
- },
1458
- {
1459
- id: "delivered",
1460
- name: "Message Delivered",
1461
- type: "action",
1462
- next: "read"
1463
- },
1464
- {
1465
- id: "read",
1466
- name: "Message Read",
1467
- type: "end"
1468
- }
1469
- ]
1470
- }
1471
- ],
1472
- "recipe-app-i18n": [
1473
- {
1474
- meta: {
1475
- key: "recipe.creation",
1476
- version: "1.0.0",
1477
- description: "Recipe creation workflow"
1478
- },
1479
- start: "draft",
1480
- steps: [
1481
- {
1482
- id: "draft",
1483
- name: "Draft Recipe",
1484
- type: "action",
1485
- next: "add-ingredients"
1486
- },
1487
- {
1488
- id: "add-ingredients",
1489
- name: "Add Ingredients",
1490
- type: "action",
1491
- next: "add-steps"
1492
- },
1493
- {
1494
- id: "add-steps",
1495
- name: "Add Steps",
1496
- type: "action",
1497
- next: "review"
1498
- },
1499
- {
1500
- id: "review",
1501
- name: "Review Recipe",
1502
- type: "decision",
1503
- condition: "recipe.isComplete",
1504
- next: ["publish", "draft"]
1505
- },
1506
- {
1507
- id: "publish",
1508
- name: "Publish Recipe",
1509
- type: "end"
1510
- }
1511
- ]
1512
- }
1513
- ]
1514
- };
1515
- return templateWorkflows[templateId] ?? [];
1516
- }
1517
- export {
1518
- useWorkflowComposer,
1519
- useSpecContent,
1520
- useRegistryTemplates,
1521
- useEvolution,
1522
- useBehaviorTracking
1523
- };
412
+ `},[F,z,q]);return{workflow:F,baseWorkflows:L,extensions:z,selectWorkflow:W,addExtension:O,removeExtension:A,compose:G,generateSpecCode:h,loading:H,error:_}}function Oq(q,Z){if(!Z)return!0;if(q.tenantId&&q.tenantId!==Z.tenantId)return!1;if(q.role&&q.role!==Z.role)return!1;if(q.device&&q.device!==Z.device)return!1;return!0}function Aq(q,Z){let X=[...q.steps];if(Z.hiddenSteps)X=X.filter((z)=>!Z.hiddenSteps?.includes(z.id));if(Z.customSteps)for(let z of Z.customSteps){let D={...z.inject,id:z.id??z.inject.id};if(z.after){let H=X.findIndex((B)=>B.id===z.after);if(H!==-1)X.splice(H+1,0,D)}else if(z.before){let H=X.findIndex((B)=>B.id===z.before);if(H!==-1)X.splice(H,0,D)}else X.push(D)}return{...q,steps:X}}function Uq(q){return q.replace(/[^a-zA-Z0-9]+(.)/g,(Z,X)=>X.toUpperCase()).replace(/^./,(Z)=>Z.toLowerCase())}function Tq(q){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"}]}]}[q]??[]}export{rq as useWorkflowComposer,Sq as useSpecContent,cq as useRegistryTemplates,bq as useEvolution,Iq as useBehaviorTracking};