docgen-tool 3.2.2 → 3.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/docgen.js +51 -0
  2. package/dist/source/docgen.js +905 -0
  3. package/dist/source/example/contents.json +12 -0
  4. package/dist/source/example/files/images/logo.png +0 -0
  5. package/dist/source/example/index.txt +4 -0
  6. package/dist/source/example/parameters.json +37 -0
  7. package/dist/source/example/release-notes.txt +1 -0
  8. package/dist/source/optional/katex/fonts/KaTeX_AMS-Regular.woff +0 -0
  9. package/dist/source/optional/katex/fonts/KaTeX_Main-Bold.woff +0 -0
  10. package/dist/source/optional/katex/fonts/KaTeX_Main-Italic.woff +0 -0
  11. package/dist/source/optional/katex/fonts/KaTeX_Main-Regular.woff +0 -0
  12. package/dist/source/optional/katex/fonts/KaTeX_Math-BoldItalic.woff +0 -0
  13. package/dist/source/optional/katex/fonts/KaTeX_Math-Italic.woff +0 -0
  14. package/dist/source/optional/katex/fonts/KaTeX_Math-Regular.woff +0 -0
  15. package/dist/source/optional/katex/fonts/KaTeX_Size1-Regular.woff +0 -0
  16. package/dist/source/optional/katex/fonts/KaTeX_Size2-Regular.woff +0 -0
  17. package/dist/source/optional/katex/fonts/KaTeX_Size3-Regular.woff +0 -0
  18. package/dist/source/optional/katex/fonts/KaTeX_Size4-Regular.woff +0 -0
  19. package/dist/source/optional/katex/katex.min.css +1 -0
  20. package/dist/source/optional/katex/katex.min.js +6 -0
  21. package/dist/source/pdf-contents.xsl +71 -0
  22. package/dist/source/pdf-stylesheet.css +59 -0
  23. package/dist/source/require/docgen.css +136 -0
  24. package/dist/source/require/katexInjector.js +18 -0
  25. package/dist/source/require/print.css +26 -0
  26. package/dist/source/require/styles/fonts/DroidSansMono.woff +0 -0
  27. package/dist/source/require/styles/fonts/Montserrat-Italic.woff +0 -0
  28. package/dist/source/require/styles/fonts/Montserrat-Regular.woff +0 -0
  29. package/dist/source/require/styles/fonts/Montserrat-SemiBold.woff +0 -0
  30. package/dist/source/require/styles/fonts/Montserrat-SemiBoldItalic.woff +0 -0
  31. package/dist/source/require/styles/framework.css +949 -0
  32. package/dist/source/require/styles/framework.icons.js +79 -0
  33. package/dist/source/require/styles/framework.js +16 -0
  34. package/dist/source/require/styles/highlight.min.css +1 -0
  35. package/dist/source/require/styles/highlight.min.js +6 -0
  36. package/dist/source/templates/main.html +95 -0
  37. package/dist/source/templates/pdfCover.html +128 -0
  38. package/dist/source/templates/pdfFooter.html +59 -0
  39. package/dist/source/templates/pdfHeader.html +21 -0
  40. package/dist/source/templates/redirect.html +10 -0
  41. package/dist/source/templates/webCover.html +73 -0
  42. package/package.json +1 -1
