@polyester/sdk 0.23.1 → 0.24.1

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 (64) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/account-signer/types.d.ts +1 -1
  3. package/dist/account-signer/types.js.map +1 -1
  4. package/dist/core-client.d.ts.map +1 -1
  5. package/dist/core-client.js +18 -45
  6. package/dist/core-client.js.map +1 -1
  7. package/dist/gen/orders/v1/orders_read_pb.d.ts +136 -13
  8. package/dist/gen/orders/v1/orders_read_pb.d.ts.map +1 -1
  9. package/dist/gen/orders/v1/orders_read_pb.js +22 -16
  10. package/dist/gen/orders/v1/orders_read_pb.js.map +1 -1
  11. package/dist/index.d.ts +4 -3
  12. package/dist/realtime/client.js +45 -26
  13. package/dist/realtime/client.js.map +1 -1
  14. package/dist/services/auth/account-signer-auth.js +1 -1
  15. package/dist/services/auth/account-signer-auth.js.map +1 -1
  16. package/dist/services/candles/candles.schemas.d.ts +10 -10
  17. package/dist/services/heatmap/heatmap.schemas.d.ts +13 -13
  18. package/dist/services/market-overview/market-overview.js +5 -4
  19. package/dist/services/market-overview/market-overview.js.map +1 -1
  20. package/dist/services/market-overview/market-overview.schemas.d.ts +3 -3
  21. package/dist/services/orderbook/orderbook.schemas.d.ts +1 -1
  22. package/dist/services/orders/index.d.ts +4 -3
  23. package/dist/services/orders/order-lineage.schemas.d.ts +11 -0
  24. package/dist/services/orders/order-lineage.schemas.d.ts.map +1 -0
  25. package/dist/services/orders/order-lineage.schemas.js +13 -0
  26. package/dist/services/orders/order-lineage.schemas.js.map +1 -0
  27. package/dist/services/orders/orders-batch.schemas.d.ts +14 -14
  28. package/dist/services/orders/orders-batch.schemas.js +1 -1
  29. package/dist/services/orders/orders-input.schemas.d.ts +24 -1
  30. package/dist/services/orders/orders-input.schemas.d.ts.map +1 -1
  31. package/dist/services/orders/orders-input.schemas.js +5 -2
  32. package/dist/services/orders/orders-input.schemas.js.map +1 -1
  33. package/dist/services/orders/orders-modify.schemas.js +1 -1
  34. package/dist/services/orders/orders-output.schemas.d.ts +63 -20
  35. package/dist/services/orders/orders-output.schemas.d.ts.map +1 -1
  36. package/dist/services/orders/orders-output.schemas.js +7 -1
  37. package/dist/services/orders/orders-output.schemas.js.map +1 -1
  38. package/dist/services/orders/orders.d.ts +6 -2
  39. package/dist/services/orders/orders.d.ts.map +1 -1
  40. package/dist/services/orders/orders.js +6 -2
  41. package/dist/services/orders/orders.js.map +1 -1
  42. package/dist/services/orders/orders.schemas.d.ts +4 -3
  43. package/dist/services/orders/orders.types.d.ts +4 -3
  44. package/dist/services/subaccounts/subaccounts.schemas.d.ts +5 -5
  45. package/dist/services/trades/trades.d.ts +4 -0
  46. package/dist/services/trades/trades.d.ts.map +1 -1
  47. package/dist/services/trades/trades.js +4 -0
  48. package/dist/services/trades/trades.js.map +1 -1
  49. package/dist/services/trades/trades.schemas.d.ts +248 -4
  50. package/dist/services/trades/trades.schemas.d.ts.map +1 -1
  51. package/dist/services/trades/trades.schemas.js +52 -12
  52. package/dist/services/trades/trades.schemas.js.map +1 -1
  53. package/dist/services/triggers/trigger-input.schemas.d.ts +3 -3
  54. package/dist/services/triggers/triggers-output.schemas.d.ts +23 -23
  55. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  56. package/dist/shared/connect-error-mapping.js +15 -5
  57. package/dist/shared/connect-error-mapping.js.map +1 -1
  58. package/dist/shared/transports.d.ts +5 -1
  59. package/dist/shared/transports.d.ts.map +1 -1
  60. package/dist/shared/transports.js.map +1 -1
  61. package/dist/utils/errors.d.ts.map +1 -1
  62. package/dist/utils/errors.js +1 -0
  63. package/dist/utils/errors.js.map +1 -1
  64. package/package.json +1 -1
