itd-api 0.9.1 → 0.9.2

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 (63) hide show
  1. package/dist/events/index.cjs +3 -4
  2. package/dist/events/index.d.cts +3 -3
  3. package/dist/events/index.d.ts +3 -3
  4. package/dist/events/index.js +4 -4
  5. package/dist/index.cjs +198 -39
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.cts +11 -65
  8. package/dist/index.d.ts +11 -65
  9. package/dist/index.js +199 -39
  10. package/dist/index.js.map +1 -1
  11. package/dist/node/index.cjs +3 -3
  12. package/dist/node/index.js +3 -3
  13. package/dist/rest/index.cjs +4 -5
  14. package/dist/rest/index.d.cts +3 -3
  15. package/dist/rest/index.d.ts +3 -3
  16. package/dist/rest/index.js +5 -5
  17. package/dist/shared/{events-BDdJyH2p.d.ts → events-BCn5LRnT.d.cts} +3 -5
  18. package/dist/shared/{events-D6y0Hxyz.js → events-BIBO2Jif.js} +4 -4
  19. package/dist/shared/{events-D6y0Hxyz.js.map → events-BIBO2Jif.js.map} +1 -1
  20. package/dist/shared/{events-BqFkwwTw.cjs → events-BsRm_Fba.cjs} +3 -9
  21. package/dist/shared/{events-BqFkwwTw.cjs.map → events-BsRm_Fba.cjs.map} +1 -1
  22. package/dist/shared/{events-BQyH5-S0.d.cts → events-t1uGgpkf.d.ts} +3 -5
  23. package/dist/shared/{multi-storage-SoW05uzO.js → multi-storage-C3Ngtop1.js} +13 -8
  24. package/dist/shared/multi-storage-C3Ngtop1.js.map +1 -0
  25. package/dist/shared/{multi-storage-CDKLa956.cjs → multi-storage-s-fPtjoy.cjs} +13 -8
  26. package/dist/shared/multi-storage-s-fPtjoy.cjs.map +1 -0
  27. package/dist/shared/{options-DOJYtoti.cjs → options-DjEtbVaf.cjs} +2 -2
  28. package/dist/shared/{options-DOJYtoti.cjs.map → options-DjEtbVaf.cjs.map} +1 -1
  29. package/dist/shared/{options-DhgGg7Ms.js → options-i4LrKfqx.js} +2 -2
  30. package/dist/shared/{options-DhgGg7Ms.js.map → options-i4LrKfqx.js.map} +1 -1
  31. package/dist/shared/{redact-Ba5iSVYZ.js → redact-DJV0XM3n.js} +40 -15
  32. package/dist/shared/redact-DJV0XM3n.js.map +1 -0
  33. package/dist/shared/{redact-BP00URmQ.cjs → redact-lAmck1Z6.cjs} +45 -14
  34. package/dist/shared/redact-lAmck1Z6.cjs.map +1 -0
  35. package/dist/shared/{render-sb1VJhUA.js → render--ZXmYEf-.js} +127 -96
  36. package/dist/shared/render--ZXmYEf-.js.map +1 -0
  37. package/dist/shared/{render-CZ_-F2Tl.d.ts → render-BdnBV-aT.d.ts} +82 -7
  38. package/dist/shared/{render-BU1_wex8.d.cts → render-DA83gS0f.d.cts} +82 -7
  39. package/dist/shared/{render-DAEeCMk9.cjs → render-DqVzx68r.cjs} +125 -100
  40. package/dist/shared/render-DqVzx68r.cjs.map +1 -0
  41. package/dist/shared/{storage-QNVxzpDB.cjs → storage-CZJZoaz9.cjs} +4 -2
  42. package/dist/shared/storage-CZJZoaz9.cjs.map +1 -0
  43. package/dist/shared/{storage-CfHKzVHf.js → storage-DiDe0PZM.js} +4 -2
  44. package/dist/shared/storage-DiDe0PZM.js.map +1 -0
  45. package/dist/shared/{url-CZZcyPI0.d.ts → url-Dbj6V6fk.d.cts} +4 -2
  46. package/dist/shared/{url-CZZcyPI0.d.cts → url-Dbj6V6fk.d.ts} +4 -2
  47. package/dist/shared/{url-CzHqE-Fg.cjs → url-Doc0XXW_.cjs} +274 -86
  48. package/dist/shared/url-Doc0XXW_.cjs.map +1 -0
  49. package/dist/shared/{url-Dsr4c5r5.js → url-i2f-X1hX.js} +274 -86
  50. package/dist/shared/url-i2f-X1hX.js.map +1 -0
  51. package/dist/web/index.cjs +1 -1
  52. package/dist/web/index.js +1 -1
  53. package/package.json +4 -4
  54. package/dist/shared/multi-storage-CDKLa956.cjs.map +0 -1
  55. package/dist/shared/multi-storage-SoW05uzO.js.map +0 -1
  56. package/dist/shared/redact-BP00URmQ.cjs.map +0 -1
  57. package/dist/shared/redact-Ba5iSVYZ.js.map +0 -1
  58. package/dist/shared/render-DAEeCMk9.cjs.map +0 -1
  59. package/dist/shared/render-sb1VJhUA.js.map +0 -1
  60. package/dist/shared/storage-CfHKzVHf.js.map +0 -1
  61. package/dist/shared/storage-QNVxzpDB.cjs.map +0 -1
  62. package/dist/shared/url-CzHqE-Fg.cjs.map +0 -1
  63. package/dist/shared/url-Dsr4c5r5.js.map +0 -1
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_url = require("../shared/url-CzHqE-Fg.cjs");
2
+ const require_url = require("../shared/url-Doc0XXW_.cjs");
3
3
  const require_errors = require("../shared/errors-BmP3TKoW.cjs");
4
- const require_redact = require("../shared/redact-BP00URmQ.cjs");
5
- const require_events = require("../shared/events-BqFkwwTw.cjs");
4
+ const require_redact = require("../shared/redact-lAmck1Z6.cjs");
5
+ const require_events = require("../shared/events-BsRm_Fba.cjs");
6
6
  exports.DEFAULT_BASE_URL = require_url.DEFAULT_BASE_URL;
7
7
  exports.EventChannel = require_events.EventChannel;
8
8
  exports.EventChannelStatus = require_url.EventChannelStatus;
@@ -46,7 +46,6 @@ exports.isItdStateError = require_errors.isItdStateError;
46
46
  exports.isItdValidationError = require_errors.isItdValidationError;
47
47
  exports.isKnownNotificationType = require_url.isKnownNotificationType;
48
48
  exports.normalizeNotification = require_url.normalizeNotification;
49
- exports.resolveEventChannelOptions = require_events.resolveEventChannelOptions;
50
49
  exports.resolveNotificationUrl = require_url.resolveNotificationUrl;
51
50
  exports.runEventMiddleware = require_events.runEventMiddleware;
52
51
  exports.systemClock = require_url.systemClock;
