@contractspec/example.integration-hub 3.8.9 → 3.8.10

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 (89) hide show
  1. package/dist/connection/connection.enum.js +1 -29
  2. package/dist/connection/connection.operation.js +1 -124
  3. package/dist/connection/connection.presentation.js +1 -125
  4. package/dist/connection/connection.schema.js +1 -71
  5. package/dist/connection/index.js +1 -127
  6. package/dist/docs/index.js +5 -49
  7. package/dist/docs/integration-hub.docblock.js +5 -49
  8. package/dist/events.js +1 -211
  9. package/dist/example.js +1 -42
  10. package/dist/handlers/index.js +5 -292
  11. package/dist/handlers/integration.handlers.js +5 -292
  12. package/dist/index.js +8 -2355
  13. package/dist/integration/index.js +1 -92
  14. package/dist/integration/integration.enum.js +1 -12
  15. package/dist/integration/integration.operations.js +1 -89
  16. package/dist/integration/integration.presentation.js +1 -120
  17. package/dist/integration/integration.schema.js +1 -42
  18. package/dist/integration-hub.capability.js +1 -43
  19. package/dist/integration-hub.feature.js +1 -330
  20. package/dist/mcp-example.js +1 -154
  21. package/dist/node/connection/connection.enum.js +1 -29
  22. package/dist/node/connection/connection.operation.js +1 -124
  23. package/dist/node/connection/connection.presentation.js +1 -125
  24. package/dist/node/connection/connection.schema.js +1 -71
  25. package/dist/node/connection/index.js +1 -127
  26. package/dist/node/docs/index.js +5 -49
  27. package/dist/node/docs/integration-hub.docblock.js +5 -49
  28. package/dist/node/events.js +1 -211
  29. package/dist/node/example.js +1 -42
  30. package/dist/node/handlers/index.js +5 -292
  31. package/dist/node/handlers/integration.handlers.js +5 -292
  32. package/dist/node/index.js +8 -2355
  33. package/dist/node/integration/index.js +1 -92
  34. package/dist/node/integration/integration.enum.js +1 -12
  35. package/dist/node/integration/integration.operations.js +1 -89
  36. package/dist/node/integration/integration.presentation.js +1 -120
  37. package/dist/node/integration/integration.schema.js +1 -42
  38. package/dist/node/integration-hub.capability.js +1 -43
  39. package/dist/node/integration-hub.feature.js +1 -330
  40. package/dist/node/mcp-example.js +1 -154
  41. package/dist/node/run-mcp.js +1 -159
  42. package/dist/node/seeders/index.js +6 -60
  43. package/dist/node/sync/index.js +1 -332
  44. package/dist/node/sync/sync.enum.js +1 -26
  45. package/dist/node/sync/sync.operations.js +1 -321
  46. package/dist/node/sync/sync.presentation.js +1 -301
  47. package/dist/node/sync/sync.schema.js +1 -154
  48. package/dist/node/sync-engine/index.js +1 -186
  49. package/dist/node/tests/operations.test-spec.js +1 -85
  50. package/dist/node/ui/IntegrationDashboard.js +1 -886
  51. package/dist/node/ui/IntegrationDashboard.visualizations.js +1 -250
  52. package/dist/node/ui/IntegrationHubChat.js +1 -34
  53. package/dist/node/ui/hooks/index.js +1 -57
  54. package/dist/node/ui/hooks/useIntegrationData.js +1 -54
  55. package/dist/node/ui/index.js +4 -1173
  56. package/dist/node/ui/renderers/index.js +4 -484
  57. package/dist/node/ui/renderers/integration.markdown.js +4 -484
  58. package/dist/node/ui/tables/ConnectionsTable.js +1 -211
  59. package/dist/node/ui/tables/IntegrationTables.js +1 -361
  60. package/dist/node/ui/tables/SyncConfigsTable.js +1 -230
  61. package/dist/node/ui/tables/integration-table.shared.js +1 -84
  62. package/dist/node/visualizations/catalog.js +1 -137
  63. package/dist/node/visualizations/index.js +1 -211
  64. package/dist/node/visualizations/selectors.js +1 -204
  65. package/dist/run-mcp.js +1 -159
  66. package/dist/seeders/index.js +6 -60
  67. package/dist/sync/index.js +1 -332
  68. package/dist/sync/sync.enum.js +1 -26
  69. package/dist/sync/sync.operations.js +1 -321
  70. package/dist/sync/sync.presentation.js +1 -301
  71. package/dist/sync/sync.schema.js +1 -154
  72. package/dist/sync-engine/index.js +1 -186
  73. package/dist/tests/operations.test-spec.js +1 -85
  74. package/dist/ui/IntegrationDashboard.js +1 -886
  75. package/dist/ui/IntegrationDashboard.visualizations.js +1 -250
  76. package/dist/ui/IntegrationHubChat.js +1 -34
  77. package/dist/ui/hooks/index.js +1 -57
  78. package/dist/ui/hooks/useIntegrationData.js +1 -54
  79. package/dist/ui/index.js +4 -1173
  80. package/dist/ui/renderers/index.js +4 -484
  81. package/dist/ui/renderers/integration.markdown.js +4 -484
  82. package/dist/ui/tables/ConnectionsTable.js +1 -211
  83. package/dist/ui/tables/IntegrationTables.js +1 -361
  84. package/dist/ui/tables/SyncConfigsTable.js +1 -230
  85. package/dist/ui/tables/integration-table.shared.js +1 -84
  86. package/dist/visualizations/catalog.js +1 -137
  87. package/dist/visualizations/index.js +1 -211
  88. package/dist/visualizations/selectors.js +1 -204
  89. package/package.json +11 -11
package/dist/index.js CHANGED
@@ -1,2356 +1,9 @@
1
1
  // @bun
