yclients-api 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ First version.
6
+
7
+ - `YclientsClient` with typed methods for companies, staff, services, records, clients, finance transactions, schedules, goods, storages, analytics, user auth (`POST /auth`) and Marketplace activation.
8
+ - Default base URL `https://api.yclients.ru/api/v1`; configurable for the legacy `.com` host.
9
+ - Retries with exponential backoff and jitter on 429 (all methods) and on 502/503/504 and network errors (idempotent methods), honoring `Retry-After`.
10
+ - `listAll()` / `iterate()` pagination that throws `YclientsPaginationError` instead of returning a truncated list.
11
+ - Error classes: `YclientsError`, `YclientsApiError`, `YclientsRateLimitError`, `YclientsNetworkError`, `YclientsPaginationError`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 davronovkhayom
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,214 @@
1
- # Temporary Holding Version
1
+ # yclients-api
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [Русская версия](./README.ru.md)
4
+
5
+ A typed, zero-dependency TypeScript client for the [YCLIENTS](https://yclients.ru) REST API.
6
+
7
+ - **Typed** methods for companies, staff, services, records (bookings), clients, finance transactions, schedules, goods, storages, analytics, user auth and Marketplace activation.
8
+ - **Defaults to `https://api.yclients.ru/api/v1`**, the API's new home after YCLIENTS moved from `yclients.com` to `yclients.ru`. The base URL is configurable.
9
+ - **Rate-limit aware**: retries HTTP 429 with exponential backoff and jitter, and honors `Retry-After`.
10
+ - **Safe pagination**: `listAll()` / `iterate()` read until the list provably ends and throw instead of silently returning a truncated list.
11
+ - **Zero runtime dependencies**: uses the global `fetch` (Node.js 20+, Deno, Bun, edge runtimes).
12
+ - **Clear errors**: `YclientsApiError`, `YclientsRateLimitError`, `YclientsNetworkError` and `YclientsPaginationError`. Query values such as phone numbers are kept out of error messages.
13
+
14
+ > This is an unofficial, community-maintained library and is not affiliated with YCLIENTS.
15
+ > Endpoint coverage comes from a production integration and the public API documentation;
16
+ > the test suite uses a mocked `fetch` and never calls the live API.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install yclients-api
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```ts
27
+ import { YclientsClient } from 'yclients-api';
28
+
29
+ const yc = new YclientsClient({
30
+ partnerToken: process.env.YCLIENTS_PARTNER_TOKEN!,
31
+ userToken: process.env.YCLIENTS_USER_TOKEN, // optional, needed for most company data
32
+ });
33
+
34
+ const companyId = 123456;
35
+
36
+ const staff = await yc.staff.list(companyId);
37
+ const services = await yc.services.list(companyId);
38
+
39
+ // Every record in January, across as many pages as needed
40
+ const records = await yc.records.listAll(companyId, {
41
+ start_date: '2026-01-01',
42
+ end_date: '2026-01-31',
43
+ });
44
+ ```
45
+
46
+ Keep tokens on the server. The partner token identifies your application and must never be shipped to a browser.
47
+
48
+ ## Authentication
49
+
50
+ YCLIENTS uses two tokens:
51
+
52
+ | Token | Who issues it | Header |
53
+ | --- | --- | --- |
54
+ | Partner token | YCLIENTS, to your developer account | `Authorization: Bearer <partner>` |
55
+ | User token | `POST /auth`, for a specific YCLIENTS user | `Authorization: Bearer <partner>, User <user>` |
56
+
57
+ The client builds the header for you. To obtain a user token:
58
+
59
+ ```ts
60
+ const yc = new YclientsClient({ partnerToken });
61
+ const { user_token } = await yc.auth.getUserToken({ login, password });
62
+
63
+ const asUser = yc.withUserToken(user_token); // same settings, different user
64
+ ```
65
+
66
+ Store the token, not the password.
67
+
68
+ ## API
69
+
70
+ All IDs accept numbers or numeric strings and are validated before a request is sent.
71
+ All methods accept an optional last argument `{ signal }` for cancellation.
72
+
73
+ | Method | Endpoint |
74
+ | --- | --- |
75
+ | `companies.list(params?)` | `GET /companies` (`{ my: 1 }` for companies the user can access) |
76
+ | `companies.get(companyId)` | `GET /company/{id}` |
77
+ | `staff.list(companyId)` | `GET /company/{id}/staff` |
78
+ | `staff.get(companyId, staffId)` | `GET /company/{id}/staff/{staff_id}` |
79
+ | `services.list(companyId, params?)` | `GET /services/{id}` |
80
+ | `records.list(companyId, params?)` | `GET /records/{id}`, one page |
81
+ | `records.listAll / iterate(companyId, params?, options?)` | every page |
82
+ | `records.get(companyId, recordId)` | `GET /record/{id}/{record_id}` |
83
+ | `clients.list(companyId, params?)` | `GET /clients/{id}`, one page |
84
+ | `clients.listAll / iterate(...)` | every page |
85
+ | `clients.get(companyId, clientId)` | `GET /client/{id}/{client_id}` |
86
+ | `transactions.list / listAll / iterate(...)` | `GET /transactions/{id}` |
87
+ | `schedule.get(companyId, staffId, from, to)` | `GET /schedule/{id}/{staff_id}/{from}/{to}` |
88
+ | `goods.list / listAll / iterate(...)` | `GET /goods/{id}` |
89
+ | `storages.list(companyId)` | `GET /storages/{id}` |
90
+ | `analytics.overall(companyId, { date_from, date_to })` | `GET /company/{id}/analytics/overall` |
91
+ | `auth.getUserToken({ login, password })` | `POST /auth` |
92
+ | `marketplace.activate({ salonId, applicationId })` | `POST /marketplace/partner/callback` |
93
+ | `request({ method, path, query, body })` | any other endpoint, returns the full envelope |
94
+
95
+ Dates are `YYYY-MM-DD` strings; `schedule.get` and `analytics.overall` also accept `Date` objects.
96
+ Entity types (`YclientsRecord`, `Client`, `Staff`, ...) list the common fields and keep an index signature, so fields YCLIENTS adds later remain reachable.
97
+
98
+ ### Anything not covered yet
99
+
100
+ ```ts
101
+ const envelope = await yc.request<{ id: number }>({
102
+ method: 'PUT',
103
+ path: `record/${companyId}/${recordId}`,
104
+ body: { comment: 'Moved by phone' },
105
+ });
106
+ console.log(envelope.success, envelope.data, envelope.meta);
107
+ ```
108
+
109
+ ## Pagination
110
+
111
+ `list()` returns one page: `{ data, meta, page, count }`.
112
+
113
+ `listAll()` and `iterate()` walk the pages and stop when:
114
+
115
+ - a page comes back empty, or
116
+ - a page is shorter than `count`, or
117
+ - the number of items read reaches `meta.total_count`.
118
+
119
+ They throw `YclientsPaginationError` if `maxPages` (default 1000) is reached first, or if the server returns the same page twice in a row. A partial list is never returned as if it were complete.
120
+
121
+ ```ts
122
+ for await (const client of yc.clients.iterate(companyId, { count: 200 })) {
123
+ await save(client); // streams page by page, constant memory
124
+ }
125
+
126
+ const recent = await yc.clients.listAll(
127
+ companyId,
128
+ { changed_after: '2026-01-01' },
129
+ { maxPages: 50 },
130
+ );
131
+ ```
132
+
133
+ ## Retries and rate limits
134
+
135
+ | Situation | GET / PUT / DELETE | POST / PATCH |
136
+ | --- | --- | --- |
137
+ | HTTP 429 | retried | retried (the request was not processed) |
138
+ | HTTP 502, 503, 504 | retried | not retried (it may have been applied) |
139
+ | Network error or timeout | retried | not retried |
140
+ | Other 4xx / 5xx | thrown | thrown |
141
+
142
+ The wait is `min(maxDelayMs, max(Retry-After, jittered exponential backoff))`.
143
+
144
+ ```ts
145
+ const yc = new YclientsClient({
146
+ partnerToken,
147
+ userToken,
148
+ timeoutMs: 20_000, // per attempt, default 30 000
149
+ retry: {
150
+ retries: 4, // default 4; 0 disables retries
151
+ minDelayMs: 1000, // default 1000
152
+ maxDelayMs: 30_000, // default 30 000
153
+ retryStatuses: [429, 502, 503, 504],
154
+ retryNetworkErrors: true,
155
+ },
156
+ onRetry: ({ attempt, delayMs, status, path }) => {
157
+ console.warn(`YCLIENTS ${path} → ${status ?? 'network error'}, retry #${attempt} in ${delayMs} ms`);
158
+ },
159
+ });
160
+ ```
161
+
162
+ When retries are spent, a `YclientsRateLimitError` carries `retryAfterMs` so you can reschedule the job.
163
+
164
+ ## Errors
165
+
166
+ ```ts
167
+ import {
168
+ YclientsApiError,
169
+ YclientsRateLimitError,
170
+ YclientsNetworkError,
171
+ YclientsPaginationError,
172
+ } from 'yclients-api';
173
+
174
+ try {
175
+ await yc.records.get(companyId, recordId);
176
+ } catch (error) {
177
+ if (error instanceof YclientsRateLimitError) {
178
+ // still 429 after all retries; error.retryAfterMs
179
+ } else if (error instanceof YclientsApiError) {
180
+ // non-2xx or { success: false }; error.status, error.apiMessage, error.body
181
+ } else if (error instanceof YclientsNetworkError) {
182
+ // no response; error.timedOut tells a timeout from a connection failure
183
+ } else if (error instanceof YclientsPaginationError) {
184
+ // list could not be read completely
185
+ }
186
+ }
187
+ ```
188
+
189
+ All of them extend `YclientsError`.
190
+
191
+ ## Migrating from `api.yclients.com`
192
+
193
+ The client talks to `https://api.yclients.ru/api/v1` by default. To keep the old host while you migrate:
194
+
195
+ ```ts
196
+ new YclientsClient({ partnerToken, baseUrl: 'https://api.yclients.com/api/v1' });
197
+ ```
198
+
199
+ `marketplace.activate()` uses the origin of `baseUrl`, so it follows the same switch.
200
+
201
+ ## Development
202
+
203
+ ```bash
204
+ npm install
205
+ npm test # vitest, mocked fetch only
206
+ npm run typecheck
207
+ npm run build # emits dist/ (ESM + .d.ts)
208
+ ```
209
+
210
+ Contributions are welcome: endpoint coverage, better types for responses you have seen in the wild, and bug reports with redacted payloads. Never paste real tokens, phone numbers or client data into issues.
211
+
212
+ ## License
213
+
214
+ [MIT](./LICENSE)
package/README.ru.md ADDED
@@ -0,0 +1,214 @@
1
+ # yclients-api
2
+
3
+ [English version](./README.md)
4
+
5
+ Типизированный клиент REST API [YCLIENTS](https://yclients.ru) на TypeScript без runtime-зависимостей.
6
+
7
+ - **Типизированные методы**: филиалы, сотрудники, услуги, записи, клиенты, финансовые транзакции, графики работы, товары, склады, аналитика, авторизация пользователя и активация приложения в Маркетплейсе.
8
+ - **По умолчанию `https://api.yclients.ru/api/v1`**: YCLIENTS переехал с `yclients.com` на `yclients.ru`. Базовый адрес можно поменять.
9
+ - **Учитывает лимиты запросов**: повторяет HTTP 429 с экспоненциальной задержкой и джиттером, соблюдает `Retry-After`.
10
+ - **Безопасная пагинация**: `listAll()` / `iterate()` читают страницы, пока список точно не закончится, и бросают ошибку вместо того, чтобы молча вернуть обрезанный список.
11
+ - **Без зависимостей**: используется глобальный `fetch` (Node.js 20+, Deno, Bun, edge-среды).
12
+ - **Понятные ошибки**: `YclientsApiError`, `YclientsRateLimitError`, `YclientsNetworkError`, `YclientsPaginationError`. Значения параметров запроса (например, телефоны) не попадают в текст ошибок.
13
+
14
+ > Это неофициальная библиотека, которую поддерживает сообщество; она не связана с компанией YCLIENTS.
15
+ > Набор методов взят из работающей интеграции и публичной документации API.
16
+ > Тесты используют подменённый `fetch` и никогда не обращаются к настоящему API.
17
+
18
+ ## Установка
19
+
20
+ ```bash
21
+ npm install yclients-api
22
+ ```
23
+
24
+ ## Быстрый старт
25
+
26
+ ```ts
27
+ import { YclientsClient } from 'yclients-api';
28
+
29
+ const yc = new YclientsClient({
30
+ partnerToken: process.env.YCLIENTS_PARTNER_TOKEN!,
31
+ userToken: process.env.YCLIENTS_USER_TOKEN, // необязателен, но нужен для большинства данных филиала
32
+ });
33
+
34
+ const companyId = 123456;
35
+
36
+ const staff = await yc.staff.list(companyId);
37
+ const services = await yc.services.list(companyId);
38
+
39
+ // Все записи за январь, сколько бы страниц ни понадобилось
40
+ const records = await yc.records.listAll(companyId, {
41
+ start_date: '2026-01-01',
42
+ end_date: '2026-01-31',
43
+ });
44
+ ```
45
+
46
+ Храните токены только на сервере. Партнёрский токен идентифицирует ваше приложение, его нельзя отдавать в браузер.
47
+
48
+ ## Авторизация
49
+
50
+ В YCLIENTS два токена:
51
+
52
+ | Токен | Кто выдаёт | Заголовок |
53
+ | --- | --- | --- |
54
+ | Партнёрский | YCLIENTS, на аккаунт разработчика | `Authorization: Bearer <partner>` |
55
+ | Пользовательский | `POST /auth`, для конкретного пользователя YCLIENTS | `Authorization: Bearer <partner>, User <user>` |
56
+
57
+ Клиент сам собирает заголовок. Получить пользовательский токен:
58
+
59
+ ```ts
60
+ const yc = new YclientsClient({ partnerToken });
61
+ const { user_token } = await yc.auth.getUserToken({ login, password });
62
+
63
+ const asUser = yc.withUserToken(user_token); // те же настройки, другой пользователь
64
+ ```
65
+
66
+ Сохраняйте токен, а не пароль.
67
+
68
+ ## Методы
69
+
70
+ ID принимаются числом или строкой из цифр и проверяются до отправки запроса.
71
+ Последний необязательный аргумент каждого метода — `{ signal }` для отмены.
72
+
73
+ | Метод | Эндпоинт |
74
+ | --- | --- |
75
+ | `companies.list(params?)` | `GET /companies` (`{ my: 1 }` — филиалы, доступные пользователю) |
76
+ | `companies.get(companyId)` | `GET /company/{id}` |
77
+ | `staff.list(companyId)` | `GET /company/{id}/staff` |
78
+ | `staff.get(companyId, staffId)` | `GET /company/{id}/staff/{staff_id}` |
79
+ | `services.list(companyId, params?)` | `GET /services/{id}` |
80
+ | `records.list(companyId, params?)` | `GET /records/{id}`, одна страница |
81
+ | `records.listAll / iterate(companyId, params?, options?)` | все страницы |
82
+ | `records.get(companyId, recordId)` | `GET /record/{id}/{record_id}` |
83
+ | `clients.list(companyId, params?)` | `GET /clients/{id}`, одна страница |
84
+ | `clients.listAll / iterate(...)` | все страницы |
85
+ | `clients.get(companyId, clientId)` | `GET /client/{id}/{client_id}` |
86
+ | `transactions.list / listAll / iterate(...)` | `GET /transactions/{id}` |
87
+ | `schedule.get(companyId, staffId, from, to)` | `GET /schedule/{id}/{staff_id}/{from}/{to}` |
88
+ | `goods.list / listAll / iterate(...)` | `GET /goods/{id}` |
89
+ | `storages.list(companyId)` | `GET /storages/{id}` |
90
+ | `analytics.overall(companyId, { date_from, date_to })` | `GET /company/{id}/analytics/overall` |
91
+ | `auth.getUserToken({ login, password })` | `POST /auth` |
92
+ | `marketplace.activate({ salonId, applicationId })` | `POST /marketplace/partner/callback` |
93
+ | `request({ method, path, query, body })` | любой другой эндпоинт, возвращает весь ответ |
94
+
95
+ Даты передаются строкой `YYYY-MM-DD`; `schedule.get` и `analytics.overall` принимают и `Date`.
96
+ Типы сущностей (`YclientsRecord`, `Client`, `Staff`, ...) описывают основные поля и оставляют индексную сигнатуру, поэтому новые поля YCLIENTS тоже доступны.
97
+
98
+ ### Если нужного метода нет
99
+
100
+ ```ts
101
+ const envelope = await yc.request<{ id: number }>({
102
+ method: 'PUT',
103
+ path: `record/${companyId}/${recordId}`,
104
+ body: { comment: 'Перенесли по телефону' },
105
+ });
106
+ console.log(envelope.success, envelope.data, envelope.meta);
107
+ ```
108
+
109
+ ## Пагинация
110
+
111
+ `list()` возвращает одну страницу: `{ data, meta, page, count }`.
112
+
113
+ `listAll()` и `iterate()` проходят страницы и останавливаются, когда:
114
+
115
+ - пришла пустая страница, или
116
+ - страница короче `count`, или
117
+ - прочитано столько элементов, сколько указано в `meta.total_count`.
118
+
119
+ Если раньше достигнут `maxPages` (по умолчанию 1000) или сервер дважды подряд вернул одну и ту же страницу, бросается `YclientsPaginationError`. Неполный список никогда не выдаётся за полный.
120
+
121
+ ```ts
122
+ for await (const client of yc.clients.iterate(companyId, { count: 200 })) {
123
+ await save(client); // постранично, без накопления в памяти
124
+ }
125
+
126
+ const recent = await yc.clients.listAll(
127
+ companyId,
128
+ { changed_after: '2026-01-01' },
129
+ { maxPages: 50 },
130
+ );
131
+ ```
132
+
133
+ ## Повторы и лимиты
134
+
135
+ | Ситуация | GET / PUT / DELETE | POST / PATCH |
136
+ | --- | --- | --- |
137
+ | HTTP 429 | повторяется | повторяется (запрос не был обработан) |
138
+ | HTTP 502, 503, 504 | повторяется | не повторяется (мог быть применён) |
139
+ | Сетевая ошибка или таймаут | повторяется | не повторяется |
140
+ | Прочие 4xx / 5xx | ошибка | ошибка |
141
+
142
+ Пауза: `min(maxDelayMs, max(Retry-After, экспоненциальная задержка с джиттером))`.
143
+
144
+ ```ts
145
+ const yc = new YclientsClient({
146
+ partnerToken,
147
+ userToken,
148
+ timeoutMs: 20_000, // на одну попытку, по умолчанию 30 000
149
+ retry: {
150
+ retries: 4, // по умолчанию 4; 0 отключает повторы
151
+ minDelayMs: 1000, // по умолчанию 1000
152
+ maxDelayMs: 30_000, // по умолчанию 30 000
153
+ retryStatuses: [429, 502, 503, 504],
154
+ retryNetworkErrors: true,
155
+ },
156
+ onRetry: ({ attempt, delayMs, status, path }) => {
157
+ console.warn(`YCLIENTS ${path} → ${status ?? 'сеть'}, повтор №${attempt} через ${delayMs} мс`);
158
+ },
159
+ });
160
+ ```
161
+
162
+ Когда попытки закончились, `YclientsRateLimitError` содержит `retryAfterMs`, чтобы задачу можно было перенести.
163
+
164
+ ## Ошибки
165
+
166
+ ```ts
167
+ import {
168
+ YclientsApiError,
169
+ YclientsRateLimitError,
170
+ YclientsNetworkError,
171
+ YclientsPaginationError,
172
+ } from 'yclients-api';
173
+
174
+ try {
175
+ await yc.records.get(companyId, recordId);
176
+ } catch (error) {
177
+ if (error instanceof YclientsRateLimitError) {
178
+ // 429 после всех повторов; error.retryAfterMs
179
+ } else if (error instanceof YclientsApiError) {
180
+ // не 2xx или { success: false }; error.status, error.apiMessage, error.body
181
+ } else if (error instanceof YclientsNetworkError) {
182
+ // ответа нет; error.timedOut отличает таймаут от обрыва соединения
183
+ } else if (error instanceof YclientsPaginationError) {
184
+ // список не удалось прочитать целиком
185
+ }
186
+ }
187
+ ```
188
+
189
+ Все они наследуются от `YclientsError`.
190
+
191
+ ## Переход с `api.yclients.com`
192
+
193
+ По умолчанию клиент обращается к `https://api.yclients.ru/api/v1`. Чтобы на время перехода остаться на старом адресе:
194
+
195
+ ```ts
196
+ new YclientsClient({ partnerToken, baseUrl: 'https://api.yclients.com/api/v1' });
197
+ ```
198
+
199
+ `marketplace.activate()` берёт домен из `baseUrl`, поэтому переключается вместе с ним.
200
+
201
+ ## Разработка
202
+
203
+ ```bash
204
+ npm install
205
+ npm test # vitest, только подменённый fetch
206
+ npm run typecheck
207
+ npm run build # собирает dist/ (ESM + .d.ts)
208
+ ```
209
+
210
+ Будем рады помощи: новые эндпоинты, более точные типы ответов, баг-репорты с обезличенными данными. Никогда не публикуйте в issues настоящие токены, телефоны и данные клиентов.
211
+
212
+ ## Лицензия
213
+
214
+ [MIT](./LICENSE)
@@ -0,0 +1,137 @@
1
+ import { type RequestOptions, type RetryEvent, type RetryOptions } from './http.js';
2
+ import { type PaginateOptions } from './pagination.js';
3
+ import type { AnalyticsParams, Client, Company, FinanceTransaction, Good, Id, IsoDate, ListClientsParams, ListCompaniesParams, ListGoodsParams, ListRecordsParams, ListTransactionsParams, Page, QueryParams, ScheduleDay, Service, Staff, Storage, UserAuthResult, YclientsEnvelope, YclientsRecord } from './types.js';
4
+ /** YCLIENTS moved its API to the `.ru` domain; `.com` is the legacy host. */
5
+ export declare const DEFAULT_BASE_URL = "https://api.yclients.ru/api/v1";
6
+ export interface YclientsClientOptions {
7
+ /** Partner (developer) token issued by YCLIENTS. Required. */
8
+ partnerToken: string;
9
+ /** User token for company-scoped endpoints. Get one with `auth.getUserToken()`. */
10
+ userToken?: string | undefined;
11
+ /** API root. Default `https://api.yclients.ru/api/v1`. */
12
+ baseUrl?: string;
13
+ /** Custom fetch implementation (proxies, tests). Default: global `fetch`. */
14
+ fetch?: typeof fetch;
15
+ /** Per-attempt timeout in ms. Default `30000`. */
16
+ timeoutMs?: number;
17
+ /** Retry/backoff settings for 429, 5xx gateway errors and network failures. */
18
+ retry?: RetryOptions;
19
+ /** Extra headers sent with every request. */
20
+ headers?: Record<string, string>;
21
+ /** `User-Agent` to send (ignored by browsers). */
22
+ userAgent?: string;
23
+ /** Called before every retry wait, e.g. for logging. */
24
+ onRetry?: (event: RetryEvent) => void;
25
+ /** @internal Test hooks. */
26
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
27
+ /** @internal Test hooks. */
28
+ random?: () => number;
29
+ }
30
+ export interface CallOptions {
31
+ signal?: AbortSignal;
32
+ }
33
+ type ListAllOptions = Omit<PaginateOptions, 'count'> & {
34
+ signal?: AbortSignal;
35
+ };
36
+ /**
37
+ * Typed client for the YCLIENTS REST API.
38
+ *
39
+ * ```ts
40
+ * const yc = new YclientsClient({ partnerToken, userToken });
41
+ * const records = await yc.records.listAll(companyId, { start_date: '2026-01-01', end_date: '2026-01-31' });
42
+ * ```
43
+ */
44
+ export declare class YclientsClient {
45
+ readonly baseUrl: string;
46
+ private readonly transport;
47
+ private readonly clientOptions;
48
+ constructor(options: YclientsClientOptions);
49
+ /** Return a new client that shares all settings but uses another user token. */
50
+ withUserToken(userToken: string): YclientsClient;
51
+ /** Low-level escape hatch: call any endpoint and get the full envelope back. */
52
+ request<T = unknown>(options: RequestOptions): Promise<YclientsEnvelope<T>>;
53
+ private getData;
54
+ private getPage;
55
+ readonly auth: {
56
+ /**
57
+ * Exchange a YCLIENTS user's login and password for a user token (`POST /auth`).
58
+ * Store the token, not the password.
59
+ */
60
+ getUserToken: (credentials: {
61
+ login: string;
62
+ password: string;
63
+ }, call?: CallOptions) => Promise<UserAuthResult>;
64
+ };
65
+ readonly companies: {
66
+ /** `GET /companies`. Pass `{ my: 1 }` to list only companies the user token can access. */
67
+ list: (params?: ListCompaniesParams, call?: CallOptions) => Promise<Company[]>;
68
+ /** `GET /company/{company_id}`. */
69
+ get: (companyId: Id, call?: CallOptions) => Promise<Company>;
70
+ };
71
+ readonly staff: {
72
+ /** `GET /company/{company_id}/staff`. Includes fired/hidden staff; filter on `fired`/`hidden`/`is_deleted`. */
73
+ list: (companyId: Id, call?: CallOptions) => Promise<Staff[]>;
74
+ /** `GET /company/{company_id}/staff/{staff_id}`. */
75
+ get: (companyId: Id, staffId: Id, call?: CallOptions) => Promise<Staff>;
76
+ };
77
+ readonly services: {
78
+ /** `GET /services/{company_id}`. */
79
+ list: (companyId: Id, params?: QueryParams, call?: CallOptions) => Promise<Service[]>;
80
+ };
81
+ readonly records: {
82
+ /** One page of `GET /records/{company_id}`. */
83
+ list: (companyId: Id, params?: ListRecordsParams, call?: CallOptions) => Promise<Page<YclientsRecord>>;
84
+ /** Iterate every record matching `params`, page by page. */
85
+ iterate: (companyId: Id, params?: Omit<ListRecordsParams, "page">, options?: ListAllOptions) => AsyncGenerator<YclientsRecord, void, undefined>;
86
+ /** Read every record matching `params` into an array. */
87
+ listAll: (companyId: Id, params?: Omit<ListRecordsParams, "page">, options?: ListAllOptions) => Promise<YclientsRecord[]>;
88
+ /** `GET /record/{company_id}/{record_id}`. */
89
+ get: (companyId: Id, recordId: Id, call?: CallOptions) => Promise<YclientsRecord>;
90
+ };
91
+ readonly clients: {
92
+ /** One page of `GET /clients/{company_id}`. */
93
+ list: (companyId: Id, params?: ListClientsParams, call?: CallOptions) => Promise<Page<Client>>;
94
+ /** Iterate every client matching `params`, page by page. */
95
+ iterate: (companyId: Id, params?: Omit<ListClientsParams, "page">, options?: ListAllOptions) => AsyncGenerator<Client, void, undefined>;
96
+ /** Read every client matching `params` into an array. */
97
+ listAll: (companyId: Id, params?: Omit<ListClientsParams, "page">, options?: ListAllOptions) => Promise<Client[]>;
98
+ /** `GET /client/{company_id}/{client_id}`. */
99
+ get: (companyId: Id, clientId: Id, call?: CallOptions) => Promise<Client>;
100
+ };
101
+ readonly transactions: {
102
+ /** One page of `GET /transactions/{company_id}`. */
103
+ list: (companyId: Id, params?: ListTransactionsParams, call?: CallOptions) => Promise<Page<FinanceTransaction>>;
104
+ iterate: (companyId: Id, params?: Omit<ListTransactionsParams, "page">, options?: ListAllOptions) => AsyncGenerator<FinanceTransaction, void, undefined>;
105
+ listAll: (companyId: Id, params?: Omit<ListTransactionsParams, "page">, options?: ListAllOptions) => Promise<FinanceTransaction[]>;
106
+ };
107
+ readonly schedule: {
108
+ /** `GET /schedule/{company_id}/{staff_id}/{start_date}/{end_date}`. */
109
+ get: (companyId: Id, staffId: Id, startDate: IsoDate | Date, endDate: IsoDate | Date, call?: CallOptions) => Promise<ScheduleDay[]>;
110
+ };
111
+ readonly goods: {
112
+ /** One page of `GET /goods/{company_id}`. */
113
+ list: (companyId: Id, params?: ListGoodsParams, call?: CallOptions) => Promise<Page<Good>>;
114
+ iterate: (companyId: Id, params?: Omit<ListGoodsParams, "page">, options?: ListAllOptions) => AsyncGenerator<Good, void, undefined>;
115
+ listAll: (companyId: Id, params?: Omit<ListGoodsParams, "page">, options?: ListAllOptions) => Promise<Good[]>;
116
+ };
117
+ readonly storages: {
118
+ /** `GET /storages/{company_id}`. */
119
+ list: (companyId: Id, call?: CallOptions) => Promise<Storage[]>;
120
+ };
121
+ readonly analytics: {
122
+ /** `GET /company/{company_id}/analytics/overall`: revenue, visits and occupancy summary. */
123
+ overall: (companyId: Id, params: AnalyticsParams, call?: CallOptions) => Promise<Record<string, unknown>>;
124
+ };
125
+ readonly marketplace: {
126
+ /**
127
+ * Confirm that a salon has connected your Marketplace application
128
+ * (`POST {origin}/marketplace/partner/callback`). Uses the partner token only.
129
+ */
130
+ activate: (input: {
131
+ salonId: Id;
132
+ applicationId: Id;
133
+ [key: string]: unknown;
134
+ }, call?: CallOptions) => Promise<unknown>;
135
+ };
136
+ }
137
+ export {};