-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
326 lines (283 loc) · 8.38 KB
/
index.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import { spawn } from "child_process";
import { generateAddType, generateDllDirectObj } from "./lib/typeUtils.js";
import { assert, extractData } from "./lib/utils.js";
import { Extension } from "./ext/index.js";
import { Result } from "./lib/result.js";
import {
ErrorRecord,
IncompleteCommand,
StartTimeoutException,
TimeoutException,
getError,
} from "./lib/errors.js";
const beforerun = `
function Out {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true)]
$o
)
return ConvertTo-Json($o) -Compress -Depth 2 -WarningAction SilentlyContinue
}
function Out-Error {
$a = $o.FullyQualifiedErrorId;
$b = $o.InvocationInfo.InvocationName;
$c = $o.InvocationInfo.ScriptLineNumber;
$d = $o.InvocationInfo.OffsetInLine;
Write-Host('¬*{"code": "' + $a + '", "term": "' + $b + '", "line": ' + $c + ', "pos": ' + $d + '}*¬');
}
function Out-Default {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true)]
$o
)
if(($o -is [System.Exception]) -or ($o -is [System.Management.Automation.ErrorRecord])) {
Out-Error($o);
}
elseif ($Null -eq $o) {
}
else {
$d = Out($o);
Write-Host('¬¬' + $d + '¬¬')
}
}
function In {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true)]
$o,
$d = 2
)
return ConvertFrom-Json($o) -Depth $d -AsHashtable -WarningAction SilentlyContinue
}
function prompt { return "" }
`;
export class PowerJS {
#queue = [];
#child = null;
#readout = null; // Null is used to ignore the first result
#readerr = "";
#started = false;
#shell = "";
#working = true; // Busy with an existing query! At first we are busy waiting ps init.
#imported_dlls = {};
#dll = {}; // An interface to directly interact with imported dlls!
#timeouts = {
start: null,
};
get dll() {
return { ...this.#dll }; // Prevent dll sets
}
get shell() {
// Used shell
return this.#shell;
}
importDll(dllpath, defenition) {
assert(this.#started, false, "Cannot import dlls after starting");
const dllname = dllpath.match(/[^\\/]+\.dll$/g).reverse()[0];
dllpath = dllpath.replace(/\\/g, "\\\\");
if (dllname == undefined)
throw new Error("The path should end with a *.dll");
var name = dllname.split(".");
name.pop();
name = name.join("_");
this.#imported_dlls[name] = this.#imported_dlls[name] || {
dllpath,
defenition: {},
};
this.#imported_dlls[name].defenition = {
...this.#imported_dlls[name].defenition,
...defenition,
};
}
#extensions = {};
getExtension(extClassOrName) {
if (extClassOrName.prototype instanceof Extension) {
return this.#extensions[extClassOrName];
} else if (typeof extClassOrName == "string") {
for (const extension of this.#extensions) {
if (extension.name == extClassOrName) return extension;
}
}
// Undefined?
}
extend(...extclasses) {
for (let extclass of extclasses) {
if (!(extclass.prototype instanceof Extension)) return;
if (this.#extensions[extclass] != undefined) return;
let extension = new extclass(this);
this.#extensions[extclass] = extension;
// Import DLLs
extension.dll_imports =
typeof extension.dll_imports == "object" ? extension.dll_imports : {};
for (const dll_import in extension.dll_imports) {
if (Object.hasOwnProperty.call(extension.dll_imports, dll_import)) {
this.importDll(dll_import, extension.dll_imports[dll_import]);
}
}
const extname =
typeof extension.name == "string" && extension.name.length
? extension.name.toLowerCase().trim()
: "extension";
extension.name = extname;
}
}
exit() {
if (this.#child && this.#child.stdin) {
// Send an exit command to the Python subprocess
this.#child.stdin.write("exit()\n");
}
}
async start(...extensions) {
assert(this.#started, false, "Cannot start twice!");
this.extend(...extensions);
this.#child.stdin.write(generateAddType(this.#imported_dlls) + beforerun);
this.#dll = generateDllDirectObj(this.#imported_dlls, this.exec.bind(this));
this.#started = true;
this.#timeouts.start = setTimeout(() => {
this.#started = false;
this.#working = false;
throw new StartTimeoutException();
}, 8000);
}
#findOptimalShell(additionalShellNames) {
// Find optimal shell
for (const sname of additionalShellNames) {
try {
this.#child = spawn(sname);
this.#shell = sname;
break;
} catch (e) {
// Report error?
}
}
}
#processPS() {
if (this.#readout != null) {
this.#process(
this.#readout.substring(this.#readout.indexOf("\n") + 1).trim()
);
} else {
this.#working = false; // Powershell Session is initiated!
clearTimeout(this.#timeouts.start);
assert(this.#readerr.length, 0, "Powershell init has an error!");
} // No process() because we need to bypass introduction data (like Powershell version...)
this.#readout = "";
this.#readerr = "";
}
#processIncompleteCommand() {
this.#readerr = "";
this.#readout = "";
if (this.#working && this.#queue[0]) {
this.#child.stdin.write("\x03"); // Close that
if (this.#queue[0].started)
this.#queue.shift().trigger.incompleteCommand();
}
}
#setChildStreams() {
this.#child.stdout.on("data", (data) => {
data = data.toString();
if (data == "PS>") {
this.#processPS();
} else if (
data.startsWith(">") &&
this.#readout != null &&
(this.#readout.length == 0 || this.#readout.endsWith("\n"))
) {
this.#processIncompleteCommand();
} else {
if (this.#readout != null) this.#readout += data;
}
});
this.#child.stderr.on("data", (data) => {
this.#readerr += data;
});
}
#update() {
if (!this.#working) {
if (
typeof this.#queue[0] == "object" &&
this.#queue[0].started == false
) {
let command = this.#queue[0].command;
this.#child.stdin.write("&{" + command.trim() + "}\n");
this.#queue[0].started = true;
this.#working = true;
}
}
setTimeout(this.#update.bind(this), 200); // Update every 200ms
}
constructor({
additionalShellNames = [],
autoStart = true,
extensions = [],
dlls = {},
} = {}) {
additionalShellNames.push("pwsh", "powershell");
dlls = typeof dlls == "object" ? dlls : {};
for (const dll_import in dlls) {
if (Object.hasOwnProperty.call(dlls, dll_import)) {
this.importDll(dll_import, dlls[dll_import]);
}
}
this.#findOptimalShell(additionalShellNames);
if (this.#child == null) {
throw new Error(
"Cannot find a powershell interpreter! Try installing powershell or adding your one!"
);
}
this.#setChildStreams();
this.#update();
if (autoStart) {
this.start(...(Array.isArray(extensions) ? extensions : []));
}
}
#process(out) {
if (typeof this.#queue[0] == "object" && this.#queue[0].started)
this.#queue.shift().resolve(out);
this.#working = false;
}
exec(config = {}) {
assert(this.#started, true, "The shell isn't initiated yet!!");
if (typeof config == "string") config = { command: config };
config = {
command: "",
timeout: 20000,
...(typeof config == "object" ? config : {}),
};
return new Promise((resolve, reject) => {
let tm = null;
if (config.timeout > 0) {
tm = setTimeout(function () {
reject(
new TimeoutException(
"Your code exceeded the timeout of " + config.timeout + "ms!"
)
);
}, config.timeout);
}
this.#queue.push({
...config,
started: false,
trigger: {
incompleteCommand() {
reject(new IncompleteCommand());
},
},
resolve(out) {
if (tm != null) clearTimeout(tm);
const { json, errjson } = extractData(out);
if (errjson != null) {
reject(getError(errjson));
return;
}
resolve(
typeof json != "object" ? json : json ? new Result(json) : null
);
},
});
});
}
}
export { Extension, Result, ErrorRecord };