@polyester/sdk 0.19.2 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/dist/gen/auth/v1/social_verification_pb.d.ts +4 -2
- package/dist/gen/auth/v1/social_verification_pb.d.ts.map +1 -1
- package/dist/gen/auth/v1/social_verification_pb.js.map +1 -1
- package/dist/gen/auth/v1/subaccounts_pb.d.ts +1 -1
- package/dist/gen/auth/v1/subaccounts_pb.js +1 -1
- package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts +290 -2
- package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts.map +1 -1
- package/dist/gen/chain/withdraw/v1/withdraw_pb.js +288 -9
- package/dist/gen/chain/withdraw/v1/withdraw_pb.js.map +1 -1
- package/dist/gen/index.d.ts +10 -10
- package/dist/gen/index.js +7 -7
- package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts +1 -1
- package/dist/gen/ledger/read/v1/ledger_read_pb.js +1 -1
- package/dist/gen/orderbook/v1/orderbook_pb.d.ts +5 -3
- package/dist/gen/orderbook/v1/orderbook_pb.d.ts.map +1 -1
- package/dist/gen/orderbook/v1/orderbook_pb.js.map +1 -1
- package/dist/gen/orders/v1/orders_pb.d.ts +14 -6
- package/dist/gen/orders/v1/orders_pb.d.ts.map +1 -1
- package/dist/gen/orders/v1/orders_pb.js +7 -1
- package/dist/gen/orders/v1/orders_pb.js.map +1 -1
- package/dist/gen/orders/v1/orders_read_pb.d.ts +1 -1
- package/dist/gen/orders/v1/orders_read_pb.js +2 -2
- package/dist/gen/transfer/v1/internal_transfer_pb.d.ts +200 -2
- package/dist/gen/transfer/v1/internal_transfer_pb.d.ts.map +1 -1
- package/dist/gen/transfer/v1/internal_transfer_pb.js +193 -4
- package/dist/gen/transfer/v1/internal_transfer_pb.js.map +1 -1
- package/dist/gen/triggers/v1/triggers_pb.d.ts +47 -2
- package/dist/gen/triggers/v1/triggers_pb.d.ts.map +1 -1
- package/dist/gen/triggers/v1/triggers_pb.js +1 -1
- package/dist/gen/triggers/v1/triggers_pb.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -2
- package/dist/realtime/client.d.ts.map +1 -1
- package/dist/realtime/client.js +11 -4
- package/dist/realtime/client.js.map +1 -1
- package/dist/services/auth/profile/profile.js +1 -1
- package/dist/services/balances/balances.js +1 -1
- package/dist/services/balances/balances.schemas.js +1 -1
- package/dist/services/candles/candles.schemas.d.ts +10 -10
- package/dist/services/heatmap/heatmap.schemas.d.ts +13 -13
- package/dist/services/internal-transfers/internal-transfers.js +1 -1
- package/dist/services/market-overview/market-overview.js +1 -1
- package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
- package/dist/services/market-overview/market-overview.schemas.js +1 -1
- package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
- package/dist/services/orders/index.d.ts +1 -1
- package/dist/services/orders/order-errors.schemas.d.ts +1 -1
- package/dist/services/orders/orders-batch.schemas.d.ts +20 -20
- package/dist/services/orders/orders-batch.schemas.js +1 -1
- package/dist/services/orders/orders-input.schemas.d.ts +6 -6
- package/dist/services/orders/orders-input.schemas.js +2 -2
- package/dist/services/orders/orders-input.schemas.js.map +1 -1
- package/dist/services/orders/orders-output.schemas.d.ts +6 -6
- package/dist/services/orders/orders.d.ts +1 -1
- package/dist/services/orders/orders.d.ts.map +1 -1
- package/dist/services/orders/orders.js +5 -3
- package/dist/services/orders/orders.js.map +1 -1
- package/dist/services/orders/orders.schemas.d.ts +1 -1
- package/dist/services/orders/orders.types.d.ts +1 -1
- package/dist/services/subaccounts/subaccounts.schemas.d.ts +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.d.ts +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.js +1 -1
- package/dist/services/trading-withdraws/trading-withdraws.schemas.js +1 -1
- package/dist/services/transfers/transfers.js +1 -1
- package/dist/services/transfers/transfers.schemas.js +1 -1
- package/dist/services/triggers/trigger-child-order.schemas.js +25 -4
- package/dist/services/triggers/trigger-child-order.schemas.js.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.d.ts +39 -3
- package/dist/services/triggers/trigger-input.schemas.d.ts.map +1 -1
- package/dist/services/triggers/trigger-input.schemas.js +3 -26
- package/dist/services/triggers/trigger-input.schemas.js.map +1 -1
- package/dist/services/triggers/triggers-output.schemas.d.ts +92 -17
- package/dist/services/triggers/triggers-output.schemas.d.ts.map +1 -1
- package/dist/services/triggers/triggers-output.schemas.js +36 -25
- package/dist/services/triggers/triggers-output.schemas.js.map +1 -1
- package/dist/shared/connect-error-mapping.d.ts.map +1 -1
- package/dist/shared/connect-error-mapping.js +50 -50
- package/dist/shared/connect-error-mapping.js.map +1 -1
- package/dist/shared/error-detail.d.ts +37 -0
- package/dist/shared/error-detail.d.ts.map +1 -0
- package/dist/shared/error-detail.js +106 -0
- package/dist/shared/error-detail.js.map +1 -0
- package/dist/shared/errors.d.ts +11 -6
- package/dist/shared/errors.d.ts.map +1 -1
- package/dist/shared/errors.js +3 -1
- package/dist/shared/errors.js.map +1 -1
- package/dist/utils/errors.d.ts.map +1 -1
- package/dist/utils/errors.js +1 -15
- package/dist/utils/errors.js.map +1 -1
- package/dist/wired-services.js +5 -5
- package/package.json +1 -1
- package/dist/utils/connect-order-errors.d.ts +0 -15
- package/dist/utils/connect-order-errors.d.ts.map +0 -1
- package/dist/utils/connect-order-errors.js +0 -41
- package/dist/utils/connect-order-errors.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -4,7 +4,6 @@ import { connectErrorToPolyesterError, createErrorMappingInterceptor, toPolyeste
|
|
|
4
4
|
import { checksumEvmAddress, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, isEvmAddress, isEvmAddressStrict, keccak256Hex } from "./utils/evm.js";
|
|
5
5
|
import { POLYESTER_TESTNET_ENVIRONMENT, createPolyesterEnvironment } from "./environment.js";
|
|
6
6
|
import { formatConnectError, formatUserFacingError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError } from "./utils/errors.js";
|
|
7
|
-
import { getOrderErrorDetail, isStaleQuoteError } from "./utils/connect-order-errors.js";
|
|
8
7
|
import { compareUnsignedIntegerStrings, shouldApplyReconciliationUpdate } from "./shared/reconciliation.js";
|
|
9
8
|
import { mergeLedgerBalances } from "./services/balances/balances.merge.js";
|
|
10
9
|
import { validateCreateAddressBookEntryInput } from "./services/address-book/address-book.schemas.js";
|
|
@@ -15,4 +14,4 @@ import { PolyesterBrowserClient } from "./browser-client.js";
|
|
|
15
14
|
import { PolyesterServerClient, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest } from "./server-client.js";
|
|
16
15
|
import { isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isSessionElevationRequiredError } from "./utils/connect-mfa-errors.js";
|
|
17
16
|
import { columnarTimestampSecAt, expandColumnarTimestampsSec } from "./utils/columnar-time.js";
|
|
18
|
-
export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterBrowserClient, PolyesterClient, PolyesterError, PolyesterServerClient, PreconditionFailedError, RateLimitError, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, TimeoutError, TransientError, ValidationError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError,
|
|
17
|
+
export { AlreadyExistsError, AuthenticationError, ConfigurationError, InternalServerError, MfaEnrollmentRequiredError, MfaLastFactorRequiredError, MfaRequiredError, MfaVerificationError, NetworkError, POLYESTER_AUTH_TOKEN_COOKIE_NAME, POLYESTER_SESSION_COOKIE_NAME, POLYESTER_TESTNET_ENVIRONMENT, PermissionError, PolicyInUseError, PolicyLockedError, PolicyScopeMismatchError, PolyesterBrowserClient, PolyesterClient, PolyesterError, PolyesterServerClient, PreconditionFailedError, RateLimitError, RequestError, ResourceNotFoundError, RevisionConflictError, ServiceUnavailableError, SessionElevationRequiredError, StaleQuoteError, StepUpRequiredError, TimeoutError, TransientError, ValidationError, checksumEvmAddress, columnarTimestampSecAt, compareUnsignedIntegerStrings, connectErrorToPolyesterError, createCookieAuthTokenStorage, createErrorMappingInterceptor, createMemoryAuthTokenStorage, createPolyesterEnvironment, createPolyesterServerClientFromCookies, createPolyesterServerClientFromRequest, errorFromHttpStatus, evmHexToBytes, evmUtf8ToBytes, evmUtf8ToHex, expandColumnarTimestampsSec, formatConnectError, formatUserFacingError, isAbortError, isEvmAddress, isEvmAddressStrict, isFreshStepUpRequiredError, isMfaEnrollmentRequiredError, isMfaLastFactorRequiredError, isPolicyInUseError, isPolicyLockedError, isPolicyScopeMismatchError, isResourceNotFoundError, isRetryableError, isRevisionConflictError, isSessionElevationRequiredError, keccak256Hex, mergeLedgerBalances, normalizeErrorMessage, shouldApplyReconciliationUpdate, tsObjToNsString as timestampToNanoseconds, toPolyesterError, validateCreateAddressBookEntryInput };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","names":[],"sources":["../../src/realtime/client.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"client.d.ts","names":[],"sources":["../../src/realtime/client.ts"],"mappings":";;;;UA2EiB;EACb,cAAc;EACd;;UAGa;EACb;EACA;EACA;EACA,kBAAkB,SAAS,wBAAwB,QAAQ,eAAe;EAC1E"}
|
package/dist/realtime/client.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AuthenticationError, InternalServerError, errorFromHttpStatus } from "../shared/errors.js";
|
|
1
|
+
import { AuthenticationError, InternalServerError, PolyesterError, errorFromHttpStatus } from "../shared/errors.js";
|
|
2
2
|
import { makeFetch } from "../shared/transports.js";
|
|
3
3
|
import { createSdkSubscriptionErrorContext, fromCentrifugeSubscriptionError } from "../shared/subscription-errors.js";
|
|
4
4
|
import { decodeProtoFrame } from "../utils/streams.js";
|
|
@@ -52,7 +52,7 @@ var RealtimeClient = class {
|
|
|
52
52
|
#emitConnectionTokenError(error) {
|
|
53
53
|
for (const shared of this.#sharedSubs.values()) if (this.#channelKind(shared.channel) === "private") this.#emitSubscriptionError(shared, "connection_token", error);
|
|
54
54
|
}
|
|
55
|
-
#subscriptionOpts(shared, attachmentEpoch) {
|
|
55
|
+
#subscriptionOpts(Centrifuge, shared, attachmentEpoch) {
|
|
56
56
|
if (this.#channelKind(shared.channel) !== "private") return void 0;
|
|
57
57
|
return { getToken: async () => {
|
|
58
58
|
try {
|
|
@@ -69,6 +69,7 @@ var RealtimeClient = class {
|
|
|
69
69
|
return json.token;
|
|
70
70
|
} catch (error) {
|
|
71
71
|
if (shared.attachmentEpoch === attachmentEpoch) this.#emitSubscriptionError(shared, "subscription_token", error);
|
|
72
|
+
if (error instanceof PolyesterError && !error.retryable) throw new Centrifuge.UnauthorizedError(error.message);
|
|
72
73
|
throw error;
|
|
73
74
|
}
|
|
74
75
|
} };
|
|
@@ -108,6 +109,7 @@ var RealtimeClient = class {
|
|
|
108
109
|
return json.token;
|
|
109
110
|
} catch (error) {
|
|
110
111
|
if (this.#privateClient === client) this.#emitConnectionTokenError(error);
|
|
112
|
+
if (error instanceof PolyesterError && !error.retryable) throw new Centrifuge.UnauthorizedError(error.message);
|
|
111
113
|
throw error;
|
|
112
114
|
}
|
|
113
115
|
} });
|
|
@@ -170,7 +172,7 @@ var RealtimeClient = class {
|
|
|
170
172
|
}
|
|
171
173
|
#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch) {
|
|
172
174
|
const client = this.#ensureClientForChannel(Centrifuge, shared.channel);
|
|
173
|
-
const sub = client.newSubscription(shared.channel, this.#subscriptionOpts(shared, attachmentEpoch));
|
|
175
|
+
const sub = client.newSubscription(shared.channel, this.#subscriptionOpts(Centrifuge, shared, attachmentEpoch));
|
|
174
176
|
shared.sub = sub;
|
|
175
177
|
shared.client = client;
|
|
176
178
|
sub.on("publication", (ctx) => {
|
|
@@ -303,7 +305,8 @@ var RealtimeClient = class {
|
|
|
303
305
|
/**
|
|
304
306
|
* Subscribes to a realtime channel and returns an unsubscribe function. Missing
|
|
305
307
|
* authentication is reported to `onError`, or thrown synchronously when no error
|
|
306
|
-
* observer is provided.
|
|
308
|
+
* observer is provided. Non-retryable token failures stop automatic retries;
|
|
309
|
+
* calling subscribe again after correcting the failure restarts private realtime.
|
|
307
310
|
*/
|
|
308
311
|
subscribe(channel, handlers) {
|
|
309
312
|
let shared;
|
|
@@ -336,6 +339,10 @@ var RealtimeClient = class {
|
|
|
336
339
|
if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);
|
|
337
340
|
if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);
|
|
338
341
|
if (onError) shared.errorHandlers.add(onError);
|
|
342
|
+
if (this.#channelKind(channel) === "private" && this.#hasAuth()) {
|
|
343
|
+
if (shared.client?.state === "disconnected") shared.client.connect();
|
|
344
|
+
if (shared.sub?.state === "unsubscribed") shared.sub.subscribe();
|
|
345
|
+
}
|
|
339
346
|
let closed = false;
|
|
340
347
|
if (onSubscribed && shared.sub?.state === "subscribed") {
|
|
341
348
|
const subscriptionEpoch = shared.subscriptionEpoch;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":["#config","#getAuthHeaders","#sharedSubs","#channelKind","#emitSubscriptionError","#publicClient","#connectionHandlers","#privateClient","#emitConnectionTokenError","#createPublicClient","#hasAuth","#createPrivateClient","#assertChannelAuth","#ensurePrivateClient","#ensurePublicClient","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#pendingTeardowns","#attachSubscription","#callErrorHandler","#disconnectClientIfIdle","#hasChannelsForKind","#teardownSubscription","#getOrCreateSubscription","#callConsumerHandler","#disconnect","#disconnectPrivate"],"sources":["../../src/realtime/client.ts"],"sourcesContent":["import { fromBinary, type DescMessage, type MessageShape } from \"@bufbuild/protobuf\";\nimport type {\n Centrifuge,\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 { AuthenticationError, errorFromHttpStatus, InternalServerError } from \"../shared/errors.js\";\nimport { makeFetch } from \"../shared/transports.js\";\nimport { decodeProtoFrame } from \"../utils/streams.js\";\nimport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\nconst realtimeFetch = makeFetch();\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 getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth?: () => boolean;\n}\n\ntype ResolvedRealtimeConfig = Pick<\n RealtimeConfig,\n \"wsUrl\" | \"tokenEndpoint\" | \"subscribeEndpoint\"\n> & {\n getAuthHeaders: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth: () => boolean;\n};\n\nexport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\ntype ConnectionHandler = { onConnected?: () => void; onDisconnected?: () => void };\ntype PublicationHandler<T = unknown> = (data: T) => void;\ntype ErrorHandler = (ctx: SdkSubscriptionErrorContext) => void;\ntype RealtimeClientKind = \"public\" | \"private\";\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 #connectionHandlers = new Set<ConnectionHandler>();\n #sharedSubs = new Map<string, SharedSubscription>();\n #pendingTeardowns = new Map<string, SharedSubscription>();\n readonly #config: ResolvedRealtimeConfig;\n\n constructor(config: RealtimeConfig) {\n this.#config = {\n wsUrl: config.wsUrl,\n tokenEndpoint: config.tokenEndpoint,\n subscribeEndpoint: config.subscribeEndpoint,\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 #emitSubscriptionError(shared: SharedSubscription, type: string, error: unknown): void {\n const ctx = createSdkSubscriptionErrorContext(shared.channel, type, error);\n for (const handler of shared.errorHandlers) {\n handler(ctx);\n }\n }\n\n #emitConnectionTokenError(error: unknown): void {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === \"private\") {\n this.#emitSubscriptionError(shared, \"connection_token\", error);\n }\n }\n }\n\n #subscriptionOpts(shared: SharedSubscription, attachmentEpoch: number) {\n if (this.#channelKind(shared.channel) !== \"private\") return undefined;\n return {\n getToken: async () => {\n try {\n const url = new URL(this.#config.subscribeEndpoint);\n url.searchParams.set(\"channel\", shared.channel);\n const headers = await this.#getAuthHeaders({ url, method: \"GET\" });\n const res = await realtimeFetch(url, { headers });\n if (!res.ok) {\n throw errorFromHttpStatus(\n res.status,\n `Failed to fetch subscription token: ${res.status}`,\n );\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\"Subscription token response had no token\");\n }\n return json.token;\n } catch (error) {\n if (shared.attachmentEpoch === attachmentEpoch) {\n this.#emitSubscriptionError(shared, \"subscription_token\", error);\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\n client.on(\"connected\", () => {\n if (this.#publicClient !== client) return;\n for (const h of this.#connectionHandlers) h.onConnected?.();\n });\n client.on(\"disconnected\", () => {\n if (this.#publicClient !== client) return;\n for (const h of this.#connectionHandlers) h.onDisconnected?.();\n });\n\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 const headers = await this.#getAuthHeaders({\n url: this.#config.tokenEndpoint,\n method: \"GET\",\n });\n const res = await realtimeFetch(this.#config.tokenEndpoint, {\n headers,\n });\n if (!res.ok) {\n throw errorFromHttpStatus(\n res.status,\n `Failed to fetch connection token: ${res.status}`,\n );\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\"Connection token response had no token\");\n }\n return json.token;\n } catch (error) {\n if (this.#privateClient === client) {\n this.#emitConnectionTokenError(error);\n }\n throw error;\n }\n },\n };\n\n client = new Centrifuge(this.#config.wsUrl, opts);\n this.#privateClient = client;\n\n client.on(\"connected\", () => {\n if (this.#privateClient !== client) return;\n for (const h of this.#connectionHandlers) h.onConnected?.();\n });\n client.on(\"disconnected\", () => {\n if (this.#privateClient !== client) return;\n for (const h of this.#connectionHandlers) h.onDisconnected?.();\n });\n\n client.connect();\n return client;\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #ensurePrivateClient(Centrifuge: CentrifugeCtor): Centrifuge {\n if (!this.#hasAuth()) {\n throw new AuthenticationError(\n \"Cannot create authenticated realtime client without authentication\",\n );\n }\n return this.#privateClient ?? this.#createPrivateClient(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 this.#assertChannelAuth(channel);\n if (this.#channelKind(channel) === \"private\") {\n return this.#ensurePrivateClient(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.#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(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\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\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 #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 = kind === \"private\" ? this.#privateClient : this.#publicClient;\n if (kind === \"private\") {\n this.#privateClient = null;\n } else {\n this.#publicClient = null;\n }\n\n try {\n client?.disconnect();\n } catch {\n // noop\n }\n }\n\n #disconnect(): void {\n const publicClient = this.#publicClient;\n const privateClient = this.#privateClient;\n\n this.#pendingTeardowns.clear();\n this.#sharedSubs.clear();\n this.#publicClient = null;\n this.#privateClient = null;\n\n try {\n publicClient?.disconnect();\n } catch {\n // noop\n }\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n this.#connectionHandlers.clear();\n }\n\n #disconnectPrivate(): void {\n const privateClient = this.#privateClient;\n this.#privateClient = null;\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 }\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 }\n\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n /**\n * Subscribes to a realtime channel and returns an unsubscribe function. Missing\n * authentication is reported to `onError`, or thrown synchronously when no error\n * observer is provided.\n */\n subscribe<T>(channel: string, handlers: SubscribeHandlers<T>): () => void {\n let shared: SharedSubscription;\n try {\n shared = this.#getOrCreateSubscription(channel);\n } catch (error) {\n if (!(error instanceof AuthenticationError)) throw error;\n if (!handlers.onError) throw error;\n\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => this.#callErrorHandler(handlers.onError, ctx));\n return () => {};\n }\n shared.consumers++;\n\n const publicationHandler = handlers.onPublication;\n const errorHandler = handlers.onError;\n const subscribedHandler = handlers.onSubscribed;\n const unsubscribedHandler = handlers.onUnsubscribed;\n\n const onError: ErrorHandler | undefined = errorHandler\n ? (ctx) => this.#callErrorHandler(errorHandler, ctx)\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 this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n unsubscribedHandler,\n onError,\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 let closed = false;\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.#disconnect();\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 * 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 get isConnected(): boolean {\n return this.#publicClient !== null || this.#privateClient !== null;\n }\n\n get activeChannels(): number {\n return this.#sharedSubs.size;\n }\n\n get totalConsumers(): number {\n let total = 0;\n for (const shared of this.#sharedSubs.values()) {\n total += shared.consumers;\n }\n return total;\n }\n}\n"],"mappings":";;;;;;AAkBA,MAAM,gBAAgB,UAAU;AAKhC,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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OAAO;KACZ,KAAKA,kBACD,OAAO,SACP,kCAAkC,OAAO,SAAS,UAAU,KAAK,CACrE;KACA;IACJ;IACA,IAAI,CAAC,KAAK;KACN,KAAKA,kBACD,OAAO,SACP,kCACI,OAAO,SACP,UACA,iCACJ,CACJ;KACA;IACJ;IACA,OAAO,cAAc,GAAG;GAC5B;GACA,cAAc,OAAO;GACrB,gBAAgB,OAAO;GACvB,SAAS,OAAO;EACpB,CAAC;CACL;;;;CAKA,aAAmB;EACf,KAAKM,YAAY;CACrB;;;;CAKA,oBAA0B;EACtB,KAAKC,mBAAmB;CAC5B;CAEA,IAAI,cAAuB;EACvB,OAAO,KAAKvB,kBAAkB,QAAQ,KAAKE,mBAAmB;CAClE;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKL,YAAY;CAC5B;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ;EACZ,KAAK,MAAM,UAAU,KAAKA,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
|
|
1
|
+
{"version":3,"file":"client.js","names":["#config","#getAuthHeaders","#sharedSubs","#channelKind","#emitSubscriptionError","#publicClient","#connectionHandlers","#privateClient","#emitConnectionTokenError","#createPublicClient","#hasAuth","#createPrivateClient","#assertChannelAuth","#ensurePrivateClient","#ensurePublicClient","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#pendingTeardowns","#attachSubscription","#callErrorHandler","#disconnectClientIfIdle","#hasChannelsForKind","#teardownSubscription","#getOrCreateSubscription","#callConsumerHandler","#disconnect","#disconnectPrivate"],"sources":["../../src/realtime/client.ts"],"sourcesContent":["import { fromBinary, type DescMessage, type MessageShape } from \"@bufbuild/protobuf\";\nimport type {\n Centrifuge,\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} from \"../shared/errors.js\";\nimport { makeFetch } from \"../shared/transports.js\";\nimport { decodeProtoFrame } from \"../utils/streams.js\";\nimport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\nconst realtimeFetch = makeFetch();\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 getAuthHeaders?: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth?: () => boolean;\n}\n\ntype ResolvedRealtimeConfig = Pick<\n RealtimeConfig,\n \"wsUrl\" | \"tokenEndpoint\" | \"subscribeEndpoint\"\n> & {\n getAuthHeaders: (request: RealtimeAuthRequest) => Promise<HeadersInit> | HeadersInit;\n hasAuth: () => boolean;\n};\n\nexport type { ConnectChannelParams, PolyesterRealtime, SubscribeHandlers } from \"./types.js\";\n\ntype ConnectionHandler = { onConnected?: () => void; onDisconnected?: () => void };\ntype PublicationHandler<T = unknown> = (data: T) => void;\ntype ErrorHandler = (ctx: SdkSubscriptionErrorContext) => void;\ntype RealtimeClientKind = \"public\" | \"private\";\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 #connectionHandlers = new Set<ConnectionHandler>();\n #sharedSubs = new Map<string, SharedSubscription>();\n #pendingTeardowns = new Map<string, SharedSubscription>();\n readonly #config: ResolvedRealtimeConfig;\n\n constructor(config: RealtimeConfig) {\n this.#config = {\n wsUrl: config.wsUrl,\n tokenEndpoint: config.tokenEndpoint,\n subscribeEndpoint: config.subscribeEndpoint,\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 #emitSubscriptionError(shared: SharedSubscription, type: string, error: unknown): void {\n const ctx = createSdkSubscriptionErrorContext(shared.channel, type, error);\n for (const handler of shared.errorHandlers) {\n handler(ctx);\n }\n }\n\n #emitConnectionTokenError(error: unknown): void {\n for (const shared of this.#sharedSubs.values()) {\n if (this.#channelKind(shared.channel) === \"private\") {\n this.#emitSubscriptionError(shared, \"connection_token\", error);\n }\n }\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 const url = new URL(this.#config.subscribeEndpoint);\n url.searchParams.set(\"channel\", shared.channel);\n const headers = await this.#getAuthHeaders({ url, method: \"GET\" });\n const res = await realtimeFetch(url, { headers });\n if (!res.ok) {\n throw errorFromHttpStatus(\n res.status,\n `Failed to fetch subscription token: ${res.status}`,\n );\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\"Subscription token response had no token\");\n }\n return json.token;\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\n client.on(\"connected\", () => {\n if (this.#publicClient !== client) return;\n for (const h of this.#connectionHandlers) h.onConnected?.();\n });\n client.on(\"disconnected\", () => {\n if (this.#publicClient !== client) return;\n for (const h of this.#connectionHandlers) h.onDisconnected?.();\n });\n\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 const headers = await this.#getAuthHeaders({\n url: this.#config.tokenEndpoint,\n method: \"GET\",\n });\n const res = await realtimeFetch(this.#config.tokenEndpoint, {\n headers,\n });\n if (!res.ok) {\n throw errorFromHttpStatus(\n res.status,\n `Failed to fetch connection token: ${res.status}`,\n );\n }\n const json = (await res.json()) as { token?: string };\n if (!json?.token) {\n throw new InternalServerError(\"Connection token response had no token\");\n }\n return json.token;\n } catch (error) {\n if (this.#privateClient === client) {\n this.#emitConnectionTokenError(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 client = new Centrifuge(this.#config.wsUrl, opts);\n this.#privateClient = client;\n\n client.on(\"connected\", () => {\n if (this.#privateClient !== client) return;\n for (const h of this.#connectionHandlers) h.onConnected?.();\n });\n client.on(\"disconnected\", () => {\n if (this.#privateClient !== client) return;\n for (const h of this.#connectionHandlers) h.onDisconnected?.();\n });\n\n client.connect();\n return client;\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #ensurePrivateClient(Centrifuge: CentrifugeCtor): Centrifuge {\n if (!this.#hasAuth()) {\n throw new AuthenticationError(\n \"Cannot create authenticated realtime client without authentication\",\n );\n }\n return this.#privateClient ?? this.#createPrivateClient(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 this.#assertChannelAuth(channel);\n if (this.#channelKind(channel) === \"private\") {\n return this.#ensurePrivateClient(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.#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\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\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 #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 = kind === \"private\" ? this.#privateClient : this.#publicClient;\n if (kind === \"private\") {\n this.#privateClient = null;\n } else {\n this.#publicClient = null;\n }\n\n try {\n client?.disconnect();\n } catch {\n // noop\n }\n }\n\n #disconnect(): void {\n const publicClient = this.#publicClient;\n const privateClient = this.#privateClient;\n\n this.#pendingTeardowns.clear();\n this.#sharedSubs.clear();\n this.#publicClient = null;\n this.#privateClient = null;\n\n try {\n publicClient?.disconnect();\n } catch {\n // noop\n }\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n this.#connectionHandlers.clear();\n }\n\n #disconnectPrivate(): void {\n const privateClient = this.#privateClient;\n this.#privateClient = null;\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 }\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 }\n\n try {\n privateClient?.disconnect();\n } catch {\n // noop\n }\n }\n\n /**\n * Subscribes to a realtime channel and returns an unsubscribe function. Missing\n * authentication is reported to `onError`, or thrown synchronously when no error\n * observer is provided. Non-retryable token failures stop automatic retries;\n * calling subscribe again after correcting the failure restarts private realtime.\n */\n subscribe<T>(channel: string, handlers: SubscribeHandlers<T>): () => void {\n let shared: SharedSubscription;\n try {\n shared = this.#getOrCreateSubscription(channel);\n } catch (error) {\n if (!(error instanceof AuthenticationError)) throw error;\n if (!handlers.onError) throw error;\n\n const ctx = createSdkSubscriptionErrorContext(channel, \"auth\", error);\n queueMicrotask(() => this.#callErrorHandler(handlers.onError, ctx));\n return () => {};\n }\n shared.consumers++;\n\n const publicationHandler = handlers.onPublication;\n const errorHandler = handlers.onError;\n const subscribedHandler = handlers.onSubscribed;\n const unsubscribedHandler = handlers.onUnsubscribed;\n\n const onError: ErrorHandler | undefined = errorHandler\n ? (ctx) => this.#callErrorHandler(errorHandler, ctx)\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 this.#callConsumerHandler(\n channel,\n \"unsubscribed_handler\",\n unsubscribedHandler,\n onError,\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\" && this.#hasAuth()) {\n if (shared.client?.state === \"disconnected\") shared.client.connect();\n if (shared.sub?.state === \"unsubscribed\") shared.sub.subscribe();\n }\n\n let closed = false;\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.#disconnect();\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 * 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 get isConnected(): boolean {\n return this.#publicClient !== null || this.#privateClient !== null;\n }\n\n get activeChannels(): number {\n return this.#sharedSubs.size;\n }\n\n get totalConsumers(): number {\n let total = 0;\n for (const shared of this.#sharedSubs.values()) {\n total += shared.consumers;\n }\n return total;\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAM,gBAAgB,UAAU;AAKhC,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;;;;AA8CA,IAAa,iBAAb,MAAyD;CACrD,gBAA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Ac,OAAO;GAChC;GACA,cAAc,OAAO;GACrB,gBAAgB,OAAO;GACvB,SAAS,OAAO;EACpB,CAAC;CACL;;;;CAKA,oBAA2C,QAA6C;EACpF,OAAO,KAAK,UAAwC,OAAO,SAAS;GAChE,gBAAgB,SAAS;IACrB,IAAI;IACJ,IAAI;KACA,MAAM,iBAAiB,OAAO,QAAQ,IAAI;IAC9C,SAAS,OAAO;KACZ,KAAKA,kBACD,OAAO,SACP,kCAAkC,OAAO,SAAS,UAAU,KAAK,CACrE;KACA;IACJ;IACA,IAAI,CAAC,KAAK;KACN,KAAKA,kBACD,OAAO,SACP,kCACI,OAAO,SACP,UACA,iCACJ,CACJ;KACA;IACJ;IACA,OAAO,cAAc,GAAG;GAC5B;GACA,cAAc,OAAO;GACrB,gBAAgB,OAAO;GACvB,SAAS,OAAO;EACpB,CAAC;CACL;;;;CAKA,aAAmB;EACf,KAAKM,YAAY;CACrB;;;;CAKA,oBAA0B;EACtB,KAAKC,mBAAmB;CAC5B;CAEA,IAAI,cAAuB;EACvB,OAAO,KAAKvB,kBAAkB,QAAQ,KAAKE,mBAAmB;CAClE;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKL,YAAY;CAC5B;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ;EACZ,KAAK,MAAM,UAAU,KAAKA,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { AccountIdentitySchema, ProfileService as ProfileService$1 } from "../../../gen/auth/v1/profile_pb.js";
|
|
1
2
|
import { parse } from "../../../shared/validation.js";
|
|
2
3
|
import { toConnectCallOptions } from "../../../shared/request-options.js";
|
|
3
4
|
import { removeUndefined } from "../../../utils/remove-undefined.js";
|
|
4
|
-
import { AccountIdentitySchema, ProfileService as ProfileService$1 } from "../../../gen/auth/v1/profile_pb.js";
|
|
5
5
|
import { AccountIdentitySchema as AccountIdentitySchema$1, ClaimGeneratedUsernameInputSchema, GeneratedUsernameOfferSchema, ProfileSchema, UpdateProfileInputSchema, UsernameHistoryEntrySchema } from "./profile.schemas.js";
|
|
6
6
|
import { createClient } from "@connectrpc/connect";
|
|
7
7
|
import * as v from "valibot";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { AssetBalanceSchema, LedgerReadService } from "../../gen/ledger/read/v1/ledger_read_pb.js";
|
|
1
2
|
import { parse } from "../../shared/validation.js";
|
|
2
3
|
import { toConnectCallOptions } from "../../shared/request-options.js";
|
|
3
4
|
import { resolveAccountScopedInput } from "../subaccount-resolver.js";
|
|
4
5
|
import { accountScopeToSubaccountId } from "../../shared/account-scope.js";
|
|
5
|
-
import { AssetBalanceSchema, LedgerReadService } from "../../gen/ledger/read/v1/ledger_read_pb.js";
|
|
6
6
|
import { connectReadyGatedProtoChannel } from "../../realtime/ready-gated-subscription.js";
|
|
7
7
|
import { BalanceHistoryInputSchema, BalancesListInputSchema, EquityHistoryInputSchema, PortfolioEquityHistoryInputSchema, createBalanceHistoryResponseSchema, createEquityHistoryResponseSchema, createLedgerBalanceSchema, createPortfolioEquityHistoryResponseSchema, createPortfolioEquitySnapshotResponseSchema } from "./balances.schemas.js";
|
|
8
8
|
import { createClient } from "@connectrpc/connect";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { BalanceRange } from "../../gen/ledger/read/v1/ledger_read_pb.js";
|
|
1
2
|
import { requiredEnumLabel } from "../../shared/proto-enum-codec.js";
|
|
2
3
|
import { PublicIdSchema } from "../../shared/schemas.js";
|
|
3
4
|
import { AccountScopeInputEntries, accountScopeToSubaccountId } from "../../shared/account-scope.js";
|
|
4
|
-
import { BalanceRange } from "../../gen/ledger/read/v1/ledger_read_pb.js";
|
|
5
5
|
import { scaledToDecimalOutput } from "../../shared/decimal-surface.js";
|
|
6
6
|
import { fromU128 } from "../../utils/u128.js";
|
|
7
7
|
import { ACCOUNT_CODE_VALUES, AccountCodeCodec } from "../../shared/ledger-codes.js";
|
|
@@ -11,7 +11,7 @@ type TimestampInit = {
|
|
|
11
11
|
};
|
|
12
12
|
declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
13
13
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
14
|
-
readonly timeframe: v.SchemaWithPipe<readonly [v.EnumSchema<typeof Timeframe$1, undefined>, v.TransformAction<Timeframe$1, DecodedEnum<"1d" | "
|
|
14
|
+
readonly timeframe: v.SchemaWithPipe<readonly [v.EnumSchema<typeof Timeframe$1, undefined>, v.TransformAction<Timeframe$1, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">>]>;
|
|
15
15
|
readonly tsSec: v.BigintSchema<undefined>;
|
|
16
16
|
readonly open: v.BigintSchema<undefined>;
|
|
17
17
|
readonly high: v.BigintSchema<undefined>;
|
|
@@ -21,7 +21,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
|
|
|
21
21
|
readonly isClosed: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
|
|
22
22
|
}, undefined>, v.TransformAction<{
|
|
23
23
|
symbolId: number;
|
|
24
|
-
timeframe: DecodedEnum<"1d" | "
|
|
24
|
+
timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
|
|
25
25
|
tsSec: bigint;
|
|
26
26
|
open: bigint;
|
|
27
27
|
high: bigint;
|
|
@@ -31,7 +31,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
|
|
|
31
31
|
isClosed: boolean;
|
|
32
32
|
}, {
|
|
33
33
|
symbolId: number;
|
|
34
|
-
timeframe: DecodedEnum<"1d" | "
|
|
34
|
+
timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
|
|
35
35
|
time: number;
|
|
36
36
|
open: string;
|
|
37
37
|
high: string;
|
|
@@ -43,7 +43,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
|
|
|
43
43
|
declare const createCandleRowIntSchema: typeof createCandleRowSchema;
|
|
44
44
|
declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
45
45
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
46
|
-
readonly timeframe: v.SchemaWithPipe<readonly [v.EnumSchema<typeof Timeframe$1, undefined>, v.TransformAction<Timeframe$1, DecodedEnum<"1d" | "
|
|
46
|
+
readonly timeframe: v.SchemaWithPipe<readonly [v.EnumSchema<typeof Timeframe$1, undefined>, v.TransformAction<Timeframe$1, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">>]>;
|
|
47
47
|
readonly tsSec: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
|
|
48
48
|
readonly open: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
|
|
49
49
|
readonly high: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
|
|
@@ -59,7 +59,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
|
|
|
59
59
|
readonly nextPageToken: v.OptionalSchema<v.StringSchema<undefined>, "">;
|
|
60
60
|
}, undefined>, v.TransformAction<{
|
|
61
61
|
symbolId: number;
|
|
62
|
-
timeframe: DecodedEnum<"1d" | "
|
|
62
|
+
timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
|
|
63
63
|
tsSec: bigint[];
|
|
64
64
|
open: bigint[];
|
|
65
65
|
high: bigint[];
|
|
@@ -75,7 +75,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
|
|
|
75
75
|
nextPageToken: string;
|
|
76
76
|
}, {
|
|
77
77
|
symbolId: number;
|
|
78
|
-
timeframe: DecodedEnum<"1d" | "
|
|
78
|
+
timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
|
|
79
79
|
time: number[];
|
|
80
80
|
open: string[];
|
|
81
81
|
high: string[];
|
|
@@ -94,7 +94,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
|
|
|
94
94
|
}>]>;
|
|
95
95
|
declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
96
96
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
97
|
-
readonly timeframe: v.SchemaWithPipe<readonly [v.EnumSchema<typeof Timeframe$1, undefined>, v.TransformAction<Timeframe$1, DecodedEnum<"1d" | "
|
|
97
|
+
readonly timeframe: v.SchemaWithPipe<readonly [v.EnumSchema<typeof Timeframe$1, undefined>, v.TransformAction<Timeframe$1, DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">>]>;
|
|
98
98
|
readonly tsSec: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
|
|
99
99
|
readonly open: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
|
|
100
100
|
readonly high: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
|
|
@@ -110,7 +110,7 @@ declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithP
|
|
|
110
110
|
readonly nextPageToken: v.OptionalSchema<v.StringSchema<undefined>, "">;
|
|
111
111
|
}, undefined>, v.TransformAction<{
|
|
112
112
|
symbolId: number;
|
|
113
|
-
timeframe: DecodedEnum<"1d" | "
|
|
113
|
+
timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
|
|
114
114
|
tsSec: bigint[];
|
|
115
115
|
open: bigint[];
|
|
116
116
|
high: bigint[];
|
|
@@ -126,7 +126,7 @@ declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithP
|
|
|
126
126
|
nextPageToken: string;
|
|
127
127
|
}, {
|
|
128
128
|
symbolId: number;
|
|
129
|
-
timeframe: DecodedEnum<"1d" | "
|
|
129
|
+
timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
|
|
130
130
|
tsSec: number[];
|
|
131
131
|
open: string[];
|
|
132
132
|
high: string[];
|
|
@@ -149,7 +149,7 @@ type CandleColumnar = v.InferOutput<ReturnType<typeof createCandleColumnarSchema
|
|
|
149
149
|
type CandleColumnarInt = v.InferOutput<ReturnType<typeof createCandleColumnarIntSchema>>;
|
|
150
150
|
declare function createListCandlesInputSchema(): v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
151
151
|
readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
|
|
152
|
-
readonly timeframe: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1s", "1m", "5m", "15m", "30m", "1h", "4h", "12h", "1d", "1w", "1mo"], undefined>, v.TransformAction<"1d" | "
|
|
152
|
+
readonly timeframe: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1s", "1m", "5m", "15m", "30m", "1h", "4h", "12h", "1d", "1w", "1mo"], undefined>, v.TransformAction<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo", Timeframe$1.SEC_1 | Timeframe$1.MIN_1 | Timeframe$1.MIN_5 | Timeframe$1.MIN_15 | Timeframe$1.MIN_30 | Timeframe$1.HOUR_1 | Timeframe$1.HOUR_4 | Timeframe$1.DAY_1 | Timeframe$1.HOUR_12 | Timeframe$1.WEEK_1 | Timeframe$1.MONTH_1>]>;
|
|
153
153
|
readonly limit: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 10000, undefined>]>, undefined>;
|
|
154
154
|
readonly includeIncomplete: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
|
|
155
155
|
readonly includeReference: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
|
|
@@ -13,8 +13,8 @@ type TimestampInit = {
|
|
|
13
13
|
};
|
|
14
14
|
declare const GetOrderbookHeatmapInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
15
15
|
readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
|
|
16
|
-
readonly interval: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["1s", "1m", "5m", "1h"], undefined>, "1s">, v.TransformAction<"
|
|
17
|
-
readonly depth: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000], undefined>, 50>, v.TransformAction<5 | 10 | 20 | 1 | 200 | 1000 | 500 |
|
|
16
|
+
readonly interval: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["1s", "1m", "5m", "1h"], undefined>, "1s">, v.TransformAction<"1h" | "1m" | "1s" | "5m", HeatmapInterval>]>;
|
|
17
|
+
readonly depth: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly [1, 5, 10, 20, 50, 100, 200, 500, 1000], undefined>, 50>, v.TransformAction<5 | 10 | 20 | 1 | 200 | 1000 | 500 | 50 | 100, HeatmapDepth>]>;
|
|
18
18
|
readonly quantityMode: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["close", "peak"], undefined>, "close">, v.TransformAction<"close" | "peak", HeatmapQuantityMode>]>;
|
|
19
19
|
readonly limit: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 20000, undefined>]>;
|
|
20
20
|
readonly startTsSec: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 0, undefined>, v.MaxValueAction<number, number, undefined>, v.TransformAction<number, bigint>]>, undefined>;
|
|
@@ -122,7 +122,7 @@ declare function convertHeatmapDeltaBucket(bucket: OrderbookHeatmapDeltaBucketRa
|
|
|
122
122
|
type OrderbookHeatmapDeltaBucket = ReturnType<typeof convertHeatmapDeltaBucket>;
|
|
123
123
|
declare const OrderbookHeatmapLiveBucketRawSchema: v.ObjectSchema<{
|
|
124
124
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
125
|
-
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"
|
|
125
|
+
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1h" | "1m" | "1s" | "5m">>]>;
|
|
126
126
|
readonly tsSec: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, number>]>;
|
|
127
127
|
readonly isFinal: v.BooleanSchema<undefined>;
|
|
128
128
|
readonly bids: v.OptionalSchema<v.ObjectSchema<{
|
|
@@ -142,7 +142,7 @@ declare const OrderbookHeatmapLiveBucketRawSchema: v.ObjectSchema<{
|
|
|
142
142
|
type OrderbookHeatmapLiveBucketRaw = v.InferOutput<typeof OrderbookHeatmapLiveBucketRawSchema>;
|
|
143
143
|
declare function convertHeatmapLiveBucket(bucket: OrderbookHeatmapLiveBucketRaw, scales: SdkScales): {
|
|
144
144
|
symbolId: number;
|
|
145
|
-
interval: DecodedEnum<"
|
|
145
|
+
interval: DecodedEnum<"1h" | "1m" | "1s" | "5m">;
|
|
146
146
|
tsSec: number;
|
|
147
147
|
isFinal: boolean;
|
|
148
148
|
bids: {
|
|
@@ -226,8 +226,8 @@ declare function convertHeatmapDeltaChain(chain: OrderbookHeatmapDeltaChainRaw,
|
|
|
226
226
|
type OrderbookHeatmapDeltaChain = ReturnType<typeof convertHeatmapDeltaChain>;
|
|
227
227
|
declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
|
|
228
228
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
229
|
-
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"
|
|
230
|
-
readonly depth: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 |
|
|
229
|
+
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1h" | "1m" | "1s" | "5m">>]>;
|
|
230
|
+
readonly depth: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 | 50 | 100>]>;
|
|
231
231
|
readonly chain: v.OptionalSchema<v.ObjectSchema<{
|
|
232
232
|
readonly baseKeyframe: v.OptionalSchema<v.ObjectSchema<{
|
|
233
233
|
readonly tsSec: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, number>]>;
|
|
@@ -267,7 +267,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
267
267
|
readonly quantityMode: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"close" | "peak">>]>;
|
|
268
268
|
readonly liveBucket: v.OptionalSchema<v.ObjectSchema<{
|
|
269
269
|
readonly symbolId: v.NumberSchema<undefined>;
|
|
270
|
-
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"
|
|
270
|
+
readonly interval: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, DecodedEnum<"1h" | "1m" | "1s" | "5m">>]>;
|
|
271
271
|
readonly tsSec: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, number>]>;
|
|
272
272
|
readonly isFinal: v.BooleanSchema<undefined>;
|
|
273
273
|
readonly bids: v.OptionalSchema<v.ObjectSchema<{
|
|
@@ -286,8 +286,8 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
286
286
|
}, undefined>, undefined>;
|
|
287
287
|
}, undefined>, v.TransformAction<{
|
|
288
288
|
symbolId: number;
|
|
289
|
-
interval: DecodedEnum<"
|
|
290
|
-
depth: 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 |
|
|
289
|
+
interval: DecodedEnum<"1h" | "1m" | "1s" | "5m">;
|
|
290
|
+
depth: 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 | 50 | 100;
|
|
291
291
|
chain?: {
|
|
292
292
|
baseKeyframe?: {
|
|
293
293
|
tsSec: number;
|
|
@@ -327,7 +327,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
327
327
|
quantityMode: DecodedEnum<"close" | "peak">;
|
|
328
328
|
liveBucket?: {
|
|
329
329
|
symbolId: number;
|
|
330
|
-
interval: DecodedEnum<"
|
|
330
|
+
interval: DecodedEnum<"1h" | "1m" | "1s" | "5m">;
|
|
331
331
|
tsSec: number;
|
|
332
332
|
isFinal: boolean;
|
|
333
333
|
bids?: {
|
|
@@ -346,8 +346,8 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
346
346
|
} | undefined;
|
|
347
347
|
}, {
|
|
348
348
|
symbolId: number;
|
|
349
|
-
interval: DecodedEnum<"
|
|
350
|
-
depth: 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 |
|
|
349
|
+
interval: DecodedEnum<"1h" | "1m" | "1s" | "5m">;
|
|
350
|
+
depth: 5 | 10 | 20 | 1 | "unspecified" | 200 | 1000 | 500 | 50 | 100;
|
|
351
351
|
chain: {
|
|
352
352
|
baseKeyframe: {
|
|
353
353
|
tsSec: number;
|
|
@@ -387,7 +387,7 @@ declare function createOrderbookHeatmapResponseSchema(scales: SdkScales): v.Sche
|
|
|
387
387
|
quantityMode: DecodedEnum<"close" | "peak">;
|
|
388
388
|
liveBucket: {
|
|
389
389
|
symbolId: number;
|
|
390
|
-
interval: DecodedEnum<"
|
|
390
|
+
interval: DecodedEnum<"1h" | "1m" | "1s" | "5m">;
|
|
391
391
|
tsSec: number;
|
|
392
392
|
isFinal: boolean;
|
|
393
393
|
bids: {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { InternalTransferService } from "../../gen/transfer/v1/internal_transfer_pb.js";
|
|
1
2
|
import { parse } from "../../shared/validation.js";
|
|
2
3
|
import { toConnectCallOptions } from "../../shared/request-options.js";
|
|
3
4
|
import { removeUndefined } from "../../utils/remove-undefined.js";
|
|
4
5
|
import { resolveAccountScopedInput } from "../subaccount-resolver.js";
|
|
5
|
-
import { InternalTransferService } from "../../gen/transfer/v1/internal_transfer_pb.js";
|
|
6
6
|
import { createCreateInternalTransferInputSchema, createCreateInternalTransferResultSchema } from "./internal-transfers.schemas.js";
|
|
7
7
|
import { createClient } from "@connectrpc/connect";
|
|
8
8
|
//#region src/services/internal-transfers/internal-transfers.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { MarketOverviewBatchSchema, MarketOverviewService as MarketOverviewService$1 } from "../../gen/marketoverview/v1/marketoverview_pb.js";
|
|
1
2
|
import { parse } from "../../shared/validation.js";
|
|
2
3
|
import { toConnectCallOptions } from "../../shared/request-options.js";
|
|
3
4
|
import { CatalogLookupError } from "../../catalogs/types.js";
|
|
4
5
|
import { isDev } from "../../utils/is-dev.js";
|
|
5
|
-
import { MarketOverviewBatchSchema, MarketOverviewService as MarketOverviewService$1 } from "../../gen/marketoverview/v1/marketoverview_pb.js";
|
|
6
6
|
import { snapshotThenStream } from "../../realtime/snapshot-then-stream.js";
|
|
7
7
|
import { ListMarketOverviewInputSchema, createMarketOverviewSchema } from "./market-overview.schemas.js";
|
|
8
8
|
import { createClient } from "@connectrpc/connect";
|
|
@@ -29,7 +29,7 @@ declare function createMarketOverviewSchema(scales: SdkScales): v.SchemaWithPipe
|
|
|
29
29
|
readonly bestAskTicks: v.BigintSchema<undefined>;
|
|
30
30
|
readonly bestAskQtyScaled: v.BigintSchema<undefined>;
|
|
31
31
|
readonly sparklines: v.OptionalSchema<v.ArraySchema<v.ObjectSchema<{
|
|
32
|
-
readonly interval: v.SchemaWithPipe<readonly [v.EnumSchema<typeof SparklineInterval, undefined>, v.TransformAction<SparklineInterval, "unspecified" | "
|
|
32
|
+
readonly interval: v.SchemaWithPipe<readonly [v.EnumSchema<typeof SparklineInterval, undefined>, v.TransformAction<SparklineInterval, "unspecified" | "1h" | "24h" | "1w" | "1m">]>;
|
|
33
33
|
readonly closeTicks: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
|
|
34
34
|
}, undefined>, undefined>, readonly []>;
|
|
35
35
|
readonly indexPriceTicks: v.BigintSchema<undefined>;
|
|
@@ -48,7 +48,7 @@ declare function createMarketOverviewSchema(scales: SdkScales): v.SchemaWithPipe
|
|
|
48
48
|
bestAskTicks: bigint;
|
|
49
49
|
bestAskQtyScaled: bigint;
|
|
50
50
|
sparklines: {
|
|
51
|
-
interval: "unspecified" | "
|
|
51
|
+
interval: "unspecified" | "1h" | "24h" | "1w" | "1m";
|
|
52
52
|
closeTicks: bigint[];
|
|
53
53
|
}[];
|
|
54
54
|
indexPriceTicks: bigint;
|
|
@@ -77,7 +77,7 @@ declare const ListMarketOverviewInputSchema: v.SchemaWithPipe<readonly [v.Strict
|
|
|
77
77
|
readonly orderBy: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["change_24h_bps", "volume_24h_quote", "last_price", "date_added"], undefined>, "volume_24h_quote">, v.TransformAction<"change_24h_bps" | "volume_24h_quote" | "last_price" | "date_added", MarketOrderBy.ORDER_BY_CHANGE_24H_BPS | MarketOrderBy.ORDER_BY_VOLUME_24H_QUOTE | MarketOrderBy.ORDER_BY_LAST_PRICE | MarketOrderBy.ORDER_BY_DATE_ADDED>]>;
|
|
78
78
|
readonly sort: v.SchemaWithPipe<readonly [v.OptionalSchema<v.PicklistSchema<readonly ["asc", "desc"], undefined>, "desc">, v.TransformAction<"asc" | "desc", SortDirection.SORT_ASC | SortDirection.SORT_DESC>]>;
|
|
79
79
|
readonly includeSparklines: v.OptionalSchema<v.BooleanSchema<undefined>, true>;
|
|
80
|
-
readonly sparklineIntervals: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ArraySchema<v.PicklistSchema<readonly ["1h", "24h", "1w", "1m"], undefined>, undefined>, readonly ["24h"]>, v.TransformAction<("
|
|
80
|
+
readonly sparklineIntervals: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ArraySchema<v.PicklistSchema<readonly ["1h", "24h", "1w", "1m"], undefined>, undefined>, readonly ["24h"]>, v.TransformAction<("1h" | "24h" | "1w" | "1m")[], (SparklineInterval.SPARKLINE_1H | SparklineInterval.SPARKLINE_24H | SparklineInterval.SPARKLINE_1W | SparklineInterval.SPARKLINE_1M)[]>]>;
|
|
81
81
|
}, undefined>, v.TransformAction<{
|
|
82
82
|
symbolIds: number[];
|
|
83
83
|
limit: number;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { SparklineInterval } from "../../gen/marketoverview/v1/marketoverview_pb.js";
|
|
1
2
|
import { requiredEnumLabel } from "../../shared/proto-enum-codec.js";
|
|
2
3
|
import { tsNsToMs } from "../../utils/time.js";
|
|
3
4
|
import { PositiveUint32InputSchema, SymbolIdInputSchema } from "../shared.js";
|
|
4
5
|
import { scaledToDecimalOutput } from "../../shared/decimal-surface.js";
|
|
5
|
-
import { SparklineInterval } from "../../gen/marketoverview/v1/marketoverview_pb.js";
|
|
6
6
|
import { MARKET_OVERVIEW_ORDER_BY_VALUES, MARKET_OVERVIEW_SORT_VALUES, MarketOverviewOrderByCodec, MarketOverviewSortCodec, SPARKLINE_INTERVAL_VALUES, SparklineIntervalCodec } from "./market-overview.codecs.js";
|
|
7
7
|
import * as v from "valibot";
|
|
8
8
|
//#region src/services/market-overview/market-overview.schemas.ts
|
|
@@ -10,7 +10,7 @@ declare const GetOrderbookInputSchema: v.SchemaWithPipe<readonly [v.ObjectSchema
|
|
|
10
10
|
depth: number;
|
|
11
11
|
}, {
|
|
12
12
|
symbolId: number;
|
|
13
|
-
depth: 5 | 10 | 20 | 1 | 200 | 1000 | 500 |
|
|
13
|
+
depth: 5 | 10 | 20 | 1 | 200 | 1000 | 500 | 50 | 100;
|
|
14
14
|
protoDepth: Depth;
|
|
15
15
|
}>]>;
|
|
16
16
|
type GetOrderbookInput = v.InferInput<typeof GetOrderbookInputSchema>;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { OrderErrorCode, OrderErrorDetail, OrderErrorDetailSchema } from "./order-errors.schemas.js";
|
|
1
2
|
import { CancelAllOrdersInput, CancelAllOrdersInputSchema, CancelAllOrdersResponse, CancelAllOrdersResponseSchema, CancelOrderInput, CancelOrderInputSchema, CancelOrderResult, CancelOrderResultSchema, CreateOrderResult, GetOrderDetailsInput, GetOrderDetailsInputSchema, NewOrderInput, OpenOrdersInput, OpenOrdersInputSchema, OrderHistoryInput, OrderHistoryInputSchema, OrderIntentInput, PreviewOrderResult, createCreateOrderResultSchema, createNewOrderInputSchema, createOrderIntentInputSchema, createPreviewOrderResultSchema } from "./orders-input.schemas.js";
|
|
2
3
|
import { ModifyOrderInput, ModifyOrderResult, ModifyOrderResultSchema, createModifyOrderInputSchema } from "./orders-modify.schemas.js";
|
|
3
4
|
import { RiskPolicyInput, StopLossInput, TakeProfitInput, TrailingStopInput, createRiskPolicyInputSchema } from "./orders-risk.schemas.js";
|
|
4
5
|
import { BatchCancelOrderInput, BatchCancelOrderResult, BatchCancelOrdersInput, BatchCancelOrdersInputSchema, BatchCancelOrdersResult, BatchCancelOrdersResultSchema, BatchCreateOrderResult, BatchCreateOrdersInput, BatchCreateOrdersResult, BatchReplaceAdmissionItem, BatchReplaceOrdersInput, BatchReplaceOrdersResult, BatchReplaceOrdersResultSchema, CancelAllAfterInput, CancelAllAfterInputSchema, CancelAllAfterResult, CancelAllAfterResultSchema, GetBatchReplaceStatusInput, GetBatchReplaceStatusInputSchema, GetBatchReplaceStatusResult, GetBatchReplaceStatusResultSchema, createBatchCreateOrdersInputSchema, createBatchCreateOrdersResultSchema } from "./orders-batch.schemas.js";
|
|
5
|
-
import { OrderErrorCode, OrderErrorDetail, OrderErrorDetailSchema } from "./order-errors.schemas.js";
|
|
6
6
|
import { Order, OrderDetails, OrderTransfer, createOrderDetailsSchema, createOrderSchema, createOrderTransferSchema } from "./orders-output.schemas.js";
|
|
7
7
|
import "./orders.schemas.js";
|
|
8
8
|
import { OrdersService } from "./orders.js";
|
|
@@ -4,7 +4,7 @@ import * as v from "valibot";
|
|
|
4
4
|
//#region src/services/orders/order-errors.schemas.d.ts
|
|
5
5
|
type OrderErrorCode = keyof typeof ErrorCode;
|
|
6
6
|
declare const OrderErrorDetailSchema: v.ObjectSchema<{
|
|
7
|
-
readonly code: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ErrorCode, undefined>, v.TransformAction<ErrorCode, "STALE_QUOTE" | "UNSPECIFIED" | "BAD_REQUEST" | "INVALID_ARGUMENT" | "INSUFFICIENT_FUNDS" | "UNKNOWN_SYMBOL" | "BAD_PRICE" | "BAD_QTY" | "MIN_NOTIONAL" | "QTY_STEP_SIZE" | "CONFLICT_DUPLICATE_CLIENT_ORDER_ID" | "UNAVAILABLE" | "UNAUTHENTICATED" | "PERMISSION_DENIED" | "NOT_FOUND" | "UPSTREAM_ERROR" | "FEE_ASSET_NOT_ALLOWED" | "PAIR_DISABLED" | "ORDER_UNKNOWN" | "INTERNAL_ERROR" | "SUBACCOUNT_INACTIVE" | "POLICY_MARKET_DENY" | "POLICY_MAX_NOTIONAL" | "POLICY_TRADING_HALTED" | "POLICY_SPOT_TRADE_DENY" | "API_KEY_ROOT_SCOPE_ONLY" | "API_KEY_SUB_SCOPE_ONLY" | "API_KEY_SUBACCOUNT_MISMATCH" | "API_KEY_POLICY_REQUIRED" | "API_KEY_UNKNOWN" | "API_KEY_MARKET_DENY" | "PRICE_TICK_SIZE" | "MIN_QTY" | "POST_ONLY_LIMIT_ONLY" | "BATCH_TOO_LARGE" | "POLICY_MAX_OPEN_ORDERS" | "MODIFICATION_REQUIRES_REPLACE" | "CONFLICT_IDEMPOTENCY_KEY_REUSE" | "MARKET_PRICE_UNAVAILABLE" | "PAIR_NOT_LISTED_YET" | "PAIR_DELISTED" | "PAIR_CANCEL_ONLY" | "PAIR_POST_ONLY" | "PAIR_REDUCE_ONLY" | "RISK_LIMIT" | "MARKET_HALTED" | "ACCOUNT_UNKNOWN" | "POST_ONLY_CROSS" | "REDUCE_ONLY_BLOCKED" | "PRICE_BAND_VIOLATION" | "MARKET_CAP_VIOLATION" | "EMPTY_BOOK" | "FOK_INSUFFICIENT_LIQUIDITY" | "ORDER_ALREADY_TERMINAL" | "TRIGGER_PRICE_INVALID" | "TRIGGER_PRICE_SOURCE_UNSUPPORTED" | "TRAILING_DISTANCE_INVALID" | "TRIGGER_NOT_FOUND" | "TRIGGER_CANCEL_REJECTED" | "TRIGGER_STATUS_INVALID" | "TRIGGER_NOT_MODIFIABLE" | "CONFLICT_DUPLICATE_CLIENT_TRIGGER_ID" | "MAX_SLIPPAGE_INVALID" | "VALIDATION_ERROR" | "OVERLOADED" | "MAX_QUOTE_DEBIT_TOO_SMALL" | "RATE_LIMIT_EXCEEDED" | "SUBACCOUNT_READ_FORBIDDEN" | "POLICY_SPOT_READ_DENY" | "API_KEY_SPOT_READ_DENY">]>;
|
|
7
|
+
readonly code: v.SchemaWithPipe<readonly [v.EnumSchema<typeof ErrorCode, undefined>, v.TransformAction<ErrorCode, "STALE_QUOTE" | "UNSPECIFIED" | "BAD_REQUEST" | "INVALID_ARGUMENT" | "INSUFFICIENT_FUNDS" | "UNKNOWN_SYMBOL" | "BAD_PRICE" | "BAD_QTY" | "MIN_NOTIONAL" | "QTY_STEP_SIZE" | "CONFLICT_DUPLICATE_CLIENT_ORDER_ID" | "UNAVAILABLE" | "UNAUTHENTICATED" | "PERMISSION_DENIED" | "NOT_FOUND" | "UPSTREAM_ERROR" | "FEE_ASSET_NOT_ALLOWED" | "PAIR_DISABLED" | "ORDER_UNKNOWN" | "INTERNAL_ERROR" | "SUBACCOUNT_INACTIVE" | "POLICY_MARKET_DENY" | "POLICY_MAX_NOTIONAL" | "POLICY_TRADING_HALTED" | "POLICY_SPOT_TRADE_DENY" | "API_KEY_ROOT_SCOPE_ONLY" | "API_KEY_SUB_SCOPE_ONLY" | "API_KEY_SUBACCOUNT_MISMATCH" | "API_KEY_POLICY_REQUIRED" | "API_KEY_UNKNOWN" | "API_KEY_MARKET_DENY" | "PRICE_TICK_SIZE" | "MIN_QTY" | "POST_ONLY_LIMIT_ONLY" | "BATCH_TOO_LARGE" | "POLICY_MAX_OPEN_ORDERS" | "MODIFICATION_REQUIRES_REPLACE" | "CONFLICT_IDEMPOTENCY_KEY_REUSE" | "MARKET_PRICE_UNAVAILABLE" | "PAIR_NOT_LISTED_YET" | "PAIR_DELISTED" | "PAIR_CANCEL_ONLY" | "PAIR_POST_ONLY" | "PAIR_REDUCE_ONLY" | "RISK_LIMIT" | "MARKET_HALTED" | "ACCOUNT_UNKNOWN" | "POST_ONLY_CROSS" | "REDUCE_ONLY_BLOCKED" | "PRICE_BAND_VIOLATION" | "MARKET_CAP_VIOLATION" | "EMPTY_BOOK" | "FOK_INSUFFICIENT_LIQUIDITY" | "ORDER_ALREADY_TERMINAL" | "TRIGGER_PRICE_INVALID" | "TRIGGER_PRICE_SOURCE_UNSUPPORTED" | "TRAILING_DISTANCE_INVALID" | "TRIGGER_NOT_FOUND" | "TRIGGER_CANCEL_REJECTED" | "TRIGGER_STATUS_INVALID" | "TRIGGER_NOT_MODIFIABLE" | "CONFLICT_DUPLICATE_CLIENT_TRIGGER_ID" | "MAX_SLIPPAGE_INVALID" | "VALIDATION_ERROR" | "OVERLOADED" | "MAX_QUOTE_DEBIT_TOO_SMALL" | "RATE_LIMIT_EXCEEDED" | "SUBACCOUNT_READ_FORBIDDEN" | "POLICY_SPOT_READ_DENY" | "API_KEY_SPOT_READ_DENY" | "CANCEL_REQUEST_EXPIRED">]>;
|
|
8
8
|
readonly violations: v.ArraySchema<v.ObjectSchema<{
|
|
9
9
|
readonly fieldPath: v.StringSchema<undefined>;
|
|
10
10
|
readonly ruleId: v.StringSchema<undefined>;
|