-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2184 lines (1975 loc) · 83.7 KB
/
server.js
File metadata and controls
2184 lines (1975 loc) · 83.7 KB
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
const http = require('http');
const fs = require('fs');
const path = require('path');
const { Lexer, marked } = require('marked');
const WebSocket = require('ws');
const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000;
const PUBLIC_DIR = path.join(__dirname, 'public');
const DATA_DIR = path.join(__dirname, 'data');
const EXAMPLES_DIR = path.join(DATA_DIR, 'examples');
const QUESTION_MD_PATH = path.join(DATA_DIR, 'question.md');
// Parse command line arguments for --edit, --copy-markdown, and --examples
let EDIT_MODE = false;
let EXAMPLES_MODE = false;
let EDIT_FILE_PATH = null;
let COPY_MARKDOWN_ENABLED = false;
const args = process.argv.slice(2);
for (let i = 0; i < args.length; i++) {
if (args[i] === '--copy-markdown') {
COPY_MARKDOWN_ENABLED = true;
continue;
}
if (args[i] === '--examples') {
EXAMPLES_MODE = true;
continue;
}
if (args[i] === '--edit' && i + 1 < args.length) {
EDIT_MODE = true;
let editPathArg = args[i + 1];
// Resolve path relative to current working directory if path is relative, otherwise use as-is
if (path.isAbsolute(editPathArg)) {
EDIT_FILE_PATH = editPathArg;
} else {
// Resolve relative paths from current working directory
EDIT_FILE_PATH = path.resolve(process.cwd(), editPathArg);
}
}
}
const MIME_TYPES = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.md': 'text/markdown; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.ico': 'image/x-icon',
'.txt': 'text/plain; charset=utf-8'
};
const MARKDOWN_RENDERER = new marked.Renderer();
MARKDOWN_RENDERER.table = function renderMarkdownTable(header, body) {
return `<div class="table-scroll"><table class="table">\n<thead>${header}</thead>\n<tbody>${body}</tbody>\n</table></div>`;
};
function isPathInside(child, parent) {
const relative = path.relative(parent, child);
return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
}
/** Basename only; safe characters for data/examples/*.md */
function isValidExampleBasename(name) {
if (typeof name !== 'string' || !name.trim()) return false;
const t = name.trim();
if (t !== path.basename(t)) return false;
return /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.md$/i.test(t);
}
function sendFile(res, filePath, status = 200) {
const ext = path.extname(filePath).toLowerCase();
const contentType = MIME_TYPES[ext] || 'application/octet-stream';
res.writeHead(status, {
'Content-Type': contentType,
// Disable aggressive caching during development
'Cache-Control': 'no-store'
});
const read = fs.createReadStream(filePath);
read.on('error', () => {
res.writeHead(500, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end('Internal Server Error');
});
read.pipe(res);
}
function respondJson(res, status, payload) {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(payload));
}
function parseSectionsFromTokens(tokens) {
const sections = new Map();
let current = null;
let buffer = [];
function flush() {
if (current !== null) sections.set(current, buffer.slice());
buffer = [];
}
for (const token of tokens) {
if (token.type === 'paragraph') {
const text = (token.text || '').trim();
const m = text.match(/^__([^_]+)__\s*$/);
const mWithContent = text.match(/^__([^_]+)__\s*\n([\s\S]*)$/);
if (m) {
flush();
current = m[1].trim();
continue;
}
if (mWithContent) {
flush();
current = mWithContent[1].trim();
const rest = mWithContent[2].trim();
if (rest) {
buffer.push({ type: 'paragraph', raw: rest, text: rest });
}
continue;
}
}
if (current !== null) buffer.push(token);
}
flush();
return sections;
}
/** @returns {string|null} */
function extractQuestionTypeFromMarkdown(markdownText) {
if (!markdownText || typeof markdownText !== 'string' || !markdownText.trim()) return null;
try {
const tokens = Lexer.lex(markdownText);
const sections = parseSectionsFromTokens(tokens);
const type = ((sections.get('Type') || []).map(t => t.raw || t.text).join('\n') || '').trim();
return type || null;
} catch (e) {
return null;
}
}
/**
* Preprocess markdown to escape \$ as literal dollar signs (not LaTeX).
* Replaces \$ with <span class="no-math">$</span> so KaTeX skips them.
*/
function escapeMathDollars(markdown) {
if (!markdown || typeof markdown !== 'string') return markdown;
return markdown.replace(/\\\$/g, '<span class="no-math">$</span>');
}
function renderMarkdown(markdown) {
if (!markdown || typeof markdown !== 'string') return '';
return marked.parse(escapeMathDollars(markdown), { renderer: MARKDOWN_RENDERER });
}
/**
* Parse __Content__ section tokens into { url } or { markdown } plus optional contentWidth, openInNewTab.
*/
function parseSideContentFromSectionTokens(sectionTokens) {
if (!sectionTokens || sectionTokens.length === 0) return null;
const contentText = sectionTokens.map(t => t.raw || t.text || '').join('\n').trim();
if (!contentText) return null;
const contentWidthMatch = contentText.match(/\[contentWidth:\s*([^\]]+)\]/i);
const contentWidth = contentWidthMatch ? contentWidthMatch[1].trim() : null;
const contentWithoutWidth = contentWidthMatch
? contentText.replace(/\s*\[contentWidth:\s*[^\]]+\]\s*/gi, '').trim()
: contentText;
if (/^https?:\/\//i.test(contentWithoutWidth)) {
const lines = contentWithoutWidth.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
const firstLine = lines[0] || '';
const openInNewTab = /\[openInNewTab\]/i.test(contentWithoutWidth);
const url = firstLine.replace(/\s+\[openInNewTab\]\s*$/i, '').trim();
const out = { url, openInNewTab: !!openInNewTab };
if (contentWidth) out.contentWidth = contentWidth;
return out;
}
const out = { markdown: contentWithoutWidth };
if (contentWidth) out.contentWidth = contentWidth;
return out;
}
function attachSideContent(activity, sections) {
const side = parseSideContentFromSectionTokens(sections.get('Content') || []);
if (side) activity.content = side;
return activity;
}
/**
* __Explain Your Answer__ body: first non-empty line must be true | yes | enabled;
* optional following lines (case preserved) = custom prompt shown instead of "Explain your answer".
* @returns {{ enabled: boolean, label: string | null }}
*/
function parseExplainYourAnswerSection(rawText) {
const raw = String(rawText || '').trim();
if (!raw) return { enabled: false, label: null };
const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
if (lines.length === 0) return { enabled: false, label: null };
const first = lines[0].toLowerCase();
const enabled = first === 'true' || first === 'yes' || first === 'enabled';
if (!enabled) return { enabled: false, label: null };
if (lines.length === 1) return { enabled: true, label: null };
const label = lines.slice(1).join('\n').trim();
return { enabled: true, label: label || null };
}
/** Client posts one result per question in order; label may be a custom name or legacy "Question N". */
function questionIndexFromOrderedResult(result, resultIndex, numQuestions) {
const n = numQuestions | 0;
if (typeof resultIndex === 'number' && resultIndex >= 0 && resultIndex < n) return resultIndex;
const m = /^Question\s+(\d+)\s*$/i.exec(String(result?.text || '').trim());
if (m) {
const i = parseInt(m[1], 10) - 1;
if (i >= 0 && i < n) return i;
}
return -1;
}
function readListItems(sectionTokens) {
const items = [];
for (const t of sectionTokens || []) {
if (t.type === 'list' && Array.isArray(t.items)) {
for (const li of t.items) {
const text = (li.text || '').trim();
if (text) items.push(text);
}
} else if (t.type === 'paragraph') {
// Support loose list formatting lines starting with - or *
const lines = (t.raw || t.text || '').split(/\r?\n/);
for (const line of lines) {
const m = line.match(/^\s*[-*]\s+(.*)$/);
if (m) items.push(m[1].trim());
}
}
}
return items;
}
function parseAnswersFromMarkdown(markdownText) {
const tokens = Lexer.lex(markdownText);
const sections = parseSectionsFromTokens(tokens);
const type = ((sections.get('Type') || []).map(t => t.raw || t.text).join('\n') || '').trim();
const responsesSection = sections.get('Responses') || [];
// Parse responses to extract selected answers
const responsesText = responsesSection.map(t => t.raw || t.text || '').join('\n');
const answers = {};
if (/^multiple choice$/i.test(type)) {
// Parse MCQ responses: "Selected Answer: D" or "Selected Answer: B, D"
// Also parse explanations if present: "Explanation: ..." (comes after Result line)
const explanations = {};
// First, parse explanations separately since they come after the Result line
// Use a more specific regex that matches each question block individually
// Split by question number pattern, then check each block for explanation
const questionBlocks = responsesText.split(/(?=\d+\.\s*\*\*[^*]+\*\*)/);
questionBlocks.forEach(block => {
const questionMatch = block.match(/^(\d+)\.\s*\*\*[^*]+\*\*/);
if (questionMatch) {
const questionNumber = parseInt(questionMatch[1], 10);
const explanationMatch = block.match(/Explanation:\s*([^\n]+)/);
if (explanationMatch) {
const questionIndex = questionNumber - 1; // Convert to 0-indexed
const explanationStr = explanationMatch[1].trim();
if (explanationStr) {
explanations[questionIndex] = explanationStr;
}
}
}
});
// Then parse selected answers
const responseRegex = /(\d+)\.\s*\*\*[^*]+\*\*[\s\S]*?Selected Answer:\s*([^\n]+)/g;
let match;
while ((match = responseRegex.exec(responsesText)) !== null) {
const questionIndex = parseInt(match[1], 10) - 1; // Convert to 0-indexed
const selectedAnswerStr = match[2].trim();
// Parse comma-separated answers and trim whitespace
const selectedAnswers = selectedAnswerStr
.split(',')
.map(s => s.trim())
.filter(Boolean);
if (selectedAnswers.length > 0 && selectedAnswers[0] !== 'No answer selected') {
answers[questionIndex] = selectedAnswers;
}
}
// Return both answers and explanations
return { answers, type, explanations };
} else if (/^fill in the blanks$/i.test(type)) {
// Parse FIB responses: "Selected Answer: [value]"
const responseRegex = /(\d+)\.\s*\*\*Blank (\d+)\*\*[\s\S]*?Selected Answer:\s*([^\n]+)/g;
let match;
while ((match = responseRegex.exec(responsesText)) !== null) {
const blankIndex = parseInt(match[2], 10) - 1; // Convert to 0-indexed
const selectedAnswer = match[3].trim();
if (selectedAnswer && selectedAnswer !== 'No answer selected') {
answers[blankIndex] = selectedAnswer;
}
}
} else if (/^matching$/i.test(type)) {
// Parse Matching responses: "Selected Answer: [value]"
const responseRegex = /(\d+)\.\s*\*\*[^*]+\*\*[\s\S]*?Selected Answer:\s*([^\n]+)/g;
let match;
while ((match = responseRegex.exec(responsesText)) !== null) {
const itemIndex = parseInt(match[1], 10) - 1; // Convert to 0-indexed
const selectedAnswer = match[2].trim();
if (selectedAnswer && selectedAnswer !== 'No answer selected') {
answers[itemIndex] = selectedAnswer;
}
}
} else if (/^text input$/i.test(type)) {
// Parse Text Input responses: "Selected Answer: [value]"
const responseRegex = /(\d+)\.\s*\*\*[^*]+\*\*[\s\S]*?Selected Answer:\s*([^\n]+)/g;
let match;
while ((match = responseRegex.exec(responsesText)) !== null) {
const questionIndex = parseInt(match[1], 10) - 1; // Convert to 0-indexed
const selectedAnswer = match[2].trim();
if (selectedAnswer && selectedAnswer !== 'No answer selected') {
answers[questionIndex] = selectedAnswer;
}
}
} else if (/^matrix$/i.test(type)) {
const explanations = {};
const questionBlocks = responsesText.split(/(?=\d+\.\s*\*\*[^*]+\*\*)/);
questionBlocks.forEach(block => {
const questionMatch = block.match(/^(\d+)\.\s*\*\*[^*]+\*\*/);
if (questionMatch) {
const questionNumber = parseInt(questionMatch[1], 10);
const explanationMatch = block.match(/Explanation:\s*([^\n]+)/);
if (explanationMatch) {
const questionIndex = questionNumber - 1;
const explanationStr = explanationMatch[1].trim();
if (explanationStr) {
explanations[questionIndex] = explanationStr;
}
}
}
});
const responseRegex = /(\d+)\.\s*\*\*[^*]+\*\*[\s\S]*?Selected Answer:\s*([^\n]+)/g;
let match;
while ((match = responseRegex.exec(responsesText)) !== null) {
const rowIndex = parseInt(match[1], 10) - 1;
const selectedAnswer = match[2].trim();
if (selectedAnswer && selectedAnswer !== 'No answer selected') {
answers[rowIndex] = selectedAnswer;
}
}
if (Object.keys(explanations).length > 0) {
return { answers, type, explanations };
}
}
return { answers, type };
}
function buildActivityFromMarkdown(markdownText) {
const tokens = Lexer.lex(markdownText);
const sections = parseSectionsFromTokens(tokens);
const type = ((sections.get('Type') || []).map(t => t.raw || t.text).join('\n') || '').trim();
const question = ((sections.get('Practice Question') || []).map(t => t.raw || t.text).join('\n') || '').trim();
if (/^fill in the blanks$/i.test(type)) {
const fibTokens = sections.get('Markdown With Blanks') || [];
const fibMarkdown = fibTokens.map(t => t.raw || t.text || '').join('\n').trim();
const suggested = readListItems(sections.get('Suggested Answers'));
// Split the content into prompt and fill-in-the-blanks content
const lines = fibMarkdown.split(/\r?\n/);
let promptLines = [];
let contentLines = [];
let foundBlockquote = false;
for (const line of lines) {
if (/^\s*>/.test(line)) {
foundBlockquote = true;
// Remove the '> ' marker and add to content
contentLines.push(line.replace(/^\s*>\s?/, ''));
} else if (foundBlockquote) {
// After finding blockquote, everything goes to content
contentLines.push(line);
} else {
// Before blockquote, everything goes to prompt (unless it's empty)
if (line.trim()) {
promptLines.push(line);
}
}
}
const prompt = promptLines.join('\n').trim();
const content = contentLines.join('\n').trim();
const blanks = [];
let idx = 0;
// Replace blank tokens with actual HTML spans that will be preserved by the markdown renderer
const contentWithBlankSpans = content.replace(/\[\[blank:([^\]]+)\]\]/gi, (_, token) => {
const answer = String(token).trim();
const currentIndex = idx++;
blanks.push({ index: currentIndex, answer });
return `<span class="blank" data-blank="${currentIndex}" aria-label="blank ${currentIndex + 1}" tabindex="0"></span>`;
});
// Build choices preserving duplicates from Suggested Answers, and ensure
// at least as many copies of each correct answer as there are blanks.
const suggestedTrimmed = suggested.map(s => s.trim()).filter(Boolean);
const requiredCounts = new Map();
blanks.forEach(b => {
const k = b.answer;
requiredCounts.set(k, (requiredCounts.get(k) || 0) + 1);
});
const suggestedCounts = new Map();
suggestedTrimmed.forEach(s => {
suggestedCounts.set(s, (suggestedCounts.get(s) || 0) + 1);
});
const choices = suggestedTrimmed.slice();
requiredCounts.forEach((req, k) => {
const have = suggestedCounts.get(k) || 0;
for (let i = have; i < req; i++) choices.push(k);
});
// simple shuffle
let s = (markdownText.length || 1337) % 2147483647 || 1337;
function rand() { s = (s * 48271) % 2147483647; return s / 2147483647; }
for (let i = choices.length - 1; i > 0; i--) {
const j = Math.floor(rand() * (i + 1));
[choices[i], choices[j]] = [choices[j], choices[i]];
}
// Render markdown to HTML for prompt and content
const promptHtml = prompt ? renderMarkdown(prompt) : '';
const contentHtml = renderMarkdown(contentWithBlankSpans);
// Parse QuestionStyle (e.g. "boxed", "bordered") from __QuestionStyle__ section
const questionStyleTokens = sections.get('QuestionStyle') || [];
const questionStyle = ((questionStyleTokens.map(t => t.raw || t.text).join('\n') || '').trim()).toLowerCase() || null;
const fibHeadingTokens = sections.get('Heading') || [];
const fibHeadingMd = fibHeadingTokens.map(t => t.raw || t.text).join('\n').trim();
let fibHeading = null;
if (fibHeadingMd) {
fibHeading = { markdown: fibHeadingMd, html: renderMarkdown(fibHeadingMd) };
}
return attachSideContent(
{
type,
question,
fib: {
raw: fibMarkdown,
prompt,
promptHtml,
content,
htmlWithPlaceholders: contentHtml,
blanks,
choices,
questionStyle: questionStyle || undefined,
...(fibHeading ? { heading: fibHeading } : {})
}
},
sections
);
}
if (/^multiple choice$/i.test(type)) {
// Parse MCQ with support for multiple questions
const questions = [];
const allTokens = Lexer.lex(markdownText);
let currentQuestion = null;
let currentSection = null;
let questionBuffer = [];
let answerBuffer = [];
let explainAnswerBuffer = [];
let questionOptionsBuffer = [];
let questionNameBuffer = [];
let headingBuffer = [];
// Deterministic shuffle using text as seed
function seededShuffle(array, seed) {
// Simple seeded random number generator
let s = seed;
function seededRandom() {
s = (s * 9301 + 49297) % 233280;
return s / 233280;
}
// Fisher-Yates shuffle with seeded random
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(seededRandom() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
// Generate seed from question text and all option texts
function generateSeed(questionText, options) {
const allText = questionText + options.map(opt => opt.text + opt.label).join('');
let hash = 0;
for (let i = 0; i < allText.length; i++) {
const char = allText.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
return Math.abs(hash);
}
function processQuestion() {
if (!currentQuestion || questionBuffer.length === 0) return;
// Parse options from question text
const questionText = questionBuffer.map(t => t.raw || t.text || '').join('\n').trim();
const options = [];
// Extract options (A., B., C., etc.)
const optionRegex = /^([A-Z])\.\s*(.+)$/gm;
let match;
const optionMap = new Map();
while ((match = optionRegex.exec(questionText)) !== null) {
const label = match[1];
const text = match[2].trim();
optionMap.set(label, text);
// Parse markdown to HTML for rendering (supports images, bold, etc.)
const textHtml = renderMarkdown(text);
options.push({
label: label,
text: text, // Keep raw text for backward compatibility
textHtml: textHtml, // Add HTML version for rendering
correct: false // Will be set from Suggested Answers
});
}
// Extract question text without options
const questionTextOnly = questionText.replace(/^[A-Z]\.\s*.+$/gm, '').trim();
// Store raw markdown text (for answer.md generation)
currentQuestion.text = questionTextOnly || questionText;
// Parse markdown to HTML for rendering (supports multiple paragraphs, blockquotes, etc.)
if (currentQuestion.text) {
currentQuestion.textHtml = renderMarkdown(currentQuestion.text);
} else {
currentQuestion.textHtml = '';
}
currentQuestion.options = options;
}
function processExplainAnswer() {
if (!currentQuestion) return;
const raw = explainAnswerBuffer.map(t => t.raw || t.text || '').join('\n').trim();
const { enabled, label } = parseExplainYourAnswerSection(raw);
currentQuestion.explainAnswer = enabled;
if (enabled && label) {
currentQuestion.explainAnswerLabel = label;
} else {
delete currentQuestion.explainAnswerLabel;
}
}
function processQuestionOptions() {
if (!currentQuestion) return;
// Parse question options section
const optionsText = questionOptionsBuffer.map(t => t.raw || t.text || '').join('\n').trim().toLowerCase();
// Check for shuffle option
if (optionsText.includes('shuffle=false') || optionsText.includes('don\'t shuffle') || optionsText.includes('dont shuffle') || optionsText === 'no shuffle') {
currentQuestion.shuffleOptions = false;
} else {
currentQuestion.shuffleOptions = true; // Default to shuffling
}
// Check for multi-select mode (any vs all)
// Default is 'all' - must select all correct answers
// 'any' means any correct answer is sufficient
if (optionsText.includes('any') || optionsText.includes('multi-select mode: any') || optionsText.includes('mode: any')) {
currentQuestion.multiSelectMode = 'any';
} else {
currentQuestion.multiSelectMode = 'all'; // Default
}
}
function processAnswers() {
if (!currentQuestion) return;
// Process explain answer first if buffer exists (even if no answers yet)
if (explainAnswerBuffer.length > 0) {
processExplainAnswer();
} else {
currentQuestion.explainAnswer = false;
delete currentQuestion.explainAnswerLabel;
}
// Process question options if buffer exists
if (questionOptionsBuffer.length > 0) {
processQuestionOptions();
} else {
currentQuestion.shuffleOptions = true; // Default to shuffling
currentQuestion.multiSelectMode = 'all'; // Default multi-select mode
}
// Process answers if buffer has content
if (answerBuffer.length > 0) {
const answerItems = readListItems(answerBuffer);
const correctAnswers = new Set();
answerItems.forEach(item => {
const trimmed = item.trim();
// Match patterns like "A", "A - Correct", "B - Correct", etc.
const match = trimmed.match(/^([A-Z])\s*(?:-?\s*(?:Correct)?)?$/i);
if (match) {
const label = match[1].toUpperCase();
if (trimmed.toLowerCase().includes('correct')) {
correctAnswers.add(label);
}
}
});
// Mark correct options
currentQuestion.options.forEach(opt => {
opt.correct = correctAnswers.has(opt.label);
});
// Determine if multi-select
currentQuestion.isMultiSelect = correctAnswers.size > 1;
}
// Shuffle options only if shuffleOptions is true (default behavior)
if (currentQuestion.shuffleOptions !== false) {
const seed = generateSeed(currentQuestion.text, currentQuestion.options);
currentQuestion.options = seededShuffle(currentQuestion.options, seed);
}
// Add to questions array
questions.push(currentQuestion);
}
// Parse tokens sequentially
for (const token of allTokens) {
if (token.type === 'paragraph') {
const text = (token.text || '').trim();
const m = text.match(/^__([^_]+)__\s*$/);
if (m) {
const sectionName = m[1].trim();
if (sectionName === 'Practice Question') {
// Process previous question/answers if any
if (currentQuestion) {
processAnswers();
}
// Start new question
const nameFromBuffer = questionNameBuffer.map(t => t.raw || t.text || '').join('\n').trim();
questionNameBuffer = [];
currentQuestion = {
id: questions.length,
name: nameFromBuffer,
text: '',
options: [],
isMultiSelect: false,
explainAnswer: false,
shuffleOptions: true,
multiSelectMode: 'all'
};
currentSection = 'question';
questionBuffer = [];
answerBuffer = [];
explainAnswerBuffer = [];
questionOptionsBuffer = [];
continue;
} else if (sectionName === 'Question Name' || sectionName === 'Question name') {
if (currentQuestion && (currentSection === 'answers' || currentSection === 'explain' || currentSection === 'questionOptions')) {
processAnswers();
currentQuestion = null;
}
currentSection = 'questionName';
questionNameBuffer = [];
continue;
} else if (sectionName === 'Suggested Answers') {
// Process current question text and question options if they exist
if (currentQuestion) {
processQuestion();
// Process question options if we were in that section
if (currentSection === 'questionOptions' && questionOptionsBuffer.length > 0) {
processQuestionOptions();
}
currentSection = 'answers';
answerBuffer = [];
}
continue;
} else if (sectionName === 'Question Options' || sectionName === 'Question options') {
// Switch to question options section - should come after question text, before Suggested Answers
if (currentQuestion && currentSection === 'question') {
processQuestion();
currentSection = 'questionOptions';
questionOptionsBuffer = [];
}
continue;
} else if (sectionName === 'Explain Your Answer' || sectionName === 'Explain your answer') {
// Switch to explain section - answers will be processed when we hit the next question or end
if (currentQuestion) {
// Process question options if we were in that section
if (currentSection === 'questionOptions' && questionOptionsBuffer.length > 0) {
processQuestionOptions();
}
if (currentSection === 'answers' || currentSection === 'questionOptions') {
currentSection = 'explain';
explainAnswerBuffer = [];
}
}
continue;
} else if (sectionName === 'Heading') {
currentSection = 'heading';
headingBuffer = [];
continue;
} else if (sectionName === 'Content') {
// Side content is read from the section map by attachSideContent; do not
// leave MCQ in 'explain' (etc.) or __Content__ tokens pollute explainAnswerBuffer.
currentSection = null;
continue;
} else if (sectionName === 'Type') {
// Skip type section
currentSection = null;
continue;
}
}
}
if (currentSection === 'heading') {
headingBuffer.push(token);
} else if (currentSection === 'questionName') {
questionNameBuffer.push(token);
} else if (currentSection === 'question' && currentQuestion) {
questionBuffer.push(token);
} else if (currentSection === 'questionOptions' && currentQuestion) {
questionOptionsBuffer.push(token);
} else if (currentSection === 'answers' && currentQuestion) {
answerBuffer.push(token);
} else if (currentSection === 'explain' && currentQuestion) {
explainAnswerBuffer.push(token);
}
}
// Process last question and answers
if (currentQuestion) {
processAnswers();
}
if (questions.length === 0) {
throw new Error('No MCQ questions found');
}
let heading = null;
if (headingBuffer.length > 0) {
const headingText = headingBuffer.map(t => t.raw || t.text || '').join('\n').trim();
if (headingText) {
heading = { markdown: headingText, html: renderMarkdown(headingText) };
}
}
return attachSideContent({ type, question: null, mcq: { questions, heading } }, sections);
}
if (/^matching$/i.test(type)) {
const matchingTokens = sections.get('Markdown With Blanks') || [];
const matchingMarkdown = matchingTokens.map(t => t.raw || t.text || '').join('\n').trim();
const suggested = readListItems(sections.get('Suggested Answers'));
// Split the content into prompt and matching items
const lines = matchingMarkdown.split(/\r?\n/);
let promptLines = [];
let itemLines = [];
let foundBlockquote = false;
for (const line of lines) {
if (/^\s*>/.test(line)) {
foundBlockquote = true;
// Remove the '> ' marker and add to items
itemLines.push(line.replace(/^\s*>\s?/, ''));
} else if (foundBlockquote) {
// After finding blockquote, everything goes to items
itemLines.push(line);
} else {
// Before blockquote, everything goes to prompt (unless it's empty)
if (line.trim()) {
promptLines.push(line);
}
}
}
const prompt = promptLines.join('\n').trim();
const items = [];
let idx = 0;
// Parse each blockquote line as a separate item
// Each line starting with '>' is a separate card
for (const line of lines) {
if (/^\s*>/.test(line)) {
const itemLine = line.replace(/^\s*>\s?/, '').trim();
const blankMatch = itemLine.match(/\[\[blank:([^\]]+)\]\]/i);
if (!blankMatch) continue;
const answer = String(blankMatch[1]).trim();
const textBeforeBlank = itemLine.replace(/\[\[blank:[^\]]+\]\]/gi, '').trim();
// Render text without blank to HTML
const textHtml = renderMarkdown(textBeforeBlank);
items.push({
index: idx++,
text: textBeforeBlank,
textHtml: textHtml,
answer: answer
});
}
}
// Build choices preserving duplicates from Suggested Answers, and ensure
// at least as many copies of each correct answer as there are blanks.
const suggestedTrimmed = suggested.map(s => s.trim()).filter(Boolean);
const requiredCounts = new Map();
items.forEach(item => {
const k = item.answer;
requiredCounts.set(k, (requiredCounts.get(k) || 0) + 1);
});
const suggestedCounts = new Map();
suggestedTrimmed.forEach(s => {
suggestedCounts.set(s, (suggestedCounts.get(s) || 0) + 1);
});
const choices = suggestedTrimmed.slice();
requiredCounts.forEach((req, k) => {
const have = suggestedCounts.get(k) || 0;
for (let i = have; i < req; i++) choices.push(k);
});
// Shuffle choices using deterministic shuffle
let s = (markdownText.length || 1337) % 2147483647 || 1337;
function rand() { s = (s * 48271) % 2147483647; return s / 2147483647; }
for (let i = choices.length - 1; i > 0; i--) {
const j = Math.floor(rand() * (i + 1));
[choices[i], choices[j]] = [choices[j], choices[i]];
}
// Render markdown to HTML for prompt
const promptHtml = prompt ? renderMarkdown(prompt) : '';
const matchingHeadingTokens = sections.get('Heading') || [];
const matchingHeadingMd = matchingHeadingTokens.map(t => t.raw || t.text).join('\n').trim();
let matchingHeading = null;
if (matchingHeadingMd) {
matchingHeading = { markdown: matchingHeadingMd, html: renderMarkdown(matchingHeadingMd) };
}
return attachSideContent({
type,
question: null,
matching: {
raw: matchingMarkdown,
prompt,
promptHtml,
items,
choices,
...(matchingHeading ? { heading: matchingHeading } : {})
}
}, sections);
}
if (/^text input$/i.test(type)) {
// Parse Text Input with support for multiple questions
const questions = [];
const allTokens = Lexer.lex(markdownText);
let currentQuestion = null;
let currentSection = null;
let questionBuffer = [];
let answerBuffer = [];
let headingBuffer = [];
let questionNameBuffer = [];
function processQuestion() {
if (!currentQuestion || questionBuffer.length === 0) return;
// Extract question text
const questionText = questionBuffer.map(t => t.raw || t.text || '').join('\n').trim();
currentQuestion.text = questionText;
// Parse markdown to HTML for rendering (supports LaTeX, images, bold, etc.)
if (currentQuestion.text) {
currentQuestion.textHtml = renderMarkdown(currentQuestion.text);
} else {
currentQuestion.textHtml = '';
}
}
function parseValidationOptions(answerText) {
// Parse validation options from answer text
// Format: "answer [kind: string|numeric|numeric-with-units] [options: key=value,key=value]"
// Examples:
// "Hello World [kind: string] [options: caseInsensitive=true,fuzzy=false]"
// "42.5 [kind: numeric] [options: threshold=0.01,precision=2]"
// "100 kg [kind: numeric-with-units] [options: threshold=0.1,precision=1,units=kg,g]"
const trimmedAnswer = answerText.trim();
const startsWithKind = trimmedAnswer.startsWith('[kind:');
let validationMatch;
if (startsWithKind) {
// Support empty correct-answer entries such as "[kind: validate-later]".
validationMatch = trimmedAnswer.match(/^\[kind:\s*([^\]]+)\](?:\s+\[options:\s*([^\]]+)\])?$/);
if (validationMatch) {
const kind = validationMatch[1] ? validationMatch[1].trim() : 'string';
const optionsText = validationMatch[2] ? validationMatch[2].trim() : '';
const options = {};
if (optionsText) {
const optionPairs = optionsText.split(',');
optionPairs.forEach(pair => {
const [key, value] = pair.split('=').map(s => s.trim());
if (key && value !== undefined) {
if (value === 'true') {
options[key] = true;
} else if (value === 'false') {
options[key] = false;
} else if (!isNaN(value)) {
options[key] = parseFloat(value);
} else {
options[key] = value;
}
}
});
}
if (kind === 'numeric-with-units' && typeof options.units === 'string') {
options.units = options.units.split(',').map(u => u.trim()).filter(Boolean);
}
return {
correctAnswer: '',
validation: {
kind,
options
}
};
}
} else {
validationMatch = trimmedAnswer.match(/^(.+?)(?:\s+\[kind:\s*([^\]]+)\])?(?:\s+\[options:\s*([^\]]+)\])?$/);
}
if (!validationMatch) {
return {
correctAnswer: trimmedAnswer,
validation: {}
};
}
const correctAnswer = validationMatch[1].trim();
const kind = validationMatch[2] ? validationMatch[2].trim() : 'string';
const optionsText = validationMatch[3] ? validationMatch[3].trim() : '';
// Parse options
const options = {};
if (optionsText) {
const optionPairs = optionsText.split(',');
optionPairs.forEach(pair => {
const [key, value] = pair.split('=').map(s => s.trim());
if (key && value !== undefined) {
// Convert string booleans and numbers
if (value === 'true') {
options[key] = true;
} else if (value === 'false') {
options[key] = false;
} else if (!isNaN(value)) {
options[key] = parseFloat(value);
} else {
options[key] = value;
}
}
});
}
// Parse units if present (comma-separated list)
if (kind === 'numeric-with-units' && options.units) {
if (typeof options.units === 'string') {
options.units = options.units.split(',').map(u => u.trim()).filter(Boolean);
}
}
return {
correctAnswer,
validation: {
kind,
options
}
};
}
function processAnswers() {
if (!currentQuestion || answerBuffer.length === 0) return;
const answerItems = readListItems(answerBuffer);
// For text-input, we expect a single correct answer per question
// But we support multiple answers in case of multiple correct answers
if (answerItems.length > 0) {