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/dist/client.js ADDED
@@ -0,0 +1,214 @@
1
+ import { DEFAULT_RETRY, Transport, defaultSleep, } from './http.js';
2
+ import { collect, paginate } from './pagination.js';
3
+ /** YCLIENTS moved its API to the `.ru` domain; `.com` is the legacy host. */
4
+ export const DEFAULT_BASE_URL = 'https://api.yclients.ru/api/v1';
5
+ const RECORDS_PAGE_SIZE = 200;
6
+ const CLIENTS_PAGE_SIZE = 200;
7
+ const TRANSACTIONS_PAGE_SIZE = 200;
8
+ const GOODS_PAGE_SIZE = 100;
9
+ function id(value, name) {
10
+ const text = String(value).trim();
11
+ if (!/^\d+$/.test(text))
12
+ throw new TypeError(`${name} must be a numeric ID, got "${text}"`);
13
+ return text;
14
+ }
15
+ function isoDate(value, name) {
16
+ if (value instanceof Date) {
17
+ if (Number.isNaN(value.getTime()))
18
+ throw new TypeError(`${name} is an invalid Date`);
19
+ return value.toISOString().slice(0, 10);
20
+ }
21
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value))
22
+ throw new TypeError(`${name} must be YYYY-MM-DD, got "${value}"`);
23
+ return value;
24
+ }
25
+ function toPage(envelope, page, count) {
26
+ const data = Array.isArray(envelope.data) ? envelope.data : [];
27
+ return { data, meta: envelope.meta ?? {}, page, count };
28
+ }
29
+ /**
30
+ * Typed client for the YCLIENTS REST API.
31
+ *
32
+ * ```ts
33
+ * const yc = new YclientsClient({ partnerToken, userToken });
34
+ * const records = await yc.records.listAll(companyId, { start_date: '2026-01-01', end_date: '2026-01-31' });
35
+ * ```
36
+ */
37
+ export class YclientsClient {
38
+ baseUrl;
39
+ transport;
40
+ clientOptions;
41
+ constructor(options) {
42
+ if (!options || typeof options.partnerToken !== 'string' || !options.partnerToken.trim()) {
43
+ throw new TypeError('YclientsClient: partnerToken is required');
44
+ }
45
+ const fetchImpl = options.fetch ?? globalThis.fetch;
46
+ if (typeof fetchImpl !== 'function') {
47
+ throw new TypeError('YclientsClient: no fetch implementation available; pass options.fetch');
48
+ }
49
+ this.clientOptions = options;
50
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
51
+ this.transport = new Transport({
52
+ baseUrl: this.baseUrl,
53
+ partnerToken: options.partnerToken.trim(),
54
+ userToken: options.userToken?.trim() || undefined,
55
+ fetch: fetchImpl,
56
+ timeoutMs: options.timeoutMs ?? 30_000,
57
+ retry: { ...DEFAULT_RETRY, ...options.retry },
58
+ headers: options.headers ?? {},
59
+ userAgent: options.userAgent,
60
+ onRetry: options.onRetry,
61
+ sleep: options.sleep ?? defaultSleep,
62
+ random: options.random ?? Math.random,
63
+ });
64
+ }
65
+ /** Return a new client that shares all settings but uses another user token. */
66
+ withUserToken(userToken) {
67
+ return new YclientsClient({ ...this.clientOptions, userToken });
68
+ }
69
+ /** Low-level escape hatch: call any endpoint and get the full envelope back. */
70
+ request(options) {
71
+ return this.transport.request(options);
72
+ }
73
+ async getData(path, query, call) {
74
+ const envelope = await this.transport.request({ path, query, signal: call?.signal });
75
+ return envelope.data;
76
+ }
77
+ async getPage(path, query, page, count, signal) {
78
+ const envelope = await this.transport.request({ path, query: { ...query, page, count }, signal });
79
+ return toPage(envelope, page, count);
80
+ }
81
+ /* ---------------- auth ---------------- */
82
+ auth = {
83
+ /**
84
+ * Exchange a YCLIENTS user's login and password for a user token (`POST /auth`).
85
+ * Store the token, not the password.
86
+ */
87
+ getUserToken: async (credentials, call) => {
88
+ const envelope = await this.transport.request({
89
+ method: 'POST',
90
+ path: 'auth',
91
+ body: { login: credentials.login, password: credentials.password },
92
+ partnerOnly: true,
93
+ signal: call?.signal,
94
+ });
95
+ return envelope.data;
96
+ },
97
+ };
98
+ /* ---------------- companies ---------------- */
99
+ companies = {
100
+ /** `GET /companies`. Pass `{ my: 1 }` to list only companies the user token can access. */
101
+ list: async (params = {}, call) => this.getData('companies', params, call).then((data) => (Array.isArray(data) ? data : [])),
102
+ /** `GET /company/{company_id}`. */
103
+ get: async (companyId, call) => this.getData(`company/${id(companyId, 'companyId')}`, undefined, call),
104
+ };
105
+ /* ---------------- staff ---------------- */
106
+ staff = {
107
+ /** `GET /company/{company_id}/staff`. Includes fired/hidden staff; filter on `fired`/`hidden`/`is_deleted`. */
108
+ list: async (companyId, call) => this.getData(`company/${id(companyId, 'companyId')}/staff`, undefined, call).then((data) => Array.isArray(data) ? data : []),
109
+ /** `GET /company/{company_id}/staff/{staff_id}`. */
110
+ get: async (companyId, staffId, call) => this.getData(`company/${id(companyId, 'companyId')}/staff/${id(staffId, 'staffId')}`, undefined, call),
111
+ };
112
+ /* ---------------- services ---------------- */
113
+ services = {
114
+ /** `GET /services/{company_id}`. */
115
+ list: async (companyId, params = {}, call) => this.getData(`services/${id(companyId, 'companyId')}`, params, call).then((data) => (Array.isArray(data) ? data : Array.isArray(data?.services) ? data.services : [])),
116
+ };
117
+ /* ---------------- records (bookings) ---------------- */
118
+ records = {
119
+ /** One page of `GET /records/{company_id}`. */
120
+ list: async (companyId, params = {}, call) => {
121
+ const { page = 1, count = RECORDS_PAGE_SIZE, ...query } = params;
122
+ return this.getPage(`records/${id(companyId, 'companyId')}`, query, Number(page), Number(count), call?.signal);
123
+ },
124
+ /** Iterate every record matching `params`, page by page. */
125
+ iterate: (companyId, params = {}, options = {}) => {
126
+ const { count = RECORDS_PAGE_SIZE, ...query } = params;
127
+ const path = `records/${id(companyId, 'companyId')}`;
128
+ return paginate((page, size, signal) => this.getPage(path, query, page, size, signal), Number(count), options);
129
+ },
130
+ /** Read every record matching `params` into an array. */
131
+ listAll: async (companyId, params = {}, options = {}) => collect(this.records.iterate(companyId, params, options)),
132
+ /** `GET /record/{company_id}/{record_id}`. */
133
+ get: async (companyId, recordId, call) => this.getData(`record/${id(companyId, 'companyId')}/${id(recordId, 'recordId')}`, undefined, call),
134
+ };
135
+ /* ---------------- clients ---------------- */
136
+ clients = {
137
+ /** One page of `GET /clients/{company_id}`. */
138
+ list: async (companyId, params = {}, call) => {
139
+ const { page = 1, count = CLIENTS_PAGE_SIZE, ...query } = params;
140
+ return this.getPage(`clients/${id(companyId, 'companyId')}`, query, Number(page), Number(count), call?.signal);
141
+ },
142
+ /** Iterate every client matching `params`, page by page. */
143
+ iterate: (companyId, params = {}, options = {}) => {
144
+ const { count = CLIENTS_PAGE_SIZE, ...query } = params;
145
+ const path = `clients/${id(companyId, 'companyId')}`;
146
+ return paginate((page, size, signal) => this.getPage(path, query, page, size, signal), Number(count), options);
147
+ },
148
+ /** Read every client matching `params` into an array. */
149
+ listAll: async (companyId, params = {}, options = {}) => collect(this.clients.iterate(companyId, params, options)),
150
+ /** `GET /client/{company_id}/{client_id}`. */
151
+ get: async (companyId, clientId, call) => this.getData(`client/${id(companyId, 'companyId')}/${id(clientId, 'clientId')}`, undefined, call),
152
+ };
153
+ /* ---------------- finance transactions ---------------- */
154
+ transactions = {
155
+ /** One page of `GET /transactions/{company_id}`. */
156
+ list: async (companyId, params = {}, call) => {
157
+ const { page = 1, count = TRANSACTIONS_PAGE_SIZE, ...query } = params;
158
+ return this.getPage(`transactions/${id(companyId, 'companyId')}`, query, Number(page), Number(count), call?.signal);
159
+ },
160
+ iterate: (companyId, params = {}, options = {}) => {
161
+ const { count = TRANSACTIONS_PAGE_SIZE, ...query } = params;
162
+ const path = `transactions/${id(companyId, 'companyId')}`;
163
+ return paginate((page, size, signal) => this.getPage(path, query, page, size, signal), Number(count), options);
164
+ },
165
+ listAll: async (companyId, params = {}, options = {}) => collect(this.transactions.iterate(companyId, params, options)),
166
+ };
167
+ /* ---------------- schedule ---------------- */
168
+ schedule = {
169
+ /** `GET /schedule/{company_id}/{staff_id}/{start_date}/{end_date}`. */
170
+ get: async (companyId, staffId, startDate, endDate, call) => this.getData(`schedule/${id(companyId, 'companyId')}/${id(staffId, 'staffId')}/${isoDate(startDate, 'startDate')}/${isoDate(endDate, 'endDate')}`, undefined, call).then((data) => (Array.isArray(data) ? data : [])),
171
+ };
172
+ /* ---------------- goods & storages ---------------- */
173
+ goods = {
174
+ /** One page of `GET /goods/{company_id}`. */
175
+ list: async (companyId, params = {}, call) => {
176
+ const { page = 1, count = GOODS_PAGE_SIZE, ...query } = params;
177
+ return this.getPage(`goods/${id(companyId, 'companyId')}`, query, Number(page), Number(count), call?.signal);
178
+ },
179
+ iterate: (companyId, params = {}, options = {}) => {
180
+ const { count = GOODS_PAGE_SIZE, ...query } = params;
181
+ const path = `goods/${id(companyId, 'companyId')}`;
182
+ return paginate((page, size, signal) => this.getPage(path, query, page, size, signal), Number(count), options);
183
+ },
184
+ listAll: async (companyId, params = {}, options = {}) => collect(this.goods.iterate(companyId, params, options)),
185
+ };
186
+ storages = {
187
+ /** `GET /storages/{company_id}`. */
188
+ list: async (companyId, call) => this.getData(`storages/${id(companyId, 'companyId')}`, undefined, call).then((data) => Array.isArray(data) ? data : []),
189
+ };
190
+ /* ---------------- analytics ---------------- */
191
+ analytics = {
192
+ /** `GET /company/{company_id}/analytics/overall`: revenue, visits and occupancy summary. */
193
+ overall: async (companyId, params, call) => this.getData(`company/${id(companyId, 'companyId')}/analytics/overall`, { ...params, date_from: isoDate(params.date_from, 'date_from'), date_to: isoDate(params.date_to, 'date_to') }, call),
194
+ };
195
+ /* ---------------- marketplace ---------------- */
196
+ marketplace = {
197
+ /**
198
+ * Confirm that a salon has connected your Marketplace application
199
+ * (`POST {origin}/marketplace/partner/callback`). Uses the partner token only.
200
+ */
201
+ activate: async (input, call) => {
202
+ const { salonId, applicationId, ...extra } = input;
203
+ const origin = new URL(this.baseUrl).origin;
204
+ const envelope = await this.transport.request({
205
+ method: 'POST',
206
+ path: `${origin}/marketplace/partner/callback`,
207
+ body: { ...extra, salon_id: Number(id(salonId, 'salonId')), application_id: Number(id(applicationId, 'applicationId')) },
208
+ partnerOnly: true,
209
+ signal: call?.signal,
210
+ });
211
+ return envelope.data;
212
+ },
213
+ };
214
+ }
@@ -0,0 +1,62 @@
1
+ /** Base class for every error thrown by this library. */
2
+ export declare class YclientsError extends Error {
3
+ constructor(message: string, options?: {
4
+ cause?: unknown;
5
+ });
6
+ }
7
+ export interface YclientsApiErrorInit {
8
+ status: number;
9
+ method: string;
10
+ url: string;
11
+ /** Parsed JSON body, if the response had one. */
12
+ body?: unknown;
13
+ /** Raw response text when the body was not JSON. */
14
+ rawBody?: string;
15
+ }
16
+ /**
17
+ * The API answered, but not with a successful envelope:
18
+ * either a non-2xx HTTP status or `{ "success": false }`.
19
+ */
20
+ export declare class YclientsApiError extends YclientsError {
21
+ readonly status: number;
22
+ readonly method: string;
23
+ readonly url: string;
24
+ readonly body: unknown;
25
+ readonly rawBody: string | undefined;
26
+ /** Message reported by YCLIENTS in `meta.message` / `message` / `error`, if any. */
27
+ readonly apiMessage: string | undefined;
28
+ constructor(init: YclientsApiErrorInit, message?: string);
29
+ }
30
+ /** HTTP 429 that was still rate-limited after all retries were spent. */
31
+ export declare class YclientsRateLimitError extends YclientsApiError {
32
+ /** Delay the server asked for (from `Retry-After`), in milliseconds, if it sent one. */
33
+ readonly retryAfterMs: number | undefined;
34
+ constructor(init: YclientsApiErrorInit & {
35
+ retryAfterMs?: number | undefined;
36
+ });
37
+ }
38
+ /** The request never got an HTTP response: DNS, TLS, connection reset or timeout. */
39
+ export declare class YclientsNetworkError extends YclientsError {
40
+ readonly method: string;
41
+ readonly url: string;
42
+ readonly timedOut: boolean;
43
+ constructor(init: {
44
+ method: string;
45
+ url: string;
46
+ timedOut: boolean;
47
+ cause: unknown;
48
+ });
49
+ }
50
+ /**
51
+ * Pagination stopped before the list was provably complete
52
+ * (page limit reached, or the server repeated a page).
53
+ * Thrown instead of silently returning a truncated list.
54
+ */
55
+ export declare class YclientsPaginationError extends YclientsError {
56
+ readonly pagesRead: number;
57
+ readonly itemsRead: number;
58
+ constructor(message: string, init: {
59
+ pagesRead: number;
60
+ itemsRead: number;
61
+ });
62
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,101 @@
1
+ /** Base class for every error thrown by this library. */
2
+ export class YclientsError extends Error {
3
+ constructor(message, options) {
4
+ super(message, options);
5
+ this.name = 'YclientsError';
6
+ }
7
+ }
8
+ /**
9
+ * The API answered, but not with a successful envelope:
10
+ * either a non-2xx HTTP status or `{ "success": false }`.
11
+ */
12
+ export class YclientsApiError extends YclientsError {
13
+ status;
14
+ method;
15
+ url;
16
+ body;
17
+ rawBody;
18
+ /** Message reported by YCLIENTS in `meta.message` / `message` / `error`, if any. */
19
+ apiMessage;
20
+ constructor(init, message) {
21
+ const apiMessage = extractApiMessage(init.body);
22
+ super(message ?? `YCLIENTS ${init.method} ${redactUrl(init.url)} failed with HTTP ${init.status}${apiMessage ? `: ${apiMessage}` : ''}`);
23
+ this.name = 'YclientsApiError';
24
+ this.status = init.status;
25
+ this.method = init.method;
26
+ this.url = redactUrl(init.url);
27
+ this.body = init.body;
28
+ this.rawBody = init.rawBody;
29
+ this.apiMessage = apiMessage;
30
+ }
31
+ }
32
+ /** HTTP 429 that was still rate-limited after all retries were spent. */
33
+ export class YclientsRateLimitError extends YclientsApiError {
34
+ /** Delay the server asked for (from `Retry-After`), in milliseconds, if it sent one. */
35
+ retryAfterMs;
36
+ constructor(init) {
37
+ super(init);
38
+ this.name = 'YclientsRateLimitError';
39
+ this.retryAfterMs = init.retryAfterMs;
40
+ }
41
+ }
42
+ /** The request never got an HTTP response: DNS, TLS, connection reset or timeout. */
43
+ export class YclientsNetworkError extends YclientsError {
44
+ method;
45
+ url;
46
+ timedOut;
47
+ constructor(init) {
48
+ super(init.timedOut
49
+ ? `YCLIENTS ${init.method} ${redactUrl(init.url)} timed out`
50
+ : `YCLIENTS ${init.method} ${redactUrl(init.url)} failed before a response was received`, { cause: init.cause });
51
+ this.name = 'YclientsNetworkError';
52
+ this.method = init.method;
53
+ this.url = redactUrl(init.url);
54
+ this.timedOut = init.timedOut;
55
+ }
56
+ }
57
+ /**
58
+ * Pagination stopped before the list was provably complete
59
+ * (page limit reached, or the server repeated a page).
60
+ * Thrown instead of silently returning a truncated list.
61
+ */
62
+ export class YclientsPaginationError extends YclientsError {
63
+ pagesRead;
64
+ itemsRead;
65
+ constructor(message, init) {
66
+ super(message);
67
+ this.name = 'YclientsPaginationError';
68
+ this.pagesRead = init.pagesRead;
69
+ this.itemsRead = init.itemsRead;
70
+ }
71
+ }
72
+ function extractApiMessage(body) {
73
+ if (!body || typeof body !== 'object')
74
+ return undefined;
75
+ const record = body;
76
+ const meta = record.meta;
77
+ const candidates = [
78
+ meta && typeof meta === 'object' ? meta.message : undefined,
79
+ record.message,
80
+ record.error,
81
+ ];
82
+ for (const candidate of candidates) {
83
+ if (typeof candidate === 'string' && candidate.trim()) {
84
+ return candidate.trim().replace(/[\r\n]+/g, ' ').slice(0, 500);
85
+ }
86
+ }
87
+ return undefined;
88
+ }
89
+ /** Strip query-string values that may contain personal data (phones, names) from error messages. */
90
+ function redactUrl(url) {
91
+ try {
92
+ const parsed = new URL(url);
93
+ for (const key of [...parsed.searchParams.keys()]) {
94
+ parsed.searchParams.set(key, '…');
95
+ }
96
+ return parsed.toString().replace(/%E2%80%A6/g, '…');
97
+ }
98
+ catch {
99
+ return url.split('?')[0] ?? url;
100
+ }
101
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import type { QueryParams, YclientsEnvelope } from './types.js';
2
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
3
+ export interface RetryOptions {
4
+ /** How many times to retry after the first attempt. Default `4`. Set `0` to disable. */
5
+ retries?: number;
6
+ /** Base delay for exponential backoff, in ms. Default `1000`. */
7
+ minDelayMs?: number;
8
+ /** Upper bound for a single wait, in ms (also caps `Retry-After`). Default `30000`. */
9
+ maxDelayMs?: number;
10
+ /**
11
+ * HTTP statuses that are retried for idempotent requests (GET, PUT, DELETE).
12
+ * `429` is always retried for every method, because a rate-limited request was not processed.
13
+ * Default `[429, 502, 503, 504]`.
14
+ */
15
+ retryStatuses?: readonly number[];
16
+ /** Retry network failures and timeouts for idempotent requests. Default `true`. */
17
+ retryNetworkErrors?: boolean;
18
+ }
19
+ export interface RetryEvent {
20
+ attempt: number;
21
+ delayMs: number;
22
+ method: HttpMethod;
23
+ /** Request URL with query values removed. */
24
+ path: string;
25
+ status?: number;
26
+ error?: unknown;
27
+ }
28
+ export interface TransportOptions {
29
+ baseUrl: string;
30
+ partnerToken: string;
31
+ userToken?: string | undefined;
32
+ fetch: typeof fetch;
33
+ timeoutMs: number;
34
+ retry: Required<RetryOptions>;
35
+ headers: Record<string, string>;
36
+ userAgent?: string | undefined;
37
+ onRetry?: ((event: RetryEvent) => void) | undefined;
38
+ /** Injected for tests. */
39
+ sleep: (ms: number, signal?: AbortSignal) => Promise<void>;
40
+ /** Injected for tests; returns a number in [0, 1). */
41
+ random: () => number;
42
+ }
43
+ export interface RequestOptions {
44
+ method?: HttpMethod;
45
+ /** Path relative to `baseUrl`, e.g. `records/123`. An absolute URL is used as is. */
46
+ path: string;
47
+ query?: QueryParams | undefined;
48
+ body?: unknown;
49
+ signal?: AbortSignal | undefined;
50
+ /** Per-request header overrides. */
51
+ headers?: Record<string, string> | undefined;
52
+ /** Send only the partner token even if the client has a user token. */
53
+ partnerOnly?: boolean | undefined;
54
+ }
55
+ export declare const DEFAULT_RETRY: Required<RetryOptions>;
56
+ export declare const YCLIENTS_ACCEPT = "application/vnd.yclients.v2+json";
57
+ export declare function buildAuthorizationHeader(partnerToken: string, userToken?: string): string;
58
+ export declare function buildUrl(baseUrl: string, path: string, query?: QueryParams): URL;
59
+ /**
60
+ * Parse a `Retry-After` header (delta-seconds or HTTP-date) into milliseconds.
61
+ * Returns `undefined` when the header is missing or unusable.
62
+ */
63
+ export declare function parseRetryAfter(header: string | null, now?: number): number | undefined;
64
+ /** Exponential backoff with "full jitter", honoring the server's Retry-After when it is longer. */
65
+ export declare function computeDelay(attempt: number, retry: Required<RetryOptions>, random: () => number, retryAfterMs?: number): number;
66
+ export declare function defaultSleep(ms: number, signal?: AbortSignal): Promise<void>;
67
+ export declare class Transport {
68
+ readonly options: TransportOptions;
69
+ constructor(options: TransportOptions);
70
+ /** Perform a request and return the full YCLIENTS envelope. */
71
+ request<T>(request: RequestOptions): Promise<YclientsEnvelope<T>>;
72
+ private send;
73
+ private parseSuccess;
74
+ private wait;
75
+ }
package/dist/http.js ADDED
@@ -0,0 +1,208 @@
1
+ import { YclientsApiError, YclientsNetworkError, YclientsRateLimitError, } from './errors.js';
2
+ export const DEFAULT_RETRY = {
3
+ retries: 4,
4
+ minDelayMs: 1000,
5
+ maxDelayMs: 30_000,
6
+ retryStatuses: [429, 502, 503, 504],
7
+ retryNetworkErrors: true,
8
+ };
9
+ const IDEMPOTENT_METHODS = new Set(['GET', 'PUT', 'DELETE']);
10
+ export const YCLIENTS_ACCEPT = 'application/vnd.yclients.v2+json';
11
+ export function buildAuthorizationHeader(partnerToken, userToken) {
12
+ return userToken ? `Bearer ${partnerToken}, User ${userToken}` : `Bearer ${partnerToken}`;
13
+ }
14
+ export function buildUrl(baseUrl, path, query) {
15
+ const url = /^https?:\/\//i.test(path)
16
+ ? new URL(path)
17
+ : new URL(path.replace(/^\/+/, ''), baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`);
18
+ if (query) {
19
+ for (const [key, value] of Object.entries(query)) {
20
+ if (value === undefined || value === null)
21
+ continue;
22
+ if (Array.isArray(value)) {
23
+ const arrayKey = key.endsWith('[]') ? key : `${key}[]`;
24
+ for (const item of value)
25
+ url.searchParams.append(arrayKey, String(item));
26
+ }
27
+ else {
28
+ url.searchParams.set(key, typeof value === 'boolean' ? (value ? '1' : '0') : String(value));
29
+ }
30
+ }
31
+ }
32
+ return url;
33
+ }
34
+ /**
35
+ * Parse a `Retry-After` header (delta-seconds or HTTP-date) into milliseconds.
36
+ * Returns `undefined` when the header is missing or unusable.
37
+ */
38
+ export function parseRetryAfter(header, now = Date.now()) {
39
+ if (!header)
40
+ return undefined;
41
+ const trimmed = header.trim();
42
+ if (/^\d+(\.\d+)?$/.test(trimmed)) {
43
+ return Math.round(Number(trimmed) * 1000);
44
+ }
45
+ const at = Date.parse(trimmed);
46
+ if (Number.isNaN(at))
47
+ return undefined;
48
+ return Math.max(0, at - now);
49
+ }
50
+ /** Exponential backoff with "full jitter", honoring the server's Retry-After when it is longer. */
51
+ export function computeDelay(attempt, retry, random, retryAfterMs) {
52
+ const exponential = Math.min(retry.maxDelayMs, retry.minDelayMs * 2 ** attempt);
53
+ const jittered = Math.round(exponential / 2 + random() * (exponential / 2));
54
+ const delay = retryAfterMs !== undefined ? Math.max(retryAfterMs, jittered) : jittered;
55
+ return Math.min(retry.maxDelayMs, delay);
56
+ }
57
+ export function defaultSleep(ms, signal) {
58
+ return new Promise((resolve, reject) => {
59
+ if (signal?.aborted) {
60
+ reject(signal.reason);
61
+ return;
62
+ }
63
+ const timer = setTimeout(() => {
64
+ signal?.removeEventListener('abort', onAbort);
65
+ resolve();
66
+ }, ms);
67
+ const onAbort = () => {
68
+ clearTimeout(timer);
69
+ reject(signal?.reason);
70
+ };
71
+ signal?.addEventListener('abort', onAbort, { once: true });
72
+ });
73
+ }
74
+ export class Transport {
75
+ options;
76
+ constructor(options) {
77
+ this.options = options;
78
+ }
79
+ /** Perform a request and return the full YCLIENTS envelope. */
80
+ async request(request) {
81
+ const method = request.method ?? 'GET';
82
+ const url = buildUrl(this.options.baseUrl, request.path, request.query);
83
+ const { retry } = this.options;
84
+ const idempotent = IDEMPOTENT_METHODS.has(method);
85
+ for (let attempt = 0;; attempt += 1) {
86
+ request.signal?.throwIfAborted();
87
+ const canRetry = attempt < retry.retries;
88
+ let response;
89
+ try {
90
+ response = await this.send(method, url, request);
91
+ }
92
+ catch (error) {
93
+ if (request.signal?.aborted)
94
+ throw request.signal.reason ?? error;
95
+ const timedOut = isTimeout(error);
96
+ const networkError = new YclientsNetworkError({ method, url: url.toString(), timedOut, cause: error });
97
+ if (!(canRetry && idempotent && retry.retryNetworkErrors))
98
+ throw networkError;
99
+ await this.wait(attempt, method, url, { error: networkError }, request.signal);
100
+ continue;
101
+ }
102
+ if (response.ok) {
103
+ return this.parseSuccess(response, method, url);
104
+ }
105
+ const { body, rawBody } = await readBody(response);
106
+ const retryAfterMs = parseRetryAfter(response.headers.get('retry-after'));
107
+ const retryable = response.status === 429 || (idempotent && retry.retryStatuses.includes(response.status));
108
+ if (canRetry && retryable) {
109
+ await this.wait(attempt, method, url, { status: response.status, retryAfterMs }, request.signal);
110
+ continue;
111
+ }
112
+ const init = { status: response.status, method, url: url.toString(), body, rawBody };
113
+ if (response.status === 429)
114
+ throw new YclientsRateLimitError({ ...init, retryAfterMs });
115
+ throw new YclientsApiError(init);
116
+ }
117
+ }
118
+ async send(method, url, request) {
119
+ const headers = {
120
+ Accept: YCLIENTS_ACCEPT,
121
+ Authorization: buildAuthorizationHeader(this.options.partnerToken, request.partnerOnly ? undefined : this.options.userToken),
122
+ ...this.options.headers,
123
+ ...(this.options.userAgent ? { 'User-Agent': this.options.userAgent } : {}),
124
+ ...request.headers,
125
+ };
126
+ let body;
127
+ if (request.body !== undefined) {
128
+ headers['Content-Type'] = 'application/json';
129
+ body = JSON.stringify(request.body);
130
+ }
131
+ const timeoutSignal = AbortSignal.timeout(this.options.timeoutMs);
132
+ const signal = request.signal ? anySignal([request.signal, timeoutSignal]) : timeoutSignal;
133
+ const init = { method, headers, signal };
134
+ if (body !== undefined)
135
+ init.body = body;
136
+ return this.options.fetch(url, init);
137
+ }
138
+ async parseSuccess(response, method, url) {
139
+ const { body, rawBody } = await readBody(response);
140
+ if (body === undefined) {
141
+ if (!rawBody) {
142
+ // 204 No Content or an empty body: treat as success without data.
143
+ return { success: true, data: undefined, meta: {} };
144
+ }
145
+ throw new YclientsApiError({ status: response.status, method, url: url.toString(), rawBody }, `YCLIENTS ${method} ${url.pathname} returned a non-JSON body`);
146
+ }
147
+ if (isEnvelope(body)) {
148
+ if (body.success === false) {
149
+ throw new YclientsApiError({ status: response.status, method, url: url.toString(), body });
150
+ }
151
+ return body;
152
+ }
153
+ // A few legacy endpoints answer with a bare array or object.
154
+ return { success: true, data: body, meta: {} };
155
+ }
156
+ async wait(attempt, method, url, info, signal) {
157
+ const delayMs = computeDelay(attempt, this.options.retry, this.options.random, info.retryAfterMs);
158
+ const event = { attempt: attempt + 1, delayMs, method, path: url.pathname };
159
+ if (info.status !== undefined)
160
+ event.status = info.status;
161
+ if (info.error !== undefined)
162
+ event.error = info.error;
163
+ this.options.onRetry?.(event);
164
+ await this.options.sleep(delayMs, signal);
165
+ }
166
+ }
167
+ function isEnvelope(body) {
168
+ return (!!body &&
169
+ typeof body === 'object' &&
170
+ !Array.isArray(body) &&
171
+ 'success' in body &&
172
+ typeof body.success === 'boolean');
173
+ }
174
+ async function readBody(response) {
175
+ let rawBody = '';
176
+ try {
177
+ rawBody = await response.text();
178
+ }
179
+ catch {
180
+ return { body: undefined, rawBody: '' };
181
+ }
182
+ if (!rawBody.trim())
183
+ return { body: undefined, rawBody };
184
+ try {
185
+ return { body: JSON.parse(rawBody), rawBody };
186
+ }
187
+ catch {
188
+ return { body: undefined, rawBody: rawBody.slice(0, 2000) };
189
+ }
190
+ }
191
+ function isTimeout(error) {
192
+ return error instanceof Error && (error.name === 'TimeoutError' || error.name === 'AbortError');
193
+ }
194
+ /** `AbortSignal.any` is Node 20.3+; this keeps the library working on every Node 20. */
195
+ function anySignal(signals) {
196
+ const anyFn = AbortSignal.any;
197
+ if (typeof anyFn === 'function')
198
+ return anyFn(signals);
199
+ const controller = new AbortController();
200
+ for (const signal of signals) {
201
+ if (signal.aborted) {
202
+ controller.abort(signal.reason);
203
+ break;
204
+ }
205
+ signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true });
206
+ }
207
+ return controller.signal;
208
+ }
@@ -0,0 +1,8 @@
1
+ export { YclientsClient, DEFAULT_BASE_URL } from './client.js';
2
+ export type { YclientsClientOptions, CallOptions } from './client.js';
3
+ export { YclientsError, YclientsApiError, YclientsRateLimitError, YclientsNetworkError, YclientsPaginationError, } from './errors.js';
4
+ export { paginate, collect } from './pagination.js';
5
+ export type { PaginateOptions, PageFetcher } from './pagination.js';
6
+ export { buildAuthorizationHeader, parseRetryAfter, computeDelay, DEFAULT_RETRY, YCLIENTS_ACCEPT } from './http.js';
7
+ export type { RetryOptions, RetryEvent, RequestOptions, HttpMethod } from './http.js';
8
+ export type * from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { YclientsClient, DEFAULT_BASE_URL } from './client.js';
2
+ export { YclientsError, YclientsApiError, YclientsRateLimitError, YclientsNetworkError, YclientsPaginationError, } from './errors.js';
3
+ export { paginate, collect } from './pagination.js';
4
+ export { buildAuthorizationHeader, parseRetryAfter, computeDelay, DEFAULT_RETRY, YCLIENTS_ACCEPT } from './http.js';