@flexemarkets/fm-sdk 0.3.4 → 0.5.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,7 +5,7 @@
5
5
  */
6
6
  import { readFileSync, existsSync } from "node:fs";
7
7
  import { homedir } from "node:os";
8
- import { basename, join } from "node:path";
8
+ import { join } from "node:path";
9
9
  import { orderedSecurities, toOrderType, toSide, unitGrid } from "./types.js";
10
10
  import { toInstant } from "./timestamps.js";
11
11
  import { EventListener, NO_SEQ } from "./stomp.js";
@@ -13,6 +13,12 @@ import { DefaultDesk, DeskHandle, } from "./desk.js";
13
13
  import { readVersion } from "./version.js";
14
14
  const FM_NETWORK_CLIENT = `fm-sdk-typescript/${readVersion()}`;
15
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;
16
22
  const BCRYPT_RE = /^\$2[abxy]?\$\d{2}\$[./A-Za-z0-9]{53}$/;
17
23
  const JWT_RE = /^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/;
18
24
  // ---------------------------------------------------------------------------
@@ -26,6 +32,23 @@ export class AuthorizationError extends FlexemarketsError {
26
32
  }
27
33
  export class InvalidArgumentError extends FlexemarketsError {
28
34
  }
35
+ /**
36
+ * An order the desk did not send, because fm-server would refuse it.
37
+ *
38
+ * Rejected by `Desk.submitLimit` when the session the desk holds is not open,
39
+ * or the holding it holds does not grant the order's side in that market --
40
+ * the two refusals fm-server answers with 400 `SESSION_CLOSED` and
41
+ * `ORDER_NOT_ALLOWED`, which `reason` names. An {@link InvalidArgumentError},
42
+ * so a caller catching the server's answer catches this too.
43
+ * `flexemarkets.desk(id, { refuseLocally: false })` sends every order instead.
44
+ */
45
+ export class OrderRefusedLocallyError extends InvalidArgumentError {
46
+ reason;
47
+ constructor(reason, message) {
48
+ super(message);
49
+ this.reason = reason;
50
+ }
51
+ }
29
52
  export class ConnectionFailedError extends FlexemarketsError {
30
53
  }
