@flexemarkets/fm-sdk 0.18.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/README.md CHANGED
@@ -13,7 +13,7 @@ TypeScript / JavaScript SDK for the [Flexemarkets](https://api.flexemarkets.com)
13
13
  >
14
14
  > Pin an exact version rather than a range (`"@flexemarkets/fm-sdk": "0.2.0"`,
15
15
  > not `^0.2.0`), read the
16
- > [upgrade notes](https://github.com/flexemarkets/fm-sdk/tree/main/docs) for the
16
+ > [upgrade notes](https://github.com/flexemarkets/fm-sdk/blob/main/docs/UPGRADING.md) for the
17
17
  > release you are moving to, and expect to change code when you move.
18
18
  >
19
19
  > Not recommended for production use.
package/dist/client.d.ts CHANGED
@@ -306,9 +306,9 @@ export declare class Flexemarkets {
306
306
  * V1 approves an account by id; the name is looked up in the account list
307
307
  * first, so callers keep naming the account they signed up.
308
308
  */
309
- approveAccount(accountName: string): Promise<Account | null>;
309
+ approveAccount(accountName: string): Promise<Account>;
310
310
  /** One account by id. */
311
- accountById(accountId: number): Promise<Account | null>;
311
+ accountById(accountId: number): Promise<Account>;
312
312
  /** One user by id. */
313
313
  userById(userId: number): Promise<Person>;
314
314
  /**
package/dist/client.js CHANGED
@@ -161,6 +161,7 @@ export class PersonHasMarketplaceDataError extends ConflictError {
161
161
  export function parsePerson(data) {
162
162
  if (!data)
163
163
  return null;
164
+ requireObject(data);
164
165
  return {
165
166
  id: data.id ?? 0,
166
167
  accountId: data.accountId ?? 0,
@@ -175,9 +176,24 @@ export function parsePerson(data) {
175
176
  lastSignInMethod: data.lastSignInMethod ?? null,
176
177
  };
177
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
+ }
178
193
  export function parseAccount(data) {
179
194
  if (!data)
180
195
  return null;
196
+ requireObject(data);
181
197
  return {
182
198
  id: data.id ?? null,
183
199
  name: data.name ?? null,
@@ -190,6 +206,7 @@ export function parseAccount(data) {
190
206
  };
191
207
  }
192
208
  export function parseToken(data) {
209
+ requireObject(data);
193
210
  return {
194
211
  requestUrl: data.requestUrl ?? null,
195
212
  person: parsePerson(data.person),
@@ -198,6 +215,7 @@ export function parseToken(data) {
198
215
  };
199
216
  }
200
217
  export function parseSecurity(data) {
218
+ requireObject(data);
201
219
  return {
202
220
  marketId: data.marketId ?? 0,
203
221
  units: data.units ?? 0,
@@ -210,6 +228,7 @@ export function parseSecurity(data) {
210
228
  };
211
229
  }
212
230
  export function parseMarket(data) {
231
+ requireObject(data);
213
232
  return {
214
233
  id: data.id ?? 0,
215
234
  marketplaceId: data.marketplaceId ?? 0,
@@ -232,6 +251,7 @@ export function parseMarket(data) {
232
251
  };
233
252
  }
234
253
  export function parseCurrentSession(data) {
254
+ requireObject(data);
235
255
  return {
236
256
  marketplaceId: data.marketplaceId ?? 0,
237
257
  sessionId: data.sessionId ?? 0,
@@ -239,6 +259,7 @@ export function parseCurrentSession(data) {
239
259
  };
240
260
  }
241
261
  export function parseCallIndicative(data) {
262
+ requireObject(data);
242
263
  return {
243
264
  marketplaceId: data.marketplaceId ?? 0,
244
265
  marketId: data.marketId ?? 0,
@@ -250,6 +271,7 @@ export function parseCallIndicative(data) {
250
271
  };
251
272
  }
252
273
  export function parseMarketCall(data) {
274
+ requireObject(data);
253
275
  return {
254
276
  id: data.id ?? 0,
255
277
  marketplaceId: data.marketplaceId ?? 0,
@@ -267,15 +289,17 @@ export function parseMarketCall(data) {
267
289
  };
268
290
  }
269
291
  export function parseMarketplace(data) {
292
+ requireObject(data);
270
293
  return {
271
294
  id: data.id ?? 0,
272
295
  name: data.name ?? null,
273
296
  description: data.description ?? null,
274
- markets: (data.markets ?? []).map(parseMarket),
297
+ markets: rows(data.markets ?? []).map(parseMarket),
275
298
  cashDecimals: data.cashDecimals ?? Decimals.DEFAULT_CASH_DECIMALS,
276
299
  };
277
300
  }
278
301
  export function parseSession(data) {
302
+ requireObject(data);
279
303
  return {
280
304
  marketplaceId: data.marketplaceId ?? 0,
281
305
  allocationId: data.allocationId ?? 0,
@@ -291,8 +315,13 @@ export function parseSession(data) {
291
315
  };
292
316
  }
293
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");
294
323
  return {
295
- id: data.id ?? 0,
324
+ id: data.id,
296
325
  original: data.original ?? 0,
297
326
  supplier: data.supplier ?? 0,
298
327
  consumer: data.consumer ?? null,
@@ -316,6 +345,7 @@ export function parseOrder(data) {
316
345
  };
317
346
  }
318
347
  export function parseParticipantState(data) {
348
+ requireObject(data);
319
349
  return {
320
350
  marketplaceId: data.marketplaceId ?? null,
321
351
  allocationId: data.allocationId ?? null,
@@ -328,6 +358,7 @@ function numberOrNull(value) {
328
358
  return value === null || value === undefined ? null : Number(value);
329
359
  }
330
360
  function parseRobotParameter(data) {
361
+ requireObject(data);
331
362
  return {
332
363
  name: data.name ?? "",
333
364
  label: data.label ?? null,
@@ -343,6 +374,7 @@ function parseRobotParameter(data) {
343
374
  };
344
375
  }
345
376
  export function parseRobotParameterConfig(data) {
377
+ requireObject(data);
346
378
  const control = data.control ?? null;
347
379
  return {
348
380
  marketplaceId: data.marketplaceId ?? null,
@@ -356,9 +388,10 @@ export function parseRobotParameterConfig(data) {
356
388
  };
357
389
  }
358
390
  export function parseMarketplaceRobot(data) {
391
+ requireObject(data);
359
392
  const manifest = data.manifest ?? {};
360
393
  const groups = manifest.parameters ?? {};
361
- const group = (name) => (groups[name] ?? []).map(parseRobotParameter);
394
+ const group = (name) => rows(groups[name] ?? []).map(parseRobotParameter);
362
395
  return {
363
396
  manifest: {
364
397
  id: manifest.id ?? "",
@@ -368,10 +401,11 @@ export function parseMarketplaceRobot(data) {
368
401
  parameters: { manager: group("manager"), user: group("user"), platform: group("platform") },
369
402
  },
370
403
  enabled: data.enabled === true,
371
- configuration: (data.configuration ?? []).map(parseRobotParameterConfig),
404
+ configuration: rows(data.configuration ?? []).map(parseRobotParameterConfig),
372
405
  };
373
406
  }
374
407
  export function parseWidget(data) {
408
+ requireObject(data);
375
409
  return {
376
410
  id: data.id ?? null,
377
411
  marketplaceId: data.marketplaceId ?? null,
@@ -408,6 +442,7 @@ function widgetPushJson(push) {
408
442
  return body;
409
443
  }
410
444
  function parseAllotment(data) {
445
+ requireObject(data);
411
446
  // The server spells the nested capital "capital" on some responses and
412
447
  // "assets" on others, and the positions inside it "grants" or "securities".
413
448
  const assetsRaw = data.assets ?? data.capital ?? null;
@@ -418,7 +453,7 @@ function parseAllotment(data) {
418
453
  id: assetsRaw.id ?? null,
419
454
  name: assetsRaw.name ?? null,
420
455
  cash: assetsRaw.cash ?? 0,
421
- securities: orderedSecurities(securitiesRaw.map(parseSecurity)),
456
+ securities: orderedSecurities(rows(securitiesRaw).map(parseSecurity)),
422
457
  };
423
458
  }
424
459
  return {
@@ -479,6 +514,7 @@ function allotmentsToHoldings(allotments) {
479
514
  });
480
515
  }
481
516
  export function parseHolding(data) {
517
+ requireObject(data);
482
518
  const securitiesRaw = data.securities ?? data.assets ?? [];
483
519
  return {
484
520
  marketplaceId: data.marketplaceId ?? 0,
@@ -488,11 +524,12 @@ export function parseHolding(data) {
488
524
  name: data.name ?? null,
489
525
  cash: data.cash ?? 0,
490
526
  availableCash: data.availableCash ?? 0,
491
- securities: orderedSecurities(securitiesRaw.map(parseSecurity)),
527
+ securities: orderedSecurities(rows(securitiesRaw).map(parseSecurity)),
492
528
  initialCash: data.initialCash ?? null,
493
529
  };
494
530
  }
495
531
  export function parseConnection(data) {
532
+ requireObject(data);
496
533
  return {
497
534
  marketplaceId: data.marketplaceId ?? 0,
498
535
  connectionId: data.id ?? data.connectionId ?? 0,
@@ -678,6 +715,29 @@ function readBody(body) {
678
715
  throw new ApiError("Failed to parse the response body");
679
716
  }
680
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
+ }
681
741
  /** The `error` a failure body names, or null when it names none. */
682
742
  function reasonIn(body) {
683
743
  try {
@@ -758,10 +818,37 @@ async function tokenExpired(resp) {
758
818
  * says with a TypeError of these two messages and nothing more specific, or
759
819
  * no answer within {@link REQUEST_TIMEOUT_MS}.
760
820
  */
761
- function answerLost(e) {
821
+ function exchangeLost(e) {
762
822
  return (e instanceof TypeError && (e.message === "fetch failed" || e.message === "terminated"))
763
823
  || (e instanceof Error && e.name === "TimeoutError");
764
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
+ }
765
852
  /** How long a request may take, start to finish, before it is given up. */
766
853
  export const REQUEST_TIMEOUT_MS = 30_000;
767
854
  /** The timeout in force: {@link REQUEST_TIMEOUT_MS}, unless a test has shortened it. */
@@ -772,8 +859,13 @@ export const requestTimeout = { ms: REQUEST_TIMEOUT_MS };
772
859
  * waited for ever, where the Python and Java SDKs give up at 30 s -- and a
773
860
  * robot stalled on one order stopped trading without a word.
774
861
  */
775
- function fetchWithin(url, init) {
776
- 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
+ }
777
869
  }
778
870
  export class Flexemarkets {
779
871
  _orderRoute;
@@ -968,7 +1060,7 @@ export class Flexemarkets {
968
1060
  "User-Agent": FM_NETWORK_CLIENT,
969
1061
  },
970
1062
  });
971
- const body = await resp.text();
1063
+ const body = await bodyOf(resp);
972
1064
  checkResponse(resp, body);
973
1065
  return readBody(body);
974
1066
  }
@@ -993,7 +1085,7 @@ export class Flexemarkets {
993
1085
  "User-Agent": FM_NETWORK_CLIENT,
994
1086
  },
995
1087
  });
996
- const body = await resp.text();
1088
+ const body = await bodyOf(resp);
997
1089
  checkResponse(resp, body);
998
1090
  return { data: readBody(body), headers: resp.headers };
999
1091
  }
@@ -1006,7 +1098,7 @@ export class Flexemarkets {
1006
1098
  const paged = `${url}${url.includes("?") ? "&" : "?"}limit=${limit}${before === undefined ? "" : `&before=${before}`}`;
1007
1099
  const { data, headers } = await this._getRead(paged);
1008
1100
  const next = NEXT_LINK.exec(headers.get("link") ?? "");
1009
- 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));
1010
1102
  }
