@polyester/sdk 0.35.0-devnet-20261110181538 → 0.35.0-devnet-20261110194522

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +11 -1
  2. package/README.md +8 -8
  3. package/dist/realtime/client.js +13 -6
  4. package/dist/realtime/client.js.map +1 -1
  5. package/dist/services/address-book/address-book.schemas.d.ts +2 -2
  6. package/dist/services/balances/balances.schemas.d.ts +3 -3
  7. package/dist/services/candles/candles.schemas.d.ts +10 -10
  8. package/dist/services/changelog/changelog.schemas.d.ts +17 -17
  9. package/dist/services/heatmap/heatmap.schemas.d.ts +13 -13
  10. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +3 -3
  11. package/dist/services/lifecycle/lifecycle.schemas.d.ts +145 -145
  12. package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
  13. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  14. package/dist/services/orders/orders-batch.schemas.d.ts +14 -14
  15. package/dist/services/orders/orders-batch.schemas.d.ts.map +1 -1
  16. package/dist/services/orders/orders-batch.schemas.js +2 -29
  17. package/dist/services/orders/orders-batch.schemas.js.map +1 -1
  18. package/dist/services/orders/orders-input.schemas.d.ts +2 -2
  19. package/dist/services/orders/orders-input.schemas.js +1 -1
  20. package/dist/services/orders/orders-input.schemas.js.map +1 -1
  21. package/dist/services/orders/orders-modify.schemas.js +1 -1
  22. package/dist/services/orders/orders-modify.schemas.js.map +1 -1
  23. package/dist/services/orders/orders-output.schemas.d.ts +14 -14
  24. package/dist/services/rewards/rewards.schemas.d.ts +3 -3
  25. package/dist/services/subaccounts/subaccounts.schemas.d.ts +15 -15
  26. package/dist/services/trades/trades.schemas.d.ts +1 -1
  27. package/dist/services/transfers/transfers.schemas.d.ts +2 -2
  28. package/dist/services/transfers/transfers.schemas.js +1 -1
  29. package/dist/services/transfers/transfers.schemas.js.map +1 -1
  30. package/dist/services/triggers/trigger-input.schemas.d.ts +16 -11
  31. package/dist/services/triggers/trigger-input.schemas.d.ts.map +1 -1
  32. package/dist/services/triggers/trigger-input.schemas.js +26 -9
  33. package/dist/services/triggers/trigger-input.schemas.js.map +1 -1
  34. package/dist/services/triggers/triggers-output.schemas.d.ts +10 -10
  35. package/dist/services/vip/vip.schemas.d.ts +3 -3
  36. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @polyester/sdk
2
2
 
3
- ## 0.35.0-devnet-20261110181538
3
+ ## 0.35.0-devnet-20261110194522
4
4
 
5
5
  ### Minor Changes
6
6
 
@@ -18,6 +18,8 @@
18
18
 
