Repository navigation
Expand file tree
/
Copy pathmarkdown-language-preprocessor.js
More file actions
68 lines (57 loc) · 2.42 KB
/
Copy pathmarkdown-language-preprocessor.js
File metadata and controls
68 lines (57 loc) · 2.42 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
(function (root, factory) {
const api = factory();
if (typeof module === 'object' && module.exports) {
module.exports = api;
}
root.WorkshopMarkdown = api;
}(typeof globalThis !== 'undefined' ? globalThis : this, function () {
'use strict';
function directiveError(lineNumber, message) {
return new Error(`Language directive error on line ${lineNumber}: ${message}`);
}
function preprocessLanguageDirectives(markdown, languageId, getLanguage) {
if (typeof markdown !== 'string') {
throw new TypeError('Markdown must be a string.');
}
if (typeof getLanguage !== 'function' || !getLanguage(languageId)) {
throw new Error(`A valid workshop language is required to render this lesson: "${languageId ?? ''}".`);
}
const output = [];
let activeLanguageId = null;
const lines = markdown.split(/\r?\n/);
lines.forEach((line, index) => {
const lineNumber = index + 1;
const languageMatch = line.match(/^:::language\s+(\S+)\s*$/);
const closingMatch = /^:::\s*$/.test(line);
const directiveLike = line.startsWith(':::');
if (languageMatch) {
if (activeLanguageId !== null) {
throw directiveError(lineNumber, 'language blocks cannot be nested.');
}
if (!getLanguage(languageMatch[1])) {
throw directiveError(lineNumber, `unknown language "${languageMatch[1]}".`);
}
activeLanguageId = languageMatch[1];
return;
}
if (closingMatch) {
if (activeLanguageId === null) {
throw directiveError(lineNumber, 'closing directive has no open language block.');
}
activeLanguageId = null;
return;
}
if (directiveLike) {
throw directiveError(lineNumber, 'expected :::language <id> or :::.');
}
if (activeLanguageId === null || activeLanguageId === languageId) {
output.push(line);
}
});
if (activeLanguageId !== null) {
throw directiveError(lines.length, `language block for "${activeLanguageId}" is not closed.`);
}
return output.join('\n');
}
return Object.freeze({ preprocessLanguageDirectives });
}));