@qontinui/ui-bridge 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/ai/index.d.mts +893 -0
  2. package/dist/ai/index.d.ts +893 -0
  3. package/dist/ai/index.js +3897 -0
  4. package/dist/ai/index.js.map +1 -0
  5. package/dist/ai/index.mjs +3839 -0
  6. package/dist/ai/index.mjs.map +1 -0
  7. package/dist/babel-plugin/index.js +515 -0
  8. package/dist/babel-plugin/index.js.map +1 -0
  9. package/dist/babel-plugin/index.mjs +499 -0
  10. package/dist/babel-plugin/index.mjs.map +1 -0
  11. package/dist/control/index.d.mts +5 -4
  12. package/dist/control/index.d.ts +5 -4
  13. package/dist/core/index.d.mts +115 -42
  14. package/dist/core/index.d.ts +115 -42
  15. package/dist/core/index.js +0 -983
  16. package/dist/core/index.js.map +1 -1
  17. package/dist/core/index.mjs +1 -972
  18. package/dist/core/index.mjs.map +1 -1
  19. package/dist/debug/index.d.mts +3 -3
  20. package/dist/debug/index.d.ts +3 -3
  21. package/dist/index.d.mts +8 -7
  22. package/dist/index.d.ts +8 -7
  23. package/dist/index.js +8249 -4163
  24. package/dist/index.js.map +1 -1
  25. package/dist/index.mjs +8193 -4152
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/{metrics-QCnK0EFw.d.ts → metrics-BfiT_rhZ.d.ts} +2 -2
  28. package/dist/{metrics-BCG7z7Aq.d.mts → metrics-DTA2bwG7.d.mts} +2 -2
  29. package/dist/native/control/index.js +453 -0
  30. package/dist/native/control/index.js.map +1 -0
  31. package/dist/native/control/index.mjs +450 -0
  32. package/dist/native/control/index.mjs.map +1 -0
  33. package/dist/native/core/index.js +486 -0
  34. package/dist/native/core/index.js.map +1 -0
  35. package/dist/native/core/index.mjs +475 -0
  36. package/dist/native/core/index.mjs.map +1 -0
  37. package/dist/native/debug/index.js +451 -0
  38. package/dist/native/debug/index.js.map +1 -0
  39. package/dist/native/debug/index.mjs +449 -0
  40. package/dist/native/debug/index.mjs.map +1 -0
  41. package/dist/native/index.js +2274 -0
  42. package/dist/native/index.js.map +1 -0
  43. package/dist/native/index.mjs +2246 -0
  44. package/dist/native/index.mjs.map +1 -0
  45. package/dist/native/react/index.js +1401 -0
  46. package/dist/native/react/index.js.map +1 -0
  47. package/dist/native/react/index.mjs +1389 -0
  48. package/dist/native/react/index.mjs.map +1 -0
  49. package/dist/native/server/index.js +415 -0
  50. package/dist/native/server/index.js.map +1 -0
  51. package/dist/native/server/index.mjs +410 -0
  52. package/dist/native/server/index.mjs.map +1 -0
  53. package/dist/react/index.d.mts +20 -6
  54. package/dist/react/index.d.ts +20 -6
  55. package/dist/react/index.js +629 -14
  56. package/dist/react/index.js.map +1 -1
  57. package/dist/react/index.mjs +629 -14
  58. package/dist/react/index.mjs.map +1 -1
  59. package/dist/{registry-CT6BVVKr.d.mts → registry-BKLEm-yk.d.ts} +29 -14
  60. package/dist/{registry-D4mQ01B3.d.ts → registry-BmZgyCz8.d.mts} +29 -14
  61. package/dist/render-log/index.d.mts +1 -1
  62. package/dist/render-log/index.d.ts +1 -1
  63. package/dist/server/express.d.mts +36 -0
  64. package/dist/server/express.d.ts +36 -0
  65. package/dist/server/express.js +196 -0
  66. package/dist/server/express.js.map +1 -0
  67. package/dist/server/express.mjs +192 -0
  68. package/dist/server/express.mjs.map +1 -0
  69. package/dist/server/handlers.d.mts +93 -0
  70. package/dist/server/handlers.d.ts +93 -0
  71. package/dist/server/handlers.js +4278 -0
  72. package/dist/server/handlers.js.map +1 -0
  73. package/dist/server/handlers.mjs +4275 -0
  74. package/dist/server/handlers.mjs.map +1 -0
  75. package/dist/server/index.d.mts +10 -0
  76. package/dist/server/index.d.ts +10 -0
  77. package/dist/server/index.js +5352 -0
  78. package/dist/server/index.js.map +1 -0
  79. package/dist/server/index.mjs +5337 -0
  80. package/dist/server/index.mjs.map +1 -0
  81. package/dist/server/nextjs.d.mts +126 -0
  82. package/dist/server/nextjs.d.ts +126 -0
  83. package/dist/server/nextjs.js +287 -0
  84. package/dist/server/nextjs.js.map +1 -0
  85. package/dist/server/nextjs.mjs +282 -0
  86. package/dist/server/nextjs.mjs.map +1 -0
  87. package/dist/server/standalone.d.mts +6 -0
  88. package/dist/server/standalone.d.ts +6 -0
  89. package/dist/server/standalone.js +719 -0
  90. package/dist/server/standalone.js.map +1 -0
  91. package/dist/server/standalone.mjs +715 -0
  92. package/dist/server/standalone.mjs.map +1 -0
  93. package/dist/standalone-BURj8J3G.d.ts +212 -0
  94. package/dist/standalone-Dwmel29d.d.mts +212 -0
  95. package/dist/swc-plugin/index.d.mts +79 -0
  96. package/dist/swc-plugin/index.d.ts +79 -0
  97. package/dist/swc-plugin/index.js +15 -0
  98. package/dist/swc-plugin/index.js.map +1 -0
  99. package/dist/swc-plugin/index.mjs +9 -0
  100. package/dist/swc-plugin/index.mjs.map +1 -0
  101. package/dist/types-B5Q0GVo0.d.mts +646 -0
  102. package/dist/{types-DdJD9yw5.d.mts → types-B7J7noLK.d.mts} +1 -1
  103. package/dist/{types-BDkXy5si.d.ts → types-BkNRILUa.d.ts} +1 -1
  104. package/dist/types-CEQLnFMv.d.mts +156 -0
  105. package/dist/types-CHnlwiTK.d.ts +156 -0
  106. package/dist/types-DfPqwU-i.d.ts +646 -0
  107. package/dist/{types-BpvpStn3.d.mts → types-jKVgTI6_.d.mts} +364 -160
  108. package/dist/{types-BpvpStn3.d.ts → types-jKVgTI6_.d.ts} +364 -160
  109. package/package.json +111 -3
  110. package/swc-plugin-wasm/ui_bridge_swc_plugin.wasm +0 -0
  111. package/dist/websocket-client-B2LC9CYc.d.mts +0 -124
  112. package/dist/websocket-client-DupH0X7B.d.ts +0 -124
