forked from freeCodeCamp/curriculum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunpackedChallenge.js
293 lines (258 loc) · 8.76 KB
/
unpackedChallenge.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
/* eslint-disable no-inline-comments */
import fs from 'fs-extra';
import path from 'path';
import _ from 'lodash';
import { dasherize } from './utils';
const jsonLinePrefix = '//--JSON:';
const paragraphBreak = '<!--break-->';
class ChallengeFile {
constructor(dir, name, suffix) {
this.dir = dir;
this.name = name;
this.suffix = suffix;
}
filePath() {
return path.join(this.dir, this.name + this.suffix);
}
write(contents) {
if (_.isArray(contents)) {
contents = contents.join('\n');
}
fs.writeFile(this.filePath(), contents, err => {
if (err) {
throw err;
}
});
}
readChunks() {
// todo: make this work async
// todo: make sure it works with encodings
let data = fs.readFileSync(this.filePath());
let lines = data.toString().split(/(?:\r\n|\r|\n)/g);
let chunks = {};
let readingChunk = null;
let currentParagraph = [];
function removeLeadingEmptyLines(array) {
let emptyString = /^\s*$/;
while (array && Array.isArray(array) && emptyString.test(array[0])) {
array.shift();
}
}
lines.forEach(line => {
let chunkEnd = /(<!|\/\*)--end--/;
let chunkStart = /(<!|\/\*)--(\w+)--/;
line = line.toString();
function pushParagraph() {
removeLeadingEmptyLines(currentParagraph);
chunks[ readingChunk ].push(currentParagraph.join('\n'));
currentParagraph = [];
}
if (chunkEnd.test(line)) {
if (!readingChunk) {
throw 'Encountered --end-- without being in a chunk';
}
if (currentParagraph.length) {
pushParagraph();
} else {
removeLeadingEmptyLines(chunks[readingChunk]);
}
readingChunk = null;
} else if (readingChunk === 'description' && line === paragraphBreak) {
pushParagraph();
} else if (chunkStart.test(line)) {
let chunkName = line.match(chunkStart)[ 2 ];
if (readingChunk) {
throw `Encountered chunk ${chunkName} start `
+ `while already reading ${readingChunk}:
${line}`;
}
readingChunk = chunkName;
} else if (readingChunk) {
if (!chunks[ readingChunk ]) {
chunks[ readingChunk ] = [];
}
if (line.startsWith(jsonLinePrefix)) {
line = JSON.parse(line.slice(jsonLinePrefix.length));
chunks[ readingChunk ].push(line);
} else if (readingChunk === 'description') {
currentParagraph.push(line);
} else {
chunks[ readingChunk ].push(line);
}
}
});
// hack to deal with solutions field being an array of a single string
// instead of an array of lines like some other fields
if (chunks.solutions) {
chunks.solutions = [ chunks.solutions.join('\n') ];
}
Object.keys(chunks).forEach(key => {
removeLeadingEmptyLines(chunks[key]);
});
// console.log(JSON.stringify(chunks, null, 2));
return chunks;
}
}
export {ChallengeFile};
class UnpackedChallenge {
constructor(targetDir, challengeJson, index) {
this.targetDir = targetDir;
this.index = index;
// todo: merge challengeJson properties into this object?
this.challenge = challengeJson;
// extract names of block and superblock from path
// note: this is a bit redundant with the
// fileName,superBlock,superOrder fields
// that getChallenges() adds to the challenge JSON
let targetDirPath = path.parse(targetDir);
let parentDirPath = path.parse(targetDirPath.dir);
// superBlockName e.g. "03-front-end-libraries"
this.superBlockName = parentDirPath.base;
// challengeBlockName e.g. "bootstrap"
this.challengeBlockName = targetDirPath.base;
}
unpack() {
this.challengeFile()
.write(this.unpackedHTML());
}
challengeFile() {
return new ChallengeFile(this.targetDir, this.baseName(), '.html');
}
baseName() {
// eslint-disable-next-line no-nested-ternary
let prefix = ((this.index < 10) ? '00' : (this.index < 100) ? '0' : '')
+ this.index;
return `${prefix}-${dasherize(this.challenge.title)}-${this.challenge.id}`;
}
expandedDescription() {
let out = [];
this.challenge.description.forEach(part => {
if (_.isString(part)) {
out.push(part.toString());
out.push(paragraphBreak);
} else {
// Descriptions are weird since sometimes they're text and sometimes
// they're "steps" which appear one at a time with optional pix and
// captions and links, or "questions" with choices and explanations...
// For now we preserve non-string descriptions via JSON but this is
// not a great solution.
// It would be better if "steps" and "description" were separate fields.
// For the record, the (unnamed) fields in step are:
// 0: image URL
// 1: caption
// 2: text
// 3: link URL
out.push(jsonLinePrefix + JSON.stringify(part));
}
});
if (out[ out.length - 1 ] === paragraphBreak) {
out.pop();
}
return out;
}
expandedTests(tests) {
if (!tests) {
return [];
}
let out = [];
tests.forEach(test => {
if (_.isString(test)) {
out.push(test);
} else {
// todo: figure out what to do about these id-title challenge links
out.push(jsonLinePrefix + JSON.stringify(test));
}
});
return out;
}
unpackedHTML() {
let text = [];
text.push('<html>');
text.push('<head>');
text.push('<link rel="stylesheet" href="../../../unpacked.css">');
text.push('<!-- shim to enable running the tests in-browser -->');
text.push('<script src="../../unpacked-bundle.js"></script>');
text.push('</head>');
text.push('<body>');
text.push(`<h1>${this.challenge.title}</h1>`);
text.push(`<p>This is the <b>unpacked</b> version of
<code>${this.superBlockName}/${this.challengeBlockName}</code>
(challenge id <code>${this.challenge.id}</code>).</p>`);
text.push('<p>Open the JavaScript console to see test results.</p>');
text.push(`<p>Edit this HTML file (between <!-- marks only!)
and run <code>npm run repack</code>
to incorporate your changes into the challenge database.</p>`);
text.push('');
text.push('<h2>Description</h2>');
text.push('<div class="unpacked description">');
text.push('<!--description-->');
if (this.challenge.description.length) {
text.push(this.expandedDescription().join('\n'));
}
text.push('<!--end-->');
text.push('</div>');
text.push('');
text.push('<h2>Seed</h2>');
text.push('<!--seed--><pre class="unpacked">');
if (this.challenge.seed) {
text.push(text, this.challenge.seed.join('\n'));
}
text.push('<!--end-->');
text.push('</pre>');
// Q: What is the difference between 'seed' and 'challengeSeed' ?
text.push('');
text.push('<h2>Challenge Seed</h2>');
text.push('<!--challengeSeed--><pre class="unpacked">');
if (this.challenge.challengeSeed) {
text.push(text, this.challenge.challengeSeed.join('\n'));
}
text.push('<!--end-->');
text.push('</pre>');
text.push('');
text.push('<h2>Head</h2>');
text.push('<!--head--><script class="unpacked head">');
if (this.challenge.head) {
text.push(text, this.challenge.head.join('\n'));
}
text.push('</script><!--end-->');
text.push('');
text.push('<h2>Solution</h2>');
text.push(
'<!--solutions--><script class="unpacked solution" id="solution">'
);
// Note: none of the challenges have more than one solution
// todo: should we deal with multiple solutions or not?
if (this.challenge.solutions && this.challenge.solutions.length > 0) {
let solution = this.challenge.solutions[ 0 ];
text.push(solution);
}
text.push('</script><!--end-->');
text.push('');
text.push('<h2>Tail</h2>');
text.push('<!--tail--><script class="unpacked tail">');
if (this.challenge.tail) {
text.push(text, this.challenge.tail.join('\n'));
}
text.push('</script><!--end-->');
text.push('');
text.push('<h2>Tests</h2>');
text.push('<script class="unpacked tests">');
text.push(`test(\'${this.challenge.title} challenge tests\', ` +
'function(t) {');
text.push('let assert = addAssertsToTapTest(t);');
text.push('let code = document.getElementById(\'solution\').innerText;');
text.push('t.plan(' +
(this.challenge.tests ? this.challenge.tests.length : 0) +
');');
text.push('/*--tests--*/');
text.push(this.expandedTests(this.challenge.tests).join('\n'));
text.push('/*--end--*/');
text.push('});');
text.push('</script>');
text.push('');
text.push('</body>');
text.push('</html>');
return text;
}
}
export {UnpackedChallenge};