@flexemarkets/fm-sdk 0.3.3 → 0.4.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
@@ -5,23 +5,20 @@
5
5
  */
6
6
  import { readFileSync, existsSync } from "node:fs";
7
7
  import { homedir } from "node:os";
8
- import { basename, join } from "node:path";
9
- import { fileURLToPath } from "node:url";
8
+ import { join } from "node:path";
10
9
  import { orderedSecurities, toOrderType, toSide, unitGrid } from "./types.js";
11
10
  import { toInstant } from "./timestamps.js";
12
11
  import { EventListener, NO_SEQ } from "./stomp.js";
13
12
  import { DefaultDesk, DeskHandle, } from "./desk.js";
14
- function readVersion() {
15
- try {
16
- const dir = fileURLToPath(new URL(".", import.meta.url));
17
- return readFileSync(join(dir, "..", "..", "..", "VERSION"), "utf-8").trim();
18
- }
19
- catch {
20
- return "0.0.0";
21
- }
22
- }
13
+ import { readVersion } from "./version.js";
23
14
  const FM_NETWORK_CLIENT = `fm-sdk-typescript/${readVersion()}`;
24
- const DEFAULT_ENDPOINT = "https://api.flexemarkets.com";
15
+ export const DEFAULT_ENDPOINT = "https://api.flexemarkets.com";
16
+ /**
17
+ * The most traded legs fm-server answers in one read. The route `trades`
18
+ * replaced had no limit; asking for the ceiling keeps as much of that as the
19
+ * server allows.
20
+ */
21
+ const MAX_TRADED_LEGS = 5000;
25
22
  const BCRYPT_RE = /^\$2[abxy]?\$\d{2}\$[./A-Za-z0-9]{53}$/;
26
23
  const JWT_RE = /^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/;
27
24
  // ---------------------------------------------------------------------------
@@ -61,7 +58,7 @@ export class HttpError extends FlexemarketsError {
61
58
  *
62
59
  * Distinct from {@link HttpError}, which means the server answered and the
63
60
  * answer was an error. This means there was no usable answer at all — a
64
- * malformed body, or a link the API root does not carry.
61
+ * malformed body.
65
62
  */
66
63
  export class ApiError extends FlexemarketsError {
67
64
  }
@@ -212,6 +209,42 @@ export function parseParticipantState(data) {
212
209
  fields: { ...(data.fields ?? {}) },
213
210
  };
214
211
  }
212
+ export function parseWidget(data) {
213
+ return {
214
+ id: data.id ?? null,
215
+ marketplaceId: data.marketplaceId ?? null,
216
+ scope: data.scope ?? null,
217
+ userId: data.userId ?? null,
218
+ key: data.key ?? null,
219
+ title: data.title ?? null,
220
+ emphasis: data.emphasis ?? null,
221
+ ttlSeconds: data.ttlSeconds ?? null,
222
+ content: { ...(data.content ?? {}) },
223
+ createdDate: toInstant(data.createdDate),
224
+ lastModifiedDate: toInstant(data.lastModifiedDate),
225
+ };
226
+ }
227
+ /**
228
+ * The wire form of a push: the target nested, nothing null.
229
+ *
230
+ * Absent rather than null so the body reads as the server documents it -- a
231
+ * marketplace target is `{"scope":"MARKETPLACE"}`, with no userId.
232
+ */
233
+ function widgetPushJson(push) {
234
+ const body = { key: push.key, content: push.content };
235
+ if (push.target != null) {
236
+ body.target = push.target.userId != null
237
+ ? { scope: push.target.scope, userId: push.target.userId }
238
+ : { scope: push.target.scope };
239
+ }
240
+ if (push.title != null)
241
+ body.title = push.title;
242
+ if (push.emphasis != null)
243
+ body.emphasis = push.emphasis;
244
+ if (push.ttlSeconds != null)
245
+ body.ttlSeconds = push.ttlSeconds;
246
+ return body;
247
+ }
215
248
  function parseAllotment(data) {
216
249
  // The server spells the nested capital "capital" on some responses and
217
250
  // "assets" on others, and the positions inside it "grants" or "securities".
@@ -306,42 +339,25 @@ export function parseConnection(data) {
306
339
  };
307
340
  }
308
341
  /**
309
- * The orders inside a HAL envelope.
342
+ * The orders in a snapshot answer, which is a bare JSON array or a failure.
310
343
  *
311
- * The server embeds them under `orders`. It was `orderDtoes` — Spring HATEOAS
312
- * pluralising `OrderDto` — and every SDK still read that name long after the
313
- * server stopped sending it, so `activeOrders` and `recentTrades` returned an
314
- * empty array always. `Desk` seeds from `activeOrders`, so its books were
315
- * never seeded; they filled from live deltas and looked plausible.
344
+ * Only the array is read because the V1 route never sent anything else:
345
+ * `GET /api/v1/marketplaces/{id}/orders` has always answered a bare array, and
346
+ * 0.4 requires fm-server 4.6.2. The HAL envelopes earlier SDKs tolerated
347
+ * belonged to the routes 0.4 no longer calls.
316
348
  *
317
- * Then the envelope itself went: fm-server now sends a bare array. Accepting
318
- * both *names* did not survive that, and this SDK failed the same silent way a
319
- * second time — `._embedded` on an array is `undefined`, so it returned an
320
- * empty book rather than throwing, while Java and Python at least raised.
349
+ * Anything else throws rather than reading as empty. An empty snapshot is the
350
+ * failure that hid twice before: `Desk` seeded an empty book, filled it from
351
+ * live deltas, and looked plausible.
321
352
  *
322
- * So read the shape rather than assume one. All three are accepted, because
323
- * all three are still deployed somewhere.
353
+ * @throws ApiError when the answer is not a JSON array
324
354
  */
