itd-api 0.12.1 → 0.13.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.
- package/dist/events/index.cjs +4 -4
- package/dist/events/index.d.cts +7 -2
- package/dist/events/index.d.ts +7 -2
- package/dist/events/index.js +4 -4
- package/dist/index.cjs +715 -90
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +515 -46
- package/dist/index.d.ts +515 -46
- package/dist/index.js +707 -91
- package/dist/index.js.map +1 -1
- package/dist/node/index.cjs +6 -7
- package/dist/node/index.cjs.map +1 -1
- package/dist/node/index.d.cts +24 -7
- package/dist/node/index.d.ts +24 -7
- package/dist/node/index.js +6 -7
- package/dist/node/index.js.map +1 -1
- package/dist/rest/index.cjs +19 -7
- package/dist/rest/index.cjs.map +1 -1
- package/dist/rest/index.d.cts +28 -7
- package/dist/rest/index.d.ts +28 -7
- package/dist/rest/index.js +17 -8
- package/dist/rest/index.js.map +1 -1
- package/dist/shared/{contracts-BoT7msmq.d.ts → contracts-DEbkC0cB.d.cts} +1 -4
- package/dist/shared/{contracts-BoT7msmq.d.cts → contracts-pxnDIsQP.d.ts} +1 -4
- package/dist/shared/{events-FaXfdle0.d.cts → events-Bip3qvCc.d.cts} +42 -63
- package/dist/shared/{events-9215JDDd.d.ts → events-DF1elRzZ.d.ts} +2 -23
- package/dist/shared/{events-_iYo8EP5.js → events-DRbBDq9p.js} +30 -40
- package/dist/shared/events-DRbBDq9p.js.map +1 -0
- package/dist/shared/{events-BKyxZQNw.cjs → events-DcxmyPTX.cjs} +30 -40
- package/dist/shared/events-DcxmyPTX.cjs.map +1 -0
- package/dist/shared/{key-value-store-COZaNHZS.d.ts → key-value-store-BGoSgLze.d.cts} +1 -4
- package/dist/shared/{key-value-store-w1Dn5Pjb.js → key-value-store-BwXlaoD4.js} +3 -4
- package/dist/shared/{key-value-store-w1Dn5Pjb.js.map → key-value-store-BwXlaoD4.js.map} +1 -1
- package/dist/shared/{key-value-store-DYSPsqwq.cjs → key-value-store-CmnIjuE4.cjs} +3 -4
- package/dist/shared/{key-value-store-DYSPsqwq.cjs.map → key-value-store-CmnIjuE4.cjs.map} +1 -1
- package/dist/shared/{key-value-store-COZaNHZS.d.cts → key-value-store-WUQBeTAr.d.ts} +1 -4
- package/dist/shared/{multi-storage-LkljOSzA.d.ts → multi-storage-DQiERirK.d.ts} +3 -6
- package/dist/shared/{multi-storage-DiBSx64p.js → multi-storage-DffEAzdc.js} +6 -7
- package/dist/shared/{multi-storage-DiBSx64p.js.map → multi-storage-DffEAzdc.js.map} +1 -1
- package/dist/shared/{multi-storage-7Y3KCseI.cjs → multi-storage-Dp5x6OOl.cjs} +6 -7
- package/dist/shared/multi-storage-Dp5x6OOl.cjs.map +1 -0
- package/dist/shared/{multi-storage-BEL7tcKn.d.cts → multi-storage-OGWNMK3x.d.cts} +3 -6
- package/dist/shared/{options-DLlaETn_.js → options-Ddyc5qec.js} +8 -12
- package/dist/shared/{options-DLlaETn_.js.map → options-Ddyc5qec.js.map} +1 -1
- package/dist/shared/{options-D5ttspWk.cjs → options-DsmQRyx4.cjs} +8 -12
- package/dist/shared/{options-D5ttspWk.cjs.map → options-DsmQRyx4.cjs.map} +1 -1
- package/dist/shared/{redact-DSfdmeY7.js → redact-BCmucE19.js} +16 -16
- package/dist/shared/redact-BCmucE19.js.map +1 -0
- package/dist/shared/{redact-BbhtA9o-.cjs → redact-BuXRKC1G.cjs} +16 -16
- package/dist/shared/redact-BuXRKC1G.cjs.map +1 -0
- package/dist/shared/{render-BS09ygcy.d.ts → render-Bvv1V5Tp.d.ts} +154 -102
- package/dist/shared/{render-BQvC5UxF.cjs → render-C1lmsu1i.cjs} +204 -109
- package/dist/shared/render-C1lmsu1i.cjs.map +1 -0
- package/dist/shared/{render-X2JCo1JS.d.cts → render-D83t9ckd.d.cts} +152 -251
- package/dist/shared/{render-CFoF2WaH.js → render-DJKZqv9O.js} +181 -110
- package/dist/shared/render-DJKZqv9O.js.map +1 -0
- package/dist/shared/{storage-86wiHeXD.js → storage-Bc4lWtSj.js} +4 -5
- package/dist/shared/{storage-86wiHeXD.js.map → storage-Bc4lWtSj.js.map} +1 -1
- package/dist/shared/{storage-CTRGT5wF.d.ts → storage-C_ZujAZt.d.ts} +2 -5
- package/dist/shared/{storage-BQrtKon9.d.cts → storage-FtS4NIC7.d.cts} +2 -5
- package/dist/shared/{storage-CIjejZDt.cjs → storage-e2xYL6ro.cjs} +4 -5
- package/dist/shared/{storage-CIjejZDt.cjs.map → storage-e2xYL6ro.cjs.map} +1 -1
- package/dist/shared/{url-ioIaywDi.cjs → url-CXRaoR_w.cjs} +263 -91
- package/dist/shared/url-CXRaoR_w.cjs.map +1 -0
- package/dist/shared/{url-_R0oJ7gE.d.cts → url-V4bCae35.d.ts} +222 -78
- package/dist/shared/{url-CdT4lMxQ.js → url-aw_NZdVY.js} +263 -91
- package/dist/shared/url-aw_NZdVY.js.map +1 -0
- package/dist/shared/{url-_R0oJ7gE.d.ts → url-n_h2pvHA.d.cts} +1915 -1620
- package/dist/shared/{validate-CFx2dISs.cjs → validate-BHKy_YMv.cjs} +8 -7
- package/dist/shared/validate-BHKy_YMv.cjs.map +1 -0
- package/dist/shared/{validate-D7_kq3g5.js → validate-BQzL_oJ4.js} +8 -7
- package/dist/shared/validate-BQzL_oJ4.js.map +1 -0
- package/dist/web/index.cjs +4 -5
- package/dist/web/index.cjs.map +1 -1
- package/dist/web/index.d.cts +22 -5
- package/dist/web/index.d.ts +22 -5
- package/dist/web/index.js +4 -5
- package/dist/web/index.js.map +1 -1
- package/package.json +6 -6
- package/dist/shared/events-BKyxZQNw.cjs.map +0 -1
- package/dist/shared/events-_iYo8EP5.js.map +0 -1
- package/dist/shared/multi-storage-7Y3KCseI.cjs.map +0 -1
- package/dist/shared/redact-BbhtA9o-.cjs.map +0 -1
- package/dist/shared/redact-DSfdmeY7.js.map +0 -1
- package/dist/shared/render-BQvC5UxF.cjs.map +0 -1
- package/dist/shared/render-CFoF2WaH.js.map +0 -1
- package/dist/shared/url-CdT4lMxQ.js.map +0 -1
- package/dist/shared/url-ioIaywDi.cjs.map +0 -1
- package/dist/shared/validate-CFx2dISs.cjs.map +0 -1
- package/dist/shared/validate-D7_kq3g5.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import { $ as OperationMethod, A as ReportTargetType, B as isBuiltInOperationId, C as ItdErrorCode, D as NotificationType, E as MessageAccess, F as ViewSource, G as DEFAULT_RATE_LIMIT_BUCKET, H as operationMethod, I as WallAccess, J as pickArray, K as createClientRuntime, L as ITD_CATALOG, M as SpanType, N as UsernameUnavailableReason, O as QrLocationPrecision, P as ViewReason, Q as pickString, R as OPERATIONS, S as InteractionType, T as LikesVisibility, U as operationRetrySafety, V as operationBucket, W as BUCKET_LIMITS, _ as CaptchaType, _t as systemClock, at as requestAbortError, b as FeedTab, c as normalizeNotification, ct as assertPluginRemovable, d as canonicalNotificationType, et as RetrySafety, f as isKnownNotificationType, ft as STATUS_SERVICE, g as CaptchaField, h as CaptchaChoice, ht as RateLimitPacing, it as createRequestAbortScope, j as ServiceState, k as ReportReason, lt as orderPluginDefinitions, m as AttachmentType, mt as LIBRARY_VERSION, n as formatNotificationText, o as passthroughOperation, p as AccessType, pt as resolveRateLimit, q as createApiError, s as voidOperation, st as RequestQueuePool, t as resolveNotificationUrl, ut as DEFAULT_BASE_URL, v as CommentSort, vt as installAsyncDisposeFallback, w as LastSeenUnit, x as IncidentKind, y as EventChannelStatus, z as defineBuiltInOperation } from "./shared/url-
|
|
2
|
-
import { A as isItdForbiddenError, C as ItdValidationError, D as isItdConflictError, E as isItdAuthError, F as isItdStateError, I as isItdValidationError, M as isItdPhoneVerificationError, N as isItdRateLimitError, O as isItdError, P as isItdServerError, S as ItdTimeoutError, T as isItdApiError, _ as ItdNotFoundError, a as ItdAbortError, b as ItdServerError, c as ItdAuthError, d as ItdError, f as ItdErrorKind, g as ItdNetworkError, h as ItdForbiddenError, i as requireOptionalBoolean, j as isItdNotFoundError, k as isItdFileError, l as ItdConfigError, m as ItdFileErrorReason, n as isRecord, o as ItdApiError, p as ItdFileError, s as ItdApiErrorKind, t as isObjectLike, u as ItdConflictError, v as ItdPhoneVerificationError, w as TimeoutBudget, x as ItdStateError, y as ItdRateLimitError } from "./shared/validate-
|
|
3
|
-
import { D as
|
|
4
|
-
import {
|
|
5
|
-
import { c as
|
|
6
|
-
import {
|
|
7
|
-
import { a as
|
|
8
|
-
import {
|
|
9
|
-
import { a as
|
|
10
|
-
|
|
1
|
+
import { $ as OperationMethod, A as ReportTargetType, B as isBuiltInOperationId, C as ItdErrorCode, D as NotificationType, E as MessageAccess, F as ViewSource, G as DEFAULT_RATE_LIMIT_BUCKET, H as operationMethod, I as WallAccess, J as pickArray, K as createClientRuntime, L as ITD_CATALOG, M as SpanType, N as UsernameUnavailableReason, O as QrLocationPrecision, P as ViewReason, Q as pickString, R as OPERATIONS, S as InteractionType, T as LikesVisibility, U as operationRetrySafety, V as operationBucket, W as BUCKET_LIMITS, _ as CaptchaType, _t as systemClock, at as requestAbortError, b as FeedTab, c as normalizeNotification, ct as assertPluginRemovable, d as canonicalNotificationType, et as RetrySafety, f as isKnownNotificationType, ft as STATUS_SERVICE, g as CaptchaField, h as CaptchaChoice, ht as RateLimitPacing, it as createRequestAbortScope, j as ServiceState, k as ReportReason, lt as orderPluginDefinitions, m as AttachmentType, mt as LIBRARY_VERSION, n as formatNotificationText, o as passthroughOperation, p as AccessType, pt as resolveRateLimit, q as createApiError, s as voidOperation, st as RequestQueuePool, t as resolveNotificationUrl, ut as DEFAULT_BASE_URL, v as CommentSort, vt as installAsyncDisposeFallback, w as LastSeenUnit, x as IncidentKind, y as EventChannelStatus, z as defineBuiltInOperation } from "./shared/url-aw_NZdVY.js";
|
|
2
|
+
import { A as isItdForbiddenError, C as ItdValidationError, D as isItdConflictError, E as isItdAuthError, F as isItdStateError, I as isItdValidationError, M as isItdPhoneVerificationError, N as isItdRateLimitError, O as isItdError, P as isItdServerError, S as ItdTimeoutError, T as isItdApiError, _ as ItdNotFoundError, a as ItdAbortError, b as ItdServerError, c as ItdAuthError, d as ItdError, f as ItdErrorKind, g as ItdNetworkError, h as ItdForbiddenError, i as requireOptionalBoolean, j as isItdNotFoundError, k as isItdFileError, l as ItdConfigError, m as ItdFileErrorReason, n as isRecord, o as ItdApiError, p as ItdFileError, s as ItdApiErrorKind, t as isObjectLike, u as ItdConflictError, v as ItdPhoneVerificationError, w as TimeoutBudget, x as ItdStateError, y as ItdRateLimitError } from "./shared/validate-BQzL_oJ4.js";
|
|
3
|
+
import { A as isBuilder, B as createFeatureHost, C as LegalDocumentBlockType, D as IMAGE_MIME_TYPES, E as AUDIO_MIME_TYPES, F as NotificationsResource, I as BaseResource, L as PaginationMode, M as toDate, N as utcStampToIso, O as VIDEO_MIME_TYPES, P as AccountLifecycleResource, R as Paginator, S as parseMarkdown, T as ALLOWED_MIME_TYPES, V as ExtensibleOperationCatalog, _ as post, a as createShopOrderAccessStorage, b as markup, c as ShopOrderStatus, d as isMyProfile, f as BannerDrawingTool, g as report, h as createResources, i as MemoryShopOrderAccessStorage, j as createStatusFeature, k as comment, l as ShopProductCategory, m as fromUrl, n as renderSpans, o as statusDays, p as fromStream, r as createShopFeature, s as ShopConsentKind, t as SpanRenderFormat, u as ShopProductStatus, v as poll, w as LegalDocumentScope, x as parseHtml, y as autoSpans, z as mapPage } from "./shared/render-DJKZqv9O.js";
|
|
4
|
+
import { _ as Emitter, a as WebSocketTransport, c as NotificationEventsTransport, d as NotificationUpdateOrigin, f as NotificationUpdateType, g as runEventMiddleware, h as UnauthorizedStreamError, i as createNotificationEventsClient, l as resolveNotificationEventsOptions, m as EventChannel, n as EventRouter, o as EVENT_OPERATIONS, p as createParser, r as NotificationEventsClient, s as NotificationEvents, t as EventComposer, u as setNotificationEventsConnectGuard, v as reportListenerError } from "./shared/events-DRbBDq9p.js";
|
|
5
|
+
import { D as fallbackLogger, E as LogLevel, c as REFRESH_COOKIE, f as encodePathSegment, h as joinUrl, k as resolveLogger, l as REFRESH_COOKIE_PATH, s as CookieJar, u as isSerializedCookieEntry, v as RuntimeMode, y as createDeviceId } from "./shared/redact-BCmucE19.js";
|
|
6
|
+
import { n as copySession, r as createTokenStorage, t as MemoryTokenStorage } from "./shared/storage-Bc4lWtSj.js";
|
|
7
|
+
import { a as scopedTokenStorage, i as isRestorableSession, n as controlledTokenStorage, r as createMultiTokenStorage, t as MemoryMultiTokenStorage } from "./shared/multi-storage-DffEAzdc.js";
|
|
8
|
+
import { c as FileTransferMode } from "./shared/options-Ddyc5qec.js";
|
|
9
|
+
import { a as isEnumerableKeyValueStore, i as createRecordKeyValueStore, o as withCodec, r as createKeyValueStore, s as withNamespace, t as MemoryKeyValueStore } from "./shared/key-value-store-BwXlaoD4.js";
|
|
10
|
+
// src/notifications-api.ts
|
|
11
11
|
var ClientNotifications = class extends NotificationsResource {
|
|
12
12
|
#createEvents;
|
|
13
13
|
#events;
|
|
@@ -24,8 +24,397 @@ var ClientNotifications = class extends NotificationsResource {
|
|
|
24
24
|
function createNotificationsApi(http, createEvents) {
|
|
25
25
|
return new ClientNotifications(http, createEvents);
|
|
26
26
|
}
|
|
27
|
-
|
|
28
|
-
|
|
27
|
+
// src/operations/account.ts
|
|
28
|
+
const ACCOUNT_GET_INFO = passthroughOperation("account.getInfo");
|
|
29
|
+
const ACCOUNT_PASSWORD_SET = voidOperation("account.password.set");
|
|
30
|
+
const ACCOUNT_PASSWORD_CHANGE = voidOperation("account.password.change");
|
|
31
|
+
// src/operations/account/changes.ts
|
|
32
|
+
const ACCOUNT_CHANGES_REQUEST_PROOF = passthroughOperation("account.changes.requestProof");
|
|
33
|
+
const ACCOUNT_CHANGES_CONFIRM = voidOperation("account.changes.confirm");
|
|
34
|
+
const ACCOUNT_CHANGES_WAIT = passthroughOperation("account.changes.wait");
|
|
35
|
+
const ACCOUNT_CHANGES_PENDING = defineBuiltInOperation("account.changes.pending", (body) => pickArray(body, "requests"));
|
|
36
|
+
const ACCOUNT_CHANGES_CANCEL_PENDING = voidOperation("account.changes.cancelPending");
|
|
37
|
+
// src/resources/account/request.ts
|
|
38
|
+
/** Выполняет запрос настройки способов входа с текущей авторизацией. */
|
|
39
|
+
function requestAccount(http, operation, path, body, options) {
|
|
40
|
+
return http.execute(operation, {
|
|
41
|
+
...options,
|
|
42
|
+
path: `/api/v1/auth${path}`,
|
|
43
|
+
body
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
// src/resources/account/changes.ts
|
|
47
|
+
/** Завершение смены номера или почты и управление отложенными заявками. */
|
|
48
|
+
var AccountChangesResource = class extends BaseResource {
|
|
49
|
+
/**
|
|
50
|
+
* Запрашивает код на привязанный номер или почту.
|
|
51
|
+
*
|
|
52
|
+
* Возьмите `changeToken` и способ доставки из результата `verifyChange()` или
|
|
53
|
+
* `phone.reverseChangeComplete()`. Полученный код передайте в {@link confirm}.
|
|
54
|
+
*/
|
|
55
|
+
requestProof(input, options = {}) {
|
|
56
|
+
return requestAccount(this.http, ACCOUNT_CHANGES_REQUEST_PROOF, "/change/proof", input, options);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Завершает смену номера или почты.
|
|
60
|
+
*
|
|
61
|
+
* Передайте `changeToken` и код из {@link requestProof} либо облачный
|
|
62
|
+
* пароль, если сервер предложил такой способ подтверждения.
|
|
63
|
+
*/
|
|
64
|
+
confirm(input, options = {}) {
|
|
65
|
+
return requestAccount(this.http, ACCOUNT_CHANGES_CONFIRM, "/change/confirm", input, options);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Создаёт отложенную заявку на смену номера или почты.
|
|
69
|
+
*
|
|
70
|
+
* @returns время применения заявки. До этого её можно отменить через {@link cancelPending}
|
|
71
|
+
*/
|
|
72
|
+
wait(changeToken, options = {}) {
|
|
73
|
+
return requestAccount(this.http, ACCOUNT_CHANGES_WAIT, "/change/wait", { changeToken }, options);
|
|
74
|
+
}
|
|
75
|
+
/** Возвращает отложенные заявки текущего аккаунта. */
|
|
76
|
+
pending(options = {}) {
|
|
77
|
+
return requestAccount(this.http, ACCOUNT_CHANGES_PENDING, "/change/pending", void 0, options);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Отменяет отложенную смену.
|
|
81
|
+
*
|
|
82
|
+
* @param requestId идентификатор заявки из {@link pending}
|
|
83
|
+
*/
|
|
84
|
+
cancelPending(requestId, options = {}) {
|
|
85
|
+
return requestAccount(this.http, ACCOUNT_CHANGES_CANCEL_PENDING, `/change/pending/${encodePathSegment(requestId, "requestId")}`, void 0, options);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
// src/operations/account/email.ts
|
|
89
|
+
/** Извлекает токен для подтверждения адреса почты. */
|
|
90
|
+
function readEmailFlow(body) {
|
|
91
|
+
const flowToken = pickString(body, "flowToken");
|
|
92
|
+
if (!flowToken) throw new ItdConfigError("Сервер не вернул flowToken для подтверждения почты");
|
|
93
|
+
return flowToken;
|
|
94
|
+
}
|
|
95
|
+
const ACCOUNT_EMAIL_ATTACH = defineBuiltInOperation("account.email.attach", readEmailFlow);
|
|
96
|
+
const ACCOUNT_EMAIL_START_CHANGE = defineBuiltInOperation("account.email.startChange", readEmailFlow);
|
|
97
|
+
const ACCOUNT_EMAIL_RESEND_OTP = voidOperation("account.email.resendOtp");
|
|
98
|
+
// src/models/phone-auth.ts
|
|
99
|
+
/** Назначение контекста согласия телефонного входа. @internal */
|
|
100
|
+
const PHONE_CONSENT_FLOW = "phone_entry";
|
|
101
|
+
/** Назначение ответа общего endpoint подтверждения кода. */
|
|
102
|
+
const AuthVerificationMode = Object.freeze({
|
|
103
|
+
SignIn: "signin",
|
|
104
|
+
Change: "change"
|
|
105
|
+
});
|
|
106
|
+
/** Серверные каналы доставки кода. */
|
|
107
|
+
const PhoneDeliveryChannel = Object.freeze({
|
|
108
|
+
MissedCall: "missed_call",
|
|
109
|
+
VoiceCall: "voice_call",
|
|
110
|
+
Sms: "sms",
|
|
111
|
+
Push: "push"
|
|
112
|
+
});
|
|
113
|
+
/** Подтверждение входящим кодом либо исходящим звонком пользователя. */
|
|
114
|
+
const PhoneVerificationMethod = Object.freeze({
|
|
115
|
+
Direct: "direct",
|
|
116
|
+
Reverse: "reverse"
|
|
117
|
+
});
|
|
118
|
+
/** Продолжение телефонного входа, ещё не выдавшее access token. */
|
|
119
|
+
const PhoneLoginStep = Object.freeze({ Password: "password" });
|
|
120
|
+
/** Состояния подтверждения номера исходящим звонком. */
|
|
121
|
+
const PhoneReverseState = Object.freeze({
|
|
122
|
+
NotStarted: "not_started",
|
|
123
|
+
Preparing: "preparing",
|
|
124
|
+
Waiting: "waiting",
|
|
125
|
+
Confirmed: "confirmed",
|
|
126
|
+
Expired: "expired",
|
|
127
|
+
Failed: "failed"
|
|
128
|
+
});
|
|
129
|
+
// src/operations/account/verification.ts
|
|
130
|
+
/** Отделяет ответ смены контакта от результата входа на общем маршруте подтверждения. */
|
|
131
|
+
function readContactChange(body) {
|
|
132
|
+
const changeToken = pickString(body, "changeToken");
|
|
133
|
+
if (!isRecord(body) || body.mode !== void 0 && body.mode !== AuthVerificationMode.Change || !changeToken) throw new ItdConfigError("Сервер не вернул подтверждение смены контакта");
|
|
134
|
+
return {
|
|
135
|
+
changeToken,
|
|
136
|
+
proofs: pickArray(body, "proofs"),
|
|
137
|
+
...typeof body.waitDays === "number" ? { waitDays: body.waitDays } : {}
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
const ACCOUNT_VERIFY_ATTACH = passthroughOperation("account.verifyAttach");
|
|
141
|
+
const ACCOUNT_VERIFY_CHANGE = defineBuiltInOperation("account.verifyChange", (body) => {
|
|
142
|
+
if (!isRecord(body) || body.mode !== AuthVerificationMode.Change) throw new ItdConfigError("Сервер не вернул режим смены контакта");
|
|
143
|
+
return readContactChange(body);
|
|
144
|
+
});
|
|
145
|
+
const ACCOUNT_PHONE_REVERSE_ATTACH_COMPLETE = passthroughOperation("account.phone.reverseAttachComplete");
|
|
146
|
+
const ACCOUNT_PHONE_REVERSE_CHANGE_COMPLETE = defineBuiltInOperation("account.phone.reverseChangeComplete", readContactChange);
|
|
147
|
+
// src/resources/account/email.ts
|
|
148
|
+
/** Привязка и смена почты текущего аккаунта. */
|
|
149
|
+
var AccountEmailResource = class extends BaseResource {
|
|
150
|
+
/**
|
|
151
|
+
* Отправляет код на почту для привязки.
|
|
152
|
+
*
|
|
153
|
+
* @returns значение `flowToken` для {@link verifyAttach} или {@link resendOtp}
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* ```ts
|
|
157
|
+
* const flowToken = await itd.account.email.attach(email);
|
|
158
|
+
* await itd.account.email.verifyAttach({ email, flowToken, otp: await getOtp() });
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
attach(email, options = {}) {
|
|
162
|
+
return requestAccount(this.http, ACCOUNT_EMAIL_ATTACH, "/email/attach", { email }, options);
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Отправляет код на новый адрес почты.
|
|
166
|
+
*
|
|
167
|
+
* @returns значение `flowToken` для {@link verifyChange} или {@link resendOtp}
|
|
168
|
+
*/
|
|
169
|
+
startChange(email, options = {}) {
|
|
170
|
+
return requestAccount(this.http, ACCOUNT_EMAIL_START_CHANGE, "/email/change", { email }, options);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Завершает привязку почты кодом.
|
|
174
|
+
*
|
|
175
|
+
* Передайте тот же адрес и `flowToken` из {@link attach}.
|
|
176
|
+
*/
|
|
177
|
+
verifyAttach(input, options = {}) {
|
|
178
|
+
return requestAccount(this.http, ACCOUNT_VERIFY_ATTACH, "/verify-otp", input, options);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Подтверждает код новой почты, запрошенный через {@link startChange}.
|
|
182
|
+
*
|
|
183
|
+
* @returns `changeToken` и способы завершить смену через `itd.account.changes`
|
|
184
|
+
*/
|
|
185
|
+
verifyChange(input, options = {}) {
|
|
186
|
+
return requestAccount(this.http, ACCOUNT_VERIFY_CHANGE, "/verify-otp", input, options);
|
|
187
|
+
}
|
|
188
|
+
/** Повторно отправляет код на тот же адрес. Передайте `flowToken` из первого запроса. */
|
|
189
|
+
resendOtp(input, options = {}) {
|
|
190
|
+
return requestAccount(this.http, ACCOUNT_EMAIL_RESEND_OTP, "/resend-otp", input, options);
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
// src/resources/account/password.ts
|
|
194
|
+
/** Облачный пароль текущего аккаунта. */
|
|
195
|
+
var AccountPasswordResource = class extends BaseResource {
|
|
196
|
+
/**
|
|
197
|
+
* Создаёт облачный пароль для аккаунта без пароля.
|
|
198
|
+
*
|
|
199
|
+
* Наличие пароля можно проверить через `itd.account.getInfo()`.
|
|
200
|
+
*/
|
|
201
|
+
set(password, options = {}) {
|
|
202
|
+
return requestAccount(this.http, ACCOUNT_PASSWORD_SET, "/set-password", { password }, options);
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Меняет облачный пароль в действующей сессии.
|
|
206
|
+
*
|
|
207
|
+
* При неверном текущем пароле сервер возвращает `ACCOUNT_CURRENT_PASSWORD_INCORRECT`.
|
|
208
|
+
*
|
|
209
|
+
* @example
|
|
210
|
+
* ```ts
|
|
211
|
+
* await itd.account.password.change({ currentPassword, newPassword });
|
|
212
|
+
* ```
|
|
213
|
+
*/
|
|
214
|
+
change({ currentPassword, newPassword }, options = {}) {
|
|
215
|
+
return this.voidOperation(ACCOUNT_PASSWORD_CHANGE, {
|
|
216
|
+
path: "/api/v1/auth/change-password",
|
|
217
|
+
body: {
|
|
218
|
+
currentPassword,
|
|
219
|
+
newPassword
|
|
220
|
+
},
|
|
221
|
+
...options
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
// src/operations/phone-flow.ts
|
|
226
|
+
/** Приводит вложенные и плоские параметры доставки к одному результату. */
|
|
227
|
+
function readPhoneDelivery(body) {
|
|
228
|
+
const response = body;
|
|
229
|
+
const next = response.next ?? response.nextChannel;
|
|
230
|
+
return {
|
|
231
|
+
channel: response.delivery?.type ?? response.channel,
|
|
232
|
+
codeLength: response.delivery?.codeLength ?? response.codeLength,
|
|
233
|
+
retryIn: response.retryIn,
|
|
234
|
+
...response.reverseOnly === true ? { reverseOnly: true } : {},
|
|
235
|
+
nextChannel: next ?? null
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
/** Извлекает `flowToken` и параметры доставки после запуска проверки номера. */
|
|
239
|
+
function readPhoneStart(body) {
|
|
240
|
+
const flowToken = pickString(body, "flowToken");
|
|
241
|
+
if (!flowToken) throw new ItdConfigError("Сервер не вернул flowToken для проверки номера");
|
|
242
|
+
return {
|
|
243
|
+
...readPhoneDelivery(body),
|
|
244
|
+
flowToken
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
// src/operations/account/phone.ts
|
|
248
|
+
const ACCOUNT_PHONE_ATTACH = defineBuiltInOperation("account.phone.attach", readPhoneStart);
|
|
249
|
+
const ACCOUNT_PHONE_START_CHANGE = defineBuiltInOperation("account.phone.startChange", readPhoneStart);
|
|
250
|
+
const ACCOUNT_PHONE_RESEND_OTP = defineBuiltInOperation("account.phone.resendOtp", readPhoneDelivery);
|
|
251
|
+
const ACCOUNT_PHONE_SYNC = passthroughOperation("account.phone.sync");
|
|
252
|
+
const ACCOUNT_PHONE_REVERSE_OPTIONS = passthroughOperation("account.phone.reverseOptions");
|
|
253
|
+
const ACCOUNT_PHONE_REVERSE_START = passthroughOperation("account.phone.reverseStart");
|
|
254
|
+
const ACCOUNT_PHONE_REVERSE_STATUS = passthroughOperation("account.phone.reverseStatus");
|
|
255
|
+
// src/resources/account/phone.ts
|
|
256
|
+
/** Привязка и смена номера текущего аккаунта. */
|
|
257
|
+
var AccountPhoneResource = class extends BaseResource {
|
|
258
|
+
#auth;
|
|
259
|
+
constructor(http, auth) {
|
|
260
|
+
super(http);
|
|
261
|
+
this.#auth = auth;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Запрашивает подтверждение номера для привязки.
|
|
265
|
+
*
|
|
266
|
+
* Передайте номер в международном формате с `+`. Если токен капчи не передан
|
|
267
|
+
* в вызов, SDK использует настроенный источник капчи.
|
|
268
|
+
* Для исходящего звонка передайте `method: PhoneVerificationMethod.Reverse`.
|
|
269
|
+
*
|
|
270
|
+
* @returns параметры доставки и `flowToken` для {@link verifyAttach}
|
|
271
|
+
*
|
|
272
|
+
* @example
|
|
273
|
+
* ```ts
|
|
274
|
+
* const { flowToken } = await itd.account.phone.attach({ phone });
|
|
275
|
+
* await itd.account.phone.verifyAttach({ phone, flowToken, otp: await getOtp() });
|
|
276
|
+
* ```
|
|
277
|
+
*/
|
|
278
|
+
attach(input, options = {}) {
|
|
279
|
+
return this.#start(ACCOUNT_PHONE_ATTACH, "/phone/attach", input, options);
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Запрашивает подтверждение нового номера для смены.
|
|
283
|
+
*
|
|
284
|
+
* Формат номера, источник капчи и выбор способа подтверждения такие же, как у {@link attach}.
|
|
285
|
+
*
|
|
286
|
+
* @returns параметры доставки и `flowToken` для {@link verifyChange}
|
|
287
|
+
*/
|
|
288
|
+
startChange(input, options = {}) {
|
|
289
|
+
return this.#start(ACCOUNT_PHONE_START_CHANGE, "/phone/change", input, options);
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Завершает привязку номера кодом.
|
|
293
|
+
*
|
|
294
|
+
* Передайте номер и `flowToken` из {@link attach}.
|
|
295
|
+
*/
|
|
296
|
+
verifyAttach(input, options = {}) {
|
|
297
|
+
return this.#request(ACCOUNT_VERIFY_ATTACH, "/verify-otp", input, options);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Подтверждает код нового номера, запрошенный через {@link startChange}.
|
|
301
|
+
*
|
|
302
|
+
* @returns `changeToken` и способы завершить смену через `itd.account.changes`
|
|
303
|
+
*/
|
|
304
|
+
verifyChange(input, options = {}) {
|
|
305
|
+
return this.#request(ACCOUNT_VERIFY_CHANGE, "/verify-otp", input, options);
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Повторно запрашивает код для того же номера. Передайте `flowToken` из первого запроса.
|
|
309
|
+
*
|
|
310
|
+
* @returns актуальные канал, длину кода и паузу до повтора в секундах
|
|
311
|
+
*/
|
|
312
|
+
resendOtp(input, options = {}) {
|
|
313
|
+
return this.#request(ACCOUNT_PHONE_RESEND_OTP, "/resend-otp", input, options);
|
|
314
|
+
}
|
|
315
|
+
/** Синхронизирует привязанный номер с профилем. */
|
|
316
|
+
sync(options = {}) {
|
|
317
|
+
return requestAccount(this.http, ACCOUNT_PHONE_SYNC, "/phone/sync", {}, options);
|
|
318
|
+
}
|
|
319
|
+
/** Возвращает доступность исходящего звонка для привязки или смены номера. */
|
|
320
|
+
reverseOptions(input, options = {}) {
|
|
321
|
+
return this.#request(ACCOUNT_PHONE_REVERSE_OPTIONS, "/phone/reverse/options", input, options);
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Подготавливает номер, на который должен позвонить пользователь.
|
|
325
|
+
*
|
|
326
|
+
* @returns состояние попытки, номер для звонка и срок действия в секундах
|
|
327
|
+
*/
|
|
328
|
+
reverseStart(input, options = {}) {
|
|
329
|
+
return this.#request(ACCOUNT_PHONE_REVERSE_START, "/phone/reverse/start", input, options);
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Читает состояние исходящего звонка.
|
|
333
|
+
*
|
|
334
|
+
* После подтверждения вызовите {@link reverseAttachComplete} при привязке
|
|
335
|
+
* или {@link reverseChangeComplete} при смене номера.
|
|
336
|
+
*/
|
|
337
|
+
reverseStatus(input, options = {}) {
|
|
338
|
+
return this.#request(ACCOUNT_PHONE_REVERSE_STATUS, "/phone/reverse/status", input, options);
|
|
339
|
+
}
|
|
340
|
+
/** Завершает привязку номера после исходящего звонка. */
|
|
341
|
+
reverseAttachComplete(input, options = {}) {
|
|
342
|
+
return this.#request(ACCOUNT_PHONE_REVERSE_ATTACH_COMPLETE, "/phone/reverse/complete", input, options);
|
|
343
|
+
}
|
|
344
|
+
/** Подтверждает новый номер звонком и возвращает варианты завершения смены. */
|
|
345
|
+
reverseChangeComplete(input, options = {}) {
|
|
346
|
+
return this.#request(ACCOUNT_PHONE_REVERSE_CHANGE_COMPLETE, "/phone/reverse/complete", input, options);
|
|
347
|
+
}
|
|
348
|
+
/** Запускает проверку номера, если за время получения капчи сессия не сменилась. */
|
|
349
|
+
async #start(operation, path, { phone, captcha, method }, options) {
|
|
350
|
+
const revision = this.#auth.revision();
|
|
351
|
+
const proof = await this.#auth.captchaToken(captcha);
|
|
352
|
+
if (this.#auth.revision() !== revision) throw new ItdStateError("Сессия сменилась во время получения капчи. Начните проверку номера заново.");
|
|
353
|
+
return this.#request(operation, path, {
|
|
354
|
+
phone,
|
|
355
|
+
captcha: proof ? {
|
|
356
|
+
provider: proof.type,
|
|
357
|
+
token: proof.token
|
|
358
|
+
} : void 0
|
|
359
|
+
}, {
|
|
360
|
+
...options,
|
|
361
|
+
headers: {
|
|
362
|
+
...options.headers,
|
|
363
|
+
...method === PhoneVerificationMethod.Reverse ? { "X-ITD-Phone-Method": PhoneVerificationMethod.Reverse } : {}
|
|
364
|
+
}
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
/** Объявляет поддержку исходящего звонка и срока действия проверки номера. */
|
|
368
|
+
#request(operation, path, body, options) {
|
|
369
|
+
return requestAccount(this.http, operation, path, body, {
|
|
370
|
+
...options,
|
|
371
|
+
headers: {
|
|
372
|
+
...options.headers,
|
|
373
|
+
"X-ITD-Phone-Reverse": "1",
|
|
374
|
+
"X-ITD-Flow-Expiry": "1",
|
|
375
|
+
...path.startsWith("/phone/reverse/") ? { "X-ITD-Reverse-Attempts": "1" } : {}
|
|
376
|
+
}
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
// src/resources/account.ts
|
|
381
|
+
/**
|
|
382
|
+
* Настройки текущего аккаунта. Доступен как `itd.account`.
|
|
383
|
+
*
|
|
384
|
+
* Здесь можно менять номер, почту и облачный пароль, управлять отложенными
|
|
385
|
+
* заявками, деактивировать и восстановить аккаунт.
|
|
386
|
+
*/
|
|
387
|
+
var AccountResource = class extends AccountLifecycleResource {
|
|
388
|
+
/** Привязка и смена номера. */
|
|
389
|
+
phone;
|
|
390
|
+
/** Привязка и смена почты. */
|
|
391
|
+
email;
|
|
392
|
+
/** Настройка облачного пароля. */
|
|
393
|
+
password;
|
|
394
|
+
/** Завершение смены номера или почты и отложенные заявки. */
|
|
395
|
+
changes;
|
|
396
|
+
constructor(http, auth) {
|
|
397
|
+
super(http);
|
|
398
|
+
this.phone = new AccountPhoneResource(http, auth);
|
|
399
|
+
this.email = new AccountEmailResource(http);
|
|
400
|
+
this.password = new AccountPasswordResource(http);
|
|
401
|
+
this.changes = new AccountChangesResource(http);
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Получает сведения о доступе к текущему аккаунту.
|
|
405
|
+
*
|
|
406
|
+
* @returns привязанные номер и почту и признак наличия облачного пароля
|
|
407
|
+
*
|
|
408
|
+
* @example
|
|
409
|
+
* ```ts
|
|
410
|
+
* const { email, phone, hasPassword } = await itd.account.getInfo();
|
|
411
|
+
* ```
|
|
412
|
+
*/
|
|
413
|
+
getInfo(options = {}) {
|
|
414
|
+
return requestAccount(this.http, ACCOUNT_GET_INFO, "/methods", void 0, options);
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
// src/operations/auth.ts
|
|
29
418
|
/** Чем закончился запрос входа. */
|
|
30
419
|
const SignInStatus = Object.freeze({
|
|
31
420
|
Authenticated: "authenticated",
|
|
@@ -61,8 +450,8 @@ function requireString(body, key, message) {
|
|
|
61
450
|
return value;
|
|
62
451
|
}
|
|
63
452
|
const AUTH_CHECK = passthroughOperation("auth.check");
|
|
64
|
-
passthroughOperation("auth.captchaProvider");
|
|
65
|
-
passthroughOperation("auth.captchaPage");
|
|
453
|
+
const AUTH_CAPTCHA_PROVIDER = passthroughOperation("auth.captchaProvider");
|
|
454
|
+
const AUTH_CAPTCHA_PAGE = passthroughOperation("auth.captchaPage");
|
|
66
455
|
const AUTH_SIGN_UP = defineBuiltInOperation("auth.signUp", (body) => requireString(body, "flowToken", "Сервер не вернул flowToken при регистрации"));
|
|
67
456
|
const AUTH_SIGN_IN = defineBuiltInOperation("auth.signIn", (body) => {
|
|
68
457
|
const accessToken = pickString(body, "accessToken");
|
|
@@ -80,7 +469,6 @@ const AUTH_RESEND_OTP = voidOperation("auth.resendOtp");
|
|
|
80
469
|
const AUTH_LOGOUT = voidOperation("auth.logout");
|
|
81
470
|
const AUTH_FORGOT_PASSWORD = defineBuiltInOperation("auth.forgotPassword", (body) => requireString(body, "flowToken", "Сервер не вернул flowToken при запросе сброса пароля"));
|
|
82
471
|
const AUTH_RESET_PASSWORD = voidOperation("auth.resetPassword");
|
|
83
|
-
const AUTH_CHANGE_PASSWORD = voidOperation("auth.changePassword");
|
|
84
472
|
const AUTH_SESSIONS = defineBuiltInOperation("auth.sessions", (body) => pickArray(body, "sessions"));
|
|
85
473
|
const AUTH_REVOKE_SESSION = voidOperation("auth.revokeSession");
|
|
86
474
|
const AUTH_REVOKE_OTHER_SESSIONS = voidOperation("auth.revokeOtherSessions");
|
|
@@ -89,8 +477,7 @@ const AUTH_QR_CLAIM = passthroughOperation("auth.qrClaim");
|
|
|
89
477
|
const AUTH_QR_SCAN = passthroughOperation("auth.qrScan");
|
|
90
478
|
const AUTH_QR_APPROVE = voidOperation("auth.qrApprove");
|
|
91
479
|
const AUTH_QR_REJECT = voidOperation("auth.qrReject");
|
|
92
|
-
|
|
93
|
-
//#region src/session/captcha.ts
|
|
480
|
+
// src/session/captcha.ts
|
|
94
481
|
function requireCaptchaText(value, field) {
|
|
95
482
|
if (value !== void 0 && (typeof value !== "string" || value.trim() === "")) throw new ItdConfigError(`${field} должен быть непустой строкой`);
|
|
96
483
|
}
|
|
@@ -126,6 +513,17 @@ function validateCaptchaToken(captcha, path) {
|
|
|
126
513
|
if (typeof type !== "string" || type.trim() === "") throw new ItdConfigError(`${path}.type должен быть непустой строкой`);
|
|
127
514
|
requireCaptchaText(field, `${path}.field`);
|
|
128
515
|
}
|
|
516
|
+
/** Разбирает ответ `GET /api/v1/auth/captcha/provider` для автоматического входа. */
|
|
517
|
+
function readCaptchaProvider(body) {
|
|
518
|
+
const config = isRecord(body) ? body : void 0;
|
|
519
|
+
const provider = config?.provider;
|
|
520
|
+
const field = config?.field;
|
|
521
|
+
if (typeof provider !== "string" || provider.trim() === "" || typeof field !== "string" || field.trim() === "") throw new ItdConfigError("Сервер вернул неподдерживаемую конфигурацию капчи");
|
|
522
|
+
return {
|
|
523
|
+
provider,
|
|
524
|
+
field
|
|
525
|
+
};
|
|
526
|
+
}
|
|
129
527
|
/** Куда класть токен: настройка, иначе умолчание провайдера. */
|
|
130
528
|
function resolveField(type, configured) {
|
|
131
529
|
const field = configured ?? CAPTCHA_FIELDS[type];
|
|
@@ -138,37 +536,30 @@ async function requireSolvedToken(solver, type, context) {
|
|
|
138
536
|
if (typeof token === "string" && token.trim() !== "") return token;
|
|
139
537
|
throw new ItdConfigError(`Источник капчи не вернул токен для провайдера «${type}». Проверьте captcha.getToken.`);
|
|
140
538
|
}
|
|
141
|
-
/**
|
|
142
|
-
|
|
143
|
-
*
|
|
144
|
-
* При `CaptchaChoice.Auto` провайдер спрашивается у сервера — тогда и тип виджета,
|
|
145
|
-
* и имя поля приходят оттуда. Явно названный тип обходится без этого запроса.
|
|
146
|
-
*
|
|
147
|
-
* @param askProvider как спросить активного провайдера; вызывается, только если это нужно
|
|
148
|
-
* @param context что источник получает вместе с типом капчи
|
|
149
|
-
* @throws {ItdConfigError} если токен получить не удалось
|
|
150
|
-
*/
|
|
151
|
-
async function solveCaptchaBody(solver, askProvider, context) {
|
|
539
|
+
/** Сохраняет провайдера и токен для API, принимающих доказательство капчи объектом. */
|
|
540
|
+
async function solveCaptchaToken(solver, askProvider, context) {
|
|
152
541
|
const choice = solver.type ?? CaptchaChoice.Auto;
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
}
|
|
157
|
-
return {
|
|
542
|
+
const { provider, field } = choice === CaptchaChoice.Auto ? await askProvider() : {
|
|
543
|
+
provider: choice,
|
|
544
|
+
field: solver.field
|
|
545
|
+
};
|
|
546
|
+
return {
|
|
547
|
+
type: provider,
|
|
548
|
+
field,
|
|
549
|
+
token: await requireSolvedToken(solver, provider, context)
|
|
550
|
+
};
|
|
158
551
|
}
|
|
159
552
|
/**
|
|
160
553
|
* Готовит фрагмент тела из готового токена.
|
|
161
554
|
*
|
|
162
555
|
* Поле берётся из самого токена либо из умолчания провайдера; запроса к серверу нет.
|
|
163
556
|
*
|
|
164
|
-
* @throws {ItdConfigError} если
|
|
557
|
+
* @throws {ItdConfigError} если для провайдера не определено поле запроса
|
|
165
558
|
*/
|
|
166
559
|
function captchaBody(captcha) {
|
|
167
|
-
validateCaptchaToken(captcha, "captcha");
|
|
168
560
|
return { [resolveField(captcha.type, captcha.field)]: captcha.token };
|
|
169
561
|
}
|
|
170
|
-
|
|
171
|
-
//#region src/session/jwt.ts
|
|
562
|
+
// src/session/jwt.ts
|
|
172
563
|
/**
|
|
173
564
|
* Разбирает строку base64url.
|
|
174
565
|
*
|
|
@@ -207,8 +598,7 @@ function readTokenMetadata(token) {
|
|
|
207
598
|
...expiresAt !== void 0 && Number.isFinite(expiresAt) ? { expiresAt } : {}
|
|
208
599
|
};
|
|
209
600
|
}
|
|
210
|
-
|
|
211
|
-
//#region src/session/auth.ts
|
|
601
|
+
// src/session/auth.ts
|
|
212
602
|
/** Запас до истечения токена на очередь и выполнение запроса. */
|
|
213
603
|
const ACCESS_TOKEN_REFRESH_LEEWAY_MS = 3e4;
|
|
214
604
|
/**
|
|
@@ -300,7 +690,6 @@ const AUTH_PATHS = {
|
|
|
300
690
|
logout: "/api/v1/auth/logout",
|
|
301
691
|
forgotPassword: "/api/v1/auth/forgot-password",
|
|
302
692
|
resetPassword: "/api/v1/auth/reset-password",
|
|
303
|
-
changePassword: "/api/v1/auth/change-password",
|
|
304
693
|
sessions: "/api/v1/auth/sessions",
|
|
305
694
|
qrStart: "/api/v1/auth/qr/start",
|
|
306
695
|
qrClaim: "/api/v1/auth/qr/claim",
|
|
@@ -992,13 +1381,20 @@ var AuthManager = class {
|
|
|
992
1381
|
* @throws {ItdConfigError} если токен неполный или источник его не вернул
|
|
993
1382
|
*/
|
|
994
1383
|
async captchaBody(explicit) {
|
|
995
|
-
|
|
1384
|
+
const token = await this.captchaToken(explicit);
|
|
1385
|
+
return token ? captchaBody(token) : {};
|
|
1386
|
+
}
|
|
1387
|
+
/** Доказательство капчи с провайдером для телефонного API. @internal */
|
|
1388
|
+
async captchaToken(explicit) {
|
|
1389
|
+
if (explicit) {
|
|
1390
|
+
validateCaptchaToken(explicit, "captcha");
|
|
1391
|
+
return explicit;
|
|
1392
|
+
}
|
|
996
1393
|
const configured = this.#takeConfiguredCaptcha();
|
|
997
|
-
if (configured) return
|
|
1394
|
+
if (configured) return configured;
|
|
998
1395
|
const solver = this.#config.captcha;
|
|
999
|
-
if (solver) return
|
|
1396
|
+
if (solver) return solveCaptchaToken(solver, () => this.#resolveCaptchaProvider(), { logger: this.#config.logger });
|
|
1000
1397
|
this.#config.logger?.debug("Запрос уходит без токена капчи: не передан аргумент captcha и не задана опция captcha");
|
|
1001
|
-
return {};
|
|
1002
1398
|
}
|
|
1003
1399
|
/** Отдаёт разовый токен из `auth.captcha`, помечая его потраченным. */
|
|
1004
1400
|
#takeConfiguredCaptcha() {
|
|
@@ -1011,10 +1407,22 @@ var AuthManager = class {
|
|
|
1011
1407
|
}
|
|
1012
1408
|
/** Спрашивает у сервера активного провайдера и поле, в котором он ждёт токен. */
|
|
1013
1409
|
async #resolveCaptchaProvider() {
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1410
|
+
try {
|
|
1411
|
+
return readCaptchaProvider(await this.#http.execute(AUTH_CAPTCHA_PROVIDER, {
|
|
1412
|
+
path: AUTH_PATHS.captchaProvider,
|
|
1413
|
+
skipAuth: true,
|
|
1414
|
+
skipAuthRefresh: true
|
|
1415
|
+
}));
|
|
1416
|
+
} catch (error) {
|
|
1417
|
+
if (isItdApiError(error) && error.status === 404 && error.code === ItdErrorCode.NOT_FOUND) {
|
|
1418
|
+
this.#config.logger?.warn("Сервер отключил определение провайдера капчи; используется Cloudflare Turnstile");
|
|
1419
|
+
return {
|
|
1420
|
+
provider: CaptchaType.Cloudflare,
|
|
1421
|
+
field: CaptchaField.Cloudflare
|
|
1422
|
+
};
|
|
1423
|
+
}
|
|
1424
|
+
throw error;
|
|
1425
|
+
}
|
|
1018
1426
|
}
|
|
1019
1427
|
async #performSignIn(credentials, revision) {
|
|
1020
1428
|
const captcha = await this.captchaBody();
|
|
@@ -1053,8 +1461,7 @@ var AuthManager = class {
|
|
|
1053
1461
|
return userId ? `: пользователь ${userId}` : "";
|
|
1054
1462
|
}
|
|
1055
1463
|
};
|
|
1056
|
-
|
|
1057
|
-
//#region src/session/qr-stream.ts
|
|
1464
|
+
// src/session/qr-stream.ts
|
|
1058
1465
|
const QR_STREAM_STATUSES = new Set(Object.values(QrLoginStreamStatus));
|
|
1059
1466
|
function readQrLoginStreamEvent(data) {
|
|
1060
1467
|
let value;
|
|
@@ -1170,8 +1577,214 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
|
|
|
1170
1577
|
abort.cleanup();
|
|
1171
1578
|
}
|
|
1172
1579
|
}
|
|
1173
|
-
|
|
1174
|
-
|
|
1580
|
+
// src/operations/auth/phone.ts
|
|
1581
|
+
/** Отклоняет неизвестный контракт до принятия результата входа. */
|
|
1582
|
+
function invalidResponse() {
|
|
1583
|
+
throw new ItdConfigError("Сервер вернул неподдерживаемый ответ телефонного входа");
|
|
1584
|
+
}
|
|
1585
|
+
/** Требует непустой секрет для продолжения телефонного потока. */
|
|
1586
|
+
function readFlowToken(body) {
|
|
1587
|
+
const value = pickString(body, "flowToken");
|
|
1588
|
+
if (!value) return invalidResponse();
|
|
1589
|
+
return value;
|
|
1590
|
+
}
|
|
1591
|
+
/** Разделяет access token и шаг пароля; режимы привязки/смены контакта не принимает. */
|
|
1592
|
+
function readLoginResult(body) {
|
|
1593
|
+
if (!isRecord(body)) return invalidResponse();
|
|
1594
|
+
if (body.mode !== void 0 && body.mode !== AuthVerificationMode.SignIn) return invalidResponse();
|
|
1595
|
+
const accessToken = pickString(body, "accessToken");
|
|
1596
|
+
if (accessToken) return { accessToken };
|
|
1597
|
+
if (body.step === PhoneLoginStep.Password) return {
|
|
1598
|
+
step: PhoneLoginStep.Password,
|
|
1599
|
+
flowToken: readFlowToken(body)
|
|
1600
|
+
};
|
|
1601
|
+
return invalidResponse();
|
|
1602
|
+
}
|
|
1603
|
+
/** Для завершения по паролю промежуточный шаг вместо access token недопустим. */
|
|
1604
|
+
function readAccessToken(body) {
|
|
1605
|
+
const result = readLoginResult(body);
|
|
1606
|
+
if (!("accessToken" in result)) return invalidResponse();
|
|
1607
|
+
return result.accessToken;
|
|
1608
|
+
}
|
|
1609
|
+
const AUTH_PHONE_CONFIG = passthroughOperation("auth.phone.config");
|
|
1610
|
+
const AUTH_PHONE_CONSENT = passthroughOperation("auth.phone.consent");
|
|
1611
|
+
const AUTH_PHONE_START = defineBuiltInOperation("auth.phone.start", readPhoneStart);
|
|
1612
|
+
const AUTH_PHONE_RESUME = defineBuiltInOperation("auth.phone.resume", (body) => ({
|
|
1613
|
+
...readPhoneDelivery(body),
|
|
1614
|
+
expiresIn: body.expiresIn
|
|
1615
|
+
}));
|
|
1616
|
+
const AUTH_PHONE_VERIFY = defineBuiltInOperation("auth.phone.verify", readLoginResult);
|
|
1617
|
+
const AUTH_PHONE_PASSWORD = defineBuiltInOperation("auth.phone.password", readAccessToken);
|
|
1618
|
+
const AUTH_PHONE_RESET_PASSWORD = defineBuiltInOperation("auth.phone.resetPassword", readAccessToken);
|
|
1619
|
+
const AUTH_PHONE_RESEND = defineBuiltInOperation("auth.phone.resend", readPhoneDelivery);
|
|
1620
|
+
const AUTH_PHONE_REVERSE_OPTIONS = passthroughOperation("auth.phone.reverseOptions");
|
|
1621
|
+
const AUTH_PHONE_REVERSE_START = passthroughOperation("auth.phone.reverseStart");
|
|
1622
|
+
const AUTH_PHONE_REVERSE_STATUS = passthroughOperation("auth.phone.reverseStatus");
|
|
1623
|
+
const AUTH_PHONE_REVERSE_COMPLETE = defineBuiltInOperation("auth.phone.reverseComplete", readLoginResult);
|
|
1624
|
+
// src/resources/auth/phone.ts
|
|
1625
|
+
/** Телефонный вход и регистрация. Доступен как `itd.auth.phone`. */
|
|
1626
|
+
var PhoneAuthResource = class extends BaseResource {
|
|
1627
|
+
#auth;
|
|
1628
|
+
constructor(http, deps) {
|
|
1629
|
+
super(http);
|
|
1630
|
+
this.#auth = deps.auth;
|
|
1631
|
+
}
|
|
1632
|
+
/** Разрешённые регионы, примеры номеров и доступные способы подтверждения. */
|
|
1633
|
+
config(options = {}) {
|
|
1634
|
+
return this.#request(AUTH_PHONE_CONFIG, "/phone/config", void 0, options);
|
|
1635
|
+
}
|
|
1636
|
+
/**
|
|
1637
|
+
* Загружает контекст phone_entry вместе с текстом и редакциями документов.
|
|
1638
|
+
*
|
|
1639
|
+
* До start() покажите документы пользователю. Истёкший контекст и новые редакции
|
|
1640
|
+
* библиотека не заменяет автоматически.
|
|
1641
|
+
*/
|
|
1642
|
+
consent(options = {}) {
|
|
1643
|
+
return this.#request(AUTH_PHONE_CONSENT, `/consent?flow=${PHONE_CONSENT_FLOW}`, void 0, options);
|
|
1644
|
+
}
|
|
1645
|
+
/**
|
|
1646
|
+
* Запрашивает подтверждение номера для входа или регистрации.
|
|
1647
|
+
*
|
|
1648
|
+
* Токен капчи отправляется объектом { provider, token }.
|
|
1649
|
+
*
|
|
1650
|
+
* @returns `flowToken` для продолжения входа, канал доставки, длина кода и пауза повтора в секундах
|
|
1651
|
+
*/
|
|
1652
|
+
async start(input, options = {}) {
|
|
1653
|
+
const captcha = await this.#auth.captchaToken(input.captcha);
|
|
1654
|
+
return this.#request(AUTH_PHONE_START, "/phone/start", {
|
|
1655
|
+
phone: input.phone,
|
|
1656
|
+
captcha: captcha ? {
|
|
1657
|
+
provider: captcha.type,
|
|
1658
|
+
token: captcha.token
|
|
1659
|
+
} : void 0,
|
|
1660
|
+
legal: {
|
|
1661
|
+
protocolVersion: input.consent.protocolVersion,
|
|
1662
|
+
contextToken: input.consent.contextToken
|
|
1663
|
+
}
|
|
1664
|
+
}, {
|
|
1665
|
+
...options,
|
|
1666
|
+
headers: {
|
|
1667
|
+
...options.headers,
|
|
1668
|
+
...input.method === PhoneVerificationMethod.Reverse ? { "X-ITD-Phone-Method": PhoneVerificationMethod.Reverse } : {}
|
|
1669
|
+
}
|
|
1670
|
+
});
|
|
1671
|
+
}
|
|
1672
|
+
/**
|
|
1673
|
+
* Возобновляет незавершённую проверку номера.
|
|
1674
|
+
*
|
|
1675
|
+
* Передайте номер и `flowToken` из {@link start}. Для следующих шагов используйте тот же
|
|
1676
|
+
* токен и параметры доставки из ответа.
|
|
1677
|
+
*/
|
|
1678
|
+
resume({ phone, flowToken }, options = {}) {
|
|
1679
|
+
return this.http.execute(AUTH_PHONE_RESUME, {
|
|
1680
|
+
...options,
|
|
1681
|
+
path: "/api/v1/auth/phone/resume",
|
|
1682
|
+
body: {
|
|
1683
|
+
phone,
|
|
1684
|
+
flowToken
|
|
1685
|
+
},
|
|
1686
|
+
redirect: "error",
|
|
1687
|
+
skipAuth: true,
|
|
1688
|
+
skipAuthRefresh: true,
|
|
1689
|
+
headers: {
|
|
1690
|
+
...options.headers,
|
|
1691
|
+
"X-ITD-Phone-Resume": "1"
|
|
1692
|
+
}
|
|
1693
|
+
});
|
|
1694
|
+
}
|
|
1695
|
+
/**
|
|
1696
|
+
* Подтверждает код без email и пароля.
|
|
1697
|
+
*
|
|
1698
|
+
* При accessToken сохраняет новую сессию; при step: 'password' возвращает секрет
|
|
1699
|
+
* для password().
|
|
1700
|
+
*/
|
|
1701
|
+
verify(input, options = {}) {
|
|
1702
|
+
return this.#complete(AUTH_PHONE_VERIFY, "/verify-otp", input, options);
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* Запрашивает повторную доставку без изменения авторизации.
|
|
1706
|
+
*
|
|
1707
|
+
* Используйте новый channel/codeLength из результата: способ доставки может измениться.
|
|
1708
|
+
* retryIn — секунды до следующего запроса.
|
|
1709
|
+
*/
|
|
1710
|
+
resend(input, options = {}) {
|
|
1711
|
+
return this.#request(AUTH_PHONE_RESEND, "/resend-otp", input, options);
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Завершает вход облачным паролем после step: 'password'.
|
|
1715
|
+
*
|
|
1716
|
+
* Передайте flowToken из этого шага. Полученный access token и cookies сохраняются
|
|
1717
|
+
* автоматически, если владелец сессии не сменился во время запроса.
|
|
1718
|
+
*/
|
|
1719
|
+
password(input, options = {}) {
|
|
1720
|
+
return this.#authenticate(AUTH_PHONE_PASSWORD, "/phone/password", input, options);
|
|
1721
|
+
}
|
|
1722
|
+
/** Устанавливает новый пароль после подтверждения номера и сохраняет сессию. */
|
|
1723
|
+
resetPassword(input, options = {}) {
|
|
1724
|
+
return this.#authenticate(AUTH_PHONE_RESET_PASSWORD, "/phone/reset-password", input, options);
|
|
1725
|
+
}
|
|
1726
|
+
/** Проверяет, доступен ли исходящий звонок для подтверждения номера. */
|
|
1727
|
+
reverseOptions(input, options = {}) {
|
|
1728
|
+
return this.#request(AUTH_PHONE_REVERSE_OPTIONS, "/phone/reverse/options", input, options);
|
|
1729
|
+
}
|
|
1730
|
+
/**
|
|
1731
|
+
* Подготавливает номер, на который пользователь должен позвонить.
|
|
1732
|
+
*
|
|
1733
|
+
* Может выделить новую попытку; не повторяется после сетевых ошибок и 5xx. Номер и срок
|
|
1734
|
+
* его действия возвращаются в phone и expiresIn.
|
|
1735
|
+
*/
|
|
1736
|
+
reverseStart(input, options = {}) {
|
|
1737
|
+
return this.#request(AUTH_PHONE_REVERSE_START, "/phone/reverse/start", input, options);
|
|
1738
|
+
}
|
|
1739
|
+
/** Читает состояние звонка через POST, без завершения входа и смены сессии. */
|
|
1740
|
+
reverseStatus(input, options = {}) {
|
|
1741
|
+
return this.#request(AUTH_PHONE_REVERSE_STATUS, "/phone/reverse/status", input, options);
|
|
1742
|
+
}
|
|
1743
|
+
/** Завершает подтверждённый звонок; сервер может потребовать облачный пароль. */
|
|
1744
|
+
reverseComplete(input, options = {}) {
|
|
1745
|
+
return this.#complete(AUTH_PHONE_REVERSE_COMPLETE, "/phone/reverse/complete", input, options);
|
|
1746
|
+
}
|
|
1747
|
+
/** Применяет cookies промежуточного шага либо атомарно сохраняет завершённый вход. */
|
|
1748
|
+
async #complete(operation, path, input, options) {
|
|
1749
|
+
const revision = this.#auth.revision();
|
|
1750
|
+
const cookies = this.#auth.createCookieFlow();
|
|
1751
|
+
const result = await this.#request(operation, path, input, options, cookies);
|
|
1752
|
+
if ("accessToken" in result) await this.#auth.commitAuthFlow(result.accessToken, cookies, revision);
|
|
1753
|
+
else this.#auth.commitCookieFlow(cookies, revision);
|
|
1754
|
+
return result;
|
|
1755
|
+
}
|
|
1756
|
+
/** Сохраняет результат пароля, не позволяя запоздалому ответу сменить нового владельца. */
|
|
1757
|
+
async #authenticate(operation, path, input, options) {
|
|
1758
|
+
const revision = this.#auth.revision();
|
|
1759
|
+
const cookies = this.#auth.createCookieFlow();
|
|
1760
|
+
const token = await this.#request(operation, path, input, options, cookies);
|
|
1761
|
+
await this.#auth.commitAuthFlow(token, cookies, revision);
|
|
1762
|
+
return token;
|
|
1763
|
+
}
|
|
1764
|
+
/**
|
|
1765
|
+
* Выполняет телефонный запрос без Bearer/refresh через общий pipeline.
|
|
1766
|
+
* X-ITD-Phone-Reverse объявляет поддержку исходящего звонка, в том числе при запросе кода.
|
|
1767
|
+
*/
|
|
1768
|
+
#request(operation, path, body, options, cookies) {
|
|
1769
|
+
return this.http.execute(operation, {
|
|
1770
|
+
...options,
|
|
1771
|
+
path: `/api/v1/auth${path}`,
|
|
1772
|
+
body,
|
|
1773
|
+
...cookies ? { cookieJar: cookies } : {},
|
|
1774
|
+
skipAuth: true,
|
|
1775
|
+
skipAuthRefresh: true,
|
|
1776
|
+
headers: {
|
|
1777
|
+
...options.headers,
|
|
1778
|
+
...operation.method === "POST" ? {
|
|
1779
|
+
"X-ITD-Phone-Reverse": "1",
|
|
1780
|
+
"X-ITD-Flow-Expiry": "1"
|
|
1781
|
+
} : {},
|
|
1782
|
+
...path.startsWith("/phone/reverse/") ? { "X-ITD-Reverse-Attempts": "1" } : {}
|
|
1783
|
+
}
|
|
1784
|
+
});
|
|
1785
|
+
}
|
|
1786
|
+
};
|
|
1787
|
+
// src/resources/auth.ts
|
|
1175
1788
|
/**
|
|
1176
1789
|
* Результат входа.
|
|
1177
1790
|
*
|
|
@@ -1184,6 +1797,8 @@ async function openQrLoginStream(connection, cookies, input, onEvent, signal) {
|
|
|
1184
1797
|
* Доступна как `itd.auth`.
|
|
1185
1798
|
*/
|
|
1186
1799
|
var AuthResource = class extends BaseResource {
|
|
1800
|
+
/** Вход и регистрация по номеру телефона. */
|
|
1801
|
+
phone;
|
|
1187
1802
|
#auth;
|
|
1188
1803
|
#connection;
|
|
1189
1804
|
#qrFlows = /* @__PURE__ */ new Map();
|
|
@@ -1191,6 +1806,7 @@ var AuthResource = class extends BaseResource {
|
|
|
1191
1806
|
super(http);
|
|
1192
1807
|
this.#auth = deps.auth;
|
|
1193
1808
|
this.#connection = deps.connection;
|
|
1809
|
+
this.phone = new PhoneAuthResource(http, deps);
|
|
1194
1810
|
}
|
|
1195
1811
|
#pruneQrFlows() {
|
|
1196
1812
|
const now = this.#connection.clock.now();
|
|
@@ -1232,13 +1848,13 @@ var AuthResource = class extends BaseResource {
|
|
|
1232
1848
|
*
|
|
1233
1849
|
* Сервер может переключить провайдера или переименовать поле без выпуска новой версии SDK.
|
|
1234
1850
|
* Автоматическому входу этот вызов не нужен — клиент делает его сам.
|
|
1235
|
-
*
|
|
1236
|
-
* @deprecated Сервер отвечает `404`; метод возвращает Cloudflare Turnstile.
|
|
1237
1851
|
*/
|
|
1238
|
-
captchaProvider(
|
|
1239
|
-
return
|
|
1240
|
-
|
|
1241
|
-
|
|
1852
|
+
captchaProvider(options = {}) {
|
|
1853
|
+
return this.http.execute(AUTH_CAPTCHA_PROVIDER, {
|
|
1854
|
+
path: AUTH_PATHS.captchaProvider,
|
|
1855
|
+
skipAuth: true,
|
|
1856
|
+
skipAuthRefresh: true,
|
|
1857
|
+
...options
|
|
1242
1858
|
});
|
|
1243
1859
|
}
|
|
1244
1860
|
/**
|
|
@@ -1247,14 +1863,14 @@ var AuthResource = class extends BaseResource {
|
|
|
1247
1863
|
* То же, что {@link captchaProvider}, плюс `url` — готовая страница на домене итд.com,
|
|
1248
1864
|
* где ключ виджета действителен. Пригодится встроенному браузеру: открыть её и забрать
|
|
1249
1865
|
* токен, ничего не собирая самому.
|
|
1250
|
-
*
|
|
1251
|
-
* @deprecated Сервер отвечает `404`; метод возвращает Cloudflare Turnstile на домене итд.com.
|
|
1252
1866
|
*/
|
|
1253
|
-
|
|
1254
|
-
return {
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1867
|
+
captchaPage(options = {}) {
|
|
1868
|
+
return this.http.execute(AUTH_CAPTCHA_PAGE, {
|
|
1869
|
+
path: AUTH_PATHS.captchaPage,
|
|
1870
|
+
skipAuth: true,
|
|
1871
|
+
skipAuthRefresh: true,
|
|
1872
|
+
...options
|
|
1873
|
+
});
|
|
1258
1874
|
}
|
|
1259
1875
|
/** Создаёт короткоживущую сессию QR-входа. */
|
|
1260
1876
|
async startQrLogin(options = {}) {
|
|
@@ -1382,6 +1998,7 @@ var AuthResource = class extends BaseResource {
|
|
|
1382
1998
|
* Регистрирует аккаунт и запускает подтверждение по коду.
|
|
1383
1999
|
*
|
|
1384
2000
|
* @returns `flowToken`, который нужно передать в {@link verifyOtp}
|
|
2001
|
+
* @deprecated Регистрация по email отключена. Используйте auth.phone.start().
|
|
1385
2002
|
*/
|
|
1386
2003
|
async signUp(credentials, options = {}) {
|
|
1387
2004
|
const { captcha, ...rest } = credentials;
|
|
@@ -1598,26 +2215,6 @@ var AuthResource = class extends BaseResource {
|
|
|
1598
2215
|
newPassword
|
|
1599
2216
|
}, options);
|
|
1600
2217
|
}
|
|
1601
|
-
/**
|
|
1602
|
-
* Меняет пароль. Требует действующей сессии.
|
|
1603
|
-
*
|
|
1604
|
-
* При неверном текущем пароле сервер отвечает `ACCOUNT_CURRENT_PASSWORD_INCORRECT`.
|
|
1605
|
-
*
|
|
1606
|
-
* @example
|
|
1607
|
-
* ```ts
|
|
1608
|
-
* await itd.auth.changePassword({ currentPassword, newPassword });
|
|
1609
|
-
* ```
|
|
1610
|
-
*/
|
|
1611
|
-
changePassword(input, options = {}) {
|
|
1612
|
-
return this.voidOperation(AUTH_CHANGE_PASSWORD, {
|
|
1613
|
-
path: AUTH_PATHS.changePassword,
|
|
1614
|
-
body: {
|
|
1615
|
-
currentPassword: input.currentPassword,
|
|
1616
|
-
newPassword: input.newPassword
|
|
1617
|
-
},
|
|
1618
|
-
...options
|
|
1619
|
-
});
|
|
1620
|
-
}
|
|
1621
2218
|
/** Загружает список активных сессий. У текущей поле `isCurrent` равно `true`. */
|
|
1622
2219
|
sessions(options = {}) {
|
|
1623
2220
|
return this.http.execute(AUTH_SESSIONS, {
|
|
@@ -1640,8 +2237,7 @@ var AuthResource = class extends BaseResource {
|
|
|
1640
2237
|
});
|
|
1641
2238
|
}
|
|
1642
2239
|
};
|
|
1643
|
-
|
|
1644
|
-
//#region src/client.ts
|
|
2240
|
+
// src/client.ts
|
|
1645
2241
|
const CLIENT_PLUGIN_REGISTRIES = /* @__PURE__ */ new WeakMap();
|
|
1646
2242
|
const DISPOSED_CLIENTS = /* @__PURE__ */ new WeakSet();
|
|
1647
2243
|
function assertClientActive(client, action) {
|
|
@@ -1705,6 +2301,7 @@ var ItdClient = class ItdClient {
|
|
|
1705
2301
|
#resources;
|
|
1706
2302
|
/** Сессионный ресурс живёт у фасада: он управляет входом и продлением. */
|
|
1707
2303
|
#auth;
|
|
2304
|
+
#account;
|
|
1708
2305
|
/** Авторизация, сессии и пароли. */
|
|
1709
2306
|
get auth() {
|
|
1710
2307
|
this.#auth ??= new AuthResource(this.#runtime.http, {
|
|
@@ -1713,6 +2310,11 @@ var ItdClient = class ItdClient {
|
|
|
1713
2310
|
});
|
|
1714
2311
|
return this.#auth;
|
|
1715
2312
|
}
|
|
2313
|
+
/** Настройки текущего аккаунта и управление его состоянием. */
|
|
2314
|
+
get account() {
|
|
2315
|
+
this.#account ??= new AccountResource(this.#runtime.http, this.#runtime.auth);
|
|
2316
|
+
return this.#account;
|
|
2317
|
+
}
|
|
1716
2318
|
/** Профили, подписки, блокировки, приватность. */
|
|
1717
2319
|
get users() {
|
|
1718
2320
|
return this.#resources.users;
|
|
@@ -1753,6 +2355,10 @@ var ItdClient = class ItdClient {
|
|
|
1753
2355
|
get subscription() {
|
|
1754
2356
|
return this.#resources.subscription;
|
|
1755
2357
|
}
|
|
2358
|
+
/** Публичные документы ИТД и история их редакций. */
|
|
2359
|
+
get legal() {
|
|
2360
|
+
return this.#resources.legal;
|
|
2361
|
+
}
|
|
1756
2362
|
/** Сведения о платформе: версии приложений, изменения, анонсы, баннер события. */
|
|
1757
2363
|
get platform() {
|
|
1758
2364
|
return this.#resources.platform;
|
|
@@ -2156,8 +2762,7 @@ var ItdClient = class ItdClient {
|
|
|
2156
2762
|
function createClient(options = {}) {
|
|
2157
2763
|
return new ItdClient(options);
|
|
2158
2764
|
}
|
|
2159
|
-
|
|
2160
|
-
//#region src/accounts.ts
|
|
2765
|
+
// src/accounts.ts
|
|
2161
2766
|
/** Как аккаунты делят между собой очередь запросов. */
|
|
2162
2767
|
const RateLimitScope = Object.freeze({
|
|
2163
2768
|
/** У каждого аккаунта своя очередь. */
|
|
@@ -2626,7 +3231,18 @@ var ItdAccounts = class ItdAccounts {
|
|
|
2626
3231
|
function createAccounts(options = {}) {
|
|
2627
3232
|
return new ItdAccounts(options);
|
|
2628
3233
|
}
|
|
2629
|
-
|
|
2630
|
-
|
|
3234
|
+
// src/models/account-access.ts
|
|
3235
|
+
/** Способ подтверждения смены номера или почты. */
|
|
3236
|
+
const ContactProofMethod = Object.freeze({
|
|
3237
|
+
Password: "password",
|
|
3238
|
+
EmailCode: "email_code",
|
|
3239
|
+
PhoneCode: "phone_code"
|
|
3240
|
+
});
|
|
3241
|
+
/** Что меняет отложенная заявка: номер или почту. */
|
|
3242
|
+
const ContactKind = Object.freeze({
|
|
3243
|
+
Email: "email",
|
|
3244
|
+
Phone: "phone"
|
|
3245
|
+
});
|
|
3246
|
+
export { ALLOWED_MIME_TYPES, AUDIO_MIME_TYPES, AccessType, AttachmentType, BUCKET_LIMITS, BannerDrawingTool, CAPTCHA_FIELDS, CaptchaChoice, CaptchaField, CaptchaType, CommentSort, ContactKind, ContactProofMethod, DEFAULT_BASE_URL, DEFAULT_RATE_LIMIT_BUCKET, EventChannel, EventChannelStatus, EventComposer, EventRouter, FeedTab, FileTransferMode, IMAGE_MIME_TYPES, IncidentKind, InteractionType, ItdAbortError, ItdAccounts, ItdApiError, ItdApiErrorKind, ItdAuthError, ItdClient, ItdConfigError, ItdConflictError, ItdError, ItdErrorCode, ItdErrorKind, ItdFileError, ItdFileErrorReason, ItdForbiddenError, ItdNetworkError, ItdNotFoundError, ItdPhoneVerificationError, ItdRateLimitError, ItdServerError, ItdStateError, ItdTimeoutError, ItdValidationError, LIBRARY_VERSION, LastSeenUnit, LegalDocumentBlockType, LegalDocumentScope, LikesVisibility, LogLevel, MemoryKeyValueStore, MemoryMultiTokenStorage, MemoryShopOrderAccessStorage, MemoryTokenStorage, MessageAccess, NotificationEvents, NotificationEventsClient, NotificationEventsTransport, NotificationType, NotificationUpdateOrigin, NotificationUpdateType, OPERATIONS, OperationMethod, PaginationMode, Paginator, PhoneDeliveryChannel, PhoneLoginStep, PhoneReverseState, PhoneVerificationMethod, QrLocationPrecision, QrLoginStatus, QrLoginStreamStatus, RateLimitPacing, RateLimitScope, ReportReason, ReportTargetType, RetrySafety, RuntimeMode, STATUS_SERVICE, ServiceState, ShopConsentKind, ShopOrderStatus, ShopProductCategory, ShopProductStatus, SignInStatus, SpanRenderFormat, SpanType, TURNSTILE_SITE_KEY, TimeoutBudget, UnauthorizedStreamError, UsernameUnavailableReason, VIDEO_MIME_TYPES, ViewReason, ViewSource, WallAccess, WebSocketTransport, autoSpans, canonicalNotificationType, comment, createAccounts, createClient, createKeyValueStore, createMultiTokenStorage, createNotificationEventsClient, createRecordKeyValueStore, createShopFeature, createShopOrderAccessStorage, createTokenStorage, formatNotificationText, fromStream, fromUrl, isBuilder, isBuiltInOperationId, isEnumerableKeyValueStore, isItdApiError, isItdAuthError, isItdConflictError, isItdError, isItdFileError, isItdForbiddenError, isItdNotFoundError, isItdPhoneVerificationError, isItdRateLimitError, isItdServerError, isItdStateError, isItdValidationError, isKnownNotificationType, isMyProfile, mapPage, markup, normalizeNotification, operationBucket, operationMethod, operationRetrySafety, parseHtml, parseMarkdown, poll, post, renderSpans, report, resolveNotificationUrl, runEventMiddleware, scopedTokenStorage, statusDays, systemClock, toDate, utcStampToIso, withCodec, withNamespace };
|
|
2631
3247
|
|
|
2632
3248
|
//# sourceMappingURL=index.js.map
|