19
19
  - The `orders.batchCreate` JSDoc now gives the batch's 15-minute idempotency window. It previously said 60 seconds, which is the `batchReplace` window. Within 15 minutes, a retry with the same `requestId` and payload returns each decided item's original result and retries the unresolved ones. After that the ID is free, and a repeat can place its orders again. ([#235](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/235))
20
20
 
21
+ - `orders.batchReplace` now accepts a `newPrice` or `newQty` change together with `clearRisk: true` in the same item, matching `orders.modify`. Previously the SDK rejected the combination before sending it. ([#243](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/243))
22
+
21
23
  - The `orders.getBatchReplaceStatus` JSDoc now gives the 60-second status window. The status is readable as soon as `batchReplace` returns. Retry a `ServiceUnavailableError` with the same request within the window. A `ResourceNotFoundError` never means the replacement was rejected: reconcile the individual orders and never resubmit an accepted batch. An item's `updatedTsNs` can be a later recovery time, so it does not identify a refusal. ([#236](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/236))
22
24
 
23
25
  - Changelog post summaries add `revision` and `updatedAt`. A post can now be republished to correct its copy or withdraw a change: `revision` starts at 1 and increases with each republication, and `updatedAt` is when the current revision was published. To follow edits, read a post again when its `revision` changes. `listChanges` restarts paging at the first change of a post republished during the walk, so deduplicate changes by `id`. ([#236](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/236))
@@ -34,12 +36,16 @@
34
36
 
35
37
  - `lifecycle.listFlows` with an `accountSelector` now also returns the transfers the account received from other accounts, such as transfers from other users or subaccounts and reward payouts. Each row carries `participation`: `"owner"` for a flow the account owns, including a transfer it sent, and `"recipient"` for a received transfer. Rows are `"unspecified"` without an account selector and in flow detail and realtime updates. Pass `participation: "owner"` to keep the previous owner-only list or `"recipient"` for received transfers only. `participation` requires `accountSelector` and throws `ValidationError` without one. A `pageToken` now resumes only the request it came from, so change nothing but `limit` between pages. ([#237](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/237))
36
38
 
39
+ - `orders.listOpen()`, `orders.listHistory()` and `transfers.list()` reject a `limit` that isn't an integer from 1 to 1000 with a `ValidationError`. A negative or fractional limit previously failed while encoding a binary request and surfaced as `InternalServerError`. ([#242](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/242))
40
+
37
41
  - `auth.login()` and `auth.refreshSession()` results now carry `session`, the issued token's assurance details (`sessionId`, `sessionLevel`, `authenticationMethods`, `authTimeMs`) in the same shape as `auth.me().session`. The wallet login response sent them, but the SDK dropped them. `session` is `undefined` when the response omits it. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
38
42
 
39
43
  - `auth.me()` now returns `rootSmartAccountAddress`, the caller's root smart-account address as lowercase `0x` hex, or `""` when the account has none. It was previously dropped. A new account can read `""` for a moment right after its first login, until the backend records the address. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
40
44
 
41
45
  - A ConnectRPC `resource_exhausted` that carries a `RateLimitDetail`, as wallet sign-in and the public catalog calls now send, maps to a `RateLimitError` with `rateLimit` set and `retryAfterMs` taken from the detail. Its `detail` is `{ service: "rate_limit", code: "RATE_LIMIT_EXCEEDED", rateLimit }`. The gateway's own refusal has no detail: `retryAfterMs` comes from `Retry-After` when present and is `undefined` for a concurrency refusal, so back off without a server hint. ([#236](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/236))
42
46
 
47
+ - Unsubscribing from a private channel, or from `connectPrivateOrders()`, in the same tick as subscribing without credentials no longer delivers the queued missing-authentication error to that consumer's `onError`. ([#242](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/242))
48
+
43
49
  - Realtime token requests (`/v1/rt/token` and `/v1/rt/subscribe`) now go through the `fetch` passed to `PolyesterClient`, like every other SDK request. They used the global `fetch` before, so proxies, mocks and request logging never saw them. `RealtimeClient` takes the same optional `fetch`. Without one, both keep using the global `fetch`. ([#238](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/238))
44
50
 
45
51
  - Realtime token requests honor `Retry-After`. When the connection or subscription token endpoint answers 429 with a `Retry-After` header, the `RateLimitError` carries it as `retryAfterMs`, and the realtime client sends no further token request until it has passed (at most 60 seconds), even when the socket retries sooner. This covers public, private and private order stream sockets. ([#232](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/232))
@@ -58,6 +64,10 @@
58
64
 
59
65
  - `tradeWsPb` in `@polyester/sdk/unstable/gen` adds the `cancelAllAfter` client command and acknowledgement, which arm, refresh or disarm the account's dead-man switch, plus the `ClientFrame` fields `timestampMs` and `recvWindowMs`, which set a per-command receive window. The SDK has no trading WebSocket client yet. ([#237](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/237))
60
66
 
67
+ - `triggers.create()` validation errors name the field missing from the trigger type you chose, e.g. `durationMs` for a TWAP or `triggerPrice` for a take-profit. They previously said `triggerType: Expected "stop_loss"` for every type except stop-loss. An unknown `triggerType` now says which values are allowed. ([#242](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/242))
68
+
69
+ - `triggers.modify()` accepts `maxSlippage: { kind: "bps", bps: 10000 }`, which a buy stop-loss or take-profit with a market child allows. It previously rejected anything above 9999 locally. The server still rejects 10000 for a sell stop-loss or take-profit and for trailing stops, with `ERROR_CODE_MAX_SLIPPAGE_INVALID`. ([#242](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/242))
70
+
61
71
  - `triggers.fromProto(trigger)` converts a `triggers.v1.Trigger` message received from another API into the same `Trigger` record that `triggers.get`, `list`, and `subscribe` return, with quantities and prices scaled by the client's catalog. It waits for the catalog and throws when the trigger's market isn't in it. ([#239](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/239))
62
72
 
63
73
  - A wallet login refused with `AUTH_WALLET_ALREADY_LINKED` maps to a non-retryable `AlreadyExistsError`. The wallet already belongs to another account, so the same login fails again. Log in with the account address the wallet already uses. ([#236](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/236))
package/README.md CHANGED
@@ -23,11 +23,11 @@ derives the smart account address, and the owner EOA signs the login challenge.
23
23
  Nothing gets deployed just to log in.
24
24
 
25
25
  ```ts
26
- import { PolyesterBrowserClient, POLYESTER_DEVNET_ENVIRONMENT } from "@polyester/sdk";
26
+ import { PolyesterBrowserClient, POLYESTER_TESTNET_ENVIRONMENT } from "@polyester/sdk";
27
27
  import type { AccountSigner } from "@polyester/sdk";
28
28
  import { createPolyesterAccountSigner } from "@polyester/sdk/account-signer";
29
29
 
30
- const environment = POLYESTER_DEVNET_ENVIRONMENT;
30
+ const environment = POLYESTER_TESTNET_ENVIRONMENT;
31
31
  const { accountAddress } = createPolyesterAccountSigner({ environment, owner });
32
32
 
33
33
  const accountSigner: AccountSigner = {
@@ -57,12 +57,12 @@ incoming request. Useful for SSR loaders and route handlers.
57
57
  ```ts
58
58
  import {
59
59
  createPolyesterServerClientFromRequest,
60
- POLYESTER_DEVNET_ENVIRONMENT,
60
+ POLYESTER_TESTNET_ENVIRONMENT,
61
61
  } from "@polyester/sdk";
62
62
 
63
63
  const client = createPolyesterServerClientFromRequest({
64
64
  request,
65
- environment: POLYESTER_DEVNET_ENVIRONMENT,
65
+ environment: POLYESTER_TESTNET_ENVIRONMENT,
66
66
  });
67
67
 
68
68
  if (client.hasUsableBearerToken) {
@@ -77,12 +77,12 @@ passing the store. For example, with current Next.js versions:
77
77
  import { cookies } from "next/headers";
78
78
  import {
79
79
  createPolyesterServerClientFromCookies,
80
- POLYESTER_DEVNET_ENVIRONMENT,
80
+ POLYESTER_TESTNET_ENVIRONMENT,
81
81
  } from "@polyester/sdk";
82
82
 
83
83
  const client = createPolyesterServerClientFromCookies({
84
84
  cookies: await cookies(),
85
- environment: POLYESTER_DEVNET_ENVIRONMENT,
85
+ environment: POLYESTER_TESTNET_ENVIRONMENT,
86
86
  });
87
87
  ```
88
88
 
@@ -99,10 +99,10 @@ For machine clients, pass an Ed25519 API key provider instead of a cookie
99
99
  session:
100
100
 
101
101
  ```ts
102
- import { PolyesterClient, POLYESTER_DEVNET_ENVIRONMENT } from "@polyester/sdk";
102
+ import { PolyesterClient, POLYESTER_TESTNET_ENVIRONMENT } from "@polyester/sdk";
103
103
 
104
104
  const client = new PolyesterClient({
105
- environment: POLYESTER_DEVNET_ENVIRONMENT,
105
+ environment: POLYESTER_TESTNET_ENVIRONMENT,
106
106
  auth: {
107
107
  kind: "api-key-ed25519",
108
108
  getKeyId: () => process.env.POLYESTER_API_KEY_ID ?? null,
@@ -458,6 +458,17 @@ var RealtimeClient = class {
458
458
  privateClient?.disconnect();
459
459
  } catch {}
460
460
  }
461
+ /** Reports a missing-auth error on the next microtask unless the caller unsubscribes first. */
462
+ #reportAuthErrorLater(channel, error, onError) {
463
+ let closed = false;
464
+ const ctx = createSdkSubscriptionErrorContext(channel, "auth", error);
465
+ queueMicrotask(() => {
466
+ if (!closed) this.#callErrorHandler(onError, ctx);
467
+ });
468
+ return () => {
469
+ closed = true;
470
+ };
471
+ }
461
472
  /**
462
473
  * Subscribes to a realtime channel and returns an unsubscribe function. Missing
463
474
  * authentication is reported to `onError`, or thrown synchronously when no error
@@ -471,9 +482,7 @@ var RealtimeClient = class {
471
482
  } catch (error) {
472
483
  if (!(error instanceof AuthenticationError)) throw error;
473
484
  if (!handlers.onError) throw error;
474
- const ctx = createSdkSubscriptionErrorContext(channel, "auth", error);
475
- queueMicrotask(() => this.#callErrorHandler(handlers.onError, ctx));
476
- return () => {};
485
+ return this.#reportAuthErrorLater(channel, error, handlers.onError);
477
486
  }
478
487
  shared.consumers++;
479
488
  const publicationHandler = handlers.onPublication;
@@ -600,9 +609,7 @@ var RealtimeClient = class {
600
609
  if (!this.#hasAuth()) {
601
610
  const error = new AuthenticationError(`Cannot subscribe to private channel "${channel}" without authentication`);
602
611
  if (!params.onError) throw error;
603
- const ctx = createSdkSubscriptionErrorContext(channel, "auth", error);
604
- queueMicrotask(() => this.#callErrorHandler(params.onError, ctx));
605
- return () => {};
612
+ return this.#reportAuthErrorLater(channel, error, params.onError);
606
613
  }
607
614
  if (this.#privateOrders) return this.#privateOrders.connect(params);
608
615
  const loading = this.#privateOrdersLoading ??= import("./private-orders.js").then(({ PrivateOrderStream }) => this.#privateOrders = new PrivateOrderStream({
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["#config","#fetch","#getAuthHeaders","#fetchToken","#tokenRetryAt","#emitErrors","#sharedSubs","#channelKind","#fetchSubscriptionToken","#emitSubscriptionError","#publicClient","#watchClient","#privateClient","#emitConnectionTokenError","#privateTokenFailure","#connection","#connectionListeners","#setConnection","#currentClient","#transportErrors","#terminateSubscriptions","#pendingTeardowns","#createPublicClient","#hasAuth","#createPrivateClient","#ensurePublicClient","#assertChannelAuth","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#attachSubscription","#callErrorHandler","#teardownSubscription","#dropConsumers","#disconnectClientIfIdle","#hasChannelsForKind","#privateOrdersEpoch","#privateOrders","#disconnectPrivateOrders","#disconnectCentrifuge","#getOrCreateSubscription","#callConsumerHandler","#privateOrdersLoading","#disconnect","#disconnectPrivate"],"sources":["../../src/realtime/client.ts"],"sourcesContent":["import { fromBinary, type DescMessage, type MessageShape } from \"@bufbuild/protobuf\";\nimport type {\n Centrifuge,\n ErrorContext,\n SubscriptionErrorContext,\n PublicationContext,\n Subscription,\n} from \"centrifuge/build/protobuf\";\nimport type * as CentrifugeModule from \"centrifuge/build/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n fromCentrifugeSubscriptionError,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport {\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n PolyesterError,\n RealtimeError,\n} from \"../shared/errors.js\";\nimport { parseRetryAfterHeader } from \"../shared/connect-error-mapping.js\";\nimport { makeFetch } from \"../shared/transports.js\";\nimport { decodeProtoFrame } from \"../utils/streams.js\";\nimport { idToBigInt } from \"../utils/base58-id.js\";\nimport type {\n ConnectChannelParams,\n PolyesterRealtime,\n RealtimeConnection,\n RealtimeConnectionStatus,\n SubscribeHandlers,\n} from \"./types.js\";\nimport type { ConnectPrivateOrdersParams, PrivateOrderStream } from \"./private-orders.js\";\n\n// ponytail: caps a bogus or huge Retry-After; a longer server window just answers 429 again with a new hint.\nconst MAX_RETRY_AFTER_MS = 60_000;\n\ntype CentrifugeCtor = typeof CentrifugeModule.Centrifuge;\ntype CentrifugeModuleLoader = () => Promise<typeof CentrifugeModule>;\n\nconst defaultCentrifugeModuleLoader: CentrifugeModuleLoader = () =>\n import(\"centrifuge/build/protobuf\");\n\n// Centrifuge's protobuf build embeds the protobuf.js runtime (~300 KB minified).\n// Loading it lazily keeps it out of the eager module graph on both the server\n// (Cloudflare isolate cold start — SSR never opens a websocket) and the client\n// app shell; it is only fetched when the first subscription attaches.\nlet centrifugeCtorPromise: Promise<CentrifugeCtor> | null = null;\nlet loadedCentrifugeCtor: CentrifugeCtor | null = null;\nlet centrifugeModuleLoader = defaultCentrifugeModuleLoader;\nexport function __setRealtimeCentrifugeForTests(Centrifuge: CentrifugeCtor | null): void {\n loadedCentrifugeCtor = Centrifuge;\n centrifugeCtorPromise = Centrifuge ? Promise.resolve(Centrifuge) : null;\n}\n\n/** Replaces the lazy Centrifuge module loader for isolated transport-load tests. */\nexport function __setRealtimeCentrifugeLoaderForTests(loader: CentrifugeModuleLoader | null): void {\n centrifugeModuleLoader = loader ?? defaultCentrifugeModuleLoader;\n loadedCentrifugeCtor = null;\n centrifugeCtorPromise = null;\n}\n\nfunction loadCentrifuge(): Promise<CentrifugeCtor> {\n if (\n centrifugeModuleLoader === defaultCentrifugeModuleLoader &&\n (import.meta as { env?: { SSR?: boolean } }).env?.SSR\n ) {\n return Promise.reject(new Error(\"Realtime subscriptions are browser-only during SSR.\"));\n }\n\n if (!centrifugeCtorPromise) {\n const loadAttempt = Promise.resolve().then(centrifugeModuleLoader);\n const retryableLoad = loadAttempt.then(\n (mod) => {\n loadedCentrifugeCtor = mod.Centrifuge;\n return mod.Centrifuge;\n },\n (error) => {\n if (centrifugeCtorPromise === retryableLoad) centrifugeCtorPromise = null;\n throw error;\n },\n );\n centrifugeCtorPromise = retryableLoad;\n }\n return centrifugeCtorPromise;\n}\n\nexport interface RealtimeAuthRequest {\n url: string | URL;\n method: string;\n}\n\nexport interface RealtimeConfig {\n wsUrl: string;\n tokenEndpoint: string;\n subscribeEndpoint: string;\n /** Private WebSocket endpoint for account order streams (`/v1/ws/private`). */\n privateWsUrl: string;\n getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth?: () => boolean;\n /**\n * Custom fetch implementation for realtime token requests. Defaults to the\n * global `fetch`, resolved on each request.\n */\n fetch?: typeof fetch;\n}\n\ntype ResolvedRealtimeConfig = Pick<\n RealtimeConfig,\n \"wsUrl\" | \"tokenEndpoint\" | \"subscribeEndpoint\" | \"privateWsUrl\"\n> & {\n getAuthHeaders: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth: () => boolean;\n};\n\nexport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\ntype PublicationHandler<T = unknown> = (data: T) => void;\ntype ErrorHandler = (ctx: SdkSubscriptionErrorContext) => void;\ntype RealtimeClientKind = \"public\" | \"private\";\n\nconst DISCONNECTED: RealtimeConnectionStatus = { state: \"disconnected\", error: null };\n/** Centrifuge client `error` types that mean a connect attempt failed; each retry emits one. */\nconst CONNECT_FAILURE_TYPES = new Set([\"transport\", \"connect\", \"connectToken\", \"connectData\"]);\n\ninterface SharedSubscription {\n channel: string;\n sub: Subscription | null;\n client: Centrifuge | null;\n attachmentEpoch: number;\n consumers: number;\n subscriptionEpoch: number;\n publicationHandlers: Set<PublicationHandler>;\n subscribedHandlers: Set<(epoch: number) => void>;\n unsubscribedHandlers: Set<() => void>;\n errorHandlers: Set<ErrorHandler>;\n}\n\n/**\n * Shared Centrifuge realtime client that multiplexes public and private protobuf subscriptions across SDK services.\n */\nexport class RealtimeClient implements PolyesterRealtime {\n #publicClient: Centrifuge | null = null;\n #privateClient: Centrifuge | null = null;\n #sharedSubs = new Map<string, SharedSubscription>();\n #pendingTeardowns = new Map<string, SharedSubscription>();\n // Loaded on first use: the stream's protobuf graph (orders included) stays out of the app shell.\n #privateOrdersLoading: Promise<PrivateOrderStream> | null = null;\n #privateOrders: PrivateOrderStream | null = null;\n #privateOrdersEpoch = 0;\n #connection: RealtimeConnection = { public: DISCONNECTED, private: DISCONNECTED };\n #connectionListeners = new Set<(connection: RealtimeConnection) => void>();\n /** Outage errors already sent to channels as `\"transport\"`; replayed to late subscribers. */\n #transportErrors = new WeakSet<Error>();\n /** The non-retryable connection token failure that stops the private socket (code 1). */\n #privateTokenFailure: Error | null = null;\n /** Token requests wait until then after a 429 with `Retry-After`. */\n #tokenRetryAt = 0;\n readonly #config: ResolvedRealtimeConfig;\n readonly #fetch: typeof fetch;\n\n constructor(config: RealtimeConfig) {\n this.#fetch = makeFetch(config.fetch);\n this.#config = {\n wsUrl: config.wsUrl,\n tokenEndpoint: config.tokenEndpoint,\n subscribeEndpoint: config.subscribeEndpoint,\n privateWsUrl: config.privateWsUrl,\n getAuthHeaders: config.getAuthHeaders ?? (() => ({})),\n hasAuth: config.hasAuth ?? (() => false),\n };\n }\n\n async #getAuthHeaders(request: RealtimeAuthRequest): Promise<HeadersInit> {\n return this.#config.getAuthHeaders(request);\n }\n\n /**\n * Every realtime token request (connection, subscription, private order stream)\n * comes through here, so one wait honors `Retry-After` for all of them; the\n * transport's own reconnect backoff still applies on top.\n */\n async #fetchToken(url: string | URL, kind: \"connection\" | \"subscription\"): Promise<string> {\n // Recheck after each await: another request's 429 may have pushed the deadline out.\n let headers: HeadersInit;\n do {\n for (let wait; (wait = this.#tokenRetryAt - Date.now()) > 0;) {\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n headers = await this.#getAuthHeaders({ url, method: \"GET\" });\n } while (this.#tokenRetryAt > Date.now());\n const res = await this.#fetch(url, { headers });\n if (!res.ok) {\n const retryAfterMs = parseRetryAfterHeader(res.headers.get(\"retry-after\"));\n if (res.status === 429 && retryAfterMs !== undefined) {\n this.#tokenRetryAt = Math.max(\n this.#tokenRetryAt,\n Date.now() + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS),\n );\n }\n throw errorFromHttpStatus(res.status, `Failed to fetch ${kind} token: ${res.status}`, {\n status: res.status,\n retryAfterMs,\n });\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\n `${kind === \"connection\" ? \"Connection\" : \"Subscription\"} token response had no token`,\n );\n }\n return json.token;\n }\n\n #fetchSubscriptionToken(channel: string): Promise<string> {\n const url = new URL(this.#config.subscribeEndpoint);\n url.searchParams.set(\"channel\", channel);\n return this.#fetchToken(url, \"subscription\");\n }\n\n /**\n * Delivers to the consumers registered when it starts: one a handler adds (a resubscribe)\n * is not part of it, and one a handler removes is skipped.\n */\n #emitErrors(recipients: SharedSubscription[], type: string, error: unknown): void {\n const deliveries = recipients.map((shared) => ({\n shared,\n ctx: createSdkSubscriptionErrorContext(shared.channel, type, error),\n handlers: Array.from(shared.errorHandlers),\n }));\n for (const { shared, ctx, handlers } of deliveries) {\n for (const handler of handlers) {\n if (shared.errorHandlers.has(handler)) handler(ctx);\n }\n }\n }\n\n #emitSubscriptionError(shared: SharedSubscription, type: string, error: unknown): void {\n this.#emitErrors([shared], type, error);\n }\n\n #emitConnectionTokenError(error: unknown): void {\n const privateSubs = [...this.#sharedSubs.values()].filter(\n (shared) => this.#channelKind(shared.channel) === \"private\",\n );\n this.#emitErrors(privateSubs, \"connection_token\", error);\n }\n\n #subscriptionOpts(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ) {\n if (this.#channelKind(shared.channel) !== \"private\") return undefined;\n return {\n getToken: async () => {\n try {\n return await this.#fetchSubscriptionToken(shared.channel);\n } catch (error) {\n if (shared.attachmentEpoch === attachmentEpoch) {\n this.#emitSubscriptionError(shared, \"subscription_token\", error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n }\n\n #hasAuth(): boolean {\n return this.#config.hasAuth();\n }\n\n #channelKind(channel: string): RealtimeClientKind {\n return channel.startsWith(\"private:\") ? \"private\" : \"public\";\n }\n\n #createPublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n const client = new Centrifuge(this.#config.wsUrl);\n this.#publicClient = client;\n this.#watchClient(client, \"public\");\n client.connect();\n return client;\n }\n\n #createPrivateClient(Centrifuge: CentrifugeCtor): Centrifuge {\n let client: Centrifuge;\n const opts = {\n getToken: async () => {\n try {\n return await this.#fetchToken(this.#config.tokenEndpoint, \"connection\");\n } catch (error) {\n if (this.#privateClient === client) {\n this.#emitConnectionTokenError(error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n if (this.#privateClient === client) this.#privateTokenFailure = error;\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n\n client = new Centrifuge(this.#config.wsUrl, opts);\n this.#privateClient = client;\n this.#privateTokenFailure = null;\n this.#watchClient(client, \"private\");\n client.connect();\n return client;\n }\n\n #currentClient(kind: RealtimeClientKind): Centrifuge | null {\n return kind === \"private\" ? this.#privateClient : this.#publicClient;\n }\n\n #setConnection(kind: RealtimeClientKind, status: RealtimeConnectionStatus): void {\n const current = this.#connection[kind];\n if (current.state === status.state && current.error === status.error) return;\n this.#connection = { ...this.#connection, [kind]: status };\n const connection = this.#connection;\n // Notify once Centrifuge has finished its transition, so a listener can disconnect or\n // subscribe safely. A newer status replaces this one, even mid-delivery.\n // Snapshot: a listener added during delivery (one replacing itself) waits for the next change.\n queueMicrotask(() => {\n for (const listener of Array.from(this.#connectionListeners)) {\n if (this.#connection !== connection) return;\n if (!this.#connectionListeners.has(listener)) continue;\n try {\n listener(connection);\n } catch {\n // Keep one listener from starving the others.\n }\n }\n });\n }\n\n #watchClient(client: Centrifuge, kind: RealtimeClientKind): void {\n this.#setConnection(kind, { state: \"connecting\", error: null });\n\n client.on(\"state\", ({ newState, oldState }) => {\n // `disconnected` is recorded by the handlers below, which know the reason.\n if (this.#currentClient(kind) !== client || newState === \"disconnected\") return;\n // A restart after a terminal close starts a new outage.\n const { error } = this.#connection[kind];\n this.#setConnection(kind, {\n state: newState,\n error: newState === \"connected\" || oldState === \"disconnected\" ? null : error,\n });\n });\n\n // Centrifuge stays in \"connecting\" across failed attempts, so the `connecting`\n // event fires once; each failed attempt arrives as a client `error` instead.\n client.on(\"error\", (ctx: ErrorContext) => {\n if (this.#currentClient(kind) !== client || !CONNECT_FAILURE_TYPES.has(ctx.type))\n return;\n const { code, message } = ctx.error as { code?: unknown; message?: unknown };\n // 109: the cached token expired; Centrifuge fetches a new one and reconnects.\n if (ctx.type === \"connect\" && code === 109) return;\n // Report the first failure of an outage only, not every reconnect retry. A token\n // failure only marks the status (private channels get \"connection_token\" from\n // getToken), so a socket failure after one is still sent to channels.\n const current = this.#connection[kind].error;\n if (current && (ctx.type === \"connectToken\" || this.#transportErrors.has(current)))\n return;\n const error = new RealtimeError(\n `Realtime ${kind} connection failed: ${typeof message === \"string\" && message ? message : ctx.type}`,\n { realtimeCode: typeof code === \"number\" ? code : 0, retryable: true },\n );\n this.#setConnection(kind, { state: \"connecting\", error });\n // Private channels already receive connection token failures as \"connection_token\".\n if (ctx.type === \"connectToken\") return;\n this.#transportErrors.add(error);\n // A consumer added by a handler gets the replay in subscribe() instead.\n const affected = [...this.#sharedSubs.values()].filter(\n (shared) => shared.client === client,\n );\n this.#emitErrors(affected, \"transport\", error);\n });\n\n client.on(\"disconnected\", (ctx) => {\n // Code 0 (disconnectCalled) comes from our own teardown, which drops the client first.\n if (this.#currentClient(kind) !== client || ctx.code === 0) return;\n // Centrifuge reports a rejected private token as \"unauthorized\"; record the real failure.\n const tokenFailure =\n kind === \"private\" && ctx.code === 1 ? this.#privateTokenFailure : null;\n if (kind === \"private\") this.#privateTokenFailure = null;\n this.#setConnection(kind, {\n state: \"disconnected\",\n error:\n tokenFailure ??\n new RealtimeError(ctx.reason || \"Realtime connection closed\", {\n realtimeCode: ctx.code,\n }),\n });\n // Code 1 (unauthorized) on the private socket: channels already got the token\n // error, and an explicit subscribe() restarts this client, so keep it. The public\n // socket has no token to fix, so there it is terminal like any other close.\n if (ctx.code === 1 && kind === \"private\") return;\n if (kind === \"private\") this.#privateClient = null;\n else this.#publicClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #assertChannelAuth(channel: string): void {\n if (this.#channelKind(channel) === \"private\" && !this.#hasAuth()) {\n throw new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n }\n }\n\n #ensureClientForChannel(Centrifuge: CentrifugeCtor, channel: string): Centrifuge {\n if (this.#channelKind(channel) === \"private\") {\n return this.#privateClient ?? this.#createPrivateClient(Centrifuge);\n }\n\n return this.#ensurePublicClient(Centrifuge);\n }\n\n #attachSubscription(shared: SharedSubscription): void {\n if (shared.sub) return;\n\n // Auth failures must surface synchronously to subscribe() callers, as\n // they did when centrifuge was imported statically.\n this.#assertChannelAuth(shared.channel);\n\n const attachmentEpoch = shared.attachmentEpoch + 1;\n shared.attachmentEpoch = attachmentEpoch;\n\n // Once the transport module is loaded, attachment stays fully\n // synchronous — only the very first attach pays the dynamic import.\n if (loadedCentrifugeCtor) {\n this.#attachSubscriptionNow(loadedCentrifugeCtor, shared, attachmentEpoch);\n return;\n }\n void this.#attachSubscriptionWhenLoaded(shared, attachmentEpoch);\n }\n\n async #attachSubscriptionWhenLoaded(\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): Promise<void> {\n let Centrifuge: CentrifugeCtor;\n try {\n Centrifuge = await loadCentrifuge();\n } catch (error) {\n if (shared.attachmentEpoch !== attachmentEpoch) return;\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n this.#emitSubscriptionError(shared, \"transport_load\", error);\n return;\n }\n\n // The subscription may have been torn down or re-attached while the\n // transport module was loading.\n if (shared.attachmentEpoch !== attachmentEpoch || shared.sub) return;\n if (this.#sharedSubs.get(shared.channel) !== shared) return;\n\n try {\n this.#assertChannelAuth(shared.channel);\n this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);\n } catch (error) {\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"auth\", error);\n }\n }\n\n #attachSubscriptionNow(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): void {\n const client = this.#ensureClientForChannel(Centrifuge, shared.channel);\n\n const sub = client.newSubscription(\n shared.channel,\n this.#subscriptionOpts(Centrifuge, shared, attachmentEpoch),\n );\n shared.sub = sub;\n shared.client = client;\n\n sub.on(\"publication\", (ctx: PublicationContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n for (const handler of shared.publicationHandlers) handler(ctx.data);\n });\n sub.on(\"subscribed\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const subscriptionEpoch = ++shared.subscriptionEpoch;\n for (const handler of shared.subscribedHandlers) handler(subscriptionEpoch);\n });\n sub.on(\"unsubscribed\", (ctx) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n if (ctx.code >= 2000 && ctx.code < 2500) {\n this.#terminateSubscriptions([shared], \"unsubscribed\", ctx);\n return;\n }\n for (const handler of shared.unsubscribedHandlers) handler();\n });\n sub.on(\"error\", (ctx: SubscriptionErrorContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const sdkCtx = fromCentrifugeSubscriptionError(ctx);\n for (const handler of shared.errorHandlers) handler(sdkCtx);\n });\n\n sub.subscribe();\n }\n\n #getOrCreateSubscription(channel: string): SharedSubscription {\n const existing = this.#sharedSubs.get(channel);\n if (existing) return existing;\n\n const pending = this.#pendingTeardowns.get(channel);\n if (pending) {\n this.#pendingTeardowns.delete(channel);\n this.#sharedSubs.set(channel, pending);\n if (!pending.sub) {\n this.#attachSubscription(pending);\n } else if (pending.sub.state !== \"subscribed\") {\n pending.sub.subscribe();\n }\n return pending;\n }\n\n const shared: SharedSubscription = {\n channel,\n sub: null,\n client: null,\n attachmentEpoch: 0,\n consumers: 0,\n subscriptionEpoch: 0,\n publicationHandlers: new Set(),\n subscribedHandlers: new Set(),\n unsubscribedHandlers: new Set(),\n errorHandlers: new Set(),\n };\n\n this.#sharedSubs.set(channel, shared);\n try {\n this.#attachSubscription(shared);\n } catch (error) {\n this.#sharedSubs.delete(channel);\n throw error;\n }\n return shared;\n }\n\n #callErrorHandler(handler: ErrorHandler | undefined, ctx: SdkSubscriptionErrorContext): void {\n if (!handler) return;\n\n try {\n handler(ctx);\n } catch {\n // Keep error reporting isolated from other subscription consumers.\n }\n }\n\n #callConsumerHandler(\n channel: string,\n type: string,\n handler: () => void,\n onError?: ErrorHandler,\n ): void {\n try {\n handler();\n } catch (error) {\n this.#callErrorHandler(\n onError,\n createSdkSubscriptionErrorContext(channel, type, error),\n );\n }\n }\n\n #terminateSubscriptions(\n subscriptions: SharedSubscription[],\n type: \"disconnected\" | \"unsubscribed\",\n ctx: { code: number; reason: string },\n ): void {\n const notifications = subscriptions.map((shared) => ({\n error: createSdkSubscriptionErrorContext(shared.channel, type, {\n code: ctx.code,\n message: ctx.reason,\n }),\n errorHandlers: [...shared.errorHandlers],\n closeHandlers: [...shared.unsubscribedHandlers],\n }));\n\n // Finish cleanup for every affected channel before callbacks can resubscribe.\n for (const shared of subscriptions) {\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n if (this.#pendingTeardowns.get(shared.channel) === shared) {\n this.#pendingTeardowns.delete(shared.channel);\n }\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n for (const { error, errorHandlers, closeHandlers } of notifications) {\n for (const handler of errorHandlers) handler(error);\n for (const handler of closeHandlers) handler();\n }\n }\n\n /** Forgets a dropped channel's consumers, so an error delivery in progress skips them. */\n #dropConsumers(shared: SharedSubscription): void {\n shared.publicationHandlers.clear();\n shared.subscribedHandlers.clear();\n shared.unsubscribedHandlers.clear();\n shared.errorHandlers.clear();\n }\n\n #teardownSubscription(shared: SharedSubscription): void {\n const sub = shared.sub;\n const client = shared.client;\n const kind = this.#channelKind(shared.channel);\n shared.sub = null;\n shared.client = null;\n shared.attachmentEpoch++;\n if (!sub) return;\n\n try {\n if (sub.state !== \"unsubscribed\") {\n sub.unsubscribe();\n }\n } catch {\n // noop\n }\n try {\n client?.removeSubscription?.(sub);\n } catch {\n // noop\n }\n this.#disconnectClientIfIdle(kind);\n }\n\n #hasChannelsForKind(kind: RealtimeClientKind): boolean {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n for (const shared of this.#pendingTeardowns.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n return false;\n }\n\n #disconnectClientIfIdle(kind: RealtimeClientKind): void {\n if (this.#hasChannelsForKind(kind)) return;\n\n const client = this.#currentClient(kind);\n if (kind === \"private\") {\n this.#privateClient = null;\n } else {\n this.#publicClient = null;\n }\n // A terminal close already recorded its error and dropped the client.\n if (client) this.#setConnection(kind, DISCONNECTED);\n\n try {\n client?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Consumers still waiting for the stream module see the new epoch and never connect. */\n #disconnectPrivateOrders(): void {\n this.#privateOrdersEpoch++;\n this.#privateOrders?.disconnect();\n }\n\n #disconnect(): void {\n this.#disconnectPrivateOrders();\n this.#disconnectCentrifuge();\n }\n\n /** Leaves private order streams alone: they run on their own socket. */\n #disconnectCentrifuge(): void {\n const publicClient = this.#publicClient;\n const privateClient = this.#privateClient;\n\n for (const shared of [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()]) {\n this.#dropConsumers(shared);\n }\n this.#pendingTeardowns.clear();\n this.#sharedSubs.clear();\n this.#publicClient = null;\n this.#privateClient = null;\n if (publicClient) this.#setConnection(\"public\", DISCONNECTED);\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n try {\n publicClient?.disconnect();\n } catch {\n // noop\n }\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n #disconnectPrivate(): void {\n this.#disconnectPrivateOrders();\n const privateClient = this.#privateClient;\n this.#privateClient = null;\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n for (const [channel, shared] of this.#sharedSubs) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#sharedSubs.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n for (const [channel, shared] of this.#pendingTeardowns) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#pendingTeardowns.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n /**\n * Subscribes to a realtime channel and returns an unsubscribe function. Missing\n * authentication is reported to `onError`, or thrown synchronously when no error\n * observer is provided. Non-retryable token failures stop automatic retries;\n * calling subscribe again after correcting the failure restarts private realtime.\n */\n subscribe<T>(channel: string, handlers: SubscribeHandlers<T>): () => void {\n let shared: SharedSubscription;\n try {\n shared = this.#getOrCreateSubscription(channel);\n } catch (error) {\n if (!(error instanceof AuthenticationError)) throw error;\n if (!handlers.onError) throw error;\n\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => this.#callErrorHandler(handlers.onError, ctx));\n return () => {};\n }\n shared.consumers++;\n\n const publicationHandler = handlers.onPublication;\n const errorHandler = handlers.onError;\n const subscribedHandler = handlers.onSubscribed;\n const unsubscribedHandler = handlers.onUnsubscribed;\n\n // Set by the returned unsubscribe: a delivery already under way skips this consumer.\n let closed = false;\n const onError: ErrorHandler | undefined = errorHandler\n ? (ctx) => {\n if (!closed) this.#callErrorHandler(errorHandler, ctx);\n }\n : undefined;\n const onPub: PublicationHandler = (data) => {\n this.#callConsumerHandler(\n channel,\n \"publication_handler\",\n () => publicationHandler(data as T),\n onError,\n );\n };\n let lastSubscribedEpoch = -1;\n const onSubscribed = subscribedHandler\n ? (subscriptionEpoch: number) => {\n if (subscriptionEpoch <= lastSubscribedEpoch) return;\n lastSubscribedEpoch = subscriptionEpoch;\n this.#callConsumerHandler(\n channel,\n \"subscribed_handler\",\n subscribedHandler,\n onError,\n );\n }\n : undefined;\n const onUnsubscribed = unsubscribedHandler\n ? () => {\n if (closed) return;\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n unsubscribedHandler,\n onError,\n );\n }\n : undefined;\n\n shared.publicationHandlers.add(onPub);\n\n if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);\n if (onError) shared.errorHandlers.add(onError);\n\n // Only an explicit subscribe restarts terminal private token failures.\n if (this.#channelKind(channel) === \"private\") {\n const reconnect = shared.client?.state === \"disconnected\";\n const resubscribe = shared.sub?.state === \"unsubscribed\";\n // hasAuth() reads the token provider, so only call it when a restart is possible.\n if ((reconnect || resubscribe) && this.#hasAuth()) {\n if (reconnect) shared.client?.connect();\n if (resubscribe) shared.sub?.subscribe();\n }\n }\n\n // Joining a socket that is already failing: this consumer missed the outage's one report.\n const outage = this.#connection[this.#channelKind(channel)].error;\n if (onError && outage && this.#transportErrors.has(outage)) {\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport\", outage);\n queueMicrotask(() => {\n if (closed || this.#connection[this.#channelKind(channel)].error !== outage) return;\n onError(ctx);\n });\n }\n if (onSubscribed && shared.sub?.state === \"subscribed\") {\n const subscriptionEpoch = shared.subscriptionEpoch;\n queueMicrotask(() => {\n if (closed || shared.sub?.state !== \"subscribed\") return;\n onSubscribed(subscriptionEpoch);\n });\n }\n\n return () => {\n if (closed) return;\n closed = true;\n\n shared.publicationHandlers.delete(onPub);\n if (onSubscribed) shared.subscribedHandlers.delete(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.delete(onUnsubscribed);\n if (onError) shared.errorHandlers.delete(onError);\n\n shared.consumers--;\n if (shared.consumers <= 0) {\n const currentShared = this.#sharedSubs.get(channel);\n if (currentShared !== shared) return;\n\n this.#sharedSubs.delete(channel);\n this.#pendingTeardowns.set(channel, shared);\n\n queueMicrotask(() => {\n if (this.#pendingTeardowns.get(channel) !== shared) return;\n this.#pendingTeardowns.delete(channel);\n\n this.#teardownSubscription(shared);\n\n if (this.#sharedSubs.size === 0 && this.#pendingTeardowns.size === 0) {\n this.#disconnectCentrifuge();\n }\n });\n }\n };\n }\n\n /**\n * Connects to a realtime channel with a custom message decoder.\n */\n connectChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array>(params.channel, {\n onPublication: (data) => {\n let decoded: MessageShape<T>;\n try {\n decoded = fromBinary(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n params.onPublication(decoded);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Connects to a realtime channel that emits protobuf messages.\n */\n connectProtoChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array | MessageShape<T>>(params.channel, {\n onPublication: (data) => {\n let msg: MessageShape<T> | null;\n try {\n msg = decodeProtoFrame(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n if (!msg) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(\n params.channel,\n \"decode\",\n \"Unable to decode protobuf frame\",\n ),\n );\n return;\n }\n params.onPublication(msg);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Streams one account's orders over the private WebSocket. Missing authentication\n * is reported to `onError`, or thrown synchronously when no error observer is provided.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n connectPrivateOrders(params: ConnectPrivateOrdersParams): () => void {\n idToBigInt(params.accountId, \"accountId\");\n const channel = `private:spot:orders:${params.accountId}`;\n if (!this.#hasAuth()) {\n const error = new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n if (!params.onError) throw error;\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => this.#callErrorHandler(params.onError, ctx));\n return () => {};\n }\n // Once loaded, connect at once: an unsubscribe and resubscribe in one tick keeps the stream.\n if (this.#privateOrders) return this.#privateOrders.connect(params);\n const loading = (this.#privateOrdersLoading ??= import(\"./private-orders.js\").then(\n ({ PrivateOrderStream }) =>\n (this.#privateOrders = new PrivateOrderStream({\n url: this.#config.privateWsUrl,\n fetchConnectToken: () =>\n this.#fetchToken(this.#config.tokenEndpoint, \"connection\"),\n fetchSubscribeToken: (ch) => this.#fetchSubscriptionToken(ch),\n })),\n ));\n const epoch = this.#privateOrdersEpoch;\n let closed = false;\n let stop: (() => void) | undefined;\n loading.then(\n (stream) => {\n if (!closed && epoch === this.#privateOrdersEpoch) stop = stream.connect(params);\n },\n (error) => {\n if (this.#privateOrdersLoading === loading) this.#privateOrdersLoading = null;\n if (closed || epoch !== this.#privateOrdersEpoch) return;\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport_load\", error);\n this.#callErrorHandler(params.onError, ctx);\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n () => params.onDisconnected?.(),\n params.onError,\n );\n },\n );\n return () => {\n closed = true;\n stop?.();\n };\n }\n\n /**\n * Disconnects the realtime client from all active channels.\n */\n disconnect(): void {\n this.#disconnect();\n }\n\n /**\n * Disconnects authenticated realtime state without touching public channels.\n */\n disconnectPrivate(): void {\n this.#disconnectPrivate();\n }\n\n /**\n * Status of the public and private sockets. A socket that cannot connect stays\n * `\"connecting\"` with `error` set, and every channel on it gets one `\"transport\"`\n * error per outage. Private order streams run on their own socket and are not included.\n */\n get connection(): RealtimeConnection {\n return this.#connection;\n }\n\n /** Calls `listener` with the current {@link connection} after it changes, in a microtask; a status replaced before then is skipped. Returns an unsubscribe function. */\n onConnectionChange(listener: (connection: RealtimeConnection) => void): () => void {\n this.#connectionListeners.add(listener);\n return () => this.#connectionListeners.delete(listener);\n }\n\n get activeChannels(): number {\n return this.#sharedSubs.size + (this.#privateOrders?.activeChannels ?? 0);\n }\n\n get totalConsumers(): number {\n let total = this.#privateOrders?.totalConsumers ?? 0;\n for (const shared of this.#sharedSubs.values()) {\n total += shared.consumers;\n }\n return total;\n }\n}\n"],"mappings":";;;;;;;;AAmCA,MAAM,qBAAqB;AAK3B,MAAM,sCACF,OAAO;AAMX,IAAI,wBAAwD;AAC5D,IAAI,uBAA8C;AAClD,IAAI,yBAAyB;AAa7B,SAAS,iBAA0C;CAC/C,IACI,2BAA2B,iCAC1B,YAA4C,KAAK,KAElD,OAAO,QAAQ,uBAAO,IAAI,MAAM,qDAAqD,CAAC;CAG1F,IAAI,CAAC,uBAAuB;EAExB,MAAM,gBADc,QAAQ,QAAQ,CAAC,CAAC,KAAK,sBACX,CAAC,CAAC,MAC7B,QAAQ;GACL,uBA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,qBACD,SACA,8BACM,OAAO,iBAAiB,GAC9B,OAAO,OACX;EACJ,CACJ;EACA,aAAa;GACT,SAAS;GACT,OAAO;EACX;CACJ;;;;CAKA,aAAmB;EACf,KAAKE,YAAY;CACrB;;;;CAKA,oBAA0B;EACtB,KAAKC,mBAAmB;CAC5B;;;;;;CAOA,IAAI,aAAiC;EACjC,OAAO,KAAK9B;CAChB;;CAGA,mBAAmB,UAAgE;EAC/E,KAAKC,qBAAqB,IAAI,QAAQ;EACtC,aAAa,KAAKA,qBAAqB,OAAO,QAAQ;CAC1D;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKV,YAAY,QAAQ,KAAKgC,gBAAgB,kBAAkB;CAC3E;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ,KAAKA,gBAAgB,kBAAkB;EACnD,KAAK,MAAM,UAAU,KAAKhC,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
1
+ {"version":3,"file":"client.js","names":["#config","#fetch","#getAuthHeaders","#fetchToken","#tokenRetryAt","#emitErrors","#sharedSubs","#channelKind","#fetchSubscriptionToken","#emitSubscriptionError","#publicClient","#watchClient","#privateClient","#emitConnectionTokenError","#privateTokenFailure","#connection","#connectionListeners","#setConnection","#currentClient","#transportErrors","#terminateSubscriptions","#pendingTeardowns","#createPublicClient","#hasAuth","#createPrivateClient","#ensurePublicClient","#assertChannelAuth","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#attachSubscription","#callErrorHandler","#teardownSubscription","#dropConsumers","#disconnectClientIfIdle","#hasChannelsForKind","#privateOrdersEpoch","#privateOrders","#disconnectPrivateOrders","#disconnectCentrifuge","#getOrCreateSubscription","#reportAuthErrorLater","#callConsumerHandler","#privateOrdersLoading","#disconnect","#disconnectPrivate"],"sources":["../../src/realtime/client.ts"],"sourcesContent":["import { fromBinary, type DescMessage, type MessageShape } from \"@bufbuild/protobuf\";\nimport type {\n Centrifuge,\n ErrorContext,\n SubscriptionErrorContext,\n PublicationContext,\n Subscription,\n} from \"centrifuge/build/protobuf\";\nimport type * as CentrifugeModule from \"centrifuge/build/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n fromCentrifugeSubscriptionError,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport {\n AuthenticationError,\n errorFromHttpStatus,\n InternalServerError,\n PolyesterError,\n RealtimeError,\n} from \"../shared/errors.js\";\nimport { parseRetryAfterHeader } from \"../shared/connect-error-mapping.js\";\nimport { makeFetch } from \"../shared/transports.js\";\nimport { decodeProtoFrame } from \"../utils/streams.js\";\nimport { idToBigInt } from \"../utils/base58-id.js\";\nimport type {\n ConnectChannelParams,\n PolyesterRealtime,\n RealtimeConnection,\n RealtimeConnectionStatus,\n SubscribeHandlers,\n} from \"./types.js\";\nimport type { ConnectPrivateOrdersParams, PrivateOrderStream } from \"./private-orders.js\";\n\n// ponytail: caps a bogus or huge Retry-After; a longer server window just answers 429 again with a new hint.\nconst MAX_RETRY_AFTER_MS = 60_000;\n\ntype CentrifugeCtor = typeof CentrifugeModule.Centrifuge;\ntype CentrifugeModuleLoader = () => Promise<typeof CentrifugeModule>;\n\nconst defaultCentrifugeModuleLoader: CentrifugeModuleLoader = () =>\n import(\"centrifuge/build/protobuf\");\n\n// Centrifuge's protobuf build embeds the protobuf.js runtime (~300 KB minified).\n// Loading it lazily keeps it out of the eager module graph on both the server\n// (Cloudflare isolate cold start — SSR never opens a websocket) and the client\n// app shell; it is only fetched when the first subscription attaches.\nlet centrifugeCtorPromise: Promise<CentrifugeCtor> | null = null;\nlet loadedCentrifugeCtor: CentrifugeCtor | null = null;\nlet centrifugeModuleLoader = defaultCentrifugeModuleLoader;\nexport function __setRealtimeCentrifugeForTests(Centrifuge: CentrifugeCtor | null): void {\n loadedCentrifugeCtor = Centrifuge;\n centrifugeCtorPromise = Centrifuge ? Promise.resolve(Centrifuge) : null;\n}\n\n/** Replaces the lazy Centrifuge module loader for isolated transport-load tests. */\nexport function __setRealtimeCentrifugeLoaderForTests(loader: CentrifugeModuleLoader | null): void {\n centrifugeModuleLoader = loader ?? defaultCentrifugeModuleLoader;\n loadedCentrifugeCtor = null;\n centrifugeCtorPromise = null;\n}\n\nfunction loadCentrifuge(): Promise<CentrifugeCtor> {\n if (\n centrifugeModuleLoader === defaultCentrifugeModuleLoader &&\n (import.meta as { env?: { SSR?: boolean } }).env?.SSR\n ) {\n return Promise.reject(new Error(\"Realtime subscriptions are browser-only during SSR.\"));\n }\n\n if (!centrifugeCtorPromise) {\n const loadAttempt = Promise.resolve().then(centrifugeModuleLoader);\n const retryableLoad = loadAttempt.then(\n (mod) => {\n loadedCentrifugeCtor = mod.Centrifuge;\n return mod.Centrifuge;\n },\n (error) => {\n if (centrifugeCtorPromise === retryableLoad) centrifugeCtorPromise = null;\n throw error;\n },\n );\n centrifugeCtorPromise = retryableLoad;\n }\n return centrifugeCtorPromise;\n}\n\nexport interface RealtimeAuthRequest {\n url: string | URL;\n method: string;\n}\n\nexport interface RealtimeConfig {\n wsUrl: string;\n tokenEndpoint: string;\n subscribeEndpoint: string;\n /** Private WebSocket endpoint for account order streams (`/v1/ws/private`). */\n privateWsUrl: string;\n getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth?: () => boolean;\n /**\n * Custom fetch implementation for realtime token requests. Defaults to the\n * global `fetch`, resolved on each request.\n */\n fetch?: typeof fetch;\n}\n\ntype ResolvedRealtimeConfig = Pick<\n RealtimeConfig,\n \"wsUrl\" | \"tokenEndpoint\" | \"subscribeEndpoint\" | \"privateWsUrl\"\n> & {\n getAuthHeaders: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth: () => boolean;\n};\n\nexport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\ntype PublicationHandler<T = unknown> = (data: T) => void;\ntype ErrorHandler = (ctx: SdkSubscriptionErrorContext) => void;\ntype RealtimeClientKind = \"public\" | \"private\";\n\nconst DISCONNECTED: RealtimeConnectionStatus = { state: \"disconnected\", error: null };\n/** Centrifuge client `error` types that mean a connect attempt failed; each retry emits one. */\nconst CONNECT_FAILURE_TYPES = new Set([\"transport\", \"connect\", \"connectToken\", \"connectData\"]);\n\ninterface SharedSubscription {\n channel: string;\n sub: Subscription | null;\n client: Centrifuge | null;\n attachmentEpoch: number;\n consumers: number;\n subscriptionEpoch: number;\n publicationHandlers: Set<PublicationHandler>;\n subscribedHandlers: Set<(epoch: number) => void>;\n unsubscribedHandlers: Set<() => void>;\n errorHandlers: Set<ErrorHandler>;\n}\n\n/**\n * Shared Centrifuge realtime client that multiplexes public and private protobuf subscriptions across SDK services.\n */\nexport class RealtimeClient implements PolyesterRealtime {\n #publicClient: Centrifuge | null = null;\n #privateClient: Centrifuge | null = null;\n #sharedSubs = new Map<string, SharedSubscription>();\n #pendingTeardowns = new Map<string, SharedSubscription>();\n // Loaded on first use: the stream's protobuf graph (orders included) stays out of the app shell.\n #privateOrdersLoading: Promise<PrivateOrderStream> | null = null;\n #privateOrders: PrivateOrderStream | null = null;\n #privateOrdersEpoch = 0;\n #connection: RealtimeConnection = { public: DISCONNECTED, private: DISCONNECTED };\n #connectionListeners = new Set<(connection: RealtimeConnection) => void>();\n /** Outage errors already sent to channels as `\"transport\"`; replayed to late subscribers. */\n #transportErrors = new WeakSet<Error>();\n /** The non-retryable connection token failure that stops the private socket (code 1). */\n #privateTokenFailure: Error | null = null;\n /** Token requests wait until then after a 429 with `Retry-After`. */\n #tokenRetryAt = 0;\n readonly #config: ResolvedRealtimeConfig;\n readonly #fetch: typeof fetch;\n\n constructor(config: RealtimeConfig) {\n this.#fetch = makeFetch(config.fetch);\n this.#config = {\n wsUrl: config.wsUrl,\n tokenEndpoint: config.tokenEndpoint,\n subscribeEndpoint: config.subscribeEndpoint,\n privateWsUrl: config.privateWsUrl,\n getAuthHeaders: config.getAuthHeaders ?? (() => ({})),\n hasAuth: config.hasAuth ?? (() => false),\n };\n }\n\n async #getAuthHeaders(request: RealtimeAuthRequest): Promise<HeadersInit> {\n return this.#config.getAuthHeaders(request);\n }\n\n /**\n * Every realtime token request (connection, subscription, private order stream)\n * comes through here, so one wait honors `Retry-After` for all of them; the\n * transport's own reconnect backoff still applies on top.\n */\n async #fetchToken(url: string | URL, kind: \"connection\" | \"subscription\"): Promise<string> {\n // Recheck after each await: another request's 429 may have pushed the deadline out.\n let headers: HeadersInit;\n do {\n for (let wait; (wait = this.#tokenRetryAt - Date.now()) > 0;) {\n await new Promise((resolve) => setTimeout(resolve, wait));\n }\n headers = await this.#getAuthHeaders({ url, method: \"GET\" });\n } while (this.#tokenRetryAt > Date.now());\n const res = await this.#fetch(url, { headers });\n if (!res.ok) {\n const retryAfterMs = parseRetryAfterHeader(res.headers.get(\"retry-after\"));\n if (res.status === 429 && retryAfterMs !== undefined) {\n this.#tokenRetryAt = Math.max(\n this.#tokenRetryAt,\n Date.now() + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS),\n );\n }\n throw errorFromHttpStatus(res.status, `Failed to fetch ${kind} token: ${res.status}`, {\n status: res.status,\n retryAfterMs,\n });\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\n `${kind === \"connection\" ? \"Connection\" : \"Subscription\"} token response had no token`,\n );\n }\n return json.token;\n }\n\n #fetchSubscriptionToken(channel: string): Promise<string> {\n const url = new URL(this.#config.subscribeEndpoint);\n url.searchParams.set(\"channel\", channel);\n return this.#fetchToken(url, \"subscription\");\n }\n\n /**\n * Delivers to the consumers registered when it starts: one a handler adds (a resubscribe)\n * is not part of it, and one a handler removes is skipped.\n */\n #emitErrors(recipients: SharedSubscription[], type: string, error: unknown): void {\n const deliveries = recipients.map((shared) => ({\n shared,\n ctx: createSdkSubscriptionErrorContext(shared.channel, type, error),\n handlers: Array.from(shared.errorHandlers),\n }));\n for (const { shared, ctx, handlers } of deliveries) {\n for (const handler of handlers) {\n if (shared.errorHandlers.has(handler)) handler(ctx);\n }\n }\n }\n\n #emitSubscriptionError(shared: SharedSubscription, type: string, error: unknown): void {\n this.#emitErrors([shared], type, error);\n }\n\n #emitConnectionTokenError(error: unknown): void {\n const privateSubs = [...this.#sharedSubs.values()].filter(\n (shared) => this.#channelKind(shared.channel) === \"private\",\n );\n this.#emitErrors(privateSubs, \"connection_token\", error);\n }\n\n #subscriptionOpts(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ) {\n if (this.#channelKind(shared.channel) !== \"private\") return undefined;\n return {\n getToken: async () => {\n try {\n return await this.#fetchSubscriptionToken(shared.channel);\n } catch (error) {\n if (shared.attachmentEpoch === attachmentEpoch) {\n this.#emitSubscriptionError(shared, \"subscription_token\", error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n }\n\n #hasAuth(): boolean {\n return this.#config.hasAuth();\n }\n\n #channelKind(channel: string): RealtimeClientKind {\n return channel.startsWith(\"private:\") ? \"private\" : \"public\";\n }\n\n #createPublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n const client = new Centrifuge(this.#config.wsUrl);\n this.#publicClient = client;\n this.#watchClient(client, \"public\");\n client.connect();\n return client;\n }\n\n #createPrivateClient(Centrifuge: CentrifugeCtor): Centrifuge {\n let client: Centrifuge;\n const opts = {\n getToken: async () => {\n try {\n return await this.#fetchToken(this.#config.tokenEndpoint, \"connection\");\n } catch (error) {\n if (this.#privateClient === client) {\n this.#emitConnectionTokenError(error);\n }\n if (error instanceof PolyesterError && !error.retryable) {\n if (this.#privateClient === client) this.#privateTokenFailure = error;\n throw new Centrifuge.UnauthorizedError(error.message);\n }\n throw error;\n }\n },\n };\n\n client = new Centrifuge(this.#config.wsUrl, opts);\n this.#privateClient = client;\n this.#privateTokenFailure = null;\n this.#watchClient(client, \"private\");\n client.connect();\n return client;\n }\n\n #currentClient(kind: RealtimeClientKind): Centrifuge | null {\n return kind === \"private\" ? this.#privateClient : this.#publicClient;\n }\n\n #setConnection(kind: RealtimeClientKind, status: RealtimeConnectionStatus): void {\n const current = this.#connection[kind];\n if (current.state === status.state && current.error === status.error) return;\n this.#connection = { ...this.#connection, [kind]: status };\n const connection = this.#connection;\n // Notify once Centrifuge has finished its transition, so a listener can disconnect or\n // subscribe safely. A newer status replaces this one, even mid-delivery.\n // Snapshot: a listener added during delivery (one replacing itself) waits for the next change.\n queueMicrotask(() => {\n for (const listener of Array.from(this.#connectionListeners)) {\n if (this.#connection !== connection) return;\n if (!this.#connectionListeners.has(listener)) continue;\n try {\n listener(connection);\n } catch {\n // Keep one listener from starving the others.\n }\n }\n });\n }\n\n #watchClient(client: Centrifuge, kind: RealtimeClientKind): void {\n this.#setConnection(kind, { state: \"connecting\", error: null });\n\n client.on(\"state\", ({ newState, oldState }) => {\n // `disconnected` is recorded by the handlers below, which know the reason.\n if (this.#currentClient(kind) !== client || newState === \"disconnected\") return;\n // A restart after a terminal close starts a new outage.\n const { error } = this.#connection[kind];\n this.#setConnection(kind, {\n state: newState,\n error: newState === \"connected\" || oldState === \"disconnected\" ? null : error,\n });\n });\n\n // Centrifuge stays in \"connecting\" across failed attempts, so the `connecting`\n // event fires once; each failed attempt arrives as a client `error` instead.\n client.on(\"error\", (ctx: ErrorContext) => {\n if (this.#currentClient(kind) !== client || !CONNECT_FAILURE_TYPES.has(ctx.type))\n return;\n const { code, message } = ctx.error as { code?: unknown; message?: unknown };\n // 109: the cached token expired; Centrifuge fetches a new one and reconnects.\n if (ctx.type === \"connect\" && code === 109) return;\n // Report the first failure of an outage only, not every reconnect retry. A token\n // failure only marks the status (private channels get \"connection_token\" from\n // getToken), so a socket failure after one is still sent to channels.\n const current = this.#connection[kind].error;\n if (current && (ctx.type === \"connectToken\" || this.#transportErrors.has(current)))\n return;\n const error = new RealtimeError(\n `Realtime ${kind} connection failed: ${typeof message === \"string\" && message ? message : ctx.type}`,\n { realtimeCode: typeof code === \"number\" ? code : 0, retryable: true },\n );\n this.#setConnection(kind, { state: \"connecting\", error });\n // Private channels already receive connection token failures as \"connection_token\".\n if (ctx.type === \"connectToken\") return;\n this.#transportErrors.add(error);\n // A consumer added by a handler gets the replay in subscribe() instead.\n const affected = [...this.#sharedSubs.values()].filter(\n (shared) => shared.client === client,\n );\n this.#emitErrors(affected, \"transport\", error);\n });\n\n client.on(\"disconnected\", (ctx) => {\n // Code 0 (disconnectCalled) comes from our own teardown, which drops the client first.\n if (this.#currentClient(kind) !== client || ctx.code === 0) return;\n // Centrifuge reports a rejected private token as \"unauthorized\"; record the real failure.\n const tokenFailure =\n kind === \"private\" && ctx.code === 1 ? this.#privateTokenFailure : null;\n if (kind === \"private\") this.#privateTokenFailure = null;\n this.#setConnection(kind, {\n state: \"disconnected\",\n error:\n tokenFailure ??\n new RealtimeError(ctx.reason || \"Realtime connection closed\", {\n realtimeCode: ctx.code,\n }),\n });\n // Code 1 (unauthorized) on the private socket: channels already got the token\n // error, and an explicit subscribe() restarts this client, so keep it. The public\n // socket has no token to fix, so there it is terminal like any other close.\n if (ctx.code === 1 && kind === \"private\") return;\n if (kind === \"private\") this.#privateClient = null;\n else this.#publicClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #assertChannelAuth(channel: string): void {\n if (this.#channelKind(channel) === \"private\" && !this.#hasAuth()) {\n throw new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n }\n }\n\n #ensureClientForChannel(Centrifuge: CentrifugeCtor, channel: string): Centrifuge {\n if (this.#channelKind(channel) === \"private\") {\n return this.#privateClient ?? this.#createPrivateClient(Centrifuge);\n }\n\n return this.#ensurePublicClient(Centrifuge);\n }\n\n #attachSubscription(shared: SharedSubscription): void {\n if (shared.sub) return;\n\n // Auth failures must surface synchronously to subscribe() callers, as\n // they did when centrifuge was imported statically.\n this.#assertChannelAuth(shared.channel);\n\n const attachmentEpoch = shared.attachmentEpoch + 1;\n shared.attachmentEpoch = attachmentEpoch;\n\n // Once the transport module is loaded, attachment stays fully\n // synchronous — only the very first attach pays the dynamic import.\n if (loadedCentrifugeCtor) {\n this.#attachSubscriptionNow(loadedCentrifugeCtor, shared, attachmentEpoch);\n return;\n }\n void this.#attachSubscriptionWhenLoaded(shared, attachmentEpoch);\n }\n\n async #attachSubscriptionWhenLoaded(\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): Promise<void> {\n let Centrifuge: CentrifugeCtor;\n try {\n Centrifuge = await loadCentrifuge();\n } catch (error) {\n if (shared.attachmentEpoch !== attachmentEpoch) return;\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n this.#emitSubscriptionError(shared, \"transport_load\", error);\n return;\n }\n\n // The subscription may have been torn down or re-attached while the\n // transport module was loading.\n if (shared.attachmentEpoch !== attachmentEpoch || shared.sub) return;\n if (this.#sharedSubs.get(shared.channel) !== shared) return;\n\n try {\n this.#assertChannelAuth(shared.channel);\n this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);\n } catch (error) {\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"auth\", error);\n }\n }\n\n #attachSubscriptionNow(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): void {\n const client = this.#ensureClientForChannel(Centrifuge, shared.channel);\n\n const sub = client.newSubscription(\n shared.channel,\n this.#subscriptionOpts(Centrifuge, shared, attachmentEpoch),\n );\n shared.sub = sub;\n shared.client = client;\n\n sub.on(\"publication\", (ctx: PublicationContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n for (const handler of shared.publicationHandlers) handler(ctx.data);\n });\n sub.on(\"subscribed\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const subscriptionEpoch = ++shared.subscriptionEpoch;\n for (const handler of shared.subscribedHandlers) handler(subscriptionEpoch);\n });\n sub.on(\"unsubscribed\", (ctx) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n if (ctx.code >= 2000 && ctx.code < 2500) {\n this.#terminateSubscriptions([shared], \"unsubscribed\", ctx);\n return;\n }\n for (const handler of shared.unsubscribedHandlers) handler();\n });\n sub.on(\"error\", (ctx: SubscriptionErrorContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const sdkCtx = fromCentrifugeSubscriptionError(ctx);\n for (const handler of shared.errorHandlers) handler(sdkCtx);\n });\n\n sub.subscribe();\n }\n\n #getOrCreateSubscription(channel: string): SharedSubscription {\n const existing = this.#sharedSubs.get(channel);\n if (existing) return existing;\n\n const pending = this.#pendingTeardowns.get(channel);\n if (pending) {\n this.#pendingTeardowns.delete(channel);\n this.#sharedSubs.set(channel, pending);\n if (!pending.sub) {\n this.#attachSubscription(pending);\n } else if (pending.sub.state !== \"subscribed\") {\n pending.sub.subscribe();\n }\n return pending;\n }\n\n const shared: SharedSubscription = {\n channel,\n sub: null,\n client: null,\n attachmentEpoch: 0,\n consumers: 0,\n subscriptionEpoch: 0,\n publicationHandlers: new Set(),\n subscribedHandlers: new Set(),\n unsubscribedHandlers: new Set(),\n errorHandlers: new Set(),\n };\n\n this.#sharedSubs.set(channel, shared);\n try {\n this.#attachSubscription(shared);\n } catch (error) {\n this.#sharedSubs.delete(channel);\n throw error;\n }\n return shared;\n }\n\n #callErrorHandler(handler: ErrorHandler | undefined, ctx: SdkSubscriptionErrorContext): void {\n if (!handler) return;\n\n try {\n handler(ctx);\n } catch {\n // Keep error reporting isolated from other subscription consumers.\n }\n }\n\n #callConsumerHandler(\n channel: string,\n type: string,\n handler: () => void,\n onError?: ErrorHandler,\n ): void {\n try {\n handler();\n } catch (error) {\n this.#callErrorHandler(\n onError,\n createSdkSubscriptionErrorContext(channel, type, error),\n );\n }\n }\n\n #terminateSubscriptions(\n subscriptions: SharedSubscription[],\n type: \"disconnected\" | \"unsubscribed\",\n ctx: { code: number; reason: string },\n ): void {\n const notifications = subscriptions.map((shared) => ({\n error: createSdkSubscriptionErrorContext(shared.channel, type, {\n code: ctx.code,\n message: ctx.reason,\n }),\n errorHandlers: [...shared.errorHandlers],\n closeHandlers: [...shared.unsubscribedHandlers],\n }));\n\n // Finish cleanup for every affected channel before callbacks can resubscribe.\n for (const shared of subscriptions) {\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n if (this.#pendingTeardowns.get(shared.channel) === shared) {\n this.#pendingTeardowns.delete(shared.channel);\n }\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n for (const { error, errorHandlers, closeHandlers } of notifications) {\n for (const handler of errorHandlers) handler(error);\n for (const handler of closeHandlers) handler();\n }\n }\n\n /** Forgets a dropped channel's consumers, so an error delivery in progress skips them. */\n #dropConsumers(shared: SharedSubscription): void {\n shared.publicationHandlers.clear();\n shared.subscribedHandlers.clear();\n shared.unsubscribedHandlers.clear();\n shared.errorHandlers.clear();\n }\n\n #teardownSubscription(shared: SharedSubscription): void {\n const sub = shared.sub;\n const client = shared.client;\n const kind = this.#channelKind(shared.channel);\n shared.sub = null;\n shared.client = null;\n shared.attachmentEpoch++;\n if (!sub) return;\n\n try {\n if (sub.state !== \"unsubscribed\") {\n sub.unsubscribe();\n }\n } catch {\n // noop\n }\n try {\n client?.removeSubscription?.(sub);\n } catch {\n // noop\n }\n this.#disconnectClientIfIdle(kind);\n }\n\n #hasChannelsForKind(kind: RealtimeClientKind): boolean {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n for (const shared of this.#pendingTeardowns.values()) {\n if (this.#channelKind(shared.channel) === kind) return true;\n }\n return false;\n }\n\n #disconnectClientIfIdle(kind: RealtimeClientKind): void {\n if (this.#hasChannelsForKind(kind)) return;\n\n const client = this.#currentClient(kind);\n if (kind === \"private\") {\n this.#privateClient = null;\n } else {\n this.#publicClient = null;\n }\n // A terminal close already recorded its error and dropped the client.\n if (client) this.#setConnection(kind, DISCONNECTED);\n\n try {\n client?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Consumers still waiting for the stream module see the new epoch and never connect. */\n #disconnectPrivateOrders(): void {\n this.#privateOrdersEpoch++;\n this.#privateOrders?.disconnect();\n }\n\n #disconnect(): void {\n this.#disconnectPrivateOrders();\n this.#disconnectCentrifuge();\n }\n\n /** Leaves private order streams alone: they run on their own socket. */\n #disconnectCentrifuge(): void {\n const publicClient = this.#publicClient;\n const privateClient = this.#privateClient;\n\n for (const shared of [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()]) {\n this.#dropConsumers(shared);\n }\n this.#pendingTeardowns.clear();\n this.#sharedSubs.clear();\n this.#publicClient = null;\n this.#privateClient = null;\n if (publicClient) this.#setConnection(\"public\", DISCONNECTED);\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n try {\n publicClient?.disconnect();\n } catch {\n // noop\n }\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n #disconnectPrivate(): void {\n this.#disconnectPrivateOrders();\n const privateClient = this.#privateClient;\n this.#privateClient = null;\n if (privateClient) this.#setConnection(\"private\", DISCONNECTED);\n\n for (const [channel, shared] of this.#sharedSubs) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#sharedSubs.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n for (const [channel, shared] of this.#pendingTeardowns) {\n if (this.#channelKind(channel) !== \"private\") continue;\n this.#pendingTeardowns.delete(channel);\n this.#teardownSubscription(shared);\n this.#dropConsumers(shared);\n }\n\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n /** Reports a missing-auth error on the next microtask unless the caller unsubscribes first. */\n #reportAuthErrorLater(\n channel: string,\n error: AuthenticationError,\n onError: ErrorHandler,\n ): () => void {\n let closed = false;\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => {\n if (!closed) this.#callErrorHandler(onError, ctx);\n });\n return () => {\n closed = true;\n };\n }\n\n /**\n * Subscribes to a realtime channel and returns an unsubscribe function. Missing\n * authentication is reported to `onError`, or thrown synchronously when no error\n * observer is provided. Non-retryable token failures stop automatic retries;\n * calling subscribe again after correcting the failure restarts private realtime.\n */\n subscribe<T>(channel: string, handlers: SubscribeHandlers<T>): () => void {\n let shared: SharedSubscription;\n try {\n shared = this.#getOrCreateSubscription(channel);\n } catch (error) {\n if (!(error instanceof AuthenticationError)) throw error;\n if (!handlers.onError) throw error;\n\n return this.#reportAuthErrorLater(channel, error, handlers.onError);\n }\n shared.consumers++;\n\n const publicationHandler = handlers.onPublication;\n const errorHandler = handlers.onError;\n const subscribedHandler = handlers.onSubscribed;\n const unsubscribedHandler = handlers.onUnsubscribed;\n\n // Set by the returned unsubscribe: a delivery already under way skips this consumer.\n let closed = false;\n const onError: ErrorHandler | undefined = errorHandler\n ? (ctx) => {\n if (!closed) this.#callErrorHandler(errorHandler, ctx);\n }\n : undefined;\n const onPub: PublicationHandler = (data) => {\n this.#callConsumerHandler(\n channel,\n \"publication_handler\",\n () => publicationHandler(data as T),\n onError,\n );\n };\n let lastSubscribedEpoch = -1;\n const onSubscribed = subscribedHandler\n ? (subscriptionEpoch: number) => {\n if (subscriptionEpoch <= lastSubscribedEpoch) return;\n lastSubscribedEpoch = subscriptionEpoch;\n this.#callConsumerHandler(\n channel,\n \"subscribed_handler\",\n subscribedHandler,\n onError,\n );\n }\n : undefined;\n const onUnsubscribed = unsubscribedHandler\n ? () => {\n if (closed) return;\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n unsubscribedHandler,\n onError,\n );\n }\n : undefined;\n\n shared.publicationHandlers.add(onPub);\n\n if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);\n if (onError) shared.errorHandlers.add(onError);\n\n // Only an explicit subscribe restarts terminal private token failures.\n if (this.#channelKind(channel) === \"private\") {\n const reconnect = shared.client?.state === \"disconnected\";\n const resubscribe = shared.sub?.state === \"unsubscribed\";\n // hasAuth() reads the token provider, so only call it when a restart is possible.\n if ((reconnect || resubscribe) && this.#hasAuth()) {\n if (reconnect) shared.client?.connect();\n if (resubscribe) shared.sub?.subscribe();\n }\n }\n\n // Joining a socket that is already failing: this consumer missed the outage's one report.\n const outage = this.#connection[this.#channelKind(channel)].error;\n if (onError && outage && this.#transportErrors.has(outage)) {\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport\", outage);\n queueMicrotask(() => {\n if (closed || this.#connection[this.#channelKind(channel)].error !== outage) return;\n onError(ctx);\n });\n }\n if (onSubscribed && shared.sub?.state === \"subscribed\") {\n const subscriptionEpoch = shared.subscriptionEpoch;\n queueMicrotask(() => {\n if (closed || shared.sub?.state !== \"subscribed\") return;\n onSubscribed(subscriptionEpoch);\n });\n }\n\n return () => {\n if (closed) return;\n closed = true;\n\n shared.publicationHandlers.delete(onPub);\n if (onSubscribed) shared.subscribedHandlers.delete(onSubscribed);\n if (onUnsubscribed) shared.unsubscribedHandlers.delete(onUnsubscribed);\n if (onError) shared.errorHandlers.delete(onError);\n\n shared.consumers--;\n if (shared.consumers <= 0) {\n const currentShared = this.#sharedSubs.get(channel);\n if (currentShared !== shared) return;\n\n this.#sharedSubs.delete(channel);\n this.#pendingTeardowns.set(channel, shared);\n\n queueMicrotask(() => {\n if (this.#pendingTeardowns.get(channel) !== shared) return;\n this.#pendingTeardowns.delete(channel);\n\n this.#teardownSubscription(shared);\n\n if (this.#sharedSubs.size === 0 && this.#pendingTeardowns.size === 0) {\n this.#disconnectCentrifuge();\n }\n });\n }\n };\n }\n\n /**\n * Connects to a realtime channel with a custom message decoder.\n */\n connectChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array>(params.channel, {\n onPublication: (data) => {\n let decoded: MessageShape<T>;\n try {\n decoded = fromBinary(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n params.onPublication(decoded);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Connects to a realtime channel that emits protobuf messages.\n */\n connectProtoChannel<T extends DescMessage>(params: ConnectChannelParams<T>): () => void {\n return this.subscribe<Uint8Array | MessageShape<T>>(params.channel, {\n onPublication: (data) => {\n let msg: MessageShape<T> | null;\n try {\n msg = decodeProtoFrame(params.schema, data);\n } catch (error) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(params.channel, \"decode\", error),\n );\n return;\n }\n if (!msg) {\n this.#callErrorHandler(\n params.onError,\n createSdkSubscriptionErrorContext(\n params.channel,\n \"decode\",\n \"Unable to decode protobuf frame\",\n ),\n );\n return;\n }\n params.onPublication(msg);\n },\n onSubscribed: params.onConnected,\n onUnsubscribed: params.onDisconnected,\n onError: params.onError,\n });\n }\n\n /**\n * Streams one account's orders over the private WebSocket. Missing authentication\n * is reported to `onError`, or thrown synchronously when no error observer is provided.\n * Throws ValidationError when `accountId` is not a base58 public ID.\n */\n connectPrivateOrders(params: ConnectPrivateOrdersParams): () => void {\n idToBigInt(params.accountId, \"accountId\");\n const channel = `private:spot:orders:${params.accountId}`;\n if (!this.#hasAuth()) {\n const error = new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n if (!params.onError) throw error;\n return this.#reportAuthErrorLater(channel, error, params.onError);\n }\n // Once loaded, connect at once: an unsubscribe and resubscribe in one tick keeps the stream.\n if (this.#privateOrders) return this.#privateOrders.connect(params);\n const loading = (this.#privateOrdersLoading ??= import(\"./private-orders.js\").then(\n ({ PrivateOrderStream }) =>\n (this.#privateOrders = new PrivateOrderStream({\n url: this.#config.privateWsUrl,\n fetchConnectToken: () =>\n this.#fetchToken(this.#config.tokenEndpoint, \"connection\"),\n fetchSubscribeToken: (ch) => this.#fetchSubscriptionToken(ch),\n })),\n ));\n const epoch = this.#privateOrdersEpoch;\n let closed = false;\n let stop: (() => void) | undefined;\n loading.then(\n (stream) => {\n if (!closed && epoch === this.#privateOrdersEpoch) stop = stream.connect(params);\n },\n (error) => {\n if (this.#privateOrdersLoading === loading) this.#privateOrdersLoading = null;\n if (closed || epoch !== this.#privateOrdersEpoch) return;\n const ctx = createSdkSubscriptionErrorContext(channel, \"transport_load\", error);\n this.#callErrorHandler(params.onError, ctx);\n this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n () => params.onDisconnected?.(),\n params.onError,\n );\n },\n );\n return () => {\n closed = true;\n stop?.();\n };\n }\n\n /**\n * Disconnects the realtime client from all active channels.\n */\n disconnect(): void {\n this.#disconnect();\n }\n\n /**\n * Disconnects authenticated realtime state without touching public channels.\n */\n disconnectPrivate(): void {\n this.#disconnectPrivate();\n }\n\n /**\n * Status of the public and private sockets. A socket that cannot connect stays\n * `\"connecting\"` with `error` set, and every channel on it gets one `\"transport\"`\n * error per outage. Private order streams run on their own socket and are not included.\n */\n get connection(): RealtimeConnection {\n return this.#connection;\n }\n\n /** Calls `listener` with the current {@link connection} after it changes, in a microtask; a status replaced before then is skipped. Returns an unsubscribe function. */\n onConnectionChange(listener: (connection: RealtimeConnection) => void): () => void {\n this.#connectionListeners.add(listener);\n return () => this.#connectionListeners.delete(listener);\n }\n\n get activeChannels(): number {\n return this.#sharedSubs.size + (this.#privateOrders?.activeChannels ?? 0);\n }\n\n get totalConsumers(): number {\n let total = this.#privateOrders?.totalConsumers ?? 0;\n for (const shared of this.#sharedSubs.values()) {\n total += shared.consumers;\n }\n return total;\n }\n}\n"],"mappings":";;;;;;;;AAmCA,MAAM,qBAAqB;AAK3B,MAAM,sCACF,OAAO;AAMX,IAAI,wBAAwD;AAC5D,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AQ,KAAK6B;EACnB,IAAI,SAAS;EACb,IAAI;EACJ,QAAQ,MACH,WAAW;GACR,IAAI,CAAC,UAAU,UAAU,KAAKA,qBAAqB,OAAO,OAAO,QAAQ,MAAM;EACnF,IACC,UAAU;GACP,IAAI,KAAKO,0BAA0B,SAAS,KAAKA,wBAAwB;GACzE,IAAI,UAAU,UAAU,KAAKP,qBAAqB;GAClD,MAAM,MAAM,kCAAkC,SAAS,kBAAkB,KAAK;GAC9E,KAAKL,kBAAkB,OAAO,SAAS,GAAG;GAC1C,KAAKW,qBACD,SACA,8BACM,OAAO,iBAAiB,GAC9B,OAAO,OACX;EACJ,CACJ;EACA,aAAa;GACT,SAAS;GACT,OAAO;EACX;CACJ;;;;CAKA,aAAmB;EACf,KAAKE,YAAY;CACrB;;;;CAKA,oBAA0B;EACtB,KAAKC,mBAAmB;CAC5B;;;;;;CAOA,IAAI,aAAiC;EACjC,OAAO,KAAK/B;CAChB;;CAGA,mBAAmB,UAAgE;EAC/E,KAAKC,qBAAqB,IAAI,QAAQ;EACtC,aAAa,KAAKA,qBAAqB,OAAO,QAAQ;CAC1D;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKV,YAAY,QAAQ,KAAKgC,gBAAgB,kBAAkB;CAC3E;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ,KAAKA,gBAAgB,kBAAkB;EACnD,KAAK,MAAM,UAAU,KAAKhC,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
@@ -297,7 +297,7 @@ declare const AddressBookSchema: v.ObjectSchema<{
297
297
  rootAccountId: string;
298
298
  subaccountId: bigint;
299
299
  }, AddressBookAccountScope>]>, undefined>;
300
- readonly callerRole: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "owner" | "admin" | "treasury" | "leveraged_trader" | "trader" | "viewer">]>;
300
+ readonly callerRole: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "owner" | "admin" | "treasury" | "leveraged_trader" | "trader" | "viewer" | "unspecified">]>;
301
301
  readonly label: v.StringSchema<undefined>;
302
302
  readonly ownerUsername: v.StringSchema<undefined>;
303
303
  readonly smartAccountAddress: v.StringSchema<undefined>;
@@ -1102,7 +1102,7 @@ declare const AddressBookViewSchema: v.ObjectSchema<{
1102
1102
  rootAccountId: string;
1103
1103
  subaccountId: bigint;
1104
1104
  }, AddressBookAccountScope>]>, undefined>;
1105
- readonly callerRole: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "owner" | "admin" | "treasury" | "leveraged_trader" | "trader" | "viewer">]>;
1105
+ readonly callerRole: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "owner" | "admin" | "treasury" | "leveraged_trader" | "trader" | "viewer" | "unspecified">]>;
1106
1106
  readonly label: v.StringSchema<undefined>;
1107
1107
  readonly ownerUsername: v.StringSchema<undefined>;
1108
1108
  readonly smartAccountAddress: v.StringSchema<undefined>;
@@ -57,7 +57,7 @@ type EquityGroupBy = v.InferOutput<typeof EquityGroupBySchema>;
57
57
  declare const BalanceHistoryInputSchema: v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
58
58
  readonly range: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1d", "7d", "30d", "90d", "180d", "365d"], undefined>, v.TransformAction<"1d" | "7d" | "30d" | "90d" | "180d" | "365d", BalanceRange$1.DAY_1 | BalanceRange$1.DAY_7 | BalanceRange$1.DAY_30 | BalanceRange$1.DAY_90 | BalanceRange$1.DAY_180 | BalanceRange$1.DAY_365>]>;
59
59
  readonly ledger: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>, 0>;
60
- readonly accountCodes: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["funding", "trading"], undefined>, v.TransformAction<"trading" | "funding", AccountCode.FUNDING | AccountCode.TRADING>]>, undefined>, readonly []>;
60
+ readonly accountCodes: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["funding", "trading"], undefined>, v.TransformAction<"funding" | "trading", AccountCode.FUNDING | AccountCode.TRADING>]>, undefined>, readonly []>;
61
61
  readonly account: v.OptionalSchema<v.UnionSchema<[v.PicklistSchema<["active", "main"], undefined>, v.StrictObjectSchema<{
62
62
  readonly subaccountId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>]>;
63
63
  }, undefined>], undefined>, undefined>;
@@ -111,14 +111,14 @@ declare function createBalanceHistoryResponseSchema(): v.SchemaWithPipe<readonly
111
111
  points: number;
112
112
  series: {
113
113
  assetId: number;
114
- accountCode: "unspecified" | "trading" | "funding";
114
+ accountCode: "unspecified" | "funding" | "trading";
115
115
  balance: string[];
116
116
  }[];
117
117
  }>]>;
118
118
  type BalanceHistoryResponse = v.InferOutput<ReturnType<typeof createBalanceHistoryResponseSchema>>;
119
119
  declare const EquityHistoryInputSchema: v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
120
120
  readonly range: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1d", "7d", "30d", "90d", "180d", "365d"], undefined>, v.TransformAction<"1d" | "7d" | "30d" | "90d" | "180d" | "365d", BalanceRange$1.DAY_1 | BalanceRange$1.DAY_7 | BalanceRange$1.DAY_30 | BalanceRange$1.DAY_90 | BalanceRange$1.DAY_180 | BalanceRange$1.DAY_365>]>;
121
- readonly accountCodes: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["funding", "trading"], undefined>, v.TransformAction<"trading" | "funding", AccountCode.FUNDING | AccountCode.TRADING>]>, undefined>, readonly []>;
121
+ readonly accountCodes: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["funding", "trading"], undefined>, v.TransformAction<"funding" | "trading", AccountCode.FUNDING | AccountCode.TRADING>]>, undefined>, readonly []>;
122
122
  readonly groupBy: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["account", "asset"], undefined>, "account">, v.TransformAction<"account" | "asset", EquityGroupBy$1.GROUP_BY_ACCOUNT | EquityGroupBy$1.GROUP_BY_ASSET>]>;
123
123
  readonly account: v.OptionalSchema<v.UnionSchema<[v.PicklistSchema<["active", "main"], undefined>, v.StrictObjectSchema<{
124
124
  readonly subaccountId: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>]>;
@@ -11,7 +11,7 @@ type TimestampInit = {
11
11
  };
12
12
  declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
13
13
  readonly symbolId: v.NumberSchema<undefined>;
14
- readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
14
+ readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">>]>;
15
15
  readonly tsSec: v.BigintSchema<undefined>;
16
16
  readonly open: v.BigintSchema<undefined>;
17
17
  readonly high: v.BigintSchema<undefined>;
@@ -22,7 +22,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
22
22
  readonly isClosed: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
23
23
  }, undefined>, v.TransformAction<{
24
24
  symbolId: number;
25
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
25
+ timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">;
26
26
  tsSec: bigint;
27
27
  open: bigint;
28
28
  high: bigint;
@@ -33,7 +33,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
33
33
  isClosed: boolean;
34
34
  }, {
35
35
  symbolId: number;
36
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
36
+ timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">;
37
37
  time: number;
38
38
  open: string;
39
39
  high: string;
@@ -46,7 +46,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
46
46
  declare const createCandleRowIntSchema: typeof createCandleRowSchema;
47
47
  declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
48
48
  readonly symbolId: v.NumberSchema<undefined>;
49
- readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
49
+ readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">>]>;
50
50
  readonly tsSec: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
51
51
  readonly open: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
52
52
  readonly high: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
@@ -63,7 +63,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
63
63
  readonly nextPageToken: v.OptionalSchema<v.StringSchema<undefined>, "">;
64
64
  }, undefined>, v.TransformAction<{
65
65
  symbolId: number;
66
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
66
+ timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">;
67
67
  tsSec: bigint[];
68
68
  open: bigint[];
69
69
  high: bigint[];
@@ -80,7 +80,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
80
80
  nextPageToken: string;
81
81
  }, {
82
82
  symbolId: number;
83
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
83
+ timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">;
84
84
  time: number[];
85
85
  open: string[];
86
86
  high: string[];
@@ -100,7 +100,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
100
100
  }>]>;
101
101
  declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
102
102
  readonly symbolId: v.NumberSchema<undefined>;
103
- readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">>]>;
103
+ readonly timeframe: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">>]>;
104
104
  readonly tsSec: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
105
105
  readonly open: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
106
106
  readonly high: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
@@ -117,7 +117,7 @@ declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithP
117
117
  readonly nextPageToken: v.OptionalSchema<v.StringSchema<undefined>, "">;
118
118
  }, undefined>, v.TransformAction<{
119
119
  symbolId: number;
120
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
120
+ timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">;
121
121
  tsSec: bigint[];
122
122
  open: bigint[];
123
123
  high: bigint[];
@@ -134,7 +134,7 @@ declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithP
134
134
  nextPageToken: string;
135
135
  }, {
136
136
  symbolId: number;
137
- timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo">;
137
+ timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo">;
138
138
  tsSec: number[];
139
139
  open: string[];
140
140
  high: string[];
@@ -158,7 +158,7 @@ type CandleColumnar = v.InferOutput<ReturnType<typeof createCandleColumnarSchema
158
158
  type CandleColumnarInt = v.InferOutput<ReturnType<typeof createCandleColumnarIntSchema>>;
159
159
  declare function createListCandlesInputSchema(): v.SchemaWithPipe<readonly [v.ObjectSchema<{
160
160
  readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
161
- readonly timeframe: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1s", "1m", "3m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "8h", "12h", "1d", "3d", "1w", "1mo"], undefined>, v.TransformAction<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1mo", Timeframe$1.SEC_1 | Timeframe$1.MIN_1 | Timeframe$1.MIN_3 | Timeframe$1.MIN_5 | Timeframe$1.MIN_15 | Timeframe$1.MIN_30 | Timeframe$1.HOUR_1 | Timeframe$1.HOUR_2 | Timeframe$1.HOUR_4 | Timeframe$1.HOUR_6 | Timeframe$1.HOUR_8 | Timeframe$1.HOUR_12 | Timeframe$1.DAY_1 | Timeframe$1.DAY_3 | Timeframe$1.WEEK_1 | Timeframe$1.MONTH_1>]>;
161
+ readonly timeframe: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1s", "1m", "3m", "5m", "15m", "30m", "1h", "2h", "4h", "6h", "8h", "12h", "1d", "3d", "1w", "1mo"], undefined>, v.TransformAction<"1d" | "1s" | "1m" | "5m" | "1h" | "3m" | "15m" | "30m" | "2h" | "4h" | "6h" | "8h" | "12h" | "3d" | "1w" | "1mo", Timeframe$1.SEC_1 | Timeframe$1.MIN_1 | Timeframe$1.MIN_3 | Timeframe$1.MIN_5 | Timeframe$1.MIN_15 | Timeframe$1.MIN_30 | Timeframe$1.HOUR_1 | Timeframe$1.HOUR_2 | Timeframe$1.HOUR_4 | Timeframe$1.HOUR_6 | Timeframe$1.HOUR_8 | Timeframe$1.HOUR_12 | Timeframe$1.DAY_1 | Timeframe$1.DAY_3 | Timeframe$1.WEEK_1 | Timeframe$1.MONTH_1>]>;
162
162
  readonly limit: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 10000, undefined>]>, undefined>;
163
163
  readonly includeIncomplete: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
164
164
  readonly includeReference: v.OptionalSchema<v.BooleanSchema<undefined>, false>;