@@ -1,4 +1,5 @@
1
- import { d as BridgeEventListener, e as BridgeEventType, i as ElementType, S as StandardAction, g as CustomAction, l as RegisteredElement, R as RegisteredComponent, a1 as Workflow, o as UIState, p as UIStateGroup, q as UITransition, T as TransitionResult, P as PathResult, N as NavigationResult, m as StateSnapshot, f as BridgeSnapshot } from './types-BpvpStn3.mjs';
1
+ import { j as BridgeEventListener, k as BridgeEventType, r as ElementType, S as StandardAction, o as CustomAction, x as RegisteredElement, y as StateGetter, w as RegisteredComponent, m as ComponentStateResponse, af as Workflow, F as UIState, G as UIStateGroup, H as UITransition, T as TransitionResult, v as PathResult, N as NavigationResult, z as StateSnapshot, l as BridgeSnapshot } from './types-jKVgTI6_.js';
2
+ import { S as SearchCriteria, o as SearchResult } from './types-DfPqwU-i.js';
2
3
 
3
4
  /**
4
5
  * Element and Component Registry
@@ -69,6 +70,26 @@ declare class UIBridgeRegistry {
69
70
  * Find element by DOM element reference
70
71
  */
71
72
  findByDOMElement(element: HTMLElement): RegisteredElement | undefined;
73
+ /**
74
+ * Search for elements using AI search criteria
75
+ */
76
+ searchElements(criteria: SearchCriteria): SearchResult[];
77
+ /**
78
+ * Find element by visible text
79
+ */
80
+ findByText(text: string, fuzzy?: boolean): RegisteredElement | undefined;
81
+ /**
82
+ * Find element by accessible name
83
+ */
84
+ findByAccessibleName(name: string): RegisteredElement | undefined;
85
+ /**
86
+ * Generate aliases for an element
87
+ */
88
+ private generateElementAliases;
89
+ /**
90
+ * Infer ARIA role from element type
91
+ */
92
+ private inferRole;
72
93
  /**
73
94
  * Register a component
74
95
  */
@@ -82,6 +103,8 @@ declare class UIBridgeRegistry {
82
103
  handler: (params?: unknown) => unknown | Promise<unknown>;
83
104
  }>;
84
105
  elementIds?: string[];
106
+ getState?: StateGetter<Record<string, unknown>>;
107
+ getComputed?: () => Record<string, unknown>;
85
108
  }): RegisteredComponent;
86
109
  /**
87
110
  * Unregister a component
@@ -95,6 +118,10 @@ declare class UIBridgeRegistry {
95
118
  * Get all registered components
96
119
  */
97
120
  getAllComponents(): RegisteredComponent[];
121
+ /**
122
+ * Get the current state and computed properties of a component
123
+ */
124
+ getComponentState(id: string): ComponentStateResponse | null;
98
125
  /**
99
126
  * Register a workflow
100
127
  */
@@ -237,17 +264,5 @@ declare class UIBridgeRegistry {
237
264
  activeStateCount: number;
238
265
  };
239
266
  }
240
- /**
241
- * Get or create the global registry
242
- */
243
- declare function getGlobalRegistry(): UIBridgeRegistry;
244
- /**
245
- * Set the global registry
246
- */
247
- declare function setGlobalRegistry(registry: UIBridgeRegistry): void;
248
- /**
249
- * Reset the global registry
250
- */
251
- declare function resetGlobalRegistry(): void;
252
267
 
253
- export { type RegistryOptions as R, UIBridgeRegistry as U, getGlobalRegistry as g, resetGlobalRegistry as r, setGlobalRegistry as s };
268
+ export { UIBridgeRegistry as U };
@@ -1,4 +1,5 @@
1
- import { d as BridgeEventListener, e as BridgeEventType, i as ElementType, S as StandardAction, g as CustomAction, l as RegisteredElement, R as RegisteredComponent, a1 as Workflow, o as UIState, p as UIStateGroup, q as UITransition, T as TransitionResult, P as PathResult, N as NavigationResult, m as StateSnapshot, f as BridgeSnapshot } from './types-BpvpStn3.js';
1
+ import { j as BridgeEventListener, k as BridgeEventType, r as ElementType, S as StandardAction, o as CustomAction, x as RegisteredElement, y as StateGetter, w as RegisteredComponent, m as ComponentStateResponse, af as Workflow, F as UIState, G as UIStateGroup, H as UITransition, T as TransitionResult, v as PathResult, N as NavigationResult, z as StateSnapshot, l as BridgeSnapshot } from './types-jKVgTI6_.mjs';
2
+ import { S as SearchCriteria, o as SearchResult } from './types-B5Q0GVo0.mjs';
2
3
 
