Move entire ns object to top-level

This commit is contained in:
Snarling 2022-08-09 15:41:47 -04:00
parent 589b9df2a7
commit 931ea730a5
18 changed files with 2169 additions and 2110 deletions

@ -2,6 +2,8 @@ import { getRamCost } from "./RamCostGenerator";
import type { WorkerScript } from "./WorkerScript";
import { Player } from "../Player";
import { helpers } from "./NetscriptHelpers";
import { ScriptArg } from "./ScriptArg";
import { NSEnums } from "src/ScriptEditor/NetscriptDefinitions";
type ExternalFunction = (...args: unknown[]) => unknown;
export type ExternalAPI = {
@ -13,6 +15,10 @@ type InternalFunction<F extends (...args: unknown[]) => unknown> = (ctx: Netscri
export type InternalAPI<API> = {
[Property in keyof API]: API[Property] extends ExternalFunction
? InternalFunction<API[Property]>
: API[Property] extends NSEnums
? NSEnums
: API[Property] extends ScriptArg[]
? ScriptArg[]
: API[Property] extends object
? InternalAPI<API[Property]>
: never;

@ -26,6 +26,8 @@ import { IPlayer } from "../PersonObjects/IPlayer";
import { FormulaGang } from "../Gang/formulas/formulas";
import { GangMember } from "../Gang/GangMember";
import { GangMemberTask } from "../Gang/GangMemberTask";
import { RunningScript } from "../Script/RunningScript";
import { toNative } from "../NetscriptFunctions/toNative";
//Helpers that are not specific to use in WorkerScripts/NetscriptContexts should be in src/utils/helpers instead
@ -34,6 +36,7 @@ export const helpers = {
string,
number,
scriptArgs,
argsToString,
isScriptErrorMessage,
//Error checking and generation
makeRuntimeRejectMsg,
@ -56,6 +59,7 @@ export const helpers = {
gangMember,
gangTask,
log,
getRunningScriptByArgs,
};
export type ScriptIdentifier = //This was previously in INetscriptHelper.ts, may move to its own file or a generic types file.
@ -66,12 +70,14 @@ export type ScriptIdentifier = //This was previously in INetscriptHelper.ts, ma
args: ScriptArg[];
};
/** If v is a number or string, returns the string representation. Error for other non-strings. */
function string(ctx: NetscriptContext, argName: string, v: unknown): string {
if (typeof v === "string") return v;
if (typeof v === "number") return v + ""; // cast to string;
throw makeRuntimeErrorMsg(ctx, `'${argName}' should be a string.`);
}
/** Validates v as non-NaN number, or as a string representation of a number, and returns that number. Error on NaN or non-number. */
function number(ctx: NetscriptContext, argName: string, v: unknown): number {
if (typeof v === "string") {
const x = parseFloat(v);
@ -83,11 +89,13 @@ function number(ctx: NetscriptContext, argName: string, v: unknown): number {
throw makeRuntimeErrorMsg(ctx, `'${argName}' should be a number.`);
}
/** Validates args as a ScriptArg[]. Throws an error if it is not. */
function scriptArgs(ctx: NetscriptContext, args: unknown) {
if (!isScriptArgs(args)) throw makeRuntimeErrorMsg(ctx, "'args' is not an array of script args");
return args;
}
/** Determines if the given msg string is an error created by makeRuntimeRejectMsg. */
function isScriptErrorMessage(msg: string): boolean {
if (!isString(msg)) {
return false;
@ -96,6 +104,26 @@ function isScriptErrorMessage(msg: string): boolean {
return splitMsg.length == 4;
}
/** Used to convert multiple arguments for tprint or print into a single string. */
function argsToString(args: unknown[]): string {
let out = "";
for (let arg of args) {
if (arg === null) {
out += "null";
continue;
}
if (arg === undefined) {
out += "undefined";
continue;
}
arg = toNative(arg);
out += typeof arg === "object" ? JSON.stringify(arg) : `${arg}`;
}
return out;
}
/** Creates an error message string containing hostname, scriptname, and the error message msg */
function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string): string {
for (const scriptUrl of workerScript.scriptRef.dependencies) {
msg = msg.replace(new RegExp(scriptUrl.url, "g"), scriptUrl.filename);
@ -104,6 +132,7 @@ function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string): string {
return "|DELIMITER|" + workerScript.hostname + "|DELIMITER|" + workerScript.name + "|DELIMITER|" + msg;
}
/** Creates an error message string with a stack trace. */
function makeRuntimeErrorMsg(ctx: NetscriptContext, msg: string): string {
const errstack = new Error().stack;
if (errstack === undefined) throw new Error("how did we not throw an error?");
@ -174,6 +203,7 @@ function makeRuntimeErrorMsg(ctx: NetscriptContext, msg: string): string {
return makeRuntimeRejectMsg(workerScript, rejectMsg);
}
/** Validate requested number of threads for h/g/w options */
function resolveNetscriptRequestedThreads(ctx: NetscriptContext, requestedThreads?: number): number {
const threads = ctx.workerScript.scriptRef.threads;
if (!requestedThreads) {
@ -195,6 +225,7 @@ function resolveNetscriptRequestedThreads(ctx: NetscriptContext, requestedThread
return requestedThreadsAsInt;
}
/** Validate singularity access by throwing an error if the player does not have access. */
function checkSingularityAccess(ctx: NetscriptContext): void {
if (Player.bitNodeN !== 4 && Player.sourceFileLvl(4) === 0) {
throw makeRuntimeErrorMsg(
@ -205,6 +236,7 @@ function checkSingularityAccess(ctx: NetscriptContext): void {
}
}
/** Create an error if a script is dead or if concurrent ns function calls are made */
function checkEnvFlags(ctx: NetscriptContext): void {
const ws = ctx.workerScript;
if (ws.env.stopFlag) throw new ScriptDeath(ws);
@ -503,3 +535,42 @@ function gangTask(ctx: NetscriptContext, t: unknown): GangMemberTask {
function log(ctx: NetscriptContext, message: () => string) {
ctx.workerScript.log(ctx.functionPath, message);
}
/**
* Searches for and returns the RunningScript object for the specified script.
* If the 'fn' argument is not specified, this returns the current RunningScript.
* @param {string} fn - Filename of script
* @param {string} hostname - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {RunningScript}
* Running script identified by the parameters, or null if no such script
* exists, or the current running script if the first argument 'fn'
* is not specified.
*/
function getRunningScriptByArgs(
ctx: NetscriptContext,
fn: string,
hostname: string,
scriptArgs: ScriptArg[],
): RunningScript | null {
if (!Array.isArray(scriptArgs)) {
throw helpers.makeRuntimeRejectMsg(
ctx.workerScript,
`Invalid scriptArgs argument passed into getRunningScript() from ${ctx.function}(). ` +
`This is probably a bug. Please report to game developer`,
);
}
if (fn != null && typeof fn === "string") {
// Get Logs of another script
if (hostname == null) {
hostname = ctx.workerScript.hostname;
}
const server = helpers.getServer(ctx, hostname);
return findRunningScript(fn, scriptArgs, server);
}
// If no arguments are specified, return the current RunningScript
return ctx.workerScript.scriptRef;
}

@ -115,121 +115,7 @@ interface NS extends INS {
infiltration: IInfiltration;
}
export function NetscriptFunctions(workerScript: WorkerScript): NS {
/**
* Searches for and returns the RunningScript object for the specified script.
* If the 'fn' argument is not specified, this returns the current RunningScript.
* @param {string} fn - Filename of script
* @param {string} hostname - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {RunningScript}
* Running script identified by the parameters, or null if no such script
* exists, or the current running script if the first argument 'fn'
* is not specified.
*/
const getRunningScriptByArgs = function (
ctx: NetscriptContext,
fn: string,
hostname: string,
scriptArgs: ScriptArg[],
): RunningScript | null {
if (!Array.isArray(scriptArgs)) {
throw helpers.makeRuntimeRejectMsg(
workerScript,
`Invalid scriptArgs argument passed into getRunningScript() from ${ctx.function}(). ` +
`This is probably a bug. Please report to game developer`,
);
}
if (fn != null && typeof fn === "string") {
// Get Logs of another script
if (hostname == null) {
hostname = workerScript.hostname;
}
const server = helpers.getServer(ctx, hostname);
return findRunningScript(fn, scriptArgs, server);
}
// If no arguments are specified, return the current RunningScript
return workerScript.scriptRef;
};
const getRunningScriptByPid = function (pid: number): RunningScript | null {
for (const server of GetAllServers()) {
const runningScript = findRunningScriptByPid(pid, server);
if (runningScript) return runningScript;
}
return null;
};
const getRunningScript = (ctx: NetscriptContext, ident: ScriptIdentifier): RunningScript | null => {
if (typeof ident === "number") {
return getRunningScriptByPid(ident);
} else {
return getRunningScriptByArgs(ctx, ident.scriptname, ident.hostname, ident.args);
}
};
/**
* Sanitizes a `RunningScript` to remove sensitive information, making it suitable for
* return through an NS function.
* @see NS.getRecentScripts
* @see NS.getRunningScript
* @param runningScript Existing, internal RunningScript
* @returns A sanitized, NS-facing copy of the RunningScript
*/
const createPublicRunningScript = function (runningScript: RunningScript): IRunningScript {
return {
args: runningScript.args.slice(),
filename: runningScript.filename,
logs: runningScript.logs.slice(),
offlineExpGained: runningScript.offlineExpGained,
offlineMoneyMade: runningScript.offlineMoneyMade,
offlineRunningTime: runningScript.offlineRunningTime,
onlineExpGained: runningScript.onlineExpGained,
onlineMoneyMade: runningScript.onlineMoneyMade,
onlineRunningTime: runningScript.onlineRunningTime,
pid: runningScript.pid,
ramUsage: runningScript.ramUsage,
server: runningScript.server,
threads: runningScript.threads,
};
};
/**
* Helper function for getting the error log message when the user specifies
* a nonexistent running script
* @param {string} fn - Filename of script
* @param {string} hostname - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {string} Error message to print to logs
*/
const getCannotFindRunningScriptErrorMessage = function (ident: ScriptIdentifier): string {
if (typeof ident === "number") return `Cannot find running script with pid: ${ident}`;
return `Cannot find running script ${ident.scriptname} on server ${ident.hostname} with args: ${arrayToString(
ident.args,
)}`;
};
/**
* Used to fail a function if the function's target is a Hacknet Server.
* This is used for functions that should run on normal Servers, but not Hacknet Servers
* @param {Server} server - Target server
* @param {string} callingFn - Name of calling function. For logging purposes
* @returns {boolean} True if the server is a Hacknet Server, false otherwise
*/
const failOnHacknetServer = function (server: BaseServer, callingFn = ""): boolean {
if (server instanceof HacknetServer) {
workerScript.log(callingFn, () => `Does not work on Hacknet Servers`);
return true;
} else {
return false;
}
};
const argsToString = function (args: unknown[]): string {
const argsToString = function (args: unknown[]): string {
let out = "";
for (let arg of args) {
if (arg === null) {
@ -245,33 +131,162 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
return out;
};
};
const singularity = NetscriptSingularity(Player, workerScript);
const base: InternalAPI<INS> = {
args: workerScript.args as unknown as any,
function getFunctionNames(obj: object, prefix: string): string[] {
const functionNames: string[] = [];
for (const [key, value] of Object.entries(obj)) {
if (key === "args") {
continue;
} else if (typeof value == "function") {
functionNames.push(prefix + key);
} else if (typeof value == "object") {
functionNames.push(...getFunctionNames(value, key + "."));
}
}
return functionNames;
}
const getRunningScriptByPid = function (pid: number): RunningScript | null {
for (const server of GetAllServers()) {
const runningScript = findRunningScriptByPid(pid, server);
if (runningScript) return runningScript;
}
return null;
};
const getRunningScript = (ctx: NetscriptContext, ident: ScriptIdentifier): RunningScript | null => {
if (typeof ident === "number") {
return getRunningScriptByPid(ident);
} else {
return getRunningScriptByArgs(ctx, ident.scriptname, ident.hostname, ident.args);
}
};
/**
* Searches for and returns the RunningScript object for the specified script.
* If the 'fn' argument is not specified, this returns the current RunningScript.
* @param {string} fn - Filename of script
* @param {string} hostname - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {RunningScript}
* Running script identified by the parameters, or null if no such script
* exists, or the current running script if the first argument 'fn'
* is not specified.
*/
const getRunningScriptByArgs = function (
ctx: NetscriptContext,
fn: string,
hostname: string,
scriptArgs: ScriptArg[],
): RunningScript | null {
if (!Array.isArray(scriptArgs)) {
throw helpers.makeRuntimeRejectMsg(
ctx.workerScript,
`Invalid scriptArgs argument passed into getRunningScript() from ${ctx.function}(). ` +
`This is probably a bug. Please report to game developer`,
);
}
if (fn != null && typeof fn === "string") {
// Get Logs of another script
if (hostname == null) {
hostname = ctx.workerScript.hostname;
}
const server = helpers.getServer(ctx, hostname);
return findRunningScript(fn, scriptArgs, server);
}
// If no arguments are specified, return the current RunningScript
return ctx.workerScript.scriptRef;
};
/**
* Helper function for getting the error log message when the user specifies
* a nonexistent running script
* @param {string} fn - Filename of script
* @param {string} hostname - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {string} Error message to print to logs
*/
const getCannotFindRunningScriptErrorMessage = function (ident: ScriptIdentifier): string {
if (typeof ident === "number") return `Cannot find running script with pid: ${ident}`;
return `Cannot find running script ${ident.scriptname} on server ${ident.hostname} with args: ${arrayToString(
ident.args,
)}`;
};
/**
* Sanitizes a `RunningScript` to remove sensitive information, making it suitable for
* return through an NS function.
* @see NS.getRecentScripts
* @see NS.getRunningScript
* @param runningScript Existing, internal RunningScript
* @returns A sanitized, NS-facing copy of the RunningScript
*/
const createPublicRunningScript = function (runningScript: RunningScript): IRunningScript {
return {
args: runningScript.args.slice(),
filename: runningScript.filename,
logs: runningScript.logs.slice(),
offlineExpGained: runningScript.offlineExpGained,
offlineMoneyMade: runningScript.offlineMoneyMade,
offlineRunningTime: runningScript.offlineRunningTime,
onlineExpGained: runningScript.onlineExpGained,
onlineMoneyMade: runningScript.onlineMoneyMade,
onlineRunningTime: runningScript.onlineRunningTime,
pid: runningScript.pid,
ramUsage: runningScript.ramUsage,
server: runningScript.server,
threads: runningScript.threads,
};
};
/**
* Used to fail a function if the function's target is a Hacknet Server.
* This is used for functions that should run on normal Servers, but not Hacknet Servers
* @param {Server} server - Target server
* @param {string} callingFn - Name of calling function. For logging purposes
* @returns {boolean} True if the server is a Hacknet Server, false otherwise
*/
const failOnHacknetServer = function (ctx:NetscriptContext, server: BaseServer, callingFn = ""): boolean {
if (server instanceof HacknetServer) {
ctx.workerScript.log(callingFn, () => `Does not work on Hacknet Servers`);
return true;
} else {
return false;
}
};
export function NetscriptFunctions(workerScript: WorkerScript): NS {
const wrappedNS = wrapAPI({}, workerScript, ns) as unknown as INS;
(wrappedNS.args as ScriptArg[]) = workerScript.args;
return wrappedNS;
}
const base: InternalAPI<INS> = {
args: [],
enums: {
toast: ToastVariant,
} as unknown as any,
},
singularity: singularity,
gang: NetscriptGang(Player, workerScript),
bladeburner: NetscriptBladeburner(Player, workerScript),
codingcontract: NetscriptCodingContract(Player, workerScript),
sleeve: NetscriptSleeve(Player),
corporation: NetscriptCorporation(Player),
stanek: NetscriptStanek(Player, workerScript),
infiltration: NetscriptInfiltration(Player),
singularity: NetscriptSingularity(),
gang: NetscriptGang(),
bladeburner: NetscriptBladeburner(),
codingcontract: NetscriptCodingContract(),
sleeve: NetscriptSleeve(),
corporation: NetscriptCorporation(),
stanek: NetscriptStanek(),
infiltration: NetscriptInfiltration(),
ui: NetscriptUserInterface(),
formulas: NetscriptFormulas(Player),
stock: NetscriptStockMarket(Player, workerScript),
grafting: NetscriptGrafting(Player),
hacknet: NetscriptHacknet(Player, workerScript),
formulas: NetscriptFormulas(),
stock: NetscriptStockMarket(),
grafting: NetscriptGrafting(),
hacknet: NetscriptHacknet(),
sprintf: () => sprintf,
vsprintf: () => vsprintf,
scan:
(ctx: NetscriptContext) =>
(_hostname: unknown = workerScript.hostname): string[] => {
(_hostname: unknown = ctx.workerScript.hostname): string[] => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
const out = [];
@ -396,7 +411,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const hostname = helpers.string(ctx, "hostname", _hostname);
const threads = helpers.resolveNetscriptRequestedThreads(
ctx,
requestedThreads ?? workerScript.scriptRef.threads,
requestedThreads ?? ctx.workerScript.scriptRef.threads,
);
const server = helpers.getServer(ctx, hostname);
@ -405,7 +420,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
return Promise.resolve(0);
}
const host = GetServer(workerScript.hostname);
const host = GetServer(ctx.workerScript.hostname);
if (host === null) {
throw new Error("Workerscript host is null");
}
@ -429,7 +444,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const moneyBefore = server.moneyAvailable <= 0 ? 1 : server.moneyAvailable;
processSingleServerGrowth(server, threads, Player, host.cpuCores);
const moneyAfter = server.moneyAvailable;
workerScript.scriptRef.recordGrow(server.hostname, threads);
ctx.workerScript.scriptRef.recordGrow(server.hostname, threads);
const expGain = calculateHackingExpGain(server, Player) * threads;
const logGrowPercent = moneyAfter / moneyBefore - 1;
helpers.log(
@ -438,11 +453,9 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
`Available money on '${server.hostname}' grown by ${numeralWrapper.formatPercentage(
logGrowPercent,
6,
)}. Gained ${numeralWrapper.formatExp(expGain)} hacking exp (t=${numeralWrapper.formatThreads(
threads,
)}).`,
)}. Gained ${numeralWrapper.formatExp(expGain)} hacking exp (t=${numeralWrapper.formatThreads(threads)}).`,
);
workerScript.scriptRef.onlineExpGained += expGain;
ctx.workerScript.scriptRef.onlineExpGained += expGain;
Player.gainHackingExp(expGain);
if (stock) {
influenceStockThroughServerGrow(server, moneyAfter - moneyBefore);
@ -498,7 +511,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const hostname = helpers.string(ctx, "hostname", _hostname);
const threads = helpers.resolveNetscriptRequestedThreads(
ctx,
requestedThreads ?? workerScript.scriptRef.threads,
requestedThreads ?? ctx.workerScript.scriptRef.threads,
);
if (hostname === undefined) {
throw helpers.makeRuntimeErrorMsg(ctx, "Takes 1 argument.");
@ -525,14 +538,14 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
)} (t=${numeralWrapper.formatThreads(threads)})`,
);
return helpers.netscriptDelay(ctx, weakenTime * 1000).then(function () {
const host = GetServer(workerScript.hostname);
const host = GetServer(ctx.workerScript.hostname);
if (host === null) {
helpers.log(ctx, () => "Server is null, did it die?");
return Promise.resolve(0);
}
const coreBonus = 1 + (host.cpuCores - 1) / 16;
server.weaken(CONSTANTS.ServerWeakenAmount * threads * coreBonus);
workerScript.scriptRef.recordWeaken(server.hostname, threads);
ctx.workerScript.scriptRef.recordWeaken(server.hostname, threads);
const expGain = calculateHackingExpGain(server, Player) * threads;
helpers.log(
ctx,
@ -541,7 +554,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
server.hackDifficulty
}. Gained ${numeralWrapper.formatExp(expGain)} hacking exp (t=${numeralWrapper.formatThreads(threads)})`,
);
workerScript.scriptRef.onlineExpGained += expGain;
ctx.workerScript.scriptRef.onlineExpGained += expGain;
Player.gainHackingExp(expGain);
return Promise.resolve(CONSTANTS.ServerWeakenAmount * threads * coreBonus);
});
@ -557,7 +570,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
share: (ctx: NetscriptContext) => async (): Promise<void> => {
helpers.log(ctx, () => "Sharing this computer.");
const end = StartSharing(
workerScript.scriptRef.threads * calculateIntelligenceBonus(Player.skills.intelligence, 2),
ctx.workerScript.scriptRef.threads * calculateIntelligenceBonus(Player.skills.intelligence, 2),
);
return helpers.netscriptDelay(ctx, 10000).finally(function () {
helpers.log(ctx, () => "Finished sharing this computer.");
@ -573,7 +586,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (args.length === 0) {
throw helpers.makeRuntimeErrorMsg(ctx, "Takes at least 1 argument.");
}
workerScript.print(argsToString(args));
ctx.workerScript.print(argsToString(args));
},
printf:
(ctx: NetscriptContext) =>
@ -582,7 +595,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (typeof format !== "string") {
throw helpers.makeRuntimeErrorMsg(ctx, "First argument must be string for the format.");
}
workerScript.print(vsprintf(format, args));
ctx.workerScript.print(vsprintf(format, args));
},
tprint:
(ctx: NetscriptContext) =>
@ -592,22 +605,22 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const str = argsToString(args);
if (str.startsWith("ERROR") || str.startsWith("FAIL")) {
Terminal.error(`${workerScript.scriptRef.filename}: ${str}`);
Terminal.error(`${ctx.workerScript.scriptRef.filename}: ${str}`);
return;
}
if (str.startsWith("SUCCESS")) {
Terminal.success(`${workerScript.scriptRef.filename}: ${str}`);
Terminal.success(`${ctx.workerScript.scriptRef.filename}: ${str}`);
return;
}
if (str.startsWith("WARN")) {
Terminal.warn(`${workerScript.scriptRef.filename}: ${str}`);
Terminal.warn(`${ctx.workerScript.scriptRef.filename}: ${str}`);
return;
}
if (str.startsWith("INFO")) {
Terminal.info(`${workerScript.scriptRef.filename}: ${str}`);
Terminal.info(`${ctx.workerScript.scriptRef.filename}: ${str}`);
return;
}
Terminal.print(`${workerScript.scriptRef.filename}: ${str}`);
Terminal.print(`${ctx.workerScript.scriptRef.filename}: ${str}`);
},
tprintf:
(ctx: NetscriptContext) =>
@ -633,8 +646,8 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
Terminal.print(`${str}`);
},
clearLog: () => (): void => {
workerScript.scriptRef.clearLog();
clearLog: (ctx: NetscriptContext) => (): void => {
ctx.workerScript.scriptRef.clearLog();
},
disableLog:
(ctx: NetscriptContext) =>
@ -642,13 +655,13 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const fn = helpers.string(ctx, "fn", _fn);
if (fn === "ALL") {
for (const fn of Object.keys(possibleLogs)) {
workerScript.disableLogs[fn] = true;
ctx.workerScript.disableLogs[fn] = true;
}
helpers.log(ctx, () => `Disabled logging for all functions`);
} else if (possibleLogs[fn] === undefined) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid argument: ${fn}.`);
} else {
workerScript.disableLogs[fn] = true;
ctx.workerScript.disableLogs[fn] = true;
helpers.log(ctx, () => `Disabled logging for ${fn}`);
}
},
@ -658,13 +671,13 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const fn = helpers.string(ctx, "fn", _fn);
if (fn === "ALL") {
for (const fn of Object.keys(possibleLogs)) {
delete workerScript.disableLogs[fn];
delete ctx.workerScript.disableLogs[fn];
}
helpers.log(ctx, () => `Enabled logging for all functions`);
} else if (possibleLogs[fn] === undefined) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid argument: ${fn}.`);
}
delete workerScript.disableLogs[fn];
delete ctx.workerScript.disableLogs[fn];
helpers.log(ctx, () => `Enabled logging for ${fn}`);
},
isLogEnabled:
@ -674,7 +687,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (possibleLogs[fn] === undefined) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid argument: ${fn}.`);
}
return !workerScript.disableLogs[fn];
return !ctx.workerScript.disableLogs[fn];
},
getScriptLogs:
(ctx: NetscriptContext) =>
@ -703,7 +716,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
closeTail:
(ctx: NetscriptContext) =>
(_pid: unknown = workerScript.scriptRef.pid): void => {
(_pid: unknown = ctx.workerScript.scriptRef.pid): void => {
const pid = helpers.number(ctx, "pid", _pid);
//Emit an event to tell the game to close the tail window if it exists
LogBoxCloserEvents.emit(pid);
@ -861,12 +874,12 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (isNaN(threads) || threads <= 0) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid thread count. Must be numeric and > 0, is ${threads}`);
}
const scriptServer = GetServer(workerScript.hostname);
const scriptServer = GetServer(ctx.workerScript.hostname);
if (scriptServer == null) {
throw helpers.makeRuntimeErrorMsg(ctx, "Could not find server. This is a bug. Report to dev.");
}
return runScriptFromScript(Player, "run", scriptServer, scriptname, args, workerScript, threads);
return runScriptFromScript(Player, "run", scriptServer, scriptname, args, ctx.workerScript, threads);
},
exec:
(ctx: NetscriptContext) =>
@ -882,7 +895,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid thread count. Must be numeric and > 0, is ${threads}`);
}
const server = helpers.getServer(ctx, hostname);
return runScriptFromScript(Player, "exec", server, scriptname, args, workerScript, threads);
return runScriptFromScript(Player, "exec", server, scriptname, args, ctx.workerScript, threads);
},
spawn:
(ctx: NetscriptContext) =>
@ -899,18 +912,18 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (isNaN(threads) || threads <= 0) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid thread count. Must be numeric and > 0, is ${threads}`);
}
const scriptServer = GetServer(workerScript.hostname);
const scriptServer = GetServer(ctx.workerScript.hostname);
if (scriptServer == null) {
throw helpers.makeRuntimeErrorMsg(ctx, "Could not find server. This is a bug. Report to dev");
}
return runScriptFromScript(Player, "spawn", scriptServer, scriptname, args, workerScript, threads);
return runScriptFromScript(Player, "spawn", scriptServer, scriptname, args, ctx.workerScript, threads);
}, spawnDelay * 1e3);
helpers.log(ctx, () => `Will execute '${scriptname}' in ${spawnDelay} seconds`);
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
if (killWorkerScript(workerScript)) {
ctx.workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
if (killWorkerScript(ctx.workerScript)) {
helpers.log(ctx, () => "Exiting...");
}
},
@ -960,7 +973,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
killall:
(ctx: NetscriptContext) =>
(_hostname: unknown = workerScript.hostname, _safetyguard: unknown = true): boolean => {
(_hostname: unknown = ctx.workerScript.hostname, _safetyguard: unknown = true): boolean => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const safetyguard = !!_safetyguard;
if (hostname === undefined) {
@ -971,7 +984,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
let scriptsKilled = 0;
for (let i = server.runningScripts.length - 1; i >= 0; --i) {
if (safetyguard === true && server.runningScripts[i].pid == workerScript.pid) continue;
if (safetyguard === true && server.runningScripts[i].pid == ctx.workerScript.pid) continue;
killWorkerScript({ runningScript: server.runningScripts[i], hostname: server.hostname });
++scriptsKilled;
}
@ -984,8 +997,8 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
return scriptsKilled > 0;
},
exit: (ctx: NetscriptContext) => (): void => {
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
if (killWorkerScript(workerScript)) {
ctx.workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
if (killWorkerScript(ctx.workerScript)) {
helpers.log(ctx, () => "Exiting...");
} else {
helpers.log(ctx, () => "Failed. This is a bug. Report to dev.");
@ -996,7 +1009,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
async (
_scriptname: unknown,
_destination: unknown,
_source: unknown = workerScript.hostname,
_source: unknown = ctx.workerScript.hostname,
): Promise<boolean> => {
const destination = helpers.string(ctx, "destination", _destination);
const source = helpers.string(ctx, "source", _source);
@ -1009,7 +1022,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
let res = true;
await Promise.all(
scripts.map(async function (script) {
if (!(await NetscriptFunctions(workerScript).scp(script, destination, source))) {
if (!(await NetscriptFunctions(ctx.workerScript).scp(script, destination, source))) {
res = false;
}
}),
@ -1206,7 +1219,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
ps:
(ctx: NetscriptContext) =>
(_hostname: unknown = workerScript.hostname): ProcessInfo[] => {
(_hostname: unknown = ctx.workerScript.hostname): ProcessInfo[] => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
const processes = [];
@ -1229,7 +1242,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
return server.hasAdminRights;
},
getHostname: (ctx: NetscriptContext) => (): string => {
const scriptServer = GetServer(workerScript.hostname);
const scriptServer = GetServer(ctx.workerScript.hostname);
if (scriptServer == null) {
throw helpers.makeRuntimeErrorMsg(ctx, "Could not find server. This is a bug. Report to dev.");
}
@ -1266,7 +1279,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
getServer:
(ctx: NetscriptContext) =>
(_hostname: unknown = workerScript.hostname): IServerDef => {
(_hostname: unknown = ctx.workerScript.hostname): IServerDef => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
const copy = Object.assign({}, server) as Server;
@ -1298,7 +1311,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 0;
}
if (failOnHacknetServer(server, "getServerMoneyAvailable")) {
if (failOnHacknetServer(ctx, server, "getServerMoneyAvailable")) {
return 0;
}
if (server.hostname == "home") {
@ -1306,10 +1319,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => `returned player's money: ${numeralWrapper.formatMoney(Player.money)}`);
return Player.money;
}
helpers.log(
ctx,
() => `returned ${numeralWrapper.formatMoney(server.moneyAvailable)} for '${server.hostname}'`,
);
helpers.log(ctx, () => `returned ${numeralWrapper.formatMoney(server.moneyAvailable)} for '${server.hostname}'`);
return server.moneyAvailable;
},
getServerSecurityLevel:
@ -1321,7 +1331,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerSecurityLevel")) {
if (failOnHacknetServer(ctx, server, "getServerSecurityLevel")) {
return 1;
}
helpers.log(
@ -1340,7 +1350,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerBaseSecurityLevel")) {
if (failOnHacknetServer(ctx, server, "getServerBaseSecurityLevel")) {
return 1;
}
helpers.log(
@ -1358,7 +1368,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerMinSecurityLevel")) {
if (failOnHacknetServer(ctx, server, "getServerMinSecurityLevel")) {
return 1;
}
helpers.log(
@ -1376,7 +1386,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerRequiredHackingLevel")) {
if (failOnHacknetServer(ctx, server, "getServerRequiredHackingLevel")) {
return 1;
}
helpers.log(
@ -1394,7 +1404,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 0;
}
if (failOnHacknetServer(server, "getServerMaxMoney")) {
if (failOnHacknetServer(ctx, server, "getServerMaxMoney")) {
return 0;
}
helpers.log(ctx, () => `returned ${numeralWrapper.formatMoney(server.moneyMax)} for '${server.hostname}'`);
@ -1409,7 +1419,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerGrowth")) {
if (failOnHacknetServer(ctx, server, "getServerGrowth")) {
return 1;
}
helpers.log(ctx, () => `returned ${server.serverGrowth} for '${server.hostname}'`);
@ -1424,7 +1434,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
helpers.log(ctx, () => "Cannot be executed on this server.");
return 5;
}
if (failOnHacknetServer(server, "getServerNumPortsRequired")) {
if (failOnHacknetServer(ctx, server, "getServerNumPortsRequired")) {
return 5;
}
helpers.log(ctx, () => `returned ${server.numOpenPortsRequired} for '${server.hostname}'`);
@ -1466,7 +1476,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
fileExists:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): boolean => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): boolean => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
if (filename === undefined) {
@ -1600,7 +1610,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
// A server cannot delete itself
if (hostname === workerScript.hostname) {
if (hostname === ctx.workerScript.hostname) {
helpers.log(ctx, () => "Cannot delete the server this script is running on.");
return false;
}
@ -1643,10 +1653,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
}
// Wasn't found on home computer
helpers.log(
ctx,
() => `Could not find server ${hostname} as a purchased server. This is a bug. Report to dev.`,
);
helpers.log(ctx, () => `Could not find server ${hostname} as a purchased server. This is a bug. Report to dev.`);
return false;
},
getPurchasedServers: () => (): string[] => {
@ -1695,13 +1702,13 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
);
}
const server = workerScript.getServer();
const server = ctx.workerScript.getServer();
if (server == null) {
throw helpers.makeRuntimeErrorMsg(ctx, "Error getting Server. This is a bug. Report to dev.");
}
if (isScriptFilename(fn)) {
// Write to script
let script = workerScript.getScriptOnServer(fn, server);
let script = ctx.workerScript.getScriptOnServer(fn, server);
if (script == null) {
// Create a new script
script = new Script(Player, fn, String(data), server.hostname, server.scripts);
@ -1771,13 +1778,13 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (isString(port)) {
// Read from script or text file
const fn = port;
const server = GetServer(workerScript.hostname);
const server = GetServer(ctx.workerScript.hostname);
if (server == null) {
throw helpers.makeRuntimeErrorMsg(ctx, "Error getting Server. This is a bug. Report to dev.");
}
if (isScriptFilename(fn)) {
// Read from script
const script = workerScript.getScriptOnServer(fn, server);
const script = ctx.workerScript.getScriptOnServer(fn, server);
if (script == null) {
return "";
}
@ -1810,7 +1817,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (isString(file)) {
// Clear text file
const fn = file;
const server = GetServer(workerScript.hostname);
const server = GetServer(ctx.workerScript.hostname);
if (server == null) {
throw helpers.makeRuntimeErrorMsg(ctx, "Error getting Server. This is a bug. Report to dev.");
}
@ -1839,7 +1846,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
rm:
(ctx: NetscriptContext) =>
(_fn: unknown, _hostname: unknown = workerScript.hostname): boolean => {
(_fn: unknown, _hostname: unknown = ctx.workerScript.hostname): boolean => {
const fn = helpers.string(ctx, "fn", _fn);
const hostname = helpers.string(ctx, "hostname", _hostname);
const s = helpers.getServer(ctx, hostname);
@ -1880,12 +1887,12 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
return suc;
},
getScriptName: () => (): string => {
return workerScript.name;
getScriptName: (ctx: NetscriptContext) => (): string => {
return ctx.workerScript.name;
},
getScriptRam:
(ctx: NetscriptContext) =>
(_scriptname: unknown, _hostname: unknown = workerScript.hostname): number => {
(_scriptname: unknown, _hostname: unknown = ctx.workerScript.hostname): number => {
const scriptname = helpers.string(ctx, "scriptname", _scriptname);
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
@ -1906,14 +1913,14 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
getHackTime:
(ctx: NetscriptContext) =>
(_hostname: unknown = workerScript.hostname): number => {
(_hostname: unknown = ctx.workerScript.hostname): number => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "invalid for this kind of server");
return Infinity;
}
if (failOnHacknetServer(server, "getHackTime")) {
if (failOnHacknetServer(ctx, server, "getHackTime")) {
return Infinity;
}
@ -1921,14 +1928,14 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
getGrowTime:
(ctx: NetscriptContext) =>
(_hostname: unknown = workerScript.hostname): number => {
(_hostname: unknown = ctx.workerScript.hostname): number => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "invalid for this kind of server");
return Infinity;
}
if (failOnHacknetServer(server, "getGrowTime")) {
if (failOnHacknetServer(ctx, server, "getGrowTime")) {
return Infinity;
}
@ -1936,14 +1943,14 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
getWeakenTime:
(ctx: NetscriptContext) =>
(_hostname: unknown = workerScript.hostname): number => {
(_hostname: unknown = ctx.workerScript.hostname): number => {
const hostname = helpers.string(ctx, "hostname", _hostname);
const server = helpers.getServer(ctx, hostname);
if (!(server instanceof Server)) {
helpers.log(ctx, () => "invalid for this kind of server");
return Infinity;
}
if (failOnHacknetServer(server, "getWeakenTime")) {
if (failOnHacknetServer(ctx, server, "getWeakenTime")) {
return Infinity;
}
@ -2039,7 +2046,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
wget:
(ctx: NetscriptContext) =>
async (_url: unknown, _target: unknown, _hostname: unknown = workerScript.hostname): Promise<boolean> => {
async (_url: unknown, _target: unknown, _hostname: unknown = ctx.workerScript.hostname): Promise<boolean> => {
const url = helpers.string(ctx, "url", _url);
const target = helpers.string(ctx, "target", _target);
const hostname = helpers.string(ctx, "hostname", _hostname);
@ -2110,7 +2117,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (typeof f !== "function") {
throw helpers.makeRuntimeErrorMsg(ctx, "argument should be function");
}
workerScript.atExit = () => {
ctx.workerScript.atExit = () => {
f();
}; // Wrap the user function to prevent WorkerScript leaking as 'this'
},
@ -2176,32 +2183,13 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
}
},
flags: Flags(workerScript.args.map((a) => String(a))),
};
flags: Flags,
};
// add undocumented functions
const ns = {
// add undocumented functions
const ns = {
...base,
...NetscriptExtra(Player),
};
function getFunctionNames(obj: object, prefix: string): string[] {
const functionNames: string[] = [];
for (const [key, value] of Object.entries(obj)) {
if (key === "args") {
continue;
} else if (typeof value == "function") {
functionNames.push(prefix + key);
} else if (typeof value == "object") {
functionNames.push(...getFunctionNames(value, key + "."));
}
}
return functionNames;
}
...NetscriptExtra(),
};
const possibleLogs = Object.fromEntries([...getFunctionNames(ns, "")].map((a) => [a, true]));
const wrappedNS = wrapAPI({}, workerScript, ns) as unknown as INS;
(wrappedNS as any).args = ns.args;
(wrappedNS as any).enums = ns.enums;
return wrappedNS;
}
const possibleLogs = Object.fromEntries([...getFunctionNames(ns, "")].map((a) => [a, true]));

@ -1,5 +1,4 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { Bladeburner } from "../Bladeburner/Bladeburner";
import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { Bladeburner as INetscriptBladeburner, BladeburnerCurAction } from "../ScriptEditor/NetscriptDefinitions";
@ -8,7 +7,7 @@ import { InternalAPI, NetscriptContext } from "src/Netscript/APIWrapper";
import { BlackOperation } from "../Bladeburner/BlackOperation";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript): InternalAPI<INetscriptBladeburner> {
export function NetscriptBladeburner(): InternalAPI<INetscriptBladeburner> {
const checkBladeburnerAccess = function (ctx: NetscriptContext, skipjoined = false): void {
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Must have joined bladeburner");
@ -102,7 +101,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.startActionNetscriptFn(player, type, name, workerScript);
return bladeburner.startActionNetscriptFn(player, type, name, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -200,7 +199,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.getActionCountRemainingNetscriptFn(type, name, workerScript);
return bladeburner.getActionCountRemainingNetscriptFn(type, name, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -275,7 +274,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.getSkillLevelNetscriptFn(skillName, workerScript);
return bladeburner.getSkillLevelNetscriptFn(skillName, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -289,7 +288,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.getSkillUpgradeCostNetscriptFn(skillName, count, workerScript);
return bladeburner.getSkillUpgradeCostNetscriptFn(skillName, count, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -303,7 +302,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.upgradeSkillNetscriptFn(skillName, count, workerScript);
return bladeburner.upgradeSkillNetscriptFn(skillName, count, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -317,7 +316,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.getTeamSizeNetscriptFn(type, name, workerScript);
return bladeburner.getTeamSizeNetscriptFn(type, name, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -332,7 +331,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
try {
return bladeburner.setTeamSizeNetscriptFn(type, name, size, workerScript);
return bladeburner.setTeamSizeNetscriptFn(type, name, size, ctx.workerScript);
} catch (e: unknown) {
throw helpers.makeRuntimeErrorMsg(ctx, String(e));
}
@ -394,7 +393,7 @@ export function NetscriptBladeburner(player: IPlayer, workerScript: WorkerScript
checkBladeburnerAccess(ctx, true);
const bladeburner = player.bladeburner;
if (bladeburner === null) throw new Error("Should not be called without Bladeburner");
return bladeburner.joinBladeburnerFactionNetscriptFn(workerScript);
return bladeburner.joinBladeburnerFactionNetscriptFn(ctx.workerScript);
},
joinBladeburnerDivision: (ctx: NetscriptContext) => (): boolean => {
if (player.bitNodeN === 7 || player.sourceFileLvl(7) > 0) {

@ -1,12 +1,11 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { is2DArray } from "../utils/helpers/is2DArray";
import { CodingContract } from "../CodingContracts";
import { CodingAttemptOptions, CodingContract as ICodingContract } from "../ScriptEditor/NetscriptDefinitions";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScript): InternalAPI<ICodingContract> {
export function NetscriptCodingContract(): InternalAPI<ICodingContract> {
const getCodingContract = function (
ctx: NetscriptContext,
func: string,
@ -28,7 +27,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
(
answer: unknown,
_filename: unknown,
_hostname: unknown = workerScript.hostname,
_hostname: unknown = ctx.workerScript.hostname,
{ returnReward }: CodingAttemptOptions = { returnReward: false },
): boolean | string => {
const filename = helpers.string(ctx, "filename", _filename);
@ -78,7 +77,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
},
getContractType:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): string => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): string => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
const contract = getCodingContract(ctx, "getContractType", hostname, filename);
@ -86,7 +85,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
},
getData:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): unknown => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): unknown => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
const contract = getCodingContract(ctx, "getData", hostname, filename);
@ -109,7 +108,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
},
getDescription:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): string => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): string => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
const contract = getCodingContract(ctx, "getDescription", hostname, filename);
@ -117,7 +116,7 @@ export function NetscriptCodingContract(player: IPlayer, workerScript: WorkerScr
},
getNumTriesRemaining:
(ctx: NetscriptContext) =>
(_filename: unknown, _hostname: unknown = workerScript.hostname): number => {
(_filename: unknown, _hostname: unknown = ctx.workerScript.hostname): number => {
const filename = helpers.string(ctx, "filename", _filename);
const hostname = helpers.string(ctx, "hostname", _hostname);
const contract = getCodingContract(ctx, "getNumTriesRemaining", hostname, filename);

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { OfficeSpace } from "../Corporation/OfficeSpace";
import { Employee } from "../Corporation/Employee";
@ -68,7 +68,7 @@ import { BitNodeMultipliers } from "../BitNode/BitNodeMultipliers";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptCorporation(player: IPlayer): InternalAPI<NSCorporation> {
export function NetscriptCorporation(): InternalAPI<NSCorporation> {
function createCorporation(corporationName: string, selfFund = true): boolean {
if (!player.canAccessCorporation() || player.hasCorporation()) return false;
if (!corporationName) return false;

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { Exploit } from "../Exploits/Exploit";
import * as bcrypt from "bcryptjs";
import { Apr1Events as devMenu } from "../ui/Apr1";
@ -16,7 +16,7 @@ export interface INetscriptExtra {
rainbow(guess: string): void;
}
export function NetscriptExtra(player: IPlayer): InternalAPI<INetscriptExtra> {
export function NetscriptExtra(): InternalAPI<INetscriptExtra> {
return {
heart: {
// Easter egg function

@ -1,12 +1,13 @@
import { toNative } from "./toNative";
import libarg from "arg";
import { ScriptArg } from "../Netscript/ScriptArg";
import { NetscriptContext } from "../Netscript/APIWrapper";
type FlagType = StringConstructor | NumberConstructor | BooleanConstructor | StringConstructor[];
type FlagsRet = { [key: string]: ScriptArg };
export function Flags(vargs: string[]): () => (data: unknown) => FlagsRet {
return (/* ctx: NetscriptContext */) =>
(schema: unknown): FlagsRet => {
export function Flags(ctx: NetscriptContext | string[]): (data: unknown) => FlagsRet {
const vargs = Array.isArray(ctx) ? ctx : ctx.workerScript.args;
return (schema: unknown): FlagsRet => {
schema = toNative(schema);
if (!Array.isArray(schema)) throw new Error("flags schema passed in is invalid.");
const args: {

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { calculateServerGrowth } from "../Server/formulas/grow";
import {
calculateMoneyGainRate,
@ -44,7 +44,7 @@ import { repFromDonation } from "../Faction/formulas/donation";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptFormulas(player: IPlayer): InternalAPI<IFormulas> {
export function NetscriptFormulas(): InternalAPI<IFormulas> {
const checkFormulasAccess = function (ctx: NetscriptContext): void {
if (!player.hasProgram(Programs.Formulas.name)) {
throw helpers.makeRuntimeErrorMsg(ctx, `Requires Formulas.exe to run.`);

@ -1,11 +1,10 @@
import { FactionNames } from "../Faction/data/FactionNames";
import { GangConstants } from "../Gang/data/Constants";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { Gang } from "../Gang/Gang";
import { AllGangs } from "../Gang/AllGangs";
import { GangMemberTasks } from "../Gang/GangMemberTasks";
import { GangMemberUpgrades } from "../Gang/GangMemberUpgrades";
import { WorkerScript } from "../Netscript/WorkerScript";
import { GangMember } from "../Gang/GangMember";
import { GangMemberTask } from "../Gang/GangMemberTask";
import { helpers } from "../Netscript/NetscriptHelpers";
@ -22,7 +21,7 @@ import {
} from "../ScriptEditor/NetscriptDefinitions";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): InternalAPI<IGang> {
export function NetscriptGang(): InternalAPI<IGang> {
const checkGangApiAccess = function (ctx: NetscriptContext): void {
const gang = player.gang;
if (gang === null) throw new Error("Must have joined gang");
@ -170,9 +169,9 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
if (gang === null) throw new Error("Should not be called without Gang");
const recruited = gang.recruitMember(memberName);
if (recruited) {
workerScript.log("gang.recruitMember", () => `Successfully recruited Gang Member '${memberName}'`);
ctx.workerScript.log("gang.recruitMember", () => `Successfully recruited Gang Member '${memberName}'`);
} else {
workerScript.log("gang.recruitMember", () => `Failed to recruit Gang Member '${memberName}'`);
ctx.workerScript.log("gang.recruitMember", () => `Failed to recruit Gang Member '${memberName}'`);
}
return recruited;
@ -195,7 +194,7 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
const gang = player.gang;
if (gang === null) throw new Error("Should not be called without Gang");
if (!gang.getAllTaskNames().includes(taskName)) {
workerScript.log(
ctx.workerScript.log(
"gang.setMemberTask",
() =>
`Failed to assign Gang Member '${memberName}' to Invalid task '${taskName}'. '${memberName}' is now Unassigned`,
@ -204,12 +203,12 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
}
const success = member.assignToTask(taskName);
if (success) {
workerScript.log(
ctx.workerScript.log(
"gang.setMemberTask",
() => `Successfully assigned Gang Member '${memberName}' to '${taskName}' task`,
);
} else {
workerScript.log(
ctx.workerScript.log(
"gang.setMemberTask",
() =>
`Failed to assign Gang Member '${memberName}' to '${taskName}' task. '${memberName}' is now Unassigned`,
@ -277,9 +276,9 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
if (!equipment) return false;
const res = member.buyUpgrade(equipment, player, gang);
if (res) {
workerScript.log("gang.purchaseEquipment", () => `Purchased '${equipName}' for Gang member '${memberName}'`);
ctx.workerScript.log("gang.purchaseEquipment", () => `Purchased '${equipName}' for Gang member '${memberName}'`);
} else {
workerScript.log(
ctx.workerScript.log(
"gang.purchaseEquipment",
() => `Failed to purchase '${equipName}' for Gang member '${memberName}'`,
);
@ -296,7 +295,7 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
if (gang === null) throw new Error("Should not be called without Gang");
const member = getGangMember(ctx, memberName);
if (!member.canAscend()) return;
return gang.ascendMember(member, workerScript);
return gang.ascendMember(member, ctx.workerScript);
},
getAscensionResult:
(ctx: NetscriptContext) =>
@ -321,10 +320,10 @@ export function NetscriptGang(player: IPlayer, workerScript: WorkerScript): Inte
if (gang === null) throw new Error("Should not be called without Gang");
if (engage) {
gang.territoryWarfareEngaged = true;
workerScript.log("gang.setTerritoryWarfare", () => "Engaging in Gang Territory Warfare");
ctx.workerScript.log("gang.setTerritoryWarfare", () => "Engaging in Gang Territory Warfare");
} else {
gang.territoryWarfareEngaged = false;
workerScript.log("gang.setTerritoryWarfare", () => "Disengaging in Gang Territory Warfare");
ctx.workerScript.log("gang.setTerritoryWarfare", () => "Disengaging in Gang Territory Warfare");
}
},
getChanceToWinClash:

@ -4,13 +4,13 @@ import { hasAugmentationPrereqs } from "../Faction/FactionHelpers";
import { CityName } from "../Locations/data/CityNames";
import { GraftableAugmentation } from "../PersonObjects/Grafting/GraftableAugmentation";
import { getGraftingAvailableAugs, calculateGraftingTimeWithBonus } from "../PersonObjects/Grafting/GraftingHelpers";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { Grafting as IGrafting } from "../ScriptEditor/NetscriptDefinitions";
import { Router } from "../ui/GameRoot";
import { GraftingWork } from "../Work/GraftingWork";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptGrafting(player: IPlayer): InternalAPI<IGrafting> {
export function NetscriptGrafting(): InternalAPI<IGrafting> {
const checkGraftingAPIAccess = (ctx: NetscriptContext): void => {
if (!player.canAccessGrafting()) {
throw helpers.makeRuntimeErrorMsg(

@ -1,5 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { WorkerScript } from "../Netscript/WorkerScript";
import { Player as player } from "../Player";
import { HacknetServerConstants } from "../Hacknet/data/Constants";
import {
getCostOfNextHacknetNode,
@ -23,7 +22,7 @@ import { Hacknet as IHacknet, NodeStats } from "../ScriptEditor/NetscriptDefinit
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptHacknet(player: IPlayer, workerScript: WorkerScript): InternalAPI<IHacknet> {
export function NetscriptHacknet(): InternalAPI<IHacknet> {
// Utility function to get Hacknet Node object
const getHacknetNode = function (ctx: NetscriptContext, i: number): HacknetNode | HacknetServer {
if (i < 0 || i >= player.hacknetNodes.length) {
@ -128,7 +127,7 @@ export function NetscriptHacknet(player: IPlayer, workerScript: WorkerScript): I
}
const node = getHacknetNode(ctx, i);
if (!(node instanceof HacknetServer)) {
workerScript.log("hacknet.upgradeCache", () => "Can only be called on hacknet servers");
helpers.log(ctx, () => "Can only be called on hacknet servers");
return false;
}
const res = purchaseCacheUpgrade(player, node, n);
@ -171,7 +170,7 @@ export function NetscriptHacknet(player: IPlayer, workerScript: WorkerScript): I
}
const node = getHacknetNode(ctx, i);
if (!(node instanceof HacknetServer)) {
workerScript.log("hacknet.getCacheUpgradeCost", () => "Can only be called on hacknet servers");
helpers.log(ctx, () => "Can only be called on hacknet servers");
return -1;
}
return node.calculateCacheUpgradeCost(n);

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import {
Infiltration as IInfiltration,
@ -20,7 +20,7 @@ import { checkEnum } from "../utils/helpers/checkEnum";
import { LocationName } from "../Locations/data/LocationNames";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptInfiltration(player: IPlayer): InternalAPI<IInfiltration> {
export function NetscriptInfiltration(): InternalAPI<IInfiltration> {
const getLocationsWithInfiltrations = Object.values(Locations).filter(
(location: Location) => location.infiltrationData,
);

@ -1,5 +1,4 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player} from "../Player";
import { purchaseAugmentation, joinFaction, getFactionAugmentationsFiltered } from "../Faction/FactionHelpers";
import { startWorkerScript } from "../NetscriptWorker";
import { Augmentation } from "../Augmentation/Augmentation";
@ -54,7 +53,7 @@ import { FactionWork } from "../Work/FactionWork";
import { FactionWorkType } from "../Work/data/FactionWorkType";
import { CompanyWork } from "../Work/CompanyWork";
export function NetscriptSingularity(player: IPlayer, workerScript: WorkerScript): InternalAPI<ISingularity> {
export function NetscriptSingularity(): InternalAPI<ISingularity> {
const getAugmentation = function (ctx: NetscriptContext, name: string): Augmentation {
if (!augmentationExists(name)) {
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid augmentation: '${name}'`);
@ -235,9 +234,9 @@ export function NetscriptSingularity(player: IPlayer, workerScript: WorkerScript
runAfterReset(cbScript);
}, 0);
// Prevent workerScript from "finishing execution naturally"
workerScript.running = false;
killWorkerScript(workerScript);
// Prevent ctx.workerScript from "finishing execution naturally"
ctx.workerScript.running = false;
killWorkerScript(ctx.workerScript);
},
installAugmentations: (ctx: NetscriptContext) =>
function (_cbScript: unknown = ""): boolean {
@ -255,8 +254,8 @@ export function NetscriptSingularity(player: IPlayer, workerScript: WorkerScript
runAfterReset(cbScript);
}, 0);
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
killWorkerScript(workerScript);
ctx.workerScript.running = false; // Prevent ctx.workerScript from "finishing execution naturally"
killWorkerScript(ctx.workerScript);
return true;
},
@ -1179,7 +1178,7 @@ export function NetscriptSingularity(player: IPlayer, workerScript: WorkerScript
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid crime: '${crimeRoughName}'`);
}
helpers.log(ctx, () => `Attempting to commit ${crime.name}...`);
const crimeTime = crime.commit(player, 1, workerScript);
const crimeTime = crime.commit(player, 1, ctx.workerScript);
if (focus) {
player.startFocusing();
Router.toWork();

@ -1,4 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { findSleevePurchasableAugs } from "../PersonObjects/Sleeve/SleeveHelpers";
import { StaticAugmentations } from "../Augmentation/StaticAugmentations";
import { CityName } from "../Locations/data/CityNames";
@ -19,7 +19,7 @@ import { isSleeveFactionWork } from "../PersonObjects/Sleeve/Work/SleeveFactionW
import { isSleeveCompanyWork } from "../PersonObjects/Sleeve/Work/SleeveCompanyWork";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptSleeve(player: IPlayer): InternalAPI<ISleeve> {
export function NetscriptSleeve(): InternalAPI<ISleeve> {
const checkSleeveAPIAccess = function (ctx: NetscriptContext): void {
if (player.bitNodeN !== 10 && !player.sourceFileLvl(10)) {
throw helpers.makeRuntimeErrorMsg(

@ -1,5 +1,4 @@
import { IPlayer } from "../PersonObjects/IPlayer";
import { WorkerScript } from "../Netscript/WorkerScript";
import { Player as player } from "../Player";
import { staneksGift } from "../CotMG/Helper";
import { Fragments, FragmentById } from "../CotMG/Fragment";
@ -18,7 +17,7 @@ import { joinFaction } from "../Faction/FactionHelpers";
import { Factions } from "../Faction/Factions";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptStanek(player: IPlayer, workerScript: WorkerScript): InternalAPI<IStanek> {
export function NetscriptStanek(): InternalAPI<IStanek> {
function checkStanekAPIAccess(ctx: NetscriptContext): void {
if (!player.hasAugmentation(AugmentationNames.StaneksGift1, true)) {
throw helpers.makeRuntimeErrorMsg(ctx, "Stanek's Gift is not installed");
@ -54,7 +53,7 @@ export function NetscriptStanek(player: IPlayer, workerScript: WorkerScript): In
//Charge the fragment
const time = staneksGift.inBonus() ? 200 : 1000;
return helpers.netscriptDelay(ctx, time).then(function () {
staneksGift.charge(player, fragment, workerScript.scriptRef.threads);
staneksGift.charge(player, fragment, ctx.workerScript.scriptRef.threads);
helpers.log(ctx, () => `Charged fragment with ${ctx.workerScript.scriptRef.threads} threads.`);
return Promise.resolve();
});

@ -1,5 +1,4 @@
import { WorkerScript } from "../Netscript/WorkerScript";
import { IPlayer } from "../PersonObjects/IPlayer";
import { Player as player } from "../Player";
import { buyStock, sellStock, shortStock, sellShort } from "../StockMarket/BuyingAndSelling";
import { StockMarket, SymbolToStockMap, placeOrder, cancelOrder, initStockMarketFn } from "../StockMarket/StockMarket";
import { getBuyTransactionCost, getSellTransactionGain } from "../StockMarket/StockMarketHelpers";
@ -17,7 +16,7 @@ import { StockOrder, TIX } from "../ScriptEditor/NetscriptDefinitions";
import { InternalAPI, NetscriptContext } from "../Netscript/APIWrapper";
import { helpers } from "../Netscript/NetscriptHelpers";
export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript): InternalAPI<TIX> {
export function NetscriptStockMarket(): InternalAPI<TIX> {
/**
* Checks if the player has TIX API access. Throws an error if the player does not
*/
@ -164,7 +163,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
const shares = helpers.number(ctx, "shares", _shares);
checkTixApiAccess(ctx);
const stock = getStockFromSymbol(ctx, symbol);
const res = buyStock(stock, shares, workerScript, {});
const res = buyStock(stock, shares, ctx.workerScript, {});
return res ? stock.getAskPrice() : 0;
},
sellStock:
@ -174,7 +173,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
const shares = helpers.number(ctx, "shares", _shares);
checkTixApiAccess(ctx);
const stock = getStockFromSymbol(ctx, symbol);
const res = sellStock(stock, shares, workerScript, {});
const res = sellStock(stock, shares, ctx.workerScript, {});
return res ? stock.getBidPrice() : 0;
},
@ -193,7 +192,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
}
}
const stock = getStockFromSymbol(ctx, symbol);
const res = shortStock(stock, shares, workerScript, {});
const res = shortStock(stock, shares, ctx.workerScript, {});
return res ? stock.getBidPrice() : 0;
},
@ -212,7 +211,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
}
}
const stock = getStockFromSymbol(ctx, symbol);
const res = sellShort(stock, shares, workerScript, {});
const res = sellShort(stock, shares, ctx.workerScript, {});
return res ? stock.getAskPrice() : 0;
},
@ -259,7 +258,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
throw helpers.makeRuntimeErrorMsg(ctx, `Invalid position type: ${pos}`);
}
return placeOrder(stock, shares, price, orderType, orderPos, workerScript);
return placeOrder(stock, shares, price, orderType, orderPos, ctx.workerScript);
},
cancelOrder:
(ctx: NetscriptContext) =>
@ -315,7 +314,7 @@ export function NetscriptStockMarket(player: IPlayer, workerScript: WorkerScript
type: orderType,
pos: orderPos,
};
return cancelOrder(params, workerScript);
return cancelOrder(params, ctx.workerScript);
},
getOrders: (ctx: NetscriptContext) => (): StockOrder => {
checkTixApiAccess(ctx);

@ -309,7 +309,7 @@ export async function determineAllPossibilitiesForTabCompletion(
return "--" + f[0];
});
try {
return flagFunc()(schema);
return flagFunc(schema);
} catch (err) {
return {};
}