1011
1103
  /** PATCH with a JSON body -- the shape every session transition takes. */
1012
1104
  async _patch(url, json) {
@@ -1027,7 +1119,7 @@ export class Flexemarkets {
1027
1119
  },
1028
1120
  body: JSON.stringify(json),
1029
1121
  });
1030
- const body = await resp.text();
1122
+ const body = await bodyOf(resp);
1031
1123
  checkResponse(resp, body);
1032
1124
  return readBody(body);
1033
1125
  }
@@ -1044,7 +1136,7 @@ export class Flexemarkets {
1044
1136
  "User-Agent": FM_NETWORK_CLIENT,
1045
1137
  },
1046
1138
  });
1047
- const body = await resp.text();
1139
+ const body = await bodyOf(resp);
1048
1140
  checkResponse(resp, body);
1049
1141
  return body;
1050
1142
  }
@@ -1060,7 +1152,7 @@ export class Flexemarkets {
1060
1152
  },
1061
1153
  body: JSON.stringify(json),
1062
1154
  });
1063
- const body = await resp.text();
1155
+ const body = await bodyOf(resp);
1064
1156
  checkResponse(resp, body);
1065
1157
  return readBody(body);
1066
1158
  }
@@ -1117,23 +1209,22 @@ export class Flexemarkets {
1117
1209
  throw new InvalidArgumentError(`No account named '${accountName}'`);
1118
1210
  }