@@ -1,3 +1,3 @@
1
- import { $ as isItdStateError, A as ItdErrorKind, B as ItdStateError, Bt as RuntimeMode, C as ItdApiError, D as ItdConfigError, E as ItdAuthError, F as ItdNetworkError, Ft as RuntimeOptions, H as ItdValidationError, Ht as systemClock, I as ItdNotFoundError, K as isItdError, P as ItdForbiddenError, R as ItdRateLimitError, S as ItdAbortError, T as ItdApiErrorKind, U as isItdApiError, V as ItdTimeoutError, Vt as ItdClock, W as isItdAuthError, Z as isItdRateLimitError, a as NotificationEvent, at as bearerToken, c as NotificationSettings, cn as EventChannelStatus, ct as Listener, et as isItdValidationError, ft as LIBRARY_VERSION, hn as NotificationType, i as formatNotificationText, it as anonymousAuth, k as ItdError, lt as Unsubscribe, mn as Loose, n as canonicalNotificationType, nt as AuthIdentity, o as normalizeNotification, ot as tokenProvider, r as isKnownNotificationType, rt as AuthProvider, s as Notification, t as resolveNotificationUrl, tt as ClientConnection, ut as DEFAULT_BASE_URL, xt as Logger, yt as ClientHooks, z as ItdServerError } from "../shared/url-CZZcyPI0.cjs";
2
- import { $ as EventTransport, A as ReconnectOptions, B as NotificationContext, C as EventChannelDeps, D as EventSession, E as EventEnqueueOptions, F as EventPredicate, G as NotificationEventsUpdate, H as NotificationEventFilter, I as EventSequentializer, J as NotificationUpdateOfType, K as NotificationOfType, L as EventTypeGuard, M as EventMiddleware, N as EventMiddlewareObject, O as EventSyncReason, P as EventNext, Q as UnreadCountUpdate, R as runEventMiddleware, S as EventChannel, T as EventChannelOptions, U as NotificationEventOfType, V as NotificationEventContext, W as NotificationEventSelector, X as NotificationUpdateType, Y as NotificationUpdateOrigin, Z as UnknownNotificationUpdate, _ as createNotificationEventsClient, a as WebSocketTransportOptions, b as NotificationEventsOptions, c as EventErrorContext, d as EventMiddlewareLike, et as EventTransportContext, f as EventRouteTable, g as NotificationEventsClientOptions, h as NotificationEventsClient, i as WebSocketTransport, j as EventHandler, k as resolveEventChannelOptions, l as EventFilter, m as EventRouter, n as WebSocketLike, nt as UnauthorizedStreamError, o as EventComposer, p as EventRouteSelector, q as NotificationUpdate, r as WebSocketOpenFailureClassifier, s as EventErrorBoundary, t as WebSocketImplementationOptions, tt as EventTransportFrame, u as EventMiddlewareGroup, v as NotificationEvents, w as EventChannelEvents, x as NotificationEventsTransport, y as NotificationEventsMap, z as EventContext } from "../shared/events-BQyH5-S0.cjs";
3
- export { type AuthIdentity, type AuthProvider, type ClientConnection, type ClientHooks, DEFAULT_BASE_URL, EventChannel, type EventChannelDeps, type EventChannelEvents, type EventChannelOptions, EventChannelStatus, EventComposer, type EventContext, type EventEnqueueOptions, type EventErrorBoundary, type EventErrorContext, type EventFilter, type EventHandler, type EventMiddleware, type EventMiddlewareGroup, type EventMiddlewareLike, type EventMiddlewareObject, type EventNext, type EventPredicate, type EventRouteSelector, type EventRouteTable, EventRouter, type EventSequentializer, type EventSession, type EventSyncReason, type EventTransport, type EventTransportContext, type EventTransportFrame, type EventTypeGuard, ItdAbortError, ItdApiError, ItdApiErrorKind, ItdAuthError, type ItdClock, ItdConfigError, ItdError, ItdErrorKind, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdRateLimitError, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type Listener, type Logger, type Loose, type Notification, type NotificationContext, type NotificationEvent, type NotificationEventContext, type NotificationEventFilter, type NotificationEventOfType, type NotificationEventSelector, NotificationEvents, NotificationEventsClient, type NotificationEventsClientOptions, type NotificationEventsMap, type NotificationEventsOptions, NotificationEventsTransport, type NotificationEventsUpdate, type NotificationOfType, type NotificationSettings, NotificationType, type NotificationUpdate, type NotificationUpdateOfType, NotificationUpdateOrigin, NotificationUpdateType, type ReconnectOptions, RuntimeMode, type RuntimeOptions, UnauthorizedStreamError, type UnknownNotificationUpdate, type UnreadCountUpdate, type Unsubscribe, type WebSocketImplementationOptions, type WebSocketLike, type WebSocketOpenFailureClassifier, WebSocketTransport, type WebSocketTransportOptions, anonymousAuth, bearerToken, canonicalNotificationType, createNotificationEventsClient, formatNotificationText, isItdApiError, isItdAuthError, isItdError, isItdRateLimitError, isItdStateError, isItdValidationError, isKnownNotificationType, normalizeNotification, resolveEventChannelOptions, resolveNotificationUrl, runEventMiddleware, systemClock, tokenProvider };
1
+ import { $ as isItdStateError, A as ItdErrorKind, B as ItdStateError, Bt as RuntimeMode, C as ItdApiError, D as ItdConfigError, E as ItdAuthError, F as ItdNetworkError, Ft as RuntimeOptions, H as ItdValidationError, Ht as systemClock, I as ItdNotFoundError, K as isItdError, P as ItdForbiddenError, R as ItdRateLimitError, S as ItdAbortError, T as ItdApiErrorKind, U as isItdApiError, V as ItdTimeoutError, Vt as ItdClock, W as isItdAuthError, Z as isItdRateLimitError, a as NotificationEvent, at as bearerToken, c as NotificationSettings, cn as EventChannelStatus, ct as Listener, et as isItdValidationError, ft as LIBRARY_VERSION, hn as NotificationType, i as formatNotificationText, it as anonymousAuth, k as ItdError, lt as Unsubscribe, mn as Loose, n as canonicalNotificationType, nt as AuthIdentity, o as normalizeNotification, ot as tokenProvider, r as isKnownNotificationType, rt as AuthProvider, s as Notification, t as resolveNotificationUrl, tt as ClientConnection, ut as DEFAULT_BASE_URL, xt as Logger, yt as ClientHooks, z as ItdServerError } from "../shared/url-Dbj6V6fk.cjs";
2
+ import { $ as EventTransportContext, A as EventHandler, B as NotificationEventContext, C as EventChannelDeps, D as EventSession, E as EventEnqueueOptions, F as EventSequentializer, G as NotificationOfType, H as NotificationEventOfType, I as EventTypeGuard, J as NotificationUpdateOrigin, K as NotificationUpdate, L as runEventMiddleware, M as EventMiddlewareObject, N as EventNext, O as EventSyncReason, P as EventPredicate, Q as EventTransport, R as EventContext, S as EventChannel, T as EventChannelOptions, U as NotificationEventSelector, V as NotificationEventFilter, W as NotificationEventsUpdate, X as UnknownNotificationUpdate, Y as NotificationUpdateType, Z as UnreadCountUpdate, _ as createNotificationEventsClient, a as WebSocketTransportOptions, b as NotificationEventsOptions, c as EventErrorContext, d as EventMiddlewareLike, et as EventTransportFrame, f as EventRouteTable, g as NotificationEventsClientOptions, h as NotificationEventsClient, i as WebSocketTransport, j as EventMiddleware, k as ReconnectOptions, l as EventFilter, m as EventRouter, n as WebSocketLike, o as EventComposer, p as EventRouteSelector, q as NotificationUpdateOfType, r as WebSocketOpenFailureClassifier, s as EventErrorBoundary, t as WebSocketImplementationOptions, tt as UnauthorizedStreamError, u as EventMiddlewareGroup, v as NotificationEvents, w as EventChannelEvents, x as NotificationEventsTransport, y as NotificationEventsMap, z as NotificationContext } from "../shared/events-BCn5LRnT.cjs";
3
+ export { type AuthIdentity, type AuthProvider, type ClientConnection, type ClientHooks, DEFAULT_BASE_URL, EventChannel, type EventChannelDeps, type EventChannelEvents, type EventChannelOptions, EventChannelStatus, EventComposer, type EventContext, type EventEnqueueOptions, type EventErrorBoundary, type EventErrorContext, type EventFilter, type EventHandler, type EventMiddleware, type EventMiddlewareGroup, type EventMiddlewareLike, type EventMiddlewareObject, type EventNext, type EventPredicate, type EventRouteSelector, type EventRouteTable, EventRouter, type EventSequentializer, type EventSession, type EventSyncReason, type EventTransport, type EventTransportContext, type EventTransportFrame, type EventTypeGuard, ItdAbortError, ItdApiError, ItdApiErrorKind, ItdAuthError, type ItdClock, ItdConfigError, ItdError, ItdErrorKind, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdRateLimitError, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type Listener, type Logger, type Loose, type Notification, type NotificationContext, type NotificationEvent, type NotificationEventContext, type NotificationEventFilter, type NotificationEventOfType, type NotificationEventSelector, NotificationEvents, NotificationEventsClient, type NotificationEventsClientOptions, type NotificationEventsMap, type NotificationEventsOptions, NotificationEventsTransport, type NotificationEventsUpdate, type NotificationOfType, type NotificationSettings, NotificationType, type NotificationUpdate, type NotificationUpdateOfType, NotificationUpdateOrigin, NotificationUpdateType, type ReconnectOptions, RuntimeMode, type RuntimeOptions, UnauthorizedStreamError, type UnknownNotificationUpdate, type UnreadCountUpdate, type Unsubscribe, type WebSocketImplementationOptions, type WebSocketLike, type WebSocketOpenFailureClassifier, WebSocketTransport, type WebSocketTransportOptions, anonymousAuth, bearerToken, canonicalNotificationType, createNotificationEventsClient, formatNotificationText, isItdApiError, isItdAuthError, isItdError, isItdRateLimitError, isItdStateError, isItdValidationError, isKnownNotificationType, normalizeNotification, resolveNotificationUrl, runEventMiddleware, systemClock, tokenProvider };
@@ -1,3 +1,3 @@
1
- import { $ as isItdStateError, A as ItdErrorKind, B as ItdStateError, Bt as RuntimeMode, C as ItdApiError, D as ItdConfigError, E as ItdAuthError, F as ItdNetworkError, Ft as RuntimeOptions, H as ItdValidationError, Ht as systemClock, I as ItdNotFoundError, K as isItdError, P as ItdForbiddenError, R as ItdRateLimitError, S as ItdAbortError, T as ItdApiErrorKind, U as isItdApiError, V as ItdTimeoutError, Vt as ItdClock, W as isItdAuthError, Z as isItdRateLimitError, a as NotificationEvent, at as bearerToken, c as NotificationSettings, cn as EventChannelStatus, ct as Listener, et as isItdValidationError, ft as LIBRARY_VERSION, hn as NotificationType, i as formatNotificationText, it as anonymousAuth, k as ItdError, lt as Unsubscribe, mn as Loose, n as canonicalNotificationType, nt as AuthIdentity, o as normalizeNotification, ot as tokenProvider, r as isKnownNotificationType, rt as AuthProvider, s as Notification, t as resolveNotificationUrl, tt as ClientConnection, ut as DEFAULT_BASE_URL, xt as Logger, yt as ClientHooks, z as ItdServerError } from "../shared/url-CZZcyPI0.js";
2
- import { $ as EventTransport, A as ReconnectOptions, B as NotificationContext, C as EventChannelDeps, D as EventSession, E as EventEnqueueOptions, F as EventPredicate, G as NotificationEventsUpdate, H as NotificationEventFilter, I as EventSequentializer, J as NotificationUpdateOfType, K as NotificationOfType, L as EventTypeGuard, M as EventMiddleware, N as EventMiddlewareObject, O as EventSyncReason, P as EventNext, Q as UnreadCountUpdate, R as runEventMiddleware, S as EventChannel, T as EventChannelOptions, U as NotificationEventOfType, V as NotificationEventContext, W as NotificationEventSelector, X as NotificationUpdateType, Y as NotificationUpdateOrigin, Z as UnknownNotificationUpdate, _ as createNotificationEventsClient, a as WebSocketTransportOptions, b as NotificationEventsOptions, c as EventErrorContext, d as EventMiddlewareLike, et as EventTransportContext, f as EventRouteTable, g as NotificationEventsClientOptions, h as NotificationEventsClient, i as WebSocketTransport, j as EventHandler, k as resolveEventChannelOptions, l as EventFilter, m as EventRouter, n as WebSocketLike, nt as UnauthorizedStreamError, o as EventComposer, p as EventRouteSelector, q as NotificationUpdate, r as WebSocketOpenFailureClassifier, s as EventErrorBoundary, t as WebSocketImplementationOptions, tt as EventTransportFrame, u as EventMiddlewareGroup, v as NotificationEvents, w as EventChannelEvents, x as NotificationEventsTransport, y as NotificationEventsMap, z as EventContext } from "../shared/events-BDdJyH2p.js";
3
- export { type AuthIdentity, type AuthProvider, type ClientConnection, type ClientHooks, DEFAULT_BASE_URL, EventChannel, type EventChannelDeps, type EventChannelEvents, type EventChannelOptions, EventChannelStatus, EventComposer, type EventContext, type EventEnqueueOptions, type EventErrorBoundary, type EventErrorContext, type EventFilter, type EventHandler, type EventMiddleware, type EventMiddlewareGroup, type EventMiddlewareLike, type EventMiddlewareObject, type EventNext, type EventPredicate, type EventRouteSelector, type EventRouteTable, EventRouter, type EventSequentializer, type EventSession, type EventSyncReason, type EventTransport, type EventTransportContext, type EventTransportFrame, type EventTypeGuard, ItdAbortError, ItdApiError, ItdApiErrorKind, ItdAuthError, type ItdClock, ItdConfigError, ItdError, ItdErrorKind, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdRateLimitError, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type Listener, type Logger, type Loose, type Notification, type NotificationContext, type NotificationEvent, type NotificationEventContext, type NotificationEventFilter, type NotificationEventOfType, type NotificationEventSelector, NotificationEvents, NotificationEventsClient, type NotificationEventsClientOptions, type NotificationEventsMap, type NotificationEventsOptions, NotificationEventsTransport, type NotificationEventsUpdate, type NotificationOfType, type NotificationSettings, NotificationType, type NotificationUpdate, type NotificationUpdateOfType, NotificationUpdateOrigin, NotificationUpdateType, type ReconnectOptions, RuntimeMode, type RuntimeOptions, UnauthorizedStreamError, type UnknownNotificationUpdate, type UnreadCountUpdate, type Unsubscribe, type WebSocketImplementationOptions, type WebSocketLike, type WebSocketOpenFailureClassifier, WebSocketTransport, type WebSocketTransportOptions, anonymousAuth, bearerToken, canonicalNotificationType, createNotificationEventsClient, formatNotificationText, isItdApiError, isItdAuthError, isItdError, isItdRateLimitError, isItdStateError, isItdValidationError, isKnownNotificationType, normalizeNotification, resolveEventChannelOptions, resolveNotificationUrl, runEventMiddleware, systemClock, tokenProvider };
1
+ import { $ as isItdStateError, A as ItdErrorKind, B as ItdStateError, Bt as RuntimeMode, C as ItdApiError, D as ItdConfigError, E as ItdAuthError, F as ItdNetworkError, Ft as RuntimeOptions, H as ItdValidationError, Ht as systemClock, I as ItdNotFoundError, K as isItdError, P as ItdForbiddenError, R as ItdRateLimitError, S as ItdAbortError, T as ItdApiErrorKind, U as isItdApiError, V as ItdTimeoutError, Vt as ItdClock, W as isItdAuthError, Z as isItdRateLimitError, a as NotificationEvent, at as bearerToken, c as NotificationSettings, cn as EventChannelStatus, ct as Listener, et as isItdValidationError, ft as LIBRARY_VERSION, hn as NotificationType, i as formatNotificationText, it as anonymousAuth, k as ItdError, lt as Unsubscribe, mn as Loose, n as canonicalNotificationType, nt as AuthIdentity, o as normalizeNotification, ot as tokenProvider, r as isKnownNotificationType, rt as AuthProvider, s as Notification, t as resolveNotificationUrl, tt as ClientConnection, ut as DEFAULT_BASE_URL, xt as Logger, yt as ClientHooks, z as ItdServerError } from "../shared/url-Dbj6V6fk.js";
2
+ import { $ as EventTransportContext, A as EventHandler, B as NotificationEventContext, C as EventChannelDeps, D as EventSession, E as EventEnqueueOptions, F as EventSequentializer, G as NotificationOfType, H as NotificationEventOfType, I as EventTypeGuard, J as NotificationUpdateOrigin, K as NotificationUpdate, L as runEventMiddleware, M as EventMiddlewareObject, N as EventNext, O as EventSyncReason, P as EventPredicate, Q as EventTransport, R as EventContext, S as EventChannel, T as EventChannelOptions, U as NotificationEventSelector, V as NotificationEventFilter, W as NotificationEventsUpdate, X as UnknownNotificationUpdate, Y as NotificationUpdateType, Z as UnreadCountUpdate, _ as createNotificationEventsClient, a as WebSocketTransportOptions, b as NotificationEventsOptions, c as EventErrorContext, d as EventMiddlewareLike, et as EventTransportFrame, f as EventRouteTable, g as NotificationEventsClientOptions, h as NotificationEventsClient, i as WebSocketTransport, j as EventMiddleware, k as ReconnectOptions, l as EventFilter, m as EventRouter, n as WebSocketLike, o as EventComposer, p as EventRouteSelector, q as NotificationUpdateOfType, r as WebSocketOpenFailureClassifier, s as EventErrorBoundary, t as WebSocketImplementationOptions, tt as UnauthorizedStreamError, u as EventMiddlewareGroup, v as NotificationEvents, w as EventChannelEvents, x as NotificationEventsTransport, y as NotificationEventsMap, z as NotificationContext } from "../shared/events-t1uGgpkf.js";
3
+ export { type AuthIdentity, type AuthProvider, type ClientConnection, type ClientHooks, DEFAULT_BASE_URL, EventChannel, type EventChannelDeps, type EventChannelEvents, type EventChannelOptions, EventChannelStatus, EventComposer, type EventContext, type EventEnqueueOptions, type EventErrorBoundary, type EventErrorContext, type EventFilter, type EventHandler, type EventMiddleware, type EventMiddlewareGroup, type EventMiddlewareLike, type EventMiddlewareObject, type EventNext, type EventPredicate, type EventRouteSelector, type EventRouteTable, EventRouter, type EventSequentializer, type EventSession, type EventSyncReason, type EventTransport, type EventTransportContext, type EventTransportFrame, type EventTypeGuard, ItdAbortError, ItdApiError, ItdApiErrorKind, ItdAuthError, type ItdClock, ItdConfigError, ItdError, ItdErrorKind, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdRateLimitError, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, type Listener, type Logger, type Loose, type Notification, type NotificationContext, type NotificationEvent, type NotificationEventContext, type NotificationEventFilter, type NotificationEventOfType, type NotificationEventSelector, NotificationEvents, NotificationEventsClient, type NotificationEventsClientOptions, type NotificationEventsMap, type NotificationEventsOptions, NotificationEventsTransport, type NotificationEventsUpdate, type NotificationOfType, type NotificationSettings, NotificationType, type NotificationUpdate, type NotificationUpdateOfType, NotificationUpdateOrigin, NotificationUpdateType, type ReconnectOptions, RuntimeMode, type RuntimeOptions, UnauthorizedStreamError, type UnknownNotificationUpdate, type UnreadCountUpdate, type Unsubscribe, type WebSocketImplementationOptions, type WebSocketLike, type WebSocketOpenFailureClassifier, WebSocketTransport, type WebSocketTransportOptions, anonymousAuth, bearerToken, canonicalNotificationType, createNotificationEventsClient, formatNotificationText, isItdApiError, isItdAuthError, isItdError, isItdRateLimitError, isItdStateError, isItdValidationError, isKnownNotificationType, normalizeNotification, resolveNotificationUrl, runEventMiddleware, systemClock, tokenProvider };
@@ -1,5 +1,5 @@
1
- import { S as NotificationType, a as tokenProvider, c as normalizeNotification, d as canonicalNotificationType, et as DEFAULT_BASE_URL, f as isKnownNotificationType, g as EventChannelStatus, i as bearerToken, it as LIBRARY_VERSION, lt as systemClock, n as formatNotificationText, r as anonymousAuth, t as resolveNotificationUrl } from "../shared/url-Dsr4c5r5.js";
1
+ import { S as NotificationType, a as tokenProvider, c as normalizeNotification, d as canonicalNotificationType, et as DEFAULT_BASE_URL, f as isKnownNotificationType, g as EventChannelStatus, i as bearerToken, it as LIBRARY_VERSION, lt as systemClock, n as formatNotificationText, r as anonymousAuth, t as resolveNotificationUrl } from "../shared/url-i2f-X1hX.js";
2
2
  import { A as isItdStateError, C as isItdError, O as isItdRateLimitError, _ as ItdStateError, a as ItdConfigError, b as isItdApiError, c as ItdErrorKind, d as ItdForbiddenError, f as ItdNetworkError, g as ItdServerError, h as ItdRateLimitError, i as ItdAuthError, j as isItdValidationError, n as ItdApiError, p as ItdNotFoundError, r as ItdApiErrorKind, s as ItdError, t as ItdAbortError, v as ItdTimeoutError, x as isItdAuthError, y as ItdValidationError } from "../shared/errors-GI10kZxk.js";
