convert to ts

This commit is contained in:
Olivier Gagnon 2021-09-24 17:07:53 -04:00
parent 4f219a3214
commit 413333c919
8 changed files with 62 additions and 55 deletions

@ -2379,7 +2379,6 @@ function applyAugmentation(aug: IPlayerOwnedAugmentation, reapply = false): void
for (const mult in augObj.mults) {
const v = Player.getMult(mult) * augObj.mults[mult];
Player.setMult(mult, v);
console.log(`${mult} ${v}`);
}
// Special logic for NeuroFlux Governor

@ -2,8 +2,9 @@ import { setTimeoutRef } from "./utils/SetTimeoutRef";
import { isString } from "../utils/helpers/isString";
import { AllServers } from "./Server/AllServers";
import { WorkerScript } from "./Netscript/WorkerScript";
export function netscriptDelay(time, workerScript) {
export function netscriptDelay(time: number, workerScript: WorkerScript): Promise<void> {
return new Promise(function (resolve) {
workerScript.delay = setTimeoutRef(() => {
workerScript.delay = null;
@ -13,7 +14,7 @@ export function netscriptDelay(time, workerScript) {
});
}
export function makeRuntimeRejectMsg(workerScript, msg, exp = null) {
export function makeRuntimeRejectMsg(workerScript: WorkerScript, msg: string, exp: any = null) {
var lineNum = "";
if (exp != null) {
var num = getErrorLineNumber(exp, workerScript);
@ -21,13 +22,17 @@ export function makeRuntimeRejectMsg(workerScript, msg, exp = null) {
}
const server = AllServers[workerScript.serverIp];
if (server == null) {
throw new Error(`WorkerScript constructed with invalid server ip: ${this.serverIp}`);
throw new Error(`WorkerScript constructed with invalid server ip: ${workerScript.serverIp}`);
}
return "|" + server.hostname + "|" + workerScript.name + "|" + msg + lineNum;
}
export function resolveNetscriptRequestedThreads(workerScript, functionName, requestedThreads) {
export function resolveNetscriptRequestedThreads(
workerScript: WorkerScript,
functionName: string,
requestedThreads: number,
) {
const threads = workerScript.scriptRef.threads;
if (!requestedThreads) {
return isNaN(threads) || threads < 1 ? 1 : threads;
@ -48,19 +53,22 @@ export function resolveNetscriptRequestedThreads(workerScript, functionName, req
return requestedThreadsAsInt;
}
export function getErrorLineNumber(exp, workerScript) {
var code = workerScript.scriptRef.codeCode();
export function getErrorLineNumber(exp: any, workerScript: WorkerScript): number {
return -1;
// TODO wtf is codeCode?
//Split code up to the start of the node
try {
code = code.substring(0, exp.start);
return (code.match(/\n/g) || []).length + 1;
} catch (e) {
return -1;
}
// var code = workerScript.scriptRef.codeCode();
// //Split code up to the start of the node
// try {
// code = code.substring(0, exp.start);
// return (code.match(/\n/g) || []).length + 1;
// } catch (e) {
// return -1;
// }
}
export function isScriptErrorMessage(msg) {
export function isScriptErrorMessage(msg: string): boolean {
if (!isString(msg)) {
return false;
}

@ -1,8 +1,10 @@
import { makeRuntimeRejectMsg } from "./NetscriptEvaluator";
import { ScriptUrl } from "./Script/ScriptUrl";
import { WorkerScript } from "./Netscript/WorkerScript";
import { Script } from "./Script/Script";
// Makes a blob that contains the code of a given script.
function makeScriptBlob(code) {
function makeScriptBlob(code: string): Blob {
return new Blob([code], { type: "text/javascript" });
}
@ -14,10 +16,11 @@ function makeScriptBlob(code) {
// (i.e. hack, grow, etc.).
// When the promise returned by this resolves, we'll have finished
// running the main function of the script.
export async function executeJSScript(scripts = [], workerScript) {
export async function executeJSScript(scripts: Script[] = [], workerScript: WorkerScript) {
let loadedModule;
let urls = null;
let uurls: ScriptUrl[] = [];
let script = workerScript.getScript();
if (script === null) throw new Error("script is null");
if (shouldCompile(script, scripts)) {
// The URL at the top is the one we want to import. It will
// recursively import all the other modules in the urlStack.
@ -27,31 +30,24 @@ export async function executeJSScript(scripts = [], workerScript) {
// load fully dynamic content. So we hide the import from webpack
// by placing it inside an eval call.
script.markUpdated();
urls = _getScriptUrls(script, scripts, []);
script.url = urls[urls.length - 1].url;
script.module = new Promise((resolve) => resolve(eval("import(urls[urls.length - 1].url)")));
script.dependencies = urls;
uurls = _getScriptUrls(script, scripts, []);
script.url = uurls[uurls.length - 1].url;
script.module = new Promise((resolve) => resolve(eval("import(uurls[uurls.length - 1].url)")));
script.dependencies = uurls;
}
loadedModule = await script.module;
let ns = workerScript.env.vars;
try {
// TODO: putting await in a non-async function yields unhelpful
// "SyntaxError: unexpected reserved word" with no line number information.
if (!loadedModule.main) {
throw makeRuntimeRejectMsg(
workerScript,
`${script.filename} cannot be run because it does not have a main function.`,
);
}
return loadedModule.main(ns);
} finally {
// Revoke the generated URLs
if (urls != null) {
for (const b in urls) URL.revokeObjectURL(b.url);
}
// TODO: putting await in a non-async function yields unhelpful
// "SyntaxError: unexpected reserved word" with no line number information.
if (!loadedModule.main) {
throw makeRuntimeRejectMsg(
workerScript,
`${script.filename} cannot be run because it does not have a main function.`,
);
}
return loadedModule.main(ns);
}
/** Returns whether we should compile the script parameter.
@ -59,7 +55,7 @@ export async function executeJSScript(scripts = [], workerScript) {
* @param {Script} script
* @param {Script[]} scripts
*/
function shouldCompile(script, scripts) {
function shouldCompile(script: Script, scripts: Script[]): boolean {
if (script.module === "") return true;
return script.dependencies.some((dep) => {
const depScript = scripts.find((s) => s.filename == dep.filename);
@ -93,7 +89,7 @@ function shouldCompile(script, scripts) {
* the script parameter.
*/
// BUG: apparently seen is never consulted. Oops.
function _getScriptUrls(script, scripts, seen) {
function _getScriptUrls(script: Script, scripts: Script[], seen: Script[]): ScriptUrl[] {
// Inspired by: https://stackoverflow.com/a/43834063/91401
/** @type {ScriptUrl[]} */
const urlStack = [];

@ -1 +1,2 @@
export declare function startWorkerScript(script: RunningScript, server: BaseServer): boolean;
export declare function prestigeWorkerScripts(): void;

@ -238,7 +238,7 @@ export interface IPlayer {
getIntelligenceBonus(weight: number): number;
getCasinoWinnings(): number;
quitJob(company: string): void;
createHacknetServer(): void;
createHacknetServer(): HacknetServer;
startCreateProgramWork(router: IRouter, programName: string, time: number, reqLevel: number): void;
queueAugmentation(augmentationName: string): void;
receiveInvite(factionName: string): void;

@ -245,7 +245,7 @@ export class PlayerObject implements IPlayer {
getIntelligenceBonus: (weight: number) => number;
getCasinoWinnings: () => number;
quitJob: (company: string) => void;
createHacknetServer: () => void;
createHacknetServer: () => HacknetServer;
startCreateProgramWork: (router: IRouter, programName: string, time: number, reqLevel: number) => void;
queueAugmentation: (augmentationName: string) => void;
receiveInvite: (factionName: string) => void;

2
src/Prestige.d.ts vendored

@ -1,2 +0,0 @@
export declare function prestigeAugmentation(): void;
export declare function prestigeSourceFile(flume: boolean): void;

@ -14,6 +14,7 @@ import { updateHashManagerCapacity } from "./Hacknet/HacknetHelpers";
import { initMessages } from "./Message/MessageHelpers";
import { prestigeWorkerScripts } from "./NetscriptWorker";
import { Player } from "./Player";
import { Router } from "./ui/GameRoot";
import { resetPidCounter } from "./Netscript/Pid";
import { LiteratureNames } from "./Literature/data/LiteratureNames";
@ -31,7 +32,7 @@ import Decimal from "decimal.js";
const BitNode8StartingMoney = 250e6;
// Prestige by purchasing augmentation
function prestigeAugmentation() {
function prestigeAugmentation(): void {
initBitNodeMultipliers(Player);
const maintainMembership = Player.factions.filter(function (faction) {
@ -42,7 +43,7 @@ function prestigeAugmentation() {
// Delete all Worker Scripts objects
prestigeWorkerScripts();
var homeComp = Player.getHomeComputer();
const homeComp = Player.getHomeComputer();
// Delete all servers except home computer
prestigeAllServers();
@ -70,14 +71,14 @@ function prestigeAugmentation() {
initForeignServers(Player.getHomeComputer());
// Gain favor for Companies
for (var member in Companies) {
for (const member in Companies) {
if (Companies.hasOwnProperty(member)) {
Companies[member].gainFavor();
}
}
// Gain favor for factions
for (var member in Factions) {
for (const member in Factions) {
if (Factions.hasOwnProperty(member)) {
Factions[member].gainFavor();
}
@ -86,7 +87,7 @@ function prestigeAugmentation() {
// Stop a Terminal action if there is onerror
if (Engine._actionInProgress) {
Engine._actionInProgress = false;
Terminal.finishAction(true);
Terminal.finishAction(Router, Player, true);
}
// Re-initialize things - This will update any changes
@ -102,8 +103,9 @@ function prestigeAugmentation() {
initMessages();
// Gang
if (Player.inGang()) {
const faction = Factions[Player.gang.facName];
const gang = Player.gang;
if (Player.inGang() && gang !== null) {
const faction = Factions[gang.facName];
if (faction instanceof Faction) {
joinFaction(faction);
}
@ -131,8 +133,12 @@ function prestigeAugmentation() {
// Red Pill
if (augmentationExists(AugmentationNames.TheRedPill) && Augmentations[AugmentationNames.TheRedPill].owned) {
var WorldDaemon = AllServers[SpecialServerIps[SpecialServerNames.WorldDaemon]];
var DaedalusServer = AllServers[SpecialServerIps[SpecialServerNames.DaedalusServer]];
const WorldDaemonIP = SpecialServerIps[SpecialServerNames.WorldDaemon];
if (typeof WorldDaemonIP !== "string") throw new Error("WorldDaemonIP should be string");
const WorldDaemon = AllServers[WorldDaemonIP];
const DaedalusServerIP = SpecialServerIps[SpecialServerNames.DaedalusServer];
if (typeof DaedalusServerIP !== "string") throw new Error("DaedalusServerIP should be string");
const DaedalusServer = AllServers[DaedalusServerIP];
if (WorldDaemon && DaedalusServer) {
WorldDaemon.serversOnNetwork.push(DaedalusServer.ip);
DaedalusServer.serversOnNetwork.push(WorldDaemon.ip);
@ -143,7 +149,7 @@ function prestigeAugmentation() {
}
// Prestige by destroying Bit Node and gaining a Source File
function prestigeSourceFile(flume) {
function prestigeSourceFile(flume: boolean): void {
initBitNodeMultipliers(Player);
updateSourceFileFlags(Player);
@ -191,7 +197,7 @@ function prestigeSourceFile(flume) {
// Stop a Terminal action if there is one
if (Engine._actionInProgress) {
Engine._actionInProgress = false;
Terminal.finishAction(true);
Terminal.finishAction(Router, Player, true);
}
// Delete all Augmentations
@ -249,7 +255,6 @@ function prestigeSourceFile(flume) {
deleteStockMarket();
}
if (Player.inGang()) clearGangUI();
Player.gang = null;
Player.corporation = null;
resetIndustryResearchTrees();