1119
1211
  const data = await this._post(this._v1(`/accounts/${account.id}/approvals`), { approve: true });
1120
- return parseAccount(data.account);
1212
+ return anAccount(data.account);
1121
1213
  }
1122
1214
  /** One account by id. */
1123
1215
  async accountById(accountId) {
1124
- return parseAccount(await this._get(this._v1(`/accounts/${accountId}`)));
1216
+ return anAccount(await this._get(this._v1(`/accounts/${accountId}`)));
1125
1217
  }
1126
1218
  /** One user by id. */
1127
1219
  async userById(userId) {
1128
- return parsePerson(await this._get(this._v1(`/users/${userId}`)));
1220
+ return aPerson(await this._get(this._v1(`/users/${userId}`)));
1129
1221
  }
1130
1222
  /**
1131
1223
  * The names of the participants a caller may target: `GET participants`,
1132
1224
  * names only. A row carries the user id too, for a manager; not needed here.
1133
1225
  */
1134
1226
  async identifiers(marketplaceId) {
1135
- const rows = (await this._get(`${this._marketplace(marketplaceId)}/participants`));
1136
- return rows.map((r) => r.name);
1227
+ return rows(await this._get(`${this._marketplace(marketplaceId)}/participants`)).map((r) => r.name);
1137
1228
  }
