@polyester/sdk 0.34.1-devnet-20261106025831 → 0.35.0-devnet-20261107174905

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/README.md +12 -0
  3. package/dist/index.d.ts +2 -2
  4. package/dist/realtime/client.d.ts.map +1 -1
  5. package/dist/realtime/client.js +178 -29
  6. package/dist/realtime/client.js.map +1 -1
  7. package/dist/realtime/index.d.ts +2 -2
  8. package/dist/realtime/types.d.ts +21 -2
  9. package/dist/realtime/types.d.ts.map +1 -1
  10. package/dist/services/candles/candles.schemas.d.ts +10 -10
  11. package/dist/services/checkpoints/checkpoints.schemas.d.ts +8 -2
  12. package/dist/services/checkpoints/checkpoints.schemas.d.ts.map +1 -1
  13. package/dist/services/checkpoints/checkpoints.schemas.js +6 -0
  14. package/dist/services/checkpoints/checkpoints.schemas.js.map +1 -1
  15. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  16. package/dist/services/lifecycle/lifecycle.schemas.d.ts +79 -79
  17. package/dist/services/orderbook/orderbook.d.ts +1 -1
  18. package/dist/services/orderbook/orderbook.js +1 -1
  19. package/dist/services/orderbook/orderbook.js.map +1 -1
  20. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  21. package/dist/services/orders/orders-batch.schemas.d.ts +7 -7
  22. package/dist/services/orders/orders-output.schemas.d.ts +3 -3
  23. package/dist/services/orders/orders.d.ts +1 -1
  24. package/dist/services/orders/orders.js +1 -1
  25. package/dist/services/orders/orders.js.map +1 -1
  26. package/dist/services/rewards/rewards.d.ts +1 -1
  27. package/dist/services/rewards/rewards.js +1 -1
  28. package/dist/services/rewards/rewards.js.map +1 -1
  29. package/dist/services/rewards/rewards.schemas.d.ts +7 -0
  30. package/dist/services/rewards/rewards.schemas.d.ts.map +1 -1
  31. package/dist/services/rewards/rewards.schemas.js +8 -1
  32. package/dist/services/rewards/rewards.schemas.js.map +1 -1
  33. package/dist/services/subaccounts/subaccounts.d.ts +1 -1
  34. package/dist/services/subaccounts/subaccounts.js +1 -1
  35. package/dist/services/subaccounts/subaccounts.js.map +1 -1
  36. package/dist/services/subaccounts/subaccounts.schemas.d.ts +10 -1
  37. package/dist/services/subaccounts/subaccounts.schemas.d.ts.map +1 -1
  38. package/dist/services/subaccounts/subaccounts.schemas.js +8 -1
  39. package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
  40. package/dist/services/trades/trades.schemas.d.ts +2 -2
  41. package/dist/services/triggers/triggers-output.schemas.d.ts +19 -19
  42. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  43. package/dist/shared/connect-error-mapping.js +5 -2
  44. package/dist/shared/connect-error-mapping.js.map +1 -1
  45. package/dist/shared/errors.d.ts +1 -1
  46. package/dist/shared/errors.d.ts.map +1 -1
  47. package/dist/shared/errors.js.map +1 -1
  48. package/dist/shared/subscription-errors.d.ts +2 -0
  49. package/dist/shared/subscription-errors.d.ts.map +1 -1
  50. package/dist/shared/subscription-errors.js.map +1 -1
  51. package/dist/shared/transports.js.map +1 -1
  52. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,11 +1,31 @@
1
1
  # @polyester/sdk
2
2
 