@@ -29,7 +29,6 @@ function loadCentrifuge() {
29
29
  var RealtimeClient = class {
30
30
  #publicClient = null;
31
31
  #privateClient = null;
32
- #connectionHandlers = /* @__PURE__ */ new Set();
33
32
  #sharedSubs = /* @__PURE__ */ new Map();
34
33
  #pendingTeardowns = /* @__PURE__ */ new Map();
35
34
  #config;
@@ -83,13 +82,10 @@ var RealtimeClient = class {
83
82
  #createPublicClient(Centrifuge) {
84
83
  const client = new Centrifuge(this.#config.wsUrl);
85
84
  this.#publicClient = client;
86
- client.on("connected", () => {
87
- if (this.#publicClient !== client) return;
88
- for (const h of this.#connectionHandlers) h.onConnected?.();
89
- });
90
- client.on("disconnected", () => {
91
- if (this.#publicClient !== client) return;
92
- for (const h of this.#connectionHandlers) h.onDisconnected?.();
85
+ client.on("disconnected", (ctx) => {
86
+ if (this.#publicClient !== client || ctx.code <= 1) return;
87
+ this.#publicClient = null;
88
+ this.#terminateSubscriptions([...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter((shared) => shared.client === client), "disconnected", ctx);
93
89
  });
94
90
  client.connect();
95
91
  return client;
@@ -114,13 +110,10 @@ var RealtimeClient = class {
114
110
  }
115
111
  } });
116
112
  this.#privateClient = client;
117
- client.on("connected", () => {
118
- if (this.#privateClient !== client) return;
119
- for (const h of this.#connectionHandlers) h.onConnected?.();
120
- });
121
- client.on("disconnected", () => {
122
- if (this.#privateClient !== client) return;
123
- for (const h of this.#connectionHandlers) h.onDisconnected?.();
113
+ client.on("disconnected", (ctx) => {
114
+ if (this.#privateClient !== client || ctx.code <= 1) return;
115
+ this.#privateClient = null;
116
+ this.#terminateSubscriptions([...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter((shared) => shared.client === client), "disconnected", ctx);
124
117
  });
125
118
  client.connect();
126
119
  return client;
@@ -128,16 +121,11 @@ var RealtimeClient = class {
128
121
  #ensurePublicClient(Centrifuge) {
129
122
  return this.#publicClient ?? this.#createPublicClient(Centrifuge);
130
123
  }
131
- #ensurePrivateClient(Centrifuge) {
132
- if (!this.#hasAuth()) throw new AuthenticationError("Cannot create authenticated realtime client without authentication");
133
- return this.#privateClient ?? this.#createPrivateClient(Centrifuge);
134
- }
135
124
  #assertChannelAuth(channel) {
136
125
  if (this.#channelKind(channel) === "private" && !this.#hasAuth()) throw new AuthenticationError(`Cannot subscribe to private channel "${channel}" without authentication`);
137
126
  }
138
127
  #ensureClientForChannel(Centrifuge, channel) {
139
- this.#assertChannelAuth(channel);
140
- if (this.#channelKind(channel) === "private") return this.#ensurePrivateClient(Centrifuge);
128
+ if (this.#channelKind(channel) === "private") return this.#privateClient ?? this.#createPrivateClient(Centrifuge);
141
129
  return this.#ensurePublicClient(Centrifuge);
142
130
  }
143
131
  #attachSubscription(shared) {
@@ -164,6 +152,7 @@ var RealtimeClient = class {
164
152
  if (shared.attachmentEpoch !== attachmentEpoch || shared.sub) return;
165
153
  if (this.#sharedSubs.get(shared.channel) !== shared) return;
166
154
  try {
155
+ this.#assertChannelAuth(shared.channel);
167
156
  this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);
168
157
  } catch (error) {
169
158
  this.#sharedSubs.delete(shared.channel);
@@ -184,8 +173,12 @@ var RealtimeClient = class {
184
173
  const subscriptionEpoch = ++shared.subscriptionEpoch;
185
174
  for (const handler of shared.subscribedHandlers) handler(subscriptionEpoch);
186
175
  });
187
- sub.on("unsubscribed", () => {
176
+ sub.on("unsubscribed", (ctx) => {
188
177
  if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;
178
+ if (ctx.code >= 2e3 && ctx.code < 2500) {
179
+ this.#terminateSubscriptions([shared], "unsubscribed", ctx);
180
+ return;
181
+ }
189
182
  for (const handler of shared.unsubscribedHandlers) handler();
190
183
  });
191
184
  sub.on("error", (ctx) => {
@@ -240,6 +233,29 @@ var RealtimeClient = class {
240
233
  this.#callErrorHandler(onError, createSdkSubscriptionErrorContext(channel, type, error));
241
234
  }
242
235
  }
236
+ #terminateSubscriptions(subscriptions, type, ctx) {
237
+ const notifications = subscriptions.map((shared) => ({
238
+ error: createSdkSubscriptionErrorContext(shared.channel, type, {
239
+ code: ctx.code,
240
+ message: ctx.reason
241
+ }),
242
+ errorHandlers: [...shared.errorHandlers],
243
+ closeHandlers: [...shared.unsubscribedHandlers]
244
+ }));
245
+ for (const shared of subscriptions) {
246
+ if (this.#sharedSubs.get(shared.channel) === shared) this.#sharedSubs.delete(shared.channel);
247
+ if (this.#pendingTeardowns.get(shared.channel) === shared) this.#pendingTeardowns.delete(shared.channel);
248
+ this.#teardownSubscription(shared);
249
+ shared.publicationHandlers.clear();
250
+ shared.subscribedHandlers.clear();
251
+ shared.unsubscribedHandlers.clear();
252
+ shared.errorHandlers.clear();
253
+ }
254
+ for (const { error, errorHandlers, closeHandlers } of notifications) {
255
+ for (const handler of errorHandlers) handler(error);
256
+ for (const handler of closeHandlers) handler();
257
+ }
258
+ }
243
259
  #teardownSubscription(shared) {
244
260
  const sub = shared.sub;
245
261
  const client = shared.client;
@@ -283,7 +299,6 @@ var RealtimeClient = class {
283
299
  try {
284
300
  privateClient?.disconnect();
285
301
  } catch {}
286
- this.#connectionHandlers.clear();
287
302
  }
288
303
  #disconnectPrivate() {
289
304
  const privateClient = this.#privateClient;
@@ -339,9 +354,13 @@ var RealtimeClient = class {
339
354
  if (onSubscribed) shared.subscribedHandlers.add(onSubscribed);
340
355
  if (onUnsubscribed) shared.unsubscribedHandlers.add(onUnsubscribed);
341
356
  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();
357
+ if (this.#channelKind(channel) === "private") {
358
+ const reconnect = shared.client?.state === "disconnected";
359
+ const resubscribe = shared.sub?.state === "unsubscribed";
360
+ if ((reconnect || resubscribe) && this.#hasAuth()) {
361
+ if (reconnect) shared.client?.connect();
362
+ if (resubscribe) shared.sub?.subscribe();
363
+ }
345
364
  }
346
365
  let closed = false;
347
366
  if (onSubscribed && shared.sub?.state === "subscribed") {
@@ -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 {\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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O,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","#terminateSubscriptions","#pendingTeardowns","#privateClient","#emitConnectionTokenError","#createPublicClient","#hasAuth","#createPrivateClient","#ensurePublicClient","#assertChannelAuth","#attachSubscriptionNow","#attachSubscriptionWhenLoaded","#ensureClientForChannel","#subscriptionOpts","#attachSubscription","#callErrorHandler","#teardownSubscription","#disconnectClientIfIdle","#hasChannelsForKind","#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 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 #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(\"disconnected\", (ctx) => {\n // Codes 0 (disconnectCalled) and 1 (unauthorized) are handled elsewhere;\n // every other disconnected event is terminal.\n if (this.#publicClient !== client || ctx.code <= 1) return;\n this.#publicClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n\n 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(\"disconnected\", (ctx) => {\n // Codes 0 (disconnectCalled) and 1 (unauthorized) are handled elsewhere;\n // every other disconnected event is terminal.\n if (this.#privateClient !== client || ctx.code <= 1) return;\n this.#privateClient = null;\n this.#terminateSubscriptions(\n [...this.#sharedSubs.values(), ...this.#pendingTeardowns.values()].filter(\n (shared) => shared.client === client,\n ),\n \"disconnected\",\n ctx,\n );\n });\n\n client.connect();\n return client;\n }\n\n #ensurePublicClient(Centrifuge: CentrifugeCtor): Centrifuge {\n return this.#publicClient ?? this.#createPublicClient(Centrifuge);\n }\n\n #assertChannelAuth(channel: string): void {\n if (this.#channelKind(channel) === \"private\" && !this.#hasAuth()) {\n throw new AuthenticationError(\n `Cannot subscribe to private channel \"${channel}\" without authentication`,\n );\n }\n }\n\n #ensureClientForChannel(Centrifuge: CentrifugeCtor, channel: string): Centrifuge {\n if (this.#channelKind(channel) === \"private\") {\n return this.#privateClient ?? this.#createPrivateClient(Centrifuge);\n }\n\n return this.#ensurePublicClient(Centrifuge);\n }\n\n #attachSubscription(shared: SharedSubscription): void {\n if (shared.sub) return;\n\n // Auth failures must surface synchronously to subscribe() callers, as\n // they did when centrifuge was imported statically.\n this.#assertChannelAuth(shared.channel);\n\n const attachmentEpoch = shared.attachmentEpoch + 1;\n shared.attachmentEpoch = attachmentEpoch;\n\n // Once the transport module is loaded, attachment stays fully\n // synchronous — only the very first attach pays the dynamic import.\n if (loadedCentrifugeCtor) {\n this.#attachSubscriptionNow(loadedCentrifugeCtor, shared, attachmentEpoch);\n return;\n }\n void this.#attachSubscriptionWhenLoaded(shared, attachmentEpoch);\n }\n\n async #attachSubscriptionWhenLoaded(\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): Promise<void> {\n let Centrifuge: CentrifugeCtor;\n try {\n Centrifuge = await loadCentrifuge();\n } catch (error) {\n if (shared.attachmentEpoch !== attachmentEpoch) return;\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n this.#emitSubscriptionError(shared, \"transport_load\", error);\n return;\n }\n\n // The subscription may have been torn down or re-attached while the\n // transport module was loading.\n if (shared.attachmentEpoch !== attachmentEpoch || shared.sub) return;\n if (this.#sharedSubs.get(shared.channel) !== shared) return;\n\n try {\n this.#assertChannelAuth(shared.channel);\n this.#attachSubscriptionNow(Centrifuge, shared, attachmentEpoch);\n } catch (error) {\n this.#sharedSubs.delete(shared.channel);\n this.#emitSubscriptionError(shared, \"auth\", error);\n }\n }\n\n #attachSubscriptionNow(\n Centrifuge: CentrifugeCtor,\n shared: SharedSubscription,\n attachmentEpoch: number,\n ): void {\n const client = this.#ensureClientForChannel(Centrifuge, shared.channel);\n\n const sub = client.newSubscription(\n shared.channel,\n this.#subscriptionOpts(Centrifuge, shared, attachmentEpoch),\n );\n shared.sub = sub;\n shared.client = client;\n\n sub.on(\"publication\", (ctx: PublicationContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n for (const handler of shared.publicationHandlers) handler(ctx.data);\n });\n sub.on(\"subscribed\", () => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const subscriptionEpoch = ++shared.subscriptionEpoch;\n for (const handler of shared.subscribedHandlers) handler(subscriptionEpoch);\n });\n sub.on(\"unsubscribed\", (ctx) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n if (ctx.code >= 2000 && ctx.code < 2500) {\n this.#terminateSubscriptions([shared], \"unsubscribed\", ctx);\n return;\n }\n for (const handler of shared.unsubscribedHandlers) handler();\n });\n sub.on(\"error\", (ctx: SubscriptionErrorContext) => {\n if (shared.sub !== sub || shared.attachmentEpoch !== attachmentEpoch) return;\n const sdkCtx = fromCentrifugeSubscriptionError(ctx);\n for (const handler of shared.errorHandlers) handler(sdkCtx);\n });\n\n sub.subscribe();\n }\n\n #getOrCreateSubscription(channel: string): SharedSubscription {\n const existing = this.#sharedSubs.get(channel);\n if (existing) return existing;\n\n const pending = this.#pendingTeardowns.get(channel);\n if (pending) {\n this.#pendingTeardowns.delete(channel);\n this.#sharedSubs.set(channel, pending);\n if (!pending.sub) {\n this.#attachSubscription(pending);\n } else if (pending.sub.state !== \"subscribed\") {\n pending.sub.subscribe();\n }\n return pending;\n }\n\n const shared: SharedSubscription = {\n channel,\n sub: null,\n client: null,\n attachmentEpoch: 0,\n consumers: 0,\n subscriptionEpoch: 0,\n publicationHandlers: new Set(),\n subscribedHandlers: new Set(),\n unsubscribedHandlers: new Set(),\n errorHandlers: new Set(),\n };\n\n this.#sharedSubs.set(channel, shared);\n try {\n this.#attachSubscription(shared);\n } catch (error) {\n this.#sharedSubs.delete(channel);\n throw error;\n }\n return shared;\n }\n\n #callErrorHandler(handler: ErrorHandler | undefined, ctx: SdkSubscriptionErrorContext): void {\n if (!handler) return;\n\n try {\n handler(ctx);\n } catch {\n // Keep error reporting isolated from other subscription consumers.\n }\n }\n\n #callConsumerHandler(\n channel: string,\n type: string,\n handler: () => void,\n onError?: ErrorHandler,\n ): void {\n try {\n handler();\n } catch (error) {\n this.#callErrorHandler(\n onError,\n createSdkSubscriptionErrorContext(channel, type, error),\n );\n }\n }\n\n #terminateSubscriptions(\n subscriptions: SharedSubscription[],\n type: \"disconnected\" | \"unsubscribed\",\n ctx: { code: number; reason: string },\n ): void {\n const notifications = subscriptions.map((shared) => ({\n error: createSdkSubscriptionErrorContext(shared.channel, type, {\n code: ctx.code,\n message: ctx.reason,\n }),\n errorHandlers: [...shared.errorHandlers],\n closeHandlers: [...shared.unsubscribedHandlers],\n }));\n\n // Finish cleanup for every affected channel before callbacks can resubscribe.\n for (const shared of subscriptions) {\n if (this.#sharedSubs.get(shared.channel) === shared) {\n this.#sharedSubs.delete(shared.channel);\n }\n if (this.#pendingTeardowns.get(shared.channel) === shared) {\n this.#pendingTeardowns.delete(shared.channel);\n }\n this.#teardownSubscription(shared);\n shared.publicationHandlers.clear();\n shared.subscribedHandlers.clear();\n shared.unsubscribedHandlers.clear();\n shared.errorHandlers.clear();\n }\n\n for (const { error, errorHandlers, closeHandlers } of notifications) {\n for (const handler of errorHandlers) handler(error);\n for (const handler of closeHandlers) handler();\n }\n }\n\n #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 }\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\") {\n const reconnect = shared.client?.state === \"disconnected\";\n const resubscribe = shared.sub?.state === \"unsubscribed\";\n // hasAuth() reads the token provider, so only call it when a restart is possible.\n if ((reconnect || resubscribe) && this.#hasAuth()) {\n if (reconnect) shared.client?.connect();\n if (resubscribe) shared.sub?.subscribe();\n }\n }\n\n 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,Q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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,KAAKtB,kBAAkB,QAAQ,KAAKG,mBAAmB;CAClE;CAEA,IAAI,iBAAyB;EACzB,OAAO,KAAKN,YAAY;CAC5B;CAEA,IAAI,iBAAyB;EACzB,IAAI,QAAQ;EACZ,KAAK,MAAM,UAAU,KAAKA,YAAY,OAAO,GACzC,SAAS,OAAO;EAEpB,OAAO;CACX;AACJ"}
@@ -70,7 +70,7 @@ var AccountSignerAuthService = class extends AuthService {
70
70
  const uri = resolveChallengeUri(options.uri ?? this.#challengeUri);
71
71
  const { message } = await this.createWalletChallenge({
72
72
  smartAccountAddress,
73
- signerAddress: accountSigner.accountAddress,
73
+ signerAddress: ownerAddress,
74
74
  uri,
75
75
  purpose: "login"
76
76
  });
@@ -1 +1 @@
1
- {"version":3,"file":"account-signer-auth.js","names":["#accountSignerConfig","#environmentFingerprint","#subaccounts","#tokenStorage","#realtime","#sessionStore","#assertAccountSignerEnvironment","#accountSigner","#accountIdentity","#identityFromSigner","#notifyStateChange","#login","#resolveAccountSigner","#challengeUri","#getEnvironmentSession","#loginMethod","#isAuthenticated","#mainAccountId","#activeAccountId","#walletProvider","#getEnvironmentBoundToken","#clearExpiredSessionState","#getCurrentTokenStorageOptions","#resolveRefreshProvider"],"sources":["../../../src/services/auth/account-signer-auth.ts"],"sourcesContent":["import { AuthService } from \"./auth.js\";\nimport { AuthenticationError, ConfigurationError } from \"../../shared/errors.js\";\nimport { AuthSessionStore } from \"./session.js\";\nimport type { AccountSigner, AccountSignerConfig, HexAddress } from \"../../account-signer/types.js\";\nimport { assertAccountSigner, resolveAccountSigner } from \"../../account-signer/types.js\";\nimport { EventEmitter } from \"../../utils/event-emitter.js\";\nimport { isJwtValid, getJwtTimeToExpiry } from \"../../utils/jwt.js\";\nimport type { SubaccountsService } from \"../subaccounts/index.js\";\nimport type {\n AuthState,\n AuthHydrationData,\n AuthLoginMethod,\n SessionData,\n ActiveAccountInfo,\n} from \"./session.types.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\nimport type { PolyesterEnvironment } from \"../../environment.js\";\nimport type { AuthAndPublicApiTransports } from \"../../shared/transports.js\";\nimport {\n createAuthTokenStorageSetOptions,\n type AuthTokenStorage,\n type AuthTokenStorageSetOptions,\n} from \"./token-storage.js\";\n\nexport interface AccountSignerAuthEvents {\n authenticated: { accountId: string; username: string };\n loggedOut: void;\n error: { code: string; message: string };\n servicesReady: void;\n stateChange: AuthState;\n}\n\nexport interface LoginResult {\n accountId: string;\n username: string;\n expiresAt: Date;\n}\n\nexport interface LoginOptions {\n /**\n * The wallet provider to use for login.\n */\n provider: \"metamask\" | \"turnkey\" | \"other\";\n /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */\n uri?: string;\n loginMethod?: AuthLoginMethod | null;\n}\n\nexport interface CreateSubaccountParams {\n /** The account signer for the new subaccount (caller derives this, e.g. via Turnkey saltNonce) */\n accountSigner: AccountSigner;\n /** Optional human-readable label for this subaccount */\n label?: string;\n /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */\n uri?: string;\n}\n\nexport interface CreateSubaccountResult {\n subaccountId: string;\n smartAccountSaltNonce: number;\n revision: string;\n}\n\ninterface AccountIdentity {\n accountAddress: HexAddress;\n ownerAddress?: HexAddress;\n}\n\n/**\n * Coordinates wallet/account-signer authentication, session storage, subaccount selection, and session refresh.\n */\nexport class AccountSignerAuthService extends AuthService {\n readonly events = new EventEmitter<AccountSignerAuthEvents>();\n\n #accountSignerConfig: AccountSignerConfig | undefined;\n #accountSigner: AccountSigner | null = null;\n #accountIdentity: AccountIdentity | null = null;\n #isAuthenticated = false;\n #mainAccountId: string | null = null;\n #activeAccountId: string | null = null;\n #subaccounts: SubaccountsService;\n #walletProvider: \"metamask\" | \"turnkey\" | \"other\" | undefined = undefined;\n #loginMethod: AuthLoginMethod | null = null;\n #challengeUri: string | undefined = undefined;\n #environmentFingerprint: string;\n #tokenStorage: AuthTokenStorage;\n #sessionStore: AuthSessionStore;\n #realtime: PolyesterRealtime;\n\n constructor({\n transports,\n accountSignerConfig,\n environment,\n subaccounts,\n realtime,\n tokenStorage,\n sessionStore,\n }: {\n transports: AuthAndPublicApiTransports;\n accountSignerConfig?: AccountSignerConfig;\n environment: PolyesterEnvironment;\n subaccounts: SubaccountsService;\n realtime: PolyesterRealtime;\n tokenStorage: AuthTokenStorage;\n sessionStore?: AuthSessionStore;\n }) {\n super(transports, realtime);\n\n this.#accountSignerConfig = accountSignerConfig;\n this.#environmentFingerprint = environment.fingerprint;\n this.#subaccounts = subaccounts;\n this.#tokenStorage = tokenStorage;\n this.#realtime = realtime;\n this.#sessionStore =\n sessionStore ??\n new AuthSessionStore({\n environmentFingerprint: environment.fingerprint,\n });\n }\n\n /**\n * Attaches the subaccounts service used when creating a subaccount during authenticated flows.\n */\n setSubaccountsService(subaccounts: SubaccountsService): void {\n this.#subaccounts = subaccounts;\n }\n\n /**\n * Sets the account signer used to sign login and account-switch challenges.\n */\n setAccountSigner(accountSigner: AccountSigner | null): void {\n if (accountSigner) this.#assertAccountSignerEnvironment(accountSigner);\n this.#accountSigner = accountSigner;\n this.#accountIdentity = accountSigner ? this.#identityFromSigner(accountSigner) : null;\n this.#notifyStateChange();\n }\n\n /**\n * Returns the active account signer, throwing if one has not been configured.\n */\n getAccountSigner(): AccountSigner | null {\n return this.#accountSigner;\n }\n\n /**\n * Signs a server-issued SIWE message with the configured account signer, exchanges it for a session token, and stores the hydrated account/subaccount session state.\n */\n async login(options: LoginOptions): Promise<LoginResult> {\n return this.#login(options);\n }\n\n async #login(\n options: LoginOptions,\n previousActiveAccount?: ActiveAccountInfo,\n ): Promise<LoginResult> {\n const { provider, loginMethod } = options;\n\n const accountSigner = await this.#resolveAccountSigner();\n\n if (!accountSigner) {\n throw new ConfigurationError(\n \"No account signer configured. Call setAccountSigner() or pass accountSigner in config.\",\n );\n }\n\n const smartAccountAddress = accountSigner.accountAddress;\n const ownerAddress = accountSigner.ownerAddress ?? accountSigner.accountAddress;\n\n const uri = resolveChallengeUri(options.uri ?? this.#challengeUri);\n const { message } = await this.createWalletChallenge({\n smartAccountAddress,\n signerAddress: accountSigner.accountAddress,\n uri,\n purpose: \"login\",\n });\n const signature = await accountSigner.signMessage(message);\n\n const response = await this.loginWithWallet({\n smartAccountAddress,\n message,\n signature,\n walletProvider: provider,\n });\n\n const environmentSession = this.#getEnvironmentSession();\n const resolvedLoginMethod =\n loginMethod ??\n this.#loginMethod ??\n environmentSession?.loginMethod ??\n (provider === \"metamask\" ? \"metamask\" : null);\n\n const tokenOptions = createAuthTokenStorageSetOptions(response.accessToken);\n const activeAccount =\n previousActiveAccount?.mainAccountId === response.accountId\n ? previousActiveAccount\n : undefined;\n this.#sessionStore.commitLogin(\n {\n accessToken: response.accessToken,\n tokenOptions,\n provider,\n loginMethod: resolvedLoginMethod,\n primaryWallet: ownerAddress,\n smartAccount: smartAccountAddress,\n accountId: response.accountId,\n activeAccount,\n username: response.username ?? undefined,\n },\n this.#tokenStorage,\n );\n this.#isAuthenticated = true;\n this.#mainAccountId = response.accountId;\n this.#activeAccountId = activeAccount?.accountId ?? response.accountId;\n this.#walletProvider = provider;\n this.#loginMethod = resolvedLoginMethod;\n this.#challengeUri = uri;\n this.#accountIdentity = this.#identityFromSigner(accountSigner);\n\n this.#notifyStateChange();\n\n this.events.emit(\"authenticated\", {\n accountId: response.accountId,\n username: response.username,\n });\n\n const expiresAt = response.expiresAt\n ? new Date(\n Number(response.expiresAt.seconds) * 1000 +\n (response.expiresAt.nanos ?? 0) / 1_000_000,\n )\n : new Date();\n\n return {\n accountId: response.accountId,\n username: response.username,\n expiresAt,\n };\n }\n\n /**\n * Builds auth state from a session token and optional active account override.\n */\n hydrateAuthState(state: AuthHydrationData): void {\n const existingToken = this.#getEnvironmentBoundToken();\n if (!existingToken || !isJwtValid(existingToken)) return;\n\n const existingSession = this.#getEnvironmentSession();\n this.#walletProvider = existingSession?.provider ?? this.#walletProvider;\n this.#loginMethod = existingSession?.loginMethod ?? this.#loginMethod;\n\n this.#isAuthenticated = true;\n this.#mainAccountId = state.mainAccountId;\n this.#activeAccountId = state.activeAccountId ?? state.mainAccountId;\n this.#accountIdentity = state.smartAccountAddress\n ? {\n accountAddress: state.smartAccountAddress,\n ownerAddress: state.ownerAddress,\n }\n : null;\n\n this.#notifyStateChange();\n }\n\n /**\n * Loads the stored token, validates that it still belongs to this environment, and restores auth state when possible.\n */\n async restoreSession(): Promise<{ accountId: string; username: string } | null> {\n const existingToken = this.#getEnvironmentBoundToken();\n\n if (!existingToken || !isJwtValid(existingToken)) {\n this.#clearExpiredSessionState();\n return null;\n }\n\n try {\n const me = await this.me();\n this.#isAuthenticated = true;\n this.#mainAccountId = me.accountId;\n\n // preserve active account if already set (e.g. via hydration), otherwise use main\n const existingSession = this.#getEnvironmentSession();\n this.#walletProvider = existingSession?.provider ?? this.#walletProvider;\n this.#loginMethod = existingSession?.loginMethod ?? this.#loginMethod;\n if (!this.#activeAccountId) {\n this.#activeAccountId = existingSession?.activeAccount?.accountId ?? me.accountId;\n }\n\n // use existing account signer if set, otherwise try to resolve from config\n if (!this.#accountSigner) {\n this.#accountSigner = await resolveAccountSigner(this.#accountSignerConfig);\n if (this.#accountSigner) {\n this.#assertAccountSignerEnvironment(this.#accountSigner);\n this.#accountIdentity = this.#identityFromSigner(this.#accountSigner);\n }\n }\n\n // keep the display session available for SSR hydration\n if (this.#accountSigner?.accountAddress) {\n const session = this.#sessionStore.ensureSession(\n {\n provider: this.#walletProvider ? this.#walletProvider : \"other\",\n loginMethod:\n this.#loginMethod ??\n (this.#walletProvider === \"metamask\" ? \"metamask\" : null),\n primaryWallet:\n this.#accountSigner.ownerAddress ?? this.#accountSigner.accountAddress,\n smartAccount: this.#accountSigner.accountAddress,\n accountId: me.accountId,\n username: me.username ?? undefined,\n },\n { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds },\n );\n this.#walletProvider = session.provider;\n this.#loginMethod = session.loginMethod ?? this.#loginMethod;\n }\n\n this.#notifyStateChange();\n return { accountId: me.accountId, username: me.username };\n } catch {\n this.#clearExpiredSessionState();\n return null;\n }\n }\n\n /**\n * Clears stored auth state and removes the persisted auth token.\n */\n async logout(): Promise<void> {\n this.#realtime.disconnectPrivate();\n this.#tokenStorage.clear();\n this.#isAuthenticated = false;\n this.#mainAccountId = null;\n this.#activeAccountId = null;\n this.#loginMethod = null;\n this.#challengeUri = undefined;\n this.#accountIdentity = null;\n\n this.#sessionStore.clear();\n\n this.#notifyStateChange();\n this.events.emit(\"loggedOut\", undefined);\n }\n\n #clearExpiredSessionState(): void {\n const shouldEmitLoggedOut = this.#isAuthenticated;\n this.#realtime.disconnectPrivate();\n this.#tokenStorage.clear();\n this.#sessionStore.clear();\n this.#isAuthenticated = false;\n this.#mainAccountId = null;\n this.#activeAccountId = null;\n this.#loginMethod = null;\n this.#challengeUri = undefined;\n this.#accountIdentity = null;\n this.#notifyStateChange();\n if (shouldEmitLoggedOut) {\n this.events.emit(\"loggedOut\", undefined);\n }\n }\n\n /**\n * Returns the remaining lifetime of the stored session token in milliseconds.\n */\n getSessionTimeToExpiry(): number {\n const token = this.#getEnvironmentBoundToken();\n if (!token) return 0;\n return getJwtTimeToExpiry(token);\n }\n\n /**\n * Refreshes the active account-signer session and updates persisted auth state.\n */\n async refreshSession(params?: {\n /** Overrides the origin remembered from login. */\n uri?: string;\n provider?: \"metamask\" | \"turnkey\" | \"other\";\n loginMethod?: AuthLoginMethod | null;\n }): Promise<LoginResult> {\n if (!this.#isAuthenticated) {\n throw new AuthenticationError(\"Must be authenticated to refresh session\");\n }\n\n const currentSession = this.#getEnvironmentSession();\n return this.#login(\n {\n provider: this.#resolveRefreshProvider(params?.provider),\n uri: params?.uri,\n loginMethod: params?.loginMethod ?? this.#loginMethod,\n },\n currentSession?.activeAccount,\n );\n }\n\n /**\n * Switches the active account/subaccount by signing the required account switch flow.\n */\n switchAccount(\n accountId: string,\n options?: { smartAccountAddress?: string; label?: string },\n ): { accountId: string; isMain: boolean } {\n if (!this.#isAuthenticated || !this.#mainAccountId) {\n throw new AuthenticationError(\"Must be authenticated to switch accounts\");\n }\n\n this.#activeAccountId = accountId;\n const isMain = accountId === this.#mainAccountId;\n\n this.#sessionStore.setActiveAccount(\n {\n accountId,\n isMain,\n smartAccountAddress: options?.smartAccountAddress,\n label: options?.label,\n },\n { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds },\n );\n this.#notifyStateChange();\n\n return { accountId, isMain };\n }\n\n /** Keeps the display-session identity current for the next server render. */\n syncSessionUsername(username: string | null): void {\n this.#sessionStore.setUsername(username, {\n maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds,\n });\n }\n\n /**\n * Creates a subaccount for the authenticated account and makes it available to the session state.\n */\n async createSubaccount(params: CreateSubaccountParams): Promise<CreateSubaccountResult> {\n if (!this.#isAuthenticated) {\n throw new AuthenticationError(\"Must be authenticated to create subaccounts\");\n }\n\n if (!this.#subaccounts) {\n throw new ConfigurationError(\n \"SubaccountsService not configured. Pass it to constructor or call setSubaccountsService().\",\n );\n }\n\n const { accountSigner, label = \"\" } = params;\n this.#assertAccountSignerEnvironment(accountSigner);\n\n const { message } = await this.createWalletChallenge({\n smartAccountAddress: accountSigner.accountAddress,\n signerAddress: accountSigner.accountAddress,\n uri: resolveChallengeUri(params.uri ?? this.#challengeUri),\n purpose: \"create_subaccount\",\n });\n const signature = await accountSigner.signMessage(message);\n\n const response = await this.#subaccounts.create({\n label,\n smartAccountAddress: accountSigner.accountAddress,\n message,\n signature,\n });\n\n return {\n subaccountId: response.subaccountId,\n smartAccountSaltNonce: response.smartAccountSaltNonce,\n revision: response.revision,\n };\n }\n\n /**\n * Returns the current account-signer auth state snapshot.\n */\n getState(): AuthState {\n const accountIdentity = this.#accountSigner ?? this.#accountIdentity;\n\n return {\n isAuthenticated: this.#isAuthenticated,\n accountAddress: accountIdentity?.accountAddress ?? null,\n ownerAddress: accountIdentity?.ownerAddress ?? null,\n mainAccountId: this.#mainAccountId,\n activeAccount:\n this.#activeAccountId && this.#mainAccountId\n ? {\n accountId: this.#activeAccountId,\n isMain: this.#activeAccountId === this.#mainAccountId,\n mainAccountId: this.#mainAccountId,\n smartAccountAddress: accountIdentity?.accountAddress,\n }\n : null,\n };\n }\n\n async #resolveAccountSigner(): Promise<AccountSigner | null> {\n if (this.#accountSigner) {\n this.#assertAccountSignerEnvironment(this.#accountSigner);\n return this.#accountSigner;\n }\n\n const resolved = await resolveAccountSigner(this.#accountSignerConfig);\n if (resolved) {\n this.#assertAccountSignerEnvironment(resolved);\n this.#accountSigner = resolved;\n this.#accountIdentity = this.#identityFromSigner(resolved);\n }\n return this.#accountSigner;\n }\n\n #notifyStateChange(): void {\n this.events.emit(\"stateChange\", this.getState());\n }\n\n #getEnvironmentBoundToken(): string | null {\n return this.#sessionStore.getEnvironmentBoundToken(this.#tokenStorage);\n }\n\n #getCurrentTokenStorageOptions(): AuthTokenStorageSetOptions {\n const token = this.#tokenStorage.get();\n if (!token) return { expiresAt: null, maxAgeSeconds: null };\n return createAuthTokenStorageSetOptions(token);\n }\n\n #resolveRefreshProvider(\n provider?: \"metamask\" | \"turnkey\" | \"other\",\n ): \"metamask\" | \"turnkey\" | \"other\" {\n return (\n provider ?? this.#walletProvider ?? this.#getEnvironmentSession()?.provider ?? \"other\"\n );\n }\n\n #assertAccountSignerEnvironment(accountSigner: AccountSigner): void {\n assertAccountSigner(accountSigner);\n if (accountSigner.environmentFingerprint !== this.#environmentFingerprint) {\n throw new ConfigurationError(\n \"Account signer environment does not match client environment.\",\n );\n }\n }\n\n #identityFromSigner(accountSigner: AccountSigner): AccountIdentity {\n return {\n accountAddress: accountSigner.accountAddress,\n ownerAddress: accountSigner.ownerAddress,\n };\n }\n\n #getEnvironmentSession(): SessionData | null {\n return this.#sessionStore.get();\n }\n}\n\nfunction resolveChallengeUri(uri: string | undefined): string {\n const resolved = uri ?? (typeof location === \"undefined\" ? undefined : location.origin);\n if (!resolved)\n throw new ConfigurationError(\n \"Wallet authentication requires a browser origin URI. Pass uri outside a browser.\",\n );\n return resolved;\n}\n"],"mappings":";;;;;;;;;;;AAuEA,IAAa,2BAAb,cAA8C,YAAY;CACtD,SAAkB,IAAI,aAAsC;CAE5D;CACA,iBAAuC;CACvC,mBAA2C;CAC3C,mBAAmB;CACnB,iBAAgC;CAChC,mBAAkC;CAClC;CACA,kBAAgE,KAAA;CAChE,eAAuC;CACvC,gBAAoC,KAAA;CACpC;CACA;CACA;CACA;CAEA,YAAY,EACR,YACA,qBACA,aACA,aACA,UACA,cACA,gBASD;EACC,MAAM,YAAY,QAAQ;EAE1B,KAAKA,uBAAuB;EAC5B,KAAKC,0BAA0B,YAAY;EAC3C,KAAKC,eAAe;EACpB,KAAKC,gBAAgB;EACrB,KAAKC,YAAY;EACjB,KAAKC,gBACD,gBACA,IAAI,iBAAiB,EACjB,wBAAwB,YAAY,YACxC,CAAC;CACT;;;;CAKA,sBAAsB,aAAuC;EACzD,KAAKH,eAAe;CACxB;;;;CAKA,iBAAiB,eAA2C;EACxD,IAAI,eAAe,KAAKI,gCAAgC,aAAa;EACrE,KAAKC,iBAAiB;EACtB,KAAKC,mBAAmB,gBAAgB,KAAKC,oBAAoB,aAAa,IAAI;EAClF,KAAKC,mBAAmB;CAC5B;;;;CAKA,mBA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KAAKgB,mBAAmB,KAAKL,uBAAuB,CAAC,EAAE,YAAY;CAEvF;CAEA,gCAAgC,eAAoC;EAChE,oBAAoB,aAAa;EACjC,IAAI,cAAc,2BAA2B,KAAKb,yBAC9C,MAAM,IAAI,mBACN,+DACJ;CAER;CAEA,oBAAoB,eAA+C;EAC/D,OAAO;GACH,gBAAgB,cAAc;GAC9B,cAAc,cAAc;EAChC;CACJ;CAEA,yBAA6C;EACzC,OAAO,KAAKI,cAAc,IAAI;CAClC;AACJ;AAEA,SAAS,oBAAoB,KAAiC;CAC1D,MAAM,WAAW,QAAQ,OAAO,aAAa,cAAc,KAAA,IAAY,SAAS;CAChF,IAAI,CAAC,UACD,MAAM,IAAI,mBACN,kFACJ;CACJ,OAAO;AACX"}
1
+ {"version":3,"file":"account-signer-auth.js","names":["#accountSignerConfig","#environmentFingerprint","#subaccounts","#tokenStorage","#realtime","#sessionStore","#assertAccountSignerEnvironment","#accountSigner","#accountIdentity","#identityFromSigner","#notifyStateChange","#login","#resolveAccountSigner","#challengeUri","#getEnvironmentSession","#loginMethod","#isAuthenticated","#mainAccountId","#activeAccountId","#walletProvider","#getEnvironmentBoundToken","#clearExpiredSessionState","#getCurrentTokenStorageOptions","#resolveRefreshProvider"],"sources":["../../../src/services/auth/account-signer-auth.ts"],"sourcesContent":["import { AuthService } from \"./auth.js\";\nimport { AuthenticationError, ConfigurationError } from \"../../shared/errors.js\";\nimport { AuthSessionStore } from \"./session.js\";\nimport type { AccountSigner, AccountSignerConfig, HexAddress } from \"../../account-signer/types.js\";\nimport { assertAccountSigner, resolveAccountSigner } from \"../../account-signer/types.js\";\nimport { EventEmitter } from \"../../utils/event-emitter.js\";\nimport { isJwtValid, getJwtTimeToExpiry } from \"../../utils/jwt.js\";\nimport type { SubaccountsService } from \"../subaccounts/index.js\";\nimport type {\n AuthState,\n AuthHydrationData,\n AuthLoginMethod,\n SessionData,\n ActiveAccountInfo,\n} from \"./session.types.js\";\nimport type { PolyesterRealtime } from \"../../realtime/index.js\";\nimport type { PolyesterEnvironment } from \"../../environment.js\";\nimport type { AuthAndPublicApiTransports } from \"../../shared/transports.js\";\nimport {\n createAuthTokenStorageSetOptions,\n type AuthTokenStorage,\n type AuthTokenStorageSetOptions,\n} from \"./token-storage.js\";\n\nexport interface AccountSignerAuthEvents {\n authenticated: { accountId: string; username: string };\n loggedOut: void;\n error: { code: string; message: string };\n servicesReady: void;\n stateChange: AuthState;\n}\n\nexport interface LoginResult {\n accountId: string;\n username: string;\n expiresAt: Date;\n}\n\nexport interface LoginOptions {\n /**\n * The wallet provider to use for login.\n */\n provider: \"metamask\" | \"turnkey\" | \"other\";\n /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */\n uri?: string;\n loginMethod?: AuthLoginMethod | null;\n}\n\nexport interface CreateSubaccountParams {\n /** The account signer for the new subaccount (caller derives this, e.g. via Turnkey saltNonce) */\n accountSigner: AccountSigner;\n /** Optional human-readable label for this subaccount */\n label?: string;\n /** Browser origin requesting the signature; defaults to location.origin in browsers. Required outside browsers. */\n uri?: string;\n}\n\nexport interface CreateSubaccountResult {\n subaccountId: string;\n smartAccountSaltNonce: number;\n revision: string;\n}\n\ninterface AccountIdentity {\n accountAddress: HexAddress;\n ownerAddress?: HexAddress;\n}\n\n/**\n * Coordinates wallet/account-signer authentication, session storage, subaccount selection, and session refresh.\n */\nexport class AccountSignerAuthService extends AuthService {\n readonly events = new EventEmitter<AccountSignerAuthEvents>();\n\n #accountSignerConfig: AccountSignerConfig | undefined;\n #accountSigner: AccountSigner | null = null;\n #accountIdentity: AccountIdentity | null = null;\n #isAuthenticated = false;\n #mainAccountId: string | null = null;\n #activeAccountId: string | null = null;\n #subaccounts: SubaccountsService;\n #walletProvider: \"metamask\" | \"turnkey\" | \"other\" | undefined = undefined;\n #loginMethod: AuthLoginMethod | null = null;\n #challengeUri: string | undefined = undefined;\n #environmentFingerprint: string;\n #tokenStorage: AuthTokenStorage;\n #sessionStore: AuthSessionStore;\n #realtime: PolyesterRealtime;\n\n constructor({\n transports,\n accountSignerConfig,\n environment,\n subaccounts,\n realtime,\n tokenStorage,\n sessionStore,\n }: {\n transports: AuthAndPublicApiTransports;\n accountSignerConfig?: AccountSignerConfig;\n environment: PolyesterEnvironment;\n subaccounts: SubaccountsService;\n realtime: PolyesterRealtime;\n tokenStorage: AuthTokenStorage;\n sessionStore?: AuthSessionStore;\n }) {\n super(transports, realtime);\n\n this.#accountSignerConfig = accountSignerConfig;\n this.#environmentFingerprint = environment.fingerprint;\n this.#subaccounts = subaccounts;\n this.#tokenStorage = tokenStorage;\n this.#realtime = realtime;\n this.#sessionStore =\n sessionStore ??\n new AuthSessionStore({\n environmentFingerprint: environment.fingerprint,\n });\n }\n\n /**\n * Attaches the subaccounts service used when creating a subaccount during authenticated flows.\n */\n setSubaccountsService(subaccounts: SubaccountsService): void {\n this.#subaccounts = subaccounts;\n }\n\n /**\n * Sets the account signer used to sign login and account-switch challenges.\n */\n setAccountSigner(accountSigner: AccountSigner | null): void {\n if (accountSigner) this.#assertAccountSignerEnvironment(accountSigner);\n this.#accountSigner = accountSigner;\n this.#accountIdentity = accountSigner ? this.#identityFromSigner(accountSigner) : null;\n this.#notifyStateChange();\n }\n\n /**\n * Returns the active account signer, throwing if one has not been configured.\n */\n getAccountSigner(): AccountSigner | null {\n return this.#accountSigner;\n }\n\n /**\n * Signs a server-issued SIWE message with the configured account signer, exchanges it for a session token, and stores the hydrated account/subaccount session state.\n */\n async login(options: LoginOptions): Promise<LoginResult> {\n return this.#login(options);\n }\n\n async #login(\n options: LoginOptions,\n previousActiveAccount?: ActiveAccountInfo,\n ): Promise<LoginResult> {\n const { provider, loginMethod } = options;\n\n const accountSigner = await this.#resolveAccountSigner();\n\n if (!accountSigner) {\n throw new ConfigurationError(\n \"No account signer configured. Call setAccountSigner() or pass accountSigner in config.\",\n );\n }\n\n const smartAccountAddress = accountSigner.accountAddress;\n const ownerAddress = accountSigner.ownerAddress ?? accountSigner.accountAddress;\n\n const uri = resolveChallengeUri(options.uri ?? this.#challengeUri);\n const { message } = await this.createWalletChallenge({\n smartAccountAddress,\n signerAddress: ownerAddress,\n uri,\n purpose: \"login\",\n });\n const signature = await accountSigner.signMessage(message);\n\n const response = await this.loginWithWallet({\n smartAccountAddress,\n message,\n signature,\n walletProvider: provider,\n });\n\n const environmentSession = this.#getEnvironmentSession();\n const resolvedLoginMethod =\n loginMethod ??\n this.#loginMethod ??\n environmentSession?.loginMethod ??\n (provider === \"metamask\" ? \"metamask\" : null);\n\n const tokenOptions = createAuthTokenStorageSetOptions(response.accessToken);\n const activeAccount =\n previousActiveAccount?.mainAccountId === response.accountId\n ? previousActiveAccount\n : undefined;\n this.#sessionStore.commitLogin(\n {\n accessToken: response.accessToken,\n tokenOptions,\n provider,\n loginMethod: resolvedLoginMethod,\n primaryWallet: ownerAddress,\n smartAccount: smartAccountAddress,\n accountId: response.accountId,\n activeAccount,\n username: response.username ?? undefined,\n },\n this.#tokenStorage,\n );\n this.#isAuthenticated = true;\n this.#mainAccountId = response.accountId;\n this.#activeAccountId = activeAccount?.accountId ?? response.accountId;\n this.#walletProvider = provider;\n this.#loginMethod = resolvedLoginMethod;\n this.#challengeUri = uri;\n this.#accountIdentity = this.#identityFromSigner(accountSigner);\n\n this.#notifyStateChange();\n\n this.events.emit(\"authenticated\", {\n accountId: response.accountId,\n username: response.username,\n });\n\n const expiresAt = response.expiresAt\n ? new Date(\n Number(response.expiresAt.seconds) * 1000 +\n (response.expiresAt.nanos ?? 0) / 1_000_000,\n )\n : new Date();\n\n return {\n accountId: response.accountId,\n username: response.username,\n expiresAt,\n };\n }\n\n /**\n * Builds auth state from a session token and optional active account override.\n */\n hydrateAuthState(state: AuthHydrationData): void {\n const existingToken = this.#getEnvironmentBoundToken();\n if (!existingToken || !isJwtValid(existingToken)) return;\n\n const existingSession = this.#getEnvironmentSession();\n this.#walletProvider = existingSession?.provider ?? this.#walletProvider;\n this.#loginMethod = existingSession?.loginMethod ?? this.#loginMethod;\n\n this.#isAuthenticated = true;\n this.#mainAccountId = state.mainAccountId;\n this.#activeAccountId = state.activeAccountId ?? state.mainAccountId;\n this.#accountIdentity = state.smartAccountAddress\n ? {\n accountAddress: state.smartAccountAddress,\n ownerAddress: state.ownerAddress,\n }\n : null;\n\n this.#notifyStateChange();\n }\n\n /**\n * Loads the stored token, validates that it still belongs to this environment, and restores auth state when possible.\n */\n async restoreSession(): Promise<{ accountId: string; username: string } | null> {\n const existingToken = this.#getEnvironmentBoundToken();\n\n if (!existingToken || !isJwtValid(existingToken)) {\n this.#clearExpiredSessionState();\n return null;\n }\n\n try {\n const me = await this.me();\n this.#isAuthenticated = true;\n this.#mainAccountId = me.accountId;\n\n // preserve active account if already set (e.g. via hydration), otherwise use main\n const existingSession = this.#getEnvironmentSession();\n this.#walletProvider = existingSession?.provider ?? this.#walletProvider;\n this.#loginMethod = existingSession?.loginMethod ?? this.#loginMethod;\n if (!this.#activeAccountId) {\n this.#activeAccountId = existingSession?.activeAccount?.accountId ?? me.accountId;\n }\n\n // use existing account signer if set, otherwise try to resolve from config\n if (!this.#accountSigner) {\n this.#accountSigner = await resolveAccountSigner(this.#accountSignerConfig);\n if (this.#accountSigner) {\n this.#assertAccountSignerEnvironment(this.#accountSigner);\n this.#accountIdentity = this.#identityFromSigner(this.#accountSigner);\n }\n }\n\n // keep the display session available for SSR hydration\n if (this.#accountSigner?.accountAddress) {\n const session = this.#sessionStore.ensureSession(\n {\n provider: this.#walletProvider ? this.#walletProvider : \"other\",\n loginMethod:\n this.#loginMethod ??\n (this.#walletProvider === \"metamask\" ? \"metamask\" : null),\n primaryWallet:\n this.#accountSigner.ownerAddress ?? this.#accountSigner.accountAddress,\n smartAccount: this.#accountSigner.accountAddress,\n accountId: me.accountId,\n username: me.username ?? undefined,\n },\n { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds },\n );\n this.#walletProvider = session.provider;\n this.#loginMethod = session.loginMethod ?? this.#loginMethod;\n }\n\n this.#notifyStateChange();\n return { accountId: me.accountId, username: me.username };\n } catch {\n this.#clearExpiredSessionState();\n return null;\n }\n }\n\n /**\n * Clears stored auth state and removes the persisted auth token.\n */\n async logout(): Promise<void> {\n this.#realtime.disconnectPrivate();\n this.#tokenStorage.clear();\n this.#isAuthenticated = false;\n this.#mainAccountId = null;\n this.#activeAccountId = null;\n this.#loginMethod = null;\n this.#challengeUri = undefined;\n this.#accountIdentity = null;\n\n this.#sessionStore.clear();\n\n this.#notifyStateChange();\n this.events.emit(\"loggedOut\", undefined);\n }\n\n #clearExpiredSessionState(): void {\n const shouldEmitLoggedOut = this.#isAuthenticated;\n this.#realtime.disconnectPrivate();\n this.#tokenStorage.clear();\n this.#sessionStore.clear();\n this.#isAuthenticated = false;\n this.#mainAccountId = null;\n this.#activeAccountId = null;\n this.#loginMethod = null;\n this.#challengeUri = undefined;\n this.#accountIdentity = null;\n this.#notifyStateChange();\n if (shouldEmitLoggedOut) {\n this.events.emit(\"loggedOut\", undefined);\n }\n }\n\n /**\n * Returns the remaining lifetime of the stored session token in milliseconds.\n */\n getSessionTimeToExpiry(): number {\n const token = this.#getEnvironmentBoundToken();\n if (!token) return 0;\n return getJwtTimeToExpiry(token);\n }\n\n /**\n * Refreshes the active account-signer session and updates persisted auth state.\n */\n async refreshSession(params?: {\n /** Overrides the origin remembered from login. */\n uri?: string;\n provider?: \"metamask\" | \"turnkey\" | \"other\";\n loginMethod?: AuthLoginMethod | null;\n }): Promise<LoginResult> {\n if (!this.#isAuthenticated) {\n throw new AuthenticationError(\"Must be authenticated to refresh session\");\n }\n\n const currentSession = this.#getEnvironmentSession();\n return this.#login(\n {\n provider: this.#resolveRefreshProvider(params?.provider),\n uri: params?.uri,\n loginMethod: params?.loginMethod ?? this.#loginMethod,\n },\n currentSession?.activeAccount,\n );\n }\n\n /**\n * Switches the active account/subaccount by signing the required account switch flow.\n */\n switchAccount(\n accountId: string,\n options?: { smartAccountAddress?: string; label?: string },\n ): { accountId: string; isMain: boolean } {\n if (!this.#isAuthenticated || !this.#mainAccountId) {\n throw new AuthenticationError(\"Must be authenticated to switch accounts\");\n }\n\n this.#activeAccountId = accountId;\n const isMain = accountId === this.#mainAccountId;\n\n this.#sessionStore.setActiveAccount(\n {\n accountId,\n isMain,\n smartAccountAddress: options?.smartAccountAddress,\n label: options?.label,\n },\n { maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds },\n );\n this.#notifyStateChange();\n\n return { accountId, isMain };\n }\n\n /** Keeps the display-session identity current for the next server render. */\n syncSessionUsername(username: string | null): void {\n this.#sessionStore.setUsername(username, {\n maxAgeSeconds: this.#getCurrentTokenStorageOptions().maxAgeSeconds,\n });\n }\n\n /**\n * Creates a subaccount for the authenticated account and makes it available to the session state.\n */\n async createSubaccount(params: CreateSubaccountParams): Promise<CreateSubaccountResult> {\n if (!this.#isAuthenticated) {\n throw new AuthenticationError(\"Must be authenticated to create subaccounts\");\n }\n\n if (!this.#subaccounts) {\n throw new ConfigurationError(\n \"SubaccountsService not configured. Pass it to constructor or call setSubaccountsService().\",\n );\n }\n\n const { accountSigner, label = \"\" } = params;\n this.#assertAccountSignerEnvironment(accountSigner);\n\n const { message } = await this.createWalletChallenge({\n smartAccountAddress: accountSigner.accountAddress,\n signerAddress: accountSigner.accountAddress,\n uri: resolveChallengeUri(params.uri ?? this.#challengeUri),\n purpose: \"create_subaccount\",\n });\n const signature = await accountSigner.signMessage(message);\n\n const response = await this.#subaccounts.create({\n label,\n smartAccountAddress: accountSigner.accountAddress,\n message,\n signature,\n });\n\n return {\n subaccountId: response.subaccountId,\n smartAccountSaltNonce: response.smartAccountSaltNonce,\n revision: response.revision,\n };\n }\n\n /**\n * Returns the current account-signer auth state snapshot.\n */\n getState(): AuthState {\n const accountIdentity = this.#accountSigner ?? this.#accountIdentity;\n\n return {\n isAuthenticated: this.#isAuthenticated,\n accountAddress: accountIdentity?.accountAddress ?? null,\n ownerAddress: accountIdentity?.ownerAddress ?? null,\n mainAccountId: this.#mainAccountId,\n activeAccount:\n this.#activeAccountId && this.#mainAccountId\n ? {\n accountId: this.#activeAccountId,\n isMain: this.#activeAccountId === this.#mainAccountId,\n mainAccountId: this.#mainAccountId,\n smartAccountAddress: accountIdentity?.accountAddress,\n }\n : null,\n };\n }\n\n async #resolveAccountSigner(): Promise<AccountSigner | null> {\n if (this.#accountSigner) {\n this.#assertAccountSignerEnvironment(this.#accountSigner);\n return this.#accountSigner;\n }\n\n const resolved = await resolveAccountSigner(this.#accountSignerConfig);\n if (resolved) {\n this.#assertAccountSignerEnvironment(resolved);\n this.#accountSigner = resolved;\n this.#accountIdentity = this.#identityFromSigner(resolved);\n }\n return this.#accountSigner;\n }\n\n #notifyStateChange(): void {\n this.events.emit(\"stateChange\", this.getState());\n }\n\n #getEnvironmentBoundToken(): string | null {\n return this.#sessionStore.getEnvironmentBoundToken(this.#tokenStorage);\n }\n\n #getCurrentTokenStorageOptions(): AuthTokenStorageSetOptions {\n const token = this.#tokenStorage.get();\n if (!token) return { expiresAt: null, maxAgeSeconds: null };\n return createAuthTokenStorageSetOptions(token);\n }\n\n #resolveRefreshProvider(\n provider?: \"metamask\" | \"turnkey\" | \"other\",\n ): \"metamask\" | \"turnkey\" | \"other\" {\n return (\n provider ?? this.#walletProvider ?? this.#getEnvironmentSession()?.provider ?? \"other\"\n );\n }\n\n #assertAccountSignerEnvironment(accountSigner: AccountSigner): void {\n assertAccountSigner(accountSigner);\n if (accountSigner.environmentFingerprint !== this.#environmentFingerprint) {\n throw new ConfigurationError(\n \"Account signer environment does not match client environment.\",\n );\n }\n }\n\n #identityFromSigner(accountSigner: AccountSigner): AccountIdentity {\n return {\n accountAddress: accountSigner.accountAddress,\n ownerAddress: accountSigner.ownerAddress,\n };\n }\n\n #getEnvironmentSession(): SessionData | null {\n return this.#sessionStore.get();\n }\n}\n\nfunction resolveChallengeUri(uri: string | undefined): string {\n const resolved = uri ?? (typeof location === \"undefined\" ? undefined : location.origin);\n if (!resolved)\n throw new ConfigurationError(\n \"Wallet authentication requires a browser origin URI. Pass uri outside a browser.\",\n );\n return resolved;\n}\n"],"mappings":";;;;;;;;;;;AAuEA,IAAa,2BAAb,cAA8C,YAAY;CACtD,SAAkB,IAAI,aAAsC;CAE5D;CACA,iBAAuC;CACvC,mBAA2C;CAC3C,mBAAmB;CACnB,iBAAgC;CAChC,mBAAkC;CAClC;CACA,kBAAgE,KAAA;CAChE,eAAuC;CACvC,gBAAoC,KAAA;CACpC;CACA;CACA;CACA;CAEA,YAAY,EACR,YACA,qBACA,aACA,aACA,UACA,cACA,gBASD;EACC,MAAM,YAAY,QAAQ;EAE1B,KAAKA,uBAAuB;EAC5B,KAAKC,0BAA0B,YAAY;EAC3C,KAAKC,eAAe;EACpB,KAAKC,gBAAgB;EACrB,KAAKC,YAAY;EACjB,KAAKC,gBACD,gBACA,IAAI,iBAAiB,EACjB,wBAAwB,YAAY,YACxC,CAAC;CACT;;;;CAKA,sBAAsB,aAAuC;EACzD,KAAKH,eAAe;CACxB;;;;CAKA,iBAAiB,eAA2C;EACxD,IAAI,eAAe,KAAKI,gCAAgC,aAAa;EACrE,KAAKC,iBAAiB;EACtB,KAAKC,mBAAmB,gBAAgB,KAAKC,oBAAoB,aAAa,IAAI;EAClF,KAAKC,mBAAmB;CAC5B;;;;CAKA,mBAAyC;EACrC,OAAO,KAAKH;CAChB;;;;CAKA,MAAM,MAAM,SAA6C;EACrD,OAAO,KAAKI,OAAO,OAAO;CAC9B;CAEA,MAAMA,OACF,SACA,uBACoB;EACpB,MAAM,EAAE,UAAU,gBAAgB;EAElC,MAAM,gBAAgB,MAAM,KAAKC,sBAAsB;EAEvD,IAAI,CAAC,eACD,MAAM,IAAI,mBACN,wFACJ;EAGJ,MAAM,sBAAsB,cAAc;EAC1C,MAAM,eAAe,cAAc,gBAAgB,cAAc;EAEjE,MAAM,MAAM,oBAAoB,QAAQ,OAAO,KAAKC,aAAa;EACjE,MAAM,EAAE,YAAY,MAAM,KAAK,sBAAsB;GACjD;GACA,eAAe;GACf;G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ACJ;CACJ,OAAO;AACX"}
@@ -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" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">>]>;
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>;
@@ -22,7 +22,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
22
22
  readonly isClosed: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
23
23
  }, undefined>, v.TransformAction<{
24
24
  symbolId: number;
25
- timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">;
25
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
26
26
  tsSec: bigint;
27
27
  open: bigint;
28
28
  high: bigint;
@@ -33,7 +33,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
33
33
  isClosed: boolean;
34
34
  }, {
35
35
  symbolId: number;
36
- timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">;
36
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
37
37
  time: number;
38
38
  open: string;
39
39
  high: string;
@@ -46,7 +46,7 @@ declare function createCandleRowSchema(scales: SdkScales): v.SchemaWithPipe<read
46
46
  declare const createCandleRowIntSchema: typeof createCandleRowSchema;
47
47
  declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
48
48
  readonly symbolId: v.NumberSchema<undefined>;
49
- readonly timeframe: v.SchemaWithPipe<readonly [v.EnumSchema<typeof Timeframe$1, undefined>, v.TransformAction<Timeframe$1, DecodedEnum<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">>]>;
49
+ 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">>]>;
50
50
  readonly tsSec: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
51
51
  readonly open: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
52
52
  readonly high: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
@@ -63,7 +63,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
63
63
  readonly nextPageToken: v.OptionalSchema<v.StringSchema<undefined>, "">;
64
64
  }, undefined>, v.TransformAction<{
65
65
  symbolId: number;
66
- timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">;
66
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
67
67
  tsSec: bigint[];
68
68
  open: bigint[];
69
69
  high: bigint[];
@@ -80,7 +80,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
80
80
  nextPageToken: string;
81
81
  }, {
82
82
  symbolId: number;
83
- timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">;
83
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
84
84
  time: number[];
85
85
  open: string[];
86
86
  high: string[];
@@ -100,7 +100,7 @@ declare function createCandleColumnarSchema(scales: SdkScales): v.SchemaWithPipe
100
100
  }>]>;
101
101
  declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.ObjectSchema<{
102
102
  readonly symbolId: v.NumberSchema<undefined>;
103
- readonly timeframe: v.SchemaWithPipe<readonly [v.EnumSchema<typeof Timeframe$1, undefined>, v.TransformAction<Timeframe$1, DecodedEnum<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">>]>;
103
+ 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">>]>;
104
104
  readonly tsSec: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
105
105
  readonly open: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
106
106
  readonly high: v.ArraySchema<v.BigintSchema<undefined>, undefined>;
@@ -117,7 +117,7 @@ declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithP
117
117
  readonly nextPageToken: v.OptionalSchema<v.StringSchema<undefined>, "">;
118
118
  }, undefined>, v.TransformAction<{
119
119
  symbolId: number;
120
- timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">;
120
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
121
121
  tsSec: bigint[];
122
122
  open: bigint[];
123
123
  high: bigint[];
@@ -134,7 +134,7 @@ declare function createCandleColumnarIntSchema(scales: SdkScales): v.SchemaWithP
134
134
  nextPageToken: string;
135
135
  }, {
136
136
  symbolId: number;
137
- timeframe: DecodedEnum<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "1mo">;
137
+ timeframe: DecodedEnum<"1d" | "1h" | "1w" | "1m" | "1s" | "5m" | "15m" | "30m" | "4h" | "12h" | "1mo">;
138
138
  tsSec: number[];
139
139
  open: string[];
140
140
  high: string[];
@@ -158,7 +158,7 @@ type CandleColumnar = v.InferOutput<ReturnType<typeof createCandleColumnarSchema
158
158
  type CandleColumnarInt = v.InferOutput<ReturnType<typeof createCandleColumnarIntSchema>>;
159
159
  declare function createListCandlesInputSchema(): v.SchemaWithPipe<readonly [v.ObjectSchema<{
160
160
  readonly symbolId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
161
- readonly timeframe: v.SchemaWithPipe<readonly [v.PicklistSchema<readonly ["1s", "1m", "5m", "15m", "30m", "1h", "4h", "12h", "1d", "1w", "1mo"], undefined>, v.TransformAction<"1d" | "1s" | "1m" | "5m" | "15m" | "30m" | "1h" | "4h" | "12h" | "1w" | "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>]>;
161
+ 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>]>;
162
162
  readonly limit: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 10000, undefined>]>, undefined>;
163
163
  readonly includeIncomplete: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
164
164
  readonly includeReference: v.OptionalSchema<v.BooleanSchema<undefined>, false>;