-
Notifications
You must be signed in to change notification settings - Fork 0
/
bundle.js
1154 lines (1043 loc) · 40.5 KB
/
bundle.js
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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.blockPage = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
const encode = require("./src/encode")
const decode = require("./src/decode")
const action = require("./src/actions")
const graph = require("./src/graph")
module.exports = {
encode : encode,
decode : decode,
action : action,
graph : graph
}
},{"./src/actions":2,"./src/decode":4,"./src/encode":5,"./src/graph":6}],2:[function(require,module,exports){
// code to perform actions on a document object and maintain its validity
/**
* valid actions
* get blank document [done]
* add a new block in a document [done]
* relate one block with another
* edit block : modify text, modify edges [done]
* delete block [done]
* validate documentObject
* search query :graph
* text search
*/
const graph = require("./graph.js");
const datatype = require("./datatype.js")
const getBlankDocObject = () => {
let docObject = {
valid: true,
blocks: [],
data: {},
graphs: {},
errors: [],
warnings: [],
metadata: {},
extra: {},
};
docObject.graphs.deps = graph.createGraph({
isSimple: true,
hasLoops: false,
hasDirectedEdges: true,
title: "Invocation block dependency graph",
});
docObject.graphs.knowledge = graph.createGraph({
hasLoops: false,
isSimple: true,
hasDirectedEdges: true,
title: "Knowledge graph",
});
return docObject
};
const removeSpace = (text) => {
// converts all spaces in between words in a string with dash
let noSpaceText = text.trim().replaceAll(/ +/g, "-");
noSpaceText = noSpaceText.toLowerCase();
return noSpaceText;
};
const randomInteger = (min = 0, max = 100) => {
return Math.floor(Math.random() * (max - min + 1) + min);
};
const replaceNewlinesAtEnd = (inputString)=>{
const regex = /\n+$/;
return inputString.replace(regex, '\n');
}
//// actions on the doc object
// these methods will have a common naming convention : doAction(doc, ...additional params), modifies the doc, returns the doc
const doAddError = (doc,errorData={"message":"",block:""})=>{
doc.valid = false;
doc.errors.push(errorData)
return doc
}
const doAddWarning = (doc,warningData={"message":"",block:""})=>{
doc.warnings.push(warningData)
return doc
}
const getBlankAnnotationObject = (type)=>{
return {
raw: "", // the raw unprocessed string
text: "", // text extracted after sanitizing brackets and annotations
blockId: "", // block id of the block in which this annotation exists TODO see if this even required as a common key
// processed: false, // indicates whether the annotation is processed or not
type: type, // the type of annotation
}
}
/**
* how to define an annotation
* each annotation has __ methods
*
* the extract method describes how to extract this annotation from a raw piece of text
* it must return {error:boolean, message:" if there is some error", annotation (array of the annotation objs , a modified version of the blank ann obj, array because there can be multiple same annotations in the text )}
*
*/
const annotations = {
declaration: {
usage: `To declare a new block, .
Format of the block :
.[block name] Block title
Block content
<new line>
`,
extract: (text) => {
const reg = /^\.\[([\+]?)([\w\s\-]+?)([,]*?)([\w\s\-]+?)\]/gm;
const parts = text.match(reg);
if (parts) {
// there should be only a single deceleration annotation
// TODO add a check if multiple dec exists in a single block
let ann = getBlankAnnotationObject("declaration")
ann["raw"] = parts[0]
const theString = parts[0].replace(".[", "").replace("]", "").trim();
ann.text = theString;
let part1 = theString.split(",");
ann.blockId = removeSpace(part1[0]);
return { error: false, message :"", annotations: [ann]};
} else {
return { error: false, message :"No declaration annotations", annotations: []};
}
},
},
append: {
usage : `To append content to an already existing block
Format :
+[block name] Title doesn't matter
More content that will be appended
<new line>`,
extract: (text) => {
const reg = /^\+\[([\+]?)([\w\s\-]+?)\]/gm;
const parts = text.match(reg);
if (parts) {
let ann = getBlankAnnotationObject("append")
ann["raw"] = parts[0]
const theString = parts[0].replace("+[", "").replace("]", "").trim();
ann.text = theString;
ann.blockId = removeSpace(theString);
return { error: false, message :"", annotations:[ann]};
} else {
return { error: false, message :"No append annotations", annotations: []};
}
},
},
invocation: {
usage : `To get include the content of one block to another block where this annotation is specified
Format :
....block content....
>[block id 1]
......block content....
>[block id 2]
`,
extract: (text) => {
const reg = /\>\[([\w\s\-]+?)([\.]*)([\w\s\-]*)([\.]*)([\w\s\-]*)\]/gm;
const parts = text.match(reg);
if (parts) {
let anns = [];
parts.map((part) => {
let ann = getBlankAnnotationObject("invocation")
ann.raw = part
const theString = part.replace(">[", "").replace("]", "").trim();
ann.text = theString;
ann.blockId = theString
// TODO added check : this can only be a valid block id
anns.push(ann);
});
return { error: false, message :"", annotations:anns};
} else {
return { error: false, message :"No invocation annotations", annotations: []};
}
},
},
edge: {
usage: `To relate one block to another in the document object's knowledge graph
Format:
...content of block-1....
~[label 1,block-2]
~[label 2,block-3]
... content of block-1....
`,
extract: (text) => {
const reg = /\~\[([\w\s\-\,\.\*]+?)\]/gm;
const parts = text.match(reg);
if (parts) {
let anns = [];
parts.map((part) => {
let ann = getBlankAnnotationObject("edge")
ann.raw = part
ann["v1"] = "*"
ann["v2"] = "*"
ann["label"] = ""
const theString = part.replace("~[", "").replace("]", "").trim();
ann.text = theString;
let part1 = theString.split(",");
if (part1.length == 2) {
ann.v2 = removeSpace(part1[1]);
ann.label = removeSpace(part1[0]);
} else if (part1.length == 3) {
ann.v1 = removeSpace(part1[0]);
ann.v2 = removeSpace(part1[2]);
ann.label = part1[1];
} else {
// TODO fix this (decide later) ... either do this be setting error : true or keep it as it is
throw new Error(
`Invalid edge annotation : ${part}. Format : or or (* for current block id)`
);
}
anns.push(ann);
})
return { error: false, message :"", annotations:anns};
} else {
return { error: false, message :"No edge annotations", annotations: []};
}
},
},
action: {
usage:`
To specify actions (kind of like a function call)
Format :
...block 1 content....
/[todo:this and that]
/[reply, to = some thing, subject = haha]
..block 1 content....
`,
extract: (text) => {
const reg = /\/\[([\s\w\:\,\=\%\.\_\-\/\>\<]+?)\]/gm;
const parts = text.match(reg);
const parseActionArguments = (argumentText) => {
let result = { action: "", arguments: { text: "", d: "0" } };
const parts = argumentText.split(":");
result.action = parts[0].trim();
if (parts.length > 1) {
let argParts = parts[1].split(",");
if (argParts.length > 0) {
result.arguments["text"] = argParts[0].trim();
argParts.shift();
argParts.map((argu) => {
let ar = argu.split("=");
result.arguments[ar[0].trim()] = ar[1].trim();
});
}
}
return result;
};
if (parts) {
let anns = [];
parts.map((part) => {
let ann = getBlankAnnotationObject("action")
ann["action"]=""
ann["arguments"]= {}
ann.raw = part
const theString = part.replace("/[", "").replace("]", "").trim();
ann.text = theString;
let part1 = parseActionArguments(theString);
ann = { ...ann, ...part1 };
anns.push(ann);
});
return { error: false, message :"", annotations:anns};
} else {
return { error: false, message :"No edge annotations", annotations: []};
}
},
}
}
const extractAllAnnotations = (rawBlock) => {
let annotationList = []; // store all the annotations found in the raw text
let annCount = {}; // to store a count of each of annotation type found in the raw text. this make processing of annotations easier
const allAnnotations = Object.keys(annotations);
allAnnotations.map((ann) => {
let anns = annotations[ann].extract(rawBlock);
// TODO modify to check the error key in the object returns
// console.log(anns)
annCount[ann] = anns["annotations"].length;
annotationList = [...annotationList, ...anns["annotations"]];
})
return { stats: annCount, annotations: annotationList };
}
const getBlankBlockObject = () => {
let newBlockData = {
blockId: "",
title:"",
text: "", // this is the text after annotations are processed. this will not include the
source: { raw: [], first: "", titleExists:false, idExists:false},
dataType: "default",
value: {},
annotations: [],
process: [],
};
// some annotations, after processing will be removed from the text of the block. this is stored in the `text` key of the object
return newBlockData
}
const doAddNewBlock = (docObject,blockText)=>{
// step 1 : extract all annotations from the block
blockText = blockText.replace(/^\n/, '')
let ann = extractAllAnnotations(blockText)
// step 2 : generate a new block object
newBlockData = getBlankBlockObject()
// step 3 : process all annotations one by one starting with declaration
let blockData; // this is the actual block data obj
// check if both declaration and append annotations exists
if(ann.stats.declaration > 0 && ann.stats.append > 0 ){
docObject = doAddError(docObject,{
text: `Annotation error`,
details: " A single block cannot have both declaration and append annotation ",
blockText
})
return docObject;
}
// processing declaration :
// 4 possible cases : (1)no dec, but append :not processed here (2) no dec , no append :create a block with random id (3) both dec and append : already taken care of above
if (ann.stats.declaration == 1) {
let dec = ann.annotations.find((itm) => {return itm.type == "declaration";});
if (docObject.data[dec.blockId]) {
throw new Error(`Re-declaration of ${dec.blockId} is invalid. Use append instead`);
}
// get the title
let lines = blockText.split('\n');
let blockTitle = lines.shift().replace(dec.raw, "");
let noBlockTitle = false
if (blockTitle.trim().length==0){
blockTitle = `Block ${dec.blockId}`
noBlockTitle = true
}
const newTextWithoutTitle = lines.join('\n');
let newText = newTextWithoutTitle
blockData = {
...newBlockData,
text: newText,
blockId: dec.blockId,
title: blockTitle,
// data type should be processed at the end of processing all annotations
source: { raw: [blockText], first: newText, titleExists:!noBlockTitle, idExists:true}, // this has the raw text, unprocessed further while processing annotations
annotations: ann.annotations,
process: ["declaration initialized"],
};
docObject.blocks.push(dec.blockId);
docObject.data[dec.blockId] = blockData;
} else if (ann.stats.append == 0) {
// define a new block
let randomBlockName = "block-"+randomInteger(1000, 9999);
blockData = {
...newBlockData,
blockId: randomBlockName,
text: blockText,
title:"Untitled",
source: { raw: [blockText], first: blockText, titleExists:false, idExists:false},
annotations: ann.annotations,
process: ["declaration initialized with random block id"],
};
docObject.blocks.push(randomBlockName);
docObject.data[randomBlockName] = blockData;
}
// add a new node for this new block in the dependency graph
try {
docObject.graphs.deps = graph.addVertex(docObject.graphs.deps, {id: blockData.blockId})
} catch (error) {
// console.error(error);
}
// append annotation
if (ann.stats.append == 1) {
let act = ann.annotations.find((itm) => {return itm.type == "append";});
let blockFound = docObject.blocks.indexOf(act.blockId) > -1;
if (blockFound) {
// update the block object
blockData = docObject.data[act.blockId];
let newText = blockText.replace(act.raw, ""); // the first line in the append cannot have anything else including a title
blockData.text = replaceNewlinesAtEnd(blockData.text) + newText;
blockData.source.first = replaceNewlinesAtEnd(blockData.source.first) + newText;
blockData.source.raw.push(blockText);
blockData.annotations = [
...blockData.annotations,
...ann.annotations,
];
blockData.process.push("Append annotation processed");
} else {
throw new Error(
`the append annotation on block ${act.blockId} is not valid at this block does not exist.`
);
}
}
// invocation annotation : here we are just adding the blocks that need to be replaced in the dependency graph
if (ann.stats.invocation > 0) {
let allInv = ann.annotations.filter((itm) => {return itm.type == "invocation";});
allInv.map((inv) => {
if (inv.blockId == blockData.blockId) {throw new Error(`Invalid invocation : ${inv.raw}. You cannot invoke the same block.`);}
try {
docObject.graphs.deps = graph.addVertex(docObject.graphs.deps, {id: inv.blockId});
} catch (error) {
// nothing to worry about. if adding a vertex in a dep graph fails, it probably means it already exists in the dep graph when it was declared
//console.error(error)
}
// adding an edge from the current block to the invocated block. this indicates that the current block is dependent on invocated block
docObject.graphs.deps = graph.addEdge(docObject.graphs.deps, {v1: blockData.blockId,v2: inv.blockId,})
docObject.data[blockData.blockId].process.push(`invocation ${inv.raw} initialized in dep graph`)
});
}
// edge annotations
const allEdges = ann.annotations.filter((itm) => {return itm.type == "edge"})
allEdges.map((ed) => {
let v1 = ed.v1 != "*" ? ed.v1 : blockData.blockId;
let v2 = ed.v2 != "*" ? ed.v2 : blockData.blockId;
if (v1 == v2) {throw new Error(`Invalid edge annotation ${ed.raw}.Cannot relate a node to itself`)}
try {
// add the current node v1 in the knowledge graph
docObject.graphs.knowledge = graph.addVertex(docObject.graphs.knowledge,{ id: v1 })
} catch (er) {
//console.error(er)
}
try {
docObject.graphs.knowledge = graph.addVertex( docObject.graphs.knowledge,{ id: v2 })
} catch (er) {
// console.error(er);
}
// now add an edge between v1 --> v2
docObject.graphs.knowledge = graph.addEdge(docObject.graphs.knowledge, { v1: v1, v2: v2, label: ed.label, temp:{addedByBlock:blockData.blockId}});
// replace the invocation text in the main text
let newText = docObject["data"][blockData.blockId].text.replace(ed.raw,"");
docObject["data"][blockData.blockId].text = newText;
docObject["data"][blockData.blockId].process.push(`edge-annotation: ${ed.text} processed`);
})
// check node dependencies
if(docObject.graphs.deps.edges.length>0){
// there are some edges in the dependency graph, we check if they are consistent i.e all the vertices between the edges exists. if they do, the dep graph can be processed otherwise not
missingBlocks = []
docObject.graphs.deps.edges.map(edge=>{
if(!docObject.data[edge.v1]){
missingBlocks.push(edge.v1)
}
if(!docObject.data[edge.v2]){
missingBlocks.push(edge.v2)
}
})
if(missingBlocks.length>0){
// cannot be processed
docObject = doAddError(docObject,{
text: `Invocation annotations can not be processed. Missing blocks : ${missingBlocks}`,
})
return docObject;
}else{
// all invocation block can be processed
// generate the order of processing of the blocks
try {
let order = graph.TopologicalSort(docObject.graphs.deps);
docObject.extra.blockOrder = order.vertexInOrder;
docObject.graphs.dfsTree = order.dfsTree;
docObject.graphs.tsTree = order.tsTree;
} catch (error) {
console.error(error)
docObject = doAddError(docObject,{
text: `${error.message}`,
details: "Invalid dependencies in the document",
})
return docObject;
}
// process the blocks in the order
try {
docObject.extra.blockOrder.map((block) => {
const blockId = block.vertexId;
if (!docObject.data[blockId]) {
throw new Error(`invocation error : the block "${blockId}" does not exists in the doc`)
}
let blockContent = docObject.data[blockId];
// find all invocation annotations for the block
let invAnn = docObject.data[blockId].annotations.filter((itm) => {return itm["type"] == "invocation"})
// process them
invAnn.map((inv) => {
let mainText = blockContent.text;
let targetText = docObject.data[inv.blockId].text;
// TODO include the spaces in paddings
mainText = mainText.replaceAll(inv.raw, targetText);
blockContent.text = mainText;
blockContent.process.push(`invocation ${inv.raw} processed`);
});
// let dt = { ...dataType };
// let dtu = { ...dataTypeUtils };
// let dataValue = dt[blockContent.dataType](blockContent, dtu);
// blockContent.value = dataValue;
// blockContent.process.push("datatype processed");
})
} catch (error) {
console.error(error)
docObject = doAddError(docObject,{
text: `${error.message}`,
details: "Some error while processing invocations",
})
return docObject;
}
}
}
// process actions annotations
// TODO fix issue when append invocation are used. all actions are being replaced again.
let actAnn = docObject.data[blockData.blockId].annotations.filter((itm) => {return itm.type == "action"})
let blockContent = docObject.data[blockData.blockId];
actAnn.map((act) => {
let mainText = blockContent.text;
blockContent.text = mainText.replace(act.raw, "");
blockContent.process.push(`Action annotation ${act.raw} replaced`);
});
// process the data type
// TODO
dataParsed = datatype.parseData(blockContent.text)
//console.log(blockContent)
//console.log(dataParsed)
blockContent.value = dataParsed
return docObject
}
const doDeleteBlock = (doc,blockId) => {
// changes to be made in : data , dep graph (all edges to and from ), knowledge graph (all edges to and from), blocks array
// TODO check if block exists
doc.graphs.deps = graph.deleteVertex(doc.graphs.deps,blockId)
doc.graphs.knowledge = graph.deleteVertex(doc.graphs.knowledge,blockId)
let bIndex = doc.blocks.indexOf(blockId);
doc.blocks.splice(bIndex, 1);
delete doc.data[blockId] // todo : more is required : first check if all annotations realted to this node are deleted as well because gragps can be defined in other blocks as well
return doc
}
const doEditBlock = (doc,blockId,changes)=>{
// we can only change the title and text
// TODO check if block exists
let blockIdR = removeSpace(blockId)
let block = {...doc.data[blockIdR]}
let oldData = { title : block.title, text : block.source.first}
// now check what needs to be changed
let newData = {
... oldData,
... changes
}
let newBlock = `.[${blockId}] ${newData.title} \n ${newData.text}`
// delete the block , preserving the edges to be added later on if required
doc.graphs.deps = graph.deleteVertex(doc.graphs.deps,blockId) // check this as well : i guess this is fine because a new dep graph is generated anyways on new node insert
updatedKg = graph.deleteVertex1(doc.graphs.knowledge,blockId)
// although the same block is added again, the knowledge graph is inconsistent as all edges related to this block were delete when this node removed from the graph
// the knowledge graph has to be updated
// add back all the edges that were not generated from the current block
doc.graphs.knowledge = updatedKg["graphData"]
doc.graphs.knowledge = graph.addVertex(doc.graphs.knowledge,{"id":blockId})
edgeToAddBack = updatedKg.edgeList.filter(itm=>{ return itm.temp.addedByBlock != blockId}) // bacuse they were not added by this block
edgeToAddBack.map(itm=>{ doc.graphs.knowledge = graph.addEdge(doc.graphs.knowledge,itm) })
let bIndex = doc.blocks.indexOf(blockId);
doc.blocks.splice(bIndex, 1);
delete doc.data[blockId]
doc = doAddNewBlock(doc,newBlock)
return doc
}
const doDeleteKGEdge = (doc,fromBlockId,toBlockId)=>{
// todo add validations
let edgeObj = {...doc.graphs.knowledge.edges.find(itm=>{ return itm.v1 == fromBlockId && itm.v2 == toBlockId })}
if(edgeObj){
blockIdToEdit = edgeObj.temp.addedByBlock
let blockContent = doc.data[blockIdToEdit]
// console.log(blockContent)
let v1F = fromBlockId == blockIdToEdit ? "*" : fromBlockId
let v2F = toBlockId == blockIdToEdit ? "*" : toBlockId
annotationIndex = blockContent.annotations.findIndex(itm=>{return (itm["type"] == "edge" && itm["v1"]== v1F ) && itm["v2"]==v2F })
rawAnnotationText = blockContent.annotations[annotationIndex].raw
blockContent.source.first = blockContent.source.first.replace(rawAnnotationText,"")
// remove from the annotation array
blockContent.annotations.splice(annotationIndex,1)
blockContent.process.push(`Edge ${rawAnnotationText} removed`)
// remove edge from the know graph
doc.graphs.knowledge = graph.deleteEdge(doc.graphs.knowledge,fromBlockId,toBlockId)
return doc
}
return doc
}
module.exports = {
getBlankDocObject,
doAddError,
doAddWarning,
doAddNewBlock,
doDeleteBlock,
doEditBlock,
doDeleteKGEdge
}
},{"./datatype.js":3,"./graph.js":6}],3:[function(require,module,exports){
const extractLines = (inputString)=>{
const regex = /^- [^:]+ : [^\n]+/gm;
// const regex = /^- [^:]+ [^.\n]* : [^\n]+/gm;
const matches = inputString.match(regex);
if (matches) {
return matches;
} else {
return [];
}
}
const parseData = (text)=>{
//console.log(text)
let lines = extractLines(text)
//console.log(lines)
let obj = {}
lines.map(line=>{
let parts = line.split(":")
let first = parts.shift()
first = first.replace("-","").replace(".","").trim()
let rest = parts.join("")
obj[first] = rest.trim()
})
return obj
}
// not in use :
const parseData1 = (text)=>{
let status = {valid:true,error:""}
const regex = /^\t*-\s/g;
let lines = text.split("\n")
let list = []
let currentIndex = 0
for (let index = 0; index < lines.length; index++) {
const line = lines[index];
// console.log(line)
const match = line.match(regex);
console.log(match)
if(match){
// find out the level of indent
}else{
status.valid = false
status.error = `Invalid list item at line ${index+1}`
break;
}
}
if(status.valid){
status['list'] = list
}
return status
}
module.exports = { parseData}
},{}],4:[function(require,module,exports){
// code to decode a document object to a text file
const act = require("./actions")
const decode = (doc,options={})=>{
// TODO check if the doc is valid
text = ""
doc.blocks.map(blockId=>{
let blockData = doc.data[blockId]
dId = blockData.source.idExists? `.[${blockId}]` : ""
dTitle = blockData.source.titleExists? `${blockData.title}` : ""
let block = `${dId}${dTitle}\n${blockData.source.first}\n\n`
text += block
})
return text.replace(/\s*$/, '')
}
module.exports = decode
},{"./actions":2}],5:[function(require,module,exports){
// code to encode a text file to document object
const act = require('./actions.js')
const encode = (document, options = {}) => {
// step 1 : convert doc to blocks
let blocks = document.split("\n\n");
// step 2: initialize blank doc object
let docObject = act.getBlankDocObject()
// step 3 : first pass through all the docs
try {
blocks.map((block, blockIndex) => {
if (block.trim() == "") {
docObject = act.doAddWarning(docObject,{
text: `Blank block at position ${blockIndex + 1}`,
blockIndex: blockIndex,
})
}
docObject = act.doAddNewBlock(docObject,block)
})
} catch (error) {
console.error(error)
docObject = act.doAddError(docObject,{
text: `${error.message}`,
details: "Error occurred during processing blocks ",
})
return docObject;
}
return docObject;
};
module.exports = encode;
},{"./actions.js":2}],6:[function(require,module,exports){
/***
the Graph program. Version 1.2.2 .
Full source code is available at https://github.com/shubhvjain/graphs
Copyright (C) 2022 Shubh
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>
***/
const createGraph = (options = {}) => {
const initialMetadata = {
title: options.title || "Graph " ,
hasLoops: options.hasLoops || false,
hasEdgeWeights: options.hasLoops || false,
hasDirectedEdges: options.hasDirectedEdges || false,
isSimple: options.isSimple || true
}
const initialOptions = {
defaultNewEdgeLabel: options.defaultNewEdgeLabel || "" ,
defaultNewVertexLabel:options.defaultNewVertexLabel || "",
defaultNewVertexWeight:options.defaultNewVertexWeight || "",
defaultNewEdgeWeight:options.defaultNewEdgeWeight || "",
addBlankVertex: options.addBlankVertex|| true
}
const theGraph = {
vertices: {},
edges: [],
metadata: initialMetadata,
options: initialOptions
}
return theGraph
}
const addVertex = (graphData,options) =>{
if(!options.id){
if(!graphData.options.addBlankVertex){
throw new Error ("No vertex id provided")
}else{
options.id = Math.floor(Math.random() * (50000) +1)
}
}
if(graphData.vertices[options.id]){
throw new Error("Vertex with same id already exists in the graph.")
}
graphData.vertices[options.id] = {
label: options.label || options.id ,
weight: 'weight' in options ? options.weight : graphData.options.defaultNewVertexWeight,
data: options.data,
temp: {...options.temp}
}
return graphData
}
const deleteVertex = (graphData, vertexId) => {
// options = {id}
if (!vertexId) {
throw new Error("No vertex id provided");
}
if (graphData.vertices[vertexId]) {
// will remove the vertex if it exists but will do nothing if it does not
// throw new Error("Vertex with this id does not exists in the graph.")
// gather all edges and delete them
const edge1Search = graphData.edges.filter((edge) => edge.v1 == vertexId);
for (const edge1 of edge1Search) {
graphData = deleteSpecificEdge(graphData, edge1.v1, edge1.v2);
}
const edge2Search = graphData.edges.filter((edge) => edge.v2 == vertexId);
for (const edge2 of edge2Search) {
graphData = deleteSpecificEdge(graphData, edge2.v1, edge2.v2);
}
// remove the vertex
delete graphData.vertices[vertexId];
return graphData;
} else {
return graphData;
}
};
const deleteVertex1 = (graphData, vertexId) => {
// options = {id}
if (!vertexId) {
throw new Error("No vertex id provided");
}
if (graphData.vertices[vertexId]) {
// will remove the vertex if it exists but will do nothing if it does not
// throw new Error("Vertex with this id does not exists in the graph.")
// gather all edges and delete them
let edgeList = []
const edge1Search = graphData.edges.filter((edge) => edge.v1 == vertexId);
for (const edge1 of edge1Search) {
edgeList.push(edge1)
graphData = deleteSpecificEdge(graphData, edge1.v1, edge1.v2);
}
const edge2Search = graphData.edges.filter((edge) => edge.v2 == vertexId);
for (const edge2 of edge2Search) {
edgeList.push(edge2)
graphData = deleteSpecificEdge(graphData, edge2.v1, edge2.v2);
}
// remove the vertex
delete graphData.vertices[vertexId];
return {"graphData":{...graphData},edgeList};
} else {
return {"graphData":{...graphData},edgeList:[]};
}
};
const addEdge = (graphData,options)=>{
if(!options.v1){throw new Error("Vertex 1 not provided")}
if(!options.v2){throw new Error("Vertex 2 not provided")}
if(!graphData.vertices[options.v1]){throw new Error(`Vertex 1 (${options.v1}) does not exists in the graph`)}
if(!graphData.vertices[options.v2]){throw new Error(`Vertex 2 (${options.v2}) does not exists in the graph`)}
const node1node2Search = graphData.edges.find(edge=>{return edge.v1 == options.v1 && edge.v2 == options.v2})
const node2node1Search = graphData.edges.find(edge=>{return edge.v1 == options.v2 && edge.v2 == options.v1})
if(graphData.metadata.isSimple){
if(node1node2Search || node2node1Search ){ throw new Error(`Edge ${options.v1}--${options.v2} already exists in the simple graph`)}
}
let newEdge = {
v1: options.v1,
v2: options.v2,
weight:options.weight|| graphData.options.defaultNewEdgeWeight,
label:options.label || graphData.options.defaultNewEdgeLabel,
temp: {...options.temp}
}
graphData.edges.push(newEdge)
return graphData
}
const deleteSpecificEdge = (graphData,v1,v2) => {
// removes an edge from v1 to v2 (only, not the other way round)
const edgeSearch = graphData.edges.findIndex(edge=>edge.v1 == v1 && edge.v2 == v2 )
if(edgeSearch !== -1){graphData.edges.splice(edgeSearch,1)}
return graphData
}
const deleteEdge = (graphData,fromVertex,toVertex) => {
graphData = deleteSpecificEdge(graphData,fromVertex,toVertex)
graphData = deleteSpecificEdge(graphData,toVertex,fromVertex)
return graphData
}
const getVertexNeighbours = (graphData,vertexId)=>{
if(!vertexId){throw new Error("No Vertex Id not provided")}
if(!graphData.vertices[vertexId]){throw new Error("Vertex not found in the graph")}
const node1Search = graphData.edges.filter(edge=>edge.v1 == vertexId)
const node2Search = graphData.edges.filter(edge=>edge.v2 == vertexId)
let neighbours = { in:[], out:[], all:[]}
node1Search.map(edge2=>{
if(neighbours.all.indexOf(edge2.v2)==-1){
neighbours.all.push(edge2.v2)
neighbours.out.push(edge2.v2)
}
})
node2Search.map(edge1=>{
if(neighbours.all.indexOf(edge1.v1)==-1){
neighbours.all.push(edge1.v1)
neighbours.in.push(edge1.v1)
}
})
if(graphData.metadata.hasDirectedEdges){
return neighbours.out
}else{
return neighbours.all
}
}
const getVertexDegree = (graphData,vertexId)=>{
const neighbours = getVertexNeighbours(graphData,vertexId)
return neighbours.length
}
const getVertexKeyMap = (graphData,options={vertexProperties:[],initialObjectValue:{}})=>{
let keyMap = {}
const allKeys = Object.keys(graphData.vertices)
vertexProps = {
'degree':(vertexId)=>{
return getVertexDegree(graphData,vertexId)
}
}
allKeys.map(ky=>{
keyMap[ky] = {...options.initialObjectValue}
options.vertexProperties.map(prop=>{
keyMap[ky][prop] = vertexProps[prop](ky)
})
})
return keyMap
}
const printEdges = (graphData)=>{
graphData.edges.map(edge=>{
console.log(` ${edge.v1} --- ${edge.v2} `)
})
}
// const fs = require("fs/promises");
const generateGraphPreview = async (graphs,options)=>{
// const saveSomethingInSomefile = async(fileContent,filePath) =>{
// await fs.writeFile(filePath, fileContent);
// }
const generateHTMLBodyForGraphs = (inputGraphs) =>{
let graphHtml = ""
inputGraphs.map((graph,index)=>{
let vertexInVisFormat = []
const vertex = Object.keys(graph.vertices)
vertex.map((v,inx)=>{
let label = `${options.showVertexCreatedOrder?"("+inx+") ":""}${graph['vertices'][v]['label']|| v} `
vertexInVisFormat.push( { id:v , label: label } )
})
let edgesInVisFormat = []
graph.edges.map(e=>{
let newEdge = { from : e.v1, to: e.v2, color: e.temp['color'] }
if(e.label){newEdge['label'] = e['label']}
edgesInVisFormat.push(newEdge)
})
let visOptions = {
"nodes":{"shape":"box"}
}
if(graph.metadata.hasDirectedEdges){visOptions['edges'] = { arrows: 'to'}}
const dataForViz = {nodes : vertexInVisFormat,edges: edgesInVisFormat,options: visOptions}
graphHtml += `
<h2> #${index+1}. ${graph.metadata.title}</h2>
<div class="graph" id="graph${index}"></div>
<details><summary>GraphData</summary><pre>${JSON.stringify(graph,null,2)}</pre></details>
<script>
let dataForViz${index} = ${JSON.stringify(dataForViz)}
const container${index} = document.getElementById('graph${index}')
const data${index} = {
nodes: new vis.DataSet(dataForViz${index}.nodes),
edges: new vis.DataSet(dataForViz${index}.edges)
}
let network${index} = new vis.Network(container${index}, data${index}, ${JSON.stringify(dataForViz['options'])});
</script>`
})
return graphHtml
}
const formats = {
'html':async ()=>{
if(!options.outputPath){throw new Error("Path for output file not provided") }
let graphHtml = generateHTMLBodyForGraphs(graphs)
const htmlTemplate = `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript" src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script><title>Graphs</title></head>
<body><style>.graph {width: 90%; height: 80vh; border: 1px solid #80808036;}</style>${graphHtml}</body></html>`
//await saveSomethingInSomefile(htmlTemplate,options.outputPath)
return {"message": "Saved",htmlTemplate: htmlTemplate}