@polyester/sdk 0.36.0-devnet-20261119181946 → 0.36.0-devnet-20261119195411

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 (35) hide show
  1. package/CHANGELOG.md +7 -1
  2. package/dist/realtime/client.js +7 -1
  3. package/dist/realtime/client.js.map +1 -1
  4. package/dist/services/account-activity/account-activity.schemas.d.ts +6 -6
  5. package/dist/services/assistant/assistant-events.schemas.d.ts +53 -24
  6. package/dist/services/assistant/assistant-events.schemas.d.ts.map +1 -1
  7. package/dist/services/assistant/assistant.schemas.d.ts +2 -2
  8. package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +13 -13
  9. package/dist/services/changelog/changelog.schemas.d.ts +38 -38
  10. package/dist/services/checkpoints/checkpoints.schemas.d.ts +1 -1
  11. package/dist/services/claims/claims.schemas.d.ts +2 -2
  12. package/dist/services/dust-conversion/dust-conversion.schemas.d.ts +6 -6
  13. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  14. package/dist/services/lifecycle/lifecycle.schemas.d.ts +79 -79
  15. package/dist/services/notifications/notifications.schemas.d.ts +4 -4
  16. package/dist/services/orderbook/orderbook.d.ts.map +1 -1
  17. package/dist/services/orderbook/orderbook.js +5 -19
  18. package/dist/services/orderbook/orderbook.js.map +1 -1
  19. package/dist/services/orders/orders-batch.schemas.d.ts +7 -7
  20. package/dist/services/orders/orders-output.schemas.d.ts +6 -6
  21. package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts +1 -1
  22. package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts.map +1 -1
  23. package/dist/services/policies/api-key-policies/api-key-policies.schemas.js +1 -1
  24. package/dist/services/policies/api-key-policies/api-key-policies.schemas.js.map +1 -1
  25. package/dist/services/price-alerts/price-alerts.schemas.d.ts +11 -11
  26. package/dist/services/rewards/rewards.schemas.d.ts +4 -4
  27. package/dist/services/social-verification/social-verification.schemas.d.ts +2 -2
  28. package/dist/services/statement-exports/statement-exports.schemas.d.ts +6 -6
  29. package/dist/services/subaccounts/subaccounts.schemas.d.ts +3 -3
  30. package/dist/services/system/system.schemas.d.ts +13 -13
  31. package/dist/services/trades/trades.schemas.d.ts +1 -1
  32. package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
  33. package/dist/services/triggers/triggers-output.schemas.d.ts +28 -28
  34. package/dist/services/vip/vip.schemas.d.ts +3 -3
  35. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @polyester/sdk
2
2
 
3
- ## 0.36.0-devnet-20261119181946
3
+ ## 0.36.0-devnet-20261119195411
4
4
 
5
5
  ### Minor Changes
6
6
 
@@ -44,6 +44,8 @@
44
44
 
