forked from khanhas/minnet-quickjs
-
Notifications
You must be signed in to change notification settings - Fork 2
/
test-rpc.js
231 lines (196 loc) · 6.17 KB
/
test-rpc.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { client, createServer, LLL_NOTICE, LLL_USER, LLL_WARN, setLog, URL } from 'net';
import * as os from 'os';
import { define, filter, getOpt, showHelp, split, toUnixTime } from 'util';
import { Console } from '../qjs-modules/lib/console.js';
import inspect from 'inspect';
import { REPL } from '../qjs-modules/lib/repl.js';
import * as std from 'std';
import * as io from 'io';
import { MessageReceiver, MessageTransmitter, MessageTransceiver, codecs, RPCApi, RPCProxy, RPCObject, FactoryClient, RPCFactory, FactoryEndpoint, RPCServer, RPCClient, RPCSocket, RPCConnect, RPCListen } from './js/rpc.js';
import { List } from 'list';
import { Lexer } from 'lexer';
import { Location } from 'location';
import { SockAddr, Socket, AsyncSocket } from 'sockets';
import { StreamReader, StreamWriter, ReadableStream, ReadableStreamDefaultController, WritableStream, WritableStreamDefaultController, TransformStream } from 'stream';
function ReadJSON(filename) {
let data = std.loadFile(filename);
if(data) console.debug(`${data.length} bytes read from '${filename}'`);
return data ? JSON.parse(data) : null;
}
function WriteFile(name, data, verbose = true) {
const f = std.open(name, 'w+');
typeof data == 'string' ? f.puts(data) : f.write(data, 0, data.byteLength);
let ret = f.tell();
f.close();
if(verbose) console.log(`Wrote ${name}: ${ret} bytes`);
}
function WriteJSON(name, data) {
WriteFile(name, JSON.stringify(data, null, 2));
}
function CreateREPL(prefix, suffix) {
const repl = new REPL(`\x1b[38;5;165m${prefix} \x1b[38;5;39m${suffix}\x1b[0m`, null, false);
repl.historyLoad(null, false);
repl.loadSaveOptions();
repl.help = () => {};
let { log } = console;
repl.show = arg => (typeof arg == 'string' ? arg : inspect(arg, globalThis.console.options));
repl.cleanup = () => {
repl.readlineRemovePrompt();
let numLines = repl.historySave();
repl.printStatus(`EXIT (wrote ${numLines} history entries)`, false);
std.exit(0);
};
console.log = repl.printFunction(log);
return repl;
}
function main(...args) {
const base = scriptArgs[0]
.replace(/.*\//g, '')
.replace(/\.js$/gi, '')
.replace(/\.[a-z]*$/, '');
const config = ReadJSON(`.${base}-config`) ?? {};
globalThis.console = new Console({
inspectOptions: { compact: 10, customInspect: true, maxStringLength: 1024 }
});
/* globalThis.console = {
log(...args) {
return console.log('X', ...args);
},
config: console.config,
options: console.options
};*/
let params = (globalThis.params = getOpt(
{
help: [false, (_x, _y, opts) => showHelp(opts), 'h'],
verbose: [false, (a, v) => (typeof v == 'number' ? v : 0) + 1, 'v'],
listen: [false, null, 'l'],
connect: [false, null, 'c'],
client: [false, null, 'C'],
server: [false, null, 'S'],
debug: [false, null, 'x'],
tls: [false, null, 't'],
'no-tls': [false, (v, pv, o) => ((o.tls = false), true), 'T'],
address: [true, null, 'a'],
port: [true, null, 'p'],
'ssl-cert': [true, null],
'ssl-private-key': [true, null],
'@': 'url'
},
args
));
if(params['no-tls'] === true) params.tls = false;
const {
'@': [url = `ws://127.0.0.1:${params.port ?? 9090}/ws`],
'ssl-cert': sslCert = 'localhost.crt',
'ssl-private-key': sslPrivateKey = 'localhost.key'
} = params;
const listen = params.listen; //params.connect && !params.listen ? false : true;
const serve = params.server; /* && !params.client*/
/*console.log('listen', listen);
console.log('serve', serve);*/
let name = process.argv[1];
name = name
.replace(/.*\//, '')
.replace(/-/g, ' ')
.replace(/\.[^\/.]*$/, '');
let repl = CreateREPL(...name.split(' '));
let uri = new URL(url);
//console.log('main', { url, uri });
let ctor = () =>
new RPCSocket(
url,
serve
? new RPCServer(
FactoryEndpoint(
{
List,
Location,
Lexer,
Location,
SockAddr,
Socket,
AsyncSocket,
StreamReader,
StreamWriter,
ReadableStream,
ReadableStreamDefaultController,
WritableStream,
WritableStreamDefaultController,
TransformStream
},
params.verbose
),
params.verbose
)
: new FactoryClient(params.verbose),
params.verbose
);
let socket = (globalThis.socket = ctor());
//socket.register({ Array, Map });
//globalThis[['connection', 'listener'][+listen]] = cli;
define(globalThis, {
get ws() {
return socket.ws;
},
get connections() {
return socket.connections;
},
get rpc() {
const { connections } = socket;
return connections[connections.length - 1];
},
get server() {
const servers = socket.connections.filter(c => c instanceof RPCServer);
return servers[servers.length - 1];
},
get client() {
const clients = socket.connections.filter(c => c instanceof RPCClient);
return clients[clients.length - 1];
}
});
Object.assign(
globalThis,
{
repl,
quit,
exit: quit,
ReadJSON,
WriteFile,
WriteJSON
},
{
MessageReceiver,
MessageTransmitter,
MessageTransceiver,
codecs,
RPCApi,
RPCProxy,
RPCObject,
RPCFactory,
RPCServer,
RPCClient,
RPCSocket,
RPCConnect,
RPCListen
}
);
/* delete globalThis.DEBUG;
Object.defineProperty(globalThis, 'DEBUG', { get: DebugFlags });*/
const MakeWS = listen ? (url, callbacks) => createServer(url, callbacks) : (url, callbacks) => client(url, callbacks);
listen ? socket.listen(MakeWS) : socket.connect(MakeWS);
function quit(why) {
console.log(`quit('${why}')`);
let cfg = { inspectOptions: console.options };
WriteJSON(`.${base}-config`, cfg);
repl.cleanup(why);
}
repl.run();
}
try {
main(...scriptArgs.slice(1));
} catch(error) {
console.log(`FAIL: ${error?.message ?? error}\n${error?.stack}`);
std.exit(1);
} finally {
//console.log('SUCCESS');
}