@flexemarkets/fm-sdk 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -12,6 +12,7 @@ import { toInstant } from "./timestamps.js";
12
12
  import { Decimals } from "./decimals.js";
13
13
  import { EventListener, NO_SEQ } from "./stomp.js";
14
14
  import { OrderStream, PendingOrder, RECONNECT_MAX_MS } from "./order-stream.js";
15
+ import { RestOrderWindow } from "./rest-orders.js";
15
16
  import { DefaultDesk, DeskHandle, } from "./desk.js";
16
17
  import { Page } from "./page.js";
17
18
  import { readVersion } from "./version.js";
@@ -160,6 +161,7 @@ export class PersonHasMarketplaceDataError extends ConflictError {
160
161
  export function parsePerson(data) {
161
162
  if (!data)
162
163
  return null;
164
+ requireObject(data);
163
165
  return {
164
166
  id: data.id ?? 0,
165
167
  accountId: data.accountId ?? 0,
@@ -174,9 +176,24 @@ export function parsePerson(data) {
174
176
  lastSignInMethod: data.lastSignInMethod ?? null,
175
177
  };
176
178
  }
179
+ /** An answer that must be an account: parseAccount reads no account as null, as a signed-in person may have none. */
180
+ function anAccount(data) {
181
+ const account = parseAccount(data);
182
+ if (account === null)
183
+ throw new ApiError("Failed to parse the response body: expected an account, got nothing");
184
+ return account;
185
+ }
186
+ /** An answer that must be a person; see {@link anAccount}. */
187
+ function aPerson(data) {
188
+ const person = parsePerson(data);
189
+ if (person === null)
190
+ throw new ApiError("Failed to parse the response body: expected a person, got nothing");
191
+ return person;
192
+ }
177
193
  export function parseAccount(data) {
178
194
  if (!data)
179
195
  return null;
196
+ requireObject(data);
180
197
  return {
181
198
  id: data.id ?? null,
182
199
  name: data.name ?? null,
@@ -189,6 +206,7 @@ export function parseAccount(data) {
189
206
  };
190
207
  }
191
208
  export function parseToken(data) {
209
+ requireObject(data);
192
210
  return {
193
211
  requestUrl: data.requestUrl ?? null,
194
212
  person: parsePerson(data.person),
@@ -197,6 +215,7 @@ export function parseToken(data) {
197
215
  };
198
216
  }
199
217
  export function parseSecurity(data) {
218
+ requireObject(data);
200
219
  return {
201
220
  marketId: data.marketId ?? 0,
202
221
  units: data.units ?? 0,
@@ -209,6 +228,7 @@ export function parseSecurity(data) {
209
228
  };
210
229
  }
211
230
  export function parseMarket(data) {
231
+ requireObject(data);
212
232
  return {
213
233
  id: data.id ?? 0,
214
234
  marketplaceId: data.marketplaceId ?? 0,
@@ -231,6 +251,7 @@ export function parseMarket(data) {
231
251
  };
232
252
  }
233
253
  export function parseCurrentSession(data) {
254
+ requireObject(data);
234
255
  return {
235
256
  marketplaceId: data.marketplaceId ?? 0,
236
257
  sessionId: data.sessionId ?? 0,
@@ -238,6 +259,7 @@ export function parseCurrentSession(data) {
238
259
  };
239
260
  }
240
261
  export function parseCallIndicative(data) {
262
+ requireObject(data);
241
263
  return {
242
264
  marketplaceId: data.marketplaceId ?? 0,
243
265
  marketId: data.marketId ?? 0,
@@ -249,6 +271,7 @@ export function parseCallIndicative(data) {
249
271
  };
250
272
  }
251
273
  export function parseMarketCall(data) {
274
+ requireObject(data);
252
275
  return {
253
276
  id: data.id ?? 0,
254
277
  marketplaceId: data.marketplaceId ?? 0,
@@ -266,15 +289,17 @@ export function parseMarketCall(data) {
266
289
  };
267
290
  }
268
291
  export function parseMarketplace(data) {
292
+ requireObject(data);
269
293
  return {
270
294
  id: data.id ?? 0,
271
295
  name: data.name ?? null,
272
296
  description: data.description ?? null,
273
- markets: (data.markets ?? []).map(parseMarket),
297
+ markets: rows(data.markets ?? []).map(parseMarket),
274
298
  cashDecimals: data.cashDecimals ?? Decimals.DEFAULT_CASH_DECIMALS,
275
299
  };
276
300
  }
277
301
  export function parseSession(data) {
302
+ requireObject(data);
278
303
  return {
279
304
  marketplaceId: data.marketplaceId ?? 0,
280
305
  allocationId: data.allocationId ?? 0,
@@ -290,8 +315,13 @@ export function parseSession(data) {
290
315
  };
291
316
  }
292
317
  export function parseOrder(data) {
318
+ requireObject(data);
319
+ // Every field below has a default, so an answer naming no order read as
320
+ // order 0, which a robot then kept as resting or cancelled.
321
+ if (!Number.isInteger(data.id))
322
+ throw new ApiError("Failed to parse the response body: an order with no id");
293
323
  return {
294
- id: data.id ?? 0,
324
+ id: data.id,
295
325
  original: data.original ?? 0,
296
326
  supplier: data.supplier ?? 0,
297
327
  consumer: data.consumer ?? null,
@@ -315,6 +345,7 @@ export function parseOrder(data) {
315
345
  };
316
346
  }
317
347
  export function parseParticipantState(data) {
348
+ requireObject(data);
318
349
  return {
319
350
  marketplaceId: data.marketplaceId ?? null,
320
351
  allocationId: data.allocationId ?? null,
@@ -327,6 +358,7 @@ function numberOrNull(value) {
327
358
  return value === null || value === undefined ? null : Number(value);
328
359
  }
329
360
  function parseRobotParameter(data) {
361
+ requireObject(data);
330
362
  return {
331
363
  name: data.name ?? "",
332
364
  label: data.label ?? null,
@@ -342,6 +374,7 @@ function parseRobotParameter(data) {
342
374
  };
343
375
  }
344
376
  export function parseRobotParameterConfig(data) {
377
+ requireObject(data);
345
378
  const control = data.control ?? null;
346
379
  return {
347
380
  marketplaceId: data.marketplaceId ?? null,
@@ -355,9 +388,10 @@ export function parseRobotParameterConfig(data) {
355
388
  };
356
389
  }
357
390
  export function parseMarketplaceRobot(data) {
391
+ requireObject(data);
358
392
  const manifest = data.manifest ?? {};
359
393
  const groups = manifest.parameters ?? {};
360
- const group = (name) => (groups[name] ?? []).map(parseRobotParameter);
394
+ const group = (name) => rows(groups[name] ?? []).map(parseRobotParameter);
361
395
  return {
362
396
  manifest: {
363
397
  id: manifest.id ?? "",
@@ -367,10 +401,11 @@ export function parseMarketplaceRobot(data) {
367
401
  parameters: { manager: group("manager"), user: group("user"), platform: group("platform") },
368
402
  },
369
403
  enabled: data.enabled === true,
370
- configuration: (data.configuration ?? []).map(parseRobotParameterConfig),
404
+ configuration: rows(data.configuration ?? []).map(parseRobotParameterConfig),
371
405
  };
372
406
  }
373
407
  export function parseWidget(data) {
408
+ requireObject(data);
374
409
  return {
375
410
  id: data.id ?? null,
376
411
  marketplaceId: data.marketplaceId ?? null,
@@ -407,6 +442,7 @@ function widgetPushJson(push) {
407
442
  return body;
408
443
  }
409
444
  function parseAllotment(data) {
445
+ requireObject(data);
410
446
  // The server spells the nested capital "capital" on some responses and
411
447
  // "assets" on others, and the positions inside it "grants" or "securities".
412
448
  const assetsRaw = data.assets ?? data.capital ?? null;
@@ -417,7 +453,7 @@ function parseAllotment(data) {
417
453
  id: assetsRaw.id ?? null,
418
454
  name: assetsRaw.name ?? null,
419
455
  cash: assetsRaw.cash ?? 0,
420
- securities: orderedSecurities(securitiesRaw.map(parseSecurity)),
456
+ securities: orderedSecurities(rows(securitiesRaw).map(parseSecurity)),
421
457
  };
422
458
  }
423
459
  return {
@@ -478,6 +514,7 @@ function allotmentsToHoldings(allotments) {
478
514
  });
479
515
  }
480
516
  export function parseHolding(data) {
517
+ requireObject(data);
481
518
  const securitiesRaw = data.securities ?? data.assets ?? [];
482
519
  return {
483
520
  marketplaceId: data.marketplaceId ?? 0,
@@ -487,11 +524,12 @@ export function parseHolding(data) {
487
524
  name: data.name ?? null,
488
525
  cash: data.cash ?? 0,
489
526
  availableCash: data.availableCash ?? 0,
490
- securities: orderedSecurities(securitiesRaw.map(parseSecurity)),
527
+ securities: orderedSecurities(rows(securitiesRaw).map(parseSecurity)),
491
528
  initialCash: data.initialCash ?? null,
492
529
  };
493
530
  }
494
531
  export function parseConnection(data) {
532
+ requireObject(data);
495
533
  return {
496
534
  marketplaceId: data.marketplaceId ?? 0,
497
535
  connectionId: data.id ?? data.connectionId ?? 0,
@@ -677,6 +715,29 @@ function readBody(body) {
677
715
  throw new ApiError("Failed to parse the response body");
678
716
  }
679
717
  }
718
+ /**
719
+ * A list answer, or {@link ApiError} if this one is not a list of objects. Valid
720
+ * JSON of the wrong shape is as unreadable as JSON that is not valid, and a
721
+ * caller catching FlexemarketsError is told so either way.
722
+ */
723
+ function rows(data) {
724
+ if (!Array.isArray(data) || !data.every(isObject)) {
725
+ throw new ApiError("Failed to parse the response body: expected a list of objects");
726
+ }
727
+ return data;
728
+ }
729
+ function isObject(data) {
730
+ return typeof data === "object" && data !== null && !Array.isArray(data);
731
+ }
732
+ /**
733
+ * Every parser starts here. Reading a field of null threw a TypeError past a
734
+ * caller catching FlexemarketsError; of a number, a string or a list it read
735
+ * undefined, and handed back an order with nothing in it.
736
+ */
737
+ function requireObject(data) {
738
+ if (!isObject(data))
739
+ throw new ApiError("Failed to parse the response body: expected an object");
740
+ }
680
741
  /** The `error` a failure body names, or null when it names none. */
681
742
  function reasonIn(body) {
682
743
  try {
@@ -757,10 +818,37 @@ async function tokenExpired(resp) {
757
818
  * says with a TypeError of these two messages and nothing more specific, or
758
819
  * no answer within {@link REQUEST_TIMEOUT_MS}.
759
820
  */
760
- function answerLost(e) {
821
+ function exchangeLost(e) {
761
822
  return (e instanceof TypeError && (e.message === "fetch failed" || e.message === "terminated"))
762
823
  || (e instanceof Error && e.name === "TimeoutError");
763
824
  }
825
+ /**
826
+ * What a lost exchange is thrown as: an {@link ApiError} carrying it as its
827
+ * cause, as in the Java and Python SDKs, rather than a bare TypeError escaping
828
+ * past a caller who catches FlexemarketsError.
829
+ */
830
+ function transportFailure(e) {
831
+ if (!exchangeLost(e))
832
+ return e;
833
+ const why = e.cause instanceof Error ? `${e.message}: ${e.cause.message}` : e.message;
834
+ return new ApiError(`HTTP request failed: ${why}`, { cause: e });
835
+ }
836
+ /**
837
+ * Whether it is worth sending again: the answer was lost, as distinct from an
838
+ * ApiError for an answer that came and could not be read.
839
+ */
840
+ function answerLost(e) {
841
+ return e instanceof ApiError && exchangeLost(e.cause);
842
+ }
843
+ /** The body of an answer, which can be lost as well after its headers came. */
844
+ async function bodyOf(resp) {
845
+ try {
846
+ return await resp.text();
847
+ }
848
+ catch (e) {
849
+ throw transportFailure(e);
850
+ }
851
+ }
764
852
  /** How long a request may take, start to finish, before it is given up. */
765
853
  export const REQUEST_TIMEOUT_MS = 30_000;
766
854
  /** The timeout in force: {@link REQUEST_TIMEOUT_MS}, unless a test has shortened it. */
@@ -771,10 +859,16 @@ export const requestTimeout = { ms: REQUEST_TIMEOUT_MS };
771
859
  * waited for ever, where the Python and Java SDKs give up at 30 s -- and a
772
860
  * robot stalled on one order stopped trading without a word.
773
861
  */
774
- function fetchWithin(url, init) {
775
- return fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(requestTimeout.ms) });
862
+ async function fetchWithin(url, init) {
863
+ try {
864
+ return await fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(requestTimeout.ms) });
865
+ }
866
+ catch (e) {
867
+ throw transportFailure(e);
868
+ }
776
869
  }
777
870
  export class Flexemarkets {
871
+ _orderRoute;
778
872
  _clientDescription;
779
873
  _endpoint;
780
874
  _baseUrl;
@@ -794,15 +888,27 @@ export class Flexemarkets {
794
888
  _account;
795
889
  _user;
796
890
  _eventListener = null;
797
- constructor(endpoint, baseUrl, tokenObj, clientDescription) {
891
+ constructor(endpoint, baseUrl, tokenObj, clientDescription, _orderRoute = "SOCKET") {
892
+ this._orderRoute = _orderRoute;
798
893
  this._endpoint = endpoint;
799
894
  this._baseUrl = baseUrl;
800
895
  this._tokenObj = tokenObj;
801
896
  this._clientDescription = clientDescription;
802
897
  }
803
- /** Connect to the Flexemarkets API. */
804
- static async connect(credential, endpoint, clientDescription) {
898
+ /**
899
+ * Connect to the Flexemarkets API.
900
+ *
901
+ * `options.orderRoute` is how {@link sendLimit} and {@link sendCancel} send
902
+ * this client's orders, for its whole life: `"SOCKET"`, the default, or
903
+ * `"REST"`, batches over REST for a caller that cannot hold a socket open
904
+ * (see {@link OrderRoute}).
905
+ */
906
+ static async connect(credential, endpoint, clientDescription, options = {}) {
805
907
  const desc = clientDescription ?? "Unspecified client";
908
+ const orderRoute = (options.orderRoute ?? "SOCKET").trim().toUpperCase();
909
+ if (orderRoute !== "SOCKET" && orderRoute !== "REST") {
910
+ throw new InvalidArgumentError(`orderRoute is SOCKET or REST, not '${options.orderRoute}'`);
911
+ }
806
912
  const config = loadConfig();
807
913
  if (credential != null) {
808
914
  // A credential the caller names replaces the one ~/.fm/credential holds,
@@ -831,7 +937,7 @@ export class Flexemarkets {
831
937
  const baseUrl = server(ep);
832
938
  // Authenticate
833
939
  const tokenObj = await signIn(baseUrl, config, desc);
834
- const fm = new Flexemarkets(ep, baseUrl, tokenObj, desc);
940
+ const fm = new Flexemarkets(ep, baseUrl, tokenObj, desc, orderRoute);
835
941
  if (config[REFRESH_TOKEN_PROPERTY]?.trim()) {
836
942
  // The same object, not a copy: each renewal writes the refresh token it
837
943
  // was handed back into it, and the next presents that one.
@@ -954,7 +1060,7 @@ export class Flexemarkets {
954
1060
  "User-Agent": FM_NETWORK_CLIENT,
955
1061
  },
956
1062
  });
957
- const body = await resp.text();
1063
+ const body = await bodyOf(resp);
958
1064
  checkResponse(resp, body);
959
1065
  return readBody(body);
960
1066
  }
@@ -979,7 +1085,7 @@ export class Flexemarkets {
979
1085
  "User-Agent": FM_NETWORK_CLIENT,
980
1086
  },
981
1087
  });
982
- const body = await resp.text();
1088
+ const body = await bodyOf(resp);
983
1089
  checkResponse(resp, body);
984
1090
  return { data: readBody(body), headers: resp.headers };
985
1091
  }
@@ -992,7 +1098,7 @@ export class Flexemarkets {
992
1098
  const paged = `${url}${url.includes("?") ? "&" : "?"}limit=${limit}${before === undefined ? "" : `&before=${before}`}`;
993
1099
  const { data, headers } = await this._getRead(paged);
994
1100
  const next = NEXT_LINK.exec(headers.get("link") ?? "");
995
- return new Page(data.map(parse), next === null ? null : Number.parseInt(next[1], 10));
1101
+ return new Page(rows(data).map(parse), next === null ? null : Number.parseInt(next[1], 10));
996
1102
  }
997
1103
  /** PATCH with a JSON body -- the shape every session transition takes. */
998
1104
  async _patch(url, json) {
@@ -1013,7 +1119,7 @@ export class Flexemarkets {
1013
1119
  },
1014
1120
  body: JSON.stringify(json),
1015
1121
  });
1016
- const body = await resp.text();
1122
+ const body = await bodyOf(resp);
1017
1123
  checkResponse(resp, body);
1018
1124
  return readBody(body);
1019
1125
  }
@@ -1030,7 +1136,7 @@ export class Flexemarkets {
1030
1136
  "User-Agent": FM_NETWORK_CLIENT,
1031
1137
  },
1032
1138
  });
1033
- const body = await resp.text();
1139
+ const body = await bodyOf(resp);
1034
1140
  checkResponse(resp, body);
1035
1141
  return body;
1036
1142
  }
@@ -1046,7 +1152,7 @@ export class Flexemarkets {
1046
1152
  },
1047
1153
  body: JSON.stringify(json),
1048
1154
  });
1049
- const body = await resp.text();
1155
+ const body = await bodyOf(resp);
1050
1156
  checkResponse(resp, body);
1051
1157
  return readBody(body);
1052
1158
  }
@@ -1103,23 +1209,22 @@ export class Flexemarkets {
1103
1209
  throw new InvalidArgumentError(`No account named '${accountName}'`);
1104
1210
  }
1105
1211
  const data = await this._post(this._v1(`/accounts/${account.id}/approvals`), { approve: true });
1106
- return parseAccount(data.account);
1212
+ return anAccount(data.account);
1107
1213
  }
1108
1214
  /** One account by id. */
1109
1215
  async accountById(accountId) {
1110
- return parseAccount(await this._get(this._v1(`/accounts/${accountId}`)));
1216
+ return anAccount(await this._get(this._v1(`/accounts/${accountId}`)));
1111
1217
  }
1112
1218
  /** One user by id. */
1113
1219
  async userById(userId) {
1114
- return parsePerson(await this._get(this._v1(`/users/${userId}`)));
1220
+ return aPerson(await this._get(this._v1(`/users/${userId}`)));
1115
1221
  }
1116
1222
  /**
1117
1223
  * The names of the participants a caller may target: `GET participants`,
1118
1224
  * names only. A row carries the user id too, for a manager; not needed here.
1119
1225
  */
1120
1226
  async identifiers(marketplaceId) {
1121
- const rows = (await this._get(`${this._marketplace(marketplaceId)}/participants`));
1122
- return rows.map((r) => r.name);
1227
+ return rows(await this._get(`${this._marketplace(marketplaceId)}/participants`)).map((r) => r.name);
1123
1228
  }
1124
1229
  /** Delete the caller's own account. Its own route, not accounts/{yourId}. */
1125
1230
  async deleteMyAccount() {
@@ -1128,14 +1233,14 @@ export class Flexemarkets {
1128
1233
  /** Every account on the server. Admin-only. */
1129
1234
  async accounts() {
1130
1235
  const data = await this._get(this._v1("/accounts"));
1131
- return data.map(parseAccount);
1236
+ return rows(data).map(anAccount);
1132
1237
  }
1133
1238
  /**
1134
1239
  * A page of `accounts()`: the newest `limit`, or of those whose id is below
1135
1240
  * `before` -- a page's `next`. The server answers at most 5,000.
1136
1241
  */
1137
1242
  async accountsPage(limit, before) {
1138
- return this._page(this._v1("/accounts"), limit, before, (a) => parseAccount(a));
1243
+ return this._page(this._v1("/accounts"), limit, before, anAccount);
1139
1244
  }
1140
1245
  /** Delete an account. Destructive, and takes its users with it. */
1141
1246
  async deleteAccount(accountId) {
@@ -1145,7 +1250,7 @@ export class Flexemarkets {
1145
1250
  async createUser(email, password, firstName, lastName, roles = []) {
1146
1251
  const user = { email, password, firstName, lastName, roles };
1147
1252
  const data = await this._create((key) => this._post(this._v1("/users"), user, key));
1148
- return parsePerson(data);
1253
+ return aPerson(data);
1149
1254
  }
1150
1255
  /** Delete a user. Destructive. */
1151
1256
  async deleteUser(userId) {
@@ -1233,7 +1338,7 @@ export class Flexemarkets {
1233
1338
  const data = await this._post(url, { userIds });
1234
1339
  return {
1235
1340
  expiresAt: toInstant(data.expiresAt),
1236
- otps: (data.otps ?? []).map((o) => ({
1341
+ otps: rows(data.otps ?? []).map((o) => ({
1237
1342
  userId: o.userId ?? 0,
1238
1343
  email: o.email ?? null,
1239
1344
  otp: o.otp ?? null,
@@ -1246,7 +1351,7 @@ export class Flexemarkets {
1246
1351
  method: "DELETE",
1247
1352
  headers: { ...this._authHeaders(), Accept: "application/json" },
1248
1353
  });
1249
- const body = await resp.text();
1354
+ const body = await bodyOf(resp);
1250
1355
  checkResponse(resp, body);
1251
1356
  }
1252
1357
  /**
@@ -1257,7 +1362,7 @@ export class Flexemarkets {
1257
1362
  method: "DELETE",
1258
1363
  headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
1259
1364
  });
1260
- const body = await resp.text();
1365
+ const body = await bodyOf(resp);
1261
1366
  checkResponse(resp, body);
1262
1367
  return readBody(body);
1263
1368
  }
@@ -1301,7 +1406,7 @@ export class Flexemarkets {
1301
1406
  },
1302
1407
  body: content,
1303
1408
  });
1304
- const body = await resp.text();
1409
+ const body = await bodyOf(resp);
1305
1410
  checkResponse(resp, body);
1306
1411
  return readBody(body);
1307
1412
  }
@@ -1323,7 +1428,7 @@ export class Flexemarkets {
1323
1428
  // -- marketplaces ----------------------------------------------------------
1324
1429
  async marketplaces() {
1325
1430
  const data = await this._get(this._v1("/marketplaces"));
1326
- return data.map(parseMarketplace);
1431
+ return rows(data).map(parseMarketplace);
1327
1432
  }
1328
1433
  /**
1329
1434
  * A page of `marketplaces()`: the newest `limit`, or of those whose id is below
@@ -1339,7 +1444,7 @@ export class Flexemarkets {
1339
1444
  */
1340
1445
  async currentSessions() {
1341
1446
  const data = await this._get(this._v1("/marketplaces/current-sessions"));
1342
- return data.map(parseCurrentSession);
1447
+ return rows(data).map(parseCurrentSession);
1343
1448
  }
1344
1449
  /**
1345
1450
  * A page of `currentSessions()`, paged by marketplace as `marketplacesPage()`
@@ -1356,7 +1461,7 @@ export class Flexemarkets {
1356
1461
  // -- markets ---------------------------------------------------------------
1357
1462
  async markets(marketplaceId) {
1358
1463
  const data = await this._get(`${this._marketplace(marketplaceId)}/markets`);
1359
- return data.map(parseMarket);
1464
+ return rows(data).map(parseMarket);
1360
1465
  }
1361
1466
  /**
1362
1467
  * What an indicative call market's book would clear at now: the price and
@@ -1409,7 +1514,7 @@ export class Flexemarkets {
1409
1514
  */
1410
1515
  async sessions(marketplaceId) {
1411
1516
  const url = `${this._marketplace(marketplaceId)}/sessions`;
1412
- return (await this._get(url)).map(parseSession);
1517
+ return rows(await this._get(url)).map(parseSession);
1413
1518
  }
1414
1519
  /**
1415
1520
  * A page of `sessions()`: the newest `limit`, or of those whose id is below
@@ -1461,6 +1566,13 @@ export class Flexemarkets {
1461
1566
  * stays open until {@link close}; at most `MAX_IN_FLIGHT` orders are
1462
1567
  * unanswered at once, and this waits, in turn, while they are. The arguments
1463
1568
  * are {@link submitLimit}'s. See docs/SUBMIT-RATE.md.
1569
+ *
1570
+ * On a client connected with `orderRoute: "REST"` the order goes over REST
1571
+ * instead: one `POST .../orders/batch` is in flight at a time, and the orders
1572
+ * sent while it is out -- at most 64 -- go together as the next, in the order
1573
+ * sent. Its `result()` is then the order or the refusal, or
1574
+ * {@link OrderOutcomeUnknownError} if the request was sent twice without a
1575
+ * readable answer. Needs fm-server 4.19.
1464
1576
  */
1465
1577
  async sendLimit(marketplaceId, marketId, side, units, price, options = {}) {
1466
1578
  const order = this._limitOrder(marketplaceId, marketId, side, units, price, options);
@@ -1489,30 +1601,39 @@ export class Flexemarkets {
1489
1601
  const answered = [];
1490
1602
  for (let start = 0; start < orders.length; start += MOST_BATCHED) {
1491
1603
  const batch = orders.slice(start, start + MOST_BATCHED);
1492
- let data;
1493
- try {
1494
- data = await this._post(url, batch);
1495
- }
1496
- catch (e) {
1497
- if (!answerLost(e))
1498
- throw e;
1499
- data = await this._post(url, batch);
1500
- }
1501
- if (!Array.isArray(data) || data.length !== batch.length) {
1502
- throw new ApiError(`Expected ${batch.length} answers to a batch of ${batch.length} orders`);
1503
- }
1604
+ const outcomes = await this._postBatch(url, batch);
1504
1605
  batch.forEach((order, i) => {
1505
- const entry = data[i];
1506
1606
  const pending = new PendingOrder(order.submissionId);
1507
- const status = typeof entry.status === "number" ? entry.status : 0;
1508
- pending._answer(status >= 200 && status < 300
1509
- ? parseOrder(entry.order)
1510
- : refused(status, JSON.stringify(entry.failure ?? null)));
1607
+ pending._answer(outcomes[i]);
1511
1608
  answered.push(pending);
1512
1609
  });
1513
1610
  }
1514
1611
  return answered;
1515
1612
  }
1613
+ /**
1614
+ * One `POST .../orders/batch`, sent once more, whole, if its answer was lost:
1615
+ * each order's placed order, or the error its refusal throws.
1616
+ */
1617
+ async _postBatch(url, batch) {
1618
+ let data;
1619
+ try {
1620
+ data = await this._post(url, batch);
1621
+ }
1622
+ catch (e) {
1623
+ if (!answerLost(e))
1624
+ throw e;
1625
+ data = await this._post(url, batch);
1626
+ }
1627
+ if (!Array.isArray(data) || data.length !== batch.length) {
1628
+ throw new ApiError(`Expected ${batch.length} answers to a batch of ${batch.length} orders`);
1629
+ }
1630
+ return rows(data).map((entry) => {
1631
+ const status = typeof entry.status === "number" ? entry.status : 0;
1632
+ return status >= 200 && status < 300
1633
+ ? parseOrder(entry.order)
1634
+ : refused(status, JSON.stringify(entry.failure ?? null));
1635
+ });
1636
+ }
1516
1637
  /** The body of a limit order, named with a fresh submission id. */
1517
1638
  _limitOrder(marketplaceId, marketId, side, units, price, options) {
1518
1639
  const { ownerTarget, ownerTargetId, clientDescription } = options;
@@ -1542,9 +1663,23 @@ export class Flexemarkets {
1542
1663
  order.submissionId = randomUUID();
1543
1664
  return order;
1544
1665
  }
1545
- /** The marketplace's order socket, opened on first use; one open for concurrent first callers. */
1666
+ /**
1667
+ * Where the marketplace's sent orders go, by this client's {@link OrderRoute}:
1668
+ * its order socket, opened on first use (one open for concurrent first
1669
+ * callers), or its REST window.
1670
+ */
1546
1671
  _orderStream(marketplaceId) {
1547
1672
  let stream = this._orderStreams.get(marketplaceId);
1673
+ if (stream === undefined && this._orderRoute === "REST") {
1674
+ const url = `${this._marketplace(marketplaceId)}/orders/batch`;
1675
+ stream = Promise.resolve(new RestOrderWindow((batch) => this._postBatch(url, batch), {
1676
+ notSent: (message) => new ConnectionFailedError(message),
1677
+ outcomeUnknown: (message, submissionId) => new OrderOutcomeUnknownError(message, submissionId),
1678
+ refusedWhole: (failure) => failure instanceof FlexemarketsError
1679
+ && typeof failure.statusCode === "number" && failure.statusCode >= 400 && failure.statusCode < 500,
1680
+ }));
1681
+ this._orderStreams.set(marketplaceId, stream);
1682
+ }
1548
1683
  if (stream === undefined) {
1549
1684
  stream = OrderStream.open((callback) => this._connectEvents(marketplaceId, callback, false, RECONNECT_MAX_MS), marketplaceId, {
1550
1685
  notSent: (message) => new ConnectionFailedError(message),
@@ -1618,11 +1753,32 @@ export class Flexemarkets {
1618
1753
  * {@link submitLimit} answered, its `id`. Unlike {@link submitCancel}'s DELETE,
1619
1754
  * which looks the order up, the socket's CANCEL goes to the exchange as named,
1620
1755
  * and the id of a fragment a split left behind matches nothing -- the CANCEL is
1621
- * recorded, consumed by itself, and nothing is cancelled. An order not yet
1622
- * answered has no id and cannot be cancelled this way. `marketId` goes on the
1756
+ * recorded, consumed by itself, and nothing is cancelled. `marketId` goes on the
1623
1757
  * wire: the socket's CANCEL names its market.
1758
+ *
1759
+ * An order not yet answered has no id, but it has its
1760
+ * {@link PendingOrder.submissionId} from the moment it is sent. Given that string
1761
+ * in place of an id, which needs fm-server 4.20, the cancel names the order by it
1762
+ * alone and can go right behind its {@link sendLimit}: it goes through the same
1763
+ * window, and fm-server takes them in the order sent, on the socket and on the
1764
+ * REST route alike. A split is no concern, as fm-server finds the order and
1765
+ * cancels through its original, and `marketId` is not on the wire, as the order
1766
+ * names its own market. Only the caller's own LIMIT orders are found. One it has
1767
+ * none of in the marketplace, which includes a limit that was itself refused, is
1768
+ * refused as not found: 404 `ORDER_NOT_IN_MARKETPLACE` on either route. fm-server
1769
+ * 4.23 and earlier answer it 400 `ORDER_INVALID` on the socket.
1624
1770
  */
1625
1771
  async sendCancel(marketplaceId, marketId, originalId) {
1772
+ if (typeof originalId === "string") {
1773
+ // By this alone, on either route: fm-server refuses a CANCEL naming its
1774
+ // order both ways, and fills in the ids and the market from what it finds.
1775
+ return (await this._orderStream(marketplaceId)).submit({
1776
+ marketplaceId,
1777
+ type: "CANCEL",
1778
+ originalSubmissionId: originalId,
1779
+ submissionId: randomUUID(),
1780
+ });
1781
+ }
1626
1782
  const cancel = {
1627
1783
  marketplaceId,
1628
1784
  marketId,
@@ -1632,6 +1788,12 @@ export class Flexemarkets {
1632
1788
  // with the one fm-server already recorded.
1633
1789
  submissionId: randomUUID(),
1634
1790
  };
1791
+ if (this._orderRoute === "REST") {
1792
+ // As a REST CANCEL has always named its order. The exchange matches it by
1793
+ // the original as given, which is why it must be one.
1794
+ cancel.id = originalId;
1795
+ cancel.supplier = originalId;
1796
+ }
1635
1797
  return (await this._orderStream(marketplaceId)).submit(cancel);
1636
1798
  }
1637
1799
  /**
@@ -1686,7 +1848,7 @@ export class Flexemarkets {
1686
1848
  if (options?.symbol != null) {
1687
1849
  const symbol = options.symbol;
1688
1850
  const data = await this._get(`${base}?state=ACTIVE&symbol=${encodeURIComponent(symbol)}`);
1689
- const orders = data.map(parseOrder);
1851
+ const orders = rows(data).map(parseOrder);
1690
1852
  for (const o of orders)
1691
1853
  o.symbol = symbol;
1692
1854
  return orders;
@@ -1694,7 +1856,7 @@ export class Flexemarkets {
1694
1856
  const url = options?.sessionIds != null && options.sessionIds.length > 0
1695
1857
  ? `${base}?sessions=${options.sessionIds.join(",")}`
1696
1858
  : `${base}?cancelled=false`;
1697
- return (await this._get(url)).map(parseOrder);
1859
+ return rows(await this._get(url)).map(parseOrder);
1698
1860
  }
1699
1861
  /**
1700
1862
  * A page of `orders()` with no filter -- cancellations left out, as there:
@@ -1717,7 +1879,7 @@ export class Flexemarkets {
1717
1879
  const url = `${this._marketplace(marketplaceId)}/orders?state=TRADED` +
1718
1880
  `&symbol=${encodeURIComponent(symbol)}&limit=${MAX_TRADED_LEGS}`;
1719
1881
  const data = await this._get(url);
1720
- const orders = data.map(parseOrder);
1882
+ const orders = rows(data).map(parseOrder);
1721
1883
  for (const o of orders) {
1722
1884
  o.id = o.original;
1723
1885
  o.symbol = symbol;
@@ -1731,7 +1893,7 @@ export class Flexemarkets {
1731
1893
  if (sessionIds && sessionIds.length > 0)
1732
1894
  url += `?sessions=${sessionIds.join(",")}`;
1733
1895
  const data = await this._get(url);
1734
- return data.map(parseHolding);
1896
+ return rows(data).map(parseHolding);
1735
1897
  }
1736
1898
  async holding(marketplaceId) {
1737
1899
  return parseHolding(await this._get(`${this._marketplace(marketplaceId)}/participants/me/holding`));
@@ -1746,7 +1908,7 @@ export class Flexemarkets {
1746
1908
  */
1747
1909
  async connections(marketplaceId) {
1748
1910
  const url = `${this._marketplace(marketplaceId)}/connections`;
1749
- return (await this._get(url)).map(parseConnection);
1911
+ return rows(await this._get(url)).map(parseConnection);
1750
1912
  }
1751
1913
  /**
1752
1914
  * A page of `connections()`: the newest `limit`, or of those whose id is below
@@ -1807,20 +1969,20 @@ export class Flexemarkets {
1807
1969
  /** Everyone in the caller's account. */
1808
1970
  async users() {
1809
1971
  const data = await this._get(this._v1("/users"));
1810
- return data.map((u) => parsePerson(u));
1972
+ return rows(data).map(aPerson);
1811
1973
  }
1812
1974
  /**
1813
1975
  * A page of `users()`: the newest `limit`, or of those whose id is below
1814
1976
  * `before` -- a page's `next`. The server answers at most 5,000.
1815
1977
  */
1816
1978
  async usersPage(limit, before) {
1817
- return this._page(this._v1("/users"), limit, before, (u) => parsePerson(u));
1979
+ return this._page(this._v1("/users"), limit, before, aPerson);
1818
1980
  }
1819
1981
  /** The opening positions of one allocation. */
1820
1982
  async allotments(marketplaceId, allocationId) {
1821
1983
  const url = `${this._marketplace(marketplaceId)}/allocations/${allocationId}/allotments`;
1822
1984
  const data = await this._get(url);
1823
- return data.map(parseAllotment);
1985
+ return rows(data).map(parseAllotment);
1824
1986
  }
1825
1987
  /**
1826
1988
  * Stage the opening positions for the next session.
@@ -1836,7 +1998,7 @@ export class Flexemarkets {
1836
1998
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1837
1999
  const body = holdings.map((h) => holdingToAllotment(marketplaceId, h));
1838
2000
  const data = await this._create((key) => this._post(url, body, key));
1839
- return allotmentsToHoldings(data.map(parseAllotment));
2001
+ return allotmentsToHoldings(rows(data).map(parseAllotment));
1840
2002
  }
1841
2003
  /**
1842
2004
  * The holdings CSV, verbatim, for the current session or for given ones.
@@ -1856,8 +2018,8 @@ export class Flexemarkets {
1856
2018
  */
1857
2019
  async uploadHoldings(marketplaceId, filename) {
1858
2020
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1859
- const data = (await this._create((key) => this._sendCsv("POST", url, filename, key)));
1860
- return allotmentsToHoldings(data.map(parseAllotment));
2021
+ const data = await this._create((key) => this._sendCsv("POST", url, filename, key));
2022
+ return allotmentsToHoldings(rows(data).map(parseAllotment));
1861
2023
  }
1862
2024
  /**
1863
2025
  * Stage an allocation from holdings CSV text, as {@link uploadHoldings} does
@@ -1871,8 +2033,8 @@ export class Flexemarkets {
1871
2033
  */
1872
2034
  async uploadHoldingsCsv(marketplaceId, csv) {
1873
2035
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1874
- const data = (await this._create((key) => this._sendCsvContent("POST", url, csv, key)));
1875
- return allotmentsToHoldings(data.map(parseAllotment));
2036
+ const data = await this._create((key) => this._sendCsvContent("POST", url, csv, key));
2037
+ return allotmentsToHoldings(rows(data).map(parseAllotment));
1876
2038
  }
1877
2039
  /**
1878
2040
  * Load per-participant private state from a CSV, returning what was stored.
@@ -1890,8 +2052,8 @@ export class Flexemarkets {
1890
2052
  */
1891
2053
  async uploadState(marketplaceId, filename) {
1892
2054
  const url = `${this._marketplace(marketplaceId)}/state`;
1893
- const data = (await this._sendCsv("PUT", url, filename));
1894
- return data.map(parseParticipantState);
2055
+ const data = await this._sendCsv("PUT", url, filename);
2056
+ return rows(data).map(parseParticipantState);
1895
2057
  }
1896
2058
  /**
1897
2059
  * Push widgets to participants' screens, returning them as stored.
@@ -1913,7 +2075,7 @@ export class Flexemarkets {
1913
2075
  const url = `${this._marketplace(marketplaceId)}/widgets`;
1914
2076
  const pushes = widgets.map(widgetPushJson);
1915
2077
  const data = await this._create((key) => this._post(url, pushes, key));
1916
- return data.map(parseWidget);
2078
+ return rows(data).map(parseWidget);
1917
2079
  }
1918
2080
  /**
1919
2081
  * Take down a widget: the marketplace's for `key`, or one participant's.
@@ -1933,7 +2095,7 @@ export class Flexemarkets {
1933
2095
  method: "DELETE",
1934
2096
  headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
1935
2097
  });
1936
- const body = await resp.text();
2098
+ const body = await bodyOf(resp);
1937
2099
  if (resp.status === 404 && body.trim() === "")
1938
2100
  return false;
1939
2101
  checkResponse(resp, body);
@@ -1949,8 +2111,9 @@ export class Flexemarkets {
1949
2111
  */
1950
2112
  async allWidgets(marketplaceId) {
1951
2113
  const data = await this._get(`${this._marketplace(marketplaceId)}/widgets?participant=all`);
2114
+ requireObject(Array.isArray(data) ? {} : data);
1952
2115
  const widgets = Array.isArray(data) ? data : (data.widgets ?? []);
1953
- return widgets.map(parseWidget);
2116
+ return rows(widgets).map(parseWidget);
1954
2117
  }
1955
2118
  /**
1956
2119
  * Clear a call-auction market now: every crossing order trades at one
@@ -1968,7 +2131,7 @@ export class Flexemarkets {
1968
2131
  async calls(marketplaceId, sessionId) {
1969
2132
  const query = sessionId === undefined ? "" : `?sessions=${sessionId}`;
1970
2133
  const data = await this._get(`${this._marketplace(marketplaceId)}/calls${query}`);
1971
- return data.map(parseMarketCall);
2134
+ return rows(data).map(parseMarketCall);
1972
2135
  }
1973
2136
  /**
1974
2137
  * A page of `calls()`: the newest `limit`, or of those whose id is below
@@ -1987,7 +2150,7 @@ export class Flexemarkets {
1987
2150
  */
1988
2151
  async marketplaceRobots(marketplaceId) {
1989
2152
  const data = await this._get(`${this._marketplace(marketplaceId)}/robots`);
1990
- return data.map(parseMarketplaceRobot);
2153
+ return rows(data).map(parseMarketplaceRobot);
1991
2154
  }
1992
2155
  /**
1993
2156
  * Set a robot parameter's value in a marketplace, and whether participants
@@ -2141,10 +2304,15 @@ export class Flexemarkets {
2141
2304
  const wsUrl = server(this._endpoint)
2142
2305
  .replace("https://", "wss://")
2143
2306
  .replace("http://", "ws://") + "/v1/events";
2144
- const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented), history, refused);
2307
+ const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented), history, refused, (message) => new ApiError(message));
2145
2308
  if (reconnectMaxPauseMs !== undefined)
2146
2309
  events.reconnectMaxPauseMs = reconnectMaxPauseMs;
2147
- await events.start();
2310
+ try {
2311
+ await events.start();
2312
+ }
2313
+ catch (e) {
2314
+ throw new ConnectionFailedError(`The event stream could not connect: ${String(e)}`, { cause: e });
2315
+ }
2148
2316
  return events;
2149
2317
  }
2150
2318
  /** Reconnect the WebSocket after a transport error. */
@@ -2199,7 +2367,7 @@ async function renewWithRefreshToken(baseUrl, config) {
2199
2367
  },
2200
2368
  body: JSON.stringify({ refreshToken: config[REFRESH_TOKEN_PROPERTY].trim() }),
2201
2369
  });
2202
- const body = await resp.text();
2370
+ const body = await bodyOf(resp);
2203
2371
  checkResponse(resp, body);
2204
2372
  const data = readBody(body);
2205
2373
  if (typeof data.refreshToken === "string" && data.refreshToken) {
@@ -2232,7 +2400,7 @@ async function signIn(baseUrl, config, clientDescription) {
2232
2400
  "User-Agent": FM_NETWORK_CLIENT,
2233
2401
  },
2234
2402
  });
2235
- const body = await resp.text();
2403
+ const body = await bodyOf(resp);
2236
2404
  checkResponse(resp, body);
2237
2405
  return parseToken(readBody(body));
2238
2406
  }
@@ -2258,7 +2426,7 @@ async function signIn(baseUrl, config, clientDescription) {
2258
2426
  password,
2259
2427
  }),
2260
2428
  });
2261
- const body = await resp.text();
2429
+ const body = await bodyOf(resp);
2262
2430
  checkResponse(resp, body);
2263
2431
  return parseToken(readBody(body));
2264
2432
  }