3
- import { _ as RuntimeMode } from "../shared/redact-Ba5iSVYZ.js";
4
- import { a as WebSocketTransport, c as NotificationEventsTransport, d as NotificationUpdateOrigin, f as NotificationUpdateType, g as runEventMiddleware, h as UnauthorizedStreamError, i as createNotificationEventsClient, m as resolveEventChannelOptions, n as EventRouter, p as EventChannel, r as NotificationEventsClient, s as NotificationEvents, t as EventComposer } from "../shared/events-D6y0Hxyz.js";
5
- export { DEFAULT_BASE_URL, EventChannel, EventChannelStatus, EventComposer, EventRouter, ItdAbortError, ItdApiError, ItdApiErrorKind, ItdAuthError, ItdConfigError, ItdError, ItdErrorKind, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdRateLimitError, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, NotificationEvents, NotificationEventsClient, NotificationEventsTransport, NotificationType, NotificationUpdateOrigin, NotificationUpdateType, RuntimeMode, UnauthorizedStreamError, WebSocketTransport, anonymousAuth, bearerToken, canonicalNotificationType, createNotificationEventsClient, formatNotificationText, isItdApiError, isItdAuthError, isItdError, isItdRateLimitError, isItdStateError, isItdValidationError, isKnownNotificationType, normalizeNotification, resolveEventChannelOptions, resolveNotificationUrl, runEventMiddleware, systemClock, tokenProvider };
3
+ import { v as RuntimeMode } from "../shared/redact-DJV0XM3n.js";
4
+ import { a as WebSocketTransport, c as NotificationEventsTransport, d as NotificationUpdateOrigin, f as NotificationUpdateType, h as runEventMiddleware, i as createNotificationEventsClient, m as UnauthorizedStreamError, n as EventRouter, p as EventChannel, r as NotificationEventsClient, s as NotificationEvents, t as EventComposer } from "../shared/events-BIBO2Jif.js";
5
+ export { DEFAULT_BASE_URL, EventChannel, EventChannelStatus, EventComposer, EventRouter, ItdAbortError, ItdApiError, ItdApiErrorKind, ItdAuthError, ItdConfigError, ItdError, ItdErrorKind, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdRateLimitError, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, NotificationEvents, NotificationEventsClient, NotificationEventsTransport, NotificationType, NotificationUpdateOrigin, NotificationUpdateType, RuntimeMode, UnauthorizedStreamError, WebSocketTransport, anonymousAuth, bearerToken, canonicalNotificationType, createNotificationEventsClient, formatNotificationText, isItdApiError, isItdAuthError, isItdError, isItdRateLimitError, isItdStateError, isItdValidationError, isKnownNotificationType, normalizeNotification, resolveNotificationUrl, runEventMiddleware, systemClock, tokenProvider };
package/dist/index.cjs CHANGED
@@ -1,13 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_url = require("./shared/url-CzHqE-Fg.cjs");
2
+ const require_url = require("./shared/url-Doc0XXW_.cjs");
3
3
  const require_errors = require("./shared/errors-BmP3TKoW.cjs");