3
- ## 0.34.1-devnet-20261106025831
3
+ ## 0.35.0-devnet-20261107174905
4
+
5
+ ### Minor Changes
6
+
7
+ - Breaking: `realtime.isConnected` is removed. It was true whenever a socket object existed, even one that never connected. Read `realtime.connection` instead: `{ public, private }`, each `{ state, error }`, where `state` is `"connecting"`, `"connected"` or `"disconnected"` and `error` is the first failure of the current outage (a socket failure after a connection token failure replaces it), cleared once the socket connects. `realtime.onConnectionChange(listener)` calls the listener with the current value after each change, in a microtask, and returns an unsubscribe function. Private order streams run on their own socket and are not included. Custom `PolyesterRealtime` implementations must add both members. ([#232](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/232))
8
+
9
+ A realtime socket that cannot connect now reports it. On the first failed attempt, every channel on that socket gets one `onError` with `type: "transport"` and a retryable `RealtimeError`, not one per reconnect retry; a channel subscribed while the socket is still failing gets it on subscribe. On the private socket, a failed connection token request is reported as `"connection_token"` on each attempt instead. The order book (whose snapshot waits for the channel to open) and trades no longer wait silently forever when the socket is unreachable; `onOpen` follows once it recovers.
10
+
11
+ Once a channel's unsubscribe function has run, that consumer gets no further `onError` or `onUnsubscribed`, even from a notification already in progress (for example, unsubscribing from inside a terminal close's `onError` no longer also calls `onUnsubscribed`). Channels that actually closed are still told, even if a handler calls `disconnect()` meanwhile.
4
12
 
5
13
  ### Patch Changes
6
14
 
15
+ - The `orders.batchCreate` JSDoc now gives the batch's 15-minute idempotency window. It previously said 60 seconds, which is the `batchReplace` window. Within 15 minutes, a retry with the same `requestId` and payload returns each decided item's original result and retries the unresolved ones. After that the ID is free, and a repeat can place its orders again. ([#235](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/235))
16
+
17
+ - `Checkpoint` now carries `openingValueUsd`, the season-end USD value of the holdings restored when the season opened (`"0"` when it opened with no balances, `undefined` when a restored balance had no USD value). With it, `seasonResultUsd` reconciles as `finalValueUsd - openingValueUsd - netInflowUsd`. ([#235](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/235))
18
+
7
19
  - `expandColumnarTimestampsSec` and `columnarTimestampSecAt` now end at `endTsSec`, so the last columnar history point is no longer one bucket early. ([#233](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/233))
8
20
 
21
+ - Realtime token requests honor `Retry-After`. When the connection or subscription token endpoint answers 429 with a `Retry-After` header, the `RateLimitError` carries it as `retryAfterMs`, and the realtime client sends no further token request until it has passed (at most 60 seconds), even when the socket retries sooner. This covers public, private and private order stream sockets. ([#232](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/232))
22
+
23
+ - `rewards.listAwards` now returns `awardsMayChange`. It is `true` while a campaign can still publish awards or one of the account's awards is awaiting a destination, ready for payout, or failed and retryable. When it is `false`, polling cannot return new awards or award changes until a new campaign is created. ([#235](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/235))
24
+
25
+ - `PolyesterErrorCode` now includes `"SUBACCOUNT_CHALLENGE_INVALID"`, the code `SubaccountChallengeInvalidError` already carries, so an exhaustive `switch` over the union covers it. ([#235](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/235))
26
+
27
+ - `Subaccount` records now carry `removed`. `subaccounts.subscribe` emits `removed: true` (with `role: "unspecified"`) when the caller loses access to a subaccount, for example after the owner removes them as a member, so drop it from local state. List and get responses always return `false`. Access and role changes do not bump `revision` or `updatedAt`, so apply them in arrival order. ([#235](https://github.com/Fabric-Labs/polyester-sdk-typescript/pull/235))
28
+
9
29
  ## 0.34.0
10
30
 
11
31
  ### Minor Changes
package/README.md CHANGED
@@ -148,6 +148,18 @@ await client.orders.create(order);
148
148
 
149
149
  Call `unsubscribe()` when the subscription is no longer needed.
150
150
 
151
+ A socket that cannot connect keeps retrying. On its first failed attempt, every
152
+ channel on it gets one `onError` with `type: "transport"` and a retryable
153
+ `RealtimeError`, and a channel subscribed while it is still failing gets the same
154
+ error right away; the next `onOpen` means it recovered. On the private socket, a
155
+ failed connection token request is reported as `type: "connection_token"` on each
156
+ attempt instead. To show connection status
157
+ on its own, read `client.realtime.connection`, which holds `{ state, error }` for
158
+ the public and the private socket, and watch it with
159
+ `client.realtime.onConnectionChange(listener)`, which returns an unsubscribe
160
+ function. `state` is `"connecting"`, `"connected"` or `"disconnected"`; a socket
161
+ that is `"connecting"` with an `error` is failing, not just slow.
162
+
151
163
  `client.orders.subscribe` streams over the private WebSocket (`/v1/ws/private`).
152
164
  Each changed order arrives complete through `onEvent`; keep the copy with the
153
165
  higher `version`. Pass `onSnapshot` to receive the account's full live view when
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@ import { ResolveAccountInput, ResolvedAccount } from "./services/accounts/accoun
13
13
  import { AccountScope, AccountScopedInput } from "./shared/account-scope.js";
14
14
  import { SdkSubscriptionErrorContext } from "./shared/subscription-errors.js";
15
15
  import { ConnectPrivateOrdersParams, PrivateOrdersEvent } from "./realtime/private-orders.js";
16
- import { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from "./realtime/types.js";
16
+ import { ConnectChannelParams, PolyesterRealtime, RealtimeConnection, RealtimeConnectionState, RealtimeConnectionStatus, SubscribeHandlers } from "./realtime/types.js";
17
17
  import "./realtime/index.js";
18
18
  import { ApiKeyPolicy, ApiKeyPolicyApplyInput, ApiKeyPolicyCreateInput, ApiKeyPolicyUpdateInput, ListApiKeyPoliciesResponse } from "./services/policies/api-key-policies/api-key-policies.schemas.js";
19
19
  import { ApiKey, ApiKeyIdInput, ApiKeyStatus, ApiKeysCreateInput, ApiKeysListInput, ApiKeysUpdateInput } from "./services/api-keys/api-keys.schemas.js";
@@ -124,4 +124,4 @@ import "./services/transfers/transfers.types.js";
124
124
  import "./services/triggers/triggers.types.js";
125
125
  import "./services/vip/vip.types.js";
126
126
  import "./services/zipper/zipper.types.js";
127
- export { type AccountCodeValue, type AccountIdentity, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type ActiveAccountInfo, type AddressBook, type AddressBookAccountScope, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type AutoWithdrawCadence, type AutoWithdrawDestination, type AutoWithdrawDestinationInput, type AutoWithdrawPause, type AutoWithdrawPauseReason, type AutoWithdrawRule, type AutoWithdrawRun, type AutoWithdrawRunReason, type AutoWithdrawRunState, type AutoWithdrawSchedule, type AutoWithdrawScheduleInput, type AutoWithdrawScopedInput, type AutoWithdrawStep, type AutoWithdrawStepReason, type AutoWithdrawStepState, type AutoWithdrawWeekday, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOrderInput, type CancelOrderResult, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ChangelogAudience, type ChangelogChange, type ChangelogChangeCategory, type ChangelogChangeEntry, type ChangelogPost, type ChangelogPostSummary, type ChangelogSection, type ChangelogSort, type ChangelogSurface, type Checkpoint, type CheckpointAssetAmount, type CheckpointBadge, type CheckpointBiggestTrade, type CheckpointChainFlow, type CheckpointEarnedBadge, type CheckpointField, type CheckpointFlowTotal, type CheckpointFundingDay, type CheckpointFundingFlowSummary, type CheckpointOrderToolCounts, type CheckpointOrderTypeCounts, type CheckpointPairActivity, type CheckpointPortfolioValuePoint, type CheckpointTimeInForceCounts, type CheckpointVipTierChange, type CheckpointVolumePoint, type ClaimCampaign, type ClaimDailyRewardInput, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPayoutDelayReason, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConnectPrivateOrdersParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateSubaccountChallengeInput, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type DisableAutoWithdrawRuleInput, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetChangelogPostInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetSubaccountInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListAutoWithdrawRunsInput, type ListAutoWithdrawRunsResult, type ListChangelogChangesInput, type ListChangelogChangesResult, type ListChangelogPostsInput, type ListChangelogPostsResult, type ListCheckpointsInput, type ListDepositAddressesInput, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListRewardAwardsInput, type ListRewardAwardsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, NotImplementedError, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, OutcomeUnknownError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterBrowserCore, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, PolyesterCore, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, PolyesterServerCore, type PolyesterServices, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PreparedTradingWithdraw, type PreviewOrderResult, type PrivateOrdersEvent, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RewardAward, type RewardFulfillmentMethod, type RewardFulfillmentState, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetAutoWithdrawRuleInput, type SetRewardDestinationInput, type SetRewardDestinationResult, type SetSubaccountMemberMfaRequirementInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationErrorCode, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeDiscount, type SpotFeeRate, type SpotFeeRateBreakdown, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountChallenge, SubaccountChallengeInvalidError, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type TakeProfitInput, type Timeframe, TimeoutError, TimestampSkewError, type Trade, type TradeBackfill, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipMetricQuality, type VipMetricStatus, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, WithdrawDeadlineExpiredError, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
127
+ export { type AccountCodeValue, type AccountIdentity, type AccountScope, type AccountScopedInput, type AccountSigner, type AccountSignerAuthEvents, type AccountSignerConfig, type CreateSubaccountResult as AccountSignerCreateSubaccountResult, type AccountSignerFactory, type ActiveAccountInfo, type AddressBook, type AddressBookAccountScope, type AddressBookEntries, type AddressBookEntriesView, type AddressBookEntry, type AddressBookRecentDestinationsView, type AddressBookTag, type AddressBookTagSummary, type AddressBookView, type AddressBookViewInvalidated, AlreadyExistsError, type ApiKey, type ApiKeyEd25519AuthProvider, type ApiKeyIdInput, type ApiKeyPolicy, type ApiKeyPolicyApplyInput, type ApiKeyPolicyCreateInput, type ApiKeyPolicyUpdateInput, type ApiKeyStatus, type ApiKeysCreateInput, type ApiKeysListInput, type ApiKeysUpdateInput, type AssetConfig, type AuthCookieLocation, type AuthHydrationData, type AuthLoginMethod, type AuthState, type AuthTokenStorage, type AuthTokenStorageSetOptions, AuthenticationError, type AutoWithdrawCadence, type AutoWithdrawDestination, type AutoWithdrawDestinationInput, type AutoWithdrawPause, type AutoWithdrawPauseReason, type AutoWithdrawRule, type AutoWithdrawRun, type AutoWithdrawRunReason, type AutoWithdrawRunState, type AutoWithdrawSchedule, type AutoWithdrawScheduleInput, type AutoWithdrawScopedInput, type AutoWithdrawStep, type AutoWithdrawStepReason, type AutoWithdrawStepState, type AutoWithdrawWeekday, type BalanceHistoryInput, type BalanceHistoryResponse, type BalanceRange, type BatchCancelOrderInput, type BatchCancelOrderResult, type BatchCancelOrdersInput, type BatchCancelOrdersResult, type BatchCreateOrderResult, type BatchCreateOrdersInput, type BatchCreateOrdersResult, type BatchGuardApprovals, type BatchReplaceAdmissionItem, type BatchReplaceOrdersInput, type BatchReplaceOrdersResult, type BatchSignProtectedActionInput, type BeginMfaChallengeInput, type BeginMfaChallengeResult, type BeginPasskeyEnrollmentInput, type BeginPasskeyEnrollmentResult, type BeginTotpEnrollmentInput, type BeginTotpEnrollmentResult, type CancelAllAfterInput, type CancelAllAfterResult, type CancelAllOrdersInput, type CancelAllOrdersResponse, type CancelOrderInput, type CancelOrderResult, type CancelTriggerInput, type CancelTriggerResult, type Candle, type CandleColumnar, type CandleColumnarInt, type CandleInt, type ChainAnalyticsRange, type ChangelogAudience, type ChangelogChange, type ChangelogChangeCategory, type ChangelogChangeEntry, type ChangelogPost, type ChangelogPostSummary, type ChangelogSection, type ChangelogSort, type ChangelogSurface, type Checkpoint, type CheckpointAssetAmount, type CheckpointBadge, type CheckpointBiggestTrade, type CheckpointChainFlow, type CheckpointEarnedBadge, type CheckpointField, type CheckpointFlowTotal, type CheckpointFundingDay, type CheckpointFundingFlowSummary, type CheckpointOrderToolCounts, type CheckpointOrderTypeCounts, type CheckpointPairActivity, type CheckpointPortfolioValuePoint, type CheckpointTimeInForceCounts, type CheckpointVipTierChange, type CheckpointVolumePoint, type ClaimCampaign, type ClaimDailyRewardInput, type ClaimDailyRewardResult, type ClaimFreshStepUpInput, type ClaimFreshStepUpResult, type ClaimGeneratedUsernameInput, type ClaimPayoutDelayReason, type ClaimPolicy, type ColumnarTimeWindow, type CompleteMfaChallengeResult, ConfigurationError, type ConnectChannelParams, type ConnectPrivateOrdersParams, type ConsumeFreshStepUpInput, type CookieAuthTokenStorageOptions, type CopyAddressBookEntryInput, type CreateAddressBookEntryInput, type CreateAddressBookTagInput, type CreateDepositAddressInput, type CreateGuardSignerWalletResult, type CreateInternalTransferInput, type CreateInternalTransferResult, type CreateOrderResult, type CreateOrderbookSubscriptionInput, type CreatePolyesterAccountSignerParams, type CreatePolyesterEnvironmentParams, type CreateServerClientFromCookiesParams, type CreateServerClientFromRequestParams, type CreateSubaccountChallengeInput, type CreateSubaccountInput, type CreateSubaccountParams, type CreateSubaccountResult$1 as CreateSubaccountResult, type CreateSubaccountResult$1 as CreateSubaccountServiceResult, type CreateTradingWithdrawResult, type CreateTradingWithdrawToExternalChainInput, type CreateTradingWithdrawToExternalChainServiceInput, type CreateTradingWithdrawToFundingInput, type CreateTradingWithdrawToFundingServiceInput, type CreateTriggerInput, type CreateTriggerResult, type CreateWalletChallengeInput, type CurrencyConversionConfig, type CurrencyConversionRates, type CurrencyMetadata, type DailyClaimReward, type DailyClaimState, type DailyClaimStatus, type DailyClaimTransfer, type DeleteAddressBookEntryInput, type DeleteAddressBookTagInput, type DeleteMfaFactorInput, type DepositAddress, type DepositWithdrawConfig, type DisableAutoWithdrawRuleInput, type EffectiveSubaccountPermissions, type EquityGroupBy, type EquityHistoryInput, type EquityHistoryResponse, type EquitySeries, type EquitySeriesGrouping, type EvmHex, type ExportGuardSignerWalletResult, type FiatConversionRate, type FiatConversionSnapshot, type FinishPasskeyChallengeInput, type FinishPasskeyEnrollmentInput, type FinishPasskeyEnrollmentResult, type FinishTotpEnrollmentInput, type FinishTotpEnrollmentResult, type GeneratedUsernameOffer, type GetAddressBookViewInput, type GetBatchReplaceStatusInput, type GetBatchReplaceStatusResult, type GetCandlesColumnsInput, type GetCandlesInput, type GetChangelogPostInput, type GetLifecycleFlowInput, type GetLifecycleFlowOutput, type GetMarketTradesInput, type GetOrderDetailsInput, type GetOrderbookHeatmapInput, type GetOrderbookInput, type GetSpotFeeRatesInput, type GetSubaccountInput, type GetTriggerInput, type GetUnifiedAssetBalancesInput, type GetUserTradesInput, type GetVerificationResponse, type GetZippedAssetSupplyGroupInput, type GetZippedAssetSupplyInput, type GuardApproval, type GuardSignerScopedInput, type GuardSignerStatus, type HeatmapDepthValue, type HeatmapIntervalValue, type HeatmapQuantityModeValue, type HexAddress, InternalServerError, type InternalTransferDestination, type InternalTransferWhitelistEntries, type InternalTransferWhitelistEntry, type InviteSubaccountMemberInput, type JwtAuthProvider, type LadderDetailsOutput, type LedgerBalance, type LedgerTransfer, type LedgerTransferSide, type LifecycleAssetIds, type LifecycleFlowDetail, type LifecycleFlowState, type LifecycleFlowStep, type LifecycleFlowStepActivity, type LifecycleFlowSummary, type LifecycleFlowSummaryProgress, type LifecycleFlowTimelineItem, type LifecycleFlowTxMatch, type LifecycleListOrderBy, type LifecycleListScope, type LifecycleReason, type LifecycleRequestFee, type LifecycleRequestFeeStatus, type LifecycleSort, type LifecycleTxLookupKind, type LifecycleZipperReason, type ListAddressBookEntriesInput, type ListApiKeyPoliciesResponse, type ListAutoWithdrawRunsInput, type ListAutoWithdrawRunsResult, type ListChangelogChangesInput, type ListChangelogChangesResult, type ListChangelogPostsInput, type ListChangelogPostsResult, type ListCheckpointsInput, type ListDepositAddressesInput, type ListInternalTransferWhitelistEntriesInput, type ListLifecycleFlowsByTxInput, type ListLifecycleFlowsByTxOutput, type ListLifecycleFlowsInput, type ListLifecycleFlowsOutput, type ListMarketOverviewInput, type ListMfaFactorsResult, type ListRewardAwardsInput, type ListRewardAwardsResult, type ListSubaccountInvitesInput, type ListTransferCounterpartiesInput, type ListTransferDestinationsInput, type ListTransfersInput, type ListTriggerEventsInput, type ListTriggerEventsResult, type ListTriggersInput, type ListTriggersResult, type LoginOptions, type LoginResult, type LoginWithWalletInput, type LoginWithWalletResponse, type MarketOverview, type MarketOverviewOrderBy, type MarketOverviewSort, type MarketOverviewSparkline, type MarketTrade, type Me, MfaEnrollmentRequiredError, type MfaFactor, MfaLastFactorRequiredError, MfaRequiredError, type MfaSessionInfo, MfaVerificationError, type MfaVerificationFailureReason, type MirroredWithdrawWhitelistEntry, type ModifyOrderInput, type ModifyOrderResult, type ModifyTriggerInput, type ModifyTriggerResult, NetworkError, type NewOrderInput, type NextVipTierThresholds, NotImplementedError, type OpenOrdersInput, type Order, type OrderDetails, type OrderErrorCode, type OrderErrorDetail, type OrderHistoryInput, type OrderIntentInput, type OrderLineage, type OrderTransfer, type OrderbookData, type OrderbookHeatmapDeltaBucket, type OrderbookHeatmapDeltaChain, type OrderbookHeatmapDeltaLevels, type OrderbookHeatmapKeyframe, type OrderbookHeatmapLevels, type OrderbookHeatmapLiveBucket, type OrderbookHeatmapResponse, type OrderbookLevel, type OrderbookStreamHandlers, type OrderbookSubscription, OutcomeUnknownError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_DEVNET_ENVIRONMENT, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, type PairConfig, type PairStatus, type PauseTriggerInput, type PauseTriggerResult, PermissionError, type PolicyAction, PolicyInUseError, PolicyLockedError, type PolicyMarketScope, PolicyScopeMismatchError, type PolyesterAccountAbstractionEnvironment, PolyesterBrowserClient, type PolyesterBrowserClientConfig, PolyesterBrowserCore, PolyesterClient, type PolyesterClientBaseConfig, type PolyesterClientConfig, type PolyesterContractsEnvironment, PolyesterCore, type PolyesterEntryPointConfig, type PolyesterEnvironment, PolyesterError, type PolyesterErrorCode, type PolyesterErrorDetail, type PolyesterErrorOptions, type PolyesterMutationOptions, type PolyesterRealtime, type PolyesterRealtimeAuthConfig, type PolyesterRequestOptions, type PolyesterSafeDeploymentConfig, PolyesterServerClient, type PolyesterServerClientConfig, PolyesterServerCore, type PolyesterServices, type PortfolioEquityHistoryInput, type PortfolioEquityHistoryResponse, type PortfolioEquitySeries, type PortfolioEquitySeriesGrouping, type PortfolioEquitySnapshotResponse, PreconditionFailedError, type PreparedTradingWithdraw, type PreviewOrderResult, type PrivateOrdersEvent, type Profile, type RateLimitConfig, type RateLimitDetail, RateLimitError, type RateLimitErrorOptions, type RateLimitFailureReason, type RateLimitPolicyClass, type RateLimitRefillModel, type RateLimitScope, type RealtimeConnection, type RealtimeConnectionState, type RealtimeConnectionStatus, RealtimeError, type RealtimeErrorOptions, type RegenerateRecoveryCodesInput, type RegenerateRecoveryCodesResult, type ReleaseFreshStepUpInput, type RemoveSubaccountMemberInput, RequestError, type ResolveAccountInput, type ResolvedAccount, type ResolvedInternalTransferDestination, ResourceNotFoundError, type RespondSubaccountInviteInput, type ResumeTriggerInput, type ResumeTriggerResult, RevisionConflictError, type RewardAward, type RewardFulfillmentMethod, type RewardFulfillmentState, type RiskPolicyInput, type RotateGuardSignerWalletResult, type SdkSubscriptionErrorContext, type ServerSessionCookieOptions, type ServerSessionSnapshot, ServiceUnavailableError, type SessionData, SessionElevationRequiredError, type SetAutoWithdrawRuleInput, type SetRewardDestinationInput, type SetRewardDestinationResult, type SetSubaccountMemberMfaRequirementInput, type SignProtectedActionInput, type SocialProvider, type SocialProviderInput, type SocialVerification, type SocialVerificationErrorCode, type SocialVerificationMethod, type SocialVerificationStatus, type SparklineIntervalName, type SpotConfig, type SpotFeeDiscount, type SpotFeeRate, type SpotFeeRateBreakdown, type SpotPairVolumeSeries, type SpotVolumeHistoryInput, type SpotVolumeHistoryResponse, type StablecoinConversionRate, StaleQuoteError, type StartVerificationInput, type StartVerificationResponse, StepUpRequiredError, type StopDetailsOutput, type StopLossInput, type Subaccount, type SubaccountActivityInput, type SubaccountChallenge, SubaccountChallengeInvalidError, type SubaccountEvent, type SubaccountIdInput, type SubaccountInvite, type SubaccountInviteStatus, type SubaccountMember, type SubaccountPermission, type SubaccountPermissionDefinition, type SubaccountPolicy, type SubaccountPolicyApplyInput, type SubaccountPolicyCreateInput, type SubaccountPolicyUpdateInput, type SubaccountRole, type SubaccountRoleCatalog, type SubaccountRoleDefinition, type SubaccountScopedInput, type SubaccountStatus, type SubscribeHandlers, type SubscribeZippedAssetSupplyInput, type TakeProfitInput, type Timeframe, TimeoutError, TimestampSkewError, type Trade, type TradeBackfill, type TradingRateLimitClass, type TradingRateLimitRule, type TradingRateLimits, type TradingWithdrawSigningConfig, type TradingWithdrawWalletSigner, type TrailingDetailsOutput, type TrailingStopInput, type TransferCodeValue, type TransferCounterparties, type TransferCounterparty, type TransferDestination, type TransferDestinations, type TransferSideKind, TransientError, type Transports, type Trigger, type TriggerDetailsOutput, type TriggerEvent, type TwapDetailsOutput, type UnifiedAssetBalancesResponse, type UpdateAddressBookEntryInput, type UpdateAddressBookTagInput, type UpdateMfaFactorInput, type UpdateMfaFactorResult, type UpdateProfileInput, type UpdateSubaccountInput, type UpdateSubaccountMemberRoleInput, UserOperationAlreadyKnownError, UserOperationNotExecutedError, UserOperationSendTimeoutError, type UsernameHistoryEntry, type ValidateWithdrawDestinationInput, type ValidateWithdrawDestinationResult, ValidationError, type VerificationReadyResponse, type VerifyRecoveryCodeChallengeInput, type VerifyTotpChallengeInput, type VipMetricQuality, type VipMetricStatus, type VipStatus, type VipTier, type VipTierCatalog, type WalletChallenge, WithdrawDeadlineExpiredError, type WithdrawWhitelistView, type ZippedAssetSupplyBatch, type ZippedAssetSupplyGroupResponse, type ZippedAssetSupplyResponse, type ZippedAssetSupplySeries, type ZippedAssetSupplyUpdate, type ZipperAssetChainVariant, type ZipperAssetConfig, type ZipperChainConfig, type ZipperChainContractConfig, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, createPolyesterServerCoreFromCookies, createPolyesterServerCoreFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, isTimeoutAbortError, keccak256Hex, loadErrorDetailDecoders, mergeLedgerBalances, normalizeErrorMessage, resolveAuthCookieName, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../../src/realtime/client.ts"],"mappings":";;;;;UA6EiB;EACb,cAAc;EACd;;UAGa;EACb;EACA;EACA;;EAEA;EACA,kBAAkB,SAAS,wBAAwB,QAAQ,eAAe;EAC1E"}
1
+ {"version":3,"file":"client.d.ts","names":[],"sources":["../../src/realtime/client.ts"],"mappings":";;;;;UAwFiB;EACb,cAAc;EACd;;UAGa;EACb;EACA;EACA;;EAEA;EACA,kBAAkB,SAAS,wBAAwB,QAAQ,eAAe;EAC1E"}
@@ -1,4 +1,5 @@
1
- import { AuthenticationError, InternalServerError, PolyesterError, errorFromHttpStatus } from "../shared/errors.js";
1
+ import { AuthenticationError, InternalServerError, PolyesterError, RealtimeError, errorFromHttpStatus } from "../shared/errors.js";
2
+ import { parseRetryAfterHeader } from "../shared/connect-error-mapping.js";
2
3
  import { makeFetch } from "../shared/transports.js";
3
4
  import { idToBigInt } from "../utils/base58-id.js";
4
5
  import { createSdkSubscriptionErrorContext, fromCentrifugeSubscriptionError } from "../shared/subscription-errors.js";
@@ -6,6 +7,7 @@ import { decodeProtoFrame } from "../utils/streams.js";
6
7
  import { fromBinary } from "@bufbuild/protobuf";
7
8
  //#region src/realtime/client.ts
8
9
  const realtimeFetch = makeFetch();
10
+ const MAX_RETRY_AFTER_MS = 6e4;
9
11
  const defaultCentrifugeModuleLoader = () => import("centrifuge/build/protobuf");
10
12
  let centrifugeCtorPromise = null;
11
13
  let loadedCentrifugeCtor = null;
@@ -24,6 +26,17 @@ function loadCentrifuge() {
24
26
  }
25
27
  return centrifugeCtorPromise;
26
28
  }
29
+ const DISCONNECTED = {
30
+ state: "disconnected",
31
+ error: null
32
+ };
33
+ /** Centrifuge client `error` types that mean a connect attempt failed; each retry emits one. */
34
+ const CONNECT_FAILURE_TYPES = /* @__PURE__ */ new Set([
35
+ "transport",
36
+ "connect",
37
+ "connectToken",
38
+ "connectData"
39
+ ]);
27
40
  /**
28
41
  * Shared Centrifuge realtime client that multiplexes public and private protobuf subscriptions across SDK services.
29
42
  */
@@ -35,6 +48,17 @@ var RealtimeClient = class {
35
48
  #privateOrdersLoading = null;
36
49
  #privateOrders = null;
37
50
  #privateOrdersEpoch = 0;
51
+ #connection = {
52
+ public: DISCONNECTED,
53
+ private: DISCONNECTED
54
+ };
55
+ #connectionListeners = /* @__PURE__ */ new Set();
56
+ /** Outage errors already sent to channels as `"transport"`; replayed to late subscribers. */
57
+ #transportErrors = /* @__PURE__ */ new WeakSet();
58
+ /** The non-retryable connection token failure that stops the private socket (code 1). */
59
+ #privateTokenFailure = null;
60
+ /** Token requests wait until then after a 429 with `Retry-After`. */
61
+ #tokenRetryAt = 0;
38
62
  #config;
39
63
  constructor(config) {
40
64
  this.#config = {
@@ -49,13 +73,29 @@ var RealtimeClient = class {
49
73
  async #getAuthHeaders(request) {
50
74
  return this.#config.getAuthHeaders(request);
51
75
  }
76
+ /**
77
+ * Every realtime token request (connection, subscription, private order stream)
78
+ * comes through here, so one wait honors `Retry-After` for all of them; the
79
+ * transport's own reconnect backoff still applies on top.
80
+ */
52
81
  async #fetchToken(url, kind) {
53
- const headers = await this.#getAuthHeaders({
54
- url,
55
- method: "GET"
56
- });
82
+ let headers;
83
+ do {
84
+ for (let wait; (wait = this.#tokenRetryAt - Date.now()) > 0;) await new Promise((resolve) => setTimeout(resolve, wait));
85
+ headers = await this.#getAuthHeaders({
86
+ url,
87
+ method: "GET"
88
+ });
89
+ } while (this.#tokenRetryAt > Date.now());
57
90
  const res = await realtimeFetch(url, { headers });
58
- if (!res.ok) throw errorFromHttpStatus(res.status, `Failed to fetch ${kind} token: ${res.status}`, { status: res.status });
91
+ if (!res.ok) {
92
+ const retryAfterMs = parseRetryAfterHeader(res.headers.get("retry-after"));
93
+ if (res.status === 429 && retryAfterMs !== void 0) this.#tokenRetryAt = Math.max(this.#tokenRetryAt, Date.now() + Math.min(retryAfterMs, MAX_RETRY_AFTER_MS));
94
+ throw errorFromHttpStatus(res.status, `Failed to fetch ${kind} token: ${res.status}`, {
95
+ status: res.status,
96
+ retryAfterMs
97
+ });
98
+ }
59
99
  const json = await res.json();
60
100
  if (!json?.token) throw new InternalServerError(`${kind === "connection" ? "Connection" : "Subscription"} token response had no token`);
61
101
  return json.token;
@@ -65,12 +105,24 @@ var RealtimeClient = class {
65
105
  url.searchParams.set("channel", channel);
66
106
  return this.#fetchToken(url, "subscription");
67
107
  }
108
+ /**
109
+ * Delivers to the consumers registered when it starts: one a handler adds (a resubscribe)
110
+ * is not part of it, and one a handler removes is skipped.
111
+ */
112
+ #emitErrors(recipients, type, error) {
113
+ const deliveries = recipients.map((shared) => ({
114
+ shared,
115
+ ctx: createSdkSubscriptionErrorContext(shared.channel, type, error),
116
+ handlers: Array.from(shared.errorHandlers)
117
+ }));
118
+ for (const { shared, ctx, handlers } of deliveries) for (const handler of handlers) if (shared.errorHandlers.has(handler)) handler(ctx);
119
+ }
68
120
  #emitSubscriptionError(shared, type, error) {
69
- const ctx = createSdkSubscriptionErrorContext(shared.channel, type, error);
70
- for (const handler of shared.errorHandlers) handler(ctx);
121
+ this.#emitErrors([shared], type, error);
71
122
  }
72
123
  #emitConnectionTokenError(error) {
73
- for (const shared of this.#sharedSubs.values()) if (this.#channelKind(shared.channel) === "private") this.#emitSubscriptionError(shared, "connection_token", error);
124
+ const privateSubs = [...this.#sharedSubs.values()].filter((shared) => this.#channelKind(shared.channel) === "private");
125
+ this.#emitErrors(privateSubs, "connection_token", error);
74
126
  }
75
127
  #subscriptionOpts(Centrifuge, shared, attachmentEpoch) {
76
128
  if (this.#channelKind(shared.channel) !== "private") return void 0;
@@ -93,11 +145,7 @@ var RealtimeClient = class {
93
145
  #createPublicClient(Centrifuge) {
94
146
  const client = new Centrifuge(this.#config.wsUrl);
95
147
  this.#publicClient = client;
96
- client.on("disconnected", (ctx) => {
97
- if (this.#publicClient !== client || ctx.code <= 1) return;
98
- this.#publicClient = null;
99
- this.#terminateSubscriptions([...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter((shared) => shared.client === client), "disconnected", ctx);
100
- });
148
+ this.#watchClient(client, "public");
101
149
  client.connect();
102
150
  return client;
103
151
  }
@@ -108,18 +156,85 @@ var RealtimeClient = class {
108
156
  return await this.#fetchToken(this.#config.tokenEndpoint, "connection");
109
157
  } catch (error) {
110
158
  if (this.#privateClient === client) this.#emitConnectionTokenError(error);
111
- if (error instanceof PolyesterError && !error.retryable) throw new Centrifuge.UnauthorizedError(error.message);
159
+ if (error instanceof PolyesterError && !error.retryable) {
160
+ if (this.#privateClient === client) this.#privateTokenFailure = error;
161
+ throw new Centrifuge.UnauthorizedError(error.message);
162
+ }
112
163
  throw error;
113
164
  }
114
165
  } });
115
166
  this.#privateClient = client;
167
+ this.#privateTokenFailure = null;
168
+ this.#watchClient(client, "private");
169
+ client.connect();
170
+ return client;
171
+ }
172
+ #currentClient(kind) {
173
+ return kind === "private" ? this.#privateClient : this.#publicClient;
174
+ }
175
+ #setConnection(kind, status) {
176
+ const current = this.#connection[kind];
177
+ if (current.state === status.state && current.error === status.error) return;
178
+ this.#connection = {
179
+ ...this.#connection,
180
+ [kind]: status
181
+ };
182
+ const connection = this.#connection;
183
+ queueMicrotask(() => {
184
+ for (const listener of Array.from(this.#connectionListeners)) {
185
+ if (this.#connection !== connection) return;
186
+ if (!this.#connectionListeners.has(listener)) continue;
187
+ try {
188
+ listener(connection);
189
+ } catch {}
190
+ }
191
+ });
192
+ }
193
+ #watchClient(client, kind) {
194
+ this.#setConnection(kind, {
195
+ state: "connecting",
196
+ error: null
197
+ });
198
+ client.on("state", ({ newState, oldState }) => {
199
+ if (this.#currentClient(kind) !== client || newState === "disconnected") return;
200
+ const { error } = this.#connection[kind];
201
+ this.#setConnection(kind, {
202
+ state: newState,
203
+ error: newState === "connected" || oldState === "disconnected" ? null : error
204
+ });
205
+ });
206
+ client.on("error", (ctx) => {
207
+ if (this.#currentClient(kind) !== client || !CONNECT_FAILURE_TYPES.has(ctx.type)) return;
208
+ const { code, message } = ctx.error;
209
+ if (ctx.type === "connect" && code === 109) return;
210
+ const current = this.#connection[kind].error;
211
+ if (current && (ctx.type === "connectToken" || this.#transportErrors.has(current))) return;
212
+ const error = new RealtimeError(`Realtime ${kind} connection failed: ${typeof message === "string" && message ? message : ctx.type}`, {
213
+ realtimeCode: typeof code === "number" ? code : 0,
214
+ retryable: true
215
+ });
216
+ this.#setConnection(kind, {
217
+ state: "connecting",
218
+ error
219
+ });
220
+ if (ctx.type === "connectToken") return;
221
+ this.#transportErrors.add(error);
222
+ const affected = [...this.#sharedSubs.values()].filter((shared) => shared.client === client);
223
+ this.#emitErrors(affected, "transport", error);
224
+ });
116
225
  client.on("disconnected", (ctx) => {
117
- if (this.#privateClient !== client || ctx.code <= 1) return;
118
- this.#privateClient = null;
226
+ if (this.#currentClient(kind) !== client || ctx.code === 0) return;
227
+ const tokenFailure = kind === "private" && ctx.code === 1 ? this.#privateTokenFailure : null;
228
+ if (kind === "private") this.#privateTokenFailure = null;
229
+ this.#setConnection(kind, {
230
+ state: "disconnected",
231
+ error: tokenFailure ?? new RealtimeError(ctx.reason || "Realtime connection closed", { realtimeCode: ctx.code })
232
+ });
233
+ if (ctx.code === 1 && kind === "private") return;
234
+ if (kind === "private") this.#privateClient = null;
235
+ else this.#publicClient = null;
119
236
  this.#terminateSubscriptions([...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter((shared) => shared.client === client), "disconnected", ctx);
120
237
  });
121
- client.connect();
122
- return client;
123
238
  }
124
239
  #ensurePublicClient(Centrifuge) {
125
240
  return this.#publicClient ?? this.#createPublicClient(Centrifuge);
@@ -249,16 +364,20 @@ var RealtimeClient = class {
249
364
  if (this.#sharedSubs.get(shared.channel) === shared) this.#sharedSubs.delete(shared.channel);
250
365
  if (this.#pendingTeardowns.get(shared.channel) === shared) this.#pendingTeardowns.delete(shared.channel);
251
366
  this.#teardownSubscription(shared);
252
- shared.publicationHandlers.clear();
253
- shared.subscribedHandlers.clear();
254
- shared.unsubscribedHandlers.clear();
255
- shared.errorHandlers.clear();
367
+ this.#dropConsumers(shared);
256
368
  }
257
369
  for (const { error, errorHandlers, closeHandlers } of notifications) {
258
370
  for (const handler of errorHandlers) handler(error);
259
371
  for (const handler of closeHandlers) handler();
260
372
  }
261
373
  }
374
+ /** Forgets a dropped channel's consumers, so an error delivery in progress skips them. */
375
+ #dropConsumers(shared) {
376
+ shared.publicationHandlers.clear();
377
+ shared.subscribedHandlers.clear();
378
+ shared.unsubscribedHandlers.clear();
379
+ shared.errorHandlers.clear();
380
+ }
262
381
  #teardownSubscription(shared) {
263
382
  const sub = shared.sub;
264
383
  const client = shared.client;
@@ -282,9 +401,10 @@ var RealtimeClient = class {
282
401
  }
283
402
  #disconnectClientIfIdle(kind) {
284
403
  if (this.#hasChannelsForKind(kind)) return;
285
- const client = kind === "private" ? this.#privateClient : this.#publicClient;
404
+ const client = this.#currentClient(kind);
286
405
  if (kind === "private") this.#privateClient = null;
287
406
  else this.#publicClient = null;
407
+ if (client) this.#setConnection(kind, DISCONNECTED);
288
408
  try {
289
409
  client?.disconnect();
290
410
  } catch {}
@@ -302,10 +422,13 @@ var RealtimeClient = class {
302
422
  #disconnectCentrifuge() {
303
423
  const publicClient = this.#publicClient;
304
424
  const privateClient = this.#privateClient;
425
+ for (const shared of [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()]) this.#dropConsumers(shared);
305
426
  this.#pendingTeardowns.clear();
306
427
  this.#sharedSubs.clear();
307
428
  this.#publicClient = null;
308
429
  this.#privateClient = null;
430
+ if (publicClient) this.#setConnection("public", DISCONNECTED);
431
+ if (privateClient) this.#setConnection("private", DISCONNECTED);
309
432
  try {
310
433
  publicClient?.disconnect();
311
434
  } catch {}
@@ -317,15 +440,18 @@ var RealtimeClient = class {
317
440
  this.#disconnectPrivateOrders();
318
441
  const privateClient = this.#privateClient;
319
442
  this.#privateClient = null;
443
+ if (privateClient) this.#setConnection("private", DISCONNECTED);
320
444
  for (const [channel, shared] of this.#sharedSubs) {
321
445
  if (this.#channelKind(channel) !== "private") continue;
322
446
  this.#sharedSubs.delete(channel);
323
447
  this.#teardownSubscription(shared);
448
+ this.#dropConsumers(shared);
324
449
  }
325
450
  for (const [channel, shared] of this.#pendingTeardowns) {
326
451
  if (this.#channelKind(channel) !== "private") continue;
327
452
  this.#pendingTeardowns.delete(channel);
328
453
  this.#teardownSubscription(shared);
454
+ this.#dropConsumers(shared);
329
455
  }
330
456
  try {
331
457
  privateClient?.disconnect();
@@ -353,7 +479,10 @@ var RealtimeClient = class {
353
479
  const errorHandler = handlers.onError;
354
480
  const subscribedHandler = handlers.onSubscribed;
355
481
  const unsubscribedHandler = handlers.onUnsubscribed;
356
- const onError = errorHandler ? (ctx) => this.#callErrorHandler(errorHandler, ctx) : void 0;
482
+ let closed = false;
483
+ const onError = errorHandler ? (ctx) => {
484
+ if (!closed) this.#callErrorHandler(errorHandler, ctx);
485
+ } : void 0;
357
486
  const onPub = (data) => {
358
487
  this.#callConsumerHandler(channel, "publication_handler", () => publicationHandler(data), onError);
359
488
  };
@@ -363,7 +492,10 @@ var RealtimeClient = class {
363
492
  lastSubscribedEpoch = subscriptionEpoch;
364
493
  this.#callConsumerHandler(channel, "subscribed_handler", subscribedHandler, onError);
365
494
  } : void 0;
366
- const onUnsubscribed = unsubscribedHandler ? () => this.#callConsumerHandler(channel, "unsubscribed_handler", unsubscribedHandler, onError) : void 0;
495
+ const onUnsubscribed = unsubscribedHandler ? () => {
496
+ if (closed) return;
497
+ this.#callConsumerHandler(channel, "unsubscribed_handler", unsubscribedHandler, onError);
498
+ } : void 0;
367
499
  shared.publicationHandlers.add(onPub);
368
500
  if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);
369
501
  if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);
@@ -376,7 +508,14 @@ var RealtimeClient = class {
376
508
  if (resubscribe) shared.sub?.subscribe();
377
509
  }
378
510
  }
379
- let closed = false;
511
+ const outage = this.#connection[this.#channelKind(channel)].error;
512
+ if (onError && outage && this.#transportErrors.has(outage)) {
513
+ const ctx = createSdkSubscriptionErrorContext(channel, "transport", outage);
514
+ queueMicrotask(() => {
515
+ if (closed || this.#connection[this.#channelKind(channel)].error !== outage) return;
516
+ onError(ctx);
517
+ });
518
+ }
380
519
  if (onSubscribed && shared.sub?.state === "subscribed") {
381
520
  const subscriptionEpoch = shared.subscriptionEpoch;
382
521
  queueMicrotask(() => {
@@ -499,8 +638,18 @@ var RealtimeClient = class {
499
638
  disconnectPrivate() {
500
639
  this.#disconnectPrivate();
501
640
  }
502
- get isConnected() {
503
- return this.#publicClient !== null || this.#privateClient !== null || (this.#privateOrders?.activeChannels ?? 0) > 0;
641
+ /**
642
+ * Status of the public and private sockets. A socket that cannot connect stays
643
+ * `"connecting"` with `error` set, and every channel on it gets one `"transport"`
644
+ * error per outage. Private order streams run on their own socket and are not included.
645
+ */
646
+ get connection() {
647
+ return this.#connection;
648
+ }
649
+ /** Calls `listener` with the current {@link connection} after it changes, in a microtask; a status replaced before then is skipped. Returns an unsubscribe function. */
650
+ onConnectionChange(listener) {
651
+ this.#connectionListeners.add(listener);
652
+ return () => this.#connectionListeners.delete(listener);
504
653
  }
505
654
  get activeChannels() {
506
655
  return this.#sharedSubs.size + (this.#privateOrders?.activeChannels ?? 0);