31
54
  export class ConfigurationError extends FlexemarketsError {
@@ -52,7 +75,7 @@ export class HttpError extends FlexemarketsError {
52
75
  *
53
76
  * Distinct from {@link HttpError}, which means the server answered and the
54
77
  * answer was an error. This means there was no usable answer at all — a
55
- * malformed body, or a link the API root does not carry.
78
+ * malformed body.
56
79
  */
57
80
  export class ApiError extends FlexemarketsError {
58
81
  }
@@ -203,6 +226,53 @@ export function parseParticipantState(data) {
203
226
  fields: { ...(data.fields ?? {}) },
204
227
  };
205
228
  }
229
+ function numberOrNull(value) {
230
+ return value === null || value === undefined ? null : Number(value);
231
+ }
232
+ function parseRobotParameter(data) {
233
+ return {
234
+ name: data.name ?? "",
235
+ label: data.label ?? null,
236
+ description: data.description ?? null,
237
+ type: data.type ?? null,
238
+ valueType: data.valueType ?? null,
239
+ // The robots write "required": null for a parameter that is not.
240
+ required: data.required === true,
241
+ defaultValue: data.default ?? null,
242
+ unit: data.unit ?? null,
243
+ min: numberOrNull(data.min),
244
+ max: numberOrNull(data.max),
245
+ };
246
+ }
247
+ export function parseRobotParameterConfig(data) {
248
+ const control = data.control ?? null;
249
+ return {
250
+ marketplaceId: data.marketplaceId ?? null,
251
+ robotId: data.robotId ?? "",
252
+ paramName: data.paramName ?? "",
253
+ value: data.value ?? "",
254
+ control: control === null
255
+ ? null
256
+ : { min: Number(control.min), max: Number(control.max), step: Number(control.step) },
257
+ exposed: data.exposed === true,
258
+ };
259
+ }
260
+ export function parseMarketplaceRobot(data) {
261
+ const manifest = data.manifest ?? {};
262
+ const groups = manifest.parameters ?? {};
263
+ const group = (name) => (groups[name] ?? []).map(parseRobotParameter);
264
+ return {
265
+ manifest: {
266
+ id: manifest.id ?? "",
267
+ version: manifest.version ?? null,
268
+ name: manifest.name ?? null,
269
+ description: manifest.description ?? null,
270
+ parameters: { manager: group("manager"), user: group("user"), platform: group("platform") },
271
+ },
272
+ enabled: data.enabled === true,
273
+ configuration: (data.configuration ?? []).map(parseRobotParameterConfig),
274
+ };
275
+ }
206
276
  export function parseWidget(data) {
207
277
  return {
208
278
  id: data.id ?? null,
@@ -333,42 +403,25 @@ export function parseConnection(data) {
333
403
  };
334
404
  }
335
405
  /**
336
- * The orders inside a HAL envelope.
406
+ * The orders in a snapshot answer, which is a bare JSON array or a failure.
337
407
  *
338
- * The server embeds them under `orders`. It was `orderDtoes` — Spring HATEOAS
339
- * pluralising `OrderDto` — and every SDK still read that name long after the
340
- * server stopped sending it, so `activeOrders` and `recentTrades` returned an
341
- * empty array always. `Desk` seeds from `activeOrders`, so its books were
342
- * never seeded; they filled from live deltas and looked plausible.
408
+ * Only the array is read because the V1 route never sent anything else:
409
+ * `GET /api/v1/marketplaces/{id}/orders` has always answered a bare array, and
410
+ * 0.4 requires fm-server 4.6.2. The HAL envelopes earlier SDKs tolerated
411
+ * belonged to the routes 0.4 no longer calls.
343
412
  *
344
- * Then the envelope itself went: fm-server now sends a bare array. Accepting
345
- * both *names* did not survive that, and this SDK failed the same silent way a
346
- * second time — `._embedded` on an array is `undefined`, so it returned an
347
- * empty book rather than throwing, while Java and Python at least raised.
413
+ * Anything else throws rather than reading as empty. An empty snapshot is the
414
+ * failure that hid twice before: `Desk` seeded an empty book, filled it from
415
+ * live deltas, and looked plausible.
348
416
  *
349
- * So read the shape rather than assume one. All three are accepted, because
350
- * all three are still deployed somewhere.
417
+ * @throws ApiError when the answer is not a JSON array
351
418
  */
352
- export function embeddedOrders(data) {
353
- if (Array.isArray(data))
354
- return data;
355
- if (data === null || typeof data !== "object")
356
- return [];
357
- const embedded = data._embedded;
358
- return embedded?.orders ?? embedded?.orderDtoes ?? [];
359
- }
360
- function parseApiRoot(data) {
361
- const linksRaw = data._links ?? {};
362
- const links = {};
363
- for (const [name, value] of Object.entries(linksRaw)) {
364
- if (typeof value === "object" && value !== null && "href" in value) {
365
- links[name] = value.href ?? "";
366
- }
367
- else if (typeof value === "string") {
368
- links[name] = value;
369
- }
419
+ export function ordersOf(data) {
420
+ if (!Array.isArray(data)) {
421
+ const kind = data === null || data === undefined ? "null" : typeof data;
422
+ throw new ApiError(`The orders snapshot answer was not a list of orders: got ${kind}`);
370
423
  }
371
- return { links };
424
+ return data;
372
425
  }
373
426
  /**
374
427
  * The most aggressive price this market will accept on `side`.
@@ -396,110 +449,6 @@ export function marketableLimit(market, side) {
396
449
  const span = market.priceMaximum - market.priceMinimum;
397
450
  return market.priceMinimum + Math.floor(span / market.priceTick) * market.priceTick;
398
451
  }
399
- /**
400
- * The `scheme://host:port` of an absolute http(s) URL, else undefined.
401
- *
402
- * A relative href already resolves against the origin it was fetched from,
403
- * and a scheme that is not HTTP is not ours to rewrite.
404
- */
405
- function httpOrigin(url) {
406
- if (!url)
407
- return undefined;
408
- const end = url.indexOf("://");
409
- if (end < 0)
410
- return undefined;
411
- const scheme = url.substring(0, end).toLowerCase();
412
- if (scheme !== "http" && scheme !== "https")
413
- return undefined;
414
- const pathStart = url.indexOf("/", end + 3);
415
- return pathStart < 0 ? url : url.substring(0, pathStart);
416
- }
417
- /**
418
- * Point the API root's links back at the host that was dialled.
419
- *
420
- * The server builds these hrefs from the request it believes it received, and
421
- * behind a proxy that belief can be wrong: an origin reached over a plaintext
422
- * leg reports `http://` even though the caller arrived on `https://`. Every
423
- * call that goes through a link — which is most of them — then leaves on plain
424
- * HTTP and meets the edge's redirect. A GET survives it. A POST does not: a
425
- * 301 is followed as a GET with the body dropped, so placing an order or
426
- * opening a session fails with nothing placed and nothing pointing at the
427
- * scheme.
428
- *
429
- * Only the origin is replaced. The path, query and any URI template are the
430
- * server's to choose; where it is reachable is not, and the token in hand was
431
- * issued by the origin dialled, not by whatever the links name.
432
- */
433
- export function rebaseApiRoot(root, endpoint) {
434
- const origin = httpOrigin(endpoint);
435
- if (!origin)
436
- return root;
437
- const links = {};
438
- const moved = [];
439
- for (const [name, href] of Object.entries(root.links)) {
440
- const named = httpOrigin(href);
441
- if (!named || named === origin) {
442
- links[name] = href;
443
- continue;
444
- }
445
- if (!moved.includes(named))
446
- moved.push(named);
447
- links[name] = origin + href.substring(named.length);
448
- }
449
- if (moved.length > 0) {
450
- // Said out loud, because the rewrite would otherwise hide a deployment
451
- // that is genuinely misconfigured — and a silent correction here is how it
452
- // stays misconfigured. The SDK keeps working; the operator still gets told
453
- // where to look.
454
- console.warn(`[fm-sdk] The API root names ${moved.join(", ")} but this client dialled ${origin}; ` +
455
- `rewriting ${moved.length} link origin(s) to match. The server is behind a proxy ` +
456
- `that is not forwarding the request scheme, so its links are wrong. Fix it at the ` +
457
- `edge — this rewrite only keeps calls working.`);
458
- }
459
- return { links };
460
- }
461
- // ---------------------------------------------------------------------------
462
- // HATEOAS link resolution
463
- // ---------------------------------------------------------------------------
464
- function processTemplate(href) {
465
- const idx = href.indexOf("{");
466
- return idx >= 0 ? href.substring(0, idx) : href;
467
- }
468
- /**
469
- * A V1 route, addressed from the server rather than through a HAL link.
470
- *
471
- * V1 is flat and versioned: the path is knowable without fetching the API root
472
- * first, which is the point of it. Every call that moves here loses a HAL
473
- * dependency as well as a version.
474
- */
475
- function v1(endpoint, path) {
476
- return `${server(endpoint)}/v1${path}`;
477
- }
478
- function uri(root, linkName) {
479
- const href = root.links[linkName];
480
- if (href === undefined)
481
- throw new ApiError(`Link '${linkName}' not found in API root.`);
482
- return processTemplate(href);
483
- }
484
- function uriId(root, linkName, id) {
485
- return `${uri(root, linkName)}/${id}`;
486
- }
487
- function uriIdSegment(root, linkName, id, segment) {
488
- return `${uriId(root, linkName, id)}/${segment}`;
489
- }
490
- function uriParam(root, linkName, param) {
491
- return `${uri(root, linkName)}?${param}`;
492
- }
493
- function uriIdSegmentParam(root, linkName, id, segment, param) {
494
- const base = uriIdSegment(root, linkName, id, segment);
495
- return param ? `${base}?${param}` : base;
496
- }
497
- function uriParamMarketplaceIdParam(root, linkName, id, param) {
498
- let u = uriParam(root, linkName, `marketplaceId=${id}`);
499
- if (param)
500
- u += `&${param}`;
501
- return u;
502
- }
503
452
  // ---------------------------------------------------------------------------
504
453
  // Credential / configuration helpers
505
454
  // ---------------------------------------------------------------------------
@@ -557,11 +506,6 @@ export function resolveEndpoint(endpoint) {
557
506
  }
558
507
  return { endpoint };
559
508
  }
560
- function sessionIdsParam(sessionIds) {
561
- if (!sessionIds || sessionIds.length === 0)
562
- return "";
563
- return "sessionIds=" + sessionIds.join(",");
564
- }
565
509
  export function loadPropertiesFile(path) {
566
510
  const props = {};
567
511
  if (!existsSync(path))
@@ -619,6 +563,20 @@ export function detail(body) {
619
563
  }
620
564
  return body;
621
565
  }
566
+ /**
567
+ * The body of a successful answer, parsed. A 200 that is not JSON -- an edge
568
+ * proxy's HTML error page, a truncated body -- is an answer the SDK cannot
569
+ * read, so it is an {@link ApiError}, as in the Java SDK, rather than a bare
570
+ * SyntaxError escaping past a caller who catches FlexemarketsError.
571
+ */
572
+ function readBody(body) {
573
+ try {
574
+ return JSON.parse(body);
575
+ }
576
+ catch {
577
+ throw new ApiError("Failed to parse the response body");
578
+ }
579
+ }
622
580
  function checkResponse(response, body) {
623
581
  const status = response.status;
624
582
  if (status >= 200 && status < 300)
@@ -648,20 +606,38 @@ function suggestedNameIn(body) {
648
606
  // ---------------------------------------------------------------------------
649
607
  // Flexemarkets client
650
608
  // ---------------------------------------------------------------------------
609
+ /** A 401 that says the token ran out, as distinct from one that is wrong. */
610
+ async function tokenExpired(resp) {
611
+ if (resp.status !== 401)
612
+ return false;
613
+ try {
614
+ const body = JSON.parse(await resp.clone().text());
615
+ return body.error === "ACCOUNT_TOKEN_EXPIRED";
616
+ }
617
+ catch {
618
+ return false;
619
+ }
620
+ }
651
621
  export class Flexemarkets {
652
622
  _clientDescription;
653
623
  _endpoint;
654
624
  _baseUrl;
655
- _bearerToken;
656
- _apiRoot;
625
+ /**
626
+ * The sign-in this client presents, replaced whole when an expired one is
627
+ * renewed (see {@link _renewToken}); the bearer header is derived from it,
628
+ * so `token()` and every request agree on which token is current.
629
+ */
630
+ _tokenObj;
631
+ /** Kept only to sign in again when the token runs out; null for a client given a token. */
632
+ _credentials = null;
633
+ _renewing = null;
657
634
  _account;
658
635
  _user;
659
- _tokenObj;
660
636
  _eventListener = null;
661
- constructor(endpoint, baseUrl, bearerToken, clientDescription) {
637
+ constructor(endpoint, baseUrl, tokenObj, clientDescription) {
662
638
  this._endpoint = endpoint;
663
639
  this._baseUrl = baseUrl;
664
- this._bearerToken = bearerToken;
640
+ this._tokenObj = tokenObj;
665
641
  this._clientDescription = clientDescription;
666
642
  }
667
643
  /** Connect to the Flexemarkets API. */
@@ -686,13 +662,12 @@ export class Flexemarkets {
686
662
  const baseUrl = server(ep);
687
663
  // Authenticate
688
664
  const tokenObj = await signIn(baseUrl, config, desc);
689
- const bearer = `Bearer ${tokenObj.token}`;
690
- const fm = new Flexemarkets(ep, baseUrl, bearer, desc);
691
- fm._tokenObj = tokenObj;
665
+ const fm = new Flexemarkets(ep, baseUrl, tokenObj, desc);
666
+ if (config.account && config.email && config.password && !(config.token && isValidToken(config.token))) {
667
+ fm._credentials = { ...config };
668
+ }
692
669
  fm._account = tokenObj.account;
693
670
  fm._user = tokenObj.person;
694
- // Fetch API root for HATEOAS links
695
- fm._apiRoot = await fm._fetchApiRoot();
696
671
  return fm;
697
672
  }
698
673
  // -- properties ------------------------------------------------------------
@@ -721,17 +696,64 @@ export class Flexemarkets {
721
696
  _authHeaders() {
722
697
  return { Authorization: this._bearerToken };
723
698
  }
699
+ /** The Authorization header for the current sign-in. */
700
+ get _bearerToken() {
701
+ return `Bearer ${this._tokenObj.token}`;
702
+ }
703
+ /**
704
+ * fetch with this client's token; if it has expired, renew it once and send
705
+ * again. Tokens live 24 hours, so a robot that ran longer ended the first
706
+ * time it asked for anything after that, or looped on the refusal -- a Utah
707
+ * poller, about 250 times a day at 00Z.
708
+ */
709
+ async _fetch(url, init) {
710
+ const presented = this._bearerToken;
711
+ const resp = await fetch(url, init);
712
+ if (!(await tokenExpired(resp)) || !(await this._renewToken(presented)))
713
+ return resp;
714
+ const headers = { ...init.headers, Authorization: this._bearerToken };
715
+ return fetch(url, { ...init, headers });
716
+ }
717
+ /**
718
+ * Sign in again with the credentials this client was made with. False when
719
+ * it was given a token rather than credentials, or the sign-in fails; the
720
+ * caller then answers with the refusal it had. `presented` is the header
721
+ * the refused request or stream connect carried: one another caller has
722
+ * already replaced is not renewed again, and concurrent callers share one
723
+ * sign-in.
724
+ */
725
+ async _renewToken(presented) {
726
+ if (this._credentials === null)
727
+ return false;
728
+ if (presented !== this._bearerToken)
729
+ return true;
730
+ if (this._renewing === null) {
731
+ this._renewing = (async () => {
732
+ try {
733
+ this._tokenObj = await signIn(this._baseUrl, this._credentials, this._clientDescription);
734
+ return true;
735
+ }
736
+ catch {
737
+ return false;
738
+ }
739
+ finally {
740
+ this._renewing = null;
741
+ }
742
+ })();
743
+ }
744
+ return this._renewing;
745
+ }
724
746
  async _get(url) {
725
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
747
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
726
748
  headers: {
727
749
  ...this._authHeaders(),
728
- Accept: "application/json, application/hal+json",
750
+ Accept: "application/json",
729
751
  "User-Agent": FM_NETWORK_CLIENT,
730
752
  },
731
753
  });
732
754
  const body = await resp.text();
733
755
  checkResponse(resp, body);
734
- return JSON.parse(body);
756
+ return readBody(body);
735
757
  }
736
758
  /**
737
759
  * GET helper that returns the parsed body bundled with the
@@ -740,10 +762,10 @@ export class Flexemarkets {
740
762
  * `Snapshot.NO_SEQ` when the header is absent.
741
763
  */
742
764
  async _getSnapshot(url) {
743
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
765
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
744
766
  headers: {
745
767
  ...this._authHeaders(),
746
- Accept: "application/json, application/hal+json",
768
+ Accept: "application/json",
747
769
  "User-Agent": FM_NETWORK_CLIENT,
748
770
  },
749
771
  });
@@ -751,24 +773,30 @@ export class Flexemarkets {
751
773
  checkResponse(resp, body);
752
774
  const raw = resp.headers.get("x-fm-as-of-seq");
753
775
  const asOfSeq = raw === null ? NO_SEQ : Number.parseInt(raw, 10);
754
- return { data: JSON.parse(body), asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
776
+ return { data: readBody(body), asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
755
777
  }
756
- /**
757
- * PATCH with no body — the shape every session transition takes: the verb and
758
- * the path carry the whole request.
759
- */
760
- async _patch(url) {
761
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
762
- method: "PATCH",
778
+ /** PATCH with a JSON body -- the shape every session transition takes. */
779
+ async _patch(url, json) {
780
+ return this._sendJson("PATCH", url, json);
781
+ }
782
+ /** PUT with a JSON body -- a robot parameter's configuration, say. */
783
+ async _put(url, json) {
784
+ return this._sendJson("PUT", url, json);
785
+ }
786
+ async _sendJson(method, url, json) {
787
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
788
+ method,
763
789
  headers: {
764
790
  ...this._authHeaders(),
765
- Accept: "application/json, application/hal+json",
791
+ "Content-Type": "application/json",
792
+ Accept: "application/json",
766
793
  "User-Agent": FM_NETWORK_CLIENT,
767
794
  },
795
+ body: JSON.stringify(json),
768
796
  });
769
797
  const body = await resp.text();
770
798
  checkResponse(resp, body);
771
- return JSON.parse(body);
799
+ return readBody(body);
772
800
  }
773
801
  /**
774
802
  * GET returning the body verbatim, for endpoints that answer with something
@@ -776,7 +804,7 @@ export class Flexemarkets {
776
804
  * the header row.
777
805
  */
778
806
  async _getText(url) {
779
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
807
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
780
808
  headers: {
781
809
  ...this._authHeaders(),
782
810
  Accept: "text/csv, */*",
@@ -788,19 +816,19 @@ export class Flexemarkets {
788
816
  return body;
789
817
  }
790
818
  async _post(url, json) {
791
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
819
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
792
820
  method: "POST",
793
821
  headers: {
794
822
  ...this._authHeaders(),
795
823
  "Content-Type": "application/json",
796
- Accept: "application/json, application/hal+json",
824
+ Accept: "application/json",
797
825
  "User-Agent": FM_NETWORK_CLIENT,
798
826
  },
799
827
  body: JSON.stringify(json),
800
828
  });
801
829
  const body = await resp.text();
802
830
  checkResponse(resp, body);
803
- return JSON.parse(body);
831
+ return readBody(body);
804
832
  }
805
833
  // -- administration --------------------------------------------------------
806
834
  /*
@@ -820,7 +848,7 @@ export class Flexemarkets {
820
848
  * cannot sign in as.
821
849
  */
822
850
  async signup(accountName, email, password, firstName, lastName) {
823
- const url = uri(this._apiRoot, "accounts");
851
+ const url = this._v1("/accounts");
824
852
  try {
825
853
  const data = await this._post(url, {
826
854
  accountName,
@@ -843,49 +871,58 @@ export class Flexemarkets {
843
871
  throw e;
844
872
  }
845
873
  }
846
- /** Approve an account by name, returning it as it now stands. */
874
+ /**
875
+ * Approve an account by name, returning it as it now stands.
876
+ *
877
+ * V1 approves an account by id; the name is looked up in the account list
878
+ * first, so callers keep naming the account they signed up.
879
+ */
847
880
  async approveAccount(accountName) {
848
- const url = `${server(this._endpoint)}/approvals`;
849
- const data = await this._post(url, { name: accountName, approval: true });
881
+ const account = (await this.accounts()).find((a) => a.name === accountName);
882
+ if (account === undefined) {
883
+ throw new InvalidArgumentError(`No account named '${accountName}'`);
884
+ }
885
+ const data = await this._post(this._v1(`/accounts/${account.id}/approvals`), { approve: true });
850
886
  return parseAccount(data.account);
851
887
  }
852
888
  /** One account by id. */
853
889
  async accountById(accountId) {
854
- return parseAccount(await this._get(uriId(this._apiRoot, "accounts", accountId)));
890
+ return parseAccount(await this._get(this._v1(`/accounts/${accountId}`)));
855
891
  }
856
892
  /** One user by id. */
857
893
  async userById(userId) {
858
- return parsePerson(await this._get(v1(this._endpoint, `/users/${userId}`)));
894
+ return parsePerson(await this._get(this._v1(`/users/${userId}`)));
859
895
  }
860
- /** The marketplace's private-trader identifiers. */
896
+ /**
897
+ * The names of the participants a caller may target: `GET participants`,
898
+ * names only. A row carries the user id too, for a manager; not needed here.
899
+ */
861
900
  async identifiers(marketplaceId) {
862
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "privateTraders");
863
- return (await this._get(url));
901
+ const rows = (await this._get(`${this._marketplace(marketplaceId)}/participants`));
902
+ return rows.map((r) => r.name);
864
903
  }
865
904
  /** Delete the caller's own account. Its own route, not accounts/{yourId}. */
866
905
  async deleteMyAccount() {
867
- await this._delete(`${server(this._endpoint)}/accounts/me`);
906
+ await this._delete(this._v1("/accounts/me"));
868
907
  }
869
908
  /** Every account on the server. Admin-only. */
870
909
  async accounts() {
871
- const url = uriParam(this._apiRoot, "accounts", "format=application/json");
872
- const data = await this._get(url);
910
+ const data = await this._get(this._v1("/accounts"));
873
911
  return data.map(parseAccount);
874
912
  }
875
913
  /** Delete an account. Destructive, and takes its users with it. */
876
914
  async deleteAccount(accountId) {
877
- await this._delete(uriId(this._apiRoot, "accounts", accountId));
915
+ await this._delete(this._v1(`/accounts/${accountId}`));
878
916
  }
879
917
  /** Create a user in the caller's account. */
880
918
  async createUser(email, password, firstName, lastName, roles = []) {
881
- const url = v1(this._endpoint, "/users");
882
- const data = await this._post(url, { email, password, firstName, lastName, roles });
919
+ const data = await this._post(this._v1("/users"), { email, password, firstName, lastName, roles });
883
920
  return parsePerson(data);
884
921
  }
885
922
  /** Delete a user. Destructive. */
886
923
  async deleteUser(userId) {
887
924
  try {
888
- await this._delete(uriId(this._apiRoot, "users", userId));
925
+ await this._delete(this._v1(`/users/${userId}`));
889
926
  }
890
927
  catch (e) {
891
928
  // The user still owns orders or allotments. Deleting them would orphan
@@ -900,7 +937,7 @@ export class Flexemarkets {
900
937
  /** Create an empty marketplace. See also {@link createMarketplaceFromJson}. */
901
938
  /** Delete a marketplace, and with it its sessions and their history. */
902
939
  async deleteMarketplace(marketplaceId) {
903
- await this._delete(uriId(this._apiRoot, "marketplaces", marketplaceId));
940
+ await this._delete(this._marketplace(marketplaceId));
904
941
  }
905
942
  /**
906
943
  * Add a market to a marketplace.
@@ -912,8 +949,7 @@ export class Flexemarkets {
912
949
  * `units` keeps the old default.
913
950
  */
914
951
  async createMarket(marketplaceId, symbol, name, price, units = unitGrid(), privateMarket = false) {
915
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "markets");
916
- return parseMarket(await this._post(url, {
952
+ return parseMarket(await this._post(`${this._marketplace(marketplaceId)}/markets`, {
917
953
  symbol,
918
954
  name,
919
955
  priceMinimum: price.minimum,
@@ -932,7 +968,8 @@ export class Flexemarkets {
932
968
  * delivered to the person they belong to.
933
969
  */
934
970
  async managerOtpBundle(userIds) {
935
- const url = `${server(this._endpoint)}/otp/manager`;
971
+ // Unversioned: fm-server has no V1 route for passcodes.
972
+ const url = `${this._baseUrl}/otp/manager`;
936
973
  const data = await this._post(url, { userIds });
937
974
  return {
938
975
  expiresAt: toInstant(data.expiresAt),
@@ -945,34 +982,71 @@ export class Flexemarkets {
945
982
  }
946
983
  /** DELETE, whose answer is a status and nothing worth parsing. */
947
984
  async _delete(url) {
948
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
985
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
949
986
  method: "DELETE",
950
987
  headers: { ...this._authHeaders(), Accept: "application/json" },
951
988
  });
952
989
  const body = await resp.text();
953
990
  checkResponse(resp, body);
954
991
  }
955
- async _fetchApiRoot() {
956
- const data = await this._get(this._baseUrl);
957
- return rebaseApiRoot(parseApiRoot(data), this._baseUrl);
992
+ /**
993
+ * DELETE whose answer is the resource as it ended -- an order's CANCEL.
994
+ */
995
+ async _deleteFor(url) {
996
+ const resp = await this._fetch(url, {
997
+ method: "DELETE",
998
+ headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
999
+ });
1000
+ const body = await resp.text();
1001
+ checkResponse(resp, body);
1002
+ return readBody(body);
1003
+ }
1004
+ /**
1005
+ * Send one CSV file as the body, `Content-Type: text/csv` -- format by
1006
+ * header, where 0.3 posted it as a multipart upload to an `/uploads`
1007
+ * segment. Bytes, not a string, so the file's own encoding survives.
1008
+ */
1009
+ async _sendCsv(method, url, filename) {
1010
+ const resp = await this._fetch(url, {
1011
+ method,
1012
+ headers: {
1013
+ ...this._authHeaders(),
1014
+ "Content-Type": "text/csv",
1015
+ Accept: "application/json",
1016
+ "User-Agent": FM_NETWORK_CLIENT,
1017
+ },
1018
+ body: readFileSync(filename),
1019
+ });
1020
+ const body = await resp.text();
1021
+ checkResponse(resp, body);
1022
+ return readBody(body);
1023
+ }
1024
+ /**
1025
+ * A V1 route. 0.4 addresses every route from the server rather than through
1026
+ * the HAL root's links: the path is knowable without fetching anything
1027
+ * first, and a root that drops a link can no longer take a call with it.
1028
+ */
1029
+ _v1(path) {
1030
+ return `${this._baseUrl}/v1${path}`;
1031
+ }
1032
+ /** The V1 route of one marketplace, under which nearly everything lives. */
1033
+ _marketplace(marketplaceId) {
1034
+ return this._v1(`/marketplaces/${marketplaceId}`);
958
1035
  }
959
1036
  // ======================================================================
960
1037
  // REST APIs
961
1038
  // ======================================================================
962
1039
  // -- marketplaces ----------------------------------------------------------
963
1040
  async marketplaces() {
964
- const url = uriParam(this._apiRoot, "marketplaces", "format=application/json");
965
- const data = await this._get(url);
1041
+ const data = await this._get(this._v1("/marketplaces"));
966
1042
  return data.map(parseMarketplace);
967
1043
  }
968
1044
  async marketplace(marketplaceId) {
969
- const url = uriId(this._apiRoot, "marketplaces", marketplaceId);
970
- return parseMarketplace(await this._get(url));
1045
+ return parseMarketplace(await this._get(this._marketplace(marketplaceId)));
971
1046
  }
972
1047
  // -- markets ---------------------------------------------------------------
973
1048
  async markets(marketplaceId) {
974
- const url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "markets", "format=application/json");
975
- const data = await this._get(url);
1049
+ const data = await this._get(`${this._marketplace(marketplaceId)}/markets`);
976
1050
  return data.map(parseMarket);
977
1051
  }
978
1052
  /**
@@ -999,9 +1073,9 @@ export class Flexemarkets {
999
1073
  hasRole(role) {
1000
1074
  return (this._user?.roles ?? []).includes(role);
1001
1075
  }
1076
+ /** The symbols of the marketplace's markets, read from the markets themselves. */
1002
1077
  async symbols(marketplaceId) {
1003
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "symbols");
1004
- return (await this._get(url));
1078
+ return (await this.markets(marketplaceId)).map((m) => m.symbol);
1005
1079
  }
1006
1080
  // -- sessions --------------------------------------------------------------
1007
1081
  /**
@@ -1011,23 +1085,17 @@ export class Flexemarkets {
1011
1085
  * the `sessionIds` this used to accept was silently ignored: it returned the
1012
1086
  * whole history and looked like it had filtered. Filter the result; fm-ui
1013
1087
  * already does.
1014
- *
1015
- * On `GET /api/v1/marketplaces/{id}/sessions`, which answers with the same
1016
- * fields as the V0 route it replaces — verified against a running server,
1017
- * not assumed — and needs no `format=application/json` to avoid HAL.
1018
1088
  */
1019
1089
  async sessions(marketplaceId) {
1020
- const url = v1(this._endpoint, `/marketplaces/${marketplaceId}/sessions`);
1090
+ const url = `${this._marketplace(marketplaceId)}/sessions`;
1021
1091
  return (await this._get(url)).map(parseSession);
1022
1092
  }
1023
1093
  async session(marketplaceId) {
1024
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "currentSession");
1025
- return parseSession(await this._get(url));
1094
+ return parseSession(await this._get(`${this._marketplace(marketplaceId)}/sessions/current`));
1026
1095
  }
1027
1096
  // -- orders ----------------------------------------------------------------
1028
1097
  async submitLimit(marketplaceId, marketId, side, units, price) {
1029
- const url = uri(this._apiRoot, "orders");
1030
- const data = await this._post(url, {
1098
+ const data = await this._post(`${this._marketplace(marketplaceId)}/orders`, {
1031
1099
  marketplaceId,
1032
1100
  marketId,
1033
1101
  type: "LIMIT",
@@ -1077,18 +1145,13 @@ export class Flexemarkets {
1077
1145
  }
1078
1146
  throw new InvalidArgumentError(`Market ${marketId} is not in marketplace ${marketplaceId}`);
1079
1147
  }
1148
+ /**
1149
+ * DELETE the order: the server builds the CANCEL from the order's own
1150
+ * lineage and market, and answers with it. `marketId` is no longer sent --
1151
+ * the order already says which market it is in.
1152
+ */
1080
1153
  async submitCancel(marketplaceId, marketId, originalId) {
1081
- const url = uri(this._apiRoot, "orders");
1082
- const data = await this._post(url, {
1083
- marketplaceId,
1084
- marketId,
1085
- type: "CANCEL",
1086
- id: originalId,
1087
- original: originalId,
1088
- supplier: originalId,
1089
- clientDescription: this._clientDescription,
1090
- });
1091
- return parseOrder(data);
1154
+ return parseOrder(await this._deleteFor(`${this._marketplace(marketplaceId)}/orders/${originalId}`));
1092
1155
  }
1093
1156
  /**
1094
1157
  * The active-orders snapshot: every resting limit order on the
@@ -1098,10 +1161,9 @@ export class Flexemarkets {
1098
1161
  * value and skip those whose seq is less than or equal.
1099
1162
  */
1100
1163
  async activeOrders(marketplaceId) {
1101
- const baseRest = this._baseUrl;
1102
- const url = `${baseRest}/v1/marketplaces/${marketplaceId}/orders/active`;
1164
+ const url = `${this._marketplace(marketplaceId)}/orders?state=ACTIVE`;
1103
1165
  const { data, asOfSeq } = await this._getSnapshot(url);
1104
- const orders = embeddedOrders(data).map(parseOrder);
1166
+ const orders = ordersOf(data).map(parseOrder);
1105
1167
  return { body: orders, asOfSeq };
1106
1168
  }
1107
1169
  /**
@@ -1115,73 +1177,75 @@ export class Flexemarkets {
1115
1177
  * order differs. `Tape` sorts what it is given, so a caller seeding a tape
1116
1178
  * through `Desk` is unaffected; a caller reading this list directly
1117
1179
  * should not assume one.
1180
+ *
1181
+ * With `marketId`, only that market's legs (`&market=`), `size` of them,
1182
+ * two to a trade. What `Desk` seeds each tape from: read for every market
1183
+ * at once, a busy market's legs fill the limit and a quiet market's tape
1184
+ * comes up empty, though it has traded.
1118
1185
  */
1119
- async recentTrades(marketplaceId, size = 1000) {
1120
- const url = `${this._baseUrl}/v1/marketplaces/${marketplaceId}/orders/recent-trades?size=${size}`;
1186
+ async recentTrades(marketplaceId, size = 1000, marketId) {
1187
+ const market = marketId === undefined ? "" : `&market=${marketId}`;
1188
+ const url = `${this._marketplace(marketplaceId)}/orders?state=TRADED${market}&limit=${size}`;
1121
1189
  const { data, asOfSeq } = await this._getSnapshot(url);
1122
- const orders = embeddedOrders(data).map(parseOrder);
1190
+ const orders = ordersOf(data).map(parseOrder);
1123
1191
  return { body: orders, asOfSeq };
1124
1192
  }
1193
+ /**
1194
+ * The marketplace's orders.
1195
+ *
1196
+ * With no option, the current session's orders less every cancelled one, the
1197
+ * CANCEL that consumed it, and both legs of a self-cross -- what a study
1198
+ * ranking participants needs. Without `cancelled=false` the V1 read is the
1199
+ * raw lifecycle, which is what `sessionIds` asks for: every LIMIT and CANCEL
1200
+ * row of the named runs, as the exchange stored them. `symbol` reads one
1201
+ * market's active orders, with the symbol filled in.
1202
+ */
1125
1203
  async orders(marketplaceId, options) {
1204
+ const base = `${this._marketplace(marketplaceId)}/orders`;
1126
1205
  if (options?.symbol != null) {
1127
- const url = uriParamMarketplaceIdParam(this._apiRoot, "symbolOrdersJson", marketplaceId, `symbol=${options.symbol}`);
1128
- const data = await this._get(url);
1206
+ const symbol = options.symbol;
1207
+ const data = await this._get(`${base}?state=ACTIVE&symbol=${encodeURIComponent(symbol)}`);
1129
1208
  const orders = data.map(parseOrder);
1130
1209
  for (const o of orders)
1131
- o.symbol = options.symbol;
1210
+ o.symbol = symbol;
1132
1211
  return orders;
1133
1212
  }
1134
- if (options?.sessionIds != null) {
1135
- const url = uriParamMarketplaceIdParam(this._apiRoot, "sessionOrdersJson", marketplaceId, sessionIdsParam(options.sessionIds));
1136
- const data = await this._get(url);
1137
- return data.map(parseOrder);
1138
- }
1139
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "orders");
1140
- const data = await this._get(url);
1141
- return data.map(parseOrder);
1213
+ const url = options?.sessionIds != null && options.sessionIds.length > 0
1214
+ ? `${base}?sessions=${options.sessionIds.join(",")}`
1215
+ : `${base}?cancelled=false`;
1216
+ return (await this._get(url)).map(parseOrder);
1142
1217
  }
1143
1218
  /**
1144
- * Tape in one market, in ascending order id.
1145
- *
1146
- * Answered by a symbol-keyed route, so the orders come back without the
1147
- * symbol on them and with the trade id in `original`; both are filled in
1148
- * before returning, which is what makes the result a trade list rather than
1149
- * a set of half-populated orders.
1219
+ * One market's traded legs, as many as the server gives in one read
1220
+ * ({@link MAX_TRADED_LEGS}), in the server's order.
1150
1221
  *
1151
- * This is the FM-3 surface (`/api/orders-json/symbol-trades`) and its order
1152
- * is the server's, which sorts by order id and nothing else. It is neither
1153
- * chronological by trade time nor most-recent-first — the first element is
1154
- * the lowest id, not the latest trade. Sort by `lastModifiedDate` if you
1155
- * want time order.
1222
+ * The answer carries the trade id in `original` and no symbol on the orders,
1223
+ * because the query already fixed the symbol. Both are filled in before
1224
+ * returning, which is what makes the result a trade list rather than a set of
1225
+ * half-populated orders. Sort by `lastModifiedDate` if you want time order.
1156
1226
  */
1157
1227
  async trades(marketplaceId, symbol) {
1158
- const url = uriParamMarketplaceIdParam(this._apiRoot, "symbolTradesJson", marketplaceId, `symbol=${symbol}`);
1228
+ const url = `${this._marketplace(marketplaceId)}/orders?state=TRADED` +
1229
+ `&symbol=${encodeURIComponent(symbol)}&limit=${MAX_TRADED_LEGS}`;
1159
1230
  const data = await this._get(url);
1160
1231
  const orders = data.map(parseOrder);
1161
1232
  for (const o of orders) {
1162
- // The symbol-keyed route answers with the trade id in `original` and no
1163
- // symbol, because the query already fixed it. Filling both in is what
1164
- // makes the result a trade list rather than half-populated orders.
1165
1233
  o.id = o.original;
1166
1234
  o.symbol = symbol;
1167
1235
  }
1168
1236
  return orders;
1169
1237
  }
1170
1238
  // -- holdings --------------------------------------------------------------
1239
+ /** Comma-separated ids, matching the server's `?sessions=` filter. */
1171
1240
  async holdings(marketplaceId, sessionIds) {
1172
- let url;
1173
- if (sessionIds && sessionIds.length > 0) {
1174
- url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "holdings", `sessions=${sessionIds.join(",")}`);
1175
- }
1176
- else {
1177
- url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings");
1178
- }
1241
+ let url = `${this._marketplace(marketplaceId)}/holdings`;
1242
+ if (sessionIds && sessionIds.length > 0)
1243
+ url += `?sessions=${sessionIds.join(",")}`;
1179
1244
  const data = await this._get(url);
1180
1245
  return data.map(parseHolding);
1181
1246
  }
1182
1247
  async holding(marketplaceId) {
1183
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "currentHolding");
1184
- return parseHolding(await this._get(url));
1248
+ return parseHolding(await this._get(`${this._marketplace(marketplaceId)}/participants/me/holding`));
1185
1249
  }
1186
1250
  // -- connections -----------------------------------------------------------
1187
1251
  /**
@@ -1192,7 +1256,7 @@ export class Flexemarkets {
1192
1256
  * filter on the result.
1193
1257
  */
1194
1258
  async connections(marketplaceId) {
1195
- const url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "connections", "format=application/json");
1259
+ const url = `${this._marketplace(marketplaceId)}/connections`;
1196
1260
  return (await this._get(url)).map(parseConnection);
1197
1261
  }
1198
1262
  // -- management ------------------------------------------------------------
@@ -1221,28 +1285,34 @@ export class Flexemarkets {
1221
1285
  catch (e) {
1222
1286
  throw new InvalidArgumentError(`Marketplace definition is not valid JSON: ${e.message}`);
1223
1287
  }
1224
- const url = `${server(this._endpoint)}/v1/marketplaces`;
1225
- return parseMarketplace(await this._post(url, parsed));
1288
+ return parseMarketplace(await this._post(this._v1("/marketplaces"), parsed));
1226
1289
  }
1227
1290
  /** Opens the marketplace's session, returning it in its new state. */
1228
1291
  async openSession(marketplaceId) {
1229
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "open")));
1292
+ return this._sessionState(marketplaceId, "OPEN");
1230
1293
  }
1231
1294
  async pauseSession(marketplaceId) {
1232
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "pause")));
1295
+ return this._sessionState(marketplaceId, "PAUSED");
1233
1296
  }
1234
1297
  async closeSession(marketplaceId) {
1235
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "close")));
1298
+ return this._sessionState(marketplaceId, "CLOSED");
1299
+ }
1300
+ /**
1301
+ * A session's lifecycle is its state, PATCHed. Asking for the state it is
1302
+ * already in changes nothing; one it cannot reach from where it is --
1303
+ * pausing a closed session -- is refused.
1304
+ */
1305
+ async _sessionState(marketplaceId, state) {
1306
+ return parseSession(await this._patch(`${this._marketplace(marketplaceId)}/sessions/current`, { state }));
1236
1307
  }
1237
- /** Everyone in the caller's account. `usersJson`, not the HAL `users` form. */
1308
+ /** Everyone in the caller's account. */
1238
1309
  async users() {
1239
- const data = await this._get(uri(this._apiRoot, "usersJson"));
1310
+ const data = await this._get(this._v1("/users"));
1240
1311
  return data.map((u) => parsePerson(u));
1241
1312
  }
1242
- /** The opening positions of one allocation. A V1 route, not on the API root. */
1313
+ /** The opening positions of one allocation. */
1243
1314
  async allotments(marketplaceId, allocationId) {
1244
- const url = `${server(this._endpoint)}/v1/marketplaces/${marketplaceId}` +
1245
- `/allotments?allocation=${allocationId}`;
1315
+ const url = `${this._marketplace(marketplaceId)}/allocations/${allocationId}/allotments`;
1246
1316
  const data = await this._get(url);
1247
1317
  return data.map(parseAllotment);
1248
1318
  }
@@ -1257,7 +1327,7 @@ export class Flexemarkets {
1257
1327
  * computes with; the allotment encoding is applied here.
1258
1328
  */
1259
1329
  async allocate(marketplaceId, holdings) {
1260
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "allocations");
1330
+ const url = `${this._marketplace(marketplaceId)}/allocations`;
1261
1331
  const body = holdings.map((h) => holdingToAllotment(marketplaceId, h));
1262
1332
  const data = await this._post(url, body);
1263
1333
  return allotmentsToHoldings(data.map(parseAllotment));
@@ -1265,32 +1335,23 @@ export class Flexemarkets {
1265
1335
  /**
1266
1336
  * The holdings CSV, verbatim, for the current session or for given ones.
1267
1337
  *
1268
- * The filter is spelled `sessions=` on this route and `sessionIds=` on
1269
- * sessions and connections. Using the wrong one is not an error — it is an
1270
- * unfiltered answer.
1338
+ * The same route as {@link holdings}, asked for `text/csv`: the format is
1339
+ * chosen by the Accept header, not by a `/downloads` segment.
1271
1340
  */
1272
1341
  async downloadHoldings(marketplaceId, sessionIds) {
1273
- if (sessionIds && sessionIds.length > 0) {
1274
- return this._getText(uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "holdings/downloads", `sessions=${sessionIds.join(",")}`));
1275
- }
1276
- return this._getText(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings/downloads"));
1342
+ let url = `${this._marketplace(marketplaceId)}/holdings`;
1343
+ if (sessionIds && sessionIds.length > 0)
1344
+ url += `?sessions=${sessionIds.join(",")}`;
1345
+ return this._getText(url);
1277
1346
  }
1278
1347
  /**
1279
1348
  * Load opening positions from a holdings CSV. Stages the next allocation on
1280
1349
  * the same terms as {@link allocate}.
1281
1350
  */
1282
1351
  async uploadHoldings(marketplaceId, filename) {
1283
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings/uploads");
1284
- const form = new FormData();
1285
- form.append("file", new Blob([readFileSync(filename)]), basename(filename));
1286
- const resp = await fetch(url, {
1287
- method: "POST",
1288
- headers: { ...this._authHeaders(), "User-Agent": FM_NETWORK_CLIENT },
1289
- body: form,
1290
- });
1291
- const body = await resp.text();
1292
- checkResponse(resp, body);
1293
- return allotmentsToHoldings(JSON.parse(body).map(parseAllotment));
1352
+ const url = `${this._marketplace(marketplaceId)}/allocations`;
1353
+ const data = (await this._sendCsv("POST", url, filename));
1354
+ return allotmentsToHoldings(data.map(parseAllotment));
1294
1355
  }
1295
1356
  /**
1296
1357
  * Load per-participant private state from a CSV, returning what was stored.
@@ -1307,17 +1368,9 @@ export class Flexemarkets {
1307
1368
  * resolves to. A study's existing values file needs no change.
1308
1369
  */
1309
1370
  async uploadState(marketplaceId, filename) {
1310
- const url = v1(this._endpoint, `/marketplaces/${marketplaceId}/state/uploads`);
1311
- const form = new FormData();
1312
- form.append("file", new Blob([readFileSync(filename)]), basename(filename));
1313
- const resp = await fetch(url, {
1314
- method: "POST",
1315
- headers: { ...this._authHeaders(), "User-Agent": FM_NETWORK_CLIENT },
1316
- body: form,
1317
- });
1318
- const body = await resp.text();
1319
- checkResponse(resp, body);
1320
- return JSON.parse(body).map(parseParticipantState);
1371
+ const url = `${this._marketplace(marketplaceId)}/state`;
1372
+ const data = (await this._sendCsv("PUT", url, filename));
1373
+ return data.map(parseParticipantState);
1321
1374
  }
1322
1375
  /**
1323
1376
  * Push widgets to participants' screens, returning them as stored.
@@ -1336,7 +1389,7 @@ export class Flexemarkets {
1336
1389
  * that status: back off and push again.
1337
1390
  */
1338
1391
  async pushWidgets(marketplaceId, widgets) {
1339
- const url = v1(this._endpoint, `/marketplaces/${marketplaceId}/widgets`);
1392
+ const url = `${this._marketplace(marketplaceId)}/widgets`;
1340
1393
  const data = await this._post(url, widgets.map(widgetPushJson));
1341
1394
  return data.map(parseWidget);
1342
1395
  }
@@ -1344,18 +1397,17 @@ export class Flexemarkets {
1344
1397
  * Take down a widget: the marketplace's for `key`, or one participant's.
1345
1398
  *
1346
1399
  * True if one was removed, false if there was none to remove. With `userId`,
1347
- * only that participant's widget goes; their marketplace widget for the same
1348
- * key, if any, shows again.
1400
+ * only that participant's widget goes -- `participants/{userId}/widgets/{key}`
1401
+ * -- and their marketplace widget for the same key, if any, shows again.
1349
1402
  *
1350
1403
  * An empty 404 is the server saying nothing was there. A 404 carrying a
1351
1404
  * failure document -- no such marketplace -- still throws, so a robot pointed
1352
1405
  * at the wrong marketplace does not read its clean-up as done.
1353
1406
  */
1354
1407
  async removeWidget(marketplaceId, key, userId) {
1355
- let url = v1(this._endpoint, `/marketplaces/${marketplaceId}/widgets/${encodeURIComponent(key)}`);
1356
- if (userId !== undefined && userId !== null)
1357
- url += `?userId=${userId}`;
1358
- const resp = await fetch(url, {
1408
+ const owner = userId !== undefined && userId !== null ? `/participants/${userId}` : "";
1409
+ const url = `${this._marketplace(marketplaceId)}${owner}/widgets/${encodeURIComponent(key)}`;
1410
+ const resp = await this._fetch(url, {
1359
1411
  method: "DELETE",
1360
1412
  headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
1361
1413
  });
@@ -1370,9 +1422,45 @@ export class Flexemarkets {
1370
1422
  * participant -- what a manager reads to check on a robot.
1371
1423
  */
1372
1424
  async allWidgets(marketplaceId) {
1373
- const data = await this._get(v1(this._endpoint, `/marketplaces/${marketplaceId}/widgets/all`));
1425
+ const data = await this._get(`${this._marketplace(marketplaceId)}/widgets?participant=all`);
1374
1426
  return data.map(parseWidget);
1375
1427
  }
1428
+ /**
1429
+ * Every robot the marketplace's robot host offers, with whether it is
1430
+ * enabled here and how a manager has configured its parameters.
1431
+ *
1432
+ * Readable by participants as well as managers: it is what a launch form is
1433
+ * built from. Asks the robot host for its catalogue, so it fails when the
1434
+ * host cannot be reached.
1435
+ */
1436
+ async marketplaceRobots(marketplaceId) {
1437
+ const data = await this._get(`${this._marketplace(marketplaceId)}/robots`);
1438
+ return data.map(parseMarketplaceRobot);
1439
+ }
1440
+ /**
1441
+ * Set a robot parameter's value in a marketplace, and whether participants
1442
+ * may move it, returning the configuration as stored.
1443
+ *
1444
+ * A null `control` fixes the value: participants launching the robot see it
1445
+ * read-only. A control exposes it within that range, starting at `value`,
1446
+ * which must lie inside it. The server refuses a parameter the robot does
1447
+ * not declare, a platform parameter, and a range outside the robot's own
1448
+ * bounds.
1449
+ *
1450
+ * The control goes up flat beside the value, and a fixed parameter sends the
1451
+ * value alone: the server reads any bound as a control.
1452
+ */
1453
+ async configureRobotParameter(marketplaceId, robotId, paramName, value, control) {
1454
+ const body = { value };
1455
+ if (control !== null) {
1456
+ body.min = control.min;
1457
+ body.max = control.max;
1458
+ body.step = control.step;
1459
+ }
1460
+ const url = `${this._marketplace(marketplaceId)}/robots/${encodeURIComponent(robotId)}`
1461
+ + `/parameters/${encodeURIComponent(paramName)}`;
1462
+ return parseRobotParameterConfig(await this._put(url, body));
1463
+ }
1376
1464
  // -- events / WebSocket ----------------------------------------------------
1377
1465
  _sharedViews = new Map();
1378
1466
  _sharedViewPromises = new Map();
@@ -1387,12 +1475,19 @@ export class Flexemarkets {
1387
1475
  * callers with different identities each get their own desk —
1388
1476
  * multi-tenant WS multiplexing is a server-side concern, not a
1389
1477
  * client-side one.
1478
+ *
1479
+ * `submitLimit` on the returned handle rejects, without sending, an order
1480
+ * the desk knows fm-server would refuse -- a session that is not open, a
1481
+ * side the holding does not grant -- with {@link OrderRefusedLocallyError}.
1482
+ * `{ refuseLocally: false }` sends every order and leaves the answer to the
1483
+ * server.
1390
1484
  */
1391
- async desk(marketplaceId) {
1485
+ async desk(marketplaceId, options = {}) {
1486
+ const refuseLocally = options.refuseLocally ?? true;
1392
1487
  const existing = this._sharedViews.get(marketplaceId);
1393
1488
  if (existing !== undefined) {
1394
1489
  existing.refCount++;
1395
- return new DeskHandle(existing.desk, () => this._releaseSharedView(marketplaceId));
1490
+ return new DeskHandle(existing.desk, () => this._releaseSharedView(marketplaceId), refuseLocally);
1396
1491
  }
1397
1492
  // Two concurrent desk() calls for the same marketplaceId need
1398
1493
  // to dedupe — JS is single-threaded but awaits introduce
@@ -1419,10 +1514,10 @@ export class Flexemarkets {
1419
1514
  if (registered.desk !== shared)
1420
1515
  shared.close();
1421
1516
  registered.refCount++;
1422
- return new DeskHandle(registered.desk, () => this._releaseSharedView(marketplaceId));
1517
+ return new DeskHandle(registered.desk, () => this._releaseSharedView(marketplaceId), refuseLocally);
1423
1518
  }
1424
1519
  this._sharedViews.set(marketplaceId, { desk: shared, refCount: 1 });
1425
- return new DeskHandle(shared, () => this._releaseSharedView(marketplaceId));
1520
+ return new DeskHandle(shared, () => this._releaseSharedView(marketplaceId), refuseLocally);
1426
1521
  }
1427
1522
  _releaseSharedView(marketplaceId) {
1428
1523
  const entry = this._sharedViews.get(marketplaceId);
@@ -1435,7 +1530,18 @@ export class Flexemarkets {
1435
1530
  }
1436
1531
  /** Start receiving real-time events via WebSocket STOMP. */
1437
1532
  async listen(marketplaceId, callback) {
1438
- this._eventListener = await this._connectEvents(marketplaceId, callback);
1533
+ // The stream this replaces is closed, not dropped with its socket,
1534
+ // heartbeats and reconnects still running.
1535
+ const previous = this._eventListener;
1536
+ this._eventListener = null;
1537
+ if (previous !== null)
1538
+ previous.close();
1539
+ const listener = await this._connectEvents(marketplaceId, callback);
1540
+ // Another listen() may have finished while this one connected.
1541
+ const raced = this._eventListener;
1542
+ if (raced !== null)
1543
+ raced.close();
1544
+ this._eventListener = listener;
1439
1545
  }
1440
1546
  /**
1441
1547
  * Open an *independent* event subscription, delivering to `callback` until
@@ -1468,7 +1574,7 @@ export class Flexemarkets {
1468
1574
  const wsUrl = server(this._endpoint)
1469
1575
  .replace("https://", "wss://")
1470
1576
  .replace("http://", "ws://") + "/events";
1471
- const events = new EventListener(wsUrl, this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder);
1577
+ const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented));
1472
1578
  await events.start();
1473
1579
  return events;
1474
1580
  }
@@ -1511,8 +1617,9 @@ async function signIn(baseUrl, config, clientDescription) {
1511
1617
  // dropped it, and the Java SDK restored it with a test. This SDK and the
1512
1618
  // Python one never had it, so token auth returned 400 in both from the day
1513
1619
  // it was written.
1620
+ // POST, as minting a token is (fm-server 4.6).
1514
1621
  const resp = await fetch(`${baseUrl}/tokens/refresh`, {
1515
- method: "GET",
1622
+ method: "POST",
1516
1623
  headers: {
1517
1624
  Authorization: `Bearer ${tok}`,
1518
1625
  Accept: "application/json",
@@ -1521,7 +1628,7 @@ async function signIn(baseUrl, config, clientDescription) {
1521
1628
  });
1522
1629
  const body = await resp.text();
1523
1630
  checkResponse(resp, body);
1524
- return parseToken(JSON.parse(body));
1631
+ return parseToken(readBody(body));
1525
1632
  }
1526
1633
  const acct = config.account ?? "";
1527
1634
  const email = config.email ?? "";
@@ -1547,6 +1654,6 @@ async function signIn(baseUrl, config, clientDescription) {
1547
1654
  });
1548
1655
  const body = await resp.text();
1549
1656
  checkResponse(resp, body);
1550
- return parseToken(JSON.parse(body));
1657
+ return parseToken(readBody(body));
1551
1658
  }
1552
1659
  //# sourceMappingURL=client.js.map