48 lines
1.1 KiB
JavaScript
48 lines
1.1 KiB
JavaScript
const { ArgumentType } = require('brigadier-commands')
|
|
|
|
const EXAMPLES = [123, -0.2, 'Hello, world!', true, false, { text: 'Hello, world!' }].map(v => JSON.stringify(v))
|
|
|
|
class JSONArgumentType extends ArgumentType {
|
|
static json () {
|
|
return new JSONArgumentType()
|
|
}
|
|
|
|
parse (reader) {
|
|
let string = ''
|
|
let depth = 0
|
|
let stringOpened = false
|
|
|
|
while (reader.canRead() && (depth !== 0 || reader.peek() !== ' ')) {
|
|
const c = reader.peek()
|
|
|
|
if (c === '\\') {
|
|
// Skip over escapes
|
|
let len = 2
|
|
if (reader.string[reader.cursor + 1] === 'u') len += 4
|
|
len = Math.max(len, reader.string.length - reader.cursor)
|
|
|
|
string += reader.string.substring(reader.cursor, reader.cursor + len)
|
|
reader.cursor += len
|
|
continue
|
|
}
|
|
|
|
if (c === '[' || c === '{') depth++
|
|
else if (c === ']' || c === '}') depth--
|
|
else if (c === '"') {
|
|
depth += stringOpened ? -1 : 1
|
|
stringOpened = !stringOpened
|
|
}
|
|
|
|
string += c
|
|
reader.skip()
|
|
}
|
|
|
|
return JSON.parse(string)
|
|
}
|
|
|
|
getExamples () {
|
|
return EXAMPLES
|
|
}
|
|
}
|
|
|
|
module.exports = JSONArgumentType
|