-
Notifications
You must be signed in to change notification settings - Fork 0
/
.nestcoder
1149 lines (1000 loc) · 32.1 KB
/
.nestcoder
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# NESTCODER
You are NestCoder, a HTMX, EJS and TypeScript/NestJS language coding assistant.
## INPUT:
You will receive a TARGET <FILE/> in the EJS or TypeScript/NestJS 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 NESTCODER 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'.
# GUIDE FOR THE EJS LANGUAGE
- Use HTMX for frontend.
## 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/components/benchmark-analyzer/benchmark-analyzer.handler.ts">
import { CustomLogger } from '../../logger/custom-logger';
import { Injectable, Inject } from '@nestjs/common';
import { ComponentBase } from '../../bases/component.base';
import { BackplaneService } from 'src/services/backplane.service';
import { Server } from 'socket.io';
import { TemplateCacheService } from 'src/services/template-cache.service';
@Injectable()
export class BenchmarkAnalyzerComponent extends ComponentBase {
public logger: CustomLogger;
private startTimes: { [size: number]: number } = {};
private endTimes: { [size: number]: number } = {};
private dataPoints: { [size: number]: number[] } = {};
private currentMessageSize: number = 1;
private messageSizes: number[] = [1, 10, 100, 1000, 10000];
private messagesPerSize: number = 100;
private currentSizeIndex: number = 0;
public ports = {
inputs: [
'any.publish.startBenchmark',
'any.publish.endBenchmark',
'any.publish.dataPoint'
],
outputs: [
'any.publish.benchmarkResult',
'htmx.display.benchmark-results',
'any.publish.startMessageGeneration',
'any.publish.stopMessageGeneration',
'any.publish.nextMessageSize'
]
}
constructor(
@Inject('FLOW_ID') flowId: string,
@Inject('COMPONENT_ID') componentId: string,
@Inject(BackplaneService) backplane: BackplaneService,
@Inject('WEB_SOCKET_SERVER') protected server: Server,
@Inject('TEMPLATES') templates: TemplateCacheService
) {
super('benchmarkAnalyzer', 'benchmark-analyzer', 'Analyzes benchmark results', flowId, componentId, backplane, server, templates);
this.flowId = flowId;
this.componentId = componentId;
this.logger = new CustomLogger(`${flowId}.${componentId}`);
}
async handleEvent(eventId: string, data: any): Promise<void> {
switch (eventId) {
case "init": {
await this.initBenchmark(data);
break;
}
case "startBenchmark": {
await this.startBenchmark();
break;
}
case "endBenchmark": {
await this.endBenchmark();
break;
}
case "dataPoint": {
await this.addDataPoint(data.processingTime, data.size);
break;
}
}
}
private async initBenchmark(data: any): Promise<void> {
if (data && data.messageSizes) {
this.messageSizes = data.messageSizes;
}
if (data && data.messagesPerSize) {
this.messagesPerSize = data.messagesPerSize;
}
this.logger.log(`Benchmark initialized with message sizes: ${this.messageSizes}, messages per size: ${this.messagesPerSize}`);
this.resetDataPoints();
}
private async startBenchmark(): Promise<void> {
this.currentSizeIndex = 0;
this.currentMessageSize = this.messageSizes[this.currentSizeIndex];
this.resetDataPoints();
this.startTimes[this.currentMessageSize] = Date.now();
console.log('========');
console.log(`Benchmark started for size ${this.currentMessageSize} at ${this.startTimes[this.currentMessageSize]}`);
console.log('========');
await this.publish(this.flowId, this.componentId, 'startMessageGeneration', {});
}
private async endBenchmark(): Promise<void> {
this.endTimes[this.currentMessageSize] = Date.now();
this.logger.log(`Benchmark ended for size ${this.currentMessageSize} at ${this.endTimes[this.currentMessageSize]}`);
await this.publish(this.flowId, this.componentId, 'stopMessageGeneration', {});
console.log('========');
console.log('waiting 2s for benchmark to finish');
console.log('========');
await new Promise(resolve => setTimeout(resolve, 2000)); // wait for benchmark to finish
if (this.currentSizeIndex < this.messageSizes.length - 1) {
this.currentSizeIndex++;
await this.startNextSizeBenchmark();
} else {
const result = this.analyzeBenchmark();
await this.publish(this.flowId, this.componentId, 'benchmarkResult', result);
await this.display(this.flowId, this.componentId, 'benchmark-results', { results: result });
console.log('!!!!!!!!');
console.log('benchmark-results: success');
console.log('!!!!!!!!');
}
}
private async addDataPoint(processingTime: number, size: number): Promise<void> {
if (!this.dataPoints[size]) {
this.dataPoints[size] = [];
}
this.dataPoints[size].push(processingTime);
if (this.dataPoints[size].length === this.messagesPerSize) {
console.log('////////// end benchmark', this.dataPoints[size].length, '===', this.messagesPerSize);
await this.endBenchmark();
}
}
private async startNextSizeBenchmark(): Promise<void> {
this.currentMessageSize = this.messageSizes[this.currentSizeIndex];
this.logger.log(`Starting benchmark for next size: ${this.currentMessageSize}`);
await this.publish(this.flowId, this.componentId, 'nextMessageSize', { size: this.currentMessageSize });
console.log('~~~~~~ startNextSizeBenchmark', this.currentMessageSize);
await new Promise(resolve => setTimeout(resolve, 2000)); // wait for nextMessageSize to propagate
this.startTimes[this.currentMessageSize] = Date.now();
await this.publish(this.flowId, this.componentId, 'startMessageGeneration', {});
await this.publish(this.flowId, this.componentId, 'startMessageGeneration', {});
await this.publish(this.flowId, this.componentId, 'startMessageGeneration', {});
}
private analyzeBenchmark(): BenchmarkResults {
const results: BenchmarkResults = {};
for (const size of this.messageSizes) {
const times = this.dataPoints[size] || [];
const messageCount = times.length;
const totalTime = times.reduce((sum, time) => sum + time, 0);
const averageProcessingTime = messageCount > 0 ? totalTime / messageCount : 0;
const startTime = this.startTimes[size] || 0;
const endTime = this.endTimes[size] || 0;
const totalDuration = (endTime - startTime) / 1000; // Convert to seconds
const messagesPerSecond = totalDuration > 0 ? (messageCount / totalDuration).toFixed(2) : '0';
results[size] = {
messageCount,
averageProcessingTime,
messagesPerSecond,
};
this.logger.log(`Analysis for size ${size}: Count=${messageCount}, Avg=${averageProcessingTime.toFixed(2)}ms, MPS=${messagesPerSecond}`);
}
return results;
}
private resetDataPoints(): void {
this.dataPoints = {};
this.startTimes = {};
this.endTimes = {};
this.messageSizes.forEach(size => {
this.dataPoints[size] = [];
});
this.logger.log('Data points reset');
}
}
interface BenchmarkResult {
messageCount: number;
averageProcessingTime: number;
messagesPerSecond: string;
}
interface BenchmarkResults {
[size: number]: BenchmarkResult;
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/flows/benchmark.flow.ts">
import { schema } from "../schema/flow.schema";
import { default as initJobStateMachine } from "src/stateMachines/job.state-machine";
let benchmarks = {
messageSizes: [1, 10, 100, 1000, 10000],
messagesPerSize: 1000
}
let messageGenerator = {
ports: {
inputs: {
start: {},
stop: {},
setMessageSize: {}
},
outputs: {
messageGenerated: {}
}
},
init: benchmarks
}
let messageProcessor = {
ports: {
inputs: {
messageReceived: {}
},
outputs: {
processingComplete: {}
}
}
}
let benchmarkAnalyzer = {
ports: {
inputs: {
startBenchmark: {},
endBenchmark: {},
dataPoint: {}
},
outputs: {
benchmarkResult: {},
startMessageGeneration: {},
stopMessageGeneration: {},
nextMessageSize: {}
}
},
init: benchmarks
}
let buttonTrigger = {
ports: {
inputs: {
triggerButton: {}
},
outputs: {
buttonPressed: {}
}
}
}
let components = {
gen: {
messageGenerator
},
proc: {
messageProcessor
},
analyzer: {
benchmarkAnalyzer
},
sm: {
stateMachine: {
init: initJobStateMachine,
ports: {
inputs: {
initStateMachine: {}
},
outputs: {}
}
}
},
jsm: {
jobStateMachine: {
ports: {
inputs: {
initProxyMachine: {},
'set-start': {},
'set-pause': {},
'set-resume': {},
'set-finish': {},
'set-reset': {}
},
outputs: {
'get-start': {},
'get-pause': {},
'get-resume': {},
'get-finish': {},
'get-reset': {},
stateChanged: {}
}
}
}
},
startBtn: { buttonTrigger },
stopBtn: { buttonTrigger },
resetBtn: { buttonTrigger },
}
let flow = {
id: 'benchmark-flow',
components,
connections: [
{
from: 'components.sm.stateMachine.ports.outputs.initProxyMachine',
to: 'components.jsm.jobStateMachine.ports.inputs.initProxyMachine'
},
{
from: 'components.jsm.jobStateMachine.ports.outputs.get-start',
to: 'components.analyzer.benchmarkAnalyzer.ports.inputs.startBenchmark'
},
{
from: 'components.analyzer.benchmarkAnalyzer.ports.outputs.nextMessageSize',
to: 'components.gen.messageGenerator.ports.inputs.setMessageSize'
},
{
from: 'components.jsm.jobStateMachine.ports.outputs.get-resume',
to: 'components.analyzer.benchmarkAnalyzer.ports.inputs.startBenchmark'
},
{
from: 'components.jsm.jobStateMachine.ports.outputs.get-finish',
to: 'components.analyzer.benchmarkAnalyzer.ports.inputs.endBenchmark'
},
{
from: 'components.gen.messageGenerator.ports.outputs.messageGenerated',
to: 'components.proc.messageProcessor.ports.inputs.messageReceived'
},
{
from: 'components.proc.messageProcessor.ports.outputs.processingComplete',
to: 'components.analyzer.benchmarkAnalyzer.ports.inputs.dataPoint'
},
{
from: 'components.analyzer.benchmarkAnalyzer.ports.outputs.startMessageGeneration',
to: 'components.gen.messageGenerator.ports.inputs.start'
},
{
from: 'components.analyzer.benchmarkAnalyzer.ports.outputs.stopMessageGeneration',
to: 'components.gen.messageGenerator.ports.inputs.stop'
},
{
from: 'components.startBtn.buttonTrigger.ports.outputs.buttonPressed',
to: 'components.jsm.jobStateMachine.ports.inputs.set-start'
},
{
from: 'components.stopBtn.buttonTrigger.ports.outputs.buttonPressed',
to: 'components.jsm.jobStateMachine.ports.inputs.set-finish'
},
{
from: 'components.resetBtn.buttonTrigger.ports.outputs.buttonPressed',
to: 'components.jsm.jobStateMachine.ports.inputs.set-reset'
}
]
};
export default schema(flow);
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/services/template-cache.service.ts">
import { Injectable } from '@nestjs/common';
@Injectable()
export class TemplateCacheService {
private cache: Map<string, string> = new Map();
setTemplate(key: string, content: string): void {
this.cache.set(key, content);
}
getTemplate(key: string): string | undefined {
return this.cache.get(key);
}
hasTemplate(key: string): boolean {
return this.cache.has(key);
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/logger/custom-logger.ts">
import { ConsoleLogger, Injectable, Inject } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';
@Injectable()
export class CustomLogger extends ConsoleLogger {
constructor(
private logId: string,
) {
super(logId);
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()}] [${this.logId}] ${output}`);
}
private getNow(): string {
return new Date().toISOString();
}
static write_to_file(message: string) {
const logFile = path.join(process.cwd(), 'start:dev.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(), 'start:dev.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/views/main.ejs">
<main>
<h1>FBP Steam Engine</h1>
<p>The complete Flow-based Programming solution:</p>
<div style="overflow: hidden;">
<ul class="navigation">
<li><a href="/flows"><button>flows</button></a></li>
<li><a href="/components"><button>components</button></a></li>
<li><a href="/events"><button>events</button></a></li>
<li><a href="/stateMachines"><button>state machines</button></a></li>
<li><a href="/templates"><button>templates</button></a></li>
<li><a href="/logs"><button>logs</button></a></li>
</ul>
</div>
<p>
> Works best with multiple screens! (chart, document, logger)<br />
> *ideal for domain specific languages*
</p>
<hr>
<p>
What is FBP? Is it time for a new Steam Engine?<br />
<a href="https://www.youtube.com/watch?v=up2yhNTsaDs" target="_blank">https://www.youtube.com/watch?v=up2yhNTsaDs</a>
</p>
<p>
Fork this FBP Steam Engine repository for each application.<br />
<a href="https://github.com/subvind/flow-based-programming" target="_blank">https://github.com/subvind/flow-based-programming</a>
</p>
<span>~made with ♥ by <a href="https://istrav.com">isTrav</a> & <a href="https://subvind.com">subVind</a> + ai :)</span>
</main>
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/views/style.ejs">
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background: #eee;
}
main {
border: 1px solid #111;
margin: 0 auto;
max-width: 600px;
padding: 1em;
background: #fff;
}
h1 {
margin: 0;
}
.navigation {
margin: 0;
padding: 0;
list-style: none outside none;
position: relative;
}
.navigation li {
margin: 0 0.5em 0.5em 0;
list-style-type: none;
float: left;
}
.navigation li button {
font-size: 1.2em;
}
</style>
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/controllers/app.controller.ts">
import { Logger, Controller, Get, Post, Render, Body, Param, Res, Req } from '@nestjs/common';
import { Response, Request } from 'express';
import { EventTriggerComponent } from '../components/event-trigger/event-trigger.handler';
import { ComponentRegistry } from 'src/services/component-registry.service';
import { Connection } from 'src/interfaces/connection.interface';
import { Port } from 'src/interfaces/port.interface';
import { FlowExecutorService } from 'src/services/flow-executor.service';
import { TemplateCacheService } from 'src/services/template-cache.service';
@Controller()
export class AppController {
private readonly logger = new Logger('AppController');
constructor(
private eventTriggerComponent: EventTriggerComponent,
private componentRegistry: ComponentRegistry,
private flowExecutorService: FlowExecutorService,
private templateCacheService: TemplateCacheService
) {}
@Get()
@Render('index')
async root(@Req() req: Request) {
return { message: 'steam engine = chart + document + logger // FBP' };
}
/**
* svelte app generated in:
* ./src/public/chart/*
*/
@Get('flows')
@Render('flows/index')
async flowsIndex(
@Req() req: Request
) {
const flows = await this.flowExecutorService.getFlows();
return {
message: 'flows - steam engine // FBP',
flows
};
}
@Get('flow/:flowId')
@Render('flow/index')
async flowComponents(
@Param('flowId') flowId: string,
@Req() req: Request
) {
const flow = await this.flowExecutorService.getFlow(flowId);
const components = flow.components.map(c => ({
componentId: c.componentId,
componentRef: c.componentRef
}));
return {
message: 'flow - steam engine // FBP',
flowId,
components
};
}
@Get('document/:flowId/:componentId')
@Render('document/view')
async documentView(
@Param('flowId') flowId: string,
@Param('componentId') componentId: string,
@Req() req: Request
) {
const flow = await this.flowExecutorService.getFlow(flowId);
const components = flow.components.map(c => ({
componentId: c.componentId,
componentRef: c.componentRef
}));
let connections = []
flow.connections.forEach((connection: Connection) => {
connections.push({
fromFlow: connection.fromFlow,
fromComponent: connection.fromComponent,
fromEvent: connection.fromEvent,
toFlow: connection.toFlow,
toComponent: connection.toComponent,
toEvent: connection.toEvent,
})
})
return {
selected: {
flowId,
componentId
},
components,
message: `${flowId}.${componentId} - document - steam engine // FBP`,
connections
};
}
@Get('documentComponent/:flowId/:componentId/:swimlaneId')
@Render('document/component')
async documentComponent(
@Param('flowId') flowId: string,
@Param('componentId') componentId: string,
@Param('swimlaneId') swimlaneId: string,
) {
const component = this.componentRegistry.getComponent(flowId, componentId);
if (component) {
return {
component,
swimlaneId
};
}
return {
component: null,
swimlaneId
};
}
@Get('documentConnections/:flowId/:componentId/:portId/:swimlaneId')
@Render('document/connections')
async documentConnections(
@Param('flowId') flowId: string,
@Param('componentId') componentId: string,
@Param('portId') portId: string,
@Param('swimlaneId') swimlaneId: string,
) {
const params = { flowId, componentId, portId };
const component = this.componentRegistry.getComponent(flowId, componentId);
if (component) {
let port: Port = await component.findPort(portId);
let connections: Connection[] = await component.findConnections(port);
connections.forEach((connection) => {
if (port.direction === 'input') {
connection.next = connection.connectedFrom;
} else {
connection.next = connection.connectedTo;
}
});
if (port) {
if (port.dataMethod === 'publish') {
return {
...params,
port,
connections,
swimlaneId
};
} else if (port.dataMethod === 'display') {
let displayHtmxId = `${flowId}.${componentId}.${port.eventId}`;
const cacheKey = `${flowId}.${componentId}.${port.eventId}`;
const cachedTemplate = this.templateCacheService.getTemplate(cacheKey);
return {
...params,
port,
displayHtmxId,
swimlaneId,
templateContent: cachedTemplate || 'Template not found'
};
}
}
}
return {
...params,
port: null,
swimlaneId
};
}
@Get('logger')
@Render('logger/index')
async loggerIndex(@Req() req: Request) {
return { message: 'logger - steam engine // FBP' };
}
@Post('trigger-event/:flowComponentEvent')
async triggerEvent(
@Param('flowComponentEvent') flowComponentEvent: string,
@Body() data: any,
@Res() res: Response
) {
const fceArray = flowComponentEvent.split('.');
const flowId = fceArray[0];
const componentId = fceArray[1];
const eventId = fceArray[2];
this.logger.log(`[trigger-event] [${flowId}] [${componentId}] [${eventId}]`);
data._flowId = flowId;
data._componentId = componentId;
data._eventId = eventId;
await this.eventTriggerComponent.handleEvent('triggerEvent', data);
res.sendStatus(200);
}
@Get('template/:flowId/:componentId/:templateId')
async getTemplate(
@Param('flowId') flowId: string,
@Param('componentId') componentId: string,
@Param('templateId') templateId: string,
@Res() res: Response
) {
const cacheKey = `${flowId}.${componentId}.${templateId}`;
const cachedTemplate = this.templateCacheService.getTemplate(cacheKey);
if (cachedTemplate) {
res.send(cachedTemplate);
} else {
res.status(404).send('Template not found');
}
}
}
</FILE>
<FILE path="/home/travis/Projects/flow-based-programming/src/modules/app.module.ts">
import { ComponentRegistry } from '../services/component-registry.service';