css-syntax-error.js
2.24 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict'
let { red, bold, gray, options: colorette } = require('colorette')
let terminalHighlight = require('./terminal-highlight')
class CssSyntaxError extends Error {
constructor(message, line, column, source, file, plugin) {
super(message)
this.name = 'CssSyntaxError'
this.reason = message
if (file) {
this.file = file
}
if (source) {
this.source = source
}
if (plugin) {
this.plugin = plugin
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
this.line = line
this.column = column
}
this.setMessage()
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError)
}
}
setMessage() {
this.message = this.plugin ? this.plugin + ': ' : ''
this.message += this.file ? this.file : '<css input>'
if (typeof this.line !== 'undefined') {
this.message += ':' + this.line + ':' + this.column
}
this.message += ': ' + this.reason
}
showSourceCode(color) {
if (!this.source) return ''
let css = this.source
if (color == null) color = colorette.enabled
if (terminalHighlight) {
if (color) css = terminalHighlight(css)
}
let lines = css.split(/\r?\n/)
let start = Math.max(this.line - 3, 0)
let end = Math.min(this.line + 2, lines.length)
let maxWidth = String(end).length
let mark, aside
if (color) {
mark = text => bold(red(text))
aside = text => gray(text)
} else {
mark = aside = str => str
}
return lines
.slice(start, end)
.map((line, index) => {
let number = start + 1 + index
let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | '
if (number === this.line) {
let spacing =
aside(gutter.replace(/\d/g, ' ')) +
line.slice(0, this.column - 1).replace(/[^\t]/g, ' ')
return mark('>') + aside(gutter) + line + '\n ' + spacing + mark('^')
}
return ' ' + aside(gutter) + line
})
.join('\n')
}
toString() {
let code = this.showSourceCode()
if (code) {
code = '\n\n' + code + '\n'
}
return this.name + ': ' + this.message + code
}
}
module.exports = CssSyntaxError
CssSyntaxError.default = CssSyntaxError