1138
1229
  /** Delete the caller's own account. Its own route, not accounts/{yourId}. */
1139
1230
  async deleteMyAccount() {
@@ -1142,14 +1233,14 @@ export class Flexemarkets {
1142
1233
  /** Every account on the server. Admin-only. */
1143
1234
  async accounts() {
1144
1235
  const data = await this._get(this._v1("/accounts"));
1145
- return data.map(parseAccount);
1236
+ return rows(data).map(anAccount);
1146
1237
  }
1147
1238
  /**
1148
1239
  * A page of `accounts()`: the newest `limit`, or of those whose id is below
1149
1240
  * `before` -- a page's `next`. The server answers at most 5,000.
1150
1241
  */
1151
1242
  async accountsPage(limit, before) {
1152
- return this._page(this._v1("/accounts"), limit, before, (a) => parseAccount(a));
1243
+ return this._page(this._v1("/accounts"), limit, before, anAccount);
1153
1244
  }
1154
1245
  /** Delete an account. Destructive, and takes its users with it. */
1155
1246
  async deleteAccount(accountId) {
@@ -1159,7 +1250,7 @@ export class Flexemarkets {
1159
1250
  async createUser(email, password, firstName, lastName, roles = []) {
1160
1251
  const user = { email, password, firstName, lastName, roles };
1161
1252
  const data = await this._create((key) => this._post(this._v1("/users"), user, key));
1162
- return parsePerson(data);
1253
+ return aPerson(data);
1163
1254
  }
1164
1255
  /** Delete a user. Destructive. */
1165
1256
  async deleteUser(userId) {
@@ -1247,7 +1338,7 @@ export class Flexemarkets {
1247
1338
  const data = await this._post(url, { userIds });
1248
1339
  return {
1249
1340
  expiresAt: toInstant(data.expiresAt),
1250
- otps: (data.otps ?? []).map((o) => ({
1341
+ otps: rows(data.otps ?? []).map((o) => ({
1251
1342
  userId: o.userId ?? 0,
1252
1343
  email: o.email ?? null,
1253
1344
  otp: o.otp ?? null,
@@ -1260,7 +1351,7 @@ export class Flexemarkets {
1260
1351
  method: "DELETE",
1261
1352
  headers: { ...this._authHeaders(), Accept: "application/json" },
1262
1353
  });
1263
- const body = await resp.text();
1354
+ const body = await bodyOf(resp);
1264
1355
  checkResponse(resp, body);
1265
1356
  }
1266
1357
  /**
@@ -1271,7 +1362,7 @@ export class Flexemarkets {
1271
1362
  method: "DELETE",
1272
1363
  headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
1273
1364
  });
1274
- const body = await resp.text();
1365
+ const body = await bodyOf(resp);
1275
1366
  checkResponse(resp, body);
1276
1367
  return readBody(body);
1277
1368
  }
@@ -1315,7 +1406,7 @@ export class Flexemarkets {
1315
1406
  },
1316
1407
  body: content,
1317
1408
  });
1318
- const body = await resp.text();
1409
+ const body = await bodyOf(resp);
1319
1410
  checkResponse(resp, body);
1320
1411
  return readBody(body);
1321
1412
  }
@@ -1337,7 +1428,7 @@ export class Flexemarkets {
1337
1428
  // -- marketplaces ----------------------------------------------------------
1338
1429
  async marketplaces() {
1339
1430
  const data = await this._get(this._v1("/marketplaces"));
1340
- return data.map(parseMarketplace);
1431
+ return rows(data).map(parseMarketplace);
1341
1432
  }
1342
1433
  /**
1343
1434
  * A page of `marketplaces()`: the newest `limit`, or of those whose id is below
@@ -1353,7 +1444,7 @@ export class Flexemarkets {
1353
1444
  */
1354
1445
  async currentSessions() {
1355
1446
  const data = await this._get(this._v1("/marketplaces/current-sessions"));
1356
- return data.map(parseCurrentSession);
1447
+ return rows(data).map(parseCurrentSession);
1357
1448
  }
1358
1449
  /**
1359
1450
  * A page of `currentSessions()`, paged by marketplace as `marketplacesPage()`
@@ -1370,7 +1461,7 @@ export class Flexemarkets {
1370
1461
  // -- markets ---------------------------------------------------------------
1371
1462
  async markets(marketplaceId) {
1372
1463
  const data = await this._get(`${this._marketplace(marketplaceId)}/markets`);
1373
- return data.map(parseMarket);
1464
+ return rows(data).map(parseMarket);
1374
1465
  }
1375
1466
  /**
1376
1467
  * What an indicative call market's book would clear at now: the price and
@@ -1423,7 +1514,7 @@ export class Flexemarkets {
1423
1514
  */
1424
1515
  async sessions(marketplaceId) {
1425
1516
  const url = `${this._marketplace(marketplaceId)}/sessions`;
1426
- return (await this._get(url)).map(parseSession);
1517
+ return rows(await this._get(url)).map(parseSession);
1427
1518
  }
1428
1519
  /**
1429
1520
  * A page of `sessions()`: the newest `limit`, or of those whose id is below
@@ -1536,8 +1627,7 @@ export class Flexemarkets {
1536
1627
  if (!Array.isArray(data) || data.length !== batch.length) {
1537
1628
  throw new ApiError(`Expected ${batch.length} answers to a batch of ${batch.length} orders`);
1538
1629
  }
1539
- return data.map((raw) => {
1540
- const entry = raw;
1630
+ return rows(data).map((entry) => {
1541
1631
  const status = typeof entry.status === "number" ? entry.status : 0;
1542
1632
  return status >= 200 && status < 300
1543
1633
  ? parseOrder(entry.order)
@@ -1758,7 +1848,7 @@ export class Flexemarkets {
1758
1848
  if (options?.symbol != null) {
1759
1849
  const symbol = options.symbol;
1760
1850
  const data = await this._get(`${base}?state=ACTIVE&symbol=${encodeURIComponent(symbol)}`);
1761
- const orders = data.map(parseOrder);
1851
+ const orders = rows(data).map(parseOrder);
1762
1852
  for (const o of orders)
1763
1853
  o.symbol = symbol;
1764
1854
  return orders;
@@ -1766,7 +1856,7 @@ export class Flexemarkets {
1766
1856
  const url = options?.sessionIds != null && options.sessionIds.length > 0
1767
1857
  ? `${base}?sessions=${options.sessionIds.join(",")}`
1768
1858
  : `${base}?cancelled=false`;
1769
- return (await this._get(url)).map(parseOrder);
1859
+ return rows(await this._get(url)).map(parseOrder);
1770
1860
  }
1771
1861
  /**
1772
1862
  * A page of `orders()` with no filter -- cancellations left out, as there:
@@ -1789,7 +1879,7 @@ export class Flexemarkets {
1789
1879
  const url = `${this._marketplace(marketplaceId)}/orders?state=TRADED` +
1790
1880
  `&symbol=${encodeURIComponent(symbol)}&limit=${MAX_TRADED_LEGS}`;
1791
1881
  const data = await this._get(url);
1792
- const orders = data.map(parseOrder);
1882
+ const orders = rows(data).map(parseOrder);
1793
1883
  for (const o of orders) {
1794
1884
  o.id = o.original;
1795
1885
  o.symbol = symbol;
@@ -1803,7 +1893,7 @@ export class Flexemarkets {
1803
1893
  if (sessionIds && sessionIds.length > 0)
1804
1894
  url += `?sessions=${sessionIds.join(",")}`;
1805
1895
  const data = await this._get(url);
1806
- return data.map(parseHolding);
1896
+ return rows(data).map(parseHolding);
1807
1897
  }
1808
1898
  async holding(marketplaceId) {
1809
1899
  return parseHolding(await this._get(`${this._marketplace(marketplaceId)}/participants/me/holding`));
@@ -1818,7 +1908,7 @@ export class Flexemarkets {
1818
1908
  */
1819
1909
  async connections(marketplaceId) {
1820
1910
  const url = `${this._marketplace(marketplaceId)}/connections`;
1821
- return (await this._get(url)).map(parseConnection);
1911
+ return rows(await this._get(url)).map(parseConnection);
1822
1912
  }
1823
1913
  /**
1824
1914
  * A page of `connections()`: the newest `limit`, or of those whose id is below
@@ -1879,20 +1969,20 @@ export class Flexemarkets {
1879
1969
  /** Everyone in the caller's account. */
1880
1970
  async users() {
1881
1971
  const data = await this._get(this._v1("/users"));
1882
- return data.map((u) => parsePerson(u));
1972
+ return rows(data).map(aPerson);
1883
1973
  }
1884
1974
  /**
1885
1975
  * A page of `users()`: the newest `limit`, or of those whose id is below
1886
1976
  * `before` -- a page's `next`. The server answers at most 5,000.
1887
1977
  */
1888
1978
  async usersPage(limit, before) {
1889
- return this._page(this._v1("/users"), limit, before, (u) => parsePerson(u));
1979
+ return this._page(this._v1("/users"), limit, before, aPerson);
1890
1980
  }
1891
1981
  /** The opening positions of one allocation. */
1892
1982
  async allotments(marketplaceId, allocationId) {
1893
1983
  const url = `${this._marketplace(marketplaceId)}/allocations/${allocationId}/allotments`;
1894
1984
  const data = await this._get(url);
1895
- return data.map(parseAllotment);
1985
+ return rows(data).map(parseAllotment);
1896
1986
  }
1897
1987
  /**
1898
1988
  * Stage the opening positions for the next session.
@@ -1908,7 +1998,7 @@ export class Flexemarkets {
1908
1998
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1909
1999
  const body = holdings.map((h) => holdingToAllotment(marketplaceId, h));
1910
2000
  const data = await this._create((key) => this._post(url, body, key));
1911
- return allotmentsToHoldings(data.map(parseAllotment));
2001
+ return allotmentsToHoldings(rows(data).map(parseAllotment));
1912
2002
  }
1913
2003
  /**
1914
2004
  * The holdings CSV, verbatim, for the current session or for given ones.
@@ -1928,8 +2018,8 @@ export class Flexemarkets {
1928
2018
  */
1929
2019
  async uploadHoldings(marketplaceId, filename) {
1930
2020
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1931
- const data = (await this._create((key) => this._sendCsv("POST", url, filename, key)));
1932
- 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));
1933
2023
  }
1934
2024
  /**
1935
2025
  * Stage an allocation from holdings CSV text, as {@link uploadHoldings} does
@@ -1943,8 +2033,8 @@ export class Flexemarkets {
1943
2033
  */
1944
2034
  async uploadHoldingsCsv(marketplaceId, csv) {
1945
2035
  const url = `${this._marketplace(marketplaceId)}/allocations`;
1946
- const data = (await this._create((key) => this._sendCsvContent("POST", url, csv, key)));
1947
- 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));
1948
2038
  }
1949
2039
  /**
1950
2040
  * Load per-participant private state from a CSV, returning what was stored.
@@ -1962,8 +2052,8 @@ export class Flexemarkets {
1962
2052
  */
1963
2053
  async uploadState(marketplaceId, filename) {
1964
2054
  const url = `${this._marketplace(marketplaceId)}/state`;
1965
- const data = (await this._sendCsv("PUT", url, filename));
1966
- return data.map(parseParticipantState);
2055
+ const data = await this._sendCsv("PUT", url, filename);
2056
+ return rows(data).map(parseParticipantState);
1967
2057
  }
1968
2058
  /**
1969
2059
  * Push widgets to participants' screens, returning them as stored.
@@ -1985,7 +2075,7 @@ export class Flexemarkets {
1985
2075
  const url = `${this._marketplace(marketplaceId)}/widgets`;
1986
2076
  const pushes = widgets.map(widgetPushJson);
1987
2077
  const data = await this._create((key) => this._post(url, pushes, key));
1988
- return data.map(parseWidget);
2078
+ return rows(data).map(parseWidget);
1989
2079
  }
1990
2080
  /**
1991
2081
  * Take down a widget: the marketplace's for `key`, or one participant's.
@@ -2005,7 +2095,7 @@ export class Flexemarkets {
2005
2095
  method: "DELETE",
2006
2096
  headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
2007
2097
  });
2008
- const body = await resp.text();
2098
+ const body = await bodyOf(resp);
2009
2099
  if (resp.status === 404 && body.trim() === "")
2010
2100
  return false;
2011
2101
  checkResponse(resp, body);
@@ -2021,8 +2111,9 @@ export class Flexemarkets {
2021
2111
  */
2022
2112
  async allWidgets(marketplaceId) {
2023
2113
  const data = await this._get(`${this._marketplace(marketplaceId)}/widgets?participant=all`);
2114
+ requireObject(Array.isArray(data) ? {} : data);
2024
2115
  const widgets = Array.isArray(data) ? data : (data.widgets ?? []);
2025
- return widgets.map(parseWidget);
2116
+ return rows(widgets).map(parseWidget);
2026
2117
  }
2027
2118
  /**
2028
2119
  * Clear a call-auction market now: every crossing order trades at one
@@ -2040,7 +2131,7 @@ export class Flexemarkets {
2040
2131
  async calls(marketplaceId, sessionId) {
2041
2132
  const query = sessionId === undefined ? "" : `?sessions=${sessionId}`;
2042
2133
  const data = await this._get(`${this._marketplace(marketplaceId)}/calls${query}`);
2043
- return data.map(parseMarketCall);
2134
+ return rows(data).map(parseMarketCall);
2044
2135
  }
2045
2136
  /**
2046
2137
  * A page of `calls()`: the newest `limit`, or of those whose id is below
@@ -2059,7 +2150,7 @@ export class Flexemarkets {
2059
2150
  */
2060
2151
  async marketplaceRobots(marketplaceId) {
2061
2152
  const data = await this._get(`${this._marketplace(marketplaceId)}/robots`);
2062
- return data.map(parseMarketplaceRobot);
2153
+ return rows(data).map(parseMarketplaceRobot);
2063
2154
  }
2064
2155
  /**
2065
2156
  * Set a robot parameter's value in a marketplace, and whether participants
@@ -2213,10 +2304,15 @@ export class Flexemarkets {
2213
2304
  const wsUrl = server(this._endpoint)
2214
2305
  .replace("https://", "wss://")
2215
2306
  .replace("http://", "ws://") + "/v1/events";
2216
- 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));
2217
2308
  if (reconnectMaxPauseMs !== undefined)
2218
2309
  events.reconnectMaxPauseMs = reconnectMaxPauseMs;
2219
- 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
+ }
2220
2316
  return events;
2221
2317
  }
2222
2318
  /** Reconnect the WebSocket after a transport error. */
@@ -2271,7 +2367,7 @@ async function renewWithRefreshToken(baseUrl, config) {
2271
2367
  },
2272
2368
  body: JSON.stringify({ refreshToken: config[REFRESH_TOKEN_PROPERTY].trim() }),
2273
2369
  });
2274
- const body = await resp.text();
2370
+ const body = await bodyOf(resp);
2275
2371
  checkResponse(resp, body);
2276
2372
  const data = readBody(body);
2277
2373
  if (typeof data.refreshToken === "string" && data.refreshToken) {
@@ -2304,7 +2400,7 @@ async function signIn(baseUrl, config, clientDescription) {
2304
2400
  "User-Agent": FM_NETWORK_CLIENT,
2305
2401
  },
2306
2402
  });
2307
- const body = await resp.text();
2403
+ const body = await bodyOf(resp);
2308
2404
  checkResponse(resp, body);
2309
2405
  return parseToken(readBody(body));
2310
2406
  }
@@ -2330,7 +2426,7 @@ async function signIn(baseUrl, config, clientDescription) {
2330
2426
  password,
2331
2427
  }),
2332
2428
  });
2333
- const body = await resp.text();
2429
+ const body = await bodyOf(resp);
2334
2430
  checkResponse(resp, body);
2335
2431
  return parseToken(readBody(body));
2336
2432
  }