@polyester/sdk 0.36.0-devnet-20261117035807 → 0.36.0-devnet-20261118123359
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/dist/realtime/client.js +5 -1
- package/dist/realtime/client.js.map +1 -1
- package/dist/realtime/snapshot-then-stream.js +5 -3
- package/dist/realtime/snapshot-then-stream.js.map +1 -1
- package/dist/services/address-book/address-book.schemas.d.ts +2 -2
- package/dist/services/assistant/assistant-events.schemas.d.ts +82 -82
- package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +22 -22
- package/dist/services/candles/candles.schemas.d.ts +10 -10
- package/dist/services/changelog/changelog.schemas.d.ts +38 -38
- package/dist/services/checkpoints/checkpoints.schemas.d.ts +3 -3
- package/dist/services/claims/claims.schemas.d.ts +2 -2
- package/dist/services/dust-conversion/dust-conversion.schemas.d.ts +11 -11
- package/dist/services/dust-conversion/dust-conversion.schemas.d.ts.map +1 -1
- package/dist/services/dust-conversion/dust-conversion.schemas.js +1 -1
- package/dist/services/dust-conversion/dust-conversion.schemas.js.map +1 -1
- package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
- package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +12 -12
- package/dist/services/lifecycle/lifecycle.d.ts +1 -1
- package/dist/services/lifecycle/lifecycle.js +2 -3
- package/dist/services/lifecycle/lifecycle.js.map +1 -1
- package/dist/services/lifecycle/lifecycle.schemas.d.ts +54 -54
- package/dist/services/notifications/notifications.schemas.d.ts +13 -1
- package/dist/services/notifications/notifications.schemas.d.ts.map +1 -1
- package/dist/services/orderbook/orderbook.js +3 -2
- package/dist/services/orderbook/orderbook.js.map +1 -1
- package/dist/services/orders/order-errors.schemas.d.ts +2 -2
- package/dist/services/orders/orders-batch.schemas.d.ts +52 -52
- package/dist/services/orders/orders-input.schemas.d.ts +6 -6
- package/dist/services/orders/orders-output.schemas.d.ts +17 -17
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js +1 -27
- package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js.map +1 -1
- package/dist/services/rewards/rewards.schemas.d.ts +4 -4
- package/dist/services/statement-exports/statement-exports.schemas.d.ts +7 -7
- package/dist/services/statement-exports/statement-exports.schemas.d.ts.map +1 -1
- package/dist/services/statement-exports/statement-exports.schemas.js +1 -1
- package/dist/services/statement-exports/statement-exports.schemas.js.map +1 -1
- package/dist/services/subaccounts/subaccounts.d.ts +2 -1
- package/dist/services/subaccounts/subaccounts.d.ts.map +1 -1
- package/dist/services/subaccounts/subaccounts.js +2 -2
- package/dist/services/subaccounts/subaccounts.js.map +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +15 -15
- package/dist/services/system/system.schemas.d.ts +13 -13
- package/dist/services/trades/trades.schemas.d.ts +2 -2
- package/dist/services/triggers/trigger-child-order.schemas.js +1 -1
- package/dist/services/triggers/trigger-child-order.schemas.js.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.d.ts +9 -9
- package/dist/services/triggers/triggers-output.schemas.d.ts +45 -45
- package/dist/shared/connect-error-mapping.d.ts.map +1 -1
- package/dist/shared/connect-error-mapping.js +24 -3
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/errors.d.ts +5 -1
- package/dist/shared/errors.d.ts.map +1 -1
- package/dist/shared/errors.js +3 -0
- package/dist/shared/errors.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @polyester/sdk
|
|
2
2
|
|
|
3
|
-
## 0.36.0-devnet-
|
|
3
|
+
## 0.36.0-devnet-20261118123359
|
|
4
4
|
|
|
5
5
|
### Minor Changes
|
|
6
6
|
|
|
@@ -24,6 +24,8 @@
|
|
|
24
24
|
|
|
25
25
|
- Breaking: `orderbook.createSubscription()` and `orderbook.subscribe()` throw `ValidationError` for a `depth` above 500 instead of silently serving 500 levels. A realtime subscribe the server refuses, including a resubscribe after a server unsubscribe, now reports a non-retryable error with the server's code and message through `onError` before `onUnsubscribed`, instead of only closing. ([#261](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/261))
|
|
26
26
|
|
|
27
|
+
- Breaking: `subaccounts.get` leaves `policy` out when the sub-account has no policy attached, instead of returning a made-up read-only "Subaccount Policy". `policy` is now optional in the return type. ([#263](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/263))
|
|
28
|
+
|
|
27
29
|
- Breaking: trading withdraws without a wallet signer are now signed by the client's API key, so `tradingWithdraws.createToFunding`, `createToExternalChain` and their `prepare*` variants work for API-key clients with no extra input. The `payloadSignature` input is removed: the SDK picked the nonce after the caller had signed, so a caller-supplied signature could never match. Without a wallet signer or API-key auth the call throws `ConfigurationError`, and an API-key withdraw that targets a subaccount throws `ValidationError` instead of silently withdrawing from the key's account. API-key withdraws now also sign again on `submit` when the deadline is near, like wallet withdraws. ([#257](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/257))
|
|
28
30
|
|
|
29
31
|
- Breaking: Trigger IDs are now opaque public IDs, like order IDs, and every existing trigger gets a new ID once: drop stored trigger IDs, list triggers again and restart trigger listings from the first page. A zero trigger ID is now rejected before it is sent. ([#251](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/251))
|
|
@@ -64,6 +66,8 @@
|
|
|
64
66
|
|
|
65
67
|
- `client.dustConversion` converts dust, Trading balances too small to trade, into one target asset: `listBalances` shows each balance's eligibility, `quote` prices a conversion for 30 seconds, `create` converts the quote, and `get` and `list` read conversions. API keys need the `convert-dust` policy action and subaccount members the `convert_dust` permission. ([#258](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/258))
|
|
66
68
|
|
|
69
|
+
- Caller-chosen IDs and keys are sent exactly as given instead of trimmed: `triggers.create` `clientTriggerId` (an empty one is now refused), `statementExports.create` `idempotencyKey` (a padded key is refused by its pattern), and `dustConversion.create` / `get` `quoteId`, `idempotencyKey` and `conversionId`. `lifecycle.subscribeOpenFlows` uses the public all-accounts channel only when `accountId` is omitted, not when it is empty. `orders.subscribe` / `realtime.connectPrivateOrders` subscribe with the trimmed account ID they validate. ([#263](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/263))
|
|
70
|
+
|
|
67
71
|
- `client.internalTransfers.batchCreate` submits up to 10 transfers under one idempotency key and one MFA check, and returns each leg's outcome. ([#258](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/258))
|
|
68
72
|
|
|
69
73
|
- Docs: the `trading_withdraw_request_fee` and `withdraw_failed` transfer types are the whole debit of a rejected or failed withdrawal, not a fee. ([#255](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/255))
|
|
@@ -94,6 +98,8 @@
|
|
|
94
98
|
|
|
95
99
|
- Order book subscriptions apply a delta only when it starts at the book's current sequence, and after a gap wait for the server's next reset instead of refetching snapshots. ([#255](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/255))
|
|
96
100
|
|
|
101
|
+
- 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))
|
|
102
|
+
|
|
97
103
|
- `PolicyAction` adds `convert-dust` and `read-funding-flows`, and sub-account permissions add `convert_dust` and `read_funding_flows`. ([#258](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/258))
|
|
98
104
|
|
|
99
105
|
- `subaccounts.policies.create` and `update` reject a negative or fractional `maxOpenOrders` with a `ValidationError` before sending. They used to send it as 0 (no cap) or truncate it. 0, `null` and an omitted field still mean no cap. ([#259](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/259))
|
|
@@ -110,6 +116,8 @@
|
|
|
110
116
|
|
|
111
117
|
- `orderbook.get` returns the snapshot's `ts`, `orders.cancelAll` returns `tsNs`, and `internalTransfers.create` returns `acceptedAtNs`, fields the server already sent but the SDK dropped. ([#258](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/258))
|
|
112
118
|
|
|
119
|
+
- `ServiceUnavailableError` carries the server's `Retry-After` as `retryAfterMs`, as `RateLimitError` already does. ([#263](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/263))
|
|
120
|
+
|
|
113
121
|
- `socialVerification.unlink` unlinks X and Discord accounts as well as Telegram. Changing or unlinking a linked X or Discord account needs a `stepUpToken` and is allowed once per provider every 30 days: auth error details and verifications carry `retryAfter`, and verifications add the `social_account_cooldown` and `social_change_limit_reached` error codes. ([#258](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/258))
|
|
114
122
|
|
|
115
123
|
- Spot config pairs and the catalog add an optional `priceBand` (`lowerBps`, `upperBps`, `referenceWindowMs`), absent when the pair has no band, and orders report the cancel reason `price_band` when the band stopped a market order. Older snapshots without it still validate. ([#251](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/251))
|
|
@@ -136,6 +144,8 @@
|
|
|
136
144
|
|
|
137
145
|
- A trading withdraw or internal transfer `quantity` too large for the 128-bit wire amount now throws `CatalogConversionError` (a `ValidationError`) naming `quantity`, instead of a plain `RangeError`. ([#259](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/259))
|
|
138
146
|
|
|
147
|
+
- A server timeout (`deadline_exceeded` or a 504) on `apiKeys.create`, API-key policy create, sub-account policy create and MFA recovery-code regeneration now throws `OutcomeUnknownError` (`retryable: false`) instead of a retryable `TimeoutError` or `ServiceUnavailableError`. The write may have been applied, so read it back before trying again. Reads and client-side timeouts are unchanged. ([#263](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/263))
|
|
148
|
+
|
|
139
149
|
- `@polyester/sdk/unstable/gen` adds `assetInfoPb` (asset information). ([#256](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/256))
|
|
140
150
|
|
|
141
151
|
- `@polyester/sdk/unstable/gen` adds `dustConversionPb` (dust conversion) and `statementExportPb` (statement exports). ([#258](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/258))
|
package/dist/realtime/client.js
CHANGED
|
@@ -603,7 +603,11 @@ var RealtimeClient = class {
|
|
|
603
603
|
* is reported to `onError`, or thrown synchronously when no error observer is provided.
|
|
604
604
|
* Throws ValidationError when `accountId` is not a base58 public ID.
|
|
605
605
|
*/
|
|
606
|
-
connectPrivateOrders(
|
|
606
|
+
connectPrivateOrders(input) {
|
|
607
|
+
const params = {
|
|
608
|
+
...input,
|
|
609
|
+
accountId: input.accountId.trim()
|
|
610
|
+
};
|
|
607
611
|
idToBigInt(params.accountId, "accountId");
|
|
608
612
|
const channel = `private:spot:orders:${params.accountId}`;
|
|
609
613
|
if (!this.#hasAuth()) {
|
|
@@ -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(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,IAAI,uBAA8C;AAClD,IAAI,yBAAyB;AAa7B,SAAS,iBAA0C;CAC/C,IACI,2BAA2B,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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 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,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;CACtB,cAAkC;EAAE,QAAQ;EAAc,SAAS;CAAa;CAChF,uCAAuB,IAAI,IAA8C;;CAEzE,mCAAmB,IAAI,QAAe;;CAEtC,uBAAqC;;CAErC,gBAAgB;CAChB;CACA;CAEA,YAAY,QAAwB;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AAI,QAAQ,KAAKA,gBAAgB,kBAAkB;EACnD,KAAK,MAAM,UAAU,KAAKhC,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PolyesterError } from "../shared/errors.js";
|
|
1
2
|
import { createSdkSubscriptionErrorContext } from "../shared/subscription-errors.js";
|
|
2
3
|
import { formatConnectError } from "../utils/errors.js";
|
|
3
4
|
import { isDev } from "../utils/is-dev.js";
|
|
@@ -71,10 +72,11 @@ function snapshotThenStream(params) {
|
|
|
71
72
|
reportBufferedPublicationError(error);
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
|
-
function scheduleSnapshotRetry() {
|
|
75
|
+
function scheduleSnapshotRetry(error) {
|
|
75
76
|
const retry = params.snapshotRetry;
|
|
76
77
|
if (!retry || retryAttempts >= retry.maxAttempts || disposed) return;
|
|
77
|
-
|
|
78
|
+
if (error instanceof PolyesterError && !error.retryable) return;
|
|
79
|
+
const delayMs = Math.min(retry.delayMs * 2 ** retryAttempts, retry.maxDelayMs ?? Number.POSITIVE_INFINITY);
|
|
78
80
|
retryAttempts++;
|
|
79
81
|
retryTimer = setTimeout(() => {
|
|
80
82
|
retryTimer = null;
|
|
@@ -100,7 +102,7 @@ function snapshotThenStream(params) {
|
|
|
100
102
|
ready = true;
|
|
101
103
|
applyBufferedAsLive();
|
|
102
104
|
}
|
|
103
|
-
scheduleSnapshotRetry();
|
|
105
|
+
scheduleSnapshotRetry(error);
|
|
104
106
|
});
|
|
105
107
|
}
|
|
106
108
|
const unsubscribeRealtime = params.realtime.connectProtoChannel({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-then-stream.js","names":[],"sources":["../../src/realtime/snapshot-then-stream.ts"],"sourcesContent":["import type { DescMessage, MessageShape } from \"@bufbuild/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"./types.js\";\nimport { formatConnectError } from \"../utils/errors.js\";\nimport { isDev } from \"../utils/is-dev.js\";\n\nexport interface SnapshotThenStreamSubscription {\n unsubscribe: () => void;\n refreshSnapshot: () => void;\n isReady: () => boolean;\n isDisposed: () => boolean;\n}\n\nexport interface SnapshotThenStreamInput<TSchema extends DescMessage, TSnapshot, TPublication> {\n realtime: PolyesterRealtime;\n channel: string;\n schema: TSchema;\n maxBufferedPublications?: number;\n bufferPublicationKey?: (publication: TPublication) => PropertyKey;\n snapshotRetry?: {\n maxAttempts: number;\n delayMs: number;\n };\n snapshotFailureMode?: \"wait\" | \"live\" | ((error: unknown) => \"wait\" | \"live\");\n snapshotErrorLog?: string;\n fetchSnapshot: () => Promise<TSnapshot>;\n readPublication: (message: MessageShape<TSchema>) => readonly TPublication[];\n applySnapshot: (snapshot: TSnapshot, bufferedPublications: readonly TPublication[]) => void;\n applyLivePublications: (publications: readonly TPublication[]) => void;\n onOpen?: () => void;\n onClose?: () => void;\n onError?: (ctx: SdkSubscriptionErrorContext) => void;\n}\n\n/**\n * Snapshot-then-stream for feed state. By default, the buffer caps at\n * `maxBufferedPublications` and drops the OLDEST publications, which is correct for\n * ephemeral feeds where a later publication supersedes earlier ones. Keyed state can\n * provide `bufferPublicationKey` to retain the latest value for every key without FIFO\n * loss. Entity transitions (orders, triggers, balances, trades) must NOT use this —\n * their ordering contract lives in the app-side `EntityStreamStore`, which buffers\n * unbounded and replays because dropping an event loses a row transition.\n */\nexport function snapshotThenStream<TSchema extends DescMessage, TSnapshot, TPublication>(\n params: SnapshotThenStreamInput<TSchema, TSnapshot, TPublication>,\n): SnapshotThenStreamSubscription {\n const maxBufferedPublications = params.maxBufferedPublications ?? 200;\n let droppedPublications = 0;\n\n let ready = false;\n let disposed = false;\n let refreshGeneration = 0;\n let pendingPublications: TPublication[] = [];\n let retryAttempts = 0;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n\n function reportSnapshotError(error: unknown): void {\n if (isDev() && params.snapshotErrorLog) {\n console.error(params.snapshotErrorLog, error);\n }\n params.onError?.(\n createSdkSubscriptionErrorContext(\n params.channel,\n \"snapshot\",\n error instanceof Error ? error : formatConnectError(error, \"snapshot failed\"),\n ),\n );\n }\n\n function takePendingPublications(): TPublication[] {\n const buffered = pendingPublications;\n pendingPublications = [];\n return buffered;\n }\n\n function applyBufferedAsLive(): void {\n const buffered = takePendingPublications();\n if (buffered.length === 0) return;\n applyLivePublications(buffered);\n }\n\n function bufferPublications(publications: readonly TPublication[]): void {\n if (params.bufferPublicationKey) {\n const byKey = new Map<PropertyKey, TPublication>();\n for (const publication of pendingPublications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n for (const publication of publications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n pendingPublications = Array.from(byKey.values());\n return;\n }\n\n const next = pendingPublications.concat(publications);\n if (next.length > maxBufferedPublications) {\n droppedPublications += next.length - maxBufferedPublications;\n if (isDev()) {\n console.warn(\n `[snapshot-then-stream] ${params.channel}: buffer cap dropped ${droppedPublications} publication(s) while snapshot in flight`,\n );\n }\n }\n pendingPublications = next.slice(-maxBufferedPublications);\n }\n\n function clearRetryTimer(): void {\n if (retryTimer === null) return;\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n\n function reportBufferedPublicationError(error: unknown): void {\n params.onError?.(\n createSdkSubscriptionErrorContext(params.channel, \"publication_handler\", error),\n );\n }\n\n function applyLivePublications(publications: readonly TPublication[]): void {\n try {\n params.applyLivePublications(publications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function applySnapshot(\n snapshot: TSnapshot,\n bufferedPublications: readonly TPublication[],\n ): void {\n try {\n params.applySnapshot(snapshot, bufferedPublications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function scheduleSnapshotRetry(): void {\n const retry = params.snapshotRetry;\n if (!retry || retryAttempts >= retry.maxAttempts || disposed) return;\n\n const delayMs = retry.delayMs * 2 ** retryAttempts;\n retryAttempts++;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n refreshSnapshot(false);\n }, delayMs);\n }\n\n function refreshSnapshot(resetRetries = true): void {\n if (disposed) return;\n clearRetryTimer();\n if (resetRetries) retryAttempts = 0;\n\n const generation = ++refreshGeneration;\n ready = false;\n\n Promise.resolve()\n .then(() => params.fetchSnapshot())\n .then((snapshot) => {\n if (disposed || generation !== refreshGeneration) return;\n\n const buffered = takePendingPublications();\n applySnapshot(snapshot, buffered);\n\n if (disposed || generation !== refreshGeneration) return;\n ready = true;\n retryAttempts = 0;\n })\n .catch((error: unknown) => {\n if (disposed || generation !== refreshGeneration) return;\n reportSnapshotError(error);\n const failureMode =\n typeof params.snapshotFailureMode === \"function\"\n ? params.snapshotFailureMode(error)\n : params.snapshotFailureMode;\n if (failureMode === \"live\") {\n ready = true;\n applyBufferedAsLive();\n }\n scheduleSnapshotRetry();\n });\n }\n\n const unsubscribeRealtime = params.realtime.connectProtoChannel({\n channel: params.channel,\n schema: params.schema,\n onPublication: (message) => {\n const publications = params.readPublication(message);\n if (publications.length === 0) return;\n\n if (!ready) {\n bufferPublications(publications);\n return;\n }\n\n applyLivePublications(publications);\n },\n onConnected: () => {\n if (disposed) return;\n pendingPublications = [];\n refreshSnapshot();\n params.onOpen?.();\n },\n onDisconnected: () => {\n if (disposed) return;\n clearRetryTimer();\n refreshGeneration++;\n ready = false;\n pendingPublications = [];\n params.onClose?.();\n },\n onError: params.onError,\n });\n\n function unsubscribe(): void {\n disposed = true;\n clearRetryTimer();\n refreshGeneration++;\n pendingPublications = [];\n try {\n unsubscribeRealtime();\n } catch {\n // noop\n }\n }\n\n return {\n unsubscribe,\n refreshSnapshot,\n isReady: () => ready,\n isDisposed: () => disposed,\n };\n}\n"],"mappings":";;;;;;;;;;;;;AA8CA,SAAgB,mBACZ,QAC8B;CAC9B,MAAM,0BAA0B,OAAO,2BAA2B;CAClE,IAAI,sBAAsB;CAE1B,IAAI,QAAQ;CACZ,IAAI,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AAmB;GACf,IAAI,UAAU;GACd,sBAAsB,CAAC;GACvB,gBAAgB;GAChB,OAAO,SAAS;EACpB;EACA,sBAAsB;GAClB,IAAI,UAAU;GACd,gBAAgB;GAChB;GACA,QAAQ;GACR,sBAAsB,CAAC;GACvB,OAAO,UAAU;EACrB;EACA,SAAS,OAAO;CACpB,CAAC;CAED,SAAS,cAAoB;EACzB,WAAW;EACX,gBAAgB;EAChB;EACA,sBAAsB,CAAC;EACvB,IAAI;GACA,oBAAoB;EACxB,QAAQ,CAER;CACJ;CAEA,OAAO;EACH;EACA;EACA,eAAe;EACf,kBAAkB;CACtB;AACJ"}
|
|
1
|
+
{"version":3,"file":"snapshot-then-stream.js","names":[],"sources":["../../src/realtime/snapshot-then-stream.ts"],"sourcesContent":["import type { DescMessage, MessageShape } from \"@bufbuild/protobuf\";\nimport {\n createSdkSubscriptionErrorContext,\n type SdkSubscriptionErrorContext,\n} from \"../shared/subscription-errors.js\";\nimport type { PolyesterRealtime } from \"./types.js\";\nimport { formatConnectError } from \"../utils/errors.js\";\nimport { PolyesterError } from \"../shared/errors.js\";\nimport { isDev } from \"../utils/is-dev.js\";\n\nexport interface SnapshotThenStreamSubscription {\n unsubscribe: () => void;\n refreshSnapshot: () => void;\n isReady: () => boolean;\n isDisposed: () => boolean;\n}\n\nexport interface SnapshotThenStreamInput<TSchema extends DescMessage, TSnapshot, TPublication> {\n realtime: PolyesterRealtime;\n channel: string;\n schema: TSchema;\n maxBufferedPublications?: number;\n bufferPublicationKey?: (publication: TPublication) => PropertyKey;\n /** Exponential backoff from `delayMs`, capped at `maxDelayMs`; never retries a non-retryable PolyesterError. */\n snapshotRetry?: {\n maxAttempts: number;\n delayMs: number;\n maxDelayMs?: number;\n };\n snapshotFailureMode?: \"wait\" | \"live\" | ((error: unknown) => \"wait\" | \"live\");\n snapshotErrorLog?: string;\n fetchSnapshot: () => Promise<TSnapshot>;\n readPublication: (message: MessageShape<TSchema>) => readonly TPublication[];\n applySnapshot: (snapshot: TSnapshot, bufferedPublications: readonly TPublication[]) => void;\n applyLivePublications: (publications: readonly TPublication[]) => void;\n onOpen?: () => void;\n onClose?: () => void;\n onError?: (ctx: SdkSubscriptionErrorContext) => void;\n}\n\n/**\n * Snapshot-then-stream for feed state. By default, the buffer caps at\n * `maxBufferedPublications` and drops the OLDEST publications, which is correct for\n * ephemeral feeds where a later publication supersedes earlier ones. Keyed state can\n * provide `bufferPublicationKey` to retain the latest value for every key without FIFO\n * loss. Entity transitions (orders, triggers, balances, trades) must NOT use this —\n * their ordering contract lives in the app-side `EntityStreamStore`, which buffers\n * unbounded and replays because dropping an event loses a row transition.\n */\nexport function snapshotThenStream<TSchema extends DescMessage, TSnapshot, TPublication>(\n params: SnapshotThenStreamInput<TSchema, TSnapshot, TPublication>,\n): SnapshotThenStreamSubscription {\n const maxBufferedPublications = params.maxBufferedPublications ?? 200;\n let droppedPublications = 0;\n\n let ready = false;\n let disposed = false;\n let refreshGeneration = 0;\n let pendingPublications: TPublication[] = [];\n let retryAttempts = 0;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n\n function reportSnapshotError(error: unknown): void {\n if (isDev() && params.snapshotErrorLog) {\n console.error(params.snapshotErrorLog, error);\n }\n params.onError?.(\n createSdkSubscriptionErrorContext(\n params.channel,\n \"snapshot\",\n error instanceof Error ? error : formatConnectError(error, \"snapshot failed\"),\n ),\n );\n }\n\n function takePendingPublications(): TPublication[] {\n const buffered = pendingPublications;\n pendingPublications = [];\n return buffered;\n }\n\n function applyBufferedAsLive(): void {\n const buffered = takePendingPublications();\n if (buffered.length === 0) return;\n applyLivePublications(buffered);\n }\n\n function bufferPublications(publications: readonly TPublication[]): void {\n if (params.bufferPublicationKey) {\n const byKey = new Map<PropertyKey, TPublication>();\n for (const publication of pendingPublications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n for (const publication of publications) {\n byKey.set(params.bufferPublicationKey(publication), publication);\n }\n pendingPublications = Array.from(byKey.values());\n return;\n }\n\n const next = pendingPublications.concat(publications);\n if (next.length > maxBufferedPublications) {\n droppedPublications += next.length - maxBufferedPublications;\n if (isDev()) {\n console.warn(\n `[snapshot-then-stream] ${params.channel}: buffer cap dropped ${droppedPublications} publication(s) while snapshot in flight`,\n );\n }\n }\n pendingPublications = next.slice(-maxBufferedPublications);\n }\n\n function clearRetryTimer(): void {\n if (retryTimer === null) return;\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n\n function reportBufferedPublicationError(error: unknown): void {\n params.onError?.(\n createSdkSubscriptionErrorContext(params.channel, \"publication_handler\", error),\n );\n }\n\n function applyLivePublications(publications: readonly TPublication[]): void {\n try {\n params.applyLivePublications(publications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function applySnapshot(\n snapshot: TSnapshot,\n bufferedPublications: readonly TPublication[],\n ): void {\n try {\n params.applySnapshot(snapshot, bufferedPublications);\n } catch (error) {\n reportBufferedPublicationError(error);\n }\n }\n\n function scheduleSnapshotRetry(error: unknown): void {\n const retry = params.snapshotRetry;\n if (!retry || retryAttempts >= retry.maxAttempts || disposed) return;\n if (error instanceof PolyesterError && !error.retryable) return;\n\n const delayMs = Math.min(\n retry.delayMs * 2 ** retryAttempts,\n retry.maxDelayMs ?? Number.POSITIVE_INFINITY,\n );\n retryAttempts++;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n refreshSnapshot(false);\n }, delayMs);\n }\n\n function refreshSnapshot(resetRetries = true): void {\n if (disposed) return;\n clearRetryTimer();\n if (resetRetries) retryAttempts = 0;\n\n const generation = ++refreshGeneration;\n ready = false;\n\n Promise.resolve()\n .then(() => params.fetchSnapshot())\n .then((snapshot) => {\n if (disposed || generation !== refreshGeneration) return;\n\n const buffered = takePendingPublications();\n applySnapshot(snapshot, buffered);\n\n if (disposed || generation !== refreshGeneration) return;\n ready = true;\n retryAttempts = 0;\n })\n .catch((error: unknown) => {\n if (disposed || generation !== refreshGeneration) return;\n reportSnapshotError(error);\n const failureMode =\n typeof params.snapshotFailureMode === \"function\"\n ? params.snapshotFailureMode(error)\n : params.snapshotFailureMode;\n if (failureMode === \"live\") {\n ready = true;\n applyBufferedAsLive();\n }\n scheduleSnapshotRetry(error);\n });\n }\n\n const unsubscribeRealtime = params.realtime.connectProtoChannel({\n channel: params.channel,\n schema: params.schema,\n onPublication: (message) => {\n const publications = params.readPublication(message);\n if (publications.length === 0) return;\n\n if (!ready) {\n bufferPublications(publications);\n return;\n }\n\n applyLivePublications(publications);\n },\n onConnected: () => {\n if (disposed) return;\n pendingPublications = [];\n refreshSnapshot();\n params.onOpen?.();\n },\n onDisconnected: () => {\n if (disposed) return;\n clearRetryTimer();\n refreshGeneration++;\n ready = false;\n pendingPublications = [];\n params.onClose?.();\n },\n onError: params.onError,\n });\n\n function unsubscribe(): void {\n disposed = true;\n clearRetryTimer();\n refreshGeneration++;\n pendingPublications = [];\n try {\n unsubscribeRealtime();\n } catch {\n // noop\n }\n }\n\n return {\n unsubscribe,\n refreshSnapshot,\n isReady: () => ready,\n isDisposed: () => disposed,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAiDA,SAAgB,mBACZ,QAC8B;CAC9B,MAAM,0BAA0B,OAAO,2BAA2B;CAClE,IAAI,sBAAsB;CAE1B,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,oBAAoB;CACxB,IAAI,sBAAsC,CAAC;CAC3C,IAAI,gBAAgB;CACpB,IAAI,aAAmD;CAEvD,SAAS,oBAAoB,OAAsB;EAC/C,IAAI,MAAM,KAAK,OAAO,kBAClB,QAAQ,MAAM,OAAO,kBAAkB,KAAK;EAEhD,OAAO,UACH,kCACI,OAAO,SACP,YACA,iBAAiB,QAAQ,QAAQ,mBAAmB,OAAO,iBAAiB,CAChF,CACJ;CACJ;CAEA,SAAS,0BAA0C;EAC/C,MAAM,WAAW;EACjB,sBAAsB,CAAC;EACvB,OAAO;CACX;CAEA,SAAS,sBAA4B;EACjC,MAAM,WAAW,wBAAwB;EACzC,IAAI,SAAS,WAAW,GAAG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EACH;EACA;EACA,eAAe;EACf,kBAAkB;CACtB;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, "
|
|
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, "
|
|
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>;
|