3
4
  /**
4
5
  * Element and Component Registry
@@ -69,6 +70,26 @@ declare class UIBridgeRegistry {
69
70
  * Find element by DOM element reference
70
71
  */
71
72
  findByDOMElement(element: HTMLElement): RegisteredElement | undefined;
73
+ /**
74
+ * Search for elements using AI search criteria
75
+ */
76
+ searchElements(criteria: SearchCriteria): SearchResult[];
77
+ /**
78
+ * Find element by visible text
79
+ */
80
+ findByText(text: string, fuzzy?: boolean): RegisteredElement | undefined;
81
+ /**
82
+ * Find element by accessible name
83
+ */
84
+ findByAccessibleName(name: string): RegisteredElement | undefined;
85
+ /**
86
+ * Generate aliases for an element
87
+ */
88
+ private generateElementAliases;
89
+ /**
90
+ * Infer ARIA role from element type
91
+ */
92
+ private inferRole;
72
93
  /**
73
94
  * Register a component
74
95
  */
@@ -82,6 +103,8 @@ declare class UIBridgeRegistry {
82
103
  handler: (params?: unknown) => unknown | Promise<unknown>;
83
104
  }>;
84
105
  elementIds?: string[];
106
+ getState?: StateGetter<Record<string, unknown>>;
107
+ getComputed?: () => Record<string, unknown>;
85
108
  }): RegisteredComponent;
86
109
  /**
87
110
  * Unregister a component
@@ -95,6 +118,10 @@ declare class UIBridgeRegistry {
95
118
  * Get all registered components
96
119
  */
97
120
  getAllComponents(): RegisteredComponent[];
121
+ /**
122
+ * Get the current state and computed properties of a component
123
+ */
124
+ getComponentState(id: string): ComponentStateResponse | null;
98
125
  /**
99
126
  * Register a workflow
100
127
  */
@@ -237,17 +264,5 @@ declare class UIBridgeRegistry {
237
264
  activeStateCount: number;
238
265
  };
239
266
  }
240
- /**
241
- * Get or create the global registry
242
- */
243
- declare function getGlobalRegistry(): UIBridgeRegistry;
244
- /**
245
- * Set the global registry
246
- */
247
- declare function setGlobalRegistry(registry: UIBridgeRegistry): void;
248
- /**
249
- * Reset the global registry
250
- */
251
- declare function resetGlobalRegistry(): void;
252
267
 
253
- export { type RegistryOptions as R, UIBridgeRegistry as U, getGlobalRegistry as g, resetGlobalRegistry as r, setGlobalRegistry as s };
268
+ export { UIBridgeRegistry as U };
@@ -1,4 +1,4 @@
1
- import { E as ElementIdentifier, h as ElementState } from '../types-BpvpStn3.mjs';
1
+ import { p as ElementIdentifier, q as ElementState } from '../types-jKVgTI6_.mjs';
2
2
 