@@ -0,0 +1,905 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var rsvp = require('rsvp');
4
+ var fs = require('fs-extra');
5
+ var path = require('path');
6
+ var cheerio = require('cheerio');
7
+ var markdown = require('markdown-it')('commonmark').enable('table');
8
+ var moment = require('moment');
9
+ var child_process_1 = require("child_process");
10
+ var schemaValidator = require('z-schema');
11
+ var chalk = require('chalk');
12
+ var spawnArgs = require('spawn-args');
13
+ var cliSpinner = require('cli-spinner').Spinner;
14
+ var imageSizeOf = require('image-size');
15
+ var package_json_1 = require("../package.json");
16
+ //Allow CommonMark links that use other protocols, such as file:///
17
+ //The markdown-it implementation is more restrictive than the CommonMark spec
18
+ //See https://github.com/markdown-it/markdown-it/issues/108
19
+ markdown.validateLink = function () {
20
+ return true;
21
+ };
22
+ /**
23
+ * DocGen class
24
+ */
25
+ function DocGen(process) {
26
+ var mainProcess = process;
27
+ var wkhtmltopdfVersion = 'wkhtmltopdf 0.12.6 (with patched qt)'; //output from wkhtmltopdf -V
28
+ var options;
29
+ var templates = {};
30
+ var meta = {};
31
+ var pages = {};
32
+ var sortedPages = {};
33
+ this.getVersion = function () {
34
+ return package_json_1.version;
35
+ };
36
+ this.setOptions = function (userOptions) {
37
+ options = userOptions;
38
+ //all user-specified paths must be normalized
39
+ if (options.input) {
40
+ options.input = path.normalize(options.input + '/');
41
+ }
42
+ if (options.output) {
43
+ options.output = path.normalize(options.output + '/');
44
+ }
45
+ //wkhtmltopdf path does not need a trailing slash
46
+ if (options.wkhtmltopdfPath && options.wkhtmltopdfPath !== '') {
47
+ options.wkhtmltopdfPath = path.normalize(options.wkhtmltopdfPath);
48
+ }
49
+ };
50
+ /*
51
+ copy the example source files (template) to any directory, when scaffold command is invoked
52
+ */
53
+ this.scaffold = function () {
54
+ console.log(chalk.green('Creating scaffold template directory'));
55
+ copyDirSync(__dirname + '/example', options.output);
56
+ };
57
+ this.run = function () {
58
+ console.log(chalk.green.bold('DocGen version ' + package_json_1.version));
59
+ //delete and recreate the output directory
60
+ remakeDirSync(options.output);
61
+ loadTemplates();
62
+ };
63
+ /*
64
+ read any file (async)
65
+ */
66
+ var readFile = function (path) {
67
+ return new rsvp.Promise(function (resolve, reject) {
68
+ fs.readFile(path, 'utf8', function (error, data) {
69
+ if (error) {
70
+ console.log(chalk.red('Error reading file: ' + path));
71
+ reject(error);
72
+ }
73
+ else {
74
+ data = data.replace(/^\uFEFF/, ''); //remove the BOM (byte-order-mark) from UTF-8 files, if present
75
+ resolve(data);
76
+ }
77
+ });
78
+ });
79
+ };
80
+ /*
81
+ write any file (async)
82
+ */
83
+ var writeFile = function (path, data) {
84
+ return new rsvp.Promise(function (resolve, reject) {
85
+ fs.writeFile(path, data, function (error) {
86
+ if (error) {
87
+ console.log(chalk.red('Error writing file: ' + path));
88
+ reject(error);
89
+ }
90
+ else {
91
+ resolve(true);
92
+ }
93
+ });
94
+ });
95
+ };
96
+ /*
97
+ copy any directory (sync)
98
+ */
99
+ var copyDirSync = function (source, destination) {
100
+ try {
101
+ fs.copySync(source, destination);
102
+ }
103
+ catch (error) {
104
+ console.log(chalk.red('Error copying directory: ' + source + ' to ' + destination));
105
+ if (options.verbose === true) {
106
+ console.log(chalk.red(error));
107
+ mainProcess.exit(1);
108
+ }
109
+ }
110
+ };
111
+ /*
112
+ remake a directory (sync) ... remove and then mkdir in one operation
113
+ */
114
+ var remakeDirSync = function (path) {
115
+ try {
116
+ fs.removeSync(path);
117
+ fs.mkdirpSync(path);
118
+ }
119
+ catch (error) {
120
+ console.log(chalk.red('Error recreating directory: ' + path));
121
+ if (options.verbose === true) {
122
+ console.log(chalk.red(error));
123
+ mainProcess.exit(1);
124
+ }
125
+ }
126
+ };
127
+ /*
128
+ remove any directory (sync)
129
+ */
130
+ var removeDirSync = function (path) {
131
+ try {
132
+ fs.removeSync(path);
133
+ }
134
+ catch (error) {
135
+ console.log(chalk.red('Error removing directory: ' + path));
136
+ if (options.verbose === true) {
137
+ console.log(chalk.red(error));
138
+ mainProcess.exit(1);
139
+ }
140
+ }
141
+ };
142
+ /*
143
+ load all HTML template files
144
+ */
145
+ var loadTemplates = function () {
146
+ console.log(chalk.green('Loading templates'));
147
+ var files = {
148
+ main: readFile(__dirname + '/templates/main.html'),
149
+ redirect: readFile(__dirname + '/templates/redirect.html'),
150
+ webCover: readFile(__dirname + '/templates/webCover.html'),
151
+ pdfCover: readFile(__dirname + '/templates/pdfCover.html'),
152
+ pdfHeader: readFile(__dirname + '/templates/pdfHeader.html'),
153
+ pdfFooter: readFile(__dirname + '/templates/pdfFooter.html'),
154
+ };
155
+ rsvp
156
+ .hash(files)
157
+ .then(function (files) {
158
+ for (var key in files) {
159
+ if (files.hasOwnProperty(key)) {
160
+ var file = files[key];
161
+ var dom = cheerio.load(file);
162
+ templates[key] = dom;
163
+ }
164
+ }
165
+ loadMeta();
166
+ })
167
+ .catch(function (error) {
168
+ console.log(chalk.red('Error loading templates'));
169
+ if (options.verbose === true) {
170
+ console.log(chalk.red(error));
171
+ }
172
+ mainProcess.exit(1);
173
+ });
174
+ };
175
+ /*
176
+ JSON schema validation
177
+ */
178
+ var schemas = {
179
+ parameters: {
180
+ title: 'DocGen Parameters Schema',
181
+ type: 'object',
182
+ required: [
183
+ 'title',
184
+ 'name',
185
+ 'version',
186
+ 'date',
187
+ 'organization',
188
+ 'author',
189
+ 'owner',
190
+ 'contributors',
191
+ 'website',
192
+ 'module',
193
+ 'id',
194
+ 'summary',
195
+ 'marking',
196
+ 'legalese',
197
+ ],
198
+ properties: {
199
+ title: { type: 'string' },
200
+ name: { type: 'string' },
201
+ version: { type: 'string' },
202
+ date: { type: 'string' },
203
+ organization: {
204
+ type: 'object',
205
+ required: ['name', 'url'],
206
+ properties: {
207
+ name: { type: 'string' },
208
+ url: { type: 'string' },
209
+ },
210
+ },
211
+ author: {
212
+ type: 'object',
213
+ required: ['name', 'url'],
214
+ properties: {
215
+ name: { type: 'string' },
216
+ url: { type: 'string' },
217
+ },
218
+ },
219
+ owner: {
220
+ type: 'object',
221
+ required: ['name', 'url'],
222
+ properties: {
223
+ name: { type: 'string' },
224
+ url: { type: 'string' },
225
+ },
226
+ },
227
+ contributors: {
228
+ type: 'array',
229
+ items: {
230
+ oneOf: [
231
+ {
232
+ type: 'object',
233
+ required: ['name', 'url'],
234
+ properties: {
235
+ name: { type: 'string' },
236
+ url: { type: 'string' },
237
+ },
238
+ },
239
+ ],
240
+ },
241
+ },
242
+ website: {
243
+ type: 'object',
244
+ required: ['name', 'url'],
245
+ properties: {
246
+ name: { type: 'string' },
247
+ url: { type: 'string' },
248
+ },
249
+ },
250
+ backlink: {
251
+ type: 'object',
252
+ required: ['name', 'url'],
253
+ properties: {
254
+ name: { type: 'string' },
255
+ url: { type: 'string' },
256
+ },
257
+ },
258
+ module: { type: 'string' },
259
+ id: { type: 'string' },
260
+ summary: { type: 'string' },
261
+ marking: { type: 'string' },
262
+ legalese: { type: 'string' },
263
+ },
264
+ },
265
+ contents: {
266
+ title: 'DocGen Table of Contents Schema',
267
+ type: 'array',
268
+ items: {
269
+ oneOf: [
270
+ {
271
+ type: 'object',
272
+ required: ['heading', 'column', 'pages'],
273
+ properties: {
274
+ name: { type: 'string' },
275
+ column: { type: 'integer', minimum: 1, maximum: 4 },
276
+ pages: {
277
+ type: 'array',
278
+ items: {
279
+ oneOf: [
280
+ {
281
+ type: 'object',
282
+ required: ['title', 'source'],
283
+ properties: {
284
+ title: { type: 'string' },
285
+ source: { type: 'string' },
286
+ html: { type: 'boolean' },
287
+ },
288
+ },
289
+ ],
290
+ },
291
+ },
292
+ },
293
+ },
294
+ ],
295
+ },
296
+ },
297
+ };
298
+ var validateJSON = function (key, data) {
299
+ var schema = schemas[key];
300
+ var validator = new schemaValidator();
301
+ var valid = validator.validate(data, schema);
302
+ if (!valid) {
303
+ console.log(chalk.red('Error parsing required file: ' +
304
+ key +
305
+ '.json (failed schema validation)'));
306
+ if (options.verbose === true) {
307
+ console.log(chalk.red(validator.getLastError()));
308
+ }
309
+ }
310
+ return valid;
311
+ };
312
+ /*
313
+ load all metadata files (JSON)
314
+ */
315
+ var loadMeta = function () {
316
+ console.log(chalk.green('Loading required JSON metadata files'));
317
+ var files = {
318
+ parameters: readFile(options.input + '/parameters.json'),
319
+ contents: readFile(options.input + '/contents.json'),
320
+ };
321
+ rsvp
322
+ .hash(files)
323
+ .then(function (files) {
324
+ for (var key in files) {
325
+ if (files.hasOwnProperty(key)) {
326
+ //ignore prototype
327
+ try {
328
+ var file = JSON.parse(files[key]);
329
+ if (validateJSON(key, file)) {
330
+ meta[key] = file;
331
+ }
332
+ else {
333
+ mainProcess.exit(1);
334
+ }
335
+ }
336
+ catch (error) {
337
+ console.log(chalk.red('Error parsing required file: ' +
338
+ key +
339
+ '.json (invalid JSON)'));
340
+ if (options.verbose === true) {
341
+ console.log(chalk.red(error));
342
+ }
343
+ mainProcess.exit(1);
344
+ }
345
+ }
346
+ }
347
+ //add the release notes to the contents list
348
+ var extra = {
349
+ heading: 'Extra',
350
+ column: 5,
351
+ pages: [{ title: 'Release notes', source: 'release-notes.txt' }],
352
+ };
353
+ meta.contents.push(extra);
354
+ loadMarkdown();
355
+ })
356
+ .catch(function (error) {
357
+ console.log(chalk.red('Error loading required JSON metadata files'));
358
+ if (options.verbose === true) {
359
+ console.log(chalk.red(error));
360
+ }
361
+ mainProcess.exit(1);
362
+ });
363
+ };
364
+ /*
365
+ load all markdown files (source)
366
+ */
367
+ var loadMarkdown = function () {
368
+ console.log(chalk.green('Loading source files'));
369
+ var keys = [];
370
+ var files = [];
371
+ meta.contents.forEach(function (section) {
372
+ section.pages.forEach(function (page) {
373
+ keys.push(page);
374
+ files.push(options.input + '/' + page.source);
375
+ });
376
+ });
377
+ //add the release notes page
378
+ keys.push('ownership');
379
+ files.push(options.input + '/release-notes.txt');
380
+ rsvp
381
+ .all(files.map(readFile))
382
+ .then(function (files) {
383
+ files.forEach(function (page, index) {
384
+ try {
385
+ var key = keys[index];
386
+ if (key.html === true) {
387
+ //allow raw HTML input pages
388
+ pages[key.source] = page;
389
+ }
390
+ else {
391
+ //otherwise parse input from Markdown into HTML
392
+ var html = markdown.render(page);
393
+ pages[key.source] = html;
394
+ }
395
+ }
396
+ catch (error) {
397
+ console.log(chalk.red('Error parsing Markdown file: ' + file.source));
398
+ if (options.verbose === true) {
399
+ console.log(chalk.red(error));
400
+ }
401
+ mainProcess.exit(1);
402
+ }
403
+ });
404
+ processContent();
405
+ })
406
+ .catch(function (error) {
407
+ console.log(error);
408
+ console.log(chalk.red('Error loading source files'));
409
+ if (options.verbose === true) {
410
+ console.log(chalk.red(error));
411
+ }
412
+ mainProcess.exit(1);
413
+ });
414
+ };
415
+ var sortPages = function () {
416
+ //sort the contents by heading
417
+ var headings = { 1: [], 2: [], 3: [], 4: [], 5: [] };
418
+ meta.contents.forEach(function (section) {
419
+ if (headings.hasOwnProperty(section.column)) {
420
+ headings[section.column].push(section);
421
+ }
422
+ });
423
+ sortedPages = headings;
424
+ };
425
+ /*
426
+ build the HTML for the table of contents
427
+ */
428
+ var webToc = function () {
429
+ sortPages();
430
+ var pdfName = meta.parameters.name.toLowerCase() + '.pdf';
431
+ var $ = templates.main;
432
+ var html = [], i = -1;
433
+ html[++i] = '<div><table class="unstyled"><tr>';
434
+ //build the contents HTML
435
+ for (var key in sortedPages) {
436
+ if (sortedPages.hasOwnProperty(key)) {
437
+ if (key != 5) {
438
+ //skip the extra column
439
+ html[++i] = '<td class="dg-tocGroup">';
440
+ sortedPages[key].forEach(function (section) {
441
+ html[++i] =
442
+ '<ul><li class="dg-tocHeading">' + section.heading + '</li>';
443
+ section.pages.forEach(function (page) {
444
+ var name = page.source.substr(0, page.source.lastIndexOf('.'));
445
+ var path = name + '.html';
446
+ html[++i] =
447
+ '<li><a href="' + path + '">' + page.title + '</a></li>';
448
+ });
449
+ html[++i] = '</li></ul>';
450
+ });
451
+ html[++i] = '</td>';
452
+ }
453
+ }
454
+ }
455
+ //fixed-width column at end
456
+ html[++i] = '<td class="dg-tocGroup" id="dg-tocFixedColumn"><ul>';
457
+ html[++i] =
458
+ '<li><span class="w-icon dg-tocIcon" data-name="person_group" title="archive"></span><a href="ownership.html">Ownership</a></li>';
459
+ html[++i] =
460
+ '<li><span class="w-icon dg-tocIcon" data-name="refresh" title="archive"></span><a href="release-notes.html">Release Notes</a></li>';
461
+ html[++i] = '</ul><div>';
462
+ if (options.pdf) {
463
+ html[++i] =
464
+ '<button class="whiteInverted" onclick="window.location=\'' +
465
+ pdfName +
466
+ '\';">';
467
+ html[++i] = '<span>PDF</span>';
468
+ html[++i] = '</button>';
469
+ }
470
+ html[++i] = '</div></td>';
471
+ html[++i] = '</tr></table></div>';
472
+ $('#dg-toc').html(html.join(''));
473
+ templates.main = $;
474
+ };
475
+ /*
476
+ insert the parameters into all templates
477
+ */
478
+ var insertParameters = function () {
479
+ //------------------------------------------------------------------------------------------------------
480
+ //logo dimensions
481
+ var hasLogo = false;
482
+ var logoWidth = 0;
483
+ var logoHeight = 0;
484
+ var logoPath;
485
+ try {
486
+ logoPath = 'files/images/logo.svg';
487
+ var logo = imageSizeOf("".concat(options.input, "/").concat(logoPath));
488
+ logoWidth = logo.width;
489
+ logoHeight = logo.height;
490
+ hasLogo = true;
491
+ }
492
+ catch (error) {
493
+ //do nothing. If logo file cannot be read, logo is simply not shown
494
+ }
495
+ if (!hasLogo) {
496
+ //PNG fallback
497
+ try {
498
+ logoPath = 'files/images/logo.png';
499
+ var logo = imageSizeOf("".concat(options.input, "/").concat(logoPath));
500
+ logoWidth = logo.width;
501
+ logoHeight = logo.height;
502
+ hasLogo = true;
503
+ }
504
+ catch (error) {
505
+ //do nothing. If logo file cannot be read, logo is simply not shown
506
+ }
507
+ }
508
+ //------------------------------------------------------------------------------------------------------
509
+ //the homepage is the first link in the first heading
510
+ var homelink = meta.contents[0].pages[0];
511
+ homelink =
512
+ homelink.source.substr(0, homelink.source.lastIndexOf('.')) + '.html';
513
+ var date = moment().format('DD/MM/YYYY');
514
+ var time = moment().format('HH:mm:ss');
515
+ var year = moment().format('YYYY');
516
+ var attribution = 'Created by DocGen ' + package_json_1.version + ' on ' + date + ' at ' + time + '.';
517
+ var releaseVersion = meta.parameters.version;
518
+ if (options.setVersion !== false) {
519
+ releaseVersion = options.setVersion;
520
+ }
521
+ var releaseDate = meta.parameters.date;
522
+ if (options.setReleaseDate !== false) {
523
+ releaseDate = options.setReleaseDate;
524
+ }
525
+ var author = '';
526
+ if (meta.parameters.author.url !== '') {
527
+ author +=
528
+ '<a href="' +
529
+ meta.parameters.author.url +
530
+ '">' +
531
+ meta.parameters.author.name +
532
+ '</a>';
533
+ }
534
+ else {
535
+ author += meta.parameters.author.name;
536
+ }
537
+ var owner = '';
538
+ if (meta.parameters.owner.url !== '') {
539
+ owner +=
540
+ '<a href="' +
541
+ meta.parameters.owner.url +
542
+ '">' +
543
+ meta.parameters.owner.name +
544
+ '</a>';
545
+ }
546
+ else {
547
+ owner += meta.parameters.owner.name;
548
+ }
549
+ var organization = '';
550
+ if (meta.parameters.organization.url !== '') {
551
+ organization +=
552
+ '<a href="' +
553
+ meta.parameters.organization.url +
554
+ '">' +
555
+ meta.parameters.organization.name +
556
+ '</a>';
557
+ }
558
+ else {
559
+ organization += meta.parameters.organization.name;
560
+ }
561
+ var website = '';
562
+ if (meta.parameters.website.url !== '') {
563
+ website +=
564
+ '<a href="' +
565
+ meta.parameters.website.url +
566
+ '">' +
567
+ meta.parameters.website.name +
568
+ '</a>';
569
+ }
570
+ else {
571
+ website += meta.parameters.website.name;
572
+ }
573
+ var backlink = '';
574
+ if (meta.parameters.backlink.url !== '') {
575
+ backlink +=
576
+ '<a href="' +
577
+ meta.parameters.backlink.url +
578
+ '">' +
579
+ meta.parameters.backlink.name +
580
+ '</a>';
581
+ }
582
+ else {
583
+ backlink += meta.parameters.backlink.name;
584
+ }
585
+ var contributors = '';
586
+ meta.parameters.contributors.forEach(function (contributor) {
587
+ if (contributor.url !== '') {
588
+ contributors +=
589
+ '<a href="' + contributor.url + '">' + contributor.name + '</a>, ';
590
+ }
591
+ else {
592
+ contributors += contributor.name + ', ';
593
+ }
594
+ });
595
+ contributors = contributors.replace(/,\s*$/, ''); //remove trailing commas
596
+ var copyright = '&copy; ' + year + ' ' + organization;
597
+ var webTitle = meta.parameters.title;
598
+ var webFooter = 'Version ' + releaseVersion + ' released on ' + releaseDate + '.';
599
+ for (var key in templates) {
600
+ if (templates.hasOwnProperty(key)) {
601
+ var $ = templates[key];
602
+ //logo
603
+ if (hasLogo === true) {
604
+ var logoUrl = logoPath;
605
+ $('#dg-logo').css('background-image', 'url(' + logoUrl + ')');
606
+ $('#dg-logo').css('height', logoHeight + 'px');
607
+ $('#dg-logo').css('line-height', logoHeight + 'px');
608
+ $('#dg-logo').css('padding-left', logoWidth + 25 + 'px');
609
+ }
610
+ else {
611
+ $('#dg-logo').css('padding-left', '0');
612
+ }
613
+ //parameters
614
+ $('title').text(meta.parameters.title);
615
+ $('#dg-homelink').attr('href', homelink);
616
+ $('#dg-title').text(meta.parameters.title);
617
+ $('#dg-owner').html(owner);
618
+ $('#dg-version').text(releaseVersion);
619
+ $('#dg-web-title-version').text('(' + releaseVersion + ')');
620
+ $('#dg-release-date').text(releaseDate);
621
+ $('#dg-web-footer').text(webFooter);
622
+ $('#dg-author').html(author);
623
+ $('#dg-contributors').html(contributors);
624
+ $('#dg-module').text(meta.parameters.module);
625
+ $('#dg-id').html(meta.parameters.id);
626
+ $('#dg-website').html(website);
627
+ $('#dg-backlink').html(backlink);
628
+ $('#dg-summary').text(meta.parameters.summary);
629
+ $('#dg-copyright').html(copyright);
630
+ $('#dg-marking').text(meta.parameters.marking);
631
+ $('#dg-legalese').text(meta.parameters.legalese);
632
+ $('#dg-attribution').text(attribution);
633
+ }
634
+ }
635
+ if (options.mathKatex === true) {
636
+ var $ = templates.main;
637
+ //support for KaTeX (bundled with DocGen)
638
+ $('head').append('<link rel="stylesheet" href="require/katex/katex.min.css" type="text/css">');
639
+ $('head').append('<script type="text/javascript" src="require/katex/katex.min.js"></script>');
640
+ $('head').append('<script type="text/javascript" src="require/katexInjector.js"></script>');
641
+ }
642
+ if (options.mathMathjax === true) {
643
+ //support for MathJax (only supported via CDN due to very large size)
644
+ //MathJax configuration is the same as used by math.stackexchange.com
645
+ //Note - wkhtmlpdf //cdn urls - see https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1634
646
+ $('head').append('<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full"></script>');
647
+ }
648
+ };
649
+ /*
650
+ process each input into an output
651
+ */
652
+ var processContent = function () {
653
+ console.log(chalk.green('Generating the static web content'));
654
+ webToc();
655
+ insertParameters();
656
+ meta.contents.forEach(function (section) {
657
+ section.pages.forEach(function (page) {
658
+ var $ = cheerio.load(templates.main.html()); //clone
659
+ var key = page.source;
660
+ var content = pages[key];
661
+ //add relevant container
662
+ if (page.html === true) {
663
+ //raw HTML pages should not be confined to the fixed width
664
+ $('#dg-content').html('<div id="dg-innerContent"></div>');
665
+ }
666
+ else {
667
+ //Markdown pages should be confined to the fixed width
668
+ $('#dg-content').html('<div class="w-fixed-width"><div id="dg-innerContent"></div></div>');
669
+ }
670
+ $('#dg-innerContent').html(content);
671
+ //------------------------------------------------------------------------------------------------------
672
+ //insert permalinks for every page heading
673
+ //when pageToc is enabled, also insert a page-level table of contents
674
+ var html = [], i = -1;
675
+ var headings = $('h1, h2, h3, h4, h5, h6');
676
+ if (headings.length > 0) {
677
+ html[++i] = '<ul class="dg-pageToc">';
678
+ }
679
+ headings.each(function () {
680
+ var label = $(this).text();
681
+ var anchor = label.toLowerCase().replace(/\s+/g, '-');
682
+ $(this).attr('id', anchor);
683
+ html[++i] = '<li><a href="#' + anchor + '">' + label + '</a></li>';
684
+ });
685
+ if (headings.length > 0) {
686
+ html[++i] = '</ul>';
687
+ }
688
+ if (options.pageToc === true && page.html !== true) {
689
+ $('#dg-innerContent').prepend(html.join(''));
690
+ }
691
+ //------------------------------------------------------------------------------------------------------
692
+ //prepend the auto heading (which makes the PDF table of contents match the web TOC)
693
+ $('#dg-innerContent').prepend('<h1 id="dg-autoTitle">' + page.title + '</h1>');
694
+ if (page.html === true) {
695
+ $('#dg-autoTitle').addClass('dg-hiddenTitle');
696
+ }
697
+ //------------------------------------------------------------------------------------------------------
698
+ //apply the w-table class
699
+ $('table:not(.unstyled)').addClass('w-table w-fixed w-stripe');
700
+ //------------------------------------------------------------------------------------------------------
701
+ pages[key] = $;
702
+ });
703
+ });
704
+ //add web ownership page
705
+ var $ = cheerio.load(templates.main.html()); //clone
706
+ $('#dg-content').html('<div class="w-fixed-width"><div id="dg-innerContent"></div></div>');
707
+ $('#dg-innerContent').html(templates.webCover.html());
708
+ templates.webCover = $;
709
+ writePages();
710
+ };
711
+ /*
712
+ write each html page
713
+ */
714
+ var writePages = function () {
715
+ console.log(chalk.green('Writing the web page files'));
716
+ var promises = {};
717
+ meta.contents.forEach(function (section) {
718
+ section.pages.forEach(function (page) {
719
+ var key = page.source;
720
+ var name = key.substr(0, page.source.lastIndexOf('.'));
721
+ var path = options.output + name + '.html';
722
+ var html = pages[key].html();
723
+ promises[key] = writeFile(path, html);
724
+ });
725
+ });
726
+ //add extra files
727
+ promises['ownership'] = writeFile(options.output + 'ownership.html', templates.webCover.html());
728
+ if (options.pdf === true) {
729
+ var pdfTempDir = options.output + 'temp/';
730
+ fs.mkdirsSync(pdfTempDir);
731
+ promises['docgenPdfCover'] = writeFile(pdfTempDir + 'pdfCover.html', templates.pdfCover.html());
732
+ promises['docgenPdfHeader'] = writeFile(pdfTempDir + 'pdfHeader.html', templates.pdfHeader.html());
733
+ promises['docgenPdfFooter'] = writeFile(pdfTempDir + 'pdfFooter.html', templates.pdfFooter.html());
734
+ }
735
+ rsvp
736
+ .hash(promises)
737
+ .then(function () {
738
+ copyDirSync(__dirname + '/require', options.output + 'require'); //CSS, JavaScript
739
+ copyDirSync(options.input + '/files', options.output + 'files'); //user-attached files and images
740
+ if (options.mathKatex === true) {
741
+ copyDirSync(__dirname + '/optional/katex', options.output + 'require/katex');
742
+ }
743
+ checkPdfVersion();
744
+ })
745
+ .catch(function (error) {
746
+ console.log(chalk.red('Error writing the web page files'));
747
+ if (options.verbose === true) {
748
+ console.log(chalk.red(error));
749
+ }
750
+ mainProcess.exit(1);
751
+ });
752
+ };
753
+ /*
754
+ wkthmltopdf options
755
+ */
756
+ var pdfOptions = [
757
+ ' --zoom 1.0',
758
+ ' --image-quality 100',
759
+ ' --print-media-type',
760
+ ' --orientation portrait',
761
+ ' --page-size A4',
762
+ ' --margin-top 25',
763
+ ' --margin-right 15',
764
+ ' --margin-bottom 16',
765
+ ' --margin-left 15',
766
+ ' --header-spacing 5',
767
+ ' --footer-spacing 5',
768
+ ' --no-stop-slow-scripts',
769
+ ];
770
+ var getPdfArguments = function () {
771
+ var pdfName = meta.parameters.name.toLowerCase() + '.pdf';
772
+ pdfOptions.push(' --enable-local-file-access');
773
+ pdfOptions.push(' --javascript-delay ' + options.pdfDelay); //code syntax highlight in wkhtmltopdf 0.12.2.1 fails without a delay (but why doesn't --no-stop-slow-scripts work?)
774
+ pdfOptions.push(' --user-style-sheet ' + __dirname + '/pdf-stylesheet.css');
775
+ pdfOptions.push(' --header-html ' + options.output + 'temp/pdfHeader.html');
776
+ pdfOptions.push(' --footer-html ' + options.output + 'temp/pdfFooter.html');
777
+ pdfOptions.push(' cover ' + options.output + 'temp/pdfCover.html');
778
+ pdfOptions.push(' toc --xsl-style-sheet ' + __dirname + '/pdf-contents.xsl');
779
+ var allPages = '';
780
+ for (var key in sortedPages) {
781
+ if (sortedPages.hasOwnProperty(key)) {
782
+ sortedPages[key].forEach(function (section) {
783
+ section.pages.forEach(function (page) {
784
+ var key = page.source;
785
+ var name = key.substr(0, page.source.lastIndexOf('.'));
786
+ var path = options.output + name + '.html';
787
+ allPages += ' ' + path;
788
+ });
789
+ });
790
+ }
791
+ }
792
+ var args = pdfOptions.join('');
793
+ args += allPages;
794
+ args += ' ' + options.output + pdfName;
795
+ return spawnArgs(args);
796
+ };
797
+ var checkPdfVersion = function () {
798
+ if (options.pdf === true) {
799
+ //first check that wkhtmltopdf is installed
800
+ (0, child_process_1.exec)(options.wkhtmltopdfPath + ' -V', function (error, stdout, stderr) {
801
+ if (error) {
802
+ console.log(chalk.red('Unable to call wkhtmltopdf. Is it installed and in path? See http://wkhtmltopdf.org'));
803
+ if (options.verbose === true) {
804
+ console.log(chalk.red(error));
805
+ }
806
+ mainProcess.exit(1);
807
+ }
808
+ else {
809
+ //warn if the version of wkhtmltopdf is not an expected version
810
+ var actualWkhtmltopdfVersion = stdout.trim();
811
+ if (actualWkhtmltopdfVersion !== wkhtmltopdfVersion) {
812
+ var warning = 'Warning: unexpected version of wkhtmltopdf, which may work but is not tested or supported';
813
+ var expectedVersion = ' expected version: ' + wkhtmltopdfVersion;
814
+ var detectedVersion = ' detected version: ' + actualWkhtmltopdfVersion;
815
+ console.log(chalk.yellow(warning));
816
+ console.log(chalk.yellow(expectedVersion));
817
+ console.log(chalk.yellow(detectedVersion));
818
+ }
819
+ generatePdf();
820
+ }
821
+ });
822
+ }
823
+ else {
824
+ cleanUp();
825
+ }
826
+ };
827
+ /*
828
+ call wkhtmltopdf as an external executable
829
+ */
830
+ var generatePdf = function () {
831
+ console.log(chalk.green('Creating the PDF copy (may take some time)'));
832
+ var args = getPdfArguments();
833
+ var wkhtmltopdf = (0, child_process_1.spawn)(options.wkhtmltopdfPath, args);
834
+ var spinner = new cliSpinner(chalk.green(' Processing... %s'));
835
+ spinner.setSpinnerString('|/-\\');
836
+ wkhtmltopdf.on('error', function (error) {
837
+ console.log(chalk.red('Error calling wkhtmltopdf to generate the PDF'));
838
+ if (options.verbose === true) {
839
+ console.log(chalk.red(error));
840
+ }
841
+ });
842
+ if (options.verbose !== true) {
843
+ spinner.start(); //only show spinner when verbose is off (otherwise show raw wkhtmltopdf output)
844
+ }
845
+ else {
846
+ //pipe the output from wkhtmltopdf back to stdout
847
+ //however, wkhtmltpdf outputs to stderr, not stdout. See:
848
+ //https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1980
849
+ wkhtmltopdf.stderr.pipe(mainProcess.stdout);
850
+ }
851
+ wkhtmltopdf.stdout.on('data', function (data) {
852
+ //do nothing
853
+ });
854
+ wkhtmltopdf.stderr.on('data', function (data) {
855
+ //do nothing
856
+ });
857
+ wkhtmltopdf.on('close', function (code) {
858
+ if (options.verbose !== true) {
859
+ spinner.stop();
860
+ console.log(''); //newline after spinner stops
861
+ }
862
+ if (code !== 0) {
863
+ var warning = 'wkhtmltopdf exited with a warning or error: try the -v option for details';
864
+ console.log(chalk.yellow(warning));
865
+ }
866
+ cleanUp();
867
+ });
868
+ };
869
+ var createRedirect = function () {
870
+ if (options.redirect) {
871
+ var parent_1 = options.output.replace(/\/$/, ''); //trim any trailing slash
872
+ parent_1 = parent_1.split(path.sep).slice(-1).pop(); //get name of final directory in the path
873
+ var homepage = meta.contents[0].pages[0];
874
+ homepage =
875
+ homepage.source.substr(0, homepage.source.lastIndexOf('.')) + '.html';
876
+ var redirectLink = parent_1 + '/' + homepage;
877
+ var $ = templates.redirect;
878
+ $('a').attr('href', redirectLink);
879
+ $('meta[http-equiv=REFRESH]').attr('content', '0;url=' + redirectLink);
880
+ var file = options.output + '../' + 'index.html';
881
+ try {
882
+ fs.outputFileSync(file, $.html(), 'utf-8');
883
+ }
884
+ catch (error) {
885
+ console.log(chalk.red('Error writing redirect file: ' + file));
886
+ if (options.verbose === true) {
887
+ console.log(chalk.red(error));
888
+ }
889
+ //don't exit because redirect error is not a fatal error
890
+ }
891
+ }
892
+ };
893
+ /*
894
+ cleanup
895
+ */
896
+ var cleanUp = function () {
897
+ createRedirect();
898
+ //remove temp files
899
+ if (options.pdf === true) {
900
+ removeDirSync(options.output + 'temp');
901
+ }
902
+ console.log(chalk.green.bold('Done!'));
903
+ };
904
+ }
905
+ module.exports = DocGen;