summaryrefslogtreecommitdiffstats
path: root/lib/parse/renderer.js
blob: 4b5c945a4b5ed3ef6791d9a52ab200265894fdf3 (plain)
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
var url = require('url');
var inherits = require('util').inherits;

var marked = require('marked');


function GitBookRenderer(options) {
    if(!(this instanceof GitBookRenderer)) {
        return new GitBookRenderer(options);
    }
    GitBookRenderer.super_.call(this, options);
}
inherits(GitBookRenderer, marked.Renderer);

GitBookRenderer.prototype._unsanitized = function(href) {
    var prot = '';
    try {
        prot = decodeURIComponent(unescape(href))
            .replace(/[^\w:]/g, '')
            .toLowerCase();

    } catch (e) {
        return true;
    }

    if(prot.indexOf('javascript:') === 0) {
        return true;
    }

    return false;
};

GitBookRenderer.prototype.link = function(href, title, text) {
    // Don't build if it looks malicious
    if (this.options.sanitize && this._unsanitized(href)) {
        return '';
    }

    // Parsed version of the url
    var parsed = url.parse(href);


    // Generate HTML for link
    var out = '<a href="' + href + '"';
    // Title if no null
    if (title) {
        out += ' title="' + title + '"';
    }
    // Target blank if external
    if(parsed.protocol) {
        out += ' target="_blank"';
    }
    out += '>' + text + '</a>';
    return out;
};

// Exports
module.exports = GitBookRenderer;