From d668eac4a63a9aa98c3efff395faa23cfcea1c1b Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Thu, 21 Mar 2024 17:08:37 +0100 Subject: [node] begin the great typescript rewrite --- nodejs/.eslintrc.json | 44 --------- nodejs/automation/contracting.js | 71 -------------- nodejs/automation/contracting.ts | 72 ++++++++++++++ nodejs/automation/init.js | 4 +- nodejs/automation/selling.js | 118 +++++++++++----------- nodejs/database/agents.js | 21 ---- nodejs/database/agents.ts | 20 ++++ nodejs/database/contracts.js | 30 ------ nodejs/database/contracts.ts | 29 ++++++ nodejs/database/db.js | 51 ---------- nodejs/database/db.ts | 52 ++++++++++ nodejs/database/ships.js | 58 ----------- nodejs/database/ships.ts | 55 +++++++++++ nodejs/database/tokens.js | 16 --- nodejs/database/tokens.ts | 14 +++ nodejs/lib/api.js | 163 ------------------------------- nodejs/lib/api.ts | 160 ++++++++++++++++++++++++++++++ nodejs/lib/contracts.js | 68 ------------- nodejs/lib/contracts.ts | 74 ++++++++++++++ nodejs/lib/priority_queue.js | 39 -------- nodejs/lib/priority_queue.ts | 36 +++++++ nodejs/lib/ships.js | 195 ------------------------------------- nodejs/lib/ships.ts | 204 +++++++++++++++++++++++++++++++++++++++ nodejs/lib/systems.js | 86 ----------------- nodejs/lib/systems.ts | 86 +++++++++++++++++ nodejs/lib/utils.js | 18 ---- nodejs/lib/utils.ts | 25 +++++ nodejs/main.js | 9 -- nodejs/main.ts | 9 ++ nodejs/model/agent.ts | 8 ++ nodejs/model/api.ts | 32 ++++++ nodejs/model/cargo.ts | 17 ++++ nodejs/model/contract.ts | 22 +++++ nodejs/model/ship.ts | 56 +++++++++++ nodejs/tsconfig.json | 109 +++++++++++++++++++++ 35 files changed, 1142 insertions(+), 929 deletions(-) delete mode 100644 nodejs/.eslintrc.json delete mode 100644 nodejs/automation/contracting.js create mode 100644 nodejs/automation/contracting.ts delete mode 100644 nodejs/database/agents.js create mode 100644 nodejs/database/agents.ts delete mode 100644 nodejs/database/contracts.js create mode 100644 nodejs/database/contracts.ts delete mode 100644 nodejs/database/db.js create mode 100644 nodejs/database/db.ts delete mode 100644 nodejs/database/ships.js create mode 100644 nodejs/database/ships.ts delete mode 100644 nodejs/database/tokens.js create mode 100644 nodejs/database/tokens.ts delete mode 100644 nodejs/lib/api.js create mode 100644 nodejs/lib/api.ts delete mode 100644 nodejs/lib/contracts.js create mode 100644 nodejs/lib/contracts.ts delete mode 100644 nodejs/lib/priority_queue.js create mode 100644 nodejs/lib/priority_queue.ts delete mode 100644 nodejs/lib/ships.js create mode 100644 nodejs/lib/ships.ts delete mode 100644 nodejs/lib/systems.js create mode 100644 nodejs/lib/systems.ts delete mode 100644 nodejs/lib/utils.js create mode 100644 nodejs/lib/utils.ts delete mode 100755 nodejs/main.js create mode 100755 nodejs/main.ts create mode 100644 nodejs/model/agent.ts create mode 100644 nodejs/model/api.ts create mode 100644 nodejs/model/cargo.ts create mode 100644 nodejs/model/contract.ts create mode 100644 nodejs/model/ship.ts create mode 100644 nodejs/tsconfig.json (limited to 'nodejs') 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) { + // 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.js deleted file mode 100644 index d7f9aab..0000000 --- a/nodejs/database/contracts.js +++ /dev/null @@ -1,30 +0,0 @@ -import db from './db.js'; - -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; - } - return JSON.parse(data.data); -} - -export function getContracts() { - const data = getContractsStatement.all(); - return data.map(contractData => JSON.parse(contractData.data)); -} - -export function setContract(data) { - if (getContract(data.id) === null) { - return addContractStatement.run(JSON.stringify(data)).lastInsertRowid; - } else { - return updateContractStatement.run({ - data: JSON.stringify(data), - id: data.id, - }).changes; - } -} diff --git a/nodejs/database/contracts.ts b/nodejs/database/contracts.ts new file mode 100644 index 0000000..576f8dd --- /dev/null +++ b/nodejs/database/contracts.ts @@ -0,0 +1,29 @@ +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: string): Contract|null { + const data = getContractStatement.get(id) as {data: string}|undefined; + if (!data) return null; + return JSON.parse(data.data); +} + +export function getContracts(): Array { + const data = getContractsStatement.all() as Array<{data: string}>; + return data.map(contractData => JSON.parse(contractData.data)); +} + +export function setContract(data: Contract) { + if (getContract(data.id) === null) { + addContractStatement.run(JSON.stringify(data)); + } else { + updateContractStatement.run({ + data: JSON.stringify(data), + id: data.id, + }); + } +} diff --git a/nodejs/database/db.js b/nodejs/database/db.js deleted file mode 100644 index 4438fec..0000000 --- a/nodejs/database/db.js +++ /dev/null @@ -1,51 +0,0 @@ -import fs from 'fs'; -import Database from 'better-sqlite3'; - -const allMigrations = [ - 'database/000_init.sql', - 'database/001_systems.sql', - 'database/002_ships.sql', - 'database/003_surveys.sql', - 'database/004_markets.sql', -]; - -const db = new Database( - process.env.NODE_ENV === 'test' ? 'test.db' : 'spacetraders.db', - process.env.NODE_ENV === 'development' ? { verbose: console.log } : null -); -db.pragma('foreign_keys = ON'); -db.pragma('journal_mode = WAL'); - -function init() { - db.transaction(function migrate() { - let version; - try { - version = db.prepare('SELECT version FROM schema_version').get().version; - } catch { - version = 0; - } - if (version === allMigrations.length) return; - while (version < allMigrations.length) { - db.exec(fs.readFileSync(allMigrations[version], 'utf8')); - version++; - } - db.exec(`DELETE FROM schema_version; INSERT INTO schema_version (version) VALUES (${version});`); - })(); -} - -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(); - 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};`)); - views.forEach(elt => db.exec(`DROP VIEW ${elt.name};`)); - db.exec(`VACUUM;`); - init(); -} - -init(); - -export default db; diff --git a/nodejs/database/db.ts b/nodejs/database/db.ts new file mode 100644 index 0000000..247ee5a --- /dev/null +++ b/nodejs/database/db.ts @@ -0,0 +1,52 @@ +import fs from 'fs'; +import Database from 'better-sqlite3'; + +const allMigrations = [ + 'database/000_init.sql', + 'database/001_systems.sql', + 'database/002_ships.sql', + 'database/003_surveys.sql', + 'database/004_markets.sql', +]; + +const db = new Database( + process.env.NODE_ENV === 'test' ? 'test.db' : 'spacetraders.db', + process.env.NODE_ENV === 'development' ? { verbose: console.log } : undefined +); +db.pragma('foreign_keys = ON'); +db.pragma('journal_mode = WAL'); + +function init() { + db.transaction(function migrate() { + let version; + try { + const res = db.prepare('SELECT version FROM schema_version').get() as {version: number}; + version = res.version; + } catch { + version = 0; + } + if (version === allMigrations.length) return; + while (version < allMigrations.length) { + db.exec(fs.readFileSync(allMigrations[version], 'utf8')); + version++; + } + db.exec(`DELETE FROM schema_version; INSERT INTO schema_version (version) VALUES (${version});`); + })(); +} + +export function reset() { + 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};`)); + views.forEach(elt => db.exec(`DROP VIEW ${elt.name};`)); + db.exec(`VACUUM;`); + init(); +} + +init(); + +export default db; diff --git a/nodejs/database/ships.js b/nodejs/database/ships.js deleted file mode 100644 index f9eb668..0000000 --- a/nodejs/database/ships.js +++ /dev/null @@ -1,58 +0,0 @@ -import db from './db.js'; - -const addShipStatement = db.prepare(`INSERT INTO ships(data) VALUES (json(?));`); -const getShipStatement = db.prepare(`SELECT data FROM ships WHERE data->>'symbol' = ?;`); -const getShipsAtStatement = db.prepare(`SELECT data FROM ships WHERE data->>'$.nav.systemSymbol' = ?;`); -const setShipCargoStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.cargo', json(:cargo)) FROM ships WHERE data->>'symbol' = :symbol) WHERE data->>'symbol' = :symbol;`); -const setShipFuelStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.fuel', json(:fuel)) FROM ships WHERE data->>'symbol' = :symbol) WHERE data->>'symbol' = :symbol;`); -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; - } - return JSON.parse(data.data); -} - -export function getShipsAt(symbol) { - const data = getShipsAtStatement.all(symbol); - if (data === undefined) { - return null; - } - return data.map(elt => JSON.parse(elt.data)); -} - - -export function setShip(data) { - if (getShip(data.symbol) === null) { - return addShipStatement.run(JSON.stringify(data)).lastInsertRowid; - } else { - return updateShipStatement.run({ - data: JSON.stringify(data), - symbol: data.symbol, - }).changes; - } -} - -export function setShipCargo(symbol, cargo) { - return setShipCargoStatement.run({ - cargo: JSON.stringify(cargo), - symbol: symbol, - }).changes; -} - -export function setShipFuel(symbol, fuel) { - return setShipFuelStatement.run({ - fuel: JSON.stringify(fuel), - symbol: symbol, - }).changes; -} - -export function setShipNav(symbol, nav) { - return setShipNavStatement.run({ - nav: JSON.stringify(nav), - symbol: symbol, - }).changes; -} diff --git a/nodejs/database/ships.ts b/nodejs/database/ships.ts new file mode 100644 index 0000000..58c8abf --- /dev/null +++ b/nodejs/database/ships.ts @@ -0,0 +1,55 @@ +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' = ?;`); +const getShipsAtStatement = db.prepare(`SELECT data FROM ships WHERE data->>'$.nav.systemSymbol' = ?;`); +const setShipCargoStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.cargo', json(:cargo)) FROM ships WHERE data->>'symbol' = :symbol) WHERE data->>'symbol' = :symbol;`); +const setShipFuelStatement = db.prepare(`UPDATE ships SET data = (SELECT json_set(data, '$.fuel', json(:fuel)) FROM ships WHERE data->>'symbol' = :symbol) WHERE data->>'symbol' = :symbol;`); +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: 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: string) { + const data = getShipsAtStatement.all(symbol) as Array<{data: string}>; + return data.map(elt => JSON.parse(elt.data)); +} + + +export function setShip(data: Ship) { + if (getShip(data.symbol) === null) { + addShipStatement.run(JSON.stringify(data)); + } else { + updateShipStatement.run({ + data: JSON.stringify(data), + symbol: data.symbol, + }); + } +} + +export function setShipCargo(symbol: string, cargo: Cargo) { + setShipCargoStatement.run({ + cargo: JSON.stringify(cargo), + symbol: symbol, + }); +} + +export function setShipFuel(symbol: string, fuel: Fuel) { + setShipFuelStatement.run({ + fuel: JSON.stringify(fuel), + symbol: symbol, + }); +} + +export function setShipNav(symbol: string, nav: Nav) { + setShipNavStatement.run({ + nav: JSON.stringify(nav), + symbol: symbol, + }); +} 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.js deleted file mode 100644 index ecb0282..0000000 --- a/nodejs/lib/api.js +++ /dev/null @@ -1,163 +0,0 @@ -import * as fs from 'fs'; -import * as events from 'events'; - -import { getToken } from '../database/tokens.js'; -import { PriorityQueue } from './priority_queue.js'; - -// queue processor module variables -const bus = new events.EventEmitter(); // a bus to notify the queue processor to start processing messages -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 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'; - } - running = true; - while(true) { - try { - if (backoffSeconds > 0) { - await sleep(backoffSeconds * 1000); - backoffSeconds = 0; - } - if (queue.isEmpty()) { - busy = false; - 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; - if (duration < 400) { // 333 should work, but 400 should still allow some manual requests to go through during development - await sleep(400 - duration); - } - } catch (e) { - running = false; - throw e; - } - } -} -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 = []; - while (true) { - const response = await send_one(request, ctx); - if (response.meta === undefined) { - throw {"message": "paginated request did not return a meta block", "request": request, "response": response}; - } - ret = ret.concat(response.data); - if (response.meta.limit * response.meta.page >= response.meta.total) { - return ret; - } - request.page++; - } -} - -function send_one(request, ctx) { - return new Promise((resolve, reject) => { - let data = { - ctx: ctx, - reject: reject, - request: request, - resolve: resolve, - }; - queue.enqueue(data, request.priority ? request.priority : 10); - if (!busy) { - bus.emit('send'); // the queue was previously empty, let's wake up the queue_processor - } - }); -} - -// send_this take a data object as argument built in the send function above -async function send_this(data) { - if (headers === undefined) { - const token = getToken(); - if (token === null) { - throw 'Could not get token from the database. Did you init or register yet?'; - } - headers = { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${token}` - }; - } - let options = { - headers: headers, - }; - if (data.request.method !== undefined) { - options['method'] = data.request.method; - } - if (data.request.payload !== undefined) { - options['body'] = JSON.stringify(data.request.payload); - } - let pagination = ""; - if (data.request.page !== undefined) { - pagination=`?limit=20&page=${data.request.page}`; - } - 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); - } - } catch (err) { - 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); - } - } -} - -export function debugLog(ctx) { - console.log(`--- ${Date()} -----------------------------------------------------------------------------`); - console.log(JSON.stringify(ctx, null, 2)); -} - -export function sleep(delay) { - return new Promise((resolve) => setTimeout(resolve, delay)) -} diff --git a/nodejs/lib/api.ts b/nodejs/lib/api.ts new file mode 100644 index 0000000..08c6c71 --- /dev/null +++ b/nodejs/lib/api.ts @@ -0,0 +1,160 @@ +import * as fs from 'fs'; +import * as events from 'events'; + +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 +let busy = false; // true if we are already sending api requests. +let backoffSeconds = 0; +let running = false; +// other module variables +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. + +async function queue_processor() { + if (running) { + throw 'refusing to start a second queue processor'; + } + running = true; + while(true) { + try { + if (backoffSeconds > 0) { + await sleep(backoffSeconds * 1000); + backoffSeconds = 0; + } + if (queue.isEmpty()) { + busy = false; + await new Promise(resolve => bus.once('send', resolve)); + busy = true; + } + const before = new Date().getTime(); + const data = queue.dequeue() as RequestPromise; + 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); + } + } catch (e) { + running = false; + throw e; + } + } +} +queue_processor(); + +export async function send(request: Request): Promise { + const response = await send_one(request); + if (response.error) return response.error; + return response.data; +} + +export async function sendPaginated(request: Request): Promise|APIError> { + if (request.page === undefined) request.page = 1; + let ret: Array = []; + while (true) { + const response = await send_one(request); + if (response.meta === undefined) { + throw {"message": "paginated request did not return a meta block", "request": request, "response": response}; + } + ret = ret.concat(response.data); + if (response.meta.limit * response.meta.page >= response.meta.total) { + return ret; + } + request.page++; + } +} + +function send_one(request: Request): Promise> { + return new Promise((resolve, reject) => { + const data: RequestPromise = { + reject: reject, + request: request, + resolve: resolve, + }; + queue.enqueue(data, request.priority ? request.priority : 10); + if (!busy) { + bus.emit('send'); // the queue was previously empty, let's wake up the queue_processor + } + }); +} + +// send_this take a data object as argument built in the send function above +async function send_this(data: RequestPromise) { + if (headers === null) { + const token = getToken(); + if (token === null) { + throw 'Could not get token from the database. Did you init or register yet?'; + } + headers = { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${token}` + }; + } + let options: {[key:string]:any} = { + headers: headers, + }; + if (data.request.method !== undefined) { + options['method'] = data.request.method; + } + if (data.request.payload !== undefined) { + options['body'] = JSON.stringify(data.request.payload); + } + let pagination = ""; + if (data.request.page !== undefined) { + pagination=`?limit=20&page=${data.request.page}`; + } + fs.writeFileSync('log', JSON.stringify({event: 'send', date: new Date(), data: data}) + '\n', {flag: 'a+'}); + try { + const response = await fetch(`https://api.spacetraders.io/v2${data.request.endpoint}${pagination}`, options); + const json = await response.json() as Response; + 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) { + 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); + } + } +} + +export function debugLog(ctx: any) { + console.log(`--- ${Date()} -----------------------------------------------------------------------------`); + console.log(JSON.stringify(ctx, null, 2)); +} + +export function sleep(delay: number): Promise { + 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 { + 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> { + const response = await api.sendPaginated({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 { + 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 { + 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; + + 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 { + 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 { + // 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 { + 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 { + 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 { + 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 { + // 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> { + const response = await api.send({endpoint: `/my/ships`, page: 1}) as Response>; + 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 { + const response = await api.send({endpoint: `/my/ships/${ship.symbol}`}) as Response; + 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.js deleted file mode 100644 index 6993431..0000000 --- a/nodejs/lib/systems.js +++ /dev/null @@ -1,86 +0,0 @@ -import * as api from './api.js'; -import * as dbMarkets from '../database/markets.js'; -import * as dbShips from '../database/ships.js'; -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) { - 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; - } - return data; -} - -// Retrieves a shipyard's information for ctx.symbol -export async function shipyard(ctx) { - const systemSymbol = utils.systemFromWaypoint(ctx.symbol); - return await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${ctx.symbol}/shipyard`}); -} - -// Retrieves the system's information for ctx.symbol and caches it in the database -export async function system(ctx) { - let s = dbSystems.getSystem(ctx.symbol); - if (s === null) { - 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; - } - } - s = response.data; - dbSystems.setSystem(s); - } - return s; -} - -// Retrieves a list of waypoints that have a specific ctx.trait like a SHIPYARD or a MARKETPLACE in the system ctx.symbol -export async function trait(ctx) { - const w = await waypoints(ctx); - return w.filter(s => s.traits.some(t => t.symbol === ctx.trait)); -} - -// Retrieves a list of waypoints that have a specific ctx.type like ASTEROID_FIELD in the system ctx.symbol -export async function type(ctx, response) { - const w = await waypoints(ctx); - return w.filter(s => s.type === ctx.type); -} - -// Retrieves the system's information for ctx.symbol and caches it in the database -export async function waypoints(ctx) { - await system(ctx); - let updated = dbSystems.getSystemUpdated(ctx.symbol); - // TODO handle uncharted systems - if (updated === null) { - let waypoints = []; - for (let page=1; true; ++page) { - 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; - } - } - waypoints = waypoints.concat(response.data); - if (response.meta.total <= response.meta.limit * page) { - break; - } - } - dbSystems.setSystemWaypoints(ctx.symbol, waypoints); - return waypoints; - } - return dbSystems.getSystem(ctx.symbol).waypoints; -} diff --git a/nodejs/lib/systems.ts b/nodejs/lib/systems.ts new file mode 100644 index 0000000..94ebab7 --- /dev/null +++ b/nodejs/lib/systems.ts @@ -0,0 +1,86 @@ +import * as api from './api.js'; +import * as dbMarkets from '../database/markets.js'; +import * as dbShips from '../database/ships.js'; +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: 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; + } + return data; +} + +// Retrieves a shipyard's information for ctx.symbol +export async function shipyard(ctx) { + const systemSymbol = utils.systemFromWaypoint(ctx.symbol); + return await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${ctx.symbol}/shipyard`}); +} + +// Retrieves the system's information for ctx.symbol and caches it in the database +export async function system(ctx) { + let s = dbSystems.getSystem(ctx.symbol); + if (s === null) { + 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; + } + } + s = response.data; + dbSystems.setSystem(s); + } + return s; +} + +// Retrieves a list of waypoints that have a specific ctx.trait like a SHIPYARD or a MARKETPLACE in the system ctx.symbol +export async function trait(ctx) { + const w = await waypoints(ctx); + return w.filter(s => s.traits.some(t => t.symbol === ctx.trait)); +} + +// Retrieves a list of waypoints that have a specific ctx.type like ASTEROID_FIELD in the system ctx.symbol +export async function type(ctx, response) { + const w = await waypoints(ctx); + return w.filter(s => s.type === ctx.type); +} + +// Retrieves the system's information for ctx.symbol and caches it in the database +export async function waypoints(ctx) { + await system(ctx); + let updated = dbSystems.getSystemUpdated(ctx.symbol); + // TODO handle uncharted systems + if (updated === null) { + let waypoints = []; + for (let page=1; true; ++page) { + 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; + } + } + waypoints = waypoints.concat(response.data); + if (response.meta.total <= response.meta.limit * page) { + break; + } + } + dbSystems.setSystemWaypoints(ctx.symbol, waypoints); + return waypoints; + } + return dbSystems.getSystem(ctx.symbol).waypoints; +} 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 = { + reject: (reason?: any) => void; + request: Request; + resolve: (value: Response | PromiseLike>) => void; +}; + +export type Response = { + 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; +}; + +// 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 ''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. */ + } +} -- cgit v1.2.3