aboutsummaryrefslogtreecommitdiff
path: root/src/gleam_json_ffi.mjs
blob: 9d3daeedd75e9aec68042e152cbe18672a719b1d (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
import { Ok, Error } from './gleam.mjs'
import { UnexpectedByte, UnexpectedEndOfInput } from './gleam/json.mjs'

export function json_to_string(json) {
  return JSON.stringify(json)
}

export function object(entries) {
  return Object.fromEntries(entries)
}

export function identity(x) {
  return x
}

export function array(list) {
  return list.toArray()
}

export function do_null() {
  return null
}

export function decode(string) {
  try {
    const result = JSON.parse(string)
    return new Ok(result)
  } catch (err) {
    return new Error(getJsonDecodeError(err))
  }
}

function getJsonDecodeError(stdErr) {
  if (isUnexpectedByte(stdErr)) return new toUnexpectedByteError(stdErr)
  if (isUnexpectedEndOfInput(stdErr)) return new UnexpectedEndOfInput()
  return new UnexpectedByte('', 0)
}

function isUnexpectedEndOfInput(err) {
  return err.message.includes('Unexpected end') || err.message.includes('Unexpected EOF')
}

const unexpectedByteRegex = /Unexpected token (.) in JSON at position (\d+)/

function isUnexpectedByte(err) {
  return unexpectedByteRegex.test(err)
}

function toUnexpectedByteError(err) {
  const match = unexpectedByteRegex.exec(err.message)
  const byte = "0x" + match[1].charCodeAt(0).toString(16).toUpperCase()
  const position = Number(match[2])
  return new UnexpectedByte(byte, position)
}