4
- const require_redact = require("./shared/redact-BP00URmQ.cjs");
5
- const require_render = require("./shared/render-DAEeCMk9.cjs");
6
- const require_options = require("./shared/options-DOJYtoti.cjs");
7
- const require_events = require("./shared/events-BqFkwwTw.cjs");
4
+ const require_redact = require("./shared/redact-lAmck1Z6.cjs");
5
+ const require_render = require("./shared/render-DqVzx68r.cjs");
6
+ const require_options = require("./shared/options-DjEtbVaf.cjs");
7
+ const require_events = require("./shared/events-BsRm_Fba.cjs");
8
8
  const require_key_value_store = require("./shared/key-value-store-B5GYVEYZ.cjs");
9
- const require_storage = require("./shared/storage-QNVxzpDB.cjs");
10
- const require_multi_storage = require("./shared/multi-storage-CDKLa956.cjs");
9
+ const require_storage = require("./shared/storage-CZJZoaz9.cjs");
10
+ const require_multi_storage = require("./shared/multi-storage-s-fPtjoy.cjs");
11
11
  //#region src/notifications-api.ts
12
12
  var ClientNotifications = class extends require_render.NotificationsResource {
13
13
  #createEvents;
@@ -50,7 +50,7 @@ const AUTH_SIGN_IN = require_url.defineBuiltInOperation("auth.signIn", (body) =>
50
50
  };
51
51
  });
