diff options
author | Julien Dessaux | 2024-03-21 17:08:37 +0100 |
---|---|---|
committer | Julien Dessaux | 2024-03-27 15:21:00 +0100 |
commit | d668eac4a63a9aa98c3efff395faa23cfcea1c1b (patch) | |
tree | 691e3bb471bcacadb975f581f73e09b84287b4a5 /nodejs | |
parent | [javascript] fixed mining loop (diff) | |
download | spacetraders-d668eac4a63a9aa98c3efff395faa23cfcea1c1b.tar.gz spacetraders-d668eac4a63a9aa98c3efff395faa23cfcea1c1b.tar.bz2 spacetraders-d668eac4a63a9aa98c3efff395faa23cfcea1c1b.zip |
[node] begin the great typescript rewrite
Diffstat (limited to 'nodejs')
30 files changed, 877 insertions, 664 deletions
diff --git a/nodejs/.eslintrc.json b/nodejs/.eslintrc.json deleted file mode 100644 index 47dd5e6..0000000 --- a/nodejs/.eslintrc.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "env": { - "es2021": true, - "node": true - }, - "extends": [ - "eslint:recommended", - "plugin:node/recommended" - ], - "overrides": [ - { - "files": ["*.js"], - "rules": { - "no-constant-condition": "off" - } - } - ], - "parserOptions": { - "ecmaVersion": "latest", - "sourceType": "module" - }, - "rules": { - "indent": [ - "error", - "tab" - ], - "linebreak-style": [ - "error", - "unix" - ], - "quotes": [ - "error", - "single" - ], - "semi": [ - "error", - "always" - ], - "node/no-unsupported-features/es-syntax": [ - "error", - { "ignores": ["modules"] } - ] - } -} diff --git a/nodejs/automation/contracting.js b/nodejs/automation/contracting.js deleted file mode 100644 index 19183fb..0000000 --- a/nodejs/automation/contracting.js +++ /dev/null @@ -1,71 +0,0 @@ -import * as mining from './mining.js'; -import * as selling from './selling.js'; -import * as dbContracts from '../database/contracts.js'; -import * as dbShips from '../database/ships.js'; -import * as api from '../lib/api.js'; -import * as contracts from '../lib/contracts.js'; -import * as libShips from '../lib/ships.js'; -import * as systems from '../lib/systems.js'; -import * as utils from '../lib/utils.js'; - -export async function init() { - const cs = dbContracts.getContracts(); - cs.forEach(contract => run(contract)); -} - -async function run(contract) { - await contracts.accept({id: contract.id}); - const contractSystem = utils.systemFromWaypoint(contract.terms.deliver[0].destinationSymbol); - let ships = dbShips.getShipsAt(contractSystem); - ships = ships.filter(ship => ship.registration.role !== 'SATELLITE'); // filter out probes - - switch(contract.type) { - case 'PROCUREMENT': - await runProcurement(contract, ships); - break; - default: - throw `Handling of contract type ${contract.type} is not implemented yet`; - } -} - -async function runProcurement(contract, ships) { - // TODO check if contract is fulfilled! - const wantedCargo = contract.terms.deliver[0].tradeSymbol; - const deliveryPoint = contract.terms.deliver[0].destinationSymbol; - const asteroids = await systems.type({symbol: ships[0].nav.systemSymbol, type: 'ENGINEERED_ASTEROID'}); - const asteroidSymbol = asteroids[0].symbol; - ships.forEach(async function(ship) { - while (!dbContracts.getContract(contract.id).fulfilled) { - ship = dbShips.getShip(ship.symbol); - let goodCargo = ship.cargo.inventory.filter(i => i.symbol === wantedCargo)[0]; - // If we are in transit, we wait until we arrive - const delay = new Date(ship.nav.route.arrival) - new Date(); - if (delay > 0) await api.sleep(delay); - // Then it depends on where we are - switch (ship.nav.waypointSymbol) { - case asteroidSymbol: - await mining.mineUntilFullOf({ - asteroidSymbol: asteroidSymbol, - good: wantedCargo, - symbol: ship.symbol - }); - await libShips.navigate({symbol: ship.symbol, waypoint: deliveryPoint}); - break; - case deliveryPoint: - if (goodCargo !== undefined) { // we could be here if a client restart happens right after selling before we navigate away - console.log(`delivering ${goodCargo.units} of ${wantedCargo}`); - if (await contracts.deliver({id: contract.id, symbol: ship.symbol, good: wantedCargo, units: goodCargo.units })) { - break; - } - } - await libShips.navigate({symbol: ship.symbol, waypoint: asteroidSymbol}); - break; - default: - // we were either selling or started contracting - await selling.sell(ship, wantedCargo); - await libShips.navigate({symbol: ship.symbol, waypoint: asteroidSymbol}); - } - } - // TODO repurpose the ship - }); -} diff --git a/nodejs/automation/contracting.ts b/nodejs/automation/contracting.ts new file mode 100644 index 0000000..2857778 --- /dev/null +++ b/nodejs/automation/contracting.ts @@ -0,0 +1,72 @@ +import { Contract } from '../model/contract.ts'; +import { Ship } from '../model/ship.ts'; +import * as mining from './mining.js'; +import * as selling from './selling.js'; +import * as dbContracts from '../database/contracts.ts'; +import * as dbShips from '../database/ships.ts'; +import * as api from '../lib/api.ts'; +import * as contracts from '../lib/contracts.ts'; +import * as libShips from '../lib/ships.ts'; +import * as systems from '../lib/systems.ts'; +import * as utils from '../lib/utils.ts'; + +export async function init() { + const cs = dbContracts.getContracts(); + cs.forEach(contract => run(contract)); +} + +async function run(contract: Contract) { + await contracts.accept(contract); + const contractSystem = utils.systemFromWaypoint(contract.terms.deliver[0].destinationSymbol); + let ships = dbShips.getShipsAt(contractSystem); + ships = ships.filter(ship => ship.registration.role !== 'SATELLITE'); // filter out probes + + switch(contract.type) { + case 'PROCUREMENT': + await runProcurement(contract, ships); + break; + default: + throw `Handling of contract type ${contract.type} is not implemented yet`; + } +} + +async function runProcurement(contract: Contract, ships: Array<Ship>) { + // TODO check if contract is fulfilled! + const wantedCargo = contract.terms.deliver[0].tradeSymbol; + const deliveryPoint = contract.terms.deliver[0].destinationSymbol; + const asteroids = await systems.type({symbol: ships[0].nav.systemSymbol, type: 'ENGINEERED_ASTEROID'}); + const asteroidSymbol = asteroids[0].symbol; + ships.forEach(async function(ship) { + while (!contract.fulfilled) { + ship = dbShips.getShip(ship.symbol) as Ship; + let goodCargo = ship.cargo.inventory.filter(i => i.symbol === wantedCargo)[0] + // If we are in transit, we wait until we arrive + const delay = new Date(ship.nav.route.arrival).getTime() - new Date().getTime(); + if (delay > 0) await api.sleep(delay); + // Then it depends on where we are + switch (ship.nav.waypointSymbol) { + case asteroidSymbol: + await mining.mineUntilFullOf({ + asteroidSymbol: asteroidSymbol, + good: wantedCargo, + symbol: ship.symbol + }); + await libShips.navigate(ship, deliveryPoint); + break; + case deliveryPoint: + if (goodCargo !== undefined) { // we could be here if a client restart happens right after selling before we navigate away + console.log(`delivering ${goodCargo.units} of ${wantedCargo}`); + contract = await contracts.deliver(contract, ship); + if (contract.fulfilled) break; + } + await libShips.navigate(ship, asteroidSymbol); + break; + default: + // we were either selling or started contracting + await selling.sell(ship, wantedCargo); + await libShips.navigate(ship, asteroidSymbol); + } + } + // TODO repurpose the ship + }); +} diff --git a/nodejs/automation/init.js b/nodejs/automation/init.js index b921942..93e5a70 100644 --- a/nodejs/automation/init.js +++ b/nodejs/automation/init.js @@ -6,6 +6,8 @@ import * as dbTokens from '../database/tokens.js'; import * as api from '../lib/api.js'; import * as ships from '../lib/ships.js'; +const symbol = process.env.NODE_ENV === 'test' ? 'ADYXAX-0' : 'ADYXAX-TS'; + // This function registers then inits the database export async function init() { const response = await fetch('https://api.spacetraders.io/v2/register', { @@ -14,7 +16,7 @@ export async function init() { 'Content-Type': 'application/json', }, body: JSON.stringify({ - symbol: "ADYXAX-JS", + symbol: symbol, faction: "COSMIC", }), }); diff --git a/nodejs/automation/selling.js b/nodejs/automation/selling.js index b52d52c..3d444af 100644 --- a/nodejs/automation/selling.js +++ b/nodejs/automation/selling.js @@ -8,65 +8,65 @@ import * as utils from '../lib/utils.js'; // example ctx { ship: {XXX}, keep: 'SILVER_ORE' } export async function sell(ship, keep) { outer: while(true) { - // first lets see what we want to sell - let cargo = utils.categorizeCargo(ship.cargo, keep); - // get the marketdata from our location - const market = await libSystems.market(ship.nav.waypointSymbol); - // can we sell anything here? - const goods = whatCanBeTradedAt(cargo.goods, market.imports.concat(market.exchange)); - for (let i = 0; i < goods.length; i++) { - const symbol = goods[i].symbol; - await libShips.sell({ - good: symbol, - symbol: ship.symbol, - units: cargo.goods[symbol], - }); - delete cargo.goods[symbol]; - }; - // are we done selling everything we can? - ship = dbShips.getShip(ship.symbol); - cargo = utils.categorizeCargo(ship.cargo, keep); - if (Object.keys(cargo.goods).length === 0) { - return; - } - // we need to move somewhere else to sell our remaining goods - // first we look into markets in our system - const rawMarkets = await libSystems.trait({symbol: ship.nav.systemSymbol, trait: 'MARKETPLACE'}); - // sorted by distance from where we are - const markets = rawMarkets.map(function (m) { return { - data: m, - distance: (m.x - ship.nav.route.destination.x) ** 2 + (m.y - ship.nav.route.destination.y) ** 2, - }}); - markets.sort(function(a, b) { - if (a.distance < b.distance) { - return -1; - } else if (a.distance > b.distance) { - return 1; - } - return 0; - }); - // check from the closest one if they import what we need to sell - for (let i = 0; i < markets.length; i++) { - const waypointSymbol = markets[i].data.symbol; - const market = await libSystems.market(waypointSymbol); - // if we have no data on the market we need to go there and see - // and if we have data and can sell there we need to go too - if (market === null || whatCanBeTradedAt(cargo.goods, market.imports).length > 0) { - await libShips.navigate({symbol: ship.symbol, waypoint: waypointSymbol}); - continue outer; - } - } - // check from the closest one if they exchange what we need to sell - for (let i = 0; i < markets.length; i++) { - const waypointSymbol = markets[i].data.symbol; - const market = await libSystems.market(waypointSymbol); - // if we can sell there we need to go - if (whatCanBeTradedAt(cargo.goods, market.exchange).length > 0) { - await libShips.navigate({symbol: ship.symbol, waypoint: waypointSymbol}); - continue outer; - } - } - throw new Error(`Ship {ship.symbol} has found no importing or exchanging market for its cargo in the system`); + // first lets see what we want to sell + let cargo = utils.categorizeCargo(ship.cargo, keep); + // get the marketdata from our location + const market = await libSystems.market(ship.nav.waypointSymbol); + // can we sell anything here? + const goods = whatCanBeTradedAt(cargo.goods, market.imports.concat(market.exchange)); + for (let i = 0; i < goods.length; i++) { + const symbol = goods[i].symbol; + await libShips.sell({ + good: symbol, + symbol: ship.symbol, + units: cargo.goods[symbol], + }); + delete cargo.goods[symbol]; + }; + // are we done selling everything we can? + ship = dbShips.getShip(ship.symbol); + cargo = utils.categorizeCargo(ship.cargo, keep); + if (Object.keys(cargo.goods).length === 0) { + return; + } + // we need to move somewhere else to sell our remaining goods + // first we look into markets in our system + const rawMarkets = await libSystems.trait({symbol: ship.nav.systemSymbol, trait: 'MARKETPLACE'}); + // sorted by distance from where we are + const markets = rawMarkets.map(function (m) { return { + data: m, + distance: (m.x - ship.nav.route.destination.x) ** 2 + (m.y - ship.nav.route.destination.y) ** 2, + }}); + markets.sort(function(a, b) { + if (a.distance < b.distance) { + return -1; + } else if (a.distance > b.distance) { + return 1; + } + return 0; + }); + // check from the closest one if they import what we need to sell + for (let i = 0; i < markets.length; i++) { + const waypointSymbol = markets[i].data.symbol; + const market = await libSystems.market(waypointSymbol); + // if we have no data on the market we need to go there and see + // and if we have data and can sell there we need to go too + if (market === null || whatCanBeTradedAt(cargo.goods, market.imports).length > 0) { + await libShips.navigate({symbol: ship.symbol, waypoint: waypointSymbol}); + continue outer; + } + } + // check from the closest one if they exchange what we need to sell + for (let i = 0; i < markets.length; i++) { + const waypointSymbol = markets[i].data.symbol; + const market = await libSystems.market(waypointSymbol); + // if we can sell there we need to go + if (whatCanBeTradedAt(cargo.goods, market.exchange).length > 0) { + await libShips.navigate({symbol: ship.symbol, waypoint: waypointSymbol}); + continue outer; + } + } + throw new Error(`Ship {ship.symbol} has found no importing or exchanging market for its cargo in the system`); } } diff --git a/nodejs/database/agents.js b/nodejs/database/agents.js deleted file mode 100644 index 8b7203b..0000000 --- a/nodejs/database/agents.js +++ /dev/null @@ -1,21 +0,0 @@ -import db from './db.js'; - -const addAgentStatement = db.prepare(`INSERT INTO agents(data) VALUES (json(?));`); -const getAgentStatement = db.prepare(`SELECT data FROM agents;`); -const setAgentStatement = db.prepare(`UPDATE agents SET data = json(?);`); - -export function addAgent(agent) { - return addAgentStatement.run(JSON.stringify(agent)).lastInsertRowid; -} - -export function getAgent() { - const data = getAgentStatement.get(); - if (data === undefined) { - return null; - } - return JSON.parse(data.data); -} - -export function setAgent(agent) { - return setAgentStatement.run(JSON.stringify(agent)).changes; -} diff --git a/nodejs/database/agents.ts b/nodejs/database/agents.ts new file mode 100644 index 0000000..41b956a --- /dev/null +++ b/nodejs/database/agents.ts @@ -0,0 +1,20 @@ +import { Agent } from '../model/agent.ts'; +import db from './db.js'; + +const addAgentStatement = db.prepare(`INSERT INTO agents(data) VALUES (json(?));`); +const getAgentStatement = db.prepare(`SELECT data FROM agents;`); +const setAgentStatement = db.prepare(`UPDATE agents SET data = json(?);`); + +export function addAgent(agent: Agent) { + addAgentStatement.run(JSON.stringify(agent)); +} + +export function getAgent(): Agent|null { + const data = getAgentStatement.get() as {data: string}|undefined; + if (!data) return null; + return JSON.parse(data.data); +} + +export function setAgent(agent: Agent) { + setAgentStatement.run(JSON.stringify(agent)); +} diff --git a/nodejs/database/contracts.js b/nodejs/database/contracts.ts index d7f9aab..576f8dd 100644 --- a/nodejs/database/contracts.js +++ b/nodejs/database/contracts.ts @@ -1,30 +1,29 @@ -import db from './db.js'; +import { Contract } from '../model/contract.ts'; +import db from './db.ts'; const addContractStatement = db.prepare(`INSERT INTO contracts(data) VALUES (json(?));`); const getContractStatement = db.prepare(`SELECT data FROM contracts WHERE data->>'id' = ?;`); const getContractsStatement = db.prepare(`SELECT data FROM contracts WHERE data->>'fulfilled' = false;`); const updateContractStatement = db.prepare(`UPDATE contracts SET data = json(:data) WHERE data->>'id' = :id;`); -export function getContract(id) { - const data = getContractStatement.get(id); - if (data === undefined) { - return null; - } +export function getContract(id: string): Contract|null { + const data = getContractStatement.get(id) as {data: string}|undefined; + if (!data) return null; return JSON.parse(data.data); } -export function getContracts() { - const data = getContractsStatement.all(); +export function getContracts(): Array<Contract> { + const data = getContractsStatement.all() as Array<{data: string}>; return data.map(contractData => JSON.parse(contractData.data)); } -export function setContract(data) { +export function setContract(data: Contract) { if (getContract(data.id) === null) { - return addContractStatement.run(JSON.stringify(data)).lastInsertRowid; + addContractStatement.run(JSON.stringify(data)); } else { - return updateContractStatement.run({ + updateContractStatement.run({ data: JSON.stringify(data), id: data.id, - }).changes; + }); } } diff --git a/nodejs/database/db.js b/nodejs/database/db.ts index 4438fec..247ee5a 100644 --- a/nodejs/database/db.js +++ b/nodejs/database/db.ts @@ -11,7 +11,7 @@ const allMigrations = [ const db = new Database( process.env.NODE_ENV === 'test' ? 'test.db' : 'spacetraders.db', - process.env.NODE_ENV === 'development' ? { verbose: console.log } : null + process.env.NODE_ENV === 'development' ? { verbose: console.log } : undefined ); db.pragma('foreign_keys = ON'); db.pragma('journal_mode = WAL'); @@ -20,7 +20,8 @@ function init() { db.transaction(function migrate() { let version; try { - version = db.prepare('SELECT version FROM schema_version').get().version; + const res = db.prepare('SELECT version FROM schema_version').get() as {version: number}; + version = res.version; } catch { version = 0; } @@ -34,10 +35,10 @@ function init() { } export function reset() { - const indices = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'index';`).all(); - const tables = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table';`).all(); - const triggers = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'trigger';`).all(); - const views = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'view';`).all(); + const indices = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'index';`).all() as Array<{name: string}>; + const tables = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'table';`).all() as Array<{name: string}>; + const triggers = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'trigger';`).all() as Array<{name: string}>; + const views = db.prepare(`SELECT name FROM sqlite_master WHERE type = 'view';`).all() as Array<{name: string}>; indices.forEach(elt => db.exec(`DROP INDEX ${elt.name};`)); tables.forEach(elt => db.exec(`DROP TABLE ${elt.name};`)); triggers.forEach(elt => db.exec(`DROP TRIGGER ${elt.name};`)); diff --git a/nodejs/database/ships.js b/nodejs/database/ships.ts index f9eb668..58c8abf 100644 --- a/nodejs/database/ships.js +++ b/nodejs/database/ships.ts @@ -1,4 +1,6 @@ -import db from './db.js'; +import db from './db.ts'; +import { Cargo } from '../model/cargo.ts'; +import { Fuel, Nav, Ship } from '../model/ship.ts'; const addShipStatement = db.prepare(`INSERT INTO ships(data) VALUES (json(?));`); const getShipStatement = db.prepare(`SELECT data FROM ships WHERE data->>'symbol' = ?;`); @@ -8,51 +10,46 @@ const setShipFuelStatement = db.prepare(`UPDATE ships SET data = (SELECT json_se const setShipNavStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.nav', json(:nav)) FROM ships WHERE data->>'symbol' = :symbol) WHERE data->>'symbol' = :symbol;`); const updateShipStatement = db.prepare(`UPDATE ships SET data = json(:data) WHERE data->>'symbol' = :symbol;`); -export function getShip(symbol) { - const data = getShipStatement.get(symbol); - if (data === undefined) { - return null; - } +export function getShip(symbol: string): Ship|null { + const data = getShipStatement.get(symbol) as {data: string}|undefined; + if (!data) return null; return JSON.parse(data.data); } -export function getShipsAt(symbol) { - const data = getShipsAtStatement.all(symbol); - if (data === undefined) { - return null; - } +export function getShipsAt(symbol: string) { + const data = getShipsAtStatement.all(symbol) as Array<{data: string}>; return data.map(elt => JSON.parse(elt.data)); } -export function setShip(data) { +export function setShip(data: Ship) { if (getShip(data.symbol) === null) { - return addShipStatement.run(JSON.stringify(data)).lastInsertRowid; + addShipStatement.run(JSON.stringify(data)); } else { - return updateShipStatement.run({ + updateShipStatement.run({ data: JSON.stringify(data), symbol: data.symbol, - }).changes; + }); } } -export function setShipCargo(symbol, cargo) { - return setShipCargoStatement.run({ +export function setShipCargo(symbol: string, cargo: Cargo) { + setShipCargoStatement.run({ cargo: JSON.stringify(cargo), symbol: symbol, - }).changes; + }); } -export function setShipFuel(symbol, fuel) { - return setShipFuelStatement.run({ +export function setShipFuel(symbol: string, fuel: Fuel) { + setShipFuelStatement.run({ fuel: JSON.stringify(fuel), symbol: symbol, - }).changes; + }); } -export function setShipNav(symbol, nav) { - return setShipNavStatement.run({ +export function setShipNav(symbol: string, nav: Nav) { + setShipNavStatement.run({ nav: JSON.stringify(nav), symbol: symbol, - }).changes; + }); } diff --git a/nodejs/database/tokens.js b/nodejs/database/tokens.js deleted file mode 100644 index 2a781af..0000000 --- a/nodejs/database/tokens.js +++ /dev/null @@ -1,16 +0,0 @@ -import db from './db.js'; - -const addTokenStatement = db.prepare(`INSERT INTO tokens(data) VALUES (?);`); -const getTokenStatement = db.prepare(`SELECT data FROM tokens;`); - -export function addToken(token) { - return addTokenStatement.run(token).lastInsertRowid; -} - -export function getToken() { - const data = getTokenStatement.get(); - if (data === undefined) { - return null; - } - return data.data; -} diff --git a/nodejs/database/tokens.ts b/nodejs/database/tokens.ts new file mode 100644 index 0000000..4495a65 --- /dev/null +++ b/nodejs/database/tokens.ts @@ -0,0 +1,14 @@ +import db from './db.ts'; + +const addTokenStatement = db.prepare(`INSERT INTO tokens(data) VALUES (?);`); +const getTokenStatement = db.prepare(`SELECT data FROM tokens;`); + +export function addToken(token: string) { + addTokenStatement.run(token); +} + +export function getToken(): string|null { + const data = getTokenStatement.get() as {data: string}|undefined; + if (data === undefined) return null; + return data.data; +} diff --git a/nodejs/lib/api.js b/nodejs/lib/api.ts index ecb0282..08c6c71 100644 --- a/nodejs/lib/api.js +++ b/nodejs/lib/api.ts @@ -1,8 +1,9 @@ import * as fs from 'fs'; import * as events from 'events'; -import { getToken } from '../database/tokens.js'; -import { PriorityQueue } from './priority_queue.js'; +import { APIError, Request, RequestPromise, Response } from '../model/api.ts'; +import { getToken } from '../database/tokens.ts'; +import { PriorityQueue } from './priority_queue.ts'; // queue processor module variables const bus = new events.EventEmitter(); // a bus to notify the queue processor to start processing messages @@ -10,10 +11,9 @@ let busy = false; // true if we are already sending api requests. let backoffSeconds = 0; let running = false; // other module variables -let headers = undefined; // a file scoped variable so that we only evaluate these once. +let headers: {[key:string]:string}|null = null; // a file scoped variable so that we only evaluate these once. let queue = new PriorityQueue(); // a priority queue to hold api calls we want to send, allows for throttling. -// a single queue processor should be running at any time, otherwise there will be trouble! async function queue_processor() { if (running) { throw 'refusing to start a second queue processor'; @@ -30,9 +30,10 @@ async function queue_processor() { await new Promise(resolve => bus.once('send', resolve)); busy = true; } - const before = new Date(); - await send_this(queue.dequeue().element); - const duration = new Date() - before; + const before = new Date().getTime(); + const data = queue.dequeue() as RequestPromise<unknown>; + await send_this(data); + const duration = new Date().getTime() - before; if (duration < 400) { // 333 should work, but 400 should still allow some manual requests to go through during development await sleep(400 - duration); } @@ -44,21 +45,17 @@ async function queue_processor() { } queue_processor(); -// send takes a request object as argument and an optional context ctx -// example request: { -// endpoint: the path part of the url to call, -// method: HTTP method for `fetch` call, defaults to 'GET', -// page: run a paginated request starting from this page until all the following pages are fetched -// payload: optional json object that will be send along with the request, -// priority: optional priority value (defaults to 10, lower than 10 means the message will be sent faster) -// } -export async function send(request, ctx) { - if (request.page === undefined) { - return await send_one(request, ctx); - } - let ret = []; +export async function send<T>(request: Request): Promise<T|APIError> { + const response = await send_one<T>(request); + if (response.error) return response.error; + return response.data; +} + +export async function sendPaginated<T>(request: Request): Promise<Array<T>|APIError> { + if (request.page === undefined) request.page = 1; + let ret: Array<T> = []; while (true) { - const response = await send_one(request, ctx); + const response = await send_one<T>(request); if (response.meta === undefined) { throw {"message": "paginated request did not return a meta block", "request": request, "response": response}; } @@ -70,10 +67,9 @@ export async function send(request, ctx) { } } -function send_one(request, ctx) { +function send_one<T>(request: Request): Promise<Response<T>> { return new Promise((resolve, reject) => { - let data = { - ctx: ctx, + const data: RequestPromise<T> = { reject: reject, request: request, resolve: resolve, @@ -86,8 +82,8 @@ function send_one(request, ctx) { } // send_this take a data object as argument built in the send function above -async function send_this(data) { - if (headers === undefined) { +async function send_this(data: RequestPromise<unknown>) { + if (headers === null) { const token = getToken(); if (token === null) { throw 'Could not get token from the database. Did you init or register yet?'; @@ -97,7 +93,7 @@ async function send_this(data) { 'Authorization': `Bearer ${token}` }; } - let options = { + let options: {[key:string]:any} = { headers: headers, }; if (data.request.method !== undefined) { @@ -112,52 +108,53 @@ async function send_this(data) { } fs.writeFileSync('log', JSON.stringify({event: 'send', date: new Date(), data: data}) + '\n', {flag: 'a+'}); try { - let response = await fetch(`https://api.spacetraders.io/v2${data.request.endpoint}${pagination}`, options); - response = await response.json(); - switch(response.error?.code) { - case 401: // TODO 401 means a server reset happened - throw response; - // TODO reject all promises in queue - // reset database - // logrotate - // spawnSync? - // break; - case 429: // 429 means rate limited, let's hold back as instructed - backoffSeconds = response.error.data.retryAfter; - queue.enqueue(data, 1); - break; - case 503: // 503 means maintenance mode, let's hold back for 1 minute - backoffSeconds = 60; - queue.enqueue(data, 1); - break; - default: // no error! - fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'}); - return data.resolve(response); + const response = await fetch(`https://api.spacetraders.io/v2${data.request.endpoint}${pagination}`, options); + const json = await response.json() as Response<unknown>; + switch(json.error?.code) { + case 401: // TODO 401 means a server reset happened + throw json; + // TODO reject all promises in queue + // reset database + // logrotate + // spawnSync? + // break; + case 429: // 429 means rate limited, let's hold back as instructed + backoffSeconds = json.error.data.retryAfter; + queue.enqueue(data, 1); + break; + case 503: // 503 means maintenance mode, let's hold back for 1 minute + backoffSeconds = 60; + queue.enqueue(data, 1); + break; + default: // no error! + fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: json}) + '\n', {flag: 'a+'}); + return data.resolve(json); } - } catch (err) { + } catch (_err) { + const err = _err as {cause?: {code: string}}; fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: err}) + '\n', {flag: 'a+'}); switch(err.cause?.code) { - case 'EAI_AGAIN': // DNS lookup timed out error, let's hold back for 5 seconds - backoffSeconds = 5; - queue.enqueue(data, 1); - break; - case 'ECONNRESET': - queue.enqueue(data, 1); - break; - case 'UND_ERR_CONNECT_TIMEOUT': - queue.enqueue(data, 1); - break; - default: - data.reject(err); + case 'EAI_AGAIN': // DNS lookup timed out error, let's hold back for 5 seconds + backoffSeconds = 5; + queue.enqueue(data, 1); + break; + case 'ECONNRESET': + queue.enqueue(data, 1); + break; + case 'UND_ERR_CONNECT_TIMEOUT': + queue.enqueue(data, 1); + break; + default: + data.reject(err); } } } -export function debugLog(ctx) { +export function debugLog(ctx: any) { console.log(`--- ${Date()} -----------------------------------------------------------------------------`); console.log(JSON.stringify(ctx, null, 2)); } -export function sleep(delay) { - return new Promise((resolve) => setTimeout(resolve, delay)) +export function sleep(delay: number): Promise<unknown> { + return new Promise((resolve) => setTimeout(resolve, delay)); } diff --git a/nodejs/lib/contracts.js b/nodejs/lib/contracts.js deleted file mode 100644 index 9718f99..0000000 --- a/nodejs/lib/contracts.js +++ /dev/null @@ -1,68 +0,0 @@ -import * as dbAgents from '../database/agents.js'; -import * as dbContracts from '../database/contracts.js'; -import * as api from './api.js'; -import * as dbShips from '../database/ships.js'; -import * as libShips from '../lib/ships.js'; - -export async function accept(ctx) { - const contract = dbContracts.getContract(ctx.id); - if (contract.accepted) { - return; - } - await api.send({endpoint: `/my/contracts/${ctx.id}/accept`, method: 'POST'}); - contract.accepted = true; - dbContracts.setContract(contract); -} - -export async function contracts() { - const contracts = await api.send({endpoint: '/my/contracts', page: 1}); - contracts.forEach(contract => dbContracts.setContract(contract)); - return contracts; -} - -// returns true if the contract has been fulfilled -export async function deliver(ctx) { - const contract = dbContracts.getContract(ctx.id); - if (contract.terms.deliver[0].unitsRequired === contract.terms.deliver[0].unitsFulfilled) { - await fulfill(ctx); - return true; - } - await libShips.dock(ctx); - const response = await api.send({ endpoint: `/my/contracts/${ctx.id}/deliver`, method: 'POST', payload: { - shipSymbol: ctx.symbol, - tradeSymbol: ctx.good, - units: ctx.units, - }}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4509: // contract delivery terms have been met - await fulfill(ctx); - return true; - default: // yet unhandled error - api.debugLog(response); - throw response; - } - } - dbContracts.setContract(response.data.contract); - dbShips.setShipCargo(ctx.symbol, response.data.cargo); - // TODO track credits - if(response.data.contract.terms.deliver[0].unitsRequired === response.data.contract.terms.deliver[0].unitsFulfilled) { - await fulfill(ctx); - return true; - } - return false; -} - -export async function fulfill(ctx) { - const contract = dbContracts.getContract(ctx.id); - if (contract.fulfilled) { - return; - } - const response = await api.send({ endpoint: `/my/contracts/${ctx.id}/fulfill`, method: 'POST'}); - if (response.error !== undefined) { - api.debugLog(response); - throw response; - } - dbAgents.setAgent(response.data.agent); - dbContracts.setContract(response.data.contract); -} diff --git a/nodejs/lib/contracts.ts b/nodejs/lib/contracts.ts new file mode 100644 index 0000000..fb62813 --- /dev/null +++ b/nodejs/lib/contracts.ts @@ -0,0 +1,74 @@ +import { Agent } from '../model/agent.ts'; +import { APIError } from '../model/api.ts'; +import { Cargo } from '../model/cargo.ts'; +import { Contract } from '../model/contract.ts'; +import { Ship } from '../model/ship.ts'; +import * as dbAgents from '../database/agents.ts'; +import * as dbContracts from '../database/contracts.ts'; +import * as api from './api.ts'; +import * as dbShips from '../database/ships.ts'; +import * as libShips from '../lib/ships.ts'; + +export async function accept(contract: Contract): Promise<Contract> { + if (contract.accepted) return contract; + const response = await api.send<{agent: Agent, contract: Contract, type: ''}>({endpoint: `/my/contracts/${contract.id}/accept`, method: 'POST'}); + if ('apiError' in response) { + api.debugLog(response); + throw response; + } + dbAgents.setAgent(response.agent); + dbContracts.setContract(response.contract); + return response.contract; +} + +export async function contracts(): Promise<Array<Contract>> { + const response = await api.sendPaginated<Contract>({endpoint: '/my/contracts', page: 1}); + if ('apiError' in response) { + api.debugLog(response); + throw response; + } + response.forEach(contract => dbContracts.setContract(contract)); + return response; +} + +export async function deliver(contract: Contract, ship: Ship): Promise<Contract> { + if (contract.terms.deliver[0].unitsRequired >= contract.terms.deliver[0].unitsFulfilled) { + return await fulfill(contract); + } + const tradeSymbol = contract.terms.deliver[0].tradeSymbol; + let units = 0; + ship.cargo.inventory.forEach(i => {if (i.symbol === tradeSymbol) units = i.units; }); + ship = await libShips.dock(ship); // we need to be docked to deliver + const response = await api.send<{contract: Contract, cargo: Cargo}>({ endpoint: `/my/contracts/${contract.id}/deliver`, method: 'POST', payload: { + shipSymbol: ship.symbol, + tradeSymbol: tradeSymbol, + units: units, + }}); + if ('apiError' in response) { + switch(response.code) { + case 4509: // contract delivery terms have been met + return await fulfill(contract); + default: // yet unhandled error + api.debugLog(response); + throw response; + } + } + dbContracts.setContract(response.contract); + dbShips.setShipCargo(ship.symbol, response.cargo); + if(response.contract.terms.deliver[0].unitsRequired >= response.contract.terms.deliver[0].unitsFulfilled) { + return await fulfill(contract); + } + return response.contract; +} + +export async function fulfill(contract: Contract): Promise<Contract> { + if (contract.fulfilled) return contract; + const response = await api.send<{agent: Agent, contract: Contract}>({ endpoint: `/my/contracts/${contract.id}/fulfill`, method: 'POST'}); + if ('apiError' in response) { + api.debugLog(response); + throw response; + } + dbAgents.setAgent(response.agent); + dbContracts.setContract(response.contract); + return response.contract; +} diff --git a/nodejs/lib/priority_queue.js b/nodejs/lib/priority_queue.js deleted file mode 100644 index da526b2..0000000 --- a/nodejs/lib/priority_queue.js +++ /dev/null @@ -1,39 +0,0 @@ -export class QElement { - constructor(element, priority) { - this.element = element; - this.priority = priority; - } -} - -export class PriorityQueue { - constructor(elt) { - this.items = []; - if (elt !== undefined) { - this.enqueue(elt, 0); - } - } - - enqueue(element, priority) { - let qElement = new QElement(element, priority); - - for (let i = 0; i < this.items.length; ++i) { - if (this.items[i].priority > qElement.priority) { - this.items.splice(i, 0, qElement); - return; - } - } - this.items.push(qElement); - } - dequeue() { - return this.items.shift(); // we would use pop to get the highest priority, shift() gives us the lowest priority - } - front() { - return this.items[0]; - } - rear() { - return this.items[this.items.length - 1]; - } - isEmpty() { - return this.items.length === 0; - } -} diff --git a/nodejs/lib/priority_queue.ts b/nodejs/lib/priority_queue.ts new file mode 100644 index 0000000..ec9e7d0 --- /dev/null +++ b/nodejs/lib/priority_queue.ts @@ -0,0 +1,36 @@ +class QElement { + element: unknown; + priority: number; + constructor(element: unknown, priority: number) { + this.element = element; + this.priority = priority; + } +} + +export class PriorityQueue { + items: Array<QElement>; + + constructor(elt?: unknown) { + this.items = []; + if (elt !== undefined) this.enqueue(elt, 0); + } + + enqueue(element: unknown, priority: number): void { + let qElement = new QElement(element, priority); + + for (let i = 0; i < this.items.length; ++i) { + if (this.items[i].priority > qElement.priority) { + this.items.splice(i, 0, qElement); + return; + } + } + this.items.push(qElement); + } + dequeue(): unknown { + // we would use pop to get the highest priority, shift() gives us the lowest priority + return this.items.shift()?.element; + } + isEmpty(): boolean { + return this.items.length === 0; + } +} diff --git a/nodejs/lib/ships.js b/nodejs/lib/ships.js deleted file mode 100644 index 835e62b..0000000 --- a/nodejs/lib/ships.js +++ /dev/null @@ -1,195 +0,0 @@ -import * as api from './api.js'; -import * as dbShips from '../database/ships.js'; -import * as dbSurveys from '../database/surveys.js'; -import * as systems from '../lib/systems.js'; - -export async function extract(ctx) { - const ship = dbShips.getShip(ctx.symbol); - const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ENGINEERED_ASTEROID'}); - // TODO if there are multiple fields, find the closest one? - await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol}); - await orbit(ctx); - // TODO handle surveying? - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/extract`, method: 'POST'}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4000: // ship is on cooldown - await api.sleep(response.error.data.cooldown.remainingSeconds * 1000); - return await extract(ctx); - case 4228: // ship is full - return null; - default: // yet unhandled error - throw response; - } - } else { - dbShips.setShipCargo(ctx.symbol, response.data.cargo); - await api.sleep(response.data.cooldown.remainingSeconds*1000); - } - return response; -} - -export async function dock(ctx) { - const ship = dbShips.getShip(ctx.symbol); - if (ship.nav.status === 'DOCKED') { - return null; - } - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/dock`, method: 'POST'}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4214: // ship is in transit - await api.sleep(response.error.data.secondsToArrival * 1000); - return await dock(ctx); - default: // yet unhandled error - throw response; - } - } - dbShips.setShipNav(ctx.symbol, response.data.nav); - return response; -} - -function hasMount(shipSymbol, mountSymbol) { - const ship = dbShips.getShip(shipSymbol); - return ship.mounts.filter(s => s.symbol === mountSymbol).length > 0; -} - -export async function jump(ctx) { - // TODO - const response = await api.send({endpoint: `/my/ships/${ctx.ship}/jump`, method: 'POST', payload: { systemSymbol: ctx.system }}); - await api.sleep(response.data.cooldown.remainingSeconds*1000); - return response; -} - -export async function navigate(ctx) { - const ship = dbShips.getShip(ctx.symbol); - if (ship.nav.waypointSymbol === ctx.waypoint) { - return; - } - await orbit(ctx); - // TODO if we do not have enough fuel, make a stop to refuel along the way or drift to the destination - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/navigate`, method: 'POST', payload: { waypointSymbol: ctx.waypoint }}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4214: // ship is in transit - await api.sleep(response.error.data.secondsToArrival * 1000); - return await navigate(ctx); - default: // yet unhandled error - throw response; - } - } - dbShips.setShipFuel(ctx.symbol, response.data.fuel); - dbShips.setShipNav(ctx.symbol, response.data.nav); - const delay = new Date(response.data.nav.route.arrival) - new Date(); - await api.sleep(delay); - response.data.nav.status = 'IN_ORBIT'; - dbShips.setShipNav(ctx.symbol, response.data.nav); - await refuel(ctx); - return response; -} - -export async function negotiate(ctx) { - // TODO - return await api.send({endpoint: `/my/ships/${ctx.ship}/negotiate/contract`, method: 'POST'}); -} - -export async function orbit(ctx) { - const ship = dbShips.getShip(ctx.symbol); - if (ship.nav.status === 'IN_ORBIT') { - return null; - } - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/orbit`, method: 'POST'}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4214: // ship is in transit - await api.sleep(response.error.data.secondsToArrival * 1000); - return await orbit(ctx); - default: // yet unhandled error - throw response; - } - } - dbShips.setShipNav(ctx.symbol, response.data.nav); - return response; -} - -export async function purchase(ctx) { - const response = await api.send({endpoint: '/my/ships', method: 'POST', payload: { - shipType: ctx.shipType, - waypointSymbol: ctx.waypoint, - }}); - if (response.error !== undefined) { - throw response; - } - dbShips.setShip(response.data.ship); - return response.data; -} - -export async function refuel(ctx) { - const ship = dbShips.getShip(ctx.symbol); - if (ship.fuel.current >= ship.fuel.capacity * 0.9) { - return null; - } - // TODO check if our current waypoint has a marketplace (and sells fuel)? - await dock(ctx); - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/refuel`, method: 'POST'}); - if (response.error !== undefined) { - throw response; - } - dbShips.setShipFuel(ctx.symbol, response.data.fuel); - // TODO track credits - return response; -} - -export async function sell(ctx) { - // TODO check if our current waypoint has a marketplace? - await dock(ctx); - const ship = dbShips.getShip(ctx.symbol); - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/sell`, method: 'POST', payload: { symbol: ctx.good, units: ctx.units }}); - if (response.error !== undefined) { - throw response; - } - dbShips.setShipCargo(ctx.symbol, response.data.cargo); - // TODO track credits - return response; -} - -export async function ships() { - const response = await api.send({endpoint: `/my/ships`, page: 1}); - if (response.error !== undefined) { - throw response; - } - response.forEach(ship => dbShips.setShip(ship)); - return response; -} - -export async function ship(ctx) { - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}`}); - if (response.error !== undefined) { - throw response; - } - dbShips.setShip(response.data); - return response; -} - -export async function survey(ctx) { - if (!hasMount(ctx.symbol, 'MOUNT_SURVEYOR_I')) { // we check if a surveyor is mounted on the ship - return null; - } - const ship = dbShips.getShip(ctx.symbol); - const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ASTEROID_FIELD'}); - // TODO if there are multiple fields, find the closest one? - await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol}); - await orbit(ctx); - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/survey`, method: 'POST'}); - api.debugLog(response); - if (response.error !== undefined) { - switch(response.error.code) { - case 4000: // ship is on cooldown - await api.sleep(response.error.data.cooldown.remainingSeconds * 1000); - return await survey(ctx); - default: // yet unhandled error - throw response; - } - } - dbSurveys.set(response.data.surveys[0]); - await api.sleep(response.data.cooldown.remainingSeconds*1000); - return response; -} diff --git a/nodejs/lib/ships.ts b/nodejs/lib/ships.ts new file mode 100644 index 0000000..2e04dd4 --- /dev/null +++ b/nodejs/lib/ships.ts @@ -0,0 +1,204 @@ +import { Response } from '../model/api.ts'; +import { Agent } from '../model/agent.ts'; +import { Cargo } from '../model/cargo.ts'; +import { Cooldown, Fuel, Nav, Ship } from '../model/ship.ts'; +import * as api from './api.js'; +import * as dbAgents from '../database/agents.ts'; +import * as dbShips from '../database/ships.js'; +import * as dbSurveys from '../database/surveys.js'; +import * as systems from '../lib/systems.js'; + +export async function dock(ship: Ship): Promise<Ship> { + if (ship.nav.status === 'DOCKED') return ship; + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/dock`, method: 'POST'}) as Response<{nav: Nav}>; + if (response.error !== undefined) { + switch(response.error.code) { + case 4214: // ship is in transit + await api.sleep(response.error.data.secondsToArrival * 1000); + return await dock(ship); + default: // yet unhandled error + api.debugLog(response); + throw response; + } + } + dbShips.setShipNav(ship.symbol, response.data.nav); + ship.nav = response.data.nav; + return ship; +} + +export async function extract(ship: Ship): Promise<Ship> { + // TODO move to a suitable asteroid? + // const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ENGINEERED_ASTEROID'}); + // TODO if there are multiple fields, find the closest one? + //await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol}); + ship = await orbit(ship); + // TODO handle surveying? + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/extract`, method: 'POST'}) as Response<{cooldown: Cooldown, cargo: Cargo}>; // TODO extraction and events api response fields cf https://spacetraders.stoplight.io/docs/spacetraders/b3931d097608d-extract-resources + if (response.error !== undefined) { + switch(response.error.code) { + case 4000: // ship is on cooldown + await api.sleep(response.error.data.cooldown.remainingSeconds * 1000); + return await extract(ship); + case 4228: // ship is full + return ship; + default: // yet unhandled error + api.debugLog(response); + throw response; + } + } else { + dbShips.setShipCargo(ship.symbol, response.data.cargo); + ship.cargo = response.data.cargo; + await api.sleep(response.data.cooldown.remainingSeconds*1000); + } + return ship; +} + +//function hasMount(shipSymbol, mountSymbol) { +// const ship = dbShips.getShip(shipSymbol); +// return ship.mounts.filter(s => s.symbol === mountSymbol).length > 0; +//} + +//export async function jump(ship: Ship): Ship { +// // TODO +// const response = await api.send({endpoint: `/my/ships/${ctx.ship}/jump`, method: 'POST', payload: { systemSymbol: ctx.system }}); +// await api.sleep(response.data.cooldown.remainingSeconds*1000); +// return response; +//} + +export async function navigate(ship: Ship, waypoint: string): Promise<Ship> { + if (ship.nav.waypointSymbol === waypoint) return ship; + ship = await orbit(ship); + // TODO if we do not have enough fuel, make a stop to refuel along the way or drift to the destination + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/navigate`, method: 'POST', payload: { waypointSymbol: waypoint }}) as Response<{fuel: Fuel, nav: Nav}>; // TODO events field + if (response.error !== undefined) { + switch(response.error.code) { + case 4214: // ship is in transit + await api.sleep(response.error.data.secondsToArrival * 1000); + return await navigate(ship, waypoint); + default: // yet unhandled error + api.debugLog(response); + throw response; + } + } + dbShips.setShipFuel(ship.symbol, response.data.fuel); + dbShips.setShipNav(ship.symbol, response.data.nav); + ship.fuel = response.data.fuel; + ship.nav = response.data.nav + const delay = new Date(response.data.nav.route.arrival).getTime() - new Date().getTime() ; + await api.sleep(delay); + response.data.nav.status = 'IN_ORBIT'; // we arrive in orbit + dbShips.setShipNav(ship.symbol, response.data.nav); + ship.nav = response.data.nav + ship = await refuel(ship); + return ship; +} + +//export async function negotiate(ctx) { +// // TODO +// return await api.send({endpoint: `/my/ships/${ctx.ship}/negotiate/contract`, method: 'POST'}); +//} + +export async function orbit(ship: Ship): Promise<Ship> { + if (ship.nav.status === 'IN_ORBIT') return ship; + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/orbit`, method: 'POST'}) as Response<{nav: Nav}>; + if (response.error !== undefined) { + switch(response.error.code) { + case 4214: // ship is in transit + await api.sleep(response.error.data.secondsToArrival * 1000); + return await orbit(ship); + default: // yet unhandled error + throw response; + } + } + dbShips.setShipNav(ship.symbol, response.data.nav); + ship.nav = response.data.nav; + return ship; +} + +//export async function purchase(ctx) { +// const response = await api.send({endpoint: '/my/ships', method: 'POST', payload: { +// shipType: ctx.shipType, +// waypointSymbol: ctx.waypoint, +// }}); +// if (response.error !== undefined) { +// throw response; +// } +// dbShips.setShip(response.data.ship); +// return response.data; +//} + +export async function refuel(ship: Ship): Promise<Ship> { + if (ship.fuel.current >= ship.fuel.capacity * 0.9) return ship; + // TODO check if our current waypoint has a marketplace (and sells fuel)? + ship = await dock(ship); + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/refuel`, method: 'POST'}) as Response<{agent: Agent, fuel: Fuel}>; // TODO transaction field + if (response.error !== undefined) { + api.debugLog(response); + throw response; + } + dbShips.setShipFuel(ship.symbol, response.data.fuel); + dbAgents.setAgent(response.data.agent); + ship.fuel = response.data.fuel; + return ship; +} + +export async function sell(ship: Ship, tradeSymbol: string): Promise<Ship> { + // TODO check if our current waypoint has a marketplace? + ship = await dock(ship); + let units = 0; + ship.cargo.inventory.forEach(i => {if (i.symbol === tradeSymbol) units = i.units; }); + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/sell`, method: 'POST', payload: { symbol: tradeSymbol, units: units }}) as Response<{agent: Agent, cargo: Cargo}>; // TODO transaction field + if (response.error !== undefined) { + api.debugLog(response); + throw response; + } + dbShips.setShipCargo(ship.symbol, response.data.cargo); + dbAgents.setAgent(response.data.agent); + ship.cargo = response.data.cargo; + return ship; +} + +export async function ships(): Promise<Array<Ship>> { + const response = await api.send({endpoint: `/my/ships`, page: 1}) as Response<Array<Ship>>; + if (response.error !== undefined) { + api.debugLog(response); + throw response; + } + response.data.forEach(ship => dbShips.setShip(ship)); + return response.data; +} + +export async function ship(ship: Ship): Promise<Ship> { + const response = await api.send({endpoint: `/my/ships/${ship.symbol}`}) as Response<Ship>; + if (response.error !== undefined) { + api.debugLog(response); + throw response; + } + dbShips.setShip(response.data); + return response.data; +} + +//export async function survey(ctx) { +// if (!hasMount(ctx.symbol, 'MOUNT_SURVEYOR_I')) { // we check if a surveyor is mounted on the ship +// return null; +// } +// const ship = dbShips.getShip(ctx.symbol); +// const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ASTEROID_FIELD'}); +// // TODO if there are multiple fields, find the closest one? +// await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol}); +// await orbit(ctx); +// const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/survey`, method: 'POST'}); +// api.debugLog(response); +// if (response.error !== undefined) { +// switch(response.error.code) { +// case 4000: // ship is on cooldown +// await api.sleep(response.error.data.cooldown.remainingSeconds * 1000); +// return await survey(ctx); +// default: // yet unhandled error +// throw response; +// } +// } +// dbSurveys.set(response.data.surveys[0]); +// await api.sleep(response.data.cooldown.remainingSeconds*1000); +// return response; +//} diff --git a/nodejs/lib/systems.js b/nodejs/lib/systems.ts index 6993431..94ebab7 100644 --- a/nodejs/lib/systems.js +++ b/nodejs/lib/systems.ts @@ -5,17 +5,17 @@ import * as dbSystems from '../database/systems.js'; import * as utils from './utils.js'; // Retrieves a marketplace's market data for waypointSymbol -export async function market(waypointSymbol) { +export async function market(waypointSymbol: string) { const data = dbMarkets.getMarketAtWaypoint(waypointSymbol); if (data === null) { - if (dbShips.getShipsAt(waypointSymbol) === null) { - return null; - } - const systemSymbol = utils.systemFromWaypoint(waypointSymbol); - let d = await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${waypointSymbol}/market`}); - delete d.data.transactions; - dbMarkets.setMarket(d.data); - return d; + if (dbShips.getShipsAt(waypointSymbol) === null) { + return null; + } + const systemSymbol = utils.systemFromWaypoint(waypointSymbol); + let d = await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${waypointSymbol}/market`}); + delete d.data.transactions; + dbMarkets.setMarket(d.data); + return d; } return data; } @@ -33,10 +33,10 @@ export async function system(ctx) { const response = await api.send({endpoint: `/systems/${ctx.symbol}`}); if (response.error !== undefined) { switch(response.error.code) { - case 404: - throw `Error retrieving info for system ${ctx.symbol}: ${response.error.message}`; - default: // yet unhandled error - throw response; + case 404: + throw `Error retrieving info for system ${ctx.symbol}: ${response.error.message}`; + default: // yet unhandled error + throw response; } } s = response.data; @@ -68,10 +68,10 @@ export async function waypoints(ctx) { const response = await api.send({endpoint: `/systems/${ctx.symbol}/waypoints?limit=20&page=${page}`, priority: 98}); if (response.error !== undefined) { switch(response.error.code) { - case 404: - throw `Error retrieving waypoints for system ${ctx.symbol}: ${response.error.message}`; - default: // yet unhandled error - throw response; + case 404: + throw `Error retrieving waypoints for system ${ctx.symbol}: ${response.error.message}`; + default: // yet unhandled error + throw response; } } waypoints = waypoints.concat(response.data); diff --git a/nodejs/lib/utils.js b/nodejs/lib/utils.js deleted file mode 100644 index a2c8128..0000000 --- a/nodejs/lib/utils.js +++ /dev/null @@ -1,18 +0,0 @@ -// cargo is a ship.cargo object, want is an optional symbol -export function categorizeCargo(cargo, want) { - const wanted = cargo.inventory.filter(i => i.symbol === want || i.symbol === 'ANTIMATTER'); - const goods = cargo.inventory.filter(i => i.symbol !== want && i.symbol !== 'ANTIMATTER'); - const wobj = wanted.reduce(function(acc, e) { - acc[e.symbol] = e.units; - return acc; - }, {}); - const gobj = goods.reduce(function(acc, e) { - acc[e.symbol] = e.units; - return acc; - }, {}); - return {wanted: wobj, goods: gobj}; -} - -export function systemFromWaypoint(waypoint) { - return waypoint.split('-').slice(0,2).join('-'); -} diff --git a/nodejs/lib/utils.ts b/nodejs/lib/utils.ts new file mode 100644 index 0000000..c5093a6 --- /dev/null +++ b/nodejs/lib/utils.ts @@ -0,0 +1,25 @@ +import { Cargo, CargoManifest } from '../model/cargo.ts'; + +export type CategorizedCargo = { + wanted: CargoManifest; + goods: CargoManifest; +}; + +// cargo is a ship.cargo object, want is an optional symbol +export function categorizeCargo(cargo: Cargo, want?: string): CategorizedCargo { + const wanted = cargo.inventory.filter(i => i.symbol === want || i.symbol === 'ANTIMATTER'); + const goods = cargo.inventory.filter(i => i.symbol !== want && i.symbol !== 'ANTIMATTER'); + const wobj = wanted.reduce(function(acc: CargoManifest, e) { + acc[e.symbol] = e.units; + return acc; + }, {}); + const gobj = goods.reduce(function(acc: CargoManifest, e) { + acc[e.symbol] = e.units; + return acc; + }, {}); + return {wanted: wobj, goods: gobj}; +} + +export function systemFromWaypoint(waypoint: string): string { + return waypoint.split('-').slice(0,2).join('-'); +} diff --git a/nodejs/main.js b/nodejs/main.js deleted file mode 100755 index a811b6a..0000000 --- a/nodejs/main.js +++ /dev/null @@ -1,9 +0,0 @@ -import * as autoContracting from './automation/contracting.js'; -import * as autoExploring from './automation/exploration.js'; -import * as autoInit from './automation/init.js'; -import * as api from './lib/api.js'; -import * as contracts from './lib/contracts.js'; - -await autoInit.init(); -autoContracting.init(); -autoExploring.init(); diff --git a/nodejs/main.ts b/nodejs/main.ts new file mode 100755 index 0000000..51be650 --- /dev/null +++ b/nodejs/main.ts @@ -0,0 +1,9 @@ +import * as autoContracting from './automation/contracting.ts'; +//import * as autoExploring from './automation/exploration.js'; +import * as autoInit from './automation/init.js'; +//import * as api from './lib/api.js'; +//import * as contracts from './lib/contracts.js'; + +await autoInit.init(); +autoContracting.init(); +//autoExploring.init(); diff --git a/nodejs/model/agent.ts b/nodejs/model/agent.ts new file mode 100644 index 0000000..dce6424 --- /dev/null +++ b/nodejs/model/agent.ts @@ -0,0 +1,8 @@ +export type Agent = { + accountId: string; + credits: number; + headquarters: string; + shipCount: number; + startingFaction: string; + symbol: string; +}; diff --git a/nodejs/model/api.ts b/nodejs/model/api.ts new file mode 100644 index 0000000..5092157 --- /dev/null +++ b/nodejs/model/api.ts @@ -0,0 +1,32 @@ +export type APIError = { + apiError: 'APIError'; + error: string; + code: number; + data: any; // TODO +}; + +export type Meta = { + limit: number; + page: number; + total: number; +} + +export type Request = { + endpoint: string; // the path part of the url to call + method?: string; // HTTP method for `fetch` call, defaults to 'GET' + page?: number; // run a paginated request starting from this page until all the following pages are fetched + payload?: { [key:string]: any}; // optional json object that will be sent along the request + priority?: number; // optional priority value, defaults to 10. lower than 10 means the message will be sent faster +}; + +export type RequestPromise<T> = { + reject: (reason?: any) => void; + request: Request; + resolve: (value: Response<T> | PromiseLike<Response<T>>) => void; +}; + +export type Response<T> = { + data: T; + error?: APIError; + meta?: Meta; +} diff --git a/nodejs/model/cargo.ts b/nodejs/model/cargo.ts new file mode 100644 index 0000000..869fa49 --- /dev/null +++ b/nodejs/model/cargo.ts @@ -0,0 +1,17 @@ +export type Inventory = { + description: string; + name: string; + symbol: string; + units: number; +}; + +export type Cargo = { + "capacity": number; + "units": number; + "inventory": Array<Inventory>; +}; + +// Custom type, not from space traders api +export type CargoManifest = { + [key: string]: number; +}; diff --git a/nodejs/model/contract.ts b/nodejs/model/contract.ts new file mode 100644 index 0000000..eb7add4 --- /dev/null +++ b/nodejs/model/contract.ts @@ -0,0 +1,22 @@ +export type Contract = { + id: string; + factionSymbol: string; + type: string; + terms: { + deadline: Date; + payment: { + onAccepted: number; + onFulfilled: number; + }, + deliver: Array<{ + tradeSymbol: string; + destinationSymbol: string; + unitsRequired: number; + unitsFulfilled: number; + }>; + }; + accepted: boolean; + fulfilled: boolean; + expiration: Date; + deadlineToAccept: Date; +}; diff --git a/nodejs/model/ship.ts b/nodejs/model/ship.ts new file mode 100644 index 0000000..9aaf601 --- /dev/null +++ b/nodejs/model/ship.ts @@ -0,0 +1,56 @@ +import { Cargo } from './cargo.ts'; + +export type Cooldown = { + shipSymbol: string; + totalSeconds: number; + remainingSeconds: number; +}; + +export type Consummed = { + amount: number; + timestamp: Date; +}; + +export type Fuel = { + capacity: number; + consummed: Consummed; + current: number; +}; + +export type Nav = { + flightMode: string; + route: Route; + status: string; + systemSymbol: string; + waypointSymbol: string; +}; + +export type Route = { + arrival: Date; + departureTime: Date; + destination: RouteEndpoint; + origin: RouteEndpoint; +}; + +export type RouteEndpoint = { + type: string; + symbol: string; + systemSymbol: string; + x: number; + y: number; +}; + +export type Ship = { + cargo: Cargo; + cooldown: Cooldown; + // crew + // engine + // frame + fuel: Fuel; + // modules + // mounts + nav: Nav; + // reactor + // registration + symbol: string; +}; diff --git a/nodejs/tsconfig.json b/nodejs/tsconfig.json new file mode 100644 index 0000000..b6ddffc --- /dev/null +++ b/nodejs/tsconfig.json @@ -0,0 +1,109 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ + // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ + // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ + // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ + // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ + // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "jsx": "preserve", /* Specify what JSX code is generated. */ + // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ + // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ + // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ + // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ + // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ + // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "esnext", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ + // "types": [], /* Specify type package names to be included without being referenced in a source file. */ + // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ + // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ + "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ + // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ + // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ + // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ + // "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + // "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ + // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ + // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ + // "outDir": "./", /* Specify an output folder for all emitted files. */ + // "removeComments": true, /* Disable emitting comments. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ + // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ + // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ + // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ + // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ + // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ + // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ + // "newLine": "crlf", /* Set the newline character for emitting files. */ + // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ + // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ + // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ + // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ + // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ + // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ + + /* Interop Constraints */ + // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ + // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ + // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + //"noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ + // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ + // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ + // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ + // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ + // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ + // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ + // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ + + /* Completeness */ + // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ + "skipLibCheck": true /* Skip type checking all .d.ts files. */ + } +} |