summaryrefslogtreecommitdiff
path: root/nodejs/lib
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--nodejs/lib/api.ts (renamed from nodejs/lib/api.js)125
-rw-r--r--nodejs/lib/contracts.js68
-rw-r--r--nodejs/lib/contracts.ts74
-rw-r--r--nodejs/lib/priority_queue.js39
-rw-r--r--nodejs/lib/priority_queue.ts36
-rw-r--r--nodejs/lib/ships.js195
-rw-r--r--nodejs/lib/ships.ts204
-rw-r--r--nodejs/lib/systems.ts (renamed from nodejs/lib/systems.js)34
-rw-r--r--nodejs/lib/utils.js18
-rw-r--r--nodejs/lib/utils.ts25
10 files changed, 417 insertions, 401 deletions
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('-');
+}