-
Notifications
You must be signed in to change notification settings - Fork 0
/
.tscoder
805 lines (681 loc) · 24.2 KB
/
.tscoder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
# TSCODER
You are TsCoder, a TypeScript language coding assistant.
## INPUT:
You will receive a TARGET <FILE/> in the TypeScript language, some additional <FILE/>'s for context, and a change or refactor <REQUEST/>, from the user.
## OUTPUT:
You must answer with one or more <FILE/> tags, including files to be overwritten, in order to fulfill the user's request.
---
# EXAMPLE TSCODER USAGE
## Suppose you're given the following INPUT:
<FILE path="/Users/v/vic/dev/tsbook/List/_.ts">
// A polymorphic List with two constructors:
// - Cons: appends an element to a list
// - Nil: the empty list
export type List<A>
= { "$": "Cons", head: A, tail: List<A> }
| { "$": "Nil" };
</FILE>
<FILE path="/Users/v/vic/dev/tsbook/List/map.ts" TARGET>
// The map function for List, to be implemented
import { List } from "./_";
export function map<A, B>(fn: (a: A) => B, list: List<A>): List<B> {
?
}
</FILE>
<REQUEST>
complete the map function
</REQUEST>
## Then, you must answer with the following OUTPUT:
<FILE path="/Users/v/vic/dev/tsbook/List/map.ts">
import { List } from "./_";
// Applies a function to each element of a list.
// - fn: the function to be applied
// - xs: the elements to apply fn to
// = a new list with fn applied to all elements
export function map<A, B>(xs: List<A>, fn: (a: A) => B): List<B> {
switch (xs.$) {
case "Cons": {
var head = fn(xs.head);
var tail = map(xs.tail, fn);
return { $: "Cons", head, tail };
}
case "Nil": {
return { $: "Nil" };
}
}
}
</FILE>
(Because it fulfills the user's request perfectly.)
---
# GUIDE FOR THE TYPESCRIPT LANGUAGE
- Your code must be inspired by pure functional programming languages like Haskell.
- Every file must declare only, and only one, top-level function or datatype.
- Functions must be pure, using switch instead of 'if-else' or 'case-of'.
- When defining local variables, align equal signs whenever possible.
- Use CamelCase for everything. (IMPORTANT)
- A 'Foo/Bar' top-level definition must be either on './Foo/Bar.ts' or './Foo/Bar/_.ts'.
## Top-Level Function
Every .ts file must define ONE top-level function. Example:
```typescript
// Calculates the size of an HTerm
// - term: the HTerm to measure
// = the number of nodes in the term
export function size(term: HTerm): number {
switch (term.$) {
case "Lam": {
var bod_size = size(term.bod({$: "Var", nam: term.nam}));
return 1 + bod_size;
}
case "App": {
var fun_size = size(term.fun);
var arg_size = size(term.arg);
return 1 + fun_size + arg_size;
}
case "Var": {
return 1;
}
}
}
```
Where:
- The function name is defined (e.g., 'size')
- Parameters are specified with their types (e.g., 'term: HTerm')
- The return type is specified (e.g., ': number')
- The function body uses a switch statement for pattern matching
- Local variables are used to make the code less horizontal
## Top-Level Datatype
Alternatively, a .ts file can also define a datatype (ADT). Example:
```typescript
// Represents a Higher-Order Abstract Syntax Term
// - Lam: lambda abstraction
// - App: function application
// - Var: variable
export type HTerm
= { $: "Lam", bod: (x: HTerm) => HTerm }
| { $: "App", fun: HTerm, arg: HTerm }
| { $: "Var", nam: string }
```
ADTs must follow this convention:
- Constructors represented as objects
- The dollar-sign is used for the constructor name
- Other object fields are the constructor fields
## Idiomatic TypeScript Examples
Below are some additional idiomatic TypeScript in the purely functional style:
### List/zip.ts
```typescript
import { List } from "./_";
// Combines two lists into a list of pairs
// - xs: the first input list
// - ys: the second input list
// = a new list of pairs, with length equal to the shorter input list
export function zip<A, B>(xs: List<A>, ys: List<B>): List<[A, B]> {
switch (xs.$) {
case "Cons": {
switch (ys.$) {
case "Cons": {
var head = [xs.head, ys.head] as [A,B];
var tail = zip(xs.tail, ys.tail);
return { $: "Cons", head, tail };
}
case "Nil": {
return { $: "Nil" };
}
}
}
case "Nil": {
return { $: "Nil" };
}
}
}
```
### List/filter.ts
```typescript
import { List } from "./_";
// Filters a list based on a predicate function
// - xs: the input list
// - pred: the predicate function to test each element
// = a new list containing only elements that satisfy the predicate
export function filter<A>(xs: List<A>, pred: (a: A) => boolean): List<A> {
switch (xs.$) {
case "Cons": {
var head = xs.head;
var tail = filter(xs.tail, pred);
return pred(xs.head) ? { $: "Cons", head, tail } : tail;
}
case "Nil": {
return { $: "Nil" };
}
}
}
```
### Tree/_.ts
```typescript
// Represents a binary tree
// - Node: an internal node with a value and two subtrees
// - Leaf: a leaf node (empty)
export type Tree<A>
= { $: "Node", val: A, left: Tree<A>, right: Tree<A> }
| { $: "Leaf" };
```
### Tree/sum.ts
```typescript
import { Tree } from "./_";
// Sums all values in a numeric tree
// - tree: the tree to sum
// = the sum of all values in the tree
export function sum(tree: Tree<number>): number {
switch (tree.$) {
case "Node": {
var left = sum(tree.left);
var right = sum(tree.right);
return tree.val + left + right;
}
case "Leaf": {
return 0;
}
}
}
```
### V3/_.ts
```typescript
// Represents a 3D vector
export type V3
= { $: "V3", x: number, y: number, z: number };
```
### V3/dot.ts
```typescript
import { V3 } from "./_";
// Calculates the dot product of two 3D vectors
// - a: the first vector
// - b: the second vector
// = the dot product of a and b
export function dot(a: V3, b: V3): number {
return a.x * b.x + a.y * b.y + a.z * b.z;
}
```
---
# NOTES
- Make ONLY the changes necessary to correctly fulfill the user's REQUEST.
- Do NOT fix, remove, complete or alter any parts unrelated to the REQUEST.
- Pay attention to the user's style, and mimic it as close as possible.
- Pay attention to the TypeScript examples and mimic their style as a default.
- Consult TypeScript guide to emit idiomatic correct code.
- Do NOT use or assume the existence of files that weren't shown to you.
- Be precise and careful in your modifications.
---
# TASK
You will now be given the actual INPUT you must work with.
<FILE path="/home/travis/Projects/flow-based-programming/src/interfaces/component.interface.ts">
export interface Component {
id: string;
name: string;
description?: string;
handleEvent: (eventName: string, data: any) => Promise<void>;
emitEvent: (flowId: string, eventName: string, data: any) => Promise<void>;
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/logger/custom-logger.ts">
import { ConsoleLogger, Injectable, Inject } from '@nestjs/common';
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
import * as fs from 'fs';
import * as path from 'path';
@Injectable()
export class CustomLogger extends ConsoleLogger {
constructor(
private componentId: string,
@Inject(AmqpConnection) private amqpConnection: AmqpConnection
) {
super(componentId);
this.setLogLevels(['log', 'error', 'warn', 'debug', 'verbose']);
}
log(message: string, context?: string) {
this.printMessage(message, 'log', context);
// this.emitLogEvent('log', message);
}
warn(message: string, context?: string) {
this.printMessage(message, 'warn', context);
// this.emitLogEvent('warn', message);
}
error(message: string, trace?: string, context?: string) {
this.printMessage(message, 'error', context);
// this.emitLogEvent('error', message);
if (trace) {
this.printMessage(trace, 'error', context);
}
}
debug(message: string, context?: string) {
this.printMessage(message, 'debug', context);
}
verbose(message: string, context?: string) {
this.printMessage(message, 'verbose', context);
}
private printMessage(message: string, logLevel: string, context?: string) {
const output = context ? `[${context}] ${message}` : message;
console.log(`[${this.getNow()}] [${logLevel.toUpperCase()}] ${output}`);
}
private async emitLogEvent(level: string, message: string) {
await this.amqpConnection.publish('flow_exchange', 'componentEvent', {
componentId: this.componentId,
eventName: 'logger',
data: {
level,
message,
},
});
}
private getNow(): string {
return new Date().toISOString();
}
static write_to_file(message: string) {
const logFile = path.join(process.cwd(), 'STDOUT.txt');
fs.appendFile(logFile, message, (err) => {
if (err) {
console.error('Failed to write to log file:', err);
}
});
}
static clearSTDOUT() {
const logFile = path.join(process.cwd(), 'STDOUT.txt');
try {
fs.writeFileSync(logFile, '');
console.log(`Log file cleared at ${logFile}`);
} catch (error) {
console.error('Failed to clear log file:', error);
}
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/components/event-trigger.component.ts">
import { Injectable } from '@nestjs/common';
import { ComponentService } from '../base.component';
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
@Injectable()
export class EventTriggerComponent extends ComponentService {
constructor() {
super('eventTrigger', 'Event Trigger', 'Handles HTMX requests and triggers events');
}
async handleEvent(eventName: string, data: any): Promise<void> {
this.logger.log(`EventTrigger handling event: ${eventName}`);
if (eventName === 'triggerEvent') {
const { flowId, componentId, eventId } = data;
await this.publish({
flowId,
componentId,
eventName: eventId,
data: data.data,
});
}
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/components/number-generator.component.ts">
import { Injectable } from '@nestjs/common';
import { ComponentService } from '../base.component';
@Injectable()
export class NumberGeneratorComponent extends ComponentService {
private interval: NodeJS.Timeout | null = null;
constructor() {
super('numberGenerator', 'Number Generator', 'Generates random numbers periodically');
}
async handleEvent(eventName: string, data: any): Promise<void> {
this.logger.log(`NumberGenerator handling event: ${eventName}`);
if (eventName === 'start') {
this.logger.log('NumberGenerator starting number generation');
this.startGenerating();
} else if (eventName === 'stop') {
this.logger.log('NumberGenerator stopping number generation');
this.stopGenerating();
}
}
private startGenerating() {
this.logger.log('NumberGenerator startGenerating method called');
if (this.interval) {
clearInterval(this.interval);
}
this.interval = setInterval(async () => {
const randomNumber = Math.random();
this.logger.log(`NumberGenerator generated number: ${randomNumber}`);
await this.emitEvent('numberGenerated', randomNumber);
// Send HTMX update
await this.sendHtmxUpdate({
number: randomNumber,
timestamp: Date.now()
}, 'number-generator');
}, 1000);
}
private stopGenerating() {
this.logger.log('NumberGenerator stopGenerating method called');
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/components/number-multiplier.component.ts">
import { Injectable, Logger } from '@nestjs/common';
import { ComponentService } from '../base.component';
@Injectable()
export class NumberMultiplierComponent extends ComponentService {
constructor() {
super('numberMultiplier', 'Number Multiplier', 'Multiplies received number by 2');
}
async handleEvent(eventName: string, data: any): Promise<void> {
this.logger.log(`NumberMultiplier handling event: ${eventName}`);
if (eventName === 'numberReceived') {
const result = data * 2;
this.logger.log(`NumberMultiplier received ${data}, multiplied result: ${result}`);
await this.emitEvent('numberMultiplied', result);
// Send HTMX update
await this.sendHtmxUpdate({
input: data,
result: result,
timestamp: Date.now()
}, 'number-multiplier');
}
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/services/component-registry.service.ts">
import { Injectable, Logger } from '@nestjs/common';
import { Component } from '../interfaces/component.interface';
@Injectable()
export class ComponentRegistry {
private components: Map<string, Component> = new Map();
private readonly logger = new Logger(ComponentRegistry.name);
registerComponent(component: Component) {
this.logger.log(`Registering component: ${component.id}`);
this.components.set(component.id, component);
}
getComponent(id: string): Component | undefined {
const component = this.components.get(id);
if (!component) {
this.logger.warn(`Component not found: ${id}`);
}
return component;
}
getAllComponents(): Component[] {
return Array.from(this.components.values());
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/services/flow-executor.service.ts">
import { Injectable, Logger } from '@nestjs/common';
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
import { ComponentRegistry } from './component-registry.service';
import { Flow } from '../interfaces/flow.interface';
@Injectable()
export class FlowExecutorService {
private readonly logger = new Logger(FlowExecutorService.name);
constructor(
private amqpConnection: AmqpConnection,
private componentRegistry: ComponentRegistry
) {}
async executeFlow(flow: Flow) {
this.logger.log(`Executing flow: ${flow.id}`);
// Create connections
for (const connection of flow.connections) {
this.logger.log(`Creating connection: ${connection.fromComponent}.${connection.fromEvent} -> ${connection.toComponent}.${connection.toEvent}`);
await this.amqpConnection.publish('flow_exchange', 'createConnection', connection);
}
// Init components
for (const component of flow.components) {
const componentInstance = this.componentRegistry.getComponent(component.componentId);
if (componentInstance) {
this.logger.log(`Initializing component: ${component.componentId}`);
try {
await this.amqpConnection.publish('flow_exchange', 'componentEvent', {
flowId: flow.id,
componentId: component.componentId,
eventName: 'init',
data: {},
});
} catch (error) {
this.logger.error(`Error initing component ${component.componentId}:`, error);
}
} else {
this.logger.warn(`Component not found: ${component.componentId}`);
}
}
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/processors/event.processor.ts">
import { Injectable, Logger } from '@nestjs/common';
import { RabbitSubscribe, RabbitRPC } from '@golevelup/nestjs-rabbitmq';
import { ComponentRegistry } from '../services/component-registry.service';
@Injectable()
export class EventProcessor {
private readonly logger = new Logger(EventProcessor.name);
private connections: Map<string, { toFlow: string; toComponent: string; toEvent: string }> = new Map();
constructor(private componentRegistry: ComponentRegistry) {}
@RabbitSubscribe({
exchange: 'flow_exchange',
routingKey: 'componentEvent',
queue: 'component_event_queue',
})
async handleComponentEvent(msg: {flowId: string, componentId: string, eventName: string, data: any}) {
const { flowId, componentId, eventName, data: eventData } = msg;
this.logger.log(`[handleComponentEvent] [${flowId}.${componentId}.${eventName}] data: ${JSON.stringify(eventData)}`);
const component = this.componentRegistry.getComponent(componentId);
if (component) {
this.logger.log(`Passing event to component: ${componentId}`);
await component.handleEvent(eventName, eventData);
// Check if there's a connection for this event
const connectionKey = `${flowId}.${componentId}.${eventName}`;
const connection = this.connections.get(connectionKey);
if (connection) {
const { toFlow, toComponent, toEvent } = connection;
this.logger.log(`[forwardingComponentEvent] [${toFlow}.${toComponent}.${toEvent}]`);
const targetComponent = this.componentRegistry.getComponent(toComponent);
if (targetComponent) {
await targetComponent.handleEvent(toEvent, { ...eventData, flowId: toFlow });
} else {
this.logger.warn(`Target component not found: ${toComponent}`);
}
}
} else {
this.logger.warn(`Component not found: ${componentId}`);
}
}
@RabbitSubscribe({
exchange: 'flow_exchange',
routingKey: 'createConnection',
queue: 'create_connection_queue',
})
async createConnection(msg: {flowId: string, fromComponent: string, fromEvent: string, toComponent: string, toEvent: string}) {
const { flowId, fromComponent, fromEvent, toComponent, toEvent } = msg;
this.logger.log(`Received createConnection: ${flowId}.${fromComponent}.${fromEvent} -> ${toComponent}.${toEvent}`);
const connectionKey = `${flowId}.${fromComponent}.${fromEvent}`;
this.connections.set(connectionKey, { toFlow: flowId, toComponent, toEvent });
this.logger.log(`Connection created: ${connectionKey} -> ${toComponent}.${toEvent}`);
return { success: true, message: 'Connection created successfully' };
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/modules/app.module.ts">
import { Module, OnModuleInit } from '@nestjs/common';
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq';
import { ComponentRegistry } from '../services/component-registry.service';
import { FlowExecutorService } from '../services/flow-executor.service';
import { EventProcessor } from '../processors/event.processor';
import { NumberGeneratorComponent } from '../components/number-generator.component';
import { NumberMultiplierComponent } from '../components/number-multiplier.component';
import { EventTriggerComponent } from '../components/event-trigger.component';
import { CustomLogger } from '../logger/custom-logger';
import { AppController } from '../controllers/app.controller';
@Module({
imports: [
RabbitMQModule.forRoot(RabbitMQModule, {
exchanges: [
{
name: 'flow_exchange',
type: 'topic',
},
],
uri: 'amqp://localhost:5672',
connectionInitOptions: { wait: false },
}),
],
controllers: [AppController],
providers: [
EventProcessor,
ComponentRegistry,
FlowExecutorService,
NumberGeneratorComponent,
NumberMultiplierComponent,
EventTriggerComponent,
CustomLogger
],
exports: [EventProcessor],
})
export class AppModule implements OnModuleInit {
constructor(
private componentRegistry: ComponentRegistry,
private numberGeneratorComponent: NumberGeneratorComponent,
private numberMultiplierComponent: NumberMultiplierComponent,
private eventTriggerComponent: EventTriggerComponent
) {}
onModuleInit() {
this.componentRegistry.registerComponent(this.numberGeneratorComponent);
this.componentRegistry.registerComponent(this.numberMultiplierComponent);
this.componentRegistry.registerComponent(this.eventTriggerComponent);
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/bootstrap/app.bootstrap.ts">
import { NestFactory } from '@nestjs/core';
import { AppModule } from '../modules/app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import * as cookieParser from 'cookie-parser';
import { FlowExecutorService } from '../services/flow-executor.service';
import { Flow } from '../interfaces/flow.interface';
import { ComponentRegistry } from '../services/component-registry.service';
import { CustomLogger } from '../logger/custom-logger';
import { resolve } from 'path';
export async function bootstrapApp(logger: CustomLogger): Promise<any> {
const app = await NestFactory.create<NestExpressApplication>(AppModule, { logger });
app.useStaticAssets(resolve('./src/public'));
app.setBaseViewsDir(resolve('./src/views'));
app.setViewEngine('ejs');
app.use(cookieParser());
// so browsers can use api
app.enableCors({
origin: '*',
});
const flowExecutor = app.get(FlowExecutorService);
const componentRegistry = app.get(ComponentRegistry);
await app.init();
const exampleFlow: Flow = {
id: 'example-flow',
components: [
{ id: 'main', componentId: 'eventTrigger' },
{ id: 'gen1', componentId: 'numberGenerator' },
{ id: 'mult1', componentId: 'numberMultiplier' },
],
connections: [
{
fromComponent: 'gen1',
fromEvent: 'numberGenerated',
toComponent: 'mult1',
toEvent: 'numberReceived',
},
],
};
logger.log('Starting flow execution...');
await flowExecutor.executeFlow(exampleFlow);
await app.listen(3000);
logger.log('Application is running on: http://localhost:3000');
return app;
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/interfaces/flow.interface.ts">
export interface Flow {
id: string;
components: {
id: string;
componentId: string;
}[];
connections: {
fromComponent: string;
fromEvent: string;
toComponent: string;
toEvent: string;
}[];
}
</FILE>
<FILE path="src/base.component.ts" TARGET>
import { Inject, Injectable } from '@nestjs/common';
import { AmqpConnection } from '@golevelup/nestjs-rabbitmq';
import { Component } from './interfaces/component.interface';
import { CustomLogger } from './logger/custom-logger';
import { WebSocketGateway, WebSocketServer, SubscribeMessage, MessageBody } from '@nestjs/websockets';
import { Server } from 'socket.io';
import * as ejs from 'ejs';
import * as path from 'path';
@WebSocketGateway()
@Injectable()
export abstract class ComponentService implements Component {
@Inject(AmqpConnection)
protected amqpConnection: AmqpConnection;
protected readonly logger: CustomLogger;
@WebSocketServer() server: Server;
constructor(
public id: string,
public name: string,
public description: string
) {
this.logger = new CustomLogger(this.id, this.amqpConnection);
}
abstract handleEvent(flowId: string, eventName: string, data: any): Promise<void>;
async emitEvent(flowId: string, eventName: string, data: any): Promise<void> {
this.logger.log(`Emitting event: ${eventName}, flowId: ${flowId}, data: ${JSON.stringify(data)}`);
await this.amqpConnection.publish('flow_exchange', 'componentEvent', {
flowId,
componentId: this.id,
eventName,
data,
});
}
@SubscribeMessage('client-event')
handleClientEvent(@MessageBody() data: any): void {
const { flowId, componentId, eventId, ...eventData } = data;
this.logger.log(`Received client event: flowId=${flowId}, componentId=${componentId}, eventId=${eventId}, data=${JSON.stringify(eventData)}`);
this.emitEvent(flowId, 'clientEventReceived', { componentId, eventId, data: eventData });
}
protected async sendHtmxUpdate(flowId: string, data: any, templateId: string) {
const htmxContent = await this.generateHtmxContent(data, flowId, templateId);
this.server.emit('htmx-update', {
flowId,
componentId: this.id,
templateId,
content: htmxContent
});
}
private async generateHtmxContent(data: any, flowId: string, templateId: string): Promise<string> {
const templatePath = path.resolve(__dirname, `./templates/${templateId}.ejs`);
try {
return await ejs.renderFile(templatePath, {
data,
flowId,
componentId: this.id,
templateId
});
} catch (error) {
this.logger.error(`Error rendering EJS template: ${error.message}`);
return `<div>Error rendering content</div>`;
}
}
async publish(message: any): Promise<void> {
try {
await this.amqpConnection.publish('flow_exchange', 'componentEvent', message);
} catch (error) {
this.logger.error(`Error publishing message: ${error.message}`);
throw error;
}
}
}
</FILE>
<REQUEST>
it should be able to handle multiple flows; flow id should be set from the constructor
</REQUEST>