325
- export function embeddedOrders(data) {
326
- if (Array.isArray(data))
327
- return data;
328
- if (data === null || typeof data !== "object")
329
- return [];
330
- const embedded = data._embedded;
331
- return embedded?.orders ?? embedded?.orderDtoes ?? [];
332
- }
333
- function parseApiRoot(data) {
334
- const linksRaw = data._links ?? {};
335
- const links = {};
336
- for (const [name, value] of Object.entries(linksRaw)) {
337
- if (typeof value === "object" && value !== null && "href" in value) {
338
- links[name] = value.href ?? "";
339
- }
340
- else if (typeof value === "string") {
341
- links[name] = value;
342
- }
355
+ export function ordersOf(data) {
356
+ if (!Array.isArray(data)) {
357
+ const kind = data === null || data === undefined ? "null" : typeof data;
358
+ throw new ApiError(`The orders snapshot answer was not a list of orders: got ${kind}`);
343
359
  }
344
- return { links };
360
+ return data;
345
361
  }
346
362
  /**
347
363
  * The most aggressive price this market will accept on `side`.
@@ -369,110 +385,6 @@ export function marketableLimit(market, side) {
369
385
  const span = market.priceMaximum - market.priceMinimum;
370
386
  return market.priceMinimum + Math.floor(span / market.priceTick) * market.priceTick;
371
387
  }
372
- /**
373
- * The `scheme://host:port` of an absolute http(s) URL, else undefined.
374
- *
375
- * A relative href already resolves against the origin it was fetched from,
376
- * and a scheme that is not HTTP is not ours to rewrite.
377
- */
378
- function httpOrigin(url) {
379
- if (!url)
380
- return undefined;
381
- const end = url.indexOf("://");
382
- if (end < 0)
383
- return undefined;
384
- const scheme = url.substring(0, end).toLowerCase();
385
- if (scheme !== "http" && scheme !== "https")
386
- return undefined;
387
- const pathStart = url.indexOf("/", end + 3);
388
- return pathStart < 0 ? url : url.substring(0, pathStart);
389
- }
390
- /**
391
- * Point the API root's links back at the host that was dialled.
392
- *
393
- * The server builds these hrefs from the request it believes it received, and
394
- * behind a proxy that belief can be wrong: an origin reached over a plaintext
395
- * leg reports `http://` even though the caller arrived on `https://`. Every
396
- * call that goes through a link — which is most of them — then leaves on plain
397
- * HTTP and meets the edge's redirect. A GET survives it. A POST does not: a
398
- * 301 is followed as a GET with the body dropped, so placing an order or
399
- * opening a session fails with nothing placed and nothing pointing at the
400
- * scheme.
401
- *
402
- * Only the origin is replaced. The path, query and any URI template are the
403
- * server's to choose; where it is reachable is not, and the token in hand was
404
- * issued by the origin dialled, not by whatever the links name.
405
- */
406
- export function rebaseApiRoot(root, endpoint) {
407
- const origin = httpOrigin(endpoint);
408
- if (!origin)
409
- return root;
410
- const links = {};
411
- const moved = [];
412
- for (const [name, href] of Object.entries(root.links)) {
413
- const named = httpOrigin(href);
414
- if (!named || named === origin) {
415
- links[name] = href;
416
- continue;
417
- }
418
- if (!moved.includes(named))
419
- moved.push(named);
420
- links[name] = origin + href.substring(named.length);
421
- }
422
- if (moved.length > 0) {
423
- // Said out loud, because the rewrite would otherwise hide a deployment
424
- // that is genuinely misconfigured — and a silent correction here is how it
425
- // stays misconfigured. The SDK keeps working; the operator still gets told
426
- // where to look.
427
- console.warn(`[fm-sdk] The API root names ${moved.join(", ")} but this client dialled ${origin}; ` +
428
- `rewriting ${moved.length} link origin(s) to match. The server is behind a proxy ` +
429
- `that is not forwarding the request scheme, so its links are wrong. Fix it at the ` +
430
- `edge — this rewrite only keeps calls working.`);
431
- }
432
- return { links };
433
- }
434
- // ---------------------------------------------------------------------------
435
- // HATEOAS link resolution
436
- // ---------------------------------------------------------------------------
437
- function processTemplate(href) {
438
- const idx = href.indexOf("{");
439
- return idx >= 0 ? href.substring(0, idx) : href;
440
- }
441
- /**
442
- * A V1 route, addressed from the server rather than through a HAL link.
443
- *
444
- * V1 is flat and versioned: the path is knowable without fetching the API root
445
- * first, which is the point of it. Every call that moves here loses a HAL
446
- * dependency as well as a version.
447
- */
448
- function v1(endpoint, path) {
449
- return `${server(endpoint)}/v1${path}`;
450
- }
451
- function uri(root, linkName) {
452
- const href = root.links[linkName];
453
- if (href === undefined)
454
- throw new ApiError(`Link '${linkName}' not found in API root.`);
455
- return processTemplate(href);
456
- }
457
- function uriId(root, linkName, id) {
458
- return `${uri(root, linkName)}/${id}`;
459
- }
460
- function uriIdSegment(root, linkName, id, segment) {
461
- return `${uriId(root, linkName, id)}/${segment}`;
462
- }
463
- function uriParam(root, linkName, param) {
464
- return `${uri(root, linkName)}?${param}`;
465
- }
466
- function uriIdSegmentParam(root, linkName, id, segment, param) {
467
- const base = uriIdSegment(root, linkName, id, segment);
468
- return param ? `${base}?${param}` : base;
469
- }
470
- function uriParamMarketplaceIdParam(root, linkName, id, param) {
471
- let u = uriParam(root, linkName, `marketplaceId=${id}`);
472
- if (param)
473
- u += `&${param}`;
474
- return u;
475
- }
476
388
  // ---------------------------------------------------------------------------
477
389
  // Credential / configuration helpers
478
390
  // ---------------------------------------------------------------------------
@@ -530,12 +442,7 @@ export function resolveEndpoint(endpoint) {
530
442
  }
531
443
  return { endpoint };
532
444
  }
533
- function sessionIdsParam(sessionIds) {
534
- if (!sessionIds || sessionIds.length === 0)
535
- return "";
536
- return "sessionIds=" + sessionIds.join(",");
537
- }
538
- function loadPropertiesFile(path) {
445
+ export function loadPropertiesFile(path) {
539
446
  const props = {};
540
447
  if (!existsSync(path))
541
448
  return props;
@@ -551,7 +458,7 @@ function loadPropertiesFile(path) {
551
458
  }
552
459
  return props;
553
460
  }
554
- function loadConfig() {
461
+ export function loadConfig() {
555
462
  const config = {};
556
463
  const fmDir = join(homedir(), ".fm");
557
464
  Object.assign(config, loadPropertiesFile(join(fmDir, "credential")));
@@ -566,16 +473,56 @@ function loadConfig() {
566
473
  // ---------------------------------------------------------------------------
567
474
  // Response handling
568
475
  // ---------------------------------------------------------------------------
476
+ /**
477
+ * What the server said, rather than the envelope it said it in.
478
+ *
479
+ * Failures arrive as `{"error","message","path","shortDigest","status"}` and
480
+ * the message is the only part a caller can act on. Falls back to the raw
481
+ * body when it does not parse, since that is when the caller most needs to
482
+ * see what came back. As the Java SDK's `_detail`, which had this fix alone:
483
+ * here a refused sign-in said only "Authentication failed.", and a refused
484
+ * order carried the whole JSON document.
485
+ */
486
+ export function detail(body) {
487
+ if (!body || !body.trim())
488
+ return "(no response body)";
489
+ try {
490
+ const parsed = JSON.parse(body);
491
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
492
+ const message = parsed.message;
493
+ if (typeof message === "string" && message.trim())
494
+ return message;
495
+ }
496
+ }
497
+ catch {
498
+ // not JSON: report it as it came
499
+ }
500
+ return body;
501
+ }
502
+ /**
503
+ * The body of a successful answer, parsed. A 200 that is not JSON -- an edge
504
+ * proxy's HTML error page, a truncated body -- is an answer the SDK cannot
505
+ * read, so it is an {@link ApiError}, as in the Java SDK, rather than a bare
506
+ * SyntaxError escaping past a caller who catches FlexemarketsError.
507
+ */
508
+ function readBody(body) {
509
+ try {
510
+ return JSON.parse(body);
511
+ }
512
+ catch {
513
+ throw new ApiError("Failed to parse the response body");
514
+ }
515
+ }
569
516
  function checkResponse(response, body) {
570
517
  const status = response.status;
571
518
  if (status >= 200 && status < 300)
572
519
  return;
573
520
  if (status === 400)
574
- throw new InvalidArgumentError(body);
521
+ throw new InvalidArgumentError("Invalid request: " + detail(body));
575
522
  if (status === 401)
576
- throw new AuthenticationError(body);
523
+ throw new AuthenticationError("Authentication failed: " + detail(body));
577
524
  if (status === 403)
578
- throw new AuthorizationError(body);
525
+ throw new AuthorizationError("Not permitted: " + detail(body));
579
526
  if (status === 409)
580
527
  throw new ConflictError(body);
581
528
  if (status >= 500)
@@ -600,7 +547,6 @@ export class Flexemarkets {
600
547
  _endpoint;
601
548
  _baseUrl;
602
549
  _bearerToken;
603
- _apiRoot;
604
550
  _account;
605
551
  _user;
606
552
  _tokenObj;
@@ -638,8 +584,6 @@ export class Flexemarkets {
638
584
  fm._tokenObj = tokenObj;
639
585
  fm._account = tokenObj.account;
640
586
  fm._user = tokenObj.person;
641
- // Fetch API root for HATEOAS links
642
- fm._apiRoot = await fm._fetchApiRoot();
643
587
  return fm;
644
588
  }
645
589
  // -- properties ------------------------------------------------------------
@@ -672,13 +616,13 @@ export class Flexemarkets {
672
616
  const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
673
617
  headers: {
674
618
  ...this._authHeaders(),
675
- Accept: "application/json, application/hal+json",
619
+ Accept: "application/json",
676
620
  "User-Agent": FM_NETWORK_CLIENT,
677
621
  },
678
622
  });
679
623
  const body = await resp.text();
680
624
  checkResponse(resp, body);
681
- return JSON.parse(body);
625
+ return readBody(body);
682
626
  }
683
627
  /**
684
628
  * GET helper that returns the parsed body bundled with the
@@ -690,7 +634,7 @@ export class Flexemarkets {
690
634
  const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
691
635
  headers: {
692
636
  ...this._authHeaders(),
693
- Accept: "application/json, application/hal+json",
637
+ Accept: "application/json",
694
638
  "User-Agent": FM_NETWORK_CLIENT,
695
639
  },
696
640
  });
@@ -698,24 +642,23 @@ export class Flexemarkets {
698
642
  checkResponse(resp, body);
699
643
  const raw = resp.headers.get("x-fm-as-of-seq");
700
644
  const asOfSeq = raw === null ? NO_SEQ : Number.parseInt(raw, 10);
701
- return { data: JSON.parse(body), asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
645
+ return { data: readBody(body), asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
702
646
  }
703
- /**
704
- * PATCH with no body — the shape every session transition takes: the verb and
705
- * the path carry the whole request.
706
- */
707
- async _patch(url) {
647
+ /** PATCH with a JSON body -- the shape every session transition takes. */
648
+ async _patch(url, json) {
708
649
  const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
709
650
  method: "PATCH",
710
651
  headers: {
711
652
  ...this._authHeaders(),
712
- Accept: "application/json, application/hal+json",
653
+ "Content-Type": "application/json",
654
+ Accept: "application/json",
713
655
  "User-Agent": FM_NETWORK_CLIENT,
714
656
  },
657
+ body: JSON.stringify(json),
715
658
  });
716
659
  const body = await resp.text();
717
660
  checkResponse(resp, body);
718
- return JSON.parse(body);
661
+ return readBody(body);
719
662
  }
720
663
  /**
721
664
  * GET returning the body verbatim, for endpoints that answer with something
@@ -740,14 +683,14 @@ export class Flexemarkets {
740
683
  headers: {
741
684
  ...this._authHeaders(),
742
685
  "Content-Type": "application/json",
743
- Accept: "application/json, application/hal+json",
686
+ Accept: "application/json",
744
687
  "User-Agent": FM_NETWORK_CLIENT,
745
688
  },
746
689
  body: JSON.stringify(json),
747
690
  });
748
691
  const body = await resp.text();
749
692
  checkResponse(resp, body);
750
- return JSON.parse(body);
693
+ return readBody(body);
751
694
  }
752
695
  // -- administration --------------------------------------------------------
753
696
  /*
@@ -767,7 +710,7 @@ export class Flexemarkets {
767
710
  * cannot sign in as.
768
711
  */
769
712
  async signup(accountName, email, password, firstName, lastName) {
770
- const url = uri(this._apiRoot, "accounts");
713
+ const url = this._v1("/accounts");
771
714
  try {
772
715
  const data = await this._post(url, {
773
716
  accountName,
@@ -790,49 +733,58 @@ export class Flexemarkets {
790
733
  throw e;
791
734
  }
792
735
  }
793
- /** Approve an account by name, returning it as it now stands. */
736
+ /**
737
+ * Approve an account by name, returning it as it now stands.
738
+ *
739
+ * V1 approves an account by id; the name is looked up in the account list
740
+ * first, so callers keep naming the account they signed up.
741
+ */
794
742
  async approveAccount(accountName) {
795
- const url = `${server(this._endpoint)}/approvals`;
796
- const data = await this._post(url, { name: accountName, approval: true });
743
+ const account = (await this.accounts()).find((a) => a.name === accountName);
744
+ if (account === undefined) {
745
+ throw new InvalidArgumentError(`No account named '${accountName}'`);
746
+ }
747
+ const data = await this._post(this._v1(`/accounts/${account.id}/approvals`), { approve: true });
797
748
  return parseAccount(data.account);
798
749
  }
799
750
  /** One account by id. */
800
751
  async accountById(accountId) {
801
- return parseAccount(await this._get(uriId(this._apiRoot, "accounts", accountId)));
752
+ return parseAccount(await this._get(this._v1(`/accounts/${accountId}`)));
802
753
  }
803
754
  /** One user by id. */
804
755
  async userById(userId) {
805
- return parsePerson(await this._get(v1(this._endpoint, `/users/${userId}`)));
756
+ return parsePerson(await this._get(this._v1(`/users/${userId}`)));
806
757
  }
807
- /** The marketplace's private-trader identifiers. */
758
+ /**
759
+ * The names of the participants a caller may target: `GET participants`,
760
+ * names only. A row carries the user id too, for a manager; not needed here.
761
+ */
808
762
  async identifiers(marketplaceId) {
809
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "privateTraders");
810
- return (await this._get(url));
763
+ const rows = (await this._get(`${this._marketplace(marketplaceId)}/participants`));
764
+ return rows.map((r) => r.name);
811
765
  }
812
766
  /** Delete the caller's own account. Its own route, not accounts/{yourId}. */
813
767
  async deleteMyAccount() {
814
- await this._delete(`${server(this._endpoint)}/accounts/me`);
768
+ await this._delete(this._v1("/accounts/me"));
815
769
  }
816
770
  /** Every account on the server. Admin-only. */
817
771
  async accounts() {
818
- const url = uriParam(this._apiRoot, "accounts", "format=application/json");
819
- const data = await this._get(url);
772
+ const data = await this._get(this._v1("/accounts"));
820
773
  return data.map(parseAccount);
821
774
  }
822
775
  /** Delete an account. Destructive, and takes its users with it. */
823
776
  async deleteAccount(accountId) {
824
- await this._delete(uriId(this._apiRoot, "accounts", accountId));
777
+ await this._delete(this._v1(`/accounts/${accountId}`));
825
778
  }
826
779
  /** Create a user in the caller's account. */
827
780
  async createUser(email, password, firstName, lastName, roles = []) {
828
- const url = v1(this._endpoint, "/users");
829
- const data = await this._post(url, { email, password, firstName, lastName, roles });
781
+ const data = await this._post(this._v1("/users"), { email, password, firstName, lastName, roles });
830
782
  return parsePerson(data);
831
783
  }
832
784
  /** Delete a user. Destructive. */
833
785
  async deleteUser(userId) {
834
786
  try {
835
- await this._delete(uriId(this._apiRoot, "users", userId));
787
+ await this._delete(this._v1(`/users/${userId}`));
836
788
  }
837
789
  catch (e) {
838
790
  // The user still owns orders or allotments. Deleting them would orphan
@@ -847,7 +799,7 @@ export class Flexemarkets {
847
799
  /** Create an empty marketplace. See also {@link createMarketplaceFromJson}. */
848
800
  /** Delete a marketplace, and with it its sessions and their history. */
849
801
  async deleteMarketplace(marketplaceId) {
850
- await this._delete(uriId(this._apiRoot, "marketplaces", marketplaceId));
802
+ await this._delete(this._marketplace(marketplaceId));
851
803
  }
852
804
  /**
853
805
  * Add a market to a marketplace.
@@ -859,8 +811,7 @@ export class Flexemarkets {
859
811
  * `units` keeps the old default.
860
812
  */
861
813
  async createMarket(marketplaceId, symbol, name, price, units = unitGrid(), privateMarket = false) {
862
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "markets");
863
- return parseMarket(await this._post(url, {
814
+ return parseMarket(await this._post(`${this._marketplace(marketplaceId)}/markets`, {
864
815
  symbol,
865
816
  name,
866
817
  priceMinimum: price.minimum,
@@ -879,7 +830,8 @@ export class Flexemarkets {
879
830
  * delivered to the person they belong to.
880
831
  */
881
832
  async managerOtpBundle(userIds) {
882
- const url = `${server(this._endpoint)}/otp/manager`;
833
+ // Unversioned: fm-server has no V1 route for passcodes.
834
+ const url = `${this._baseUrl}/otp/manager`;
883
835
  const data = await this._post(url, { userIds });
884
836
  return {
885
837
  expiresAt: toInstant(data.expiresAt),
@@ -899,27 +851,64 @@ export class Flexemarkets {
899
851
  const body = await resp.text();
900
852
  checkResponse(resp, body);
901
853
  }
902
- async _fetchApiRoot() {
903
- const data = await this._get(this._baseUrl);
904
- return rebaseApiRoot(parseApiRoot(data), this._baseUrl);
854
+ /**
855
+ * DELETE whose answer is the resource as it ended -- an order's CANCEL.
856
+ */
857
+ async _deleteFor(url) {
858
+ const resp = await fetch(url, {
859
+ method: "DELETE",
860
+ headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
861
+ });
862
+ const body = await resp.text();
863
+ checkResponse(resp, body);
864
+ return readBody(body);
865
+ }
866
+ /**
867
+ * Send one CSV file as the body, `Content-Type: text/csv` -- format by
868
+ * header, where 0.3 posted it as a multipart upload to an `/uploads`
869
+ * segment. Bytes, not a string, so the file's own encoding survives.
870
+ */
871
+ async _sendCsv(method, url, filename) {
872
+ const resp = await fetch(url, {
873
+ method,
874
+ headers: {
875
+ ...this._authHeaders(),
876
+ "Content-Type": "text/csv",
877
+ Accept: "application/json",
878
+ "User-Agent": FM_NETWORK_CLIENT,
879
+ },
880
+ body: readFileSync(filename),
881
+ });
882
+ const body = await resp.text();
883
+ checkResponse(resp, body);
884
+ return readBody(body);
885
+ }
886
+ /**
887
+ * A V1 route. 0.4 addresses every route from the server rather than through
888
+ * the HAL root's links: the path is knowable without fetching anything
889
+ * first, and a root that drops a link can no longer take a call with it.
890
+ */
891
+ _v1(path) {
892
+ return `${this._baseUrl}/v1${path}`;
893
+ }
894
+ /** The V1 route of one marketplace, under which nearly everything lives. */
895
+ _marketplace(marketplaceId) {
896
+ return this._v1(`/marketplaces/${marketplaceId}`);
905
897
  }
906
898
  // ======================================================================
907
899
  // REST APIs
908
900
  // ======================================================================
909
901
  // -- marketplaces ----------------------------------------------------------
910
902
  async marketplaces() {
911
- const url = uriParam(this._apiRoot, "marketplaces", "format=application/json");
912
- const data = await this._get(url);
903
+ const data = await this._get(this._v1("/marketplaces"));
913
904
  return data.map(parseMarketplace);
914
905
  }
915
906
  async marketplace(marketplaceId) {
916
- const url = uriId(this._apiRoot, "marketplaces", marketplaceId);
917
- return parseMarketplace(await this._get(url));
907
+ return parseMarketplace(await this._get(this._marketplace(marketplaceId)));
918
908
  }
919
909
  // -- markets ---------------------------------------------------------------
920
910
  async markets(marketplaceId) {
921
- const url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "markets", "format=application/json");
922
- const data = await this._get(url);
911
+ const data = await this._get(`${this._marketplace(marketplaceId)}/markets`);
923
912
  return data.map(parseMarket);
924
913
  }
925
914
  /**
@@ -946,9 +935,9 @@ export class Flexemarkets {
946
935
  hasRole(role) {
947
936
  return (this._user?.roles ?? []).includes(role);
948
937
  }
938
+ /** The symbols of the marketplace's markets, read from the markets themselves. */
949
939
  async symbols(marketplaceId) {
950
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "symbols");
951
- return (await this._get(url));
940
+ return (await this.markets(marketplaceId)).map((m) => m.symbol);
952
941
  }
953
942
  // -- sessions --------------------------------------------------------------
954
943
  /**
@@ -958,23 +947,17 @@ export class Flexemarkets {
958
947
  * the `sessionIds` this used to accept was silently ignored: it returned the
959
948
  * whole history and looked like it had filtered. Filter the result; fm-ui
960
949
  * already does.
961
- *
962
- * On `GET /api/v1/marketplaces/{id}/sessions`, which answers with the same
963
- * fields as the V0 route it replaces — verified against a running server,
964
- * not assumed — and needs no `format=application/json` to avoid HAL.
965
950
  */
966
951
  async sessions(marketplaceId) {
967
- const url = v1(this._endpoint, `/marketplaces/${marketplaceId}/sessions`);
952
+ const url = `${this._marketplace(marketplaceId)}/sessions`;
968
953
  return (await this._get(url)).map(parseSession);
969
954
  }
970
955
  async session(marketplaceId) {
971
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "currentSession");
972
- return parseSession(await this._get(url));
956
+ return parseSession(await this._get(`${this._marketplace(marketplaceId)}/sessions/current`));
973
957
  }
974
958
  // -- orders ----------------------------------------------------------------
975
959
  async submitLimit(marketplaceId, marketId, side, units, price) {
976
- const url = uri(this._apiRoot, "orders");
977
- const data = await this._post(url, {
960
+ const data = await this._post(`${this._marketplace(marketplaceId)}/orders`, {
978
961
  marketplaceId,
979
962
  marketId,
980
963
  type: "LIMIT",
@@ -1024,18 +1007,13 @@ export class Flexemarkets {
1024
1007
  }
1025
1008
  throw new InvalidArgumentError(`Market ${marketId} is not in marketplace ${marketplaceId}`);
1026
1009
  }
1010
+ /**
1011
+ * DELETE the order: the server builds the CANCEL from the order's own
1012
+ * lineage and market, and answers with it. `marketId` is no longer sent --
1013
+ * the order already says which market it is in.
1014
+ */
1027
1015
  async submitCancel(marketplaceId, marketId, originalId) {
1028
- const url = uri(this._apiRoot, "orders");
1029
- const data = await this._post(url, {
1030
- marketplaceId,
1031
- marketId,
1032
- type: "CANCEL",
1033
- id: originalId,
1034
- original: originalId,
1035
- supplier: originalId,
1036
- clientDescription: this._clientDescription,
1037
- });
1038
- return parseOrder(data);
1016
+ return parseOrder(await this._deleteFor(`${this._marketplace(marketplaceId)}/orders/${originalId}`));
1039
1017
  }
1040
1018
  /**
1041
1019
  * The active-orders snapshot: every resting limit order on the
@@ -1045,10 +1023,9 @@ export class Flexemarkets {
1045
1023
  * value and skip those whose seq is less than or equal.
1046
1024
  */
1047
1025
  async activeOrders(marketplaceId) {
1048
- const baseRest = this._baseUrl;
1049
- const url = `${baseRest}/v1/marketplaces/${marketplaceId}/orders/active`;
1026
+ const url = `${this._marketplace(marketplaceId)}/orders?state=ACTIVE`;
1050
1027
  const { data, asOfSeq } = await this._getSnapshot(url);
1051
- const orders = embeddedOrders(data).map(parseOrder);
1028
+ const orders = ordersOf(data).map(parseOrder);
1052
1029
  return { body: orders, asOfSeq };
1053
1030
  }
1054
1031
  /**
@@ -1062,73 +1039,75 @@ export class Flexemarkets {
1062
1039
  * order differs. `Tape` sorts what it is given, so a caller seeding a tape
1063
1040
  * through `Desk` is unaffected; a caller reading this list directly
1064
1041
  * should not assume one.
1042
+ *
1043
+ * With `marketId`, only that market's legs (`&market=`), `size` of them,
1044
+ * two to a trade. What `Desk` seeds each tape from: read for every market
1045
+ * at once, a busy market's legs fill the limit and a quiet market's tape
1046
+ * comes up empty, though it has traded.
1065
1047
  */
1066
- async recentTrades(marketplaceId, size = 1000) {
1067
- const url = `${this._baseUrl}/v1/marketplaces/${marketplaceId}/orders/recent-trades?size=${size}`;
1048
+ async recentTrades(marketplaceId, size = 1000, marketId) {
1049
+ const market = marketId === undefined ? "" : `&market=${marketId}`;
1050
+ const url = `${this._marketplace(marketplaceId)}/orders?state=TRADED${market}&limit=${size}`;
1068
1051
  const { data, asOfSeq } = await this._getSnapshot(url);
1069
- const orders = embeddedOrders(data).map(parseOrder);
1052
+ const orders = ordersOf(data).map(parseOrder);
1070
1053
  return { body: orders, asOfSeq };
1071
1054
  }
1055
+ /**
1056
+ * The marketplace's orders.
1057
+ *
1058
+ * With no option, the current session's orders less every cancelled one, the
1059
+ * CANCEL that consumed it, and both legs of a self-cross -- what a study
1060
+ * ranking participants needs. Without `cancelled=false` the V1 read is the
1061
+ * raw lifecycle, which is what `sessionIds` asks for: every LIMIT and CANCEL
1062
+ * row of the named runs, as the exchange stored them. `symbol` reads one
1063
+ * market's active orders, with the symbol filled in.
1064
+ */
1072
1065
  async orders(marketplaceId, options) {
1066
+ const base = `${this._marketplace(marketplaceId)}/orders`;
1073
1067
  if (options?.symbol != null) {
1074
- const url = uriParamMarketplaceIdParam(this._apiRoot, "symbolOrdersJson", marketplaceId, `symbol=${options.symbol}`);
1075
- const data = await this._get(url);
1068
+ const symbol = options.symbol;
1069
+ const data = await this._get(`${base}?state=ACTIVE&symbol=${encodeURIComponent(symbol)}`);
1076
1070
  const orders = data.map(parseOrder);
1077
1071
  for (const o of orders)
1078
- o.symbol = options.symbol;
1072
+ o.symbol = symbol;
1079
1073
  return orders;
1080
1074
  }
1081
- if (options?.sessionIds != null) {
1082
- const url = uriParamMarketplaceIdParam(this._apiRoot, "sessionOrdersJson", marketplaceId, sessionIdsParam(options.sessionIds));
1083
- const data = await this._get(url);
1084
- return data.map(parseOrder);
1085
- }
1086
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "orders");
1087
- const data = await this._get(url);
1088
- return data.map(parseOrder);
1075
+ const url = options?.sessionIds != null && options.sessionIds.length > 0
1076
+ ? `${base}?sessions=${options.sessionIds.join(",")}`
1077
+ : `${base}?cancelled=false`;
1078
+ return (await this._get(url)).map(parseOrder);
1089
1079
  }
1090
1080
  /**
1091
- * Tape in one market, in ascending order id.
1092
- *
1093
- * Answered by a symbol-keyed route, so the orders come back without the
1094
- * symbol on them and with the trade id in `original`; both are filled in
1095
- * before returning, which is what makes the result a trade list rather than
1096
- * a set of half-populated orders.
1081
+ * One market's traded legs, as many as the server gives in one read
1082
+ * ({@link MAX_TRADED_LEGS}), in the server's order.
1097
1083
  *
1098
- * This is the FM-3 surface (`/api/orders-json/symbol-trades`) and its order
1099
- * is the server's, which sorts by order id and nothing else. It is neither
1100
- * chronological by trade time nor most-recent-first — the first element is
1101
- * the lowest id, not the latest trade. Sort by `lastModifiedDate` if you
1102
- * want time order.
1084
+ * The answer carries the trade id in `original` and no symbol on the orders,
1085
+ * because the query already fixed the symbol. Both are filled in before
1086
+ * returning, which is what makes the result a trade list rather than a set of
1087
+ * half-populated orders. Sort by `lastModifiedDate` if you want time order.
1103
1088
  */
1104
1089
  async trades(marketplaceId, symbol) {
1105
- const url = uriParamMarketplaceIdParam(this._apiRoot, "symbolTradesJson", marketplaceId, `symbol=${symbol}`);
1090
+ const url = `${this._marketplace(marketplaceId)}/orders?state=TRADED` +
1091
+ `&symbol=${encodeURIComponent(symbol)}&limit=${MAX_TRADED_LEGS}`;
1106
1092
  const data = await this._get(url);
1107
1093
  const orders = data.map(parseOrder);
1108
1094
  for (const o of orders) {
1109
- // The symbol-keyed route answers with the trade id in `original` and no
1110
- // symbol, because the query already fixed it. Filling both in is what
1111
- // makes the result a trade list rather than half-populated orders.
1112
1095
  o.id = o.original;
1113
1096
  o.symbol = symbol;
1114
1097
  }
1115
1098
  return orders;
1116
1099
  }
1117
1100
  // -- holdings --------------------------------------------------------------
1101
+ /** Comma-separated ids, matching the server's `?sessions=` filter. */
1118
1102
  async holdings(marketplaceId, sessionIds) {
1119
- let url;
1120
- if (sessionIds && sessionIds.length > 0) {
1121
- url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "holdings", `sessions=${sessionIds.join(",")}`);
1122
- }
1123
- else {
1124
- url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings");
1125
- }
1103
+ let url = `${this._marketplace(marketplaceId)}/holdings`;
1104
+ if (sessionIds && sessionIds.length > 0)
1105
+ url += `?sessions=${sessionIds.join(",")}`;
1126
1106
  const data = await this._get(url);
1127
1107
  return data.map(parseHolding);
1128
1108
  }
1129
1109
  async holding(marketplaceId) {
1130
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "currentHolding");
1131
- return parseHolding(await this._get(url));
1110
+ return parseHolding(await this._get(`${this._marketplace(marketplaceId)}/participants/me/holding`));
1132
1111
  }
1133
1112
  // -- connections -----------------------------------------------------------
1134
1113
  /**
@@ -1139,7 +1118,7 @@ export class Flexemarkets {
1139
1118
  * filter on the result.
1140
1119
  */
1141
1120
  async connections(marketplaceId) {
1142
- const url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "connections", "format=application/json");
1121
+ const url = `${this._marketplace(marketplaceId)}/connections`;
1143
1122
  return (await this._get(url)).map(parseConnection);
1144
1123
  }
1145
1124
  // -- management ------------------------------------------------------------
@@ -1168,28 +1147,34 @@ export class Flexemarkets {
1168
1147
  catch (e) {
1169
1148
  throw new InvalidArgumentError(`Marketplace definition is not valid JSON: ${e.message}`);
1170
1149
  }
1171
- const url = `${server(this._endpoint)}/v1/marketplaces`;
1172
- return parseMarketplace(await this._post(url, parsed));
1150
+ return parseMarketplace(await this._post(this._v1("/marketplaces"), parsed));
1173
1151
  }
1174
1152
  /** Opens the marketplace's session, returning it in its new state. */
1175
1153
  async openSession(marketplaceId) {
1176
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "open")));
1154
+ return this._sessionState(marketplaceId, "OPEN");
1177
1155
  }
1178
1156
  async pauseSession(marketplaceId) {
1179
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "pause")));
1157
+ return this._sessionState(marketplaceId, "PAUSED");
1180
1158
  }
1181
1159
  async closeSession(marketplaceId) {
1182
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "close")));
1160
+ return this._sessionState(marketplaceId, "CLOSED");
1183
1161
  }
1184
- /** Everyone in the caller's account. `usersJson`, not the HAL `users` form. */
1162
+ /**
1163
+ * A session's lifecycle is its state, PATCHed. Asking for the state it is
1164
+ * already in changes nothing; one it cannot reach from where it is --
1165
+ * pausing a closed session -- is refused.
1166
+ */
1167
+ async _sessionState(marketplaceId, state) {
1168
+ return parseSession(await this._patch(`${this._marketplace(marketplaceId)}/sessions/current`, { state }));
1169
+ }
1170
+ /** Everyone in the caller's account. */
1185
1171
  async users() {
1186
- const data = await this._get(uri(this._apiRoot, "usersJson"));
1172
+ const data = await this._get(this._v1("/users"));
1187
1173
  return data.map((u) => parsePerson(u));
1188
1174
  }
1189
- /** The opening positions of one allocation. A V1 route, not on the API root. */
1175
+ /** The opening positions of one allocation. */
1190
1176
  async allotments(marketplaceId, allocationId) {
1191
- const url = `${server(this._endpoint)}/v1/marketplaces/${marketplaceId}` +
1192
- `/allotments?allocation=${allocationId}`;
1177
+ const url = `${this._marketplace(marketplaceId)}/allocations/${allocationId}/allotments`;
1193
1178
  const data = await this._get(url);
1194
1179
  return data.map(parseAllotment);
1195
1180
  }
@@ -1204,7 +1189,7 @@ export class Flexemarkets {
1204
1189
  * computes with; the allotment encoding is applied here.
1205
1190
  */
1206
1191
  async allocate(marketplaceId, holdings) {
1207
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "allocations");
1192
+ const url = `${this._marketplace(marketplaceId)}/allocations`;
1208
1193
  const body = holdings.map((h) => holdingToAllotment(marketplaceId, h));
1209
1194
  const data = await this._post(url, body);
1210
1195
  return allotmentsToHoldings(data.map(parseAllotment));
@@ -1212,32 +1197,23 @@ export class Flexemarkets {
1212
1197
  /**
1213
1198
  * The holdings CSV, verbatim, for the current session or for given ones.
1214
1199
  *
1215
- * The filter is spelled `sessions=` on this route and `sessionIds=` on
1216
- * sessions and connections. Using the wrong one is not an error — it is an
1217
- * unfiltered answer.
1200
+ * The same route as {@link holdings}, asked for `text/csv`: the format is
1201
+ * chosen by the Accept header, not by a `/downloads` segment.
1218
1202
  */
1219
1203
  async downloadHoldings(marketplaceId, sessionIds) {
1220
- if (sessionIds && sessionIds.length > 0) {
1221
- return this._getText(uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "holdings/downloads", `sessions=${sessionIds.join(",")}`));
1222
- }
1223
- return this._getText(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings/downloads"));
1204
+ let url = `${this._marketplace(marketplaceId)}/holdings`;
1205
+ if (sessionIds && sessionIds.length > 0)
1206
+ url += `?sessions=${sessionIds.join(",")}`;
1207
+ return this._getText(url);
1224
1208
  }
1225
1209
  /**
1226
1210
  * Load opening positions from a holdings CSV. Stages the next allocation on
1227
1211
  * the same terms as {@link allocate}.
1228
1212
  */
1229
1213
  async uploadHoldings(marketplaceId, filename) {
1230
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings/uploads");
1231
- const form = new FormData();
1232
- form.append("file", new Blob([readFileSync(filename)]), basename(filename));
1233
- const resp = await fetch(url, {
1234
- method: "POST",
1235
- headers: { ...this._authHeaders(), "User-Agent": FM_NETWORK_CLIENT },
1236
- body: form,
1237
- });
1238
- const body = await resp.text();
1239
- checkResponse(resp, body);
1240
- return allotmentsToHoldings(JSON.parse(body).map(parseAllotment));
1214
+ const url = `${this._marketplace(marketplaceId)}/allocations`;
1215
+ const data = (await this._sendCsv("POST", url, filename));
1216
+ return allotmentsToHoldings(data.map(parseAllotment));
1241
1217
  }
1242
1218
  /**
1243
1219
  * Load per-participant private state from a CSV, returning what was stored.
@@ -1254,17 +1230,62 @@ export class Flexemarkets {
1254
1230
  * resolves to. A study's existing values file needs no change.
1255
1231
  */
1256
1232
  async uploadState(marketplaceId, filename) {
1257
- const url = v1(this._endpoint, `/marketplaces/${marketplaceId}/state/uploads`);
1258
- const form = new FormData();
1259
- form.append("file", new Blob([readFileSync(filename)]), basename(filename));
1233
+ const url = `${this._marketplace(marketplaceId)}/state`;
1234
+ const data = (await this._sendCsv("PUT", url, filename));
1235
+ return data.map(parseParticipantState);
1236
+ }
1237
+ /**
1238
+ * Push widgets to participants' screens, returning them as stored.
1239
+ *
1240
+ * One request for the whole list, which is what the server's rate limit is
1241
+ * shaped for: a session-open that tells sixty traders their values is one
1242
+ * push of sixty, not sixty pushes. A push to a target and key that already
1243
+ * has a widget replaces it.
1244
+ *
1245
+ * Not staged, unlike an allocation: it reaches the screen as soon as the
1246
+ * server stores it, and it is cleared when the session closes.
1247
+ *
1248
+ * The server checks the content and refuses a list with anything wrong in it
1249
+ * as an InvalidArgumentError; nothing in the list is stored. Pushing faster
1250
+ * than the server allows is answered 429, which arrives as an HttpError with
1251
+ * that status: back off and push again.
1252
+ */
1253
+ async pushWidgets(marketplaceId, widgets) {
1254
+ const url = `${this._marketplace(marketplaceId)}/widgets`;
1255
+ const data = await this._post(url, widgets.map(widgetPushJson));
1256
+ return data.map(parseWidget);
1257
+ }
1258
+ /**
1259
+ * Take down a widget: the marketplace's for `key`, or one participant's.
1260
+ *
1261
+ * True if one was removed, false if there was none to remove. With `userId`,
1262
+ * only that participant's widget goes -- `participants/{userId}/widgets/{key}`
1263
+ * -- and their marketplace widget for the same key, if any, shows again.
1264
+ *
1265
+ * An empty 404 is the server saying nothing was there. A 404 carrying a
1266
+ * failure document -- no such marketplace -- still throws, so a robot pointed
1267
+ * at the wrong marketplace does not read its clean-up as done.
1268
+ */
1269
+ async removeWidget(marketplaceId, key, userId) {
1270
+ const owner = userId !== undefined && userId !== null ? `/participants/${userId}` : "";
1271
+ const url = `${this._marketplace(marketplaceId)}${owner}/widgets/${encodeURIComponent(key)}`;
1260
1272
  const resp = await fetch(url, {
1261
- method: "POST",
1262
- headers: { ...this._authHeaders(), "User-Agent": FM_NETWORK_CLIENT },
1263
- body: form,
1273
+ method: "DELETE",
1274
+ headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
1264
1275
  });
1265
1276
  const body = await resp.text();
1277
+ if (resp.status === 404 && body.trim() === "")
1278
+ return false;
1266
1279
  checkResponse(resp, body);
1267
- return JSON.parse(body).map(parseParticipantState);
1280
+ return true;
1281
+ }
1282
+ /**
1283
+ * Every widget pushed to the marketplace and still standing, for every
1284
+ * participant -- what a manager reads to check on a robot.
1285
+ */
1286
+ async allWidgets(marketplaceId) {
1287
+ const data = await this._get(`${this._marketplace(marketplaceId)}/widgets?participant=all`);
1288
+ return data.map(parseWidget);
1268
1289
  }
1269
1290
  // -- events / WebSocket ----------------------------------------------------
1270
1291
  _sharedViews = new Map();
@@ -1404,8 +1425,9 @@ async function signIn(baseUrl, config, clientDescription) {
1404
1425
  // dropped it, and the Java SDK restored it with a test. This SDK and the
1405
1426
  // Python one never had it, so token auth returned 400 in both from the day
1406
1427
  // it was written.
1428
+ // POST, as minting a token is (fm-server 4.6).
1407
1429
  const resp = await fetch(`${baseUrl}/tokens/refresh`, {
1408
- method: "GET",
1430
+ method: "POST",
1409
1431
  headers: {
1410
1432
  Authorization: `Bearer ${tok}`,
1411
1433
  Accept: "application/json",
@@ -1413,11 +1435,8 @@ async function signIn(baseUrl, config, clientDescription) {
1413
1435
  },
1414
1436
  });
1415
1437
  const body = await resp.text();
1416
- if (resp.status === 401) {
1417
- throw new AuthenticationError("Authentication failed with provided token.");
1418
- }
1419
1438
  checkResponse(resp, body);
1420
- return parseToken(JSON.parse(body));
1439
+ return parseToken(readBody(body));
1421
1440
  }
1422
1441
  const acct = config.account ?? "";
1423
1442
  const email = config.email ?? "";
@@ -1442,10 +1461,7 @@ async function signIn(baseUrl, config, clientDescription) {
1442
1461
  }),
1443
1462
  });
1444
1463
  const body = await resp.text();
1445
- if (resp.status === 401) {
1446
- throw new AuthenticationError("Authentication failed.");
1447
- }
1448
1464
  checkResponse(resp, body);
1449
- return parseToken(JSON.parse(body));
1465
+ return parseToken(readBody(body));
1450
1466
  }
1451
1467
  //# sourceMappingURL=client.js.map