/
browser.js
120 lines (95 loc) · 2.08 KB
/
browser.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
111
112
113
114
115
116
117
118
119
120
const op = {};
const Null = require('./null.js');
const Hash = require('./hash.js');
const core = require('./core.js');
const AnsiToHtml = require('ansi-to-html');
const NQPObject = require('./nqp-object.js');
exports.op = op;
class BufferedConsole extends NQPObject {
constructor(output) {
super();
this.buffered = [];
this.output = output;
}
$$writefh(buf) {
const buffer = core.toRawBuffer(buf);
this.$$write(buffer.toString());
}
$$write(str) {
const lines = str.split(/\n/);
if (lines.length === 0) return;
for (let i = 0; i < lines.length-1; i++) {
if (i === 0) {
this.output(this.buffered.join('') + lines[0]);
this.buffered.length = 0;
} else {
this.output(lines[i]);
}
}
if (lines[lines.length - 1] !== '') {
this.buffered.push(lines[lines.length - 1]);
}
}
$$isttyfh() {
return 1;
}
$$setbuffersizefh(size) {
return this;
}
}
class BrowserStdin extends NQPObject {
$$isttyfh() {
return 1;
}
}
const converter = new AnsiToHtml({escapeXML: true, stream: true});
class HijackedConsole extends NQPObject {
constructor(hijack) {
super();
this.hijack = hijack;
}
$$writefh(buf) {
const buffer = core.toRawBuffer(buf);
this.$$write(buffer.toString());
}
$$write(str) {
this.hijack(converter.toHtml(str));
}
$$isttyfh() {
return 1;
}
}
const STDOUT =
window.NQP_STDOUT ? new HijackedConsole(window.NQP_STDOUT)
: new BufferedConsole(output => console.log(output));
const STDERR = new BufferedConsole(output => console.error(output));
const STDIN = new BrowserStdin();
op.say = function(arg) {
STDOUT.$$write(arg + '\n');
return arg;
};
op.print = function(arg) {
STDOUT.$$write(arg);
return arg;
};
op.getstdin = function(arg) {
return STDIN;
};
op.getstdout = function(arg) {
return STDOUT;
};
op.getstderr = function(arg) {
return STDERR;
};
op.getenvhash = function() {
return new Hash();
};
op.getpid = function() {
return -1;
};
op.getppid = function() {
return -1;
};
op.cwd = function() {
return '?';
};