forked from alainbryden/bitburner-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfns1.js
77 lines (69 loc) · 2.03 KB
/
fns1.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
/**
* Free NetScript!
*/
export class FNS {
/** @param {NS} ns */
constructor(ns, path="ns.") {
return new Proxy(this, {
get: function (target, property) {
property = property.replace("$", "");
let cost = NaN;
try {
cost = ns.getFunctionRamCost(path.slice(3) + property);
} catch (e) {
if (!(e.message && e.message.endsWith("invalid type"))) {
if (typeof e === "string") {
throw new Error(e);
} else {
throw e;
}
}
}
if (cost >= 0) { // this is a valid ns function
return async (...args) => {
return await runGhostScript(ns, path + property, args);
}
} else { // this is a valid ns object
return new FNS(ns, path + property + ".");
}
}
});
}
}
/** @param {NS} ns */
async function runGhostScript(ns, func, args) {
const expr = `${func}(${args.map(a => JSON.stringify(a))})`
const resultPid = ns.run("fns/fns.js", {ramOverride: 1.6 + ns.getFunctionRamCost(func.slice(3))}, expr);
if (resultPid === 0) {
throw new Error("Unable to run ghost script!");
} else {
await ns.getPortHandle(resultPid).nextWrite();
}
const result = JSON.parse(ns.readPort(resultPid));
if (typeof result === "number") {
return result;
} else if (result.error === null) {
return JSON.parse(result.result);
} else {
const error = new Error("An error was thrown when handling a ghost script!");
error.stack += "\n" + result.error.stack;
throw error;
}
}
/** @param {NS} ns */
export async function main(ns) {
const expr = ns.args[0];
let result = null, error = null;
try {
result = await eval(expr);
} catch (e) {
error = JSON.parse(JSON.stringify(e, Object.getOwnPropertyNames(e)));
}
ns.atExit(() => {
if (typeof result === "number") {
ns.writePort(ns.pid, result);
} else {
ns.writePort(ns.pid, JSON.stringify({result: JSON.stringify(result), error: error}));
}
})
}