@contractspec/module.examples 1.57.0 → 1.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,913 @@
1
+ // src/registry.ts
2
+ import { ExampleRegistry } from "@contractspec/lib.contracts";
3
+
4
+ // src/builtins.ts
5
+ import AgentConsole from "@contractspec/example.agent-console/example";
6
+ import AiSupportBot from "@contractspec/example.ai-support-bot/example";
7
+ import AnalyticsDashboard from "@contractspec/example.analytics-dashboard/example";
8
+ import ContentGeneration from "@contractspec/example.content-generation/example";
9
+ import CrmPipeline from "@contractspec/example.crm-pipeline/example";
10
+ import IntegrationHub from "@contractspec/example.integration-hub/example";
11
+ import IntegrationStripe from "@contractspec/example.integration-stripe/example";
12
+ import VoiceProviders from "@contractspec/example.voice-providers/example";
13
+ import KbUpdatePipeline from "@contractspec/example.kb-update-pipeline/example";
14
+ import KnowledgeCanon from "@contractspec/example.knowledge-canon/example";
15
+ import LearningPatterns from "@contractspec/example.learning-patterns/example";
16
+ import LearningJourneyAmbientCoach from "@contractspec/example.learning-journey-ambient-coach/example";
17
+ import LearningJourneyCrmOnboarding from "@contractspec/example.learning-journey-crm-onboarding/example";
18
+ import LearningJourneyDuoDrills from "@contractspec/example.learning-journey-duo-drills/example";
19
+ import LearningJourneyPlatformTour from "@contractspec/example.learning-journey-platform-tour/example";
20
+ import LearningJourneyQuestChallenges from "@contractspec/example.learning-journey-quest-challenges/example";
21
+ import LearningJourneyRegistry from "@contractspec/example.learning-journey-registry/example";
22
+ import LearningJourneyStudioOnboarding from "@contractspec/example.learning-journey-studio-onboarding/example";
23
+ import LearningJourneyUiCoaching from "@contractspec/example.learning-journey-ui-coaching/example";
24
+ import LearningJourneyUiGamified from "@contractspec/example.learning-journey-ui-gamified/example";
25
+ import LearningJourneyUiOnboarding from "@contractspec/example.learning-journey-ui-onboarding/example";
26
+ import LearningJourneyUiShared from "@contractspec/example.learning-journey-ui-shared/example";
27
+ import LifecycleCli from "@contractspec/example.lifecycle-cli/example";
28
+ import LifecycleDashboard from "@contractspec/example.lifecycle-dashboard/example";
29
+ import LocaleJurisdictionGate from "@contractspec/example.locale-jurisdiction-gate/example";
30
+ import Marketplace from "@contractspec/example.marketplace/example";
31
+ import OpenbankingPowens from "@contractspec/example.openbanking-powens/example";
32
+ import Personalization from "@contractspec/example.personalization/example";
33
+ import PolicySafeKnowledgeAssistant from "@contractspec/example.policy-safe-knowledge-assistant/example";
34
+ import SaasBoilerplate from "@contractspec/example.saas-boilerplate/example";
35
+ import ServiceBusinessOs from "@contractspec/example.service-business-os/example";
36
+ import TeamHub from "@contractspec/example.team-hub/example";
37
+ import VersionedKnowledgeBase from "@contractspec/example.versioned-knowledge-base/example";
38
+ import WealthSnapshot from "@contractspec/example.wealth-snapshot/example";
39
+ import WorkflowSystem from "@contractspec/example.workflow-system/example";
40
+ var EXAMPLE_REGISTRY = [
41
+ AgentConsole,
42
+ AiSupportBot,
43
+ AnalyticsDashboard,
44
+ ContentGeneration,
45
+ CrmPipeline,
46
+ IntegrationHub,
47
+ IntegrationStripe,
48
+ VoiceProviders,
49
+ KbUpdatePipeline,
50
+ KnowledgeCanon,
51
+ LearningPatterns,
52
+ LearningJourneyAmbientCoach,
53
+ LearningJourneyCrmOnboarding,
54
+ LearningJourneyDuoDrills,
55
+ LearningJourneyPlatformTour,
56
+ LearningJourneyQuestChallenges,
57
+ LearningJourneyRegistry,
58
+ LearningJourneyStudioOnboarding,
59
+ LearningJourneyUiCoaching,
60
+ LearningJourneyUiGamified,
61
+ LearningJourneyUiOnboarding,
62
+ LearningJourneyUiShared,
63
+ LifecycleCli,
64
+ LifecycleDashboard,
65
+ LocaleJurisdictionGate,
66
+ Marketplace,
67
+ OpenbankingPowens,
68
+ Personalization,
69
+ PolicySafeKnowledgeAssistant,
70
+ SaasBoilerplate,
71
+ ServiceBusinessOs,
72
+ TeamHub,
73
+ VersionedKnowledgeBase,
74
+ WealthSnapshot,
75
+ WorkflowSystem
76
+ ];
77
+
78
+ // src/registry.ts
79
+ import { ExampleRegistry as ExampleRegistry2 } from "@contractspec/lib.contracts";
80
+ var globalRegistry = new ExampleRegistry;
81
+ for (const example of EXAMPLE_REGISTRY) {
82
+ globalRegistry.register(example);
83
+ }
84
+ var EXAMPLE_REGISTRY2 = globalRegistry.list();
85
+ function listExamples() {
86
+ return globalRegistry.list();
87
+ }
88
+ function getExample(key) {
89
+ return globalRegistry.get(key);
90
+ }
91
+ function searchExamples(query) {
92
+ return globalRegistry.search(query);
93
+ }
94
+ // src/runtime/engine.ts
95
+ import {
96
+ createDefaultTransformEngine,
97
+ registerBasicValidation,
98
+ registerDefaultReactRenderer
99
+ } from "@contractspec/lib.contracts/presentations";
100
+ import {
101
+ agentDashboardMarkdownRenderer,
102
+ agentListMarkdownRenderer,
103
+ agentListReactRenderer,
104
+ runListMarkdownRenderer,
105
+ toolRegistryMarkdownRenderer
106
+ } from "@contractspec/example.agent-console";
107
+ import {
108
+ projectListMarkdownRenderer,
109
+ projectListReactRenderer,
110
+ saasBillingMarkdownRenderer,
111
+ saasDashboardMarkdownRenderer
112
+ } from "@contractspec/example.saas-boilerplate";
113
+ import {
114
+ crmDashboardMarkdownRenderer,
115
+ crmPipelineMarkdownRenderer,
116
+ crmPipelineReactRenderer
117
+ } from "@contractspec/example.crm-pipeline";
118
+ import {
119
+ workflowDashboardMarkdownRenderer,
120
+ workflowDefinitionListMarkdownRenderer,
121
+ workflowInstanceDetailMarkdownRenderer
122
+ } from "@contractspec/example.workflow-system";
123
+ import {
124
+ marketplaceDashboardMarkdownRenderer,
125
+ orderListMarkdownRenderer,
126
+ productCatalogMarkdownRenderer
127
+ } from "@contractspec/example.marketplace";
128
+ import {
129
+ connectionListMarkdownRenderer,
130
+ integrationDashboardMarkdownRenderer,
131
+ syncConfigMarkdownRenderer
132
+ } from "@contractspec/example.integration-hub";
133
+ import {
134
+ analyticsDashboardMarkdownRenderer,
135
+ dashboardListMarkdownRenderer,
136
+ queryBuilderMarkdownRenderer
137
+ } from "@contractspec/example.analytics-dashboard";
138
+ function createTemplateTransformEngine() {
139
+ const engine = createDefaultTransformEngine();
140
+ registerDefaultReactRenderer(engine);
141
+ registerBasicValidation(engine);
142
+ registerTemplateRenderers(engine);
143
+ return engine;
144
+ }
145
+ function registerTemplateRenderers(engine) {
146
+ engine.register(agentListReactRenderer);
147
+ engine.register(agentListMarkdownRenderer);
148
+ engine.register(runListMarkdownRenderer);
149
+ engine.register(toolRegistryMarkdownRenderer);
150
+ engine.register(agentDashboardMarkdownRenderer);
151
+ engine.register(projectListReactRenderer);
152
+ engine.register(projectListMarkdownRenderer);
153
+ engine.register(saasDashboardMarkdownRenderer);
154
+ engine.register(saasBillingMarkdownRenderer);
155
+ engine.register(crmPipelineReactRenderer);
156
+ engine.register(crmPipelineMarkdownRenderer);
157
+ engine.register(crmDashboardMarkdownRenderer);
158
+ engine.register(workflowDashboardMarkdownRenderer);
159
+ engine.register(workflowDefinitionListMarkdownRenderer);
160
+ engine.register(workflowInstanceDetailMarkdownRenderer);
161
+ engine.register(marketplaceDashboardMarkdownRenderer);
162
+ engine.register(productCatalogMarkdownRenderer);
163
+ engine.register(orderListMarkdownRenderer);
164
+ engine.register(integrationDashboardMarkdownRenderer);
165
+ engine.register(connectionListMarkdownRenderer);
166
+ engine.register(syncConfigMarkdownRenderer);
167
+ engine.register(analyticsDashboardMarkdownRenderer);
168
+ engine.register(dashboardListMarkdownRenderer);
169
+ engine.register(queryBuilderMarkdownRenderer);
170
+ }
171
+ var templateEngine = null;
172
+ function getTemplateEngine() {
173
+ if (!templateEngine) {
174
+ templateEngine = createTemplateTransformEngine();
175
+ }
176
+ return templateEngine;
177
+ }
178
+ function resetTemplateEngine() {
179
+ templateEngine = null;
180
+ }
181
+ // src/runtime/registry.ts
182
+ var PRESENTATIONS_BY_TEMPLATE = {
183
+ "saas-boilerplate": [
184
+ "saas-boilerplate.dashboard",
185
+ "saas-boilerplate.project.list",
186
+ "saas-boilerplate.billing.settings"
187
+ ],
188
+ "crm-pipeline": ["crm-pipeline.dashboard", "crm-pipeline.deal.pipeline"],
189
+ "agent-console": [
190
+ "agent-console.dashboard",
191
+ "agent-console.agent.list",
192
+ "agent-console.run.list",
193
+ "agent-console.tool.registry"
194
+ ],
195
+ "workflow-system": [
196
+ "workflow-system.dashboard",
197
+ "workflow-system.definition.list",
198
+ "workflow-system.instance.detail"
199
+ ],
200
+ marketplace: [
201
+ "marketplace.dashboard",
202
+ "marketplace.product.catalog",
203
+ "marketplace.order.list",
204
+ "marketplace.store.manage"
205
+ ],
206
+ "integration-hub": [
207
+ "integration-hub.dashboard",
208
+ "integration-hub.connection.list",
209
+ "integration-hub.sync.config"
210
+ ],
211
+ "analytics-dashboard": [
212
+ "analytics-dashboard.dashboard",
213
+ "analytics-dashboard.list",
214
+ "analytics-dashboard.query.builder"
215
+ ],
216
+ "learning-journey-studio-onboarding": [
217
+ "learning.journey.track_list",
218
+ "learning.journey.track_detail",
219
+ "learning.journey.progress_widget"
220
+ ],
221
+ "learning-journey-platform-tour": [
222
+ "learning.journey.track_list",
223
+ "learning.journey.track_detail",
224
+ "learning.journey.progress_widget"
225
+ ],
226
+ "learning-journey-crm-onboarding": [
227
+ "learning.journey.track_list",
228
+ "learning.journey.track_detail",
229
+ "learning.journey.progress_widget"
230
+ ],
231
+ "learning-journey-duo-drills": [
232
+ "learning.journey.track_list",
233
+ "learning.journey.track_detail",
234
+ "learning.journey.progress_widget"
235
+ ],
236
+ "learning-journey-ambient-coach": [
237
+ "learning.journey.track_list",
238
+ "learning.journey.track_detail",
239
+ "learning.journey.progress_widget"
240
+ ],
241
+ "learning-journey-quest-challenges": [
242
+ "learning.journey.track_list",
243
+ "learning.journey.track_detail",
244
+ "learning.journey.progress_widget"
245
+ ]
246
+ };
247
+ var TEMPLATE_REGISTRY = [
248
+ {
249
+ id: "todos-app",
250
+ name: "To-dos List App",
251
+ description: "CRUD flows, filtering, priorities, and ceremonies for handing off work across crews.",
252
+ category: "productivity",
253
+ complexity: "beginner",
254
+ icon: "✅",
255
+ features: ["CRUD tasks", "Filters", "Categories", "Search", "Priorities"],
256
+ tags: ["tasks", "ops", "starter"],
257
+ schema: {
258
+ models: ["Task", "TaskCategory"],
259
+ contracts: ["template.todos.crud"]
260
+ },
261
+ components: {
262
+ list: "TaskList",
263
+ detail: "TaskDetailPanel",
264
+ form: "TaskForm"
265
+ },
266
+ preview: {
267
+ demoUrl: "/sandbox?template=todos-app"
268
+ },
269
+ docs: {
270
+ quickstart: "/docs/templates/todos-app"
271
+ }
272
+ },
273
+ {
274
+ id: "messaging-app",
275
+ name: "Messaging Application",
276
+ description: "Conversation roster, optimistic sending, typing indicators, and delivery telemetry.",
277
+ category: "communication",
278
+ complexity: "intermediate",
279
+ icon: "\uD83D\uDCAC",
280
+ features: [
281
+ "Conversations",
282
+ "Real-time feed",
283
+ "Typing indicators",
284
+ "Read receipts"
285
+ ],
286
+ tags: ["messaging", "realtime", "ws"],
287
+ schema: {
288
+ models: ["Conversation", "ConversationParticipant", "Message"],
289
+ contracts: ["template.messaging.core"]
290
+ },
291
+ components: {
292
+ list: "ConversationList",
293
+ detail: "MessageThread",
294
+ form: "MessageComposer"
295
+ },
296
+ preview: {
297
+ demoUrl: "/sandbox?template=messaging-app"
298
+ },
299
+ docs: {
300
+ quickstart: "/docs/templates/messaging-app"
301
+ }
302
+ },
303
+ {
304
+ id: "recipe-app-i18n",
305
+ name: "Recipe App (i18n)",
306
+ description: "Localized browsing experience with bilingual content, categories, and favorites.",
307
+ category: "content",
308
+ complexity: "intermediate",
309
+ icon: "\uD83C\uDF72",
310
+ features: ["i18n", "Favorites", "Categories", "Search", "RTL-ready"],
311
+ tags: ["content", "i18n", "localization"],
312
+ schema: {
313
+ models: [
314
+ "RecipeCategory",
315
+ "Recipe",
316
+ "RecipeIngredient",
317
+ "RecipeInstruction"
318
+ ],
319
+ contracts: ["template.recipes.browse"]
320
+ },
321
+ components: {
322
+ list: "RecipeList",
323
+ detail: "RecipeDetail",
324
+ form: "RecipeForm"
325
+ },
326
+ preview: {
327
+ demoUrl: "/sandbox?template=recipe-app-i18n"
328
+ },
329
+ docs: {
330
+ quickstart: "/docs/templates/recipe-app-i18n"
331
+ }
332
+ },
333
+ ...listExamples().map((example) => {
334
+ const tags = example.meta.keywords ?? [];
335
+ const category = tags.some((t) => t.toLowerCase() === "ai") || tags.some((t) => t.toLowerCase() === "assistant") ? "ai" : "business";
336
+ const complexity = "beginner";
337
+ const icon = "\uD83D\uDCE6";
338
+ return {
339
+ id: example.meta.key,
340
+ name: example.meta.title ?? example.meta.key,
341
+ description: example.meta.description ?? "",
342
+ category,
343
+ complexity,
344
+ icon,
345
+ features: [],
346
+ tags: [...tags],
347
+ schema: { models: [], contracts: [] },
348
+ components: { list: "ExampleList", detail: "ExampleDetail" },
349
+ preview: {
350
+ demoUrl: `/sandbox?template=${encodeURIComponent(example.meta.key)}`
351
+ },
352
+ package: example.entrypoints.packageName,
353
+ presentations: PRESENTATIONS_BY_TEMPLATE[example.meta.key] ?? [],
354
+ renderTargets: ["react", "markdown"]
355
+ };
356
+ })
357
+ ];
358
+ function listTemplates(filter) {
359
+ if (!filter)
360
+ return TEMPLATE_REGISTRY;
361
+ return TEMPLATE_REGISTRY.filter((template) => {
362
+ if (filter.category && template.category !== filter.category) {
363
+ return false;
364
+ }
365
+ if (filter.complexity && template.complexity !== filter.complexity) {
366
+ return false;
367
+ }
368
+ if (filter.tag && !template.tags.some((tag) => tag.toLowerCase() === filter.tag?.toLowerCase())) {
369
+ return false;
370
+ }
371
+ return true;
372
+ });
373
+ }
374
+ function getTemplate(id) {
375
+ return TEMPLATE_REGISTRY.find((template) => template.id === id);
376
+ }
377
+ function getTemplatesByModule(modulePackage) {
378
+ return TEMPLATE_REGISTRY.filter((template) => template.usesModules?.includes(modulePackage));
379
+ }
380
+ function getClonableTemplates() {
381
+ return TEMPLATE_REGISTRY.filter((template) => !!template.package);
382
+ }
383
+
384
+ // src/runtime/registry-client.ts
385
+ class ContractSpecRegistryClient {
386
+ baseUrl;
387
+ fetchImpl;
388
+ constructor(options) {
389
+ this.baseUrl = options.registryUrl.replace(/\/+$/, "");
390
+ this.fetchImpl = options.fetchImpl ?? fetch;
391
+ }
392
+ async getManifest() {
393
+ const res = await this.fetchImpl(`${this.baseUrl}/r/contractspec.json`, {
394
+ method: "GET",
395
+ headers: { Accept: "application/json" }
396
+ });
397
+ if (!res.ok) {
398
+ throw new Error(`Registry manifest fetch failed: ${res.status} ${res.statusText}`);
399
+ }
400
+ return await res.json();
401
+ }
402
+ async listByType(type) {
403
+ const manifest = await this.getManifest();
404
+ return manifest.items.filter((i) => i.type === type);
405
+ }
406
+ async listTemplateSummaries() {
407
+ const templates = await this.listByType("contractspec:template");
408
+ return templates.map((t) => ({
409
+ id: t.key,
410
+ title: t.title,
411
+ description: t.description,
412
+ version: t.version,
413
+ tags: t.meta.tags,
414
+ source: "registry"
415
+ }));
416
+ }
417
+ async getItem(typeSegment, name) {
418
+ const res = await this.fetchImpl(`${this.baseUrl}/r/contractspec/${typeSegment}/${name}.json`, {
419
+ method: "GET",
420
+ headers: { Accept: "application/json" }
421
+ });
422
+ if (!res.ok) {
423
+ throw new Error(`Registry item fetch failed: ${res.status} ${res.statusText}`);
424
+ }
425
+ return await res.json();
426
+ }
427
+ }
428
+
429
+ // src/runtime/installer.ts
430
+ import { web } from "@contractspec/lib.runtime-sandbox";
431
+ "use client";
432
+ var { LocalRuntimeServices } = web;
433
+ var SAVE_TEMPLATE_MUTATION = `
434
+ mutation SaveTemplateToStudio($input: SaveTemplateInput!) {
435
+ saveTemplateToStudio(input: $input) {
436
+ projectId
437
+ status
438
+ }
439
+ }
440
+ `;
441
+
442
+ class TemplateInstaller {
443
+ runtime;
444
+ endpoint;
445
+ registryUrl;
446
+ fetchImpl;
447
+ constructor(options = {}) {
448
+ this.runtime = options.runtime ?? new LocalRuntimeServices;
449
+ this.endpoint = options.endpoint ?? "/api/graphql";
450
+ this.registryUrl = options.registryUrl ? options.registryUrl.replace(/\/+$/, "") : null;
451
+ this.fetchImpl = options.fetchImpl ?? fetch;
452
+ }
453
+ async init() {
454
+ await this.runtime.init();
455
+ }
456
+ list(filter) {
457
+ return filter ? TEMPLATE_REGISTRY.filter((template) => {
458
+ if (filter.category && filter.category !== template.category) {
459
+ return false;
460
+ }
461
+ if (filter.complexity && filter.complexity !== template.complexity) {
462
+ return false;
463
+ }
464
+ if (filter.tag && !template.tags.includes(filter.tag)) {
465
+ return false;
466
+ }
467
+ return true;
468
+ }) : TEMPLATE_REGISTRY;
469
+ }
470
+ async listRemoteTemplates() {
471
+ if (!this.registryUrl)
472
+ return [];
473
+ const client = new ContractSpecRegistryClient({
474
+ registryUrl: this.registryUrl,
475
+ fetchImpl: this.fetchImpl
476
+ });
477
+ return await client.listTemplateSummaries();
478
+ }
479
+ resolveLocalTemplateId(id) {
480
+ const found = getTemplate(id);
481
+ return found ? id : null;
482
+ }
483
+ get(templateId) {
484
+ return getTemplate(templateId);
485
+ }
486
+ async install(templateId, options = {}) {
487
+ await this.runtime.seedTemplate({
488
+ templateId,
489
+ projectId: options.projectId
490
+ });
491
+ }
492
+ async saveToStudio(options) {
493
+ const snapshot = await this.runtime.db.export();
494
+ const payload = toBase64(snapshot);
495
+ const response = await this.fetchImpl(options.endpoint ?? this.endpoint, {
496
+ method: "POST",
497
+ headers: {
498
+ "Content-Type": "application/json",
499
+ ...options.token ? { Authorization: `Bearer ${options.token}` } : {}
500
+ },
501
+ body: JSON.stringify({
502
+ query: SAVE_TEMPLATE_MUTATION,
503
+ variables: {
504
+ input: {
505
+ templateId: options.templateId,
506
+ projectName: options.projectName,
507
+ organizationId: options.organizationId,
508
+ payload
509
+ }
510
+ }
511
+ })
512
+ });
513
+ if (!response.ok) {
514
+ throw new Error(`Failed to save template: ${response.status} ${response.statusText}`);
515
+ }
516
+ const json = await response.json();
517
+ if (json.errors?.length) {
518
+ throw new Error(json.errors[0]?.message ?? "Unknown error");
519
+ }
520
+ if (!json.data?.saveTemplateToStudio) {
521
+ throw new Error("Invalid response from Studio API");
522
+ }
523
+ return json.data.saveTemplateToStudio;
524
+ }
525
+ }
526
+ function toBase64(bytes) {
527
+ if (typeof Buffer !== "undefined") {
528
+ return Buffer.from(bytes).toString("base64");
529
+ }
530
+ let binary = "";
531
+ bytes.forEach((value) => {
532
+ binary += String.fromCharCode(value);
533
+ });
534
+ return btoa(binary);
535
+ }
536
+ // src/runtime/context.tsx
537
+ import { useEffect, useMemo, useState } from "react";
538
+ import { ApolloProvider } from "@apollo/client/react";
539
+ import { web as web2 } from "@contractspec/lib.runtime-sandbox";
540
+ import {
541
+ createCrmHandlers
542
+ } from "@contractspec/example.crm-pipeline";
543
+ import {
544
+ createSaasHandlers
545
+ } from "@contractspec/example.saas-boilerplate";
546
+ import {
547
+ createAgentHandlers
548
+ } from "@contractspec/example.agent-console";
549
+ import {
550
+ createWorkflowHandlers
551
+ } from "@contractspec/example.workflow-system";
552
+ import {
553
+ createMarketplaceHandlers
554
+ } from "@contractspec/example.marketplace";
555
+ import {
556
+ createIntegrationHandlers
557
+ } from "@contractspec/example.integration-hub";
558
+ import {
559
+ createAnalyticsHandlers
560
+ } from "@contractspec/example.analytics-dashboard";
561
+ import {
562
+ createPolicySafeKnowledgeAssistantHandlers
563
+ } from "@contractspec/example.policy-safe-knowledge-assistant";
564
+ import {
565
+ TemplateRuntimeContext,
566
+ useTemplateRuntime,
567
+ useTemplateComponents
568
+ } from "@contractspec/lib.example-shared-ui";
569
+ import { jsxDEV } from "react/jsx-dev-runtime";
570
+ "use client";
571
+ var { LocalRuntimeServices: LocalRuntimeServices2 } = web2;
572
+ function logBootstrapFailure(error) {
573
+ console.error(`
574
+ [TemplateRuntime] Bootstrap Failed
575
+ ==================================
576
+
577
+ The runtime failed to initialize. This usually happens because:
578
+ 1. The PostgreSQL Web environment (pglite) failed to load
579
+ 2. The schema migration failed
580
+ 3. The initial seed data could not be inserted
581
+
582
+ Check the console for specific database errors.
583
+ `.trim(), error);
584
+ }
585
+
586
+ class TemplateHandlers {
587
+ crm;
588
+ saas;
589
+ agent;
590
+ workflow;
591
+ marketplace;
592
+ integration;
593
+ analytics;
594
+ policySafeKnowledgeAssistant;
595
+ }
596
+ function TemplateRuntimeProvider({
597
+ templateId,
598
+ projectId = "default-project",
599
+ lazy = false,
600
+ children
601
+ }) {
602
+ const [context, setContext] = useState(null);
603
+ const [error, setError] = useState(null);
604
+ useEffect(() => {
605
+ let mounted = true;
606
+ async function bootstrap() {
607
+ try {
608
+ if (lazy)
609
+ return;
610
+ const template = getTemplate(templateId);
611
+ if (!template) {
612
+ throw new Error(`Template not found: ${templateId}`);
613
+ }
614
+ const runtime = new LocalRuntimeServices2;
615
+ await runtime.init({});
616
+ const installer = new TemplateInstaller({ runtime });
617
+ await installer.install(templateId, { projectId });
618
+ const client = web2.createLocalGraphqlClient(runtime);
619
+ const engine = await getTemplateEngine();
620
+ const handlers = new TemplateHandlers;
621
+ handlers.crm = createCrmHandlers(runtime.db);
622
+ handlers.saas = createSaasHandlers(runtime.db);
623
+ handlers.agent = createAgentHandlers(runtime.db);
624
+ handlers.workflow = createWorkflowHandlers(runtime.db);
625
+ handlers.marketplace = createMarketplaceHandlers(runtime.db);
626
+ handlers.integration = createIntegrationHandlers(runtime.db);
627
+ handlers.analytics = createAnalyticsHandlers(runtime.db);
628
+ handlers.policySafeKnowledgeAssistant = createPolicySafeKnowledgeAssistantHandlers(runtime.db);
629
+ const fetchData = async (presentationName) => {
630
+ if (presentationName === "crm-pipeline.dashboard") {
631
+ const [dealsResult, stages] = await Promise.all([
632
+ handlers.crm.listDeals({
633
+ projectId,
634
+ pipelineId: "pipeline-1",
635
+ limit: 50
636
+ }),
637
+ handlers.crm.getPipelineStages({ pipelineId: "pipeline-1" })
638
+ ]);
639
+ return {
640
+ data: {
641
+ deals: dealsResult.deals,
642
+ stages,
643
+ summary: {
644
+ total: dealsResult.total,
645
+ totalValue: dealsResult.totalValue
646
+ }
647
+ },
648
+ metadata: {
649
+ total: dealsResult.total,
650
+ timestamp: new Date,
651
+ source: "crm-pipeline"
652
+ }
653
+ };
654
+ }
655
+ if (presentationName === "crm-pipeline.deal.pipeline") {
656
+ const [dealsResult, stages] = await Promise.all([
657
+ handlers.crm.listDeals({
658
+ projectId,
659
+ pipelineId: "pipeline-1",
660
+ limit: 100
661
+ }),
662
+ handlers.crm.getPipelineStages({ pipelineId: "pipeline-1" })
663
+ ]);
664
+ return {
665
+ data: {
666
+ deals: dealsResult.deals,
667
+ stages,
668
+ total: dealsResult.total,
669
+ totalValue: dealsResult.totalValue
670
+ },
671
+ metadata: {
672
+ total: dealsResult.total,
673
+ timestamp: new Date,
674
+ source: "crm-pipeline"
675
+ }
676
+ };
677
+ }
678
+ if (presentationName === "saas-boilerplate.dashboard") {
679
+ const [projectsResult, subscription] = await Promise.all([
680
+ handlers.saas.listProjects({ projectId, limit: 10 }),
681
+ handlers.saas.getSubscription({ projectId })
682
+ ]);
683
+ return {
684
+ data: {
685
+ projects: projectsResult.items,
686
+ subscription,
687
+ summary: { totalProjects: projectsResult.total }
688
+ },
689
+ metadata: {
690
+ total: projectsResult.total,
691
+ timestamp: new Date,
692
+ source: "saas-boilerplate"
693
+ }
694
+ };
695
+ }
696
+ if (presentationName === "saas-boilerplate.project.list") {
697
+ const result = await handlers.saas.listProjects({
698
+ projectId,
699
+ limit: 50
700
+ });
701
+ return {
702
+ data: result.items,
703
+ metadata: {
704
+ total: result.total,
705
+ timestamp: new Date,
706
+ source: "saas-boilerplate"
707
+ }
708
+ };
709
+ }
710
+ if (presentationName === "saas-boilerplate.billing.settings") {
711
+ const subscription = await handlers.saas.getSubscription({
712
+ projectId
713
+ });
714
+ return {
715
+ data: subscription,
716
+ metadata: { timestamp: new Date, source: "saas-boilerplate" }
717
+ };
718
+ }
719
+ if (presentationName === "agent-console.dashboard") {
720
+ const [agentsResult, runsResult, toolsResult] = await Promise.all([
721
+ handlers.agent.listAgents({
722
+ projectId,
723
+ organizationId: "demo-org",
724
+ limit: 10
725
+ }),
726
+ handlers.agent.listRuns({ projectId, limit: 10 }),
727
+ handlers.agent.listTools({
728
+ projectId,
729
+ organizationId: "demo-org",
730
+ limit: 10
731
+ })
732
+ ]);
733
+ return {
734
+ data: {
735
+ agents: agentsResult.items,
736
+ runs: runsResult.items,
737
+ tools: toolsResult.items,
738
+ summary: {
739
+ totalAgents: agentsResult.total,
740
+ totalRuns: runsResult.total,
741
+ totalTools: toolsResult.total
742
+ }
743
+ },
744
+ metadata: { timestamp: new Date, source: "agent-console" }
745
+ };
746
+ }
747
+ if (presentationName === "agent-console.agent.list") {
748
+ const result = await handlers.agent.listAgents({
749
+ projectId,
750
+ organizationId: "demo-org",
751
+ limit: 50
752
+ });
753
+ return {
754
+ data: result.items,
755
+ metadata: {
756
+ total: result.total,
757
+ timestamp: new Date,
758
+ source: "agent-console"
759
+ }
760
+ };
761
+ }
762
+ if (presentationName === "agent-console.run.list") {
763
+ const result = await handlers.agent.listRuns({
764
+ projectId,
765
+ limit: 50
766
+ });
767
+ return {
768
+ data: result.items,
769
+ metadata: {
770
+ total: result.total,
771
+ timestamp: new Date,
772
+ source: "agent-console"
773
+ }
774
+ };
775
+ }
776
+ if (presentationName === "agent-console.tool.registry") {
777
+ const result = await handlers.agent.listTools({
778
+ projectId,
779
+ organizationId: "demo-org",
780
+ limit: 50
781
+ });
782
+ return {
783
+ data: result.items,
784
+ metadata: {
785
+ total: result.total,
786
+ timestamp: new Date,
787
+ source: "agent-console"
788
+ }
789
+ };
790
+ }
791
+ console.warn(`No data fetcher found for presentation: ${presentationName}`);
792
+ return {
793
+ data: null,
794
+ metadata: { timestamp: new Date, source: "unknown" }
795
+ };
796
+ };
797
+ if (mounted) {
798
+ setContext({
799
+ template,
800
+ runtime,
801
+ installer,
802
+ client,
803
+ templateId,
804
+ projectId,
805
+ engine,
806
+ handlers,
807
+ fetchData
808
+ });
809
+ }
810
+ } catch (err) {
811
+ logBootstrapFailure(err);
812
+ if (mounted) {
813
+ setError(err instanceof Error ? err : new Error("Unknown runtime error"));
814
+ }
815
+ }
816
+ }
817
+ bootstrap();
818
+ return () => {
819
+ mounted = false;
820
+ };
821
+ }, [templateId, projectId, lazy]);
822
+ const components = useTemplateComponents(templateId);
823
+ const contextValue = useMemo(() => {
824
+ if (!context)
825
+ return null;
826
+ return {
827
+ ...context,
828
+ components
829
+ };
830
+ }, [context, components]);
831
+ if (error) {
832
+ return /* @__PURE__ */ jsxDEV("div", {
833
+ className: "rounded border border-red-200 bg-red-50 p-4 text-red-500",
834
+ children: [
835
+ /* @__PURE__ */ jsxDEV("h3", {
836
+ className: "font-bold",
837
+ children: "Runtime Error"
838
+ }, undefined, false, undefined, this),
839
+ /* @__PURE__ */ jsxDEV("pre", {
840
+ className: "mt-2 overflow-auto text-xs",
841
+ children: error.message
842
+ }, undefined, false, undefined, this)
843
+ ]
844
+ }, undefined, true, undefined, this);
845
+ }
846
+ if (!contextValue) {
847
+ return /* @__PURE__ */ jsxDEV("div", {
848
+ className: "animate-pulse p-12 text-center text-gray-400",
849
+ children: "Initializing runtime environment..."
850
+ }, undefined, false, undefined, this);
851
+ }
852
+ return /* @__PURE__ */ jsxDEV(ApolloProvider, {
853
+ client: contextValue.client,
854
+ children: /* @__PURE__ */ jsxDEV(TemplateRuntimeContext.Provider, {
855
+ value: contextValue,
856
+ children
857
+ }, undefined, false, undefined, this)
858
+ }, undefined, false, undefined, this);
859
+ }
860
+ function useTemplateEngine() {
861
+ return useTemplateRuntime().engine;
862
+ }
863
+ function useTemplateHandlers() {
864
+ return useTemplateRuntime().handlers;
865
+ }
866
+ function useCrmHandlers() {
867
+ return useTemplateHandlers().crm;
868
+ }
869
+ function useSaasHandlers() {
870
+ return useTemplateHandlers().saas;
871
+ }
872
+ function useAgentHandlers() {
873
+ return useTemplateHandlers().agent;
874
+ }
875
+ function useWorkflowHandlers() {
876
+ return useTemplateHandlers().workflow;
877
+ }
878
+ function useMarketplaceHandlers() {
879
+ return useTemplateHandlers().marketplace;
880
+ }
881
+ function useIntegrationHandlers() {
882
+ return useTemplateHandlers().integration;
883
+ }
884
+ function useAnalyticsHandlers() {
885
+ return useTemplateHandlers().analytics;
886
+ }
887
+ export {
888
+ useWorkflowHandlers,
889
+ useTemplateHandlers,
890
+ useTemplateEngine,
891
+ useSaasHandlers,
892
+ useMarketplaceHandlers,
893
+ useIntegrationHandlers,
894
+ useCrmHandlers,
895
+ useAnalyticsHandlers,
896
+ useAgentHandlers,
897
+ searchExamples,
898
+ resetTemplateEngine,
899
+ listTemplates,
900
+ listExamples,
901
+ getTemplatesByModule,
902
+ getTemplateEngine,
903
+ getTemplate,
904
+ getExample,
905
+ getClonableTemplates,
906
+ createTemplateTransformEngine,
907
+ TemplateRuntimeProvider,
908
+ TemplateInstaller,
909
+ TemplateHandlers,
910
+ TEMPLATE_REGISTRY,
911
+ ExampleRegistry2 as ExampleRegistry,
912
+ EXAMPLE_REGISTRY2 as EXAMPLE_REGISTRY
913
+ };