@fractal-solutions/qflow 1.0.51 → 1.0.53

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.
@@ -1,12 +1,17 @@
1
1
  export class HttpServerNode extends AsyncNode {
2
+ constructor();
2
3
  server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> | null;
3
- flowToTrigger: AsyncFlow | null;
4
+ findMatchingRoute(routes: any, method: any, path: any): {
5
+ flow: any;
6
+ params: {};
7
+ } | null;
8
+ handleStatic(staticDir: any, reqPath: any, res: any): Promise<boolean>;
9
+ applyCorsHeaders(res: any, corsConfig: any): void;
4
10
  execAsync(): Promise<{
5
11
  status: string;
6
12
  port: any;
7
13
  }>;
8
- postAsync(shared: any, prepRes: any, execRes: any): Promise<any>;
14
+ postAsync(shared: any, prepRes: any, execRes: any): Promise<string>;
9
15
  }
10
16
  import { AsyncNode } from '../qflow.js';
11
17
  import http from 'http';
12
- import { AsyncFlow } from '../qflow.js';
@@ -1,28 +1,133 @@
1
1
  import { AsyncNode, AsyncFlow } from '../qflow.js';
2
2
  import http from 'http';
3
3
  import { URL } from 'url';
4
+ import path from 'path';
5
+ import { promises as fsPromises } from 'fs';
6
+ import fs from 'fs';
7
+ // Basic mime-type lookup to avoid adding new dependencies
8
+ function getMimeType(filePath) {
9
+ const ext = path.extname(filePath).toLowerCase();
10
+ const types = {
11
+ '.html': 'text/html',
12
+ '.css': 'text/css',
13
+ '.js': 'application/javascript',
14
+ '.json': 'application/json',
15
+ '.png': 'image/png',
16
+ '.jpg': 'image/jpeg',
17
+ '.jpeg': 'image/jpeg',
18
+ '.gif': 'image/gif',
19
+ '.svg': 'image/svg+xml',
20
+ '.txt': 'text/plain',
21
+ };
22
+ return types[ext] || 'application/octet-stream';
23
+ }
4
24
  export class HttpServerNode extends AsyncNode {
5
- constructor(maxRetries = 1, wait = 0) {
6
- super(maxRetries, wait);
25
+ constructor() {
26
+ super();
7
27
  this.server = null;
8
- this.flowToTrigger = null;
9
28
  }
10
- async execAsync() {
11
- const { port = 3000, flow, waitForFlow = false } = this.params;
12
- if (!flow || !(flow instanceof AsyncFlow)) {
13
- throw new Error('HttpServerNode requires a `flow` parameter of type AsyncFlow to trigger.');
29
+ // Helper to find a matching route and extract params
30
+ findMatchingRoute(routes, method, path) {
31
+ for (const routePath in routes) {
32
+ const routeHandlers = routes[routePath];
33
+ const paramNames = [];
34
+ // Convert route path to regex, e.g., /users/:id -> /users/([^/]+)
35
+ const regexPath = routePath.replace(/:(\w+)/g, (_, paramName) => {
36
+ paramNames.push(paramName);
37
+ return '([^/]+)';
38
+ });
39
+ const regex = new RegExp(`^${regexPath}$`);
40
+ const match = path.match(regex);
41
+ if (match) {
42
+ const handler = routeHandlers[method.toUpperCase()];
43
+ if (handler) {
44
+ const params = {};
45
+ paramNames.forEach((name, index) => {
46
+ params[name] = match[index + 1];
47
+ });
48
+ return { flow: handler, params };
49
+ }
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ // Helper to serve static files
55
+ async handleStatic(staticDir, reqPath, res) {
56
+ if (!staticDir)
57
+ return false;
58
+ // Prevent directory traversal attacks
59
+ const safePath = path.normalize(reqPath).replace(/^(\.\.[\/\\])+/, '');
60
+ const filePath = path.join(staticDir, safePath);
61
+ try {
62
+ const stats = await fsPromises.stat(filePath);
63
+ if (stats.isFile()) {
64
+ const mimeType = getMimeType(filePath);
65
+ res.writeHead(200, { 'Content-Type': mimeType });
66
+ // Create a read stream and pipe it to the response
67
+ const fileStream = fs.createReadStream(filePath);
68
+ fileStream.pipe(res);
69
+ return true;
70
+ }
71
+ }
72
+ catch (e) {
73
+ // File doesn't exist, fall through to dynamic routing
74
+ }
75
+ return false;
76
+ }
77
+ // Helper to apply CORS headers
78
+ applyCorsHeaders(res, corsConfig) {
79
+ if (!corsConfig)
80
+ return;
81
+ if (corsConfig.origin) {
82
+ res.setHeader('Access-Control-Allow-Origin', corsConfig.origin);
83
+ }
84
+ if (corsConfig.methods) {
85
+ res.setHeader('Access-Control-Allow-Methods', corsConfig.methods);
14
86
  }
15
- this.flowToTrigger = flow;
87
+ if (corsConfig.headers) {
88
+ res.setHeader('Access-Control-Allow-Headers', corsConfig.headers);
89
+ }
90
+ }
91
+ async execAsync() {
92
+ const { port = 3000, routes = {}, staticDir, cors } = this.params;
16
93
  if (this.server && this.server.listening) {
17
- console.warn(`[HttpServerNode] Server already listening on port ${port}. Reusing existing server.`);
94
+ console.warn(`[HttpServerNode] Server already listening on port ${port}.`);
18
95
  return { status: 'server_already_running', port };
19
96
  }
20
97
  this.server = http.createServer(async (req, res) => {
98
+ // Apply CORS headers to all responses
99
+ this.applyCorsHeaders(res, cors);
100
+ // Handle CORS pre-flight OPTIONS request
101
+ if (cors && req.method === 'OPTIONS') {
102
+ res.writeHead(204); // No Content
103
+ res.end();
104
+ return;
105
+ }
21
106
  const requestUrl = new URL(req.url, `http://${req.headers.host}`);
107
+ const reqPath = requestUrl.pathname;
108
+ // 1. Try to serve static file
109
+ if (staticDir) {
110
+ const served = await this.handleStatic(staticDir, reqPath, res);
111
+ if (served)
112
+ return;
113
+ }
114
+ // 2. Find a matching dynamic route
115
+ const routeMatch = this.findMatchingRoute(routes, req.method, reqPath);
116
+ if (!routeMatch) {
117
+ res.writeHead(404, { 'Content-Type': 'application/json' });
118
+ res.end(JSON.stringify({ error: 'Not Found' }));
119
+ return;
120
+ }
121
+ const { flow, params: pathParams } = routeMatch;
122
+ if (!(flow instanceof AsyncFlow)) {
123
+ console.error(`[HttpServerNode] Handler for ${req.method} ${reqPath} is not an AsyncFlow.`);
124
+ res.writeHead(500, { 'Content-Type': 'application/json' });
125
+ res.end(JSON.stringify({ error: 'Internal Server Error: Invalid handler' }));
126
+ return;
127
+ }
128
+ // 3. Process request body and trigger flow
22
129
  let body = '';
23
- req.on('data', chunk => {
24
- body += chunk.toString();
25
- });
130
+ req.on('data', chunk => { body += chunk.toString(); });
26
131
  req.on('end', async () => {
27
132
  let payload;
28
133
  if (body) {
@@ -30,56 +135,55 @@ export class HttpServerNode extends AsyncNode {
30
135
  payload = JSON.parse(body);
31
136
  }
32
137
  catch (e) {
33
- console.error('[HttpServerNode] Failed to parse request body as JSON:', e);
34
- res.writeHead(400, { 'Content-Type': 'application/json' });
35
- res.end(JSON.stringify({ error: 'Invalid JSON payload' }));
36
- return;
138
+ payload = body; // Not JSON, treat as raw string
37
139
  }
38
140
  }
39
- const triggeredFlowShared = {
40
- webhook: {
41
- req,
42
- res,
43
- headers: req.headers,
44
- payload,
45
- method: req.method,
46
- path: requestUrl.pathname,
47
- query: Object.fromEntries(requestUrl.searchParams)
48
- }
141
+ const requestContext = {
142
+ headers: req.headers,
143
+ body: payload,
144
+ method: req.method,
145
+ path: reqPath,
146
+ query: Object.fromEntries(requestUrl.searchParams),
147
+ params: pathParams
49
148
  };
50
- if (waitForFlow) {
51
- try {
52
- const flowResult = await this.flowToTrigger.runAsync(triggeredFlowShared);
53
- if (!res.writableEnded) {
54
- res.writeHead(200, { 'Content-Type': 'application/json' });
55
- res.end(JSON.stringify(flowResult));
56
- }
57
- }
58
- catch (flowError) {
59
- console.error('[HttpServerNode] Triggered flow failed:', flowError);
60
- if (!res.writableEnded) {
61
- res.writeHead(500, { 'Content-Type': 'application/json' });
62
- res.end(JSON.stringify({ error: 'Flow execution failed' }));
149
+ try {
150
+ const flowResult = await flow.runAsync({ request: requestContext });
151
+ const response = flowResult || { statusCode: 204, body: '' };
152
+ const statusCode = response.statusCode || 200;
153
+ const headers = response.headers || {};
154
+ let responseBody = response.body;
155
+ if (typeof responseBody === 'object' && !(responseBody instanceof Buffer)) {
156
+ responseBody = JSON.stringify(responseBody);
157
+ if (!headers['Content-Type']) {
158
+ headers['Content-Type'] = 'application/json';
63
159
  }
64
160
  }
161
+ res.writeHead(statusCode, headers);
162
+ res.end(responseBody);
65
163
  }
66
- else {
67
- this.flowToTrigger.runAsync(triggeredFlowShared).catch(flowError => {
68
- console.error('[HttpServerNode] Triggered flow failed:', flowError);
69
- });
164
+ catch (flowError) {
165
+ console.error(`[HttpServerNode] Flow for ${req.method} ${reqPath} failed:`, flowError);
166
+ if (!res.writableEnded) {
167
+ res.writeHead(500, { 'Content-Type': 'application/json' });
168
+ res.end(JSON.stringify({ error: 'Flow execution failed', details: flowError.message }));
169
+ }
70
170
  }
71
171
  });
72
172
  });
73
- await new Promise(resolve => {
173
+ await new Promise((resolve, reject) => {
174
+ this.server.on('error', (err) => {
175
+ console.error(`[HttpServerNode] Failed to start server on port ${port}:`, err.message);
176
+ reject(err);
177
+ });
74
178
  this.server.listen(port, () => {
75
- console.log(`[HttpServerNode] Listening for requests on http://localhost:${port}`);
179
+ console.log(`[HttpServerNode] Listening on http://localhost:${port}`);
76
180
  resolve();
77
181
  });
78
182
  });
79
183
  return { status: 'listening', port };
80
184
  }
81
185
  async postAsync(shared, prepRes, execRes) {
82
- // The server should not be closed here.
83
- return execRes;
186
+ shared.httpServer = this.server;
187
+ return 'default';
84
188
  }
85
189
  }
@@ -25,6 +25,7 @@ export * from "./shell.js";
25
25
  export * from "./filesystem.js";
26
26
  export * from "./user.js";
27
27
  export * from "./http.js";
28
+ export * from "./http_server.js";
28
29
  export * from "./search.js";
29
30
  export * from "./summarize.js";
30
31
  export * from "./memory.js";
@@ -25,6 +25,7 @@ export * from './shell.js';
25
25
  export * from './filesystem.js';
26
26
  export * from './user.js';
27
27
  export * from './http.js';
28
+ export * from './http_server.js';
28
29
  export * from './search.js';
29
30
  export * from './summarize.js';
30
31
  export * from './memory.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fractal-solutions/qflow",
3
- "version": "1.0.51",
3
+ "version": "1.0.53",
4
4
  "description": "A lightweight and flexible JavaScript library for creating and managing workflows and agents.",
5
5
  "main": "dist/qflow.js",
6
6
  "types": "dist/qflow.d.ts",