2
- // src/connection/connection.enum.ts
3
- import { defineEnum } from "@contractspec/lib.schema";
4
- var ConnectionStatusEnum = defineEnum("ConnectionStatus", [
5
- "PENDING",
6
- "CONNECTED",
7
- "DISCONNECTED",
8
- "ERROR",
9
- "EXPIRED"
10
- ]);
11
- var AuthTypeEnum = defineEnum("AuthType", [
12
- "api_key",
13
- "oauth2",
14
- "bearer",
15
- "header",
16
- "basic",
17
- "webhook_signing",
18
- "service_account"
19
- ]);
20
- var TransportTypeEnum = defineEnum("TransportType", [
21
- "rest",
22
- "mcp",
23
- "webhook",
24
- "sdk"
25
- ]);
26
-
27
- // src/connection/connection.schema.ts
28
- import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
29
- var ConnectionModel = defineSchemaModel({
30
- name: "ConnectionModel",
31
- fields: {
32
- id: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
33
- integrationId: {
34
- type: ScalarTypeEnum.String_unsecure(),
35
- isOptional: false
36
- },
37
- name: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
38
- status: { type: ConnectionStatusEnum, isOptional: false },
39
- authType: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
40
- externalAccountName: {
41
- type: ScalarTypeEnum.String_unsecure(),
42
- isOptional: true
43
- },
44
- connectedAt: { type: ScalarTypeEnum.DateTime(), isOptional: true },
45
- lastHealthCheck: { type: ScalarTypeEnum.DateTime(), isOptional: true },
46
- healthStatus: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
47
- transport: { type: TransportTypeEnum, isOptional: true },
48
- authMethod: { type: AuthTypeEnum, isOptional: true },
49
- apiVersion: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
50
- ownershipMode: { type: ScalarTypeEnum.String_unsecure(), isOptional: true }
51
- }
52
- });
53
- var CreateConnectionInputModel = defineSchemaModel({
54
- name: "CreateConnectionInput",
55
- fields: {
56
- integrationId: {
57
- type: ScalarTypeEnum.String_unsecure(),
58
- isOptional: false
59
- },
60
- name: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
61
- authType: { type: ScalarTypeEnum.NonEmptyString(), isOptional: false },
62
- credentials: { type: ScalarTypeEnum.JSON(), isOptional: true },
63
- transport: { type: TransportTypeEnum, isOptional: true },
64
- authMethod: { type: AuthTypeEnum, isOptional: true },
65
- apiVersion: { type: ScalarTypeEnum.String_unsecure(), isOptional: true },
66
- ownershipMode: { type: ScalarTypeEnum.String_unsecure(), isOptional: true }
67
- }
68
- });
69
-
70
- // src/connection/connection.operation.ts
71
- import { defineCommand } from "@contractspec/lib.contracts-spec/operations";
72
- var OWNERS = ["@example.integration-hub"];
73
- var CreateConnectionContract = defineCommand({
74
- meta: {
75
- key: "integration.connection.create",
76
- version: "1.0.0",
77
- stability: "stable",
78
- owners: [...OWNERS],
79
- tags: ["integration", "connection", "create"],
80
- description: "Create a connection to an external system.",
81
- goal: "Authenticate with external systems.",
82
- context: "Connection setup."
83
- },
84
- io: { input: CreateConnectionInputModel, output: ConnectionModel },
85
- policy: { auth: "user" },
86
- sideEffects: {
87
- emits: [
88
- {
89
- key: "integration.connection.created",
90
- version: "1.0.0",
91
- when: "Connection created",
92
- payload: ConnectionModel
93
- }
94
- ],
95
- audit: ["integration.connection.created"]
96
- },
97
- acceptance: {
98
- scenarios: [
99
- {
100
- key: "create-connection-happy-path",
101
- given: ["User is authenticated"],
102
- when: ["User creates connection with valid credentials"],
103
- then: ["Connection is created", "ConnectionCreated event is emitted"]
104
- }
105
- ],
106
- examples: [
107
- {
108
- key: "connect-crm",
109
- input: {
110
- name: "Salesforce Prod",
111
- integrationId: "salesforce",
112
- credentials: { clientId: "xxx" }
113
- },
114
- output: {
115
- id: "conn-123",
116
- status: "connected",
117
- connectedAt: "2025-01-01T12:00:00Z"
118
- }
119
- }
120
- ]
121
- }
122
- });
123
- // src/handlers/integration.handlers.ts
124
- import { web } from "@contractspec/lib.runtime-sandbox";
125
- var { generateId } = web;
126
- function rowToIntegration(row) {
127
- return {
128
- id: row.id,
129
- projectId: row.projectId,
130
- organizationId: row.organizationId,
131
- name: row.name,
132
- description: row.description ?? undefined,
133
- type: row.type,
134
- status: row.status,
135
- iconUrl: row.iconUrl ?? undefined,
136
- createdAt: new Date(row.createdAt),
137
- updatedAt: new Date(row.updatedAt)
138
- };
139
- }
140
- function rowToConnection(row) {
141
- return {
142
- id: row.id,
143
- integrationId: row.integrationId,
144
- name: row.name,
145
- status: row.status,
146
- credentials: row.credentials ? JSON.parse(row.credentials) : undefined,
147
- config: row.config ? JSON.parse(row.config) : undefined,
148
- lastSyncAt: row.lastSyncAt ? new Date(row.lastSyncAt) : undefined,
149
- errorMessage: row.errorMessage ?? undefined,
150
- createdAt: new Date(row.createdAt),
151
- updatedAt: new Date(row.updatedAt)
152
- };
153
- }
154
- function rowToSyncConfig(row) {
155
- return {
156
- id: row.id,
157
- connectionId: row.connectionId,
158
- name: row.name,
159
- sourceEntity: row.sourceEntity,
160
- targetEntity: row.targetEntity,
161
- frequency: row.frequency,
162
- status: row.status,
163
- lastRunAt: row.lastRunAt ? new Date(row.lastRunAt) : undefined,
164
- lastRunStatus: row.lastRunStatus ?? undefined,
165
- recordsSynced: row.recordsSynced,
166
- createdAt: new Date(row.createdAt),
167
- updatedAt: new Date(row.updatedAt)
168
- };
169
- }
170
- function rowToFieldMapping(row) {
171
- return {
172
- id: row.id,
173
- syncConfigId: row.syncConfigId,
174
- sourceField: row.sourceField,
175
- targetField: row.targetField,
176
- transformType: row.transformType ?? undefined,
177
- transformConfig: row.transformConfig ? JSON.parse(row.transformConfig) : undefined,
178
- createdAt: new Date(row.createdAt)
179
- };
180
- }
181
- function createIntegrationHandlers(db) {
182
- async function listIntegrations(input) {
183
- const { projectId, type, status, search, limit = 20, offset = 0 } = input;
184
- let whereClause = "WHERE projectId = ?";
185
- const params = [projectId];
186
- if (type && type !== "all") {
187
- whereClause += " AND type = ?";
188
- params.push(type);
189
- }
190
- if (status && status !== "all") {
191
- whereClause += " AND status = ?";
192
- params.push(status);
193
- }
194
- if (search) {
195
- whereClause += " AND name LIKE ?";
196
- params.push(`%${search}%`);
197
- }
198
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM integration ${whereClause}`, params)).rows;
199
- const total = countResult[0]?.count ?? 0;
200
- const rows = (await db.query(`SELECT * FROM integration ${whereClause} ORDER BY name LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
201
- return {
202
- integrations: rows.map(rowToIntegration),
203
- total
204
- };
205
- }
206
- async function createIntegration(input, context) {
207
- const id = generateId("integ");
208
- const now = new Date().toISOString();
209
- await db.execute(`INSERT INTO integration (id, projectId, organizationId, name, description, type, status, iconUrl, createdAt, updatedAt)
210
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
211
- id,
212
- context.projectId,
213
- context.organizationId,
214
- input.name,
215
- input.description ?? null,
216
- input.type,
217
- "INACTIVE",
218
- input.iconUrl ?? null,
219
- now,
220
- now
221
- ]);
222
- const rows = (await db.query(`SELECT * FROM integration WHERE id = ?`, [id])).rows;
223
- return rowToIntegration(rows[0]);
224
- }
225
- async function listConnections(input) {
226
- const { integrationId, status, limit = 20, offset = 0 } = input;
227
- let whereClause = "WHERE 1=1";
228
- const params = [];
229
- if (integrationId) {
230
- whereClause += " AND integrationId = ?";
231
- params.push(integrationId);
232
- }
233
- if (status && status !== "all") {
234
- whereClause += " AND status = ?";
235
- params.push(status);
236
- }
237
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM integration_connection ${whereClause}`, params)).rows;
238
- const total = countResult[0]?.count ?? 0;
239
- const rows = (await db.query(`SELECT * FROM integration_connection ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
240
- return {
241
- connections: rows.map(rowToConnection),
242
- total
243
- };
244
- }
245
- async function connectService(input) {
246
- const id = generateId("conn");
247
- const now = new Date().toISOString();
248
- await db.execute(`INSERT INTO integration_connection (id, integrationId, name, status, credentials, config, createdAt, updatedAt)
249
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [
250
- id,
251
- input.integrationId,
252
- input.name,
253
- "PENDING",
254
- input.credentials ? JSON.stringify(input.credentials) : null,
255
- input.config ? JSON.stringify(input.config) : null,
256
- now,
257
- now
258
- ]);
259
- await db.execute(`UPDATE integration_connection SET status = 'CONNECTED', updatedAt = ? WHERE id = ?`, [now, id]);
260
- await db.execute(`UPDATE integration SET status = 'ACTIVE', updatedAt = ? WHERE id = ?`, [now, input.integrationId]);
261
- const rows = (await db.query(`SELECT * FROM integration_connection WHERE id = ?`, [id])).rows;
262
- return rowToConnection(rows[0]);
263
- }
264
- async function disconnectService(connectionId) {
265
- const now = new Date().toISOString();
266
- await db.execute(`UPDATE integration_connection SET status = 'DISCONNECTED', updatedAt = ? WHERE id = ?`, [now, connectionId]);
267
- const rows = (await db.query(`SELECT * FROM integration_connection WHERE id = ?`, [
268
- connectionId
269
- ])).rows;
270
- return rowToConnection(rows[0]);
271
- }
272
- async function listSyncConfigs(input) {
273
- const { connectionId, status, limit = 20, offset = 0 } = input;
274
- let whereClause = "WHERE 1=1";
275
- const params = [];
276
- if (connectionId) {
277
- whereClause += " AND connectionId = ?";
278
- params.push(connectionId);
279
- }
280
- if (status && status !== "all") {
281
- whereClause += " AND status = ?";
282
- params.push(status);
283
- }
284
- const countResult = (await db.query(`SELECT COUNT(*) as count FROM integration_sync_config ${whereClause}`, params)).rows;
285
- const total = countResult[0]?.count ?? 0;
286
- const rows = (await db.query(`SELECT * FROM integration_sync_config ${whereClause} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`, [...params, limit, offset])).rows;
287
- return {
288
- configs: rows.map(rowToSyncConfig),
289
- total
290
- };
291
- }
292
- async function configureSync(input) {
293
- const id = generateId("sync");
294
- const now = new Date().toISOString();
295
- await db.execute(`INSERT INTO integration_sync_config (id, connectionId, name, sourceEntity, targetEntity, frequency, status, recordsSynced, createdAt, updatedAt)
296
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
297
- id,
298
- input.connectionId,
299
- input.name,
300
- input.sourceEntity,
301
- input.targetEntity,
302
- input.frequency ?? "DAILY",
303
- "ACTIVE",
304
- 0,
305
- now,
306
- now
307
- ]);
308
- const rows = (await db.query(`SELECT * FROM integration_sync_config WHERE id = ?`, [id])).rows;
309
- return rowToSyncConfig(rows[0]);
310
- }
311
- async function mapFields(input) {
312
- const now = new Date().toISOString();
313
- const mappings = [];
314
- await db.execute(`DELETE FROM integration_field_mapping WHERE syncConfigId = ?`, [input.syncConfigId]);
315
- for (const mapping of input.mappings) {
316
- const id = generateId("fmap");
317
- await db.execute(`INSERT INTO integration_field_mapping (id, syncConfigId, sourceField, targetField, transformType, transformConfig, createdAt)
318
- VALUES (?, ?, ?, ?, ?, ?, ?)`, [
319
- id,
320
- input.syncConfigId,
321
- mapping.sourceField,
322
- mapping.targetField,
323
- mapping.transformType ?? null,
324
- mapping.transformConfig ? JSON.stringify(mapping.transformConfig) : null,
325
- now
326
- ]);
327
- const rows = (await db.query(`SELECT * FROM integration_field_mapping WHERE id = ?`, [
328
- id
329
- ])).rows;
330
- mappings.push(rowToFieldMapping(rows[0]));
331
- }
332
- return mappings;
333
- }
334
- async function getFieldMappings(syncConfigId) {
335
- const rows = (await db.query(`SELECT * FROM integration_field_mapping WHERE syncConfigId = ?`, [syncConfigId])).rows;
336
- return rows.map(rowToFieldMapping);
337
- }
338
- async function runSync(syncConfigId) {
339
- const now = new Date().toISOString();
340
- const recordsSynced = Math.floor(Math.random() * 1000) + 50;
341
- await db.execute(`UPDATE integration_sync_config SET lastRunAt = ?, lastRunStatus = 'SUCCESS', recordsSynced = recordsSynced + ?, updatedAt = ? WHERE id = ?`, [now, recordsSynced, now, syncConfigId]);
342
- const config = (await db.query(`SELECT * FROM integration_sync_config WHERE id = ?`, [
343
- syncConfigId
344
- ])).rows;
345
- if (config[0]) {
346
- await db.execute(`UPDATE integration_connection SET lastSyncAt = ?, updatedAt = ? WHERE id = ?`, [now, now, config[0].connectionId]);
347
- }
348
- const rows = (await db.query(`SELECT * FROM integration_sync_config WHERE id = ?`, [
349
- syncConfigId
350
- ])).rows;
351
- return rowToSyncConfig(rows[0]);
352
- }
353
- async function validateByokKey(input) {
354
- const rows = (await db.query(`SELECT * FROM integration_connection WHERE id = ?`, [
355
- input.connectionId
356
- ])).rows;
357
- if (!rows[0]) {
358
- return {
359
- valid: false,
360
- provider: "unknown",
361
- keyPrefix: "",
362
- error: `Connection ${input.connectionId} not found`
363
- };
364
- }
365
- const keyPrefix = input.providerKey.slice(0, 8);
366
- const looksValid = input.providerKey.length >= 16;
367
- return {
368
- valid: looksValid,
369
- provider: rows[0].name,
370
- keyPrefix: `${keyPrefix}...`,
371
- expiresAt: looksValid ? new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString() : undefined,
372
- error: looksValid ? undefined : "Key must be at least 16 characters"
373
- };
374
- }
375
- async function refreshOAuth2Token(input) {
376
- const now = new Date().toISOString();
377
- await db.execute(`UPDATE integration_connection SET updatedAt = ? WHERE id = ?`, [now, input.connectionId]);
378
- return {
379
- refreshed: true,
380
- expiresAt: new Date(Date.now() + 3600 * 1000).toISOString(),
381
- tokenType: "Bearer",
382
- scopes: ["read", "write", "sync"]
383
- };
384
- }
385
- async function getTransportOptions(input) {
386
- return {
387
- integrationId: input.integrationId,
388
- transports: [
389
- { transport: "rest", supported: true, defaultVersion: "v2" },
390
- { transport: "mcp", supported: true, defaultVersion: "v1" },
391
- { transport: "webhook", supported: true },
392
- { transport: "sdk", supported: false }
393
- ]
394
- };
395
- }
396
- return {
397
- listIntegrations,
398
- createIntegration,
399
- listConnections,
400
- connectService,
401
- disconnectService,
402
- listSyncConfigs,
403
- configureSync,
404
- mapFields,
405
- getFieldMappings,
406
- runSync,
407
- validateByokKey,
408
- refreshOAuth2Token,
409
- getTransportOptions
410
- };
411
- }
412
-
413
- // src/integration/integration.enum.ts
414
- import { defineEnum as defineEnum2 } from "@contractspec/lib.schema";
415
- var IntegrationStatusEnum = defineEnum2("IntegrationStatus", [
416
- "DRAFT",
417
- "ACTIVE",
418
- "PAUSED",
419
- "ERROR",
420
- "ARCHIVED"
421
- ]);
422
-
423
- // src/integration/integration.schema.ts
424
- import { defineSchemaModel as defineSchemaModel2, ScalarTypeEnum as ScalarTypeEnum2 } from "@contractspec/lib.schema";
425
- var IntegrationModel = defineSchemaModel2({
426
- name: "IntegrationModel",
427
- fields: {
428
- id: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
429
- name: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
430
- slug: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
431
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
432
- provider: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false },
433
- status: { type: IntegrationStatusEnum, isOptional: false },
434
- createdAt: { type: ScalarTypeEnum2.DateTime(), isOptional: false }
435
- }
436
- });
437
- var CreateIntegrationInputModel = defineSchemaModel2({
438
- name: "CreateIntegrationInput",
439
- fields: {
440
- name: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
441
- slug: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
442
- description: { type: ScalarTypeEnum2.String_unsecure(), isOptional: true },
443
- provider: { type: ScalarTypeEnum2.NonEmptyString(), isOptional: false },
444
- config: { type: ScalarTypeEnum2.JSON(), isOptional: true },
445
- featureFlagKey: {
446
- type: ScalarTypeEnum2.String_unsecure(),
447
- isOptional: true
448
- }
449
- }
450
- });
451
-
452
- // src/integration/integration.operations.ts
453
- import { defineCommand as defineCommand2 } from "@contractspec/lib.contracts-spec/operations";
454
- var CreateIntegrationContract = defineCommand2({
455
- meta: {
456
- key: "integration.create",
457
- version: "1.0.0",
458
- stability: "stable",
459
- owners: ["@example.integration-hub"],
460
- tags: ["integration", "create"],
461
- description: "Create a new integration.",
462
- goal: "Allow users to set up integrations with external systems.",
463
- context: "Integration setup."
464
- },
465
- io: { input: CreateIntegrationInputModel, output: IntegrationModel },
466
- policy: { auth: "user" },
467
- sideEffects: {
468
- emits: [
469
- {
470
- key: "integration.created",
471
- version: "1.0.0",
472
- when: "Integration created",
473
- payload: IntegrationModel
474
- }
475
- ],
476
- audit: ["integration.created"]
477
- },
478
- acceptance: {
479
- scenarios: [
480
- {
481
- key: "create-integration-happy-path",
482
- given: ["User is admin"],
483
- when: ["User defines new integration type"],
484
- then: [
485
- "Integration definition is created",
486
- "IntegrationCreated event is emitted"
487
- ]
488
- }
489
- ],
490
- examples: [
491
- {
492
- key: "create-slack",
493
- input: { name: "Slack", category: "communication", authType: "oauth2" },
494
- output: { id: "slack", status: "active" }
495
- }
496
- ]
497
- }
498
- });
499
- // src/mcp-example.ts
500
- import {
501
- createMcpToolsets
502
- } from "@contractspec/lib.ai-agent/tools/mcp-client";
503
- import { randomUUID } from "crypto";
504
- var DEFAULT_STDIO_ARGS = [
505
- "-y",
506
- "@modelcontextprotocol/server-filesystem",
507
- "."
508
- ];
509
- async function runIntegrationHubMcpExampleFromEnv() {
510
- const mode = resolveMode();
511
- const transport = resolveTransport();
512
- const config = buildMcpConfigFromEnv();
513
- const toolset = await createMcpToolsets([config], {
514
- onNameCollision: "error"
515
- });
516
- try {
517
- const toolNames = Object.keys(toolset.tools).sort();
518
- const output = {
519
- mode,
520
- server: {
521
- name: config.name,
522
- transport
523
- },
524
- authMethod: process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_AUTH_METHOD,
525
- apiVersion: process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_API_VERSION,
526
- tools: toolNames
527
- };
528
- if (mode === "call") {
529
- const toolName = requireEnv("CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_NAME");
530
- const toolArgs = parseRecordEnvOrDefault("CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_ARGS_JSON", {});
531
- const tool = toolset.tools[toolName];
532
- if (!tool?.execute) {
533
- throw new Error(`Tool "${toolName}" was not found. Available tools: ${toolNames.join(", ")}`);
534
- }
535
- const toolOutput = await tool.execute(toolArgs, {
536
- toolCallId: `integration-hub-${randomUUID()}`,
537
- messages: []
538
- });
539
- output.toolCall = {
540
- name: toolName,
541
- args: toolArgs,
542
- output: toolOutput
543
- };
544
- }
545
- return output;
546
- } finally {
547
- await toolset.cleanup().catch(() => {
548
- return;
549
- });
550
- }
551
- }
552
- function buildMcpConfigFromEnv() {
553
- const name = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_NAME ?? "filesystem";
554
- const transport = resolveTransport();
555
- const toolPrefix = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_PREFIX;
556
- if (transport === "stdio") {
557
- return {
558
- name,
559
- transport,
560
- command: process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_COMMAND ?? "npx",
561
- args: parseStringArrayEnv("CONTRACTSPEC_INTEGRATION_HUB_MCP_ARGS_JSON", DEFAULT_STDIO_ARGS),
562
- toolPrefix
563
- };
564
- }
565
- const accessToken = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_ACCESS_TOKEN;
566
- const accessTokenEnvVar = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_ACCESS_TOKEN_ENV;
567
- const mcpTransport = transport === "webhook" || transport === "http" ? "http" : "sse";
568
- return {
569
- name,
570
- transport: mcpTransport,
571
- url: requireEnv("CONTRACTSPEC_INTEGRATION_HUB_MCP_URL"),
572
- headers: parseStringRecordEnv("CONTRACTSPEC_INTEGRATION_HUB_MCP_HEADERS_JSON"),
573
- accessToken,
574
- accessTokenEnvVar,
575
- toolPrefix
576
- };
577
- }
578
- function resolveMode() {
579
- const rawMode = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_MODE?.toLowerCase() ?? "list";
580
- if (rawMode === "list" || rawMode === "call") {
581
- return rawMode;
582
- }
583
- throw new Error(`Unsupported CONTRACTSPEC_INTEGRATION_HUB_MCP_MODE: ${rawMode}. Use "list" or "call".`);
584
- }
585
- function resolveTransport() {
586
- const rawTransport = process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_TRANSPORT?.toLowerCase() ?? "stdio";
587
- if (rawTransport === "stdio" || rawTransport === "http" || rawTransport === "sse" || rawTransport === "webhook") {
588
- return rawTransport;
589
- }
590
- throw new Error(`Unsupported CONTRACTSPEC_INTEGRATION_HUB_MCP_TRANSPORT: ${rawTransport}. Use "stdio", "http", "sse", or "webhook".`);
591
- }
592
- function parseStringArrayEnv(key, fallback) {
593
- const raw = process.env[key];
594
- if (!raw) {
595
- return fallback;
596
- }
597
- const parsed = parseJsonEnv(key);
598
- if (!Array.isArray(parsed) || parsed.some((value) => typeof value !== "string")) {
599
- throw new Error(`${key} must be a JSON string array.`);
600
- }
601
- return parsed;
602
- }
603
- function parseRecordEnv(key) {
604
- const raw = process.env[key];
605
- if (!raw) {
606
- return;
607
- }
608
- const parsed = parseJsonEnv(key);
609
- if (!isRecord(parsed)) {
610
- throw new Error(`${key} must be a JSON object.`);
611
- }
612
- return parsed;
613
- }
614
- function parseRecordEnvOrDefault(key, fallback) {
615
- return parseRecordEnv(key) ?? fallback;
616
- }
617
- function parseStringRecordEnv(key) {
618
- const parsed = parseRecordEnv(key);
619
- if (!parsed) {
620
- return;
621
- }
622
- const entries = Object.entries(parsed);
623
- const invalidEntry = entries.find(([, value]) => typeof value !== "string");
624
- if (invalidEntry) {
625
- throw new Error(`${key} must contain only string values.`);
626
- }
627
- return Object.fromEntries(entries);
628
- }
629
- function parseJsonEnv(key) {
630
- const raw = process.env[key];
631
- if (!raw) {
632
- return;
633
- }
634
- try {
635
- return JSON.parse(raw);
636
- } catch {
637
- throw new Error(`${key} contains invalid JSON.`);
638
- }
639
- }
640
- function requireEnv(key) {
641
- const value = process.env[key];
642
- if (!value) {
643
- throw new Error(`Missing required env var: ${key}`);
644
- }
645
- return value;
646
- }
647
- function isRecord(value) {
648
- return typeof value === "object" && value !== null && !Array.isArray(value);
649
- }
650
-
651
- // src/sync/sync.enum.ts
652
- import { defineEnum as defineEnum3 } from "@contractspec/lib.schema";
653
- var SyncDirectionEnum = defineEnum3("SyncDirection", [
654
- "INBOUND",
655
- "OUTBOUND",
656
- "BIDIRECTIONAL"
657
- ]);
658
- var SyncStatusEnum = defineEnum3("SyncStatus", [
659
- "PENDING",
660
- "RUNNING",
661
- "COMPLETED",
662
- "FAILED",
663
- "CANCELLED"
664
- ]);
665
- var MappingTypeEnum = defineEnum3("MappingType", [
666
- "DIRECT",
667
- "TRANSFORM",
668
- "LOOKUP",
669
- "CONSTANT",
670
- "COMPUTED"
671
- ]);
672
-
673
- // src/sync/sync.schema.ts
674
- import { defineSchemaModel as defineSchemaModel3, ScalarTypeEnum as ScalarTypeEnum3 } from "@contractspec/lib.schema";
675
- var FieldMappingModel = defineSchemaModel3({
676
- name: "FieldMappingModel",
677
- fields: {
678
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
679
- sourceField: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
680
- targetField: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
681
- mappingType: { type: MappingTypeEnum, isOptional: false },
682
- transformExpression: {
683
- type: ScalarTypeEnum3.String_unsecure(),
684
- isOptional: true
685
- },
686
- isRequired: { type: ScalarTypeEnum3.Boolean(), isOptional: false }
687
- }
688
- });
689
- var SyncConfigModel = defineSchemaModel3({
690
- name: "SyncConfigModel",
691
- fields: {
692
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
693
- integrationId: {
694
- type: ScalarTypeEnum3.String_unsecure(),
695
- isOptional: false
696
- },
697
- connectionId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
698
- name: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
699
- direction: { type: SyncDirectionEnum, isOptional: false },
700
- sourceObject: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
701
- targetObject: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
702
- scheduleEnabled: { type: ScalarTypeEnum3.Boolean(), isOptional: false },
703
- scheduleCron: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
704
- isActive: { type: ScalarTypeEnum3.Boolean(), isOptional: false },
705
- lastSyncAt: { type: ScalarTypeEnum3.DateTime(), isOptional: true },
706
- fieldMappings: { type: FieldMappingModel, isArray: true, isOptional: true }
707
- }
708
- });
709
- var SyncRunModel = defineSchemaModel3({
710
- name: "SyncRunModel",
711
- fields: {
712
- id: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
713
- syncConfigId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
714
- status: { type: SyncStatusEnum, isOptional: false },
715
- direction: { type: SyncDirectionEnum, isOptional: false },
716
- trigger: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
717
- recordsProcessed: {
718
- type: ScalarTypeEnum3.Int_unsecure(),
719
- isOptional: false
720
- },
721
- recordsCreated: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
722
- recordsUpdated: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
723
- recordsFailed: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false },
724
- errorMessage: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
725
- startedAt: { type: ScalarTypeEnum3.DateTime(), isOptional: true },
726
- completedAt: { type: ScalarTypeEnum3.DateTime(), isOptional: true },
727
- createdAt: { type: ScalarTypeEnum3.DateTime(), isOptional: false }
728
- }
729
- });
730
- var CreateSyncConfigInputModel = defineSchemaModel3({
731
- name: "CreateSyncConfigInput",
732
- fields: {
733
- integrationId: {
734
- type: ScalarTypeEnum3.String_unsecure(),
735
- isOptional: false
736
- },
737
- connectionId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
738
- name: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
739
- direction: { type: SyncDirectionEnum, isOptional: false },
740
- sourceObject: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
741
- targetObject: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
742
- scheduleEnabled: { type: ScalarTypeEnum3.Boolean(), isOptional: true },
743
- scheduleCron: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true }
744
- }
745
- });
746
- var AddFieldMappingInputModel = defineSchemaModel3({
747
- name: "AddFieldMappingInput",
748
- fields: {
749
- syncConfigId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
750
- sourceField: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
751
- targetField: { type: ScalarTypeEnum3.NonEmptyString(), isOptional: false },
752
- mappingType: { type: MappingTypeEnum, isOptional: false },
753
- transformExpression: {
754
- type: ScalarTypeEnum3.String_unsecure(),
755
- isOptional: true
756
- },
757
- lookupConfig: { type: ScalarTypeEnum3.JSON(), isOptional: true },
758
- constantValue: { type: ScalarTypeEnum3.JSON(), isOptional: true },
759
- isRequired: { type: ScalarTypeEnum3.Boolean(), isOptional: true },
760
- defaultValue: { type: ScalarTypeEnum3.JSON(), isOptional: true }
761
- }
762
- });
763
- var TriggerSyncInputModel = defineSchemaModel3({
764
- name: "TriggerSyncInput",
765
- fields: {
766
- syncConfigId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
767
- direction: { type: SyncDirectionEnum, isOptional: true },
768
- fullSync: { type: ScalarTypeEnum3.Boolean(), isOptional: true }
769
- }
770
- });
771
- var ListSyncRunsInputModel = defineSchemaModel3({
772
- name: "ListSyncRunsInput",
773
- fields: {
774
- syncConfigId: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
775
- status: { type: SyncStatusEnum, isOptional: true },
776
- limit: {
777
- type: ScalarTypeEnum3.Int_unsecure(),
778
- isOptional: true,
779
- defaultValue: 20
780
- },
781
- offset: {
782
- type: ScalarTypeEnum3.Int_unsecure(),
783
- isOptional: true,
784
- defaultValue: 0
785
- }
786
- }
787
- });
788
- var ListSyncRunsOutputModel = defineSchemaModel3({
789
- name: "ListSyncRunsOutput",
790
- fields: {
791
- runs: { type: SyncRunModel, isArray: true, isOptional: false },
792
- total: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false }
793
- }
794
- });
795
-
796
- // src/sync/sync.operations.ts
797
- import {
798
- defineCommand as defineCommand3,
799
- defineQuery
800
- } from "@contractspec/lib.contracts-spec/operations";
801
- var OWNERS2 = ["@example.integration-hub"];
802
- var CreateSyncConfigContract = defineCommand3({
803
- meta: {
804
- key: "integration.syncConfig.create",
805
- version: "1.0.0",
806
- stability: "stable",
807
- owners: [...OWNERS2],
808
- tags: ["integration", "sync", "config", "create"],
809
- description: "Create a sync configuration.",
810
- goal: "Define how data should be synchronized.",
811
- context: "Sync setup."
812
- },
813
- io: { input: CreateSyncConfigInputModel, output: SyncConfigModel },
814
- policy: { auth: "user" },
815
- sideEffects: {
816
- emits: [
817
- {
818
- key: "integration.syncConfig.created",
819
- version: "1.0.0",
820
- when: "Sync config created",
821
- payload: SyncConfigModel
822
- }
823
- ],
824
- audit: ["integration.syncConfig.created"]
825
- },
826
- acceptance: {
827
- scenarios: [
828
- {
829
- key: "create-sync-happy-path",
830
- given: ["User is authenticated"],
831
- when: ["User creates sync config"],
832
- then: ["Sync config is created", "SyncConfigCreated event is emitted"]
833
- }
834
- ],
835
- examples: [
836
- {
837
- key: "create-contact-sync",
838
- input: {
839
- name: "Contacts Sync",
840
- sourceConnectionId: "conn-1",
841
- targetConnectionId: "conn-2"
842
- },
843
- output: { id: "sync-123", status: "active" }
844
- }
845
- ]
846
- }
847
- });
848
- var AddFieldMappingContract = defineCommand3({
849
- meta: {
850
- key: "integration.fieldMapping.add",
851
- version: "1.0.0",
852
- stability: "stable",
853
- owners: [...OWNERS2],
854
- tags: ["integration", "mapping", "field"],
855
- description: "Add a field mapping to a sync config.",
856
- goal: "Map fields between systems.",
857
- context: "Mapping configuration."
858
- },
859
- io: { input: AddFieldMappingInputModel, output: FieldMappingModel },
860
- policy: { auth: "user" },
861
- sideEffects: {
862
- emits: [
863
- {
864
- key: "integration.fieldMapping.added",
865
- version: "1.0.0",
866
- when: "Mapping added",
867
- payload: FieldMappingModel
868
- }
869
- ]
870
- },
871
- acceptance: {
872
- scenarios: [
873
- {
874
- key: "add-mapping-happy-path",
875
- given: ["Sync config exists"],
876
- when: ["User adds field mapping"],
877
- then: ["Mapping is added", "FieldMappingAdded event is emitted"]
878
- }
879
- ],
880
- examples: [
881
- {
882
- key: "map-email",
883
- input: {
884
- syncConfigId: "sync-123",
885
- sourceField: "email",
886
- targetField: "user_email"
887
- },
888
- output: { id: "map-456", type: "string" }
889
- }
890
- ]
891
- }
892
- });
893
- var TriggerSyncContract = defineCommand3({
894
- meta: {
895
- key: "integration.sync.trigger",
896
- version: "1.0.0",
897
- stability: "stable",
898
- owners: [...OWNERS2],
899
- tags: ["integration", "sync", "trigger"],
900
- description: "Trigger a manual sync.",
901
- goal: "Start data synchronization.",
902
- context: "Manual sync or webhook trigger."
903
- },
904
- io: { input: TriggerSyncInputModel, output: SyncRunModel },
905
- policy: { auth: "user" },
906
- sideEffects: {
907
- emits: [
908
- {
909
- key: "integration.sync.started",
910
- version: "1.0.0",
911
- when: "Sync starts",
912
- payload: SyncRunModel
913
- }
914
- ],
915
- audit: ["integration.sync.triggered"]
916
- },
917
- acceptance: {
918
- scenarios: [
919
- {
920
- key: "trigger-sync-happy-path",
921
- given: ["Sync config exists"],
922
- when: ["User triggers sync"],
923
- then: ["Sync run starts", "SyncStarted event is emitted"]
924
- }
925
- ],
926
- examples: [
927
- {
928
- key: "manual-trigger",
929
- input: { syncConfigId: "sync-123" },
930
- output: { id: "run-789", status: "pending" }
931
- }
932
- ]
933
- }
934
- });
935
- var ListSyncRunsContract = defineQuery({
936
- meta: {
937
- key: "integration.syncRun.list",
938
- version: "1.0.0",
939
- stability: "stable",
940
- owners: [...OWNERS2],
941
- tags: ["integration", "sync", "run", "list"],
942
- description: "List sync run history.",
943
- goal: "View sync history and status.",
944
- context: "Sync monitoring."
945
- },
946
- io: { input: ListSyncRunsInputModel, output: ListSyncRunsOutputModel },
947
- policy: { auth: "user" },
948
- acceptance: {
949
- scenarios: [
950
- {
951
- key: "list-runs-happy-path",
952
- given: ["User has access to syncs"],
953
- when: ["User lists sync runs"],
954
- then: ["List of runs is returned"]
955
- }
956
- ],
957
- examples: [
958
- {
959
- key: "list-recent",
960
- input: { limit: 10 },
961
- output: { items: [], total: 50 }
962
- }
963
- ]
964
- }
965
- });
966
- // src/sync-engine/index.ts
967
- class BasicFieldTransformer {
968
- transform(value, expression) {
969
- try {
970
- if (expression.startsWith("uppercase")) {
971
- return typeof value === "string" ? value.toUpperCase() : value;
972
- }
973
- if (expression.startsWith("lowercase")) {
974
- return typeof value === "string" ? value.toLowerCase() : value;
975
- }
976
- if (expression.startsWith("trim")) {
977
- return typeof value === "string" ? value.trim() : value;
978
- }
979
- if (expression.startsWith("default:")) {
980
- const defaultVal = expression.replace("default:", "");
981
- return value ?? JSON.parse(defaultVal);
982
- }
983
- if (expression.startsWith("concat:")) {
984
- const separator = expression.replace("concat:", "") || " ";
985
- if (Array.isArray(value)) {
986
- return value.join(separator);
987
- }
988
- return value;
989
- }
990
- if (expression.startsWith("split:")) {
991
- const separator = expression.replace("split:", "") || ",";
992
- if (typeof value === "string") {
993
- return value.split(separator);
994
- }
995
- return value;
996
- }
997
- if (expression.startsWith("number")) {
998
- return Number(value);
999
- }
1000
- if (expression.startsWith("boolean")) {
1001
- return Boolean(value);
1002
- }
1003
- if (expression.startsWith("string")) {
1004
- return String(value);
1005
- }
1006
- return value;
1007
- } catch {
1008
- return value;
1009
- }
1010
- }
1011
- }
1012
-
1013
- class BasicSyncEngine {
1014
- transformer;
1015
- constructor(transformer) {
1016
- this.transformer = transformer ?? new BasicFieldTransformer;
1017
- }
1018
- async sync(_context) {
1019
- const result = {
1020
- success: true,
1021
- recordsProcessed: 0,
1022
- recordsCreated: 0,
1023
- recordsUpdated: 0,
1024
- recordsDeleted: 0,
1025
- recordsFailed: 0,
1026
- recordsSkipped: 0,
1027
- errors: []
1028
- };
1029
- return result;
1030
- }
1031
- transformRecord(sourceRecord, mappings, _context) {
1032
- const targetData = {};
1033
- for (const mapping of mappings) {
1034
- let value;
1035
- let sourceValue;
1036
- switch (mapping.mappingType) {
1037
- case "DIRECT":
1038
- value = this.getNestedValue(sourceRecord.data, mapping.sourceField);
1039
- break;
1040
- case "TRANSFORM":
1041
- sourceValue = this.getNestedValue(sourceRecord.data, mapping.sourceField);
1042
- value = mapping.transformExpression ? this.transformer.transform(sourceValue, mapping.transformExpression) : sourceValue;
1043
- break;
1044
- case "CONSTANT":
1045
- value = mapping.constantValue;
1046
- break;
1047
- case "LOOKUP":
1048
- value = this.getNestedValue(sourceRecord.data, mapping.sourceField);
1049
- break;
1050
- case "COMPUTED":
1051
- value = mapping.transformExpression ? this.evaluateComputed(sourceRecord.data, mapping.transformExpression) : null;
1052
- break;
1053
- default:
1054
- value = this.getNestedValue(sourceRecord.data, mapping.sourceField);
1055
- }
1056
- if (value === undefined || value === null) {
1057
- value = mapping.defaultValue;
1058
- }
1059
- this.setNestedValue(targetData, mapping.targetField, value);
1060
- }
1061
- return {
1062
- id: sourceRecord.id,
1063
- data: targetData
1064
- };
1065
- }
1066
- validateRecord(record, mappings) {
1067
- const errors = [];
1068
- for (const mapping of mappings) {
1069
- if (mapping.isRequired) {
1070
- const value = this.getNestedValue(record.data, mapping.targetField);
1071
- if (value === undefined || value === null) {
1072
- errors.push({
1073
- recordId: record.id,
1074
- field: mapping.targetField,
1075
- message: `Required field ${mapping.targetField} is missing`,
1076
- code: "REQUIRED_FIELD_MISSING"
1077
- });
1078
- }
1079
- }
1080
- }
1081
- return {
1082
- valid: errors.length === 0,
1083
- errors
1084
- };
1085
- }
1086
- getNestedValue(obj, path) {
1087
- const parts = path.split(".");
1088
- let current = obj;
1089
- for (const part of parts) {
1090
- if (current === null || current === undefined) {
1091
- return;
1092
- }
1093
- current = current[part];
1094
- }
1095
- return current;
1096
- }
1097
- setNestedValue(obj, path, value) {
1098
- const parts = path.split(".");
1099
- let current = obj;
1100
- for (let i = 0;i < parts.length - 1; i++) {
1101
- const part = parts[i];
1102
- if (part === undefined)
1103
- continue;
1104
- if (!(part in current)) {
1105
- current[part] = {};
1106
- }
1107
- current = current[part];
1108
- }
1109
- const lastPart = parts[parts.length - 1];
1110
- if (lastPart !== undefined) {
1111
- current[lastPart] = value;
1112
- }
1113
- }
1114
- evaluateComputed(data, expression) {
1115
- try {
1116
- const result = expression.replace(/\$\{([^}]+)\}/g, (_, path) => {
1117
- const value = this.getNestedValue(data, path);
1118
- return String(value ?? "");
1119
- });
1120
- return result;
1121
- } catch {
1122
- return null;
1123
- }
1124
- }
1125
- }
1126
- function createSyncEngine(transformer) {
1127
- return new BasicSyncEngine(transformer);
1128
- }
1129
- function computeChecksum(data) {
1130
- const str = JSON.stringify(data, Object.keys(data).sort());
1131
- let hash = 0;
1132
- for (let i = 0;i < str.length; i++) {
1133
- const char = str.charCodeAt(i);
1134
- hash = (hash << 5) - hash + char;
1135
- hash = hash & hash;
1136
- }
1137
- return hash.toString(16);
1138
- }
1139
- function hasChanges(sourceChecksum, targetChecksum) {
1140
- if (!sourceChecksum || !targetChecksum) {
1141
- return true;
1142
- }
1143
- return sourceChecksum !== targetChecksum;
1144
- }
1145
-
1146
- // src/ui/hooks/useIntegrationData.ts
1147
- import { useTemplateRuntime } from "@contractspec/lib.example-shared-ui";
1148
- import { useCallback, useEffect, useState } from "react";
1149
- "use client";
1150
- function useIntegrationData(projectId = "local-project") {
1151
- const { handlers } = useTemplateRuntime();
1152
- const integration = handlers.integration;
1153
- const [integrations, setIntegrations] = useState([]);
1154
- const [connections, setConnections] = useState([]);
1155
- const [syncConfigs, setSyncConfigs] = useState([]);
1156
- const [loading, setLoading] = useState(true);
1157
- const [error, setError] = useState(null);
1158
- const fetchData = useCallback(async () => {
1159
- try {
1160
- setLoading(true);
1161
- setError(null);
1162
- const [integResult, connResult, syncResult] = await Promise.all([
1163
- integration.listIntegrations({ projectId, limit: 100 }),
1164
- integration.listConnections({ limit: 100 }),
1165
- integration.listSyncConfigs({ limit: 100 })
1166
- ]);
1167
- setIntegrations(integResult.integrations);
1168
- setConnections(connResult.connections);
1169
- setSyncConfigs(syncResult.configs);
1170
- } catch (err) {
1171
- setError(err instanceof Error ? err : new Error("Failed to load integrations"));
1172
- } finally {
1173
- setLoading(false);
1174
- }
1175
- }, [integration, projectId]);
1176
- useEffect(() => {
1177
- fetchData();
1178
- }, [fetchData]);
1179
- const stats = {
1180
- totalIntegrations: integrations.length,
1181
- activeIntegrations: integrations.filter((i) => i.status === "ACTIVE").length,
1182
- totalConnections: connections.length,
1183
- connectedCount: connections.filter((c) => c.status === "CONNECTED").length,
1184
- totalSyncs: syncConfigs.length,
1185
- activeSyncs: syncConfigs.filter((s) => s.status === "ACTIVE").length
1186
- };
1187
- return {
1188
- integrations,
1189
- connections,
1190
- syncConfigs,
1191
- loading,
1192
- error,
1193
- stats,
1194
- refetch: fetchData
1195
- };
1196
- }
1197
-
1198
- // src/ui/hooks/index.ts
1199
- "use client";
1200
-
1201
- // src/visualizations/catalog.ts
1202
- import {
1203
- defineVisualization,
1204
- VisualizationRegistry
1205
- } from "@contractspec/lib.contracts-spec/visualizations";
1206
- var INTEGRATION_LIST_REF = {
1207
- key: "integration.list",
1208
- version: "1.0.0"
1209
- };
1210
- var CONNECTION_LIST_REF = {
1211
- key: "integration.connection.list",
1212
- version: "1.0.0"
1213
- };
1214
- var SYNC_CONFIG_REF = {
1215
- key: "integration.syncConfig.list",
1216
- version: "1.0.0"
1217
- };
1218
- var META = {
1219
- version: "1.0.0",
1220
- domain: "integration",
1221
- stability: "experimental",
1222
- owners: ["@example.integration-hub"],
1223
- tags: ["integration", "visualization", "sync"]
1224
- };
1225
- var IntegrationTypeVisualization = defineVisualization({
1226
- meta: {
1227
- ...META,
1228
- key: "integration-hub.visualization.integration-types",
1229
- title: "Integration Types",
1230
- description: "Distribution of configured integration categories.",
1231
- goal: "Show where integration coverage is concentrated.",
1232
- context: "Integration overview."
1233
- },
1234
- source: { primary: INTEGRATION_LIST_REF, resultPath: "data" },
1235
- visualization: {
1236
- kind: "pie",
1237
- nameDimension: "type",
1238
- valueMeasure: "count",
1239
- dimensions: [
1240
- { key: "type", label: "Type", dataPath: "type", type: "category" }
1241
- ],
1242
- measures: [
1243
- { key: "count", label: "Count", dataPath: "count", format: "number" }
1244
- ],
1245
- table: { caption: "Integration counts by type." }
1246
- }
1247
- });
1248
- var ConnectionStatusVisualization = defineVisualization({
1249
- meta: {
1250
- ...META,
1251
- key: "integration-hub.visualization.connection-status",
1252
- title: "Connection Status",
1253
- description: "Status distribution across configured connections.",
1254
- goal: "Highlight connection health and instability.",
1255
- context: "Connection monitoring."
1256
- },
1257
- source: { primary: CONNECTION_LIST_REF, resultPath: "data" },
1258
- visualization: {
1259
- kind: "cartesian",
1260
- variant: "bar",
1261
- xDimension: "status",
1262
- yMeasures: ["count"],
1263
- dimensions: [
1264
- { key: "status", label: "Status", dataPath: "status", type: "category" }
1265
- ],
1266
- measures: [
1267
- {
1268
- key: "count",
1269
- label: "Connections",
1270
- dataPath: "count",
1271
- format: "number",
1272
- color: "#1d4ed8"
1273
- }
1274
- ],
1275
- table: { caption: "Connection counts by status." }
1276
- }
1277
- });
1278
- var HealthySyncMetricVisualization = defineVisualization({
1279
- meta: {
1280
- ...META,
1281
- key: "integration-hub.visualization.sync-healthy",
1282
- title: "Healthy Syncs",
1283
- description: "Sync configurations currently healthy or recently successful.",
1284
- goal: "Summarize healthy synchronization capacity.",
1285
- context: "Sync-state comparison."
1286
- },
1287
- source: { primary: SYNC_CONFIG_REF, resultPath: "data" },
1288
- visualization: {
1289
- kind: "metric",
1290
- measure: "value",
1291
- measures: [
1292
- { key: "value", label: "Syncs", dataPath: "value", format: "number" }
1293
- ],
1294
- table: { caption: "Healthy sync count." }
1295
- }
1296
- });
1297
- var AttentionSyncMetricVisualization = defineVisualization({
1298
- meta: {
1299
- ...META,
1300
- key: "integration-hub.visualization.sync-attention",
1301
- title: "Attention Needed",
1302
- description: "Sync configurations paused, failing, or otherwise needing review.",
1303
- goal: "Summarize syncs needing action.",
1304
- context: "Sync-state comparison."
1305
- },
1306
- source: { primary: SYNC_CONFIG_REF, resultPath: "data" },
1307
- visualization: {
1308
- kind: "metric",
1309
- measure: "value",
1310
- measures: [
1311
- { key: "value", label: "Syncs", dataPath: "value", format: "number" }
1312
- ],
1313
- table: { caption: "Syncs requiring attention." }
1314
- }
1315
- });
1316
- var IntegrationVisualizationSpecs = [
1317
- IntegrationTypeVisualization,
1318
- ConnectionStatusVisualization,
1319
- HealthySyncMetricVisualization,
1320
- AttentionSyncMetricVisualization
1321
- ];
1322
- var IntegrationVisualizationRegistry = new VisualizationRegistry([
1323
- ...IntegrationVisualizationSpecs
1324
- ]);
1325
- var IntegrationVisualizationRefs = IntegrationVisualizationSpecs.map((spec) => ({
1326
- key: spec.meta.key,
1327
- version: spec.meta.version
1328
- }));
1329
-
1330
- // src/visualizations/selectors.ts
1331
- function isHealthySync(status) {
1332
- return status === "ACTIVE" || status === "SUCCESS";
1333
- }
1334
- function createIntegrationVisualizationSections(integrations, connections, syncConfigs) {
1335
- const integrationTypes = new Map;
1336
- const connectionStatuses = new Map;
1337
- let healthySyncs = 0;
1338
- let attentionSyncs = 0;
1339
- for (const integration of integrations) {
1340
- integrationTypes.set(integration.type, (integrationTypes.get(integration.type) ?? 0) + 1);
1341
- }
1342
- for (const connection of connections) {
1343
- connectionStatuses.set(connection.status, (connectionStatuses.get(connection.status) ?? 0) + 1);
1344
- }
1345
- for (const syncConfig of syncConfigs) {
1346
- if (isHealthySync(syncConfig.status)) {
1347
- healthySyncs += 1;
1348
- } else {
1349
- attentionSyncs += 1;
1350
- }
1351
- }
1352
- const primaryItems = [
1353
- {
1354
- key: "integration-types",
1355
- spec: IntegrationTypeVisualization,
1356
- data: {
1357
- data: Array.from(integrationTypes.entries()).map(([type, count]) => ({
1358
- type,
1359
- count
1360
- }))
1361
- },
1362
- title: "Integration Types",
1363
- description: "Configured integrations grouped by category.",
1364
- height: 260
1365
- },
1366
- {
1367
- key: "connection-status",
1368
- spec: ConnectionStatusVisualization,
1369
- data: {
1370
- data: Array.from(connectionStatuses.entries()).map(([status, count]) => ({
1371
- status,
1372
- count
1373
- }))
1374
- },
1375
- title: "Connection Status",
1376
- description: "Operational health across current connections."
1377
- }
1378
- ];
1379
- const comparisonItems = [
1380
- {
1381
- key: "healthy-syncs",
1382
- spec: HealthySyncMetricVisualization,
1383
- data: { data: [{ value: healthySyncs }] },
1384
- title: "Healthy Syncs",
1385
- description: "Active or recently successful sync configurations.",
1386
- height: 200
1387
- },
1388
- {
1389
- key: "attention-syncs",
1390
- spec: AttentionSyncMetricVisualization,
1391
- data: { data: [{ value: attentionSyncs }] },
1392
- title: "Attention Needed",
1393
- description: "Paused, failed, or degraded sync configurations.",
1394
- height: 200
1395
- }
1396
- ];
1397
- return {
1398
- primaryItems,
1399
- comparisonItems
1400
- };
1401
- }
1402
- // src/ui/IntegrationDashboard.visualizations.tsx
1403
- import {
1404
- ComparisonView,
1405
- VisualizationCard,
1406
- VisualizationGrid
1407
- } from "@contractspec/lib.design-system";
1408
- import { jsxDEV } from "react/jsx-dev-runtime";
1409
- "use client";
1410
- function IntegrationVisualizationOverview({
1411
- integrations,
1412
- connections,
1413
- syncConfigs
1414
- }) {
1415
- const { primaryItems, comparisonItems } = createIntegrationVisualizationSections(integrations, connections, syncConfigs);
1416
- return /* @__PURE__ */ jsxDEV("section", {
1417
- className: "space-y-4",
1418
- children: [
1419
- /* @__PURE__ */ jsxDEV("div", {
1420
- children: [
1421
- /* @__PURE__ */ jsxDEV("h3", {
1422
- className: "font-semibold text-lg",
1423
- children: "Integration Visualizations"
1424
- }, undefined, false, undefined, this),
1425
- /* @__PURE__ */ jsxDEV("p", {
1426
- className: "text-muted-foreground text-sm",
1427
- children: "Contract-backed charts for integration coverage and sync health."
1428
- }, undefined, false, undefined, this)
1429
- ]
1430
- }, undefined, true, undefined, this),
1431
- /* @__PURE__ */ jsxDEV(VisualizationGrid, {
1432
- children: primaryItems.map((item) => /* @__PURE__ */ jsxDEV(VisualizationCard, {
1433
- data: item.data,
1434
- description: item.description,
1435
- height: item.height,
1436
- spec: item.spec,
1437
- title: item.title
1438
- }, item.key, false, undefined, this))
1439
- }, undefined, false, undefined, this),
1440
- /* @__PURE__ */ jsxDEV(ComparisonView, {
1441
- description: "Comparison surface for healthy versus attention-needed syncs.",
1442
- items: comparisonItems,
1443
- title: "Sync-State Comparison"
1444
- }, undefined, false, undefined, this)
1445
- ]
1446
- }, undefined, true, undefined, this);
1447
- }
1448
-
1449
- // src/ui/IntegrationHubChat.tsx
1450
- import { ChatWithSidebar } from "@contractspec/module.ai-chat";
1451
- import { jsxDEV as jsxDEV2 } from "react/jsx-dev-runtime";
1452
- "use client";
1453
- var DEFAULT_SUGGESTIONS = [
1454
- "List my integrations",
1455
- "Show sync status",
1456
- "Add a connection"
1457
- ];
1458
- var DEFAULT_SYSTEM_PROMPT = `You are an Integration Hub assistant. Help users manage integrations, connections, and sync configurations. When asked about integrations, connections, or syncs, provide clear, actionable guidance.`;
1459
- function IntegrationHubChat({
1460
- proxyUrl = "/api/chat",
1461
- mcpServers,
1462
- thinkingLevel = "thinking",
1463
- suggestions = DEFAULT_SUGGESTIONS,
1464
- systemPrompt = DEFAULT_SYSTEM_PROMPT,
1465
- className
1466
- }) {
1467
- return /* @__PURE__ */ jsxDEV2("div", {
1468
- className: className ?? "flex h-[500px] flex-col",
1469
- children: /* @__PURE__ */ jsxDEV2(ChatWithSidebar, {
1470
- className: "flex-1",
1471
- systemPrompt,
1472
- proxyUrl,
1473
- mcpServers,
1474
- thinkingLevel,
1475
- suggestions,
1476
- showSuggestionsWhenEmpty: true
1477
- }, undefined, false, undefined, this)
1478
- }, undefined, false, undefined, this);
1479
- }
1480
-
1481
- // src/ui/tables/integration-table.shared.tsx
1482
- import { Button } from "@contractspec/lib.design-system";
1483
- import { Badge } from "@contractspec/lib.ui-kit-web/ui/badge";
1484
- import { HStack } from "@contractspec/lib.ui-kit-web/ui/stack";
1485
- import { jsxDEV as jsxDEV3 } from "react/jsx-dev-runtime";
1486
- "use client";
1487
- var STATUS_VARIANTS = {
1488
- ACTIVE: "default",
1489
- CONNECTED: "default",
1490
- SUCCESS: "default",
1491
- PENDING: "secondary",
1492
- PAUSED: "secondary",
1493
- ERROR: "destructive",
1494
- DISCONNECTED: "outline"
1495
- };
1496
- function formatDateTime(value) {
1497
- return value ? value.toLocaleString() : "Never";
1498
- }
1499
- function formatJson(value) {
1500
- return value ? JSON.stringify(value, null, 2) : "No configuration";
1501
- }
1502
- function StatusBadge({ status }) {
1503
- return /* @__PURE__ */ jsxDEV3(Badge, {
1504
- variant: STATUS_VARIANTS[status] ?? "outline",
1505
- children: status
1506
- }, undefined, false, undefined, this);
1507
- }
1508
- function IntegrationTableToolbar({
1509
- controller,
1510
- label,
1511
- toggleColumnId,
1512
- toggleVisibleLabel,
1513
- toggleHiddenLabel,
1514
- pinColumnId,
1515
- pinLabel,
1516
- resizeColumnId,
1517
- resizeLabel
1518
- }) {
1519
- const firstRow = controller.rows[0];
1520
- const toggleColumn = controller.columns.find((column) => column.id === toggleColumnId);
1521
- const pinColumn = controller.columns.find((column) => column.id === pinColumnId);
1522
- const resizeColumn = controller.columns.find((column) => column.id === resizeColumnId);
1523
- const pinTarget = pinColumn?.pinState === "left" ? false : "left";
1524
- return /* @__PURE__ */ jsxDEV3(HStack, {
1525
- gap: "sm",
1526
- className: "flex-wrap",
1527
- children: [
1528
- /* @__PURE__ */ jsxDEV3(Badge, {
1529
- variant: "outline",
1530
- children: label
1531
- }, undefined, false, undefined, this),
1532
- /* @__PURE__ */ jsxDEV3(Button, {
1533
- variant: "outline",
1534
- size: "sm",
1535
- onPress: () => firstRow?.toggleExpanded?.(!firstRow?.isExpanded),
1536
- children: "Expand First Row"
1537
- }, undefined, false, undefined, this),
1538
- /* @__PURE__ */ jsxDEV3(Button, {
1539
- variant: "outline",
1540
- size: "sm",
1541
- onPress: () => toggleColumn?.toggleVisibility?.(!toggleColumn?.visible),
1542
- children: toggleColumn?.visible ? toggleVisibleLabel : toggleHiddenLabel
1543
- }, undefined, false, undefined, this),
1544
- /* @__PURE__ */ jsxDEV3(Button, {
1545
- variant: "outline",
1546
- size: "sm",
1547
- onPress: () => pinColumn?.pin?.(pinTarget),
1548
- children: pinColumn?.pinState === "left" ? `Unpin ${pinLabel}` : `Pin ${pinLabel}`
1549
- }, undefined, false, undefined, this),
1550
- /* @__PURE__ */ jsxDEV3(Button, {
1551
- variant: "outline",
1552
- size: "sm",
1553
- onPress: () => resizeColumn?.resizeBy?.(40),
1554
- children: resizeLabel
1555
- }, undefined, false, undefined, this)
1556
- ]
1557
- }, undefined, true, undefined, this);
1558
- }
1559
-
1560
- // src/ui/tables/ConnectionsTable.tsx
1561
- import { DataTable } from "@contractspec/lib.design-system";
1562
- import { useContractTable } from "@contractspec/lib.presentation-runtime-react";
1563
- import { VStack } from "@contractspec/lib.ui-kit-web/ui/stack";
1564
- import { Text } from "@contractspec/lib.ui-kit-web/ui/text";
1565
- import { jsxDEV as jsxDEV4 } from "react/jsx-dev-runtime";
1566
- "use client";
1567
- function ConnectionsTable({
1568
- connections
1569
- }) {
1570
- const controller = useContractTable({
1571
- data: connections,
1572
- columns: [
1573
- {
1574
- id: "connection",
1575
- header: "Connection",
1576
- label: "Connection",
1577
- accessor: (connection) => connection.name,
1578
- cell: ({ item }) => /* @__PURE__ */ jsxDEV4(VStack, {
1579
- gap: "xs",
1580
- children: [
1581
- /* @__PURE__ */ jsxDEV4(Text, {
1582
- className: "font-medium text-sm",
1583
- children: item.name
1584
- }, undefined, false, undefined, this),
1585
- /* @__PURE__ */ jsxDEV4(Text, {
1586
- className: "text-muted-foreground text-xs",
1587
- children: [
1588
- "Created ",
1589
- item.createdAt.toLocaleDateString()
1590
- ]
1591
- }, undefined, true, undefined, this)
1592
- ]
1593
- }, undefined, true, undefined, this),
1594
- size: 240,
1595
- minSize: 180,
1596
- canSort: true,
1597
- canPin: true,
1598
- canResize: true
1599
- },
1600
- {
1601
- id: "status",
1602
- header: "Status",
1603
- label: "Status",
1604
- accessorKey: "status",
1605
- cell: ({ value }) => /* @__PURE__ */ jsxDEV4(StatusBadge, {
1606
- status: String(value)
1607
- }, undefined, false, undefined, this),
1608
- size: 150,
1609
- canSort: true,
1610
- canPin: true,
1611
- canResize: true
1612
- },
1613
- {
1614
- id: "lastSyncAt",
1615
- header: "Last Sync",
1616
- label: "Last Sync",
1617
- accessor: (connection) => connection.lastSyncAt?.getTime() ?? 0,
1618
- cell: ({ item }) => formatDateTime(item.lastSyncAt),
1619
- size: 200,
1620
- canSort: true,
1621
- canHide: true,
1622
- canResize: true
1623
- },
1624
- {
1625
- id: "errorMessage",
1626
- header: "Errors",
1627
- label: "Errors",
1628
- accessor: (connection) => connection.errorMessage ?? "",
1629
- cell: ({ value }) => String(value || "No errors"),
1630
- size: 240,
1631
- canHide: true,
1632
- canResize: true
1633
- }
1634
- ],
1635
- initialState: {
1636
- pagination: { pageIndex: 0, pageSize: 3 },
1637
- columnVisibility: { errorMessage: false },
1638
- columnPinning: { left: ["connection"], right: [] }
1639
- },
1640
- renderExpandedContent: (connection) => /* @__PURE__ */ jsxDEV4(VStack, {
1641
- gap: "sm",
1642
- className: "py-2",
1643
- children: [
1644
- /* @__PURE__ */ jsxDEV4(Text, {
1645
- className: "font-medium text-sm",
1646
- children: "Credentials"
1647
- }, undefined, false, undefined, this),
1648
- /* @__PURE__ */ jsxDEV4("pre", {
1649
- className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
1650
- children: formatJson(connection.credentials)
1651
- }, undefined, false, undefined, this),
1652
- /* @__PURE__ */ jsxDEV4(Text, {
1653
- className: "font-medium text-sm",
1654
- children: "Config"
1655
- }, undefined, false, undefined, this),
1656
- /* @__PURE__ */ jsxDEV4("pre", {
1657
- className: "overflow-auto rounded-md bg-muted/40 p-3 text-xs",
1658
- children: formatJson(connection.config)
1659
- }, undefined, false, undefined, this),
1660
- /* @__PURE__ */ jsxDEV4(Text, {
1661
- className: "text-muted-foreground text-sm",
1662
- children: connection.errorMessage ?? "No sync errors recorded."
1663
- }, undefined, false, undefined, this)
1664
- ]
1665
- }, undefined, true, undefined, this),
1666
- getCanExpand: () => true
1667
- });
1668
- return /* @__PURE__ */ jsxDEV4(DataTable, {
1669
- controller,
1670
- title: "Connections",
1671
- description: "Client-mode ContractSpec table with visibility, pinning, resizing, and expanded diagnostics.",
1672
- toolbar: /* @__PURE__ */ jsxDEV4(IntegrationTableToolbar, {
1673
- controller,
1674
- label: `${connections.length} total connections`,
1675
- toggleColumnId: "errorMessage",
1676
- toggleVisibleLabel: "Hide Error Column",
1677
- toggleHiddenLabel: "Show Error Column",
1678
- pinColumnId: "status",
1679
- pinLabel: "Status",
1680
- resizeColumnId: "connection",
1681
- resizeLabel: "Widen Connection"
1682
- }, undefined, false, undefined, this),
1683
- emptyState: /* @__PURE__ */ jsxDEV4("div", {
1684
- className: "rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",
1685
- children: "No connections found"
1686
- }, undefined, false, undefined, this)
1687
- }, undefined, false, undefined, this);
1688
- }
1689
-
1690
- // src/ui/tables/SyncConfigsTable.tsx
1691
- import { DataTable as DataTable2 } from "@contractspec/lib.design-system";
1692
- import { useContractTable as useContractTable2 } from "@contractspec/lib.presentation-runtime-react";
1693
- import { VStack as VStack2 } from "@contractspec/lib.ui-kit-web/ui/stack";
1694
- import { Text as Text2 } from "@contractspec/lib.ui-kit-web/ui/text";
1695
- import { jsxDEV as jsxDEV5 } from "react/jsx-dev-runtime";
1696
- "use client";
1697
- function SyncConfigsTable({
1698
- syncConfigs
1699
- }) {
1700
- const controller = useContractTable2({
1701
- data: syncConfigs,
1702
- columns: [
1703
- {
1704
- id: "sync",
1705
- header: "Sync Config",
1706
- label: "Sync Config",
1707
- accessor: (sync) => sync.name,
1708
- cell: ({ item }) => /* @__PURE__ */ jsxDEV5(VStack2, {
1709
- gap: "xs",
1710
- children: [
1711
- /* @__PURE__ */ jsxDEV5(Text2, {
1712
- className: "font-medium text-sm",
1713
- children: item.name
1714
- }, undefined, false, undefined, this),
1715
- /* @__PURE__ */ jsxDEV5(Text2, {
1716
- className: "text-muted-foreground text-xs",
1717
- children: [
1718
- item.sourceEntity,
1719
- " \u2192 ",
1720
- item.targetEntity
1721
- ]
1722
- }, undefined, true, undefined, this)
1723
- ]
1724
- }, undefined, true, undefined, this),
1725
- size: 260,
1726
- minSize: 200,
1727
- canSort: true,
1728
- canPin: true,
1729
- canResize: true
1730
- },
1731
- {
1732
- id: "frequency",
1733
- header: "Frequency",
1734
- label: "Frequency",
1735
- accessorKey: "frequency",
1736
- size: 160,
1737
- canSort: true,
1738
- canHide: true,
1739
- canResize: true
1740
- },
1741
- {
1742
- id: "status",
1743
- header: "Status",
1744
- label: "Status",
1745
- accessorKey: "status",
1746
- cell: ({ value }) => /* @__PURE__ */ jsxDEV5(StatusBadge, {
1747
- status: String(value)
1748
- }, undefined, false, undefined, this),
1749
- size: 150,
1750
- canSort: true,
1751
- canPin: true,
1752
- canResize: true
1753
- },
1754
- {
1755
- id: "recordsSynced",
1756
- header: "Records",
1757
- label: "Records",
1758
- accessorKey: "recordsSynced",
1759
- align: "right",
1760
- size: 140,
1761
- canSort: true,
1762
- canResize: true
1763
- },
1764
- {
1765
- id: "lastRunAt",
1766
- header: "Last Run",
1767
- label: "Last Run",
1768
- accessor: (sync) => sync.lastRunAt?.getTime() ?? 0,
1769
- cell: ({ item }) => formatDateTime(item.lastRunAt),
1770
- size: 200,
1771
- canSort: true,
1772
- canHide: true,
1773
- canResize: true
1774
- }
1775
- ],
1776
- initialState: {
1777
- pagination: { pageIndex: 0, pageSize: 3 },
1778
- columnVisibility: { lastRunAt: false },
1779
- columnPinning: { left: ["sync"], right: [] }
1780
- },
1781
- renderExpandedContent: (sync) => /* @__PURE__ */ jsxDEV5(VStack2, {
1782
- gap: "sm",
1783
- className: "py-2",
1784
- children: [
1785
- /* @__PURE__ */ jsxDEV5(Text2, {
1786
- className: "text-muted-foreground text-sm",
1787
- children: [
1788
- "Connection ",
1789
- sync.connectionId
1790
- ]
1791
- }, undefined, true, undefined, this),
1792
- /* @__PURE__ */ jsxDEV5(Text2, {
1793
- className: "text-muted-foreground text-sm",
1794
- children: [
1795
- "Last run: ",
1796
- formatDateTime(sync.lastRunAt)
1797
- ]
1798
- }, undefined, true, undefined, this),
1799
- /* @__PURE__ */ jsxDEV5(Text2, {
1800
- className: "text-muted-foreground text-sm",
1801
- children: [
1802
- "Last status: ",
1803
- sync.lastRunStatus ?? "No runs recorded"
1804
- ]
1805
- }, undefined, true, undefined, this),
1806
- /* @__PURE__ */ jsxDEV5(Text2, {
1807
- className: "text-muted-foreground text-sm",
1808
- children: [
1809
- "Updated ",
1810
- sync.updatedAt.toLocaleString()
1811
- ]
1812
- }, undefined, true, undefined, this)
1813
- ]
1814
- }, undefined, true, undefined, this),
1815
- getCanExpand: () => true
1816
- });
1817
- return /* @__PURE__ */ jsxDEV5(DataTable2, {
1818
- controller,
1819
- title: "Sync Configs",
1820
- description: "Shared table primitives applied to sync monitoring without changing the surrounding dashboard layout.",
1821
- toolbar: /* @__PURE__ */ jsxDEV5(IntegrationTableToolbar, {
1822
- controller,
1823
- label: `${syncConfigs.length} syncs`,
1824
- toggleColumnId: "lastRunAt",
1825
- toggleVisibleLabel: "Hide Last Run",
1826
- toggleHiddenLabel: "Show Last Run",
1827
- pinColumnId: "status",
1828
- pinLabel: "Status",
1829
- resizeColumnId: "sync",
1830
- resizeLabel: "Widen Sync"
1831
- }, undefined, false, undefined, this),
1832
- emptyState: /* @__PURE__ */ jsxDEV5("div", {
1833
- className: "rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",
1834
- children: "No sync configurations found"
1835
- }, undefined, false, undefined, this)
1836
- }, undefined, false, undefined, this);
1837
- }
1838
- // src/ui/IntegrationDashboard.tsx
1839
- import {
1840
- Button as Button2,
1841
- ErrorState,
1842
- LoaderBlock,
1843
- StatCard,
1844
- StatCardGroup
1845
- } from "@contractspec/lib.design-system";
1846
- import { useState as useState2 } from "react";
1847
- import { jsxDEV as jsxDEV6 } from "react/jsx-dev-runtime";
1848
- "use client";
1849
- var STATUS_COLORS = {
1850
- ACTIVE: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
1851
- INACTIVE: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
1852
- CONNECTED: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",
1853
- DISCONNECTED: "bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",
1854
- PENDING: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",
1855
- ERROR: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",
1856
- PAUSED: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"
1857
- };
1858
- var TYPE_ICONS = {
1859
- CRM: "\uD83D\uDCCA",
1860
- MARKETING: "\uD83D\uDCE3",
1861
- PAYMENT: "\uD83D\uDCB3",
1862
- COMMUNICATION: "\uD83D\uDCAC",
1863
- DATA: "\uD83D\uDDC4\uFE0F",
1864
- CUSTOM: "\u2699\uFE0F"
1865
- };
1866
- function IntegrationDashboard() {
1867
- const [activeTab, setActiveTab] = useState2("integrations");
1868
- const {
1869
- integrations,
1870
- connections,
1871
- syncConfigs,
1872
- loading,
1873
- error,
1874
- stats,
1875
- refetch
1876
- } = useIntegrationData();
1877
- const tabs = [
1878
- { id: "integrations", label: "Integrations", icon: "\uD83D\uDD0C" },
1879
- { id: "connections", label: "Connections", icon: "\uD83D\uDD17" },
1880
- { id: "syncs", label: "Sync Configs", icon: "\uD83D\uDD04" },
1881
- { id: "chat", label: "Chat", icon: "\uD83D\uDCAC" }
1882
- ];
1883
- if (loading) {
1884
- return /* @__PURE__ */ jsxDEV6(LoaderBlock, {
1885
- label: "Loading Integrations..."
1886
- }, undefined, false, undefined, this);
1887
- }
1888
- if (error) {
1889
- return /* @__PURE__ */ jsxDEV6(ErrorState, {
1890
- title: "Failed to load Integrations",
1891
- description: error.message,
1892
- onRetry: refetch,
1893
- retryLabel: "Retry"
1894
- }, undefined, false, undefined, this);
1895
- }
1896
- return /* @__PURE__ */ jsxDEV6("div", {
1897
- className: "space-y-6",
1898
- children: [
1899
- /* @__PURE__ */ jsxDEV6("div", {
1900
- className: "flex items-center justify-between",
1901
- children: [
1902
- /* @__PURE__ */ jsxDEV6("h2", {
1903
- className: "font-bold text-2xl",
1904
- children: "Integration Hub"
1905
- }, undefined, false, undefined, this),
1906
- /* @__PURE__ */ jsxDEV6(Button2, {
1907
- onClick: () => alert("Add integration modal"),
1908
- children: [
1909
- /* @__PURE__ */ jsxDEV6("span", {
1910
- className: "mr-2",
1911
- children: "+"
1912
- }, undefined, false, undefined, this),
1913
- " Add Integration"
1914
- ]
1915
- }, undefined, true, undefined, this)
1916
- ]
1917
- }, undefined, true, undefined, this),
1918
- /* @__PURE__ */ jsxDEV6(StatCardGroup, {
1919
- children: [
1920
- /* @__PURE__ */ jsxDEV6(StatCard, {
1921
- label: "Integrations",
1922
- value: stats.totalIntegrations,
1923
- hint: `${stats.activeIntegrations} active`
1924
- }, undefined, false, undefined, this),
1925
- /* @__PURE__ */ jsxDEV6(StatCard, {
1926
- label: "Connections",
1927
- value: stats.totalConnections,
1928
- hint: `${stats.connectedCount} connected`
1929
- }, undefined, false, undefined, this),
1930
- /* @__PURE__ */ jsxDEV6(StatCard, {
1931
- label: "Syncs",
1932
- value: stats.totalSyncs,
1933
- hint: `${stats.activeSyncs} active`
1934
- }, undefined, false, undefined, this)
1935
- ]
1936
- }, undefined, true, undefined, this),
1937
- /* @__PURE__ */ jsxDEV6(IntegrationVisualizationOverview, {
1938
- connections,
1939
- integrations,
1940
- syncConfigs
1941
- }, undefined, false, undefined, this),
1942
- /* @__PURE__ */ jsxDEV6("nav", {
1943
- className: "flex gap-1 rounded-lg bg-muted p-1",
1944
- role: "tablist",
1945
- children: tabs.map((tab) => /* @__PURE__ */ jsxDEV6(Button2, {
1946
- type: "button",
1947
- role: "tab",
1948
- "aria-selected": activeTab === tab.id,
1949
- onClick: () => setActiveTab(tab.id),
1950
- className: `flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${activeTab === tab.id ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
1951
- children: [
1952
- /* @__PURE__ */ jsxDEV6("span", {
1953
- children: tab.icon
1954
- }, undefined, false, undefined, this),
1955
- tab.label
1956
- ]
1957
- }, tab.id, true, undefined, this))
1958
- }, undefined, false, undefined, this),
1959
- /* @__PURE__ */ jsxDEV6("div", {
1960
- className: "min-h-[400px]",
1961
- role: "tabpanel",
1962
- children: [
1963
- activeTab === "integrations" && /* @__PURE__ */ jsxDEV6("div", {
1964
- className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-3",
1965
- children: [
1966
- integrations.map((integration) => /* @__PURE__ */ jsxDEV6("div", {
1967
- className: "cursor-pointer rounded-lg border border-border bg-card p-4 transition-colors hover:bg-muted/50",
1968
- children: [
1969
- /* @__PURE__ */ jsxDEV6("div", {
1970
- className: "mb-3 flex items-center gap-3",
1971
- children: [
1972
- /* @__PURE__ */ jsxDEV6("span", {
1973
- className: "text-2xl",
1974
- children: TYPE_ICONS[integration.type] ?? "\u2699\uFE0F"
1975
- }, undefined, false, undefined, this),
1976
- /* @__PURE__ */ jsxDEV6("div", {
1977
- children: [
1978
- /* @__PURE__ */ jsxDEV6("h3", {
1979
- className: "font-medium",
1980
- children: integration.name
1981
- }, undefined, false, undefined, this),
1982
- /* @__PURE__ */ jsxDEV6("p", {
1983
- className: "text-muted-foreground text-sm",
1984
- children: integration.type
1985
- }, undefined, false, undefined, this)
1986
- ]
1987
- }, undefined, true, undefined, this)
1988
- ]
1989
- }, undefined, true, undefined, this),
1990
- /* @__PURE__ */ jsxDEV6("div", {
1991
- className: "flex items-center justify-between",
1992
- children: [
1993
- /* @__PURE__ */ jsxDEV6("span", {
1994
- className: `inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${STATUS_COLORS[integration.status] ?? ""}`,
1995
- children: integration.status
1996
- }, undefined, false, undefined, this),
1997
- /* @__PURE__ */ jsxDEV6("span", {
1998
- className: "text-muted-foreground text-xs",
1999
- children: integration.createdAt.toLocaleDateString()
2000
- }, undefined, false, undefined, this)
2001
- ]
2002
- }, undefined, true, undefined, this)
2003
- ]
2004
- }, integration.id, true, undefined, this)),
2005
- integrations.length === 0 && /* @__PURE__ */ jsxDEV6("div", {
2006
- className: "col-span-full flex h-64 items-center justify-center text-muted-foreground",
2007
- children: "No integrations configured"
2008
- }, undefined, false, undefined, this)
2009
- ]
2010
- }, undefined, true, undefined, this),
2011
- activeTab === "connections" && /* @__PURE__ */ jsxDEV6(ConnectionsTable, {
2012
- connections
2013
- }, undefined, false, undefined, this),
2014
- activeTab === "chat" && /* @__PURE__ */ jsxDEV6(IntegrationHubChat, {
2015
- proxyUrl: "/api/chat",
2016
- thinkingLevel: "thinking",
2017
- suggestions: [
2018
- "List my integrations",
2019
- "Show sync status",
2020
- "Add a connection"
2021
- ],
2022
- className: "min-h-[400px]"
2023
- }, undefined, false, undefined, this),
2024
- activeTab === "syncs" && /* @__PURE__ */ jsxDEV6(SyncConfigsTable, {
2025
- syncConfigs
2026
- }, undefined, false, undefined, this)
2027
- ]
2028
- }, undefined, true, undefined, this)
2029
- ]
2030
- }, undefined, true, undefined, this);
2031
- }
2032
-
2033
- // src/ui/renderers/integration.markdown.ts
2034
- var mockIntegrations = [
2035
- {
2036
- id: "int-1",
2037
- name: "Salesforce",
2038
- type: "CRM",
2039
- status: "ACTIVE",
2040
- connectionCount: 3
2041
- },
2042
- {
2043
- id: "int-2",
2044
- name: "HubSpot",
2045
- type: "MARKETING",
2046
- status: "ACTIVE",
2047
- connectionCount: 2
2048
- },
2049
- {
2050
- id: "int-3",
2051
- name: "Stripe",
2052
- type: "PAYMENT",
2053
- status: "ACTIVE",
2054
- connectionCount: 1
2055
- },
2056
- {
2057
- id: "int-4",
2058
- name: "Slack",
2059
- type: "COMMUNICATION",
2060
- status: "INACTIVE",
2061
- connectionCount: 0
2062
- },
2063
- {
2064
- id: "int-5",
2065
- name: "Google Sheets",
2066
- type: "DATA",
2067
- status: "ACTIVE",
2068
- connectionCount: 5
2069
- },
2070
- {
2071
- id: "int-6",
2072
- name: "PostHog",
2073
- type: "ANALYTICS",
2074
- status: "ACTIVE",
2075
- connectionCount: 1
2076
- }
2077
- ];
2078
- var mockConnections = [
2079
- {
2080
- id: "conn-1",
2081
- integrationId: "int-1",
2082
- name: "Production Salesforce",
2083
- status: "CONNECTED",
2084
- lastSyncAt: "2024-01-16T10:00:00Z"
2085
- },
2086
- {
2087
- id: "conn-2",
2088
- integrationId: "int-1",
2089
- name: "Sandbox Salesforce",
2090
- status: "CONNECTED",
2091
- lastSyncAt: "2024-01-15T14:00:00Z"
2092
- },
2093
- {
2094
- id: "conn-3",
2095
- integrationId: "int-2",
2096
- name: "Marketing HubSpot",
2097
- status: "CONNECTED",
2098
- lastSyncAt: "2024-01-16T08:00:00Z"
2099
- },
2100
- {
2101
- id: "conn-4",
2102
- integrationId: "int-3",
2103
- name: "Stripe Live",
2104
- status: "CONNECTED",
2105
- lastSyncAt: "2024-01-16T12:00:00Z"
2106
- },
2107
- {
2108
- id: "conn-5",
2109
- integrationId: "int-5",
2110
- name: "Analytics Sheet",
2111
- status: "ERROR",
2112
- lastSyncAt: "2024-01-14T09:00:00Z",
2113
- error: "Authentication expired"
2114
- },
2115
- {
2116
- id: "conn-6",
2117
- integrationId: "int-6",
2118
- name: "PostHog Workspace",
2119
- status: "CONNECTED",
2120
- lastSyncAt: "2024-01-16T11:45:00Z"
2121
- }
2122
- ];
2123
- var mockSyncConfigs = [
2124
- {
2125
- id: "sync-1",
2126
- connectionId: "conn-1",
2127
- name: "Contacts Sync",
2128
- frequency: "HOURLY",
2129
- lastRunAt: "2024-01-16T10:00:00Z",
2130
- status: "SUCCESS",
2131
- recordsSynced: 1250
2132
- },
2133
- {
2134
- id: "sync-2",
2135
- connectionId: "conn-1",
2136
- name: "Opportunities Sync",
2137
- frequency: "DAILY",
2138
- lastRunAt: "2024-01-16T00:00:00Z",
2139
- status: "SUCCESS",
2140
- recordsSynced: 340
2141
- },
2142
- {
2143
- id: "sync-3",
2144
- connectionId: "conn-3",
2145
- name: "Orders Sync",
2146
- frequency: "REALTIME",
2147
- lastRunAt: "2024-01-16T12:30:00Z",
2148
- status: "SUCCESS",
2149
- recordsSynced: 89
2150
- },
2151
- {
2152
- id: "sync-4",
2153
- connectionId: "conn-5",
2154
- name: "Metrics Export",
2155
- frequency: "DAILY",
2156
- lastRunAt: "2024-01-14T09:00:00Z",
2157
- status: "FAILED",
2158
- recordsSynced: 0
2159
- }
2160
- ];
2161
- var integrationDashboardMarkdownRenderer = {
2162
- target: "markdown",
2163
- render: async (desc) => {
2164
- if (desc.source.type !== "component" || desc.source.componentKey !== "IntegrationDashboard") {
2165
- throw new Error("integrationDashboardMarkdownRenderer: not IntegrationDashboard");
2166
- }
2167
- const integrations = mockIntegrations;
2168
- const connections = mockConnections;
2169
- const syncs = mockSyncConfigs;
2170
- const visualizations = createIntegrationVisualizationSections(integrations, connections, syncs);
2171
- const activeIntegrations = integrations.filter((i) => i.status === "ACTIVE");
2172
- const connectedConnections = connections.filter((c) => c.status === "CONNECTED");
2173
- const errorConnections = connections.filter((c) => c.status === "ERROR");
2174
- const successfulSyncs = syncs.filter((s) => s.status === "SUCCESS");
2175
- const totalRecordsSynced = successfulSyncs.reduce((sum, s) => sum + s.recordsSynced, 0);
2176
- const lines = [
2177
- "# Integration Hub",
2178
- "",
2179
- "> Connect and sync data with external services",
2180
- "",
2181
- "## Overview",
2182
- "",
2183
- "| Metric | Value |",
2184
- "|--------|-------|",
2185
- `| Active Integrations | ${activeIntegrations.length} |`,
2186
- `| Connected Services | ${connectedConnections.length} |`,
2187
- `| Error Connections | ${errorConnections.length} |`,
2188
- `| Sync Configs | ${syncs.length} |`,
2189
- `| Records Synced (24h) | ${totalRecordsSynced.toLocaleString()} |`,
2190
- ""
2191
- ];
2192
- lines.push("## Visualization Overview");
2193
- lines.push("");
2194
- for (const item of [
2195
- ...visualizations.primaryItems,
2196
- ...visualizations.comparisonItems
2197
- ]) {
2198
- lines.push(`- **${item.title}** via \`${item.spec.meta.key}\``);
2199
- }
2200
- lines.push("");
2201
- lines.push("## Integrations");
2202
- lines.push("");
2203
- lines.push("| Name | Type | Connections | Status |");
2204
- lines.push("|------|------|-------------|--------|");
2205
- for (const integration of integrations) {
2206
- const statusIcon = integration.status === "ACTIVE" ? "\uD83D\uDFE2" : "\u26AB";
2207
- lines.push(`| ${integration.name} | ${integration.type} | ${integration.connectionCount} | ${statusIcon} ${integration.status} |`);
2208
- }
2209
- lines.push("");
2210
- lines.push("## Recent Sync Activity");
2211
- lines.push("");
2212
- lines.push("| Sync | Frequency | Last Run | Records | Status |");
2213
- lines.push("|------|-----------|----------|---------|--------|");
2214
- for (const sync of syncs) {
2215
- const lastRun = new Date(sync.lastRunAt).toLocaleString();
2216
- const statusIcon = sync.status === "SUCCESS" ? "\u2705" : "\u274C";
2217
- lines.push(`| ${sync.name} | ${sync.frequency} | ${lastRun} | ${sync.recordsSynced} | ${statusIcon} ${sync.status} |`);
2218
- }
2219
- if (errorConnections.length > 0) {
2220
- lines.push("");
2221
- lines.push("## \u26A0\uFE0F Connections with Errors");
2222
- lines.push("");
2223
- for (const conn of errorConnections) {
2224
- const integration = integrations.find((i) => i.id === conn.integrationId);
2225
- lines.push(`- **${conn.name}** (${integration?.name ?? "Unknown"}): ${conn.error ?? "Unknown error"}`);
2226
- }
2227
- }
2228
- return {
2229
- mimeType: "text/markdown",
2230
- body: lines.join(`
2231
- `)
2232
- };
2233
- }
2234
- };
2235
- var connectionListMarkdownRenderer = {
2236
- target: "markdown",
2237
- render: async (desc) => {
2238
- if (desc.source.type !== "component" || desc.source.componentKey !== "ConnectionList") {
2239
- throw new Error("connectionListMarkdownRenderer: not ConnectionList");
2240
- }
2241
- const connections = mockConnections;
2242
- const integrations = mockIntegrations;
2243
- const lines = [
2244
- "# Connections",
2245
- "",
2246
- "> Manage connections to external services",
2247
- ""
2248
- ];
2249
- for (const integration of integrations) {
2250
- const intConnections = connections.filter((c) => c.integrationId === integration.id);
2251
- if (intConnections.length === 0)
2252
- continue;
2253
- lines.push(`## ${integration.name}`);
2254
- lines.push("");
2255
- lines.push("| Connection | Status | Last Sync |");
2256
- lines.push("|------------|--------|-----------|");
2257
- for (const conn of intConnections) {
2258
- const lastSync = new Date(conn.lastSyncAt).toLocaleString();
2259
- const statusIcon = conn.status === "CONNECTED" ? "\uD83D\uDFE2" : conn.status === "ERROR" ? "\uD83D\uDD34" : "\u26AB";
2260
- lines.push(`| ${conn.name} | ${statusIcon} ${conn.status} | ${lastSync} |`);
2261
- }
2262
- lines.push("");
2263
- }
2264
- return {
2265
- mimeType: "text/markdown",
2266
- body: lines.join(`
2267
- `)
2268
- };
2269
- }
2270
- };
2271
- var syncConfigMarkdownRenderer = {
2272
- target: "markdown",
2273
- render: async (desc) => {
2274
- if (desc.source.type !== "component" || desc.source.componentKey !== "SyncConfigEditor") {
2275
- throw new Error("syncConfigMarkdownRenderer: not SyncConfigEditor");
2276
- }
2277
- const syncs = mockSyncConfigs;
2278
- const connections = mockConnections;
2279
- const lines = [
2280
- "# Sync Configurations",
2281
- "",
2282
- "> Configure automated data synchronization",
2283
- ""
2284
- ];
2285
- for (const sync of syncs) {
2286
- const connection = connections.find((c) => c.id === sync.connectionId);
2287
- const statusIcon = sync.status === "SUCCESS" ? "\u2705" : "\u274C";
2288
- lines.push(`## ${sync.name}`);
2289
- lines.push("");
2290
- lines.push(`**Connection:** ${connection?.name ?? "Unknown"}`);
2291
- lines.push(`**Frequency:** ${sync.frequency}`);
2292
- lines.push(`**Status:** ${statusIcon} ${sync.status}`);
2293
- lines.push(`**Last Run:** ${new Date(sync.lastRunAt).toLocaleString()}`);
2294
- lines.push(`**Records Synced:** ${sync.recordsSynced.toLocaleString()}`);
2295
- lines.push("");
2296
- }
2297
- lines.push("## Frequency Options");
2298
- lines.push("");
2299
- lines.push("- **REALTIME**: Sync on every change");
2300
- lines.push("- **HOURLY**: Sync every hour");
2301
- lines.push("- **DAILY**: Sync once per day");
2302
- lines.push("- **WEEKLY**: Sync once per week");
2303
- lines.push("- **MANUAL**: Sync only when triggered");
2304
- return {
2305
- mimeType: "text/markdown",
2306
- body: lines.join(`
2307
- `)
2308
- };
2309
- }
2310
- };
2311
- export {
2312
- useIntegrationData,
2313
- syncConfigMarkdownRenderer,
2314
- runIntegrationHubMcpExampleFromEnv,
2315
- integrationDashboardMarkdownRenderer,
2316
- hasChanges,
2317
- createSyncEngine,
2318
- createIntegrationVisualizationSections,
2319
- createIntegrationHandlers,
2320
- connectionListMarkdownRenderer,
2321
- computeChecksum,
2322
- TriggerSyncInputModel,
2323
- TriggerSyncContract,
2324
- SyncStatusEnum,
2325
- SyncRunModel,
2326
- SyncDirectionEnum,
2327
- SyncConfigModel,
2328
- MappingTypeEnum,
2329
- ListSyncRunsOutputModel,
2330
- ListSyncRunsInputModel,
2331
- ListSyncRunsContract,
2332
- IntegrationVisualizationSpecs,
2333
- IntegrationVisualizationRegistry,
2334
- IntegrationVisualizationRefs,
2335
- IntegrationTypeVisualization,
2336
- IntegrationStatusEnum,
2337
- IntegrationModel,
2338
- IntegrationHubChat,
2339
- IntegrationDashboard,
2340
- HealthySyncMetricVisualization,
2341
- FieldMappingModel,
2342
- CreateSyncConfigInputModel,
2343
- CreateSyncConfigContract,
2344
- CreateIntegrationInputModel,
2345
- CreateIntegrationContract,
2346
- CreateConnectionInputModel,
2347
- CreateConnectionContract,
2348
- ConnectionStatusVisualization,
2349
- ConnectionStatusEnum,
2350
- ConnectionModel,
2351
- BasicSyncEngine,
2352
- BasicFieldTransformer,
2353
- AttentionSyncMetricVisualization,
2354
- AddFieldMappingInputModel,
2355
- AddFieldMappingContract
2356
- };
2
+ import{defineEnum as HH}from"@contractspec/lib.schema";var KH=HH("ConnectionStatus",["PENDING","CONNECTED","DISCONNECTED","ERROR","EXPIRED"]),XH=HH("AuthType",["api_key","oauth2","bearer","header","basic","webhook_signing","service_account"]),ZH=HH("TransportType",["rest","mcp","webhook","sdk"]);import{defineSchemaModel as jH,ScalarTypeEnum as N}from"@contractspec/lib.schema";var m=jH({name:"ConnectionModel",fields:{id:{type:N.String_unsecure(),isOptional:!1},integrationId:{type:N.String_unsecure(),isOptional:!1},name:{type:N.String_unsecure(),isOptional:!1},status:{type:KH,isOptional:!1},authType:{type:N.String_unsecure(),isOptional:!1},externalAccountName:{type:N.String_unsecure(),isOptional:!0},connectedAt:{type:N.DateTime(),isOptional:!0},lastHealthCheck:{type:N.DateTime(),isOptional:!0},healthStatus:{type:N.String_unsecure(),isOptional:!0},transport:{type:ZH,isOptional:!0},authMethod:{type:XH,isOptional:!0},apiVersion:{type:N.String_unsecure(),isOptional:!0},ownershipMode:{type:N.String_unsecure(),isOptional:!0}}}),$H=jH({name:"CreateConnectionInput",fields:{integrationId:{type:N.String_unsecure(),isOptional:!1},name:{type:N.NonEmptyString(),isOptional:!1},authType:{type:N.NonEmptyString(),isOptional:!1},credentials:{type:N.JSON(),isOptional:!0},transport:{type:ZH,isOptional:!0},authMethod:{type:XH,isOptional:!0},apiVersion:{type:N.String_unsecure(),isOptional:!0},ownershipMode:{type:N.String_unsecure(),isOptional:!0}}});import{defineCommand as aH}from"@contractspec/lib.contracts-spec/operations";var nH=["@example.integration-hub"],eH=aH({meta:{key:"integration.connection.create",version:"1.0.0",stability:"stable",owners:[...nH],tags:["integration","connection","create"],description:"Create a connection to an external system.",goal:"Authenticate with external systems.",context:"Connection setup."},io:{input:$H,output:m},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.connection.created",version:"1.0.0",when:"Connection created",payload:m}],audit:["integration.connection.created"]},acceptance:{scenarios:[{key:"create-connection-happy-path",given:["User is authenticated"],when:["User creates connection with valid credentials"],then:["Connection is created","ConnectionCreated event is emitted"]}],examples:[{key:"connect-crm",input:{name:"Salesforce Prod",integrationId:"salesforce",credentials:{clientId:"xxx"}},output:{id:"conn-123",status:"connected",connectedAt:"2025-01-01T12:00:00Z"}}]}});import{web as HK}from"@contractspec/lib.runtime-sandbox";var{generateId:p}=HK;function hH(H){return{id:H.id,projectId:H.projectId,organizationId:H.organizationId,name:H.name,description:H.description??void 0,type:H.type,status:H.status,iconUrl:H.iconUrl??void 0,createdAt:new Date(H.createdAt),updatedAt:new Date(H.updatedAt)}}function QH(H){return{id:H.id,integrationId:H.integrationId,name:H.name,status:H.status,credentials:H.credentials?JSON.parse(H.credentials):void 0,config:H.config?JSON.parse(H.config):void 0,lastSyncAt:H.lastSyncAt?new Date(H.lastSyncAt):void 0,errorMessage:H.errorMessage??void 0,createdAt:new Date(H.createdAt),updatedAt:new Date(H.updatedAt)}}function qH(H){return{id:H.id,connectionId:H.connectionId,name:H.name,sourceEntity:H.sourceEntity,targetEntity:H.targetEntity,frequency:H.frequency,status:H.status,lastRunAt:H.lastRunAt?new Date(H.lastRunAt):void 0,lastRunStatus:H.lastRunStatus??void 0,recordsSynced:H.recordsSynced,createdAt:new Date(H.createdAt),updatedAt:new Date(H.updatedAt)}}function xH(H){return{id:H.id,syncConfigId:H.syncConfigId,sourceField:H.sourceField,targetField:H.targetField,transformType:H.transformType??void 0,transformConfig:H.transformConfig?JSON.parse(H.transformConfig):void 0,createdAt:new Date(H.createdAt)}}function KK(H){async function Z(Q){let{projectId:Y,type:P,status:B,search:_,limit:z=20,offset:M=0}=Q,j="WHERE projectId = ?",f=[Y];if(P&&P!=="all")j+=" AND type = ?",f.push(P);if(B&&B!=="all")j+=" AND status = ?",f.push(B);if(_)j+=" AND name LIKE ?",f.push(`%${_}%`);let sH=(await H.query(`SELECT COUNT(*) as count FROM integration ${j}`,f)).rows[0]?.count??0;return{integrations:(await H.query(`SELECT * FROM integration ${j} ORDER BY name LIMIT ? OFFSET ?`,[...f,z,M])).rows.map(hH),total:sH}}async function K(Q,Y){let P=p("integ"),B=new Date().toISOString();await H.execute(`INSERT INTO integration (id, projectId, organizationId, name, description, type, status, iconUrl, createdAt, updatedAt)
3
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[P,Y.projectId,Y.organizationId,Q.name,Q.description??null,Q.type,"INACTIVE",Q.iconUrl??null,B,B]);let _=(await H.query("SELECT * FROM integration WHERE id = ?",[P])).rows;return hH(_[0])}async function X(Q){let{integrationId:Y,status:P,limit:B=20,offset:_=0}=Q,z="WHERE 1=1",M=[];if(Y)z+=" AND integrationId = ?",M.push(Y);if(P&&P!=="all")z+=" AND status = ?",M.push(P);let f=(await H.query(`SELECT COUNT(*) as count FROM integration_connection ${z}`,M)).rows[0]?.count??0;return{connections:(await H.query(`SELECT * FROM integration_connection ${z} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`,[...M,B,_])).rows.map(QH),total:f}}async function $(Q){let Y=p("conn"),P=new Date().toISOString();await H.execute(`INSERT INTO integration_connection (id, integrationId, name, status, credentials, config, createdAt, updatedAt)
4
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[Y,Q.integrationId,Q.name,"PENDING",Q.credentials?JSON.stringify(Q.credentials):null,Q.config?JSON.stringify(Q.config):null,P,P]),await H.execute("UPDATE integration_connection SET status = 'CONNECTED', updatedAt = ? WHERE id = ?",[P,Y]),await H.execute("UPDATE integration SET status = 'ACTIVE', updatedAt = ? WHERE id = ?",[P,Q.integrationId]);let B=(await H.query("SELECT * FROM integration_connection WHERE id = ?",[Y])).rows;return QH(B[0])}async function q(Q){let Y=new Date().toISOString();await H.execute("UPDATE integration_connection SET status = 'DISCONNECTED', updatedAt = ? WHERE id = ?",[Y,Q]);let P=(await H.query("SELECT * FROM integration_connection WHERE id = ?",[Q])).rows;return QH(P[0])}async function G(Q){let{connectionId:Y,status:P,limit:B=20,offset:_=0}=Q,z="WHERE 1=1",M=[];if(Y)z+=" AND connectionId = ?",M.push(Y);if(P&&P!=="all")z+=" AND status = ?",M.push(P);let f=(await H.query(`SELECT COUNT(*) as count FROM integration_sync_config ${z}`,M)).rows[0]?.count??0;return{configs:(await H.query(`SELECT * FROM integration_sync_config ${z} ORDER BY updatedAt DESC LIMIT ? OFFSET ?`,[...M,B,_])).rows.map(qH),total:f}}async function W(Q){let Y=p("sync"),P=new Date().toISOString();await H.execute(`INSERT INTO integration_sync_config (id, connectionId, name, sourceEntity, targetEntity, frequency, status, recordsSynced, createdAt, updatedAt)
5
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[Y,Q.connectionId,Q.name,Q.sourceEntity,Q.targetEntity,Q.frequency??"DAILY","ACTIVE",0,P,P]);let B=(await H.query("SELECT * FROM integration_sync_config WHERE id = ?",[Y])).rows;return qH(B[0])}async function A(Q){let Y=new Date().toISOString(),P=[];await H.execute("DELETE FROM integration_field_mapping WHERE syncConfigId = ?",[Q.syncConfigId]);for(let B of Q.mappings){let _=p("fmap");await H.execute(`INSERT INTO integration_field_mapping (id, syncConfigId, sourceField, targetField, transformType, transformConfig, createdAt)
6
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,[_,Q.syncConfigId,B.sourceField,B.targetField,B.transformType??null,B.transformConfig?JSON.stringify(B.transformConfig):null,Y]);let z=(await H.query("SELECT * FROM integration_field_mapping WHERE id = ?",[_])).rows;P.push(xH(z[0]))}return P}async function O(Q){return(await H.query("SELECT * FROM integration_field_mapping WHERE syncConfigId = ?",[Q])).rows.map(xH)}async function U(Q){let Y=new Date().toISOString(),P=Math.floor(Math.random()*1000)+50;await H.execute("UPDATE integration_sync_config SET lastRunAt = ?, lastRunStatus = 'SUCCESS', recordsSynced = recordsSynced + ?, updatedAt = ? WHERE id = ?",[Y,P,Y,Q]);let B=(await H.query("SELECT * FROM integration_sync_config WHERE id = ?",[Q])).rows;if(B[0])await H.execute("UPDATE integration_connection SET lastSyncAt = ?, updatedAt = ? WHERE id = ?",[Y,Y,B[0].connectionId]);let _=(await H.query("SELECT * FROM integration_sync_config WHERE id = ?",[Q])).rows;return qH(_[0])}async function D(Q){let Y=(await H.query("SELECT * FROM integration_connection WHERE id = ?",[Q.connectionId])).rows;if(!Y[0])return{valid:!1,provider:"unknown",keyPrefix:"",error:`Connection ${Q.connectionId} not found`};let P=Q.providerKey.slice(0,8),B=Q.providerKey.length>=16;return{valid:B,provider:Y[0].name,keyPrefix:`${P}...`,expiresAt:B?new Date(Date.now()+7776000000).toISOString():void 0,error:B?void 0:"Key must be at least 16 characters"}}async function F(Q){let Y=new Date().toISOString();return await H.execute("UPDATE integration_connection SET updatedAt = ? WHERE id = ?",[Y,Q.connectionId]),{refreshed:!0,expiresAt:new Date(Date.now()+3600000).toISOString(),tokenType:"Bearer",scopes:["read","write","sync"]}}async function V(Q){return{integrationId:Q.integrationId,transports:[{transport:"rest",supported:!0,defaultVersion:"v2"},{transport:"mcp",supported:!0,defaultVersion:"v1"},{transport:"webhook",supported:!0},{transport:"sdk",supported:!1}]}}return{listIntegrations:Z,createIntegration:K,listConnections:X,connectService:$,disconnectService:q,listSyncConfigs:G,configureSync:W,mapFields:A,getFieldMappings:O,runSync:U,validateByokKey:D,refreshOAuth2Token:F,getTransportOptions:V}}import{defineEnum as XK}from"@contractspec/lib.schema";var UH=XK("IntegrationStatus",["DRAFT","ACTIVE","PAUSED","ERROR","ARCHIVED"]);import{defineSchemaModel as EH,ScalarTypeEnum as R}from"@contractspec/lib.schema";var u=EH({name:"IntegrationModel",fields:{id:{type:R.String_unsecure(),isOptional:!1},name:{type:R.String_unsecure(),isOptional:!1},slug:{type:R.String_unsecure(),isOptional:!1},description:{type:R.String_unsecure(),isOptional:!0},provider:{type:R.String_unsecure(),isOptional:!1},status:{type:UH,isOptional:!1},createdAt:{type:R.DateTime(),isOptional:!1}}}),JH=EH({name:"CreateIntegrationInput",fields:{name:{type:R.NonEmptyString(),isOptional:!1},slug:{type:R.NonEmptyString(),isOptional:!1},description:{type:R.String_unsecure(),isOptional:!0},provider:{type:R.NonEmptyString(),isOptional:!1},config:{type:R.JSON(),isOptional:!0},featureFlagKey:{type:R.String_unsecure(),isOptional:!0}}});import{defineCommand as ZK}from"@contractspec/lib.contracts-spec/operations";var $K=ZK({meta:{key:"integration.create",version:"1.0.0",stability:"stable",owners:["@example.integration-hub"],tags:["integration","create"],description:"Create a new integration.",goal:"Allow users to set up integrations with external systems.",context:"Integration setup."},io:{input:JH,output:u},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.created",version:"1.0.0",when:"Integration created",payload:u}],audit:["integration.created"]},acceptance:{scenarios:[{key:"create-integration-happy-path",given:["User is admin"],when:["User defines new integration type"],then:["Integration definition is created","IntegrationCreated event is emitted"]}],examples:[{key:"create-slack",input:{name:"Slack",category:"communication",authType:"oauth2"},output:{id:"slack",status:"active"}}]}});import{createMcpToolsets as QK}from"@contractspec/lib.ai-agent/tools/mcp-client";import{randomUUID as qK}from"crypto";var UK=["-y","@modelcontextprotocol/server-filesystem","."];async function MX(){let H=YK(),Z=vH(),K=JK(),X=await QK([K],{onNameCollision:"error"});try{let $=Object.keys(X.tools).sort(),q={mode:H,server:{name:K.name,transport:Z},authMethod:process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_AUTH_METHOD,apiVersion:process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_API_VERSION,tools:$};if(H==="call"){let G=wH("CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_NAME"),W=GK("CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_ARGS_JSON",{}),A=X.tools[G];if(!A?.execute)throw Error(`Tool "${G}" was not found. Available tools: ${$.join(", ")}`);let O=await A.execute(W,{toolCallId:`integration-hub-${qK()}`,messages:[]});q.toolCall={name:G,args:W,output:O}}return q}finally{await X.cleanup().catch(()=>{return})}}function JK(){let H=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_NAME??"filesystem",Z=vH(),K=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_TOOL_PREFIX;if(Z==="stdio")return{name:H,transport:Z,command:process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_COMMAND??"npx",args:DK("CONTRACTSPEC_INTEGRATION_HUB_MCP_ARGS_JSON",UK),toolPrefix:K};let X=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_ACCESS_TOKEN,$=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_ACCESS_TOKEN_ENV;return{name:H,transport:Z==="webhook"||Z==="http"?"http":"sse",url:wH("CONTRACTSPEC_INTEGRATION_HUB_MCP_URL"),headers:PK("CONTRACTSPEC_INTEGRATION_HUB_MCP_HEADERS_JSON"),accessToken:X,accessTokenEnvVar:$,toolPrefix:K}}function YK(){let H=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_MODE?.toLowerCase()??"list";if(H==="list"||H==="call")return H;throw Error(`Unsupported CONTRACTSPEC_INTEGRATION_HUB_MCP_MODE: ${H}. Use "list" or "call".`)}function vH(){let H=process.env.CONTRACTSPEC_INTEGRATION_HUB_MCP_TRANSPORT?.toLowerCase()??"stdio";if(H==="stdio"||H==="http"||H==="sse"||H==="webhook")return H;throw Error(`Unsupported CONTRACTSPEC_INTEGRATION_HUB_MCP_TRANSPORT: ${H}. Use "stdio", "http", "sse", or "webhook".`)}function DK(H,Z){if(!process.env[H])return Z;let X=TH(H);if(!Array.isArray(X)||X.some(($)=>typeof $!=="string"))throw Error(`${H} must be a JSON string array.`);return X}function bH(H){if(!process.env[H])return;let K=TH(H);if(!WK(K))throw Error(`${H} must be a JSON object.`);return K}function GK(H,Z){return bH(H)??Z}function PK(H){let Z=bH(H);if(!Z)return;let K=Object.entries(Z);if(K.find(([,$])=>typeof $!=="string"))throw Error(`${H} must contain only string values.`);return Object.fromEntries(K)}function TH(H){let Z=process.env[H];if(!Z)return;try{return JSON.parse(Z)}catch{throw Error(`${H} contains invalid JSON.`)}}function wH(H){let Z=process.env[H];if(!Z)throw Error(`Missing required env var: ${H}`);return Z}function WK(H){return typeof H==="object"&&H!==null&&!Array.isArray(H)}import{defineEnum as YH}from"@contractspec/lib.schema";var x=YH("SyncDirection",["INBOUND","OUTBOUND","BIDIRECTIONAL"]),l=YH("SyncStatus",["PENDING","RUNNING","COMPLETED","FAILED","CANCELLED"]),c=YH("MappingType",["DIRECT","TRANSFORM","LOOKUP","CONSTANT","COMPUTED"]);import{defineSchemaModel as C,ScalarTypeEnum as J}from"@contractspec/lib.schema";var b=C({name:"FieldMappingModel",fields:{id:{type:J.String_unsecure(),isOptional:!1},sourceField:{type:J.String_unsecure(),isOptional:!1},targetField:{type:J.String_unsecure(),isOptional:!1},mappingType:{type:c,isOptional:!1},transformExpression:{type:J.String_unsecure(),isOptional:!0},isRequired:{type:J.Boolean(),isOptional:!1}}}),r=C({name:"SyncConfigModel",fields:{id:{type:J.String_unsecure(),isOptional:!1},integrationId:{type:J.String_unsecure(),isOptional:!1},connectionId:{type:J.String_unsecure(),isOptional:!1},name:{type:J.String_unsecure(),isOptional:!1},direction:{type:x,isOptional:!1},sourceObject:{type:J.String_unsecure(),isOptional:!1},targetObject:{type:J.String_unsecure(),isOptional:!1},scheduleEnabled:{type:J.Boolean(),isOptional:!1},scheduleCron:{type:J.String_unsecure(),isOptional:!0},isActive:{type:J.Boolean(),isOptional:!1},lastSyncAt:{type:J.DateTime(),isOptional:!0},fieldMappings:{type:b,isArray:!0,isOptional:!0}}}),T=C({name:"SyncRunModel",fields:{id:{type:J.String_unsecure(),isOptional:!1},syncConfigId:{type:J.String_unsecure(),isOptional:!1},status:{type:l,isOptional:!1},direction:{type:x,isOptional:!1},trigger:{type:J.String_unsecure(),isOptional:!1},recordsProcessed:{type:J.Int_unsecure(),isOptional:!1},recordsCreated:{type:J.Int_unsecure(),isOptional:!1},recordsUpdated:{type:J.Int_unsecure(),isOptional:!1},recordsFailed:{type:J.Int_unsecure(),isOptional:!1},errorMessage:{type:J.String_unsecure(),isOptional:!0},startedAt:{type:J.DateTime(),isOptional:!0},completedAt:{type:J.DateTime(),isOptional:!0},createdAt:{type:J.DateTime(),isOptional:!1}}}),DH=C({name:"CreateSyncConfigInput",fields:{integrationId:{type:J.String_unsecure(),isOptional:!1},connectionId:{type:J.String_unsecure(),isOptional:!1},name:{type:J.NonEmptyString(),isOptional:!1},direction:{type:x,isOptional:!1},sourceObject:{type:J.NonEmptyString(),isOptional:!1},targetObject:{type:J.NonEmptyString(),isOptional:!1},scheduleEnabled:{type:J.Boolean(),isOptional:!0},scheduleCron:{type:J.String_unsecure(),isOptional:!0}}}),GH=C({name:"AddFieldMappingInput",fields:{syncConfigId:{type:J.String_unsecure(),isOptional:!1},sourceField:{type:J.NonEmptyString(),isOptional:!1},targetField:{type:J.NonEmptyString(),isOptional:!1},mappingType:{type:c,isOptional:!1},transformExpression:{type:J.String_unsecure(),isOptional:!0},lookupConfig:{type:J.JSON(),isOptional:!0},constantValue:{type:J.JSON(),isOptional:!0},isRequired:{type:J.Boolean(),isOptional:!0},defaultValue:{type:J.JSON(),isOptional:!0}}}),PH=C({name:"TriggerSyncInput",fields:{syncConfigId:{type:J.String_unsecure(),isOptional:!1},direction:{type:x,isOptional:!0},fullSync:{type:J.Boolean(),isOptional:!0}}}),WH=C({name:"ListSyncRunsInput",fields:{syncConfigId:{type:J.String_unsecure(),isOptional:!1},status:{type:l,isOptional:!0},limit:{type:J.Int_unsecure(),isOptional:!0,defaultValue:20},offset:{type:J.Int_unsecure(),isOptional:!0,defaultValue:0}}}),BH=C({name:"ListSyncRunsOutput",fields:{runs:{type:T,isArray:!0,isOptional:!1},total:{type:J.Int_unsecure(),isOptional:!1}}});import{defineCommand as OH,defineQuery as BK}from"@contractspec/lib.contracts-spec/operations";var i=["@example.integration-hub"],OK=OH({meta:{key:"integration.syncConfig.create",version:"1.0.0",stability:"stable",owners:[...i],tags:["integration","sync","config","create"],description:"Create a sync configuration.",goal:"Define how data should be synchronized.",context:"Sync setup."},io:{input:DH,output:r},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.syncConfig.created",version:"1.0.0",when:"Sync config created",payload:r}],audit:["integration.syncConfig.created"]},acceptance:{scenarios:[{key:"create-sync-happy-path",given:["User is authenticated"],when:["User creates sync config"],then:["Sync config is created","SyncConfigCreated event is emitted"]}],examples:[{key:"create-contact-sync",input:{name:"Contacts Sync",sourceConnectionId:"conn-1",targetConnectionId:"conn-2"},output:{id:"sync-123",status:"active"}}]}}),LK=OH({meta:{key:"integration.fieldMapping.add",version:"1.0.0",stability:"stable",owners:[...i],tags:["integration","mapping","field"],description:"Add a field mapping to a sync config.",goal:"Map fields between systems.",context:"Mapping configuration."},io:{input:GH,output:b},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.fieldMapping.added",version:"1.0.0",when:"Mapping added",payload:b}]},acceptance:{scenarios:[{key:"add-mapping-happy-path",given:["Sync config exists"],when:["User adds field mapping"],then:["Mapping is added","FieldMappingAdded event is emitted"]}],examples:[{key:"map-email",input:{syncConfigId:"sync-123",sourceField:"email",targetField:"user_email"},output:{id:"map-456",type:"string"}}]}}),NK=OH({meta:{key:"integration.sync.trigger",version:"1.0.0",stability:"stable",owners:[...i],tags:["integration","sync","trigger"],description:"Trigger a manual sync.",goal:"Start data synchronization.",context:"Manual sync or webhook trigger."},io:{input:PH,output:T},policy:{auth:"user"},sideEffects:{emits:[{key:"integration.sync.started",version:"1.0.0",when:"Sync starts",payload:T}],audit:["integration.sync.triggered"]},acceptance:{scenarios:[{key:"trigger-sync-happy-path",given:["Sync config exists"],when:["User triggers sync"],then:["Sync run starts","SyncStarted event is emitted"]}],examples:[{key:"manual-trigger",input:{syncConfigId:"sync-123"},output:{id:"run-789",status:"pending"}}]}}),AK=BK({meta:{key:"integration.syncRun.list",version:"1.0.0",stability:"stable",owners:[...i],tags:["integration","sync","run","list"],description:"List sync run history.",goal:"View sync history and status.",context:"Sync monitoring."},io:{input:WH,output:BH},policy:{auth:"user"},acceptance:{scenarios:[{key:"list-runs-happy-path",given:["User has access to syncs"],when:["User lists sync runs"],then:["List of runs is returned"]}],examples:[{key:"list-recent",input:{limit:10},output:{items:[],total:50}}]}});class SH{transform(H,Z){try{if(Z.startsWith("uppercase"))return typeof H==="string"?H.toUpperCase():H;if(Z.startsWith("lowercase"))return typeof H==="string"?H.toLowerCase():H;if(Z.startsWith("trim"))return typeof H==="string"?H.trim():H;if(Z.startsWith("default:")){let K=Z.replace("default:","");return H??JSON.parse(K)}if(Z.startsWith("concat:")){let K=Z.replace("concat:","")||" ";if(Array.isArray(H))return H.join(K);return H}if(Z.startsWith("split:")){let K=Z.replace("split:","")||",";if(typeof H==="string")return H.split(K);return H}if(Z.startsWith("number"))return Number(H);if(Z.startsWith("boolean"))return Boolean(H);if(Z.startsWith("string"))return String(H);return H}catch{return H}}}class gH{transformer;constructor(H){this.transformer=H??new SH}async sync(H){return{success:!0,recordsProcessed:0,recordsCreated:0,recordsUpdated:0,recordsDeleted:0,recordsFailed:0,recordsSkipped:0,errors:[]}}transformRecord(H,Z,K){let X={};for(let $ of Z){let q,G;switch($.mappingType){case"DIRECT":q=this.getNestedValue(H.data,$.sourceField);break;case"TRANSFORM":G=this.getNestedValue(H.data,$.sourceField),q=$.transformExpression?this.transformer.transform(G,$.transformExpression):G;break;case"CONSTANT":q=$.constantValue;break;case"LOOKUP":q=this.getNestedValue(H.data,$.sourceField);break;case"COMPUTED":q=$.transformExpression?this.evaluateComputed(H.data,$.transformExpression):null;break;default:q=this.getNestedValue(H.data,$.sourceField)}if(q===void 0||q===null)q=$.defaultValue;this.setNestedValue(X,$.targetField,q)}return{id:H.id,data:X}}validateRecord(H,Z){let K=[];for(let X of Z)if(X.isRequired){let $=this.getNestedValue(H.data,X.targetField);if($===void 0||$===null)K.push({recordId:H.id,field:X.targetField,message:`Required field ${X.targetField} is missing`,code:"REQUIRED_FIELD_MISSING"})}return{valid:K.length===0,errors:K}}getNestedValue(H,Z){let K=Z.split("."),X=H;for(let $ of K){if(X===null||X===void 0)return;X=X[$]}return X}setNestedValue(H,Z,K){let X=Z.split("."),$=H;for(let G=0;G<X.length-1;G++){let W=X[G];if(W===void 0)continue;if(!(W in $))$[W]={};$=$[W]}let q=X[X.length-1];if(q!==void 0)$[q]=K}evaluateComputed(H,Z){try{return Z.replace(/\$\{([^}]+)\}/g,(X,$)=>{let q=this.getNestedValue(H,$);return String(q??"")})}catch{return null}}}function gX(H){return new gH(H)}function yX(H){let Z=JSON.stringify(H,Object.keys(H).sort()),K=0;for(let X=0;X<Z.length;X++){let $=Z.charCodeAt(X);K=(K<<5)-K+$,K=K&K}return K.toString(16)}function dX(H,Z){if(!H||!Z)return!0;return H!==Z}import{useTemplateRuntime as FK}from"@contractspec/lib.example-shared-ui";import{useCallback as _K,useEffect as zK,useState as w}from"react";function LH(H="local-project"){let{handlers:Z}=FK(),K=Z.integration,[X,$]=w([]),[q,G]=w([]),[W,A]=w([]),[O,U]=w(!0),[D,F]=w(null),V=_K(async()=>{try{U(!0),F(null);let[Y,P,B]=await Promise.all([K.listIntegrations({projectId:H,limit:100}),K.listConnections({limit:100}),K.listSyncConfigs({limit:100})]);$(Y.integrations),G(P.connections),A(B.configs)}catch(Y){F(Y instanceof Error?Y:Error("Failed to load integrations"))}finally{U(!1)}},[K,H]);zK(()=>{V()},[V]);let Q={totalIntegrations:X.length,activeIntegrations:X.filter((Y)=>Y.status==="ACTIVE").length,totalConnections:q.length,connectedCount:q.filter((Y)=>Y.status==="CONNECTED").length,totalSyncs:W.length,activeSyncs:W.filter((Y)=>Y.status==="ACTIVE").length};return{integrations:X,connections:q,syncConfigs:W,loading:O,error:D,stats:Q,refetch:V}}import{defineVisualization as o,VisualizationRegistry as RK}from"@contractspec/lib.contracts-spec/visualizations";var VK={key:"integration.list",version:"1.0.0"},MK={key:"integration.connection.list",version:"1.0.0"},yH={key:"integration.syncConfig.list",version:"1.0.0"},t={version:"1.0.0",domain:"integration",stability:"experimental",owners:["@example.integration-hub"],tags:["integration","visualization","sync"]},NH=o({meta:{...t,key:"integration-hub.visualization.integration-types",title:"Integration Types",description:"Distribution of configured integration categories.",goal:"Show where integration coverage is concentrated.",context:"Integration overview."},source:{primary:VK,resultPath:"data"},visualization:{kind:"pie",nameDimension:"type",valueMeasure:"count",dimensions:[{key:"type",label:"Type",dataPath:"type",type:"category"}],measures:[{key:"count",label:"Count",dataPath:"count",format:"number"}],table:{caption:"Integration counts by type."}}}),AH=o({meta:{...t,key:"integration-hub.visualization.connection-status",title:"Connection Status",description:"Status distribution across configured connections.",goal:"Highlight connection health and instability.",context:"Connection monitoring."},source:{primary:MK,resultPath:"data"},visualization:{kind:"cartesian",variant:"bar",xDimension:"status",yMeasures:["count"],dimensions:[{key:"status",label:"Status",dataPath:"status",type:"category"}],measures:[{key:"count",label:"Connections",dataPath:"count",format:"number",color:"#1d4ed8"}],table:{caption:"Connection counts by status."}}}),FH=o({meta:{...t,key:"integration-hub.visualization.sync-healthy",title:"Healthy Syncs",description:"Sync configurations currently healthy or recently successful.",goal:"Summarize healthy synchronization capacity.",context:"Sync-state comparison."},source:{primary:yH,resultPath:"data"},visualization:{kind:"metric",measure:"value",measures:[{key:"value",label:"Syncs",dataPath:"value",format:"number"}],table:{caption:"Healthy sync count."}}}),_H=o({meta:{...t,key:"integration-hub.visualization.sync-attention",title:"Attention Needed",description:"Sync configurations paused, failing, or otherwise needing review.",goal:"Summarize syncs needing action.",context:"Sync-state comparison."},source:{primary:yH,resultPath:"data"},visualization:{kind:"metric",measure:"value",measures:[{key:"value",label:"Syncs",dataPath:"value",format:"number"}],table:{caption:"Syncs requiring attention."}}}),dH=[NH,AH,FH,_H],oX=new RK([...dH]),tX=dH.map((H)=>({key:H.meta.key,version:H.meta.version}));function IK(H){return H==="ACTIVE"||H==="SUCCESS"}function s(H,Z,K){let X=new Map,$=new Map,q=0,G=0;for(let O of H)X.set(O.type,(X.get(O.type)??0)+1);for(let O of Z)$.set(O.status,($.get(O.status)??0)+1);for(let O of K)if(IK(O.status))q+=1;else G+=1;return{primaryItems:[{key:"integration-types",spec:NH,data:{data:Array.from(X.entries()).map(([O,U])=>({type:O,count:U}))},title:"Integration Types",description:"Configured integrations grouped by category.",height:260},{key:"connection-status",spec:AH,data:{data:Array.from($.entries()).map(([O,U])=>({status:O,count:U}))},title:"Connection Status",description:"Operational health across current connections."}],comparisonItems:[{key:"healthy-syncs",spec:FH,data:{data:[{value:q}]},title:"Healthy Syncs",description:"Active or recently successful sync configurations.",height:200},{key:"attention-syncs",spec:_H,data:{data:[{value:G}]},title:"Attention Needed",description:"Paused, failed, or degraded sync configurations.",height:200}]}}import{ComparisonView as kK,VisualizationCard as fK,VisualizationGrid as CK}from"@contractspec/lib.design-system";import{jsx as S,jsxs as mH}from"react/jsx-runtime";function pH({integrations:H,connections:Z,syncConfigs:K}){let{primaryItems:X,comparisonItems:$}=s(H,Z,K);return mH("section",{className:"space-y-4",children:[mH("div",{children:[S("h3",{className:"font-semibold text-lg",children:"Integration Visualizations"}),S("p",{className:"text-muted-foreground text-sm",children:"Contract-backed charts for integration coverage and sync health."})]}),S(CK,{children:X.map((q)=>S(fK,{data:q.data,description:q.description,height:q.height,spec:q.spec,title:q.title},q.key))}),S(kK,{description:"Comparison surface for healthy versus attention-needed syncs.",items:$,title:"Sync-State Comparison"})]})}import{ChatWithSidebar as jK}from"@contractspec/module.ai-chat";import{jsx as uH}from"react/jsx-runtime";var hK=["List my integrations","Show sync status","Add a connection"],xK="You are an Integration Hub assistant. Help users manage integrations, connections, and sync configurations. When asked about integrations, connections, or syncs, provide clear, actionable guidance.";function zH({proxyUrl:H="/api/chat",mcpServers:Z,thinkingLevel:K="thinking",suggestions:X=hK,systemPrompt:$=xK,className:q}){return uH("div",{className:q??"flex h-[500px] flex-col",children:uH(jK,{className:"flex-1",systemPrompt:$,proxyUrl:H,mcpServers:Z,thinkingLevel:K,suggestions:X,showSuggestionsWhenEmpty:!0})})}import{Button as a}from"@contractspec/lib.design-system";import{Badge as lH}from"@contractspec/lib.ui-kit-web/ui/badge";import{HStack as EK}from"@contractspec/lib.ui-kit-web/ui/stack";import{jsx as E,jsxs as bK}from"react/jsx-runtime";var vK={ACTIVE:"default",CONNECTED:"default",SUCCESS:"default",PENDING:"secondary",PAUSED:"secondary",ERROR:"destructive",DISCONNECTED:"outline"};function g(H){return H?H.toLocaleString():"Never"}function RH(H){return H?JSON.stringify(H,null,2):"No configuration"}function n({status:H}){return E(lH,{variant:vK[H]??"outline",children:H})}function e({controller:H,label:Z,toggleColumnId:K,toggleVisibleLabel:X,toggleHiddenLabel:$,pinColumnId:q,pinLabel:G,resizeColumnId:W,resizeLabel:A}){let O=H.rows[0],U=H.columns.find((Q)=>Q.id===K),D=H.columns.find((Q)=>Q.id===q),F=H.columns.find((Q)=>Q.id===W),V=D?.pinState==="left"?!1:"left";return bK(EK,{gap:"sm",className:"flex-wrap",children:[E(lH,{variant:"outline",children:Z}),E(a,{variant:"outline",size:"sm",onPress:()=>O?.toggleExpanded?.(!O?.isExpanded),children:"Expand First Row"}),E(a,{variant:"outline",size:"sm",onPress:()=>U?.toggleVisibility?.(!U?.visible),children:U?.visible?X:$}),E(a,{variant:"outline",size:"sm",onPress:()=>D?.pin?.(V),children:D?.pinState==="left"?`Unpin ${G}`:`Pin ${G}`}),E(a,{variant:"outline",size:"sm",onPress:()=>F?.resizeBy?.(40),children:A})]})}import{DataTable as TK}from"@contractspec/lib.design-system";import{useContractTable as wK}from"@contractspec/lib.presentation-runtime-react";import{VStack as cH}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as y}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as k,jsxs as VH}from"react/jsx-runtime";function MH({connections:H}){let Z=wK({data:H,columns:[{id:"connection",header:"Connection",label:"Connection",accessor:(K)=>K.name,cell:({item:K})=>VH(cH,{gap:"xs",children:[k(y,{className:"font-medium text-sm",children:K.name}),VH(y,{className:"text-muted-foreground text-xs",children:["Created ",K.createdAt.toLocaleDateString()]})]}),size:240,minSize:180,canSort:!0,canPin:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:K})=>k(n,{status:String(K)}),size:150,canSort:!0,canPin:!0,canResize:!0},{id:"lastSyncAt",header:"Last Sync",label:"Last Sync",accessor:(K)=>K.lastSyncAt?.getTime()??0,cell:({item:K})=>g(K.lastSyncAt),size:200,canSort:!0,canHide:!0,canResize:!0},{id:"errorMessage",header:"Errors",label:"Errors",accessor:(K)=>K.errorMessage??"",cell:({value:K})=>String(K||"No errors"),size:240,canHide:!0,canResize:!0}],initialState:{pagination:{pageIndex:0,pageSize:3},columnVisibility:{errorMessage:!1},columnPinning:{left:["connection"],right:[]}},renderExpandedContent:(K)=>VH(cH,{gap:"sm",className:"py-2",children:[k(y,{className:"font-medium text-sm",children:"Credentials"}),k("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:RH(K.credentials)}),k(y,{className:"font-medium text-sm",children:"Config"}),k("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:RH(K.config)}),k(y,{className:"text-muted-foreground text-sm",children:K.errorMessage??"No sync errors recorded."})]}),getCanExpand:()=>!0});return k(TK,{controller:Z,title:"Connections",description:"Client-mode ContractSpec table with visibility, pinning, resizing, and expanded diagnostics.",toolbar:k(e,{controller:Z,label:`${H.length} total connections`,toggleColumnId:"errorMessage",toggleVisibleLabel:"Hide Error Column",toggleHiddenLabel:"Show Error Column",pinColumnId:"status",pinLabel:"Status",resizeColumnId:"connection",resizeLabel:"Widen Connection"}),emptyState:k("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No connections found"})})}import{DataTable as SK}from"@contractspec/lib.design-system";import{useContractTable as gK}from"@contractspec/lib.presentation-runtime-react";import{VStack as rH}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as v}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as d,jsxs as h}from"react/jsx-runtime";function IH({syncConfigs:H}){let Z=gK({data:H,columns:[{id:"sync",header:"Sync Config",label:"Sync Config",accessor:(K)=>K.name,cell:({item:K})=>h(rH,{gap:"xs",children:[d(v,{className:"font-medium text-sm",children:K.name}),h(v,{className:"text-muted-foreground text-xs",children:[K.sourceEntity," \u2192 ",K.targetEntity]})]}),size:260,minSize:200,canSort:!0,canPin:!0,canResize:!0},{id:"frequency",header:"Frequency",label:"Frequency",accessorKey:"frequency",size:160,canSort:!0,canHide:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:K})=>d(n,{status:String(K)}),size:150,canSort:!0,canPin:!0,canResize:!0},{id:"recordsSynced",header:"Records",label:"Records",accessorKey:"recordsSynced",align:"right",size:140,canSort:!0,canResize:!0},{id:"lastRunAt",header:"Last Run",label:"Last Run",accessor:(K)=>K.lastRunAt?.getTime()??0,cell:({item:K})=>g(K.lastRunAt),size:200,canSort:!0,canHide:!0,canResize:!0}],initialState:{pagination:{pageIndex:0,pageSize:3},columnVisibility:{lastRunAt:!1},columnPinning:{left:["sync"],right:[]}},renderExpandedContent:(K)=>h(rH,{gap:"sm",className:"py-2",children:[h(v,{className:"text-muted-foreground text-sm",children:["Connection ",K.connectionId]}),h(v,{className:"text-muted-foreground text-sm",children:["Last run: ",g(K.lastRunAt)]}),h(v,{className:"text-muted-foreground text-sm",children:["Last status: ",K.lastRunStatus??"No runs recorded"]}),h(v,{className:"text-muted-foreground text-sm",children:["Updated ",K.updatedAt.toLocaleString()]})]}),getCanExpand:()=>!0});return d(SK,{controller:Z,title:"Sync Configs",description:"Shared table primitives applied to sync monitoring without changing the surrounding dashboard layout.",toolbar:d(e,{controller:Z,label:`${H.length} syncs`,toggleColumnId:"lastRunAt",toggleVisibleLabel:"Hide Last Run",toggleHiddenLabel:"Show Last Run",pinColumnId:"status",pinLabel:"Status",resizeColumnId:"sync",resizeLabel:"Widen Sync"}),emptyState:d("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No sync configurations found"})})}import{Button as iH,ErrorState as yK,LoaderBlock as dK,StatCard as kH,StatCardGroup as mK}from"@contractspec/lib.design-system";import{useState as pK}from"react";import{jsx as L,jsxs as I}from"react/jsx-runtime";var uK={ACTIVE:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",INACTIVE:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",CONNECTED:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",DISCONNECTED:"bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400",PENDING:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",ERROR:"bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",PAUSED:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400"},lK={CRM:"\uD83D\uDCCA",MARKETING:"\uD83D\uDCE3",PAYMENT:"\uD83D\uDCB3",COMMUNICATION:"\uD83D\uDCAC",DATA:"\uD83D\uDDC4\uFE0F",CUSTOM:"\u2699\uFE0F"};function cK(){let[H,Z]=pK("integrations"),{integrations:K,connections:X,syncConfigs:$,loading:q,error:G,stats:W,refetch:A}=LH(),O=[{id:"integrations",label:"Integrations",icon:"\uD83D\uDD0C"},{id:"connections",label:"Connections",icon:"\uD83D\uDD17"},{id:"syncs",label:"Sync Configs",icon:"\uD83D\uDD04"},{id:"chat",label:"Chat",icon:"\uD83D\uDCAC"}];if(q)return L(dK,{label:"Loading Integrations..."});if(G)return L(yK,{title:"Failed to load Integrations",description:G.message,onRetry:A,retryLabel:"Retry"});return I("div",{className:"space-y-6",children:[I("div",{className:"flex items-center justify-between",children:[L("h2",{className:"font-bold text-2xl",children:"Integration Hub"}),I(iH,{onClick:()=>alert("Add integration modal"),children:[L("span",{className:"mr-2",children:"+"})," Add Integration"]})]}),I(mK,{children:[L(kH,{label:"Integrations",value:W.totalIntegrations,hint:`${W.activeIntegrations} active`}),L(kH,{label:"Connections",value:W.totalConnections,hint:`${W.connectedCount} connected`}),L(kH,{label:"Syncs",value:W.totalSyncs,hint:`${W.activeSyncs} active`})]}),L(pH,{connections:X,integrations:K,syncConfigs:$}),L("nav",{className:"flex gap-1 rounded-lg bg-muted p-1",role:"tablist",children:O.map((U)=>I(iH,{type:"button",role:"tab","aria-selected":H===U.id,onClick:()=>Z(U.id),className:`flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${H===U.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[L("span",{children:U.icon}),U.label]},U.id))}),I("div",{className:"min-h-[400px]",role:"tabpanel",children:[H==="integrations"&&I("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[K.map((U)=>I("div",{className:"cursor-pointer rounded-lg border border-border bg-card p-4 transition-colors hover:bg-muted/50",children:[I("div",{className:"mb-3 flex items-center gap-3",children:[L("span",{className:"text-2xl",children:lK[U.type]??"\u2699\uFE0F"}),I("div",{children:[L("h3",{className:"font-medium",children:U.name}),L("p",{className:"text-muted-foreground text-sm",children:U.type})]})]}),I("div",{className:"flex items-center justify-between",children:[L("span",{className:`inline-flex rounded-full px-2 py-0.5 font-medium text-xs ${uK[U.status]??""}`,children:U.status}),L("span",{className:"text-muted-foreground text-xs",children:U.createdAt.toLocaleDateString()})]})]},U.id)),K.length===0&&L("div",{className:"col-span-full flex h-64 items-center justify-center text-muted-foreground",children:"No integrations configured"})]}),H==="connections"&&L(MH,{connections:X}),H==="chat"&&L(zH,{proxyUrl:"/api/chat",thinkingLevel:"thinking",suggestions:["List my integrations","Show sync status","Add a connection"],className:"min-h-[400px]"}),H==="syncs"&&L(IH,{syncConfigs:$})]})]})}var oH=[{id:"int-1",name:"Salesforce",type:"CRM",status:"ACTIVE",connectionCount:3},{id:"int-2",name:"HubSpot",type:"MARKETING",status:"ACTIVE",connectionCount:2},{id:"int-3",name:"Stripe",type:"PAYMENT",status:"ACTIVE",connectionCount:1},{id:"int-4",name:"Slack",type:"COMMUNICATION",status:"INACTIVE",connectionCount:0},{id:"int-5",name:"Google Sheets",type:"DATA",status:"ACTIVE",connectionCount:5},{id:"int-6",name:"PostHog",type:"ANALYTICS",status:"ACTIVE",connectionCount:1}],fH=[{id:"conn-1",integrationId:"int-1",name:"Production Salesforce",status:"CONNECTED",lastSyncAt:"2024-01-16T10:00:00Z"},{id:"conn-2",integrationId:"int-1",name:"Sandbox Salesforce",status:"CONNECTED",lastSyncAt:"2024-01-15T14:00:00Z"},{id:"conn-3",integrationId:"int-2",name:"Marketing HubSpot",status:"CONNECTED",lastSyncAt:"2024-01-16T08:00:00Z"},{id:"conn-4",integrationId:"int-3",name:"Stripe Live",status:"CONNECTED",lastSyncAt:"2024-01-16T12:00:00Z"},{id:"conn-5",integrationId:"int-5",name:"Analytics Sheet",status:"ERROR",lastSyncAt:"2024-01-14T09:00:00Z",error:"Authentication expired"},{id:"conn-6",integrationId:"int-6",name:"PostHog Workspace",status:"CONNECTED",lastSyncAt:"2024-01-16T11:45:00Z"}],tH=[{id:"sync-1",connectionId:"conn-1",name:"Contacts Sync",frequency:"HOURLY",lastRunAt:"2024-01-16T10:00:00Z",status:"SUCCESS",recordsSynced:1250},{id:"sync-2",connectionId:"conn-1",name:"Opportunities Sync",frequency:"DAILY",lastRunAt:"2024-01-16T00:00:00Z",status:"SUCCESS",recordsSynced:340},{id:"sync-3",connectionId:"conn-3",name:"Orders Sync",frequency:"REALTIME",lastRunAt:"2024-01-16T12:30:00Z",status:"SUCCESS",recordsSynced:89},{id:"sync-4",connectionId:"conn-5",name:"Metrics Export",frequency:"DAILY",lastRunAt:"2024-01-14T09:00:00Z",status:"FAILED",recordsSynced:0}],rK={target:"markdown",render:async(H)=>{if(H.source.type!=="component"||H.source.componentKey!=="IntegrationDashboard")throw Error("integrationDashboardMarkdownRenderer: not IntegrationDashboard");let Z=oH,K=fH,X=tH,$=s(Z,K,X),q=Z.filter((D)=>D.status==="ACTIVE"),G=K.filter((D)=>D.status==="CONNECTED"),W=K.filter((D)=>D.status==="ERROR"),O=X.filter((D)=>D.status==="SUCCESS").reduce((D,F)=>D+F.recordsSynced,0),U=["# Integration Hub","","> Connect and sync data with external services","","## Overview","","| Metric | Value |","|--------|-------|",`| Active Integrations | ${q.length} |`,`| Connected Services | ${G.length} |`,`| Error Connections | ${W.length} |`,`| Sync Configs | ${X.length} |`,`| Records Synced (24h) | ${O.toLocaleString()} |`,""];U.push("## Visualization Overview"),U.push("");for(let D of[...$.primaryItems,...$.comparisonItems])U.push(`- **${D.title}** via \`${D.spec.meta.key}\``);U.push(""),U.push("## Integrations"),U.push(""),U.push("| Name | Type | Connections | Status |"),U.push("|------|------|-------------|--------|");for(let D of Z){let F=D.status==="ACTIVE"?"\uD83D\uDFE2":"\u26AB";U.push(`| ${D.name} | ${D.type} | ${D.connectionCount} | ${F} ${D.status} |`)}U.push(""),U.push("## Recent Sync Activity"),U.push(""),U.push("| Sync | Frequency | Last Run | Records | Status |"),U.push("|------|-----------|----------|---------|--------|");for(let D of X){let F=new Date(D.lastRunAt).toLocaleString(),V=D.status==="SUCCESS"?"\u2705":"\u274C";U.push(`| ${D.name} | ${D.frequency} | ${F} | ${D.recordsSynced} | ${V} ${D.status} |`)}if(W.length>0){U.push(""),U.push("## \u26A0\uFE0F Connections with Errors"),U.push("");for(let D of W){let F=Z.find((V)=>V.id===D.integrationId);U.push(`- **${D.name}** (${F?.name??"Unknown"}): ${D.error??"Unknown error"}`)}}return{mimeType:"text/markdown",body:U.join(`
7
+ `)}}},iK={target:"markdown",render:async(H)=>{if(H.source.type!=="component"||H.source.componentKey!=="ConnectionList")throw Error("connectionListMarkdownRenderer: not ConnectionList");let Z=fH,K=oH,X=["# Connections","","> Manage connections to external services",""];for(let $ of K){let q=Z.filter((G)=>G.integrationId===$.id);if(q.length===0)continue;X.push(`## ${$.name}`),X.push(""),X.push("| Connection | Status | Last Sync |"),X.push("|------------|--------|-----------|");for(let G of q){let W=new Date(G.lastSyncAt).toLocaleString(),A=G.status==="CONNECTED"?"\uD83D\uDFE2":G.status==="ERROR"?"\uD83D\uDD34":"\u26AB";X.push(`| ${G.name} | ${A} ${G.status} | ${W} |`)}X.push("")}return{mimeType:"text/markdown",body:X.join(`
8
+ `)}}},oK={target:"markdown",render:async(H)=>{if(H.source.type!=="component"||H.source.componentKey!=="SyncConfigEditor")throw Error("syncConfigMarkdownRenderer: not SyncConfigEditor");let Z=tH,K=fH,X=["# Sync Configurations","","> Configure automated data synchronization",""];for(let $ of Z){let q=K.find((W)=>W.id===$.connectionId),G=$.status==="SUCCESS"?"\u2705":"\u274C";X.push(`## ${$.name}`),X.push(""),X.push(`**Connection:** ${q?.name??"Unknown"}`),X.push(`**Frequency:** ${$.frequency}`),X.push(`**Status:** ${G} ${$.status}`),X.push(`**Last Run:** ${new Date($.lastRunAt).toLocaleString()}`),X.push(`**Records Synced:** ${$.recordsSynced.toLocaleString()}`),X.push("")}return X.push("## Frequency Options"),X.push(""),X.push("- **REALTIME**: Sync on every change"),X.push("- **HOURLY**: Sync every hour"),X.push("- **DAILY**: Sync once per day"),X.push("- **WEEKLY**: Sync once per week"),X.push("- **MANUAL**: Sync only when triggered"),{mimeType:"text/markdown",body:X.join(`
9
+ `)}}};export{LH as useIntegrationData,oK as syncConfigMarkdownRenderer,MX as runIntegrationHubMcpExampleFromEnv,rK as integrationDashboardMarkdownRenderer,dX as hasChanges,gX as createSyncEngine,s as createIntegrationVisualizationSections,KK as createIntegrationHandlers,iK as connectionListMarkdownRenderer,yX as computeChecksum,PH as TriggerSyncInputModel,NK as TriggerSyncContract,l as SyncStatusEnum,T as SyncRunModel,x as SyncDirectionEnum,r as SyncConfigModel,c as MappingTypeEnum,BH as ListSyncRunsOutputModel,WH as ListSyncRunsInputModel,AK as ListSyncRunsContract,dH as IntegrationVisualizationSpecs,oX as IntegrationVisualizationRegistry,tX as IntegrationVisualizationRefs,NH as IntegrationTypeVisualization,UH as IntegrationStatusEnum,u as IntegrationModel,zH as IntegrationHubChat,cK as IntegrationDashboard,FH as HealthySyncMetricVisualization,b as FieldMappingModel,DH as CreateSyncConfigInputModel,OK as CreateSyncConfigContract,JH as CreateIntegrationInputModel,$K as CreateIntegrationContract,$H as CreateConnectionInputModel,eH as CreateConnectionContract,AH as ConnectionStatusVisualization,KH as ConnectionStatusEnum,m as ConnectionModel,gH as BasicSyncEngine,SH as BasicFieldTransformer,_H as AttentionSyncMetricVisualization,GH as AddFieldMappingInputModel,LK as AddFieldMappingContract};