3
3
  /**
4
4
  * DOM Capture Module
@@ -1,4 +1,4 @@
1
- import { E as ElementIdentifier, h as ElementState } from '../types-BpvpStn3.js';
1
+ import { p as ElementIdentifier, q as ElementState } from '../types-jKVgTI6_.js';
2
2
 
3
3
  /**
4
4
  * DOM Capture Module
@@ -0,0 +1,36 @@
1
+ import { Router } from 'express';
2
+ import { U as UIBridgeServerConfig, c as UIBridgeServerHandlers } from '../types-CEQLnFMv.mjs';
3
+ import '../types-jKVgTI6_.mjs';
4
+ import '../types-B7J7noLK.mjs';
5
+ import '../types-B5Q0GVo0.mjs';
6
+ import '../render-log/index.mjs';
7
+
8
+ /**
9
+ * Express Adapter
10
+ *
11
+ * Express.js middleware for UI Bridge server.
12
+ */
13
+
14
+ /**
15
+ * Express-specific configuration
16
+ */
17
+ interface ExpressAdapterConfig extends UIBridgeServerConfig {
18
+ /** Use JSON body parser (if not already configured) */
19
+ useBodyParser?: boolean;
20
+ }
21
+ /**
22
+ * Create Express router with UI Bridge routes
23
+ */
24
+ declare function createExpressRouter(handlers: UIBridgeServerHandlers, config?: ExpressAdapterConfig): Router;
25
+ /**
26
+ * Create Express app with UI Bridge routes
27
+ *
28
+ * Convenience function that creates a complete Express app with UI Bridge.
29
+ */
30
+ declare function createExpressApp(handlers: UIBridgeServerHandlers, config?: ExpressAdapterConfig): unknown;
31
+ /**
32
+ * Express middleware that adds UI Bridge to an existing app
33
+ */
34
+ declare function uiBridgeMiddleware(handlers: UIBridgeServerHandlers, config?: ExpressAdapterConfig): Router;
35
+
36
+ export { type ExpressAdapterConfig, createExpressApp, createExpressRouter, uiBridgeMiddleware };
@@ -0,0 +1,36 @@
1
+ import { Router } from 'express';
2
+ import { U as UIBridgeServerConfig, c as UIBridgeServerHandlers } from '../types-CHnlwiTK.js';
3
+ import '../types-jKVgTI6_.js';
4
+ import '../types-BkNRILUa.js';
5
+ import '../types-DfPqwU-i.js';
6
+ import '../render-log/index.js';
7
+
8
+ /**
9
+ * Express Adapter
10
+ *
11
+ * Express.js middleware for UI Bridge server.
12
+ */
13
+
14
+ /**
15
+ * Express-specific configuration
16
+ */
17
+ interface ExpressAdapterConfig extends UIBridgeServerConfig {
18
+ /** Use JSON body parser (if not already configured) */
19
+ useBodyParser?: boolean;
20
+ }
21
+ /**
22
+ * Create Express router with UI Bridge routes
23
+ */
24
+ declare function createExpressRouter(handlers: UIBridgeServerHandlers, config?: ExpressAdapterConfig): Router;
25
+ /**
26
+ * Create Express app with UI Bridge routes
27
+ *
28
+ * Convenience function that creates a complete Express app with UI Bridge.
29
+ */
30
+ declare function createExpressApp(handlers: UIBridgeServerHandlers, config?: ExpressAdapterConfig): unknown;
31
+ /**
32
+ * Express middleware that adds UI Bridge to an existing app
33
+ */
34
+ declare function uiBridgeMiddleware(handlers: UIBridgeServerHandlers, config?: ExpressAdapterConfig): Router;
35
+
36
+ export { type ExpressAdapterConfig, createExpressApp, createExpressRouter, uiBridgeMiddleware };
@@ -0,0 +1,196 @@
1
+ 'use strict';
2
+
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
9
+
10
+ // src/server/types.ts
11
+ var UI_BRIDGE_ROUTES = [
12
+ // Render log
13
+ { method: "GET", path: "/render-log", handler: "getRenderLog" },
14
+ { method: "DELETE", path: "/render-log", handler: "clearRenderLog" },
15
+ { method: "POST", path: "/render-log/snapshot", handler: "captureSnapshot" },
16
+ { method: "GET", path: "/render-log/path", handler: "getRenderLogPath" },
17
+ // Control - Elements
18
+ { method: "GET", path: "/control/elements", handler: "getElements" },
19
+ { method: "GET", path: "/control/element/:id", handler: "getElement", params: ["id"] },
20
+ { method: "GET", path: "/control/element/:id/state", handler: "getElementState", params: ["id"] },
21
+ {
22
+ method: "POST",
23
+ path: "/control/element/:id/action",
24
+ handler: "executeElementAction",
25
+ params: ["id"],
26
+ bodyRequired: true
27
+ },
28
+ // Control - Components
29
+ { method: "GET", path: "/control/components", handler: "getComponents" },
30
+ { method: "GET", path: "/control/component/:id", handler: "getComponent", params: ["id"] },
31
+ { method: "GET", path: "/control/component/:id/state", handler: "getComponentState", params: ["id"] },
32
+ {
33
+ method: "POST",
34
+ path: "/control/component/:id/action/:actionId",
35
+ handler: "executeComponentAction",
36
+ params: ["id", "actionId"],
37
+ bodyRequired: true
38
+ },
39
+ // Find (formerly Discovery)
40
+ { method: "POST", path: "/control/find", handler: "find" },
41
+ { method: "POST", path: "/control/discover", handler: "discover" },
42
+ // @deprecated Use /control/find
43
+ { method: "GET", path: "/control/snapshot", handler: "getControlSnapshot" },
44
+ // Workflows
45
+ { method: "GET", path: "/control/workflows", handler: "getWorkflows" },
46
+ { method: "POST", path: "/control/workflow/:id/run", handler: "runWorkflow", params: ["id"] },
47
+ {
48
+ method: "GET",
49
+ path: "/control/workflow/:runId/status",
50
+ handler: "getWorkflowStatus",
51
+ params: ["runId"]
52
+ },
53
+ // Debug
54
+ { method: "GET", path: "/debug/action-history", handler: "getActionHistory" },
55
+ { method: "GET", path: "/debug/metrics", handler: "getMetrics" },
56
+ { method: "POST", path: "/debug/highlight/:id", handler: "highlightElement", params: ["id"] },
57
+ { method: "GET", path: "/debug/element-tree", handler: "getElementTree" },
58
+ // AI-native endpoints
59
+ { method: "POST", path: "/ai/search", handler: "aiSearch", bodyRequired: true },
60
+ { method: "POST", path: "/ai/execute", handler: "aiExecute", bodyRequired: true },
61
+ { method: "POST", path: "/ai/assert", handler: "aiAssert", bodyRequired: true },
62
+ { method: "POST", path: "/ai/assert/batch", handler: "aiAssertBatch", bodyRequired: true },
63
+ { method: "GET", path: "/ai/snapshot", handler: "getSemanticSnapshot" },
64
+ { method: "GET", path: "/ai/diff", handler: "getSemanticDiff" },
65
+ { method: "GET", path: "/ai/summary", handler: "getPageSummary" },
66
+ { method: "POST", path: "/ai/semantic-search", handler: "aiSemanticSearch", bodyRequired: true }
67
+ ];
68
+
69
+ // src/server/express.ts
70
+ function createCORSMiddleware(options) {
71
+ const corsOptions = typeof options === "boolean" ? { origin: options, methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"] } : options;
72
+ return (req, res, next) => {
73
+ if (corsOptions.origin === true) {
74
+ res.setHeader("Access-Control-Allow-Origin", "*");
75
+ } else if (typeof corsOptions.origin === "string") {
76
+ res.setHeader("Access-Control-Allow-Origin", corsOptions.origin);
77
+ } else if (Array.isArray(corsOptions.origin)) {
78
+ const origin = req.headers.origin;
79
+ if (origin && corsOptions.origin.includes(origin)) {
80
+ res.setHeader("Access-Control-Allow-Origin", origin);
81
+ }
82
+ }
83
+ if (corsOptions.methods) {
84
+ res.setHeader("Access-Control-Allow-Methods", corsOptions.methods.join(", "));
85
+ }
86
+ if (corsOptions.headers) {
87
+ res.setHeader("Access-Control-Allow-Headers", corsOptions.headers.join(", "));
88
+ } else {
89
+ res.setHeader(
90
+ "Access-Control-Allow-Headers",
91
+ "Content-Type, Authorization, X-Requested-With"
92
+ );
93
+ }
94
+ if (corsOptions.credentials) {
95
+ res.setHeader("Access-Control-Allow-Credentials", "true");
96
+ }
97
+ if (corsOptions.maxAge) {
98
+ res.setHeader("Access-Control-Max-Age", String(corsOptions.maxAge));
99
+ }
100
+ if (req.method === "OPTIONS") {
101
+ res.status(204).end();
102
+ return;
103
+ }
104
+ next();
105
+ };
106
+ }
107
+ function wrapError(error, code) {
108
+ return {
109
+ success: false,
110
+ error: typeof error === "string" ? error : error.message,
111
+ code,
112
+ timestamp: Date.now()
113
+ };
114
+ }
115
+ function createExpressRouter(handlers, config = {}) {
116
+ const express = __require("express");
117
+ const router = express.Router();
118
+ if (config.cors) {
119
+ router.use(createCORSMiddleware(config.cors));
120
+ }
121
+ if (config.useBodyParser) {
122
+ router.use(express.json());
123
+ }
124
+ if (config.authenticate) {
125
+ router.use(async (req, res, next) => {
126
+ try {
127
+ const authenticated = await config.authenticate(req);
128
+ if (!authenticated) {
129
+ res.status(401).json(wrapError("Unauthorized", "UNAUTHORIZED"));
130
+ return;
131
+ }
132
+ next();
133
+ } catch (error) {
134
+ res.status(500).json(wrapError(error, "AUTH_ERROR"));
135
+ }
136
+ });
137
+ }
138
+ for (const route of UI_BRIDGE_ROUTES) {
139
+ const method = route.method.toLowerCase();
140
+ const path = route.path;
141
+ const handlerName = route.handler;
142
+ const handler = handlers[handlerName];
143
+ if (!handler) {
144
+ console.warn(`Handler not found for route: ${route.method} ${route.path}`);
145
+ continue;
146
+ }
147
+ router[method](
148
+ path,
149
+ createRouteHandler(route, handler)
150
+ );
151
+ }
152
+ return router;
153
+ }
154
+ function createRouteHandler(route, handler) {
155
+ return async (req, res) => {
156
+ try {
157
+ const args = [];
158
+ if (route.params) {
159
+ for (const param of route.params) {
160
+ args.push(req.params[param]);
161
+ }
162
+ }
163
+ if (route.bodyRequired || route.method === "POST") {
164
+ args.push(req.body);
165
+ }
166
+ if (route.method === "GET" && Object.keys(req.query).length > 0) {
167
+ args.push(req.query);
168
+ }
169
+ const result = await handler(...args);
170
+ res.json(result);
171
+ } catch (error) {
172
+ res.status(500).json(wrapError(error, "INTERNAL_ERROR"));
173
+ }
174
+ };
175
+ }
176
+ function createExpressApp(handlers, config = {}) {
177
+ const express = __require("express");
178
+ const app = express();
179
+ app.use(express.json());
180
+ const basePath = config.basePath || "/ui-bridge";
181
+ const router = createExpressRouter(handlers, { ...config, useBodyParser: false });
182
+ app.use(basePath, router);
183
+ app.get("/health", (_req, res) => {
184
+ res.json({ status: "ok", timestamp: Date.now() });
185
+ });
186
+ return app;
187
+ }
188
+ function uiBridgeMiddleware(handlers, config = {}) {
189
+ return createExpressRouter(handlers, config);
190
+ }
191
+
192
+ exports.createExpressApp = createExpressApp;
193
+ exports.createExpressRouter = createExpressRouter;
194
+ exports.uiBridgeMiddleware = uiBridgeMiddleware;
195
+ //# sourceMappingURL=express.js.map
196
+ //# sourceMappingURL=express.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/server/types.ts","../../src/server/express.ts"],"names":[],"mappings":";;;;;;;;;;AA2LO,IAAM,gBAAA,GAAsC;AAAA;AAAA,EAEjD,EAAE,MAAA,EAAQ,KAAA,EAAO,IAAA,EAAM,aAAA,EAAe,SAAS,cAAA,EA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AAA;AAAA,IACjB,SAAS,KAAA,EAAO;AACd,MAAA,GAAA,CAAI,OAAO,GAAG,CAAA,CAAE,KAAK,SAAA,CAAU,KAAA,EAAgB,gBAAgB,CAAC,CAAA;AAAA,IAClE;AAAA,EACF,CAAA;AACF;AAOO,SAAS,gBAAA,CACd,QAAA,EACA,MAAA,GAA+B,EAAC,EACvB;AAET,EAAA,MAAM,OAAA,GAAU,UAAQ,SAAS,CAAA;AACjC,EAAA,MAAM,MAAM,OAAA,EAAQ;AAEpB,EAAA,GAAA,CAAI,GAAA,CAAI,OAAA,CAAQ,IAAA,EAAM,CAAA;AAEtB,EAAA,MAAM,QAAA,GAAW,OAAO,QAAA,IAAY,YAAA;AACpC,EAAA,MAAM,MAAA,GAAS,oBAAoB,QAAA,EAAU,EAAE,GAAG,MAAA,EAAQ,aAAA,EAAe,OAAO,CAAA;AAEhF,EAAA,GAAA,CAAI,GAAA,CAAI,UAAU,MAAM,CAAA;AAGxB,EAAA,GAAA,CAAI,GAAA,CAAI,SAAA,EAAW,CAAC,IAAA,EAAe,GAAA,KAAkB;AACnD,IAAA,GAAA,CAAI,IAAA,CAAK,EAAE,MAAA,EAAQ,IAAA,EAAM,WAAW,IAAA,CAAK,GAAA,IAAO,CAAA;AAAA,EAClD,CAAC,CAAA;AAED,EAAA,OAAO,GAAA;AACT;AAKO,SAAS,kBAAA,CACd,QAAA,EACA,MAAA,GAA+B,EAAC,EACxB;AACR,EAAA,OAAO,mBAAA,CAAoB,UAAU,MAAM,CAAA;AAC7C","file":"express.js","sourcesContent":["/**\n * UI Bridge Server Types\n *\n * Shared types for server adapters.\n */\n\nimport type { UIBridgeConfig } from '../core';\nimport type {\n ControlActionRequest,\n ControlActionResponse,\n ComponentActionRequest,\n ComponentActionResponse,\n FindRequest,\n FindResponse,\n ControlSnapshot,\n WorkflowRunRequest,\n WorkflowRunResponse,\n} from '../control';\nimport type { RenderLogEntry, RenderLogEntryType } from '../render-log';\nimport type {\n SearchCriteria,\n SearchResponse,\n NLActionRequest,\n NLActionResponse,\n AssertionRequest,\n AssertionResult,\n BatchAssertionRequest,\n BatchAssertionResult,\n SemanticSnapshot,\n SemanticDiff,\n SemanticSearchCriteria,\n SemanticSearchResponse,\n} from '../ai';\n\n/**\n * Server configuration\n */\nexport interface UIBridgeServerConfig extends UIBridgeConfig {\n /** Base path for API routes */\n basePath?: string;\n /** Enable CORS */\n cors?: boolean | CORSOptions;\n /** Authentication middleware */\n authenticate?: (req: unknown) => boolean | Promise<boolean>;\n /** Rate limiting */\n rateLimit?: RateLimitOptions;\n}\n\n/**\n * CORS options\n */\nexport interface CORSOptions {\n /** Allowed origins */\n origin?: string | string[] | boolean;\n /** Allowed methods */\n methods?: string[];\n /** Allowed headers */\n headers?: string[];\n /** Expose headers */\n exposeHeaders?: string[];\n /** Allow credentials */\n credentials?: boolean;\n /** Max age for preflight cache */\n maxAge?: number;\n}\n\n/**\n * Rate limit options\n */\nexport interface RateLimitOptions {\n /** Time window in milliseconds */\n windowMs?: number;\n /** Max requests per window */\n max?: number;\n /** Message when rate limited */\n message?: string;\n}\n\n/**\n * API response wrapper\n */\nexport interface APIResponse<T = unknown> {\n /** Whether the request succeeded */\n success: boolean;\n /** Response data */\n data?: T;\n /** Error message if failed */\n error?: string;\n /** Error code */\n code?: string;\n /** Request timestamp */\n timestamp: number;\n}\n\n/**\n * Render log query parameters\n */\nexport interface RenderLogQuery {\n /** Filter by entry type */\n type?: RenderLogEntryType;\n /** Filter entries since timestamp */\n since?: number;\n /** Filter entries until timestamp */\n until?: number;\n /** Limit number of results */\n limit?: number;\n}\n\n/**\n * Server handler interface\n *\n * Implementations provide these handlers for different frameworks.\n */\nexport interface UIBridgeServerHandlers {\n // Render log endpoints\n getRenderLog: (query?: RenderLogQuery) => Promise<APIResponse<RenderLogEntry[]>>;\n clearRenderLog: () => Promise<APIResponse<void>>;\n captureSnapshot: () => Promise<APIResponse<unknown>>;\n getRenderLogPath: () => Promise<APIResponse<{ path: string }>>;\n\n // Control endpoints\n getElements: () => Promise<APIResponse<ControlSnapshot['elements']>>;\n getElement: (id: string) => Promise<APIResponse<ControlSnapshot['elements'][0]>>;\n getElementState: (id: string) => Promise<APIResponse<unknown>>;\n executeElementAction: (\n id: string,\n request: ControlActionRequest\n ) => Promise<APIResponse<ControlActionResponse>>;\n\n // Component endpoints\n getComponents: () => Promise<APIResponse<ControlSnapshot['components']>>;\n getComponent: (id: string) => Promise<APIResponse<ControlSnapshot['components'][0]>>;\n getComponentState: (id: string) => Promise<APIResponse<{ state: Record<string, unknown>; computed: Record<string, unknown>; timestamp: number }>>;\n executeComponentAction: (\n id: string,\n request: ComponentActionRequest\n ) => Promise<APIResponse<ComponentActionResponse>>;\n\n // Find endpoints\n find: (request?: FindRequest) => Promise<APIResponse<FindResponse>>;\n /**\n * @deprecated Use find() instead\n */\n discover: (request?: FindRequest) => Promise<APIResponse<FindResponse>>;\n getControlSnapshot: () => Promise<APIResponse<ControlSnapshot>>;\n\n // Workflow endpoints\n getWorkflows: () => Promise<APIResponse<ControlSnapshot['workflows']>>;\n runWorkflow: (\n id: string,\n request?: WorkflowRunRequest\n ) => Promise<APIResponse<WorkflowRunResponse>>;\n getWorkflowStatus: (runId: string) => Promise<APIResponse<WorkflowRunResponse>>;\n\n // Debug endpoints\n getActionHistory: (limit?: number) => Promise<APIResponse<unknown[]>>;\n getMetrics: () => Promise<APIResponse<unknown>>;\n highlightElement: (id: string) => Promise<APIResponse<void>>;\n getElementTree: () => Promise<APIResponse<unknown>>;\n\n // AI-native endpoints\n aiSearch: (criteria: SearchCriteria) => Promise<APIResponse<SearchResponse>>;\n aiExecute: (request: NLActionRequest) => Promise<APIResponse<NLActionResponse>>;\n aiAssert: (request: AssertionRequest) => Promise<APIResponse<AssertionResult>>;\n aiAssertBatch: (request: BatchAssertionRequest) => Promise<APIResponse<BatchAssertionResult>>;\n getSemanticSnapshot: () => Promise<APIResponse<SemanticSnapshot>>;\n getSemanticDiff: (since?: number) => Promise<APIResponse<SemanticDiff | null>>;\n getPageSummary: () => Promise<APIResponse<string>>;\n\n // Semantic search (embedding-based)\n aiSemanticSearch: (criteria: SemanticSearchCriteria) => Promise<APIResponse<SemanticSearchResponse>>;\n}\n\n/**\n * Route definition\n */\nexport interface RouteDefinition {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';\n path: string;\n handler: string; // Key in UIBridgeServerHandlers\n params?: string[]; // URL params to extract\n bodyRequired?: boolean;\n}\n\n/**\n * All UI Bridge routes\n */\nexport const UI_BRIDGE_ROUTES: RouteDefinition[] = [\n // Render log\n { method: 'GET', path: '/render-log', handler: 'getRenderLog' },\n { method: 'DELETE', path: '/render-log', handler: 'clearRenderLog' },\n { method: 'POST', path: '/render-log/snapshot', handler: 'captureSnapshot' },\n { method: 'GET', path: '/render-log/path', handler: 'getRenderLogPath' },\n\n // Control - Elements\n { method: 'GET', path: '/control/elements', handler: 'getElements' },\n { method: 'GET', path: '/control/element/:id', handler: 'getElement', params: ['id'] },\n { method: 'GET', path: '/control/element/:id/state', handler: 'getElementState', params: ['id'] },\n {\n method: 'POST',\n path: '/control/element/:id/action',\n handler: 'executeElementAction',\n params: ['id'],\n bodyRequired: true,\n },\n\n // Control - Components\n { method: 'GET', path: '/control/components', handler: 'getComponents' },\n { method: 'GET', path: '/control/component/:id', handler: 'getComponent', params: ['id'] },\n { method: 'GET', path: '/control/component/:id/state', handler: 'getComponentState', params: ['id'] },\n {\n method: 'POST',\n path: '/control/component/:id/action/:actionId',\n handler: 'executeComponentAction',\n params: ['id', 'actionId'],\n bodyRequired: true,\n },\n\n // Find (formerly Discovery)\n { method: 'POST', path: '/control/find', handler: 'find' },\n { method: 'POST', path: '/control/discover', handler: 'discover' }, // @deprecated Use /control/find\n { method: 'GET', path: '/control/snapshot', handler: 'getControlSnapshot' },\n\n // Workflows\n { method: 'GET', path: '/control/workflows', handler: 'getWorkflows' },\n { method: 'POST', path: '/control/workflow/:id/run', handler: 'runWorkflow', params: ['id'] },\n {\n method: 'GET',\n path: '/control/workflow/:runId/status',\n handler: 'getWorkflowStatus',\n params: ['runId'],\n },\n\n // Debug\n { method: 'GET', path: '/debug/action-history', handler: 'getActionHistory' },\n { method: 'GET', path: '/debug/metrics', handler: 'getMetrics' },\n { method: 'POST', path: '/debug/highlight/:id', handler: 'highlightElement', params: ['id'] },\n { method: 'GET', path: '/debug/element-tree', handler: 'getElementTree' },\n\n // AI-native endpoints\n { method: 'POST', path: '/ai/search', handler: 'aiSearch', bodyRequired: true },\n { method: 'POST', path: '/ai/execute', handler: 'aiExecute', bodyRequired: true },\n { method: 'POST', path: '/ai/assert', handler: 'aiAssert', bodyRequired: true },\n { method: 'POST', path: '/ai/assert/batch', handler: 'aiAssertBatch', bodyRequired: true },\n { method: 'GET', path: '/ai/snapshot', handler: 'getSemanticSnapshot' },\n { method: 'GET', path: '/ai/diff', handler: 'getSemanticDiff' },\n { method: 'GET', path: '/ai/summary', handler: 'getPageSummary' },\n { method: 'POST', path: '/ai/semantic-search', handler: 'aiSemanticSearch', bodyRequired: true },\n];\n\n/**\n * WebSocket message types\n */\nexport type WebSocketMessageType =\n | 'subscribe'\n | 'unsubscribe'\n | 'event'\n | 'snapshot'\n | 'action'\n | 'error';\n\n/**\n * WebSocket message\n */\nexport interface WebSocketMessage<T = unknown> {\n type: WebSocketMessageType;\n channel?: string;\n data?: T;\n error?: string;\n timestamp: number;\n}\n","/**\n * Express Adapter\n *\n * Express.js middleware for UI Bridge server.\n */\n\nimport type { Router, Request, Response, NextFunction } from 'express';\nimport type {\n UIBridgeServerConfig,\n UIBridgeServerHandlers,\n APIResponse,\n RouteDefinition,\n CORSOptions,\n} from './types';\nimport { UI_BRIDGE_ROUTES } from './types';\n\n/**\n * Express-specific configuration\n */\nexport interface ExpressAdapterConfig extends UIBridgeServerConfig {\n /** Use JSON body parser (if not already configured) */\n useBodyParser?: boolean;\n}\n\n/**\n * Create CORS middleware\n */\nfunction createCORSMiddleware(options: CORSOptions | boolean) {\n const corsOptions: CORSOptions =\n typeof options === 'boolean'\n ? { origin: options, methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'] }\n : options;\n\n return (req: Request, res: Response, next: NextFunction) => {\n // Origin\n if (corsOptions.origin === true) {\n res.setHeader('Access-Control-Allow-Origin', '*');\n } else if (typeof corsOptions.origin === 'string') {\n res.setHeader('Access-Control-Allow-Origin', corsOptions.origin);\n } else if (Array.isArray(corsOptions.origin)) {\n const origin = req.headers.origin;\n if (origin && corsOptions.origin.includes(origin)) {\n res.setHeader('Access-Control-Allow-Origin', origin);\n }\n }\n\n // Methods\n if (corsOptions.methods) {\n res.setHeader('Access-Control-Allow-Methods', corsOptions.methods.join(', '));\n }\n\n // Headers\n if (corsOptions.headers) {\n res.setHeader('Access-Control-Allow-Headers', corsOptions.headers.join(', '));\n } else {\n res.setHeader(\n 'Access-Control-Allow-Headers',\n 'Content-Type, Authorization, X-Requested-With'\n );\n }\n\n // Credentials\n if (corsOptions.credentials) {\n res.setHeader('Access-Control-Allow-Credentials', 'true');\n }\n\n // Max age\n if (corsOptions.maxAge) {\n res.setHeader('Access-Control-Max-Age', String(corsOptions.maxAge));\n }\n\n // Handle preflight\n if (req.method === 'OPTIONS') {\n res.status(204).end();\n return;\n }\n\n next();\n };\n}\n\n/**\n * Wrap error in API format\n */\nfunction wrapError(error: Error | string, code?: string): APIResponse<never> {\n return {\n success: false,\n error: typeof error === 'string' ? error : error.message,\n code,\n timestamp: Date.now(),\n };\n}\n\n/**\n * Create Express router with UI Bridge routes\n */\nexport function createExpressRouter(\n handlers: UIBridgeServerHandlers,\n config: ExpressAdapterConfig = {}\n): Router {\n // Dynamic import to avoid bundling Express if not used\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const express = require('express');\n const router: Router = express.Router();\n\n // Add CORS middleware if configured\n if (config.cors) {\n router.use(createCORSMiddleware(config.cors));\n }\n\n // Add body parser if requested\n if (config.useBodyParser) {\n router.use(express.json());\n }\n\n // Add authentication middleware if configured\n if (config.authenticate) {\n router.use(async (req: Request, res: Response, next: NextFunction) => {\n try {\n const authenticated = await config.authenticate!(req);\n if (!authenticated) {\n res.status(401).json(wrapError('Unauthorized', 'UNAUTHORIZED'));\n return;\n }\n next();\n } catch (error) {\n res.status(500).json(wrapError(error as Error, 'AUTH_ERROR'));\n }\n });\n }\n\n // Register routes\n for (const route of UI_BRIDGE_ROUTES) {\n const method = route.method.toLowerCase() as 'get' | 'post' | 'put' | 'delete' | 'patch';\n const path = route.path;\n const handlerName = route.handler as keyof UIBridgeServerHandlers;\n const handler = handlers[handlerName];\n\n if (!handler) {\n console.warn(`Handler not found for route: ${route.method} ${route.path}`);\n continue;\n }\n\n router[method](\n path,\n createRouteHandler(route, handler as (...args: unknown[]) => Promise<APIResponse<unknown>>)\n );\n }\n\n return router;\n}\n\n/**\n * Create a route handler from a route definition\n */\nfunction createRouteHandler(\n route: RouteDefinition,\n handler: (...args: unknown[]) => Promise<APIResponse<unknown>>\n) {\n return async (req: Request, res: Response) => {\n try {\n // Extract params\n const args: unknown[] = [];\n\n if (route.params) {\n for (const param of route.params) {\n args.push(req.params[param]);\n }\n }\n\n // Add body if required\n if (route.bodyRequired || route.method === 'POST') {\n args.push(req.body);\n }\n\n // Add query params for GET requests\n if (route.method === 'GET' && Object.keys(req.query).length > 0) {\n args.push(req.query);\n }\n\n const result = await handler(...args);\n res.json(result);\n } catch (error) {\n res.status(500).json(wrapError(error as Error, 'INTERNAL_ERROR'));\n }\n };\n}\n\n/**\n * Create Express app with UI Bridge routes\n *\n * Convenience function that creates a complete Express app with UI Bridge.\n */\nexport function createExpressApp(\n handlers: UIBridgeServerHandlers,\n config: ExpressAdapterConfig = {}\n): unknown {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const express = require('express');\n const app = express();\n\n app.use(express.json());\n\n const basePath = config.basePath || '/ui-bridge';\n const router = createExpressRouter(handlers, { ...config, useBodyParser: false });\n\n app.use(basePath, router);\n\n // Health check\n app.get('/health', (_req: Request, res: Response) => {\n res.json({ status: 'ok', timestamp: Date.now() });\n });\n\n return app;\n}\n\n/**\n * Express middleware that adds UI Bridge to an existing app\n */\nexport function uiBridgeMiddleware(\n handlers: UIBridgeServerHandlers,\n config: ExpressAdapterConfig = {}\n): Router {\n return createExpressRouter(handlers, config);\n}\n"]}