52
52
  const AUTH_VERIFY_OTP = require_url.defineBuiltInOperation("auth.verifyOtp", (body) => requireString(body, "accessToken", "Сервер не вернул accessToken после подтверждения кода"));
53
- const AUTH_REFRESH = require_url.defineBuiltInOperation("auth.refresh", (body) => require_url.pickString(body, "accessToken"));
53
+ const AUTH_REFRESH = require_url.defineBuiltInOperation("auth.refresh", (body) => requireString(body, "accessToken", "Сервер не вернул accessToken при обновлении сессии"));
54
54
  const AUTH_RESEND_OTP = require_url.voidOperation("auth.resendOtp");
55
55
  const AUTH_LOGOUT = require_url.voidOperation("auth.logout");
56
56
  const AUTH_FORGOT_PASSWORD = require_url.defineBuiltInOperation("auth.forgotPassword", (body) => requireString(body, "flowToken", "Сервер не вернул flowToken при запросе сброса пароля"));
@@ -120,12 +120,18 @@ function validateAuth(auth) {
120
120
  return auth;
121
121
  }
122
122
  if (typeof auth !== "object" || auth === null) throw new require_errors.ItdConfigError(`auth должен быть строкой с токеном или объектом, получено: ${typeof auth}`);
123
+ if ([
124
+ "getToken" in auth,
125
+ "accessToken" in auth || "refreshToken" in auth,
126
+ "email" in auth || "password" in auth
127
+ ].filter(Boolean).length > 1) throw new require_errors.ItdConfigError("auth должен описывать ровно один способ авторизации: getToken, accessToken или email/password");
123
128
  if ("getToken" in auth) {
124
129
  if (typeof auth.getToken !== "function") throw new require_errors.ItdConfigError("auth.getToken должен быть функцией");
125
130
  return { ...auth };
126
131
  }
127
132
  if ("accessToken" in auth) {
128
133
  if (typeof auth.accessToken !== "string" || auth.accessToken.trim() === "") throw new require_errors.ItdConfigError("auth.accessToken должен быть непустой строкой");
134
+ if (auth.refreshToken !== void 0 && (typeof auth.refreshToken !== "string" || auth.refreshToken.trim() === "")) throw new require_errors.ItdConfigError("auth.refreshToken должен быть непустой строкой");
129
135
  return { ...auth };
130
136
  }
