aboutsummaryrefslogtreecommitdiffstats
path: root/mitmproxy/contentviews/javascript.py
blob: b5f09150f3b8a0e499330ec5894e8917fc84b633 (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
import io
import re

from mitmproxy.utils import strutils
from mitmproxy.contentviews import base

DELIMITERS = '{};\n'
SPECIAL_AREAS = (
    r"(?<=[^\w\s)])\s*/(?:[^\n/]|(?<!\\)(?:\\\\)*\\/)+?/(?=[gimsuy]{0,6}\s*(?:[;,).\n]|$))",
    r"'" + strutils.MULTILINE_CONTENT_LINE_CONTINUATION + strutils.NO_ESCAPE + "'",
    r'"' + strutils.MULTILINE_CONTENT_LINE_CONTINUATION + strutils.NO_ESCAPE + '"',
    r'`' + strutils.MULTILINE_CONTENT + strutils.NO_ESCAPE + '`',
    r"/\*" + strutils.MULTILINE_CONTENT + r"\*/",
    r"//" + strutils.SINGLELINE_CONTENT + "$",
    r"for\(" + strutils.SINGLELINE_CONTENT + r"\)",
)


def beautify(data):
    data = strutils.escape_special_areas(
        data,
        SPECIAL_AREAS,
        DELIMITERS
    )

    data = re.sub(r"\s*{\s*(?!};)", " {\n", data)
    data = re.sub(r"\s*;\s*", ";\n", data)
    data = re.sub(r"(?<!{)\s*}(;)?\s*", r"\n}\1\n", data)

    beautified = io.StringIO()
    indent_level = 0

    for line in data.splitlines(True):
        if line.endswith("{\n"):
            beautified.write(" " * 2 * indent_level + line)
            indent_level += 1
        elif line.startswith("}"):
            indent_level -= 1
            beautified.write(" " * 2 * indent_level + line)
        else:
            beautified.write(" " * 2 * indent_level + line)

    data = strutils.unescape_special_areas(beautified.getvalue())
    return data


class ViewJavaScript(base.View):
    name = "JavaScript"
    content_types = [
        "application/x-javascript",
        "application/javascript",
        "text/javascript"
    ]

    def __call__(self, data, **metadata):
        data = data.decode("utf-8", "replace")
        res = beautify(data)
        return "JavaScript", base.format_text(res)