forked from fiatjaf/jq-web
-
Notifications
You must be signed in to change notification settings - Fork 1
/
post.js
110 lines (94 loc) · 2.54 KB
/
post.js
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/** @format */
// necessary because the default emscriptem exit() logs a lot of text.
function exit() {}
// takes a string as input and returns a string
// like `echo <jsonstring> | jq <filter>`, returning the value of STDOUT
function raw(jsonstring, filter, flags) {
if (!initialized) return '{}'
stdin = jsonstring
inBuffer = []
outBuffer = []
errBuffer = []
// window.FS=FS
flags = flags || []
Module.callMain(flags.concat(filter, '/dev/stdin')) // induce c main open it
// make sure closed & clean up fd
if(FS.streams[1]) FS.close(FS.streams[1])
if(FS.streams[2]) FS.close(FS.streams[2])
if(FS.streams[3]) FS.close(FS.streams[3])
if(FS.streams.length>3) FS.streams.pop()
// calling main closes stdout, so we reopen it here:
FS.streams[1] = FS.open('/dev/stdout', 577, 0)
FS.streams[2] = FS.open('/dev/stderr', 577, 0)
if (errBuffer.length) {
console.log('%cstderr%c: %c%s', 'background:red;color:black', '', 'color:red', fromByteArray(errBuffer))
}
if (outBuffer.length) {
return fromByteArray(outBuffer).trim()
}
if (errBuffer.length) {
var errBufferContents = fromByteArray(errBuffer)
var errString = errBufferContents
if (errString.indexOf(':') > -1) {
var parts = errString.split(':')
errString = parts[parts.length - 1].trim()
}
var err = new Error(errString)
err.stack = errBufferContents
throw err
}
return ''
}
// takes an object as input and tries to return objects.
function json(json, filter) {
if (!initialized) return {}
var jsonstring = JSON.stringify(json)
var result = raw(jsonstring, filter, ['-c']).trim()
if (result.indexOf('\n') !== -1) {
return result
.split('\n')
.filter(function(x) {
return x
})
.reduce(function(acc, line) {
return acc.concat(JSON.parse(line))
}, [])
} else {
return JSON.parse(result)
}
}
jq.json = json
jq.raw = raw
jq.onInitialized = {
addListener: function(cb) {
if (initialized) {
cb()
}
initListeners.push(cb)
}
}
jq.promised = {}
jq.promised.json = function() {
var args = arguments
return new Promise(function(resolve, reject) {
jq.onInitialized.addListener(function() {
try {
resolve(jq.json.apply(jq, args))
} catch (e) {
reject(e)
}
})
})
}
jq.promised.raw = function() {
var args = arguments
return new Promise(function(resolve, reject) {
jq.onInitialized.addListener(function() {
try {
resolve(jq.raw.apply(jq, args))
} catch (e) {
reject(e)
}
})
})
}