45
45
  - `apiKeys.setAssistantKeys` can bound a key with a permission `preset` (`read_only` or `trade_with_approval`) instead of a `policyId`. Available on devnet only. ([#255](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/255))
46
46
 
47
+ - `apiKeys.policies.apply` now throws `ValidationError` for a blank `policyId` (`""` or whitespace) instead of clearing the key's policy. Pass `null` to clear the binding. ([#269](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/269))
48
+
47
49
  - API-key signing timestamps lead the local clock by at most 500 ms. A burst that signs more requests than milliseconds pass now waits for the clock instead of running past the backend's 1000 ms future limit and getting `TimestampSkewError`. Timestamps still strictly increase, and a single call or a slow sequence is signed as before. This covers `createApiKeyEd25519AuthHeaders` and every `api-key-ed25519` client. ([#257](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/257))
48
50
 
49
51
  - `client.assistant.sendMessage` takes the `page` the user is on, named by route template and title. Available on devnet only. ([#255](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/255))
@@ -148,6 +150,8 @@
148
150
 
149
151
  - An order book subscription keeps asking for the snapshot while `GetOrderBook` answers that the book is not available yet (backoff from 1 s up to 8 s), and shows the book as soon as it is ready. Before, it stopped after three tries and stayed empty until the socket reconnected. A non-retryable snapshot error is not retried. ([#263](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/263))
150
152
 
153
+ - `orderbook.subscribe` on a symbol that does not exist now reports `ResourceNotFoundError` through `onError` instead of emitting an available, empty book. ([#270](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/270))
154
+
151
155
  - `PolicyAction` adds `manage-api-keys`, `manage-api-key-policies` and `manage-subaccount-policies`, API-key policy permissions that take effect only on an admin key. ([#266](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/266))
152
156
 
153
157
  - `PolicyAction` adds `convert-dust` and `read-funding-flows`, which sub-account and API-key policies both accept, and sub-account permissions add `convert_dust` and `read_funding_flows`. ([#258](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/258))
@@ -174,6 +178,8 @@
174
178
 
175
179
  - The order book stops retrying its snapshot once `realtime.disconnect()` closes the socket. `lifecycle.subscribeOpenFlows` trims a padded `accountId` again, and a `null` `accountId` throws instead of opening the public all-accounts channel. A `ServiceUnavailableError` from a gateway that only says "service temporarily unavailable" now carries `retryAfterMs` from `Retry-After`. ([#265](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/265))
176
180
 
181
+ - A realtime subscription whose transport can't be constructed (for example, no global `WebSocket` on the runtime) now reports `type: "transport_load"` to `onError` instead of `type: "auth"`. ([#269](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/269))
182
+
177
183
  - `auth.refreshSession()` keeps the account selected with `switchAccount` even when the display-session cookie can't be read (Node, Bun, workers, or a browser with cookies blocked). Before, the refresh fell back to the main account, so later calls without an explicit `account` ran on the main account. ([#268](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/268))
178
184
 
179
185
  - `RequestTooLargeError` carries the exceeded `limitBytes` in its `detail` when the server sends a `RequestErrorDetail`, whatever the message. ([#266](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/266))
@@ -272,10 +272,16 @@ var RealtimeClient = class {
272
272
  if (this.#sharedSubs.get(shared.channel) !== shared) return;
273
273
  try {
274
274
  this.#assertChannelAuth(shared.channel);
275
- this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);
276
275
  } catch (error) {
277
276
  this.#sharedSubs.delete(shared.channel);
278
277
  this.#emitSubscriptionError(shared, "auth", error);
278
+ return;
279
+ }
280
+ try {
281
+ this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);
282
+ } catch (error) {
283
+ this.#sharedSubs.delete(shared.channel);
284
+ this.#emitSubscriptionError(shared, "transport_load", error);
279
285
  }
280
286
  }
281
287
  #attachSubscriptionNow(Centrifuge, shared, attachmentEpoch) {
@@ -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","#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 // Codes from 100 are the server's: a refused (re)subscribe or a terminal unsubscribe\n // push. Below 100 the client ended it, and a token failure was already reported.\n if (ctx.code >= 100) {\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(input: ConnectPrivateOrdersParams): () => void {\n // The base58 check trims, so the stream must use the trimmed ID too.\n const params = { ...input, accountId: input.accountId.trim() };\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,IAAI,uBAA8C;AAClD,IAAI,yBAAyB;AAa7B,SAAS,iBAA0C;CAC/C,IACI,2BAA2B,iCAC1B,YAA4C,KAAK,KAElD,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,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"}
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 } catch (error) {\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"auth\", error);\n return;\n }\n try {\n this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);\n } catch (error) {\n // e.g. Centrifuge's \"WebSocket constructor not found\" on a runtime without one.\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"transport_load\", 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 // Codes from 100 are the server's: a refused (re)subscribe or a terminal unsubscribe\n // push. Below 100 the client ended it, and a token failure was already reported.\n if (ctx.code >= 100) {\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(input: ConnectPrivateOrdersParams): () => void {\n // The base58 check trims, so the stream must use the trimmed ID too.\n const params = { ...input, accountId: input.accountId.trim() };\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,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,uBAAuB,IAAI;GAC3B,OAAO,IAAI;EACf,IACC,UAAU;GACP,IAAI,0BAA0B,eAAe,wBAAwB;GACrE,MAAM;EACV,CACJ;EACA,wBAAwB;CAC5B;CACA,OAAO;AACX;AAoCA,MAAM,eAAyC;CAAE,OAAO;CAAgB,OAAO;AAAK;;AAEpF,MAAM,wCAAwB,IAAI,IAAI;CAAC;CAAa;CAAW;CAAgB;AAAa,CAAC;;;;AAkB7F,IAAa,iBAAb,MAAyD;CACrD,gBAAmC;CACnC,iBAAoC;CACpC,8BAAc,IAAI,IAAgC;CAClD,oCAAoB,IAAI,IAAgC;CAExD,wBAA4D;CAC5D,iBAA4C;CAC5C,sBAAsB;CACt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BAAmB;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"}
@@ -27,9 +27,9 @@ declare const ListAccountActivityInputSchema: v.SchemaWithPipe<readonly [v.Stric
27
27
  }, undefined>, v.TransformAction<{
28
28
  subaccountIds?: bigint[] | undefined;
29
29
  includeMainAccount?: boolean | undefined;
30
- entityKinds?: ("subaccount" | "api_key" | "account" | "session" | "member" | "policy" | "invite" | "security" | "destination")[] | undefined;
31
- eventActions?: ("disabled" | "revoked" | "removed" | "created" | "updated" | "deleted" | "enabled" | "role_set" | "received" | "replied" | "failed" | "blocked" | "hold_placed" | "hold_released" | "requested" | "applied")[] | undefined;
32
- sources?: ("web" | "mobile" | "api")[] | undefined;
30
+ entityKinds?: ("subaccount" | "api_key" | "account" | "destination" | "session" | "member" | "policy" | "invite" | "security")[] | undefined;
31
+ eventActions?: ("disabled" | "revoked" | "removed" | "failed" | "applied" | "enabled" | "created" | "updated" | "deleted" | "role_set" | "received" | "replied" | "blocked" | "hold_placed" | "hold_released" | "requested")[] | undefined;
32
+ sources?: ("api" | "web" | "mobile")[] | undefined;
33
33
  apiKeyId?: bigint | undefined;
34
34
  startTime?: import("@bufbuild/protobuf/wkt").Timestamp | undefined;
35
35
  endTime?: import("@bufbuild/protobuf/wkt").Timestamp | undefined;
@@ -57,9 +57,9 @@ declare const ListAccountActivityResultSchema: v.ObjectSchema<{
57
57
  seconds: bigint;
58
58
  nanos: number;
59
59
  } | undefined, number | undefined>]>;
60
- readonly entityKind: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "subaccount" | "api_key" | "account" | "session" | "member" | "policy" | "invite" | "security" | "destination">]>;
61
- readonly eventAction: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "disabled" | "revoked" | "removed" | "created" | "updated" | "deleted" | "enabled" | "role_set" | "received" | "replied" | "failed" | "blocked" | "hold_placed" | "hold_released" | "requested" | "applied">]>;
62
- readonly source: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "web" | "mobile" | "api">]>;
60
+ readonly entityKind: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "subaccount" | "api_key" | "account" | "destination" | "session" | "member" | "policy" | "invite" | "security">]>;
61
+ readonly eventAction: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "disabled" | "revoked" | "removed" | "failed" | "applied" | "enabled" | "created" | "updated" | "deleted" | "role_set" | "received" | "replied" | "blocked" | "hold_placed" | "hold_released" | "requested">]>;
62
+ readonly source: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "api" | "web" | "mobile">]>;
63
63
  readonly ip: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
64
64
  readonly userAgent: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
65
65
  readonly actorAccountId: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;