131
137
  if ("email" in auth || "password" in auth) {
@@ -213,10 +219,67 @@ const AUTH_PATHS = {
213
219
  const TURNSTILE_SITE_KEY = "0x4AAAAAACHhxczw6fJGwPBg";
214
220
  /** Убирает поле, которое сохраняли промежуточные версии с поддержкой `getUserId()`. */
215
221
  function withoutLegacyUserId(session) {
216
- const clean = { ...session };
222
+ const clean = require_storage.copySession(session);
217
223
  delete clean.userId;
218
224
  return clean;
219
225
  }
226
+ function normalizeSessionValue(value, source, mode = "strict", logger) {
227
+ const tolerant = mode === "stored";
228
+ if (!require_url.isRecord$1(value)) {
229
+ if (tolerant) {
230
+ logger?.warn(`${source} вернула не объект сессии; сохранённая запись пропущена`);
231
+ return null;
232
+ }
233
+ throw new require_errors.ItdConfigError(`${source} должна быть объектом сессии`);
234
+ }
235
+ const record = value;
236
+ const normalized = { ...record };
237
+ delete normalized.userId;
238
+ const normalizeString = (field) => {
239
+ const item = record[field];
240
+ if (item === void 0) {
241
+ delete normalized[field];
242
+ return;
243
+ }
244
+ if (item !== void 0 && (typeof item !== "string" || item.trim() === "")) {
245
+ if (tolerant) {
246
+ logger?.warn(`${source}.${field} повреждена; поле сохранённой сессии пропущено`);
247
+ delete normalized[field];
248
+ return;
249
+ }
250
+ throw new require_errors.ItdConfigError(`${source}.${field} должна быть непустой строкой`);
251
+ }
252
+ normalized[field] = item;
253
+ };
254
+ normalizeString("accessToken");
255
+ normalizeString("refreshToken");
256
+ normalizeString("deviceId");
257
+ if (record.obtainedAt === void 0) delete normalized.obtainedAt;
258
+ else if (typeof record.obtainedAt !== "number" || !Number.isFinite(record.obtainedAt)) {
259
+ if (!tolerant) throw new require_errors.ItdConfigError(`${source}.obtainedAt должна быть конечным числом`);
260
+ else {
261
+ logger?.warn(`${source}.obtainedAt повреждена; поле сохранённой сессии пропущено`);
262
+ delete normalized.obtainedAt;
263
+ }
264
+ }
265
+ if (record.cookies === void 0) delete normalized.cookies;
266
+ else if (!Array.isArray(record.cookies)) {
267
+ if (tolerant) {
268
+ logger?.warn(`${source}.cookies повреждена; поле сохранённой сессии пропущено`);
269
+ delete normalized.cookies;
270
+ } else throw new require_errors.ItdConfigError(`${source}.cookies должна быть массивом`);
271
+ } else {
272
+ const valid = record.cookies.filter((cookie) => typeof cookie === "string" && require_redact.isSerializedCookieEntry(cookie));
273
+ if (valid.length > 0) normalized.cookies = valid;
274
+ else delete normalized.cookies;
275
+ }
276
+ return normalized;
277
+ }
278
+ function normalizeSession(value, source) {
279
+ const normalized = normalizeSessionValue(value, source);
280
+ if (!normalized) throw new require_errors.ItdConfigError(`${source} должна быть объектом сессии`);
281
+ return normalized;
282
+ }
220
283
  let authScopeSequence = 0;
221
284
  function nextAuthScope() {
222
285
  authScopeSequence += 1;
@@ -271,6 +334,9 @@ var AuthManager = class {
271
334
  * воскресить уже очищенную сессию поверх `signOut`.
272
335
  */
273
336
  #authEpoch = 0;
337
+ #externalReadGeneration = 0;
338
+ #disposed = false;
339
+ #persistence = Promise.resolve();
274
340
  constructor(config, http, jar, hooks = {}) {
275
341
  this.#config = config;
276
342
  this.#http = http;
@@ -280,14 +346,23 @@ var AuthManager = class {
280
346
  }
281
347
  /** Подписка на события авторизации. */
282
348
  get on() {
283
- return this.#emitter.on.bind(this.#emitter);
349
+ return ((...args) => {
350
+ this.#assertActive();
351
+ return this.#emitter.on(...args);
352
+ });
284
353
  }
285
354
  /** Подписка на одно срабатывание. */
286
355
  get once() {
287
- return this.#emitter.once.bind(this.#emitter);
356
+ return ((...args) => {
357
+ this.#assertActive();
358
+ return this.#emitter.once(...args);
359
+ });
288
360
  }
289
361
  /** Снимает служебные подписки при окончательном освобождении владельца. @internal */
290
362
  dispose() {
363
+ if (this.#disposed) return;
364
+ this.#disposed = true;
365
+ this.#externalReadGeneration += 1;
291
366
  this.#invalidateInFlight();
292
367
  this.#emitter.removeAllListeners();
293
368
  }
@@ -302,6 +377,7 @@ var AuthManager = class {
302
377
  }
303
378
  /** Загружает сессию и возвращает идентификаторы аккаунта и сессии для плагинов. */
304
379
  async getAuthIdentity() {
380
+ this.#assertActive();
305
381
  const session = await this.#loadSession();
306
382
  if (session?.accessToken) return this.#identityForToken(session.accessToken);
307
383
  const auth = this.#config.auth;
@@ -322,6 +398,30 @@ var AuthManager = class {
322
398
  /** Отмечает смену владельца авторизации — обесценивает результат идущего обновления. */
323
399
  #invalidateInFlight() {
324
400
  this.#authEpoch += 1;
401
+ this.#externalReadGeneration += 1;
402
+ }
403
+ /** Ревизия владельца сессии для условного commit внешнего auth-flow. @internal */
404
+ revision() {
405
+ this.#assertActive();
406
+ return this.#authEpoch;
407
+ }
408
+ /** Создаёт изолированный jar для сетевого auth-flow. @internal */
409
+ createCookieFlow(inherit = true) {
410
+ this.#assertActive();
411
+ return inherit ? this.#jar.clone() : new require_redact.CookieJar();
412
+ }
413
+ /** Применяет cookies только если владелец сессии не сменился. @internal */
414
+ commitCookieFlow(cookies, expectedRevision) {
415
+ this.#assertActive();
416
+ if (this.#authEpoch !== expectedRevision) return false;
417
+ this.#jar.replaceWith(cookies);
418
+ return true;
419
+ }
420
+ #assertActive() {
421
+ if (this.#disposed) throw new require_errors.ItdStateError("Менеджер авторизации уже освобождён");
422
+ }
423
+ #currentAccessToken() {
424
+ return this.#session?.accessToken ?? null;
325
425
  }
326
426
  #identityForToken(accessToken) {
327
427
  const token = accessToken ? readTokenIdentity(accessToken) : {};
@@ -331,7 +431,11 @@ var AuthManager = class {
331
431
  };
332
432
  }
333
433
  async #readExternalToken(getToken) {
434
+ this.#assertActive();
435
+ const generation = ++this.#externalReadGeneration;
334
436
  const token = await getToken() ?? null;
437
+ this.#assertActive();
438
+ if (generation !== this.#externalReadGeneration) return token;
335
439
  const current = this.#identityForToken(token ?? void 0);
336
440
  if (this.#externalToken !== void 0 && this.#externalToken !== token) {
337
441
  this.#rotateAuthScope();
@@ -362,6 +466,7 @@ var AuthManager = class {
362
466
  * ответ был бы `false` даже при полностью рабочей сохранённой сессии.
363
467
  */
364
468
  async hasRefreshSession() {
469
+ this.#assertActive();
365
470
  await this.#loadSession();
366
471
  return this.#hasRefreshSession();
367
472
  }
@@ -378,6 +483,7 @@ var AuthManager = class {
378
483
  * обязаны завершиться до захвата слота очереди.
379
484
  */
380
485
  async prepare() {
486
+ this.#assertActive();
381
487
  await this.token();
382
488
  }
383
489
  /**
@@ -397,6 +503,7 @@ var AuthManager = class {
397
503
  * через `itd.auth.refresh()`, а библиотека просто пробрасывает {@link ItdAuthError}.
398
504
  */
399
505
  recover() {
506
+ this.#assertActive();
400
507
  return this.#config.autoRefresh ? this.onUnauthorized() : Promise.resolve(false);
401
508
  }
402
509
  /**
@@ -407,6 +514,7 @@ var AuthManager = class {
407
514
  * по новой сессии на каждый старт.
408
515
  */
409
516
  deviceId() {
517
+ this.#assertActive();
410
518
  if (this.#deviceId) return Promise.resolve(this.#deviceId);
411
519
  this.#deviceIdLoading ??= this.#resolveDeviceId().finally(() => {
412
520
  this.#deviceIdLoading = null;
@@ -414,9 +522,12 @@ var AuthManager = class {
414
522
  return this.#deviceIdLoading;
415
523
  }
416
524
  async #resolveDeviceId() {
525
+ const revision = this.#authEpoch;
417
526
  const session = await this.#loadSession();
527
+ this.#assertActive();
418
528
  const deviceId = this.#config.deviceId ?? session?.deviceId ?? require_redact.createDeviceId();
419
529
  this.#deviceId = deviceId;
530
+ if (this.#authEpoch !== revision) return deviceId;
420
531
  if (session?.deviceId !== deviceId) await this.#saveSession({
421
532
  ...session ?? {},
422
533
  deviceId
@@ -430,6 +541,7 @@ var AuthManager = class {
430
541
  * и пароль, первый же запрос сам заведёт сессию.
431
542
  */
432
543
  async token() {
544
+ this.#assertActive();
433
545
  const session = await this.#loadSession();
434
546
  if (session?.accessToken) return session.accessToken;
435
547
  const auth = this.#config.auth;
@@ -444,6 +556,7 @@ var AuthManager = class {
444
556
  * @returns `true`, если токен обновлён и запрос имеет смысл повторить
445
557
  */
446
558
  async onUnauthorized() {
559
+ this.#assertActive();
447
560
  try {
448
561
  if (await this.#refreshDeduplicated() !== null) return true;
449
562
  this.#emitter.emit("authError", { error: this.#noRefreshSessionError() });
@@ -479,24 +592,33 @@ var AuthManager = class {
479
592
  * @throws {ItdAuthError} если обновить сессию не удалось
480
593
  */
481
594
  async refresh() {
595
+ this.#assertActive();
482
596
  const token = await this.#refreshDeduplicated();
483
597
  if (token === null) throw this.#noRefreshSessionError();
484
598
  return token;
485
599
  }
486
600
  /** Сохраняет токен, полученный извне, — например после подтверждения OTP. */
487
- async setAccessToken(accessToken) {
601
+ async setAccessToken(accessToken, expectedRevision = this.#authEpoch, cookies) {
602
+ this.#assertActive();
603
+ if (typeof accessToken !== "string" || accessToken.trim() === "") throw new require_errors.ItdConfigError("accessToken должен быть непустой строкой");
488
604
  await this.#loadSession();
605
+ this.#assertActive();
606
+ if (this.#authEpoch !== expectedRevision) return false;
607
+ if (cookies) this.#jar.replaceWith(cookies);
489
608
  this.#invalidateInFlight();
490
609
  this.#transitionAuth(accessToken);
491
- await this.#saveSession({
610
+ const saved = this.#saveSession({
492
611
  ...this.#session ?? {},
493
612
  accessToken,
494
613
  obtainedAt: this.#config.clock.now()
495
614
  });
496
615
  this.#emitter.emit("tokens", { accessToken });
616
+ await saved;
617
+ return true;
497
618
  }
498
619
  /** Текущая сессия целиком. Полезно, чтобы сохранить её самому. */
499
620
  async getSession() {
621
+ this.#assertActive();
500
622
  const session = await this.#loadSession();
501
623
  return session ? require_storage.copySession(session) : null;
502
624
  }
@@ -507,20 +629,24 @@ var AuthManager = class {
507
629
  * токена идентификатор прежнего владельца остаться не может.
508
630
  */
509
631
  async getUserId() {
632
+ this.#assertActive();
510
633
  const session = await this.#loadSession();
511
634
  return session?.accessToken ? readTokenSubject(session.accessToken) : void 0;
512
635
  }
513
636
  /** Заменяет сессию и связанные с ней cookie целиком. */
514
637
  async setSession(session) {
638
+ this.#assertActive();
639
+ const normalized = normalizeSession(session, "session");
515
640
  await this.#loadSession();
641
+ this.#assertActive();
516
642
  this.#invalidateInFlight();
517
- this.#transitionAuth(session.accessToken);
643
+ this.#transitionAuth(normalized.accessToken);
518
644
  this.#jar.clear();
519
- this.#jar.deserialize(session.cookies);
520
- if (session.deviceId) this.#deviceId = session.deviceId;
521
- this.#session = session;
645
+ this.#jar.deserialize(normalized.cookies);
646
+ if (normalized.deviceId) this.#deviceId = normalized.deviceId;
647
+ this.#session = normalized;
522
648
  this.#seedRefreshCookie();
523
- await this.#saveSession(session);
649
+ await this.#saveSession(normalized);
524
650
  }
525
651
  /**
526
652
  * Забывает сессию и cookie. Сетевой запрос не выполняется.
@@ -529,14 +655,19 @@ var AuthManager = class {
529
655
  * новую запись в списке сессий.
530
656
  */
531
657
  async clear() {
658
+ this.#assertActive();
532
659
  await this.#loadSession();
660
+ this.#assertActive();
533
661
  this.#invalidateInFlight();
534
662
  this.#transitionAuth(void 0);
535
- this.#session = null;
536
663
  this.#jar.clear();
537
- await this.#config.storage.clear();
538
- if (this.#deviceId) await this.#saveSession({ deviceId: this.#deviceId });
664
+ const retained = this.#deviceId ? { deviceId: this.#deviceId } : null;
665
+ this.#session = retained;
539
666
  this.#emitter.emit("signOut", void 0);
667
+ await this.#enqueuePersistence(async () => {
668
+ await this.#config.storage.clear();
669
+ if (retained) await this.#config.storage.set(require_storage.copySession(retained));
670
+ });
540
671
  }
541
672
  #loadSession() {
542
673
  if (this.#session !== void 0) return Promise.resolve(this.#session);
@@ -547,7 +678,8 @@ var AuthManager = class {
547
678
  }
548
679
  async #performLoad() {
549
680
  const loaded = await this.#config.storage.get() ?? null;
550
- const stored = loaded ? withoutLegacyUserId(loaded) : null;
681
+ this.#assertActive();
682
+ const stored = loaded === null ? null : normalizeSessionValue(loaded, "storage.get()", "stored", this.#config.logger);
551
683
  if (stored?.cookies) this.#jar.deserialize(stored.cookies);
552
684
  const fromConfig = this.#sessionFromConfig(this.#config.auth);
553
685
  this.#session = stored && fromConfig ? {
@@ -569,7 +701,7 @@ var AuthManager = class {
569
701
  if (!this.#config.useCookieJar) return;
570
702
  const refreshToken = this.#session?.refreshToken;
571
703
  if (!refreshToken) return;
572
- if (this.#jar.has("refresh_token")) return;
704
+ if (this.#jar.has("refresh_token", this.#config.baseUrl + "/api/v1/auth")) return;
573
705
  this.#jar.set(this.#config.baseUrl, require_redact.REFRESH_COOKIE, refreshToken, require_redact.REFRESH_COOKIE_PATH);
574
706
  }
575
707
  #sessionFromConfig(auth) {
@@ -588,13 +720,19 @@ var AuthManager = class {
588
720
  async #saveSession(session) {
589
721
  const cookies = this.#config.useCookieJar ? this.#jar.serialize() : void 0;
590
722
  const deviceId = session.deviceId ?? this.#deviceId;
723
+ const { cookies: _staleCookies, ...withoutCookies } = require_storage.copySession(session);
591
724
  const next = withoutLegacyUserId({
592
- ...session,
725
+ ...withoutCookies,
593
726
  ...cookies?.length ? { cookies } : {},
594
727
  ...deviceId ? { deviceId } : {}
595
728
  });
596
729
  this.#session = next;
597
- await this.#config.storage.set(next);
730
+ await this.#enqueuePersistence(() => this.#config.storage.set(require_storage.copySession(next)));
731
+ }
732
+ #enqueuePersistence(operation) {
733
+ const pending = this.#persistence.then(operation, operation);
734
+ this.#persistence = pending.catch(() => {});
735
+ return pending;
598
736
  }
599
737
  /**
600
738
  * Обновление с дедупликацией.
@@ -610,34 +748,41 @@ var AuthManager = class {
610
748
  return promise;
611
749
  }
612
750
  async #performRefresh() {
751
+ this.#assertActive();
613
752
  await this.#loadSession();
614
753
  if (!this.#hasRefreshSession()) return this.#reloginOrNull();
615
754
  const epoch = this.#authEpoch;
755
+ const flowCookies = this.#jar.clone();
616
756
  try {
617
757
  const accessToken = await this.#http.execute(AUTH_REFRESH, {
618
758
  path: AUTH_PATHS.refresh,
619
759
  skipAuth: true,
620
- skipAuthRefresh: true
760
+ skipAuthRefresh: true,
761
+ cookieJar: flowCookies
621
762
  });
622
- if (!accessToken) return this.#reloginOrNull();
623
763
  if (this.#authEpoch !== epoch) return this.#session?.accessToken ?? null;
764
+ this.#jar.replaceWith(flowCookies);
624
765
  const rotated = this.#jar.getValue(require_redact.REFRESH_COOKIE, this.#config.baseUrl + require_redact.REFRESH_COOKIE_PATH);
625
766
  this.#transitionAuth(accessToken, false);
626
- await this.#saveSession({
767
+ const saved = this.#saveSession({
627
768
  ...this.#session ?? {},
628
769
  accessToken,
629
770
  ...rotated ? { refreshToken: rotated } : {},
630
771
  obtainedAt: this.#config.clock.now()
631
772
  });
632
773
  this.#emitter.emit("tokens", { accessToken });
774
+ await saved;
633
775
  return accessToken;
634
776
  } catch (error) {
635
- if (error instanceof require_errors.ItdApiError) {
777
+ if (error instanceof require_errors.ItdAuthError) {
636
778
  if (this.#authEpoch !== epoch) return this.#session?.accessToken ?? null;
779
+ this.#invalidateInFlight();
780
+ const clearedRevision = this.#authEpoch;
637
781
  this.#transitionAuth(void 0);
638
782
  this.#session = null;
639
783
  this.#jar.clear();
640
- await this.#config.storage.clear();
784
+ await this.#enqueuePersistence(() => this.#config.storage.clear());
785
+ if (this.#authEpoch !== clearedRevision) return this.#currentAccessToken();
641
786
  const relogged = await this.#reloginOrNull();
642
787
  if (relogged !== null) return relogged;
643
788
  throw error;
@@ -651,7 +796,8 @@ var AuthManager = class {
651
796
  if (!this.#config.reloginOnRefreshFailure || !auth || typeof auth !== "object" || !("email" in auth)) return null;
652
797
  try {
653
798
  return await this.#signInWithCredentials(auth);
654
- } catch {
799
+ } catch (error) {
800
+ this.#config.logger?.warn("Автоматический повторный вход не удался", error);
655
801
  return null;
656
802
  }
657
803
  }
@@ -663,7 +809,8 @@ var AuthManager = class {
663
809
  */
664
810
  #signInWithCredentials(credentials) {
665
811
  if (this.#signingIn) return this.#signingIn;
666
- const promise = this.#performSignIn(credentials).finally(() => {
812
+ const revision = this.#authEpoch;
813
+ const promise = this.#performSignIn(credentials, revision).finally(() => {
667
814
  this.#signingIn = null;
668
815
  });
669
816
  this.#signingIn = promise;
@@ -683,8 +830,9 @@ var AuthManager = class {
683
830
  if (credentials.turnstileToken) return credentials.turnstileToken;
684
831
  throw new require_errors.ItdConfigError("Вход по email и паролю требует токен капчи Cloudflare Turnstile: без него сервер отвечает 422. Передайте auth.getTurnstileToken (источник свежего токена) либо разовый auth.turnstileToken. Ключ виджета — TURNSTILE_SITE_KEY. В Node токен умеет добывать отдельный пакет: npm i @itd-api/turnstile, затем getTurnstileToken: createTurnstileSolver().");
685
832
  }
686
- async #performSignIn(credentials) {
833
+ async #performSignIn(credentials, revision) {
687
834
  const turnstileToken = await this.#resolveTurnstileToken(credentials);
835
+ const flowCookies = new require_redact.CookieJar();
688
836
  const result = await this.#http.execute(AUTH_SIGN_IN, {
689
837
  path: AUTH_PATHS.signIn,
690
838
  body: {
@@ -693,18 +841,23 @@ var AuthManager = class {
693
841
  turnstileToken
694
842
  },
695
843
  skipAuth: true,
696
- skipAuthRefresh: true
844
+ skipAuthRefresh: true,
845
+ cookieJar: flowCookies
697
846
  });
698
847
  if (result.status !== SignInStatus.Authenticated) throw new require_errors.ItdConfigError("Вход по email и паролю требует подтверждения кодом из письма. Автоматический вход невозможен: воспользуйтесь itd.auth.signInWithOtp() и передайте полученный accessToken в конфигурацию клиента.");
699
848
  const accessToken = result.accessToken;
849
+ this.#assertActive();
850
+ if (this.#authEpoch !== revision) return this.#session?.accessToken ?? null;
851
+ this.#jar.replaceWith(flowCookies);
700
852
  this.#invalidateInFlight();
701
853
  this.#transitionAuth(accessToken);
702
- await this.#saveSession({
854
+ const saved = this.#saveSession({
703
855
  accessToken,
704
856
  obtainedAt: this.#config.clock.now()
705
857
  });
706
858
  this.#emitter.emit("tokens", { accessToken });
707
859
  this.#emitter.emit("signIn", { accessToken });
860
+ await saved;
708
861
  return accessToken;
709
862
  }
710
863
  };
@@ -763,14 +916,18 @@ var AuthResource = class extends require_render.BaseResource {
763
916
  * @param credentials email, пароль и обязательный токен капчи — см. {@link CaptchaCredentials}
764
917
  */
765
918
  async signIn(credentials, options = {}) {
919
+ const revision = this.#auth.revision();
920
+ const cookies = this.#auth.createCookieFlow(false);
766
921
  const result = await this.http.execute(AUTH_SIGN_IN, {
767
922
  path: AUTH_PATHS.signIn,
768
923
  body: credentials,
769
924
  skipAuth: true,
770
925
  skipAuthRefresh: true,
926
+ cookieJar: cookies,
771
927
  ...options
772
928
  });
773
- if (result.status === SignInStatus.Authenticated) await this.#auth.setAccessToken(result.accessToken);
929
+ if (result.status === SignInStatus.Authenticated) await this.#auth.setAccessToken(result.accessToken, revision, cookies);
930
+ else this.#auth.commitCookieFlow(cookies, revision);
774
931
  return result;
775
932
  }
776
933
  /**
@@ -779,14 +936,17 @@ var AuthResource = class extends require_render.BaseResource {
779
936
  * Полученный токен сохраняется в клиенте автоматически.
780
937
  */
781
938
  async verifyOtp(input, options = {}) {
939
+ const revision = this.#auth.revision();
940
+ const cookies = this.#auth.createCookieFlow();
782
941
  const accessToken = await this.http.execute(AUTH_VERIFY_OTP, {
783
942
  path: AUTH_PATHS.verifyOtp,
784
943
  body: input,
785
944
  skipAuth: true,
786
945
  skipAuthRefresh: true,
946
+ cookieJar: cookies,
787
947
  ...options
788
948
  });
789
- await this.#auth.setAccessToken(accessToken);
949
+ await this.#auth.setAccessToken(accessToken, revision, cookies);
790
950
  return accessToken;
791
951
  }
792
952
  /** Отправляет код подтверждения повторно. */
@@ -1705,7 +1865,7 @@ var ItdAccounts = class ItdAccounts {
1705
1865
  })));
1706
1866
  const added = [];
1707
1867
  for (const { name, session } of sessions) {
1708
- if (!require_multi_storage.isRestorableSession(session)) continue;
1868
+ if (!require_multi_storage.isRestorableSession(session, this.#base.baseUrl ?? "https://xn--d1ah4a.com")) continue;
1709
1869
  if (this.#clients.has(name) || this.#removing.has(name)) continue;
1710
1870
  this.addAccount(name);
1711
1871
  added.push(name);
@@ -2039,7 +2199,6 @@ exports.comment = require_render.comment;
2039
2199
  exports.createAccounts = createAccounts;
2040
2200
  exports.createClient = createClient;
2041
2201
  exports.createKeyValueStore = require_key_value_store.createKeyValueStore;
2042
- exports.createMemoryShopOrderAccessStorage = require_render.createMemoryShopOrderAccessStorage;
2043
2202
  exports.createMultiTokenStorage = require_multi_storage.createMultiTokenStorage;
2044
2203
  exports.createNotificationEventsClient = require_events.createNotificationEventsClient;
2045
2204
  exports.createRecordKeyValueStore = require_key_value_store.createRecordKeyValueStore;