@streamfarm/sdk 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.
Files changed (69) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +291 -2
  4. package/dist/cjs/chat.d.ts +51 -0
  5. package/dist/cjs/chat.js +224 -0
  6. package/dist/cjs/client.d.ts +44 -0
  7. package/dist/cjs/client.js +64 -0
  8. package/dist/cjs/errors.d.ts +86 -0
  9. package/dist/cjs/errors.js +110 -0
  10. package/dist/cjs/generated/openapi.d.ts +4127 -0
  11. package/dist/cjs/generated/openapi.js +7 -0
  12. package/dist/cjs/http.d.ts +81 -0
  13. package/dist/cjs/http.js +304 -0
  14. package/dist/cjs/index.d.ts +10 -0
  15. package/dist/cjs/index.js +22 -0
  16. package/dist/cjs/package.json +3 -0
  17. package/dist/cjs/pagination.d.ts +9 -0
  18. package/dist/cjs/pagination.js +22 -0
  19. package/dist/cjs/resources/account.d.ts +32 -0
  20. package/dist/cjs/resources/account.js +58 -0
  21. package/dist/cjs/resources/ads.d.ts +25 -0
  22. package/dist/cjs/resources/ads.js +46 -0
  23. package/dist/cjs/resources/base.d.ts +12 -0
  24. package/dist/cjs/resources/base.js +23 -0
  25. package/dist/cjs/resources/comments.d.ts +27 -0
  26. package/dist/cjs/resources/comments.js +46 -0
  27. package/dist/cjs/resources/platforms.d.ts +24 -0
  28. package/dist/cjs/resources/platforms.js +41 -0
  29. package/dist/cjs/resources/streams.d.ts +39 -0
  30. package/dist/cjs/resources/streams.js +76 -0
  31. package/dist/cjs/resources/studio.d.ts +20 -0
  32. package/dist/cjs/resources/studio.js +39 -0
  33. package/dist/cjs/types.d.ts +124 -0
  34. package/dist/cjs/types.js +2 -0
  35. package/dist/cjs/version.d.ts +2 -0
  36. package/dist/cjs/version.js +5 -0
  37. package/dist/esm/chat.d.ts +51 -0
  38. package/dist/esm/chat.js +220 -0
  39. package/dist/esm/client.d.ts +44 -0
  40. package/dist/esm/client.js +60 -0
  41. package/dist/esm/errors.d.ts +86 -0
  42. package/dist/esm/errors.js +94 -0
  43. package/dist/esm/generated/openapi.d.ts +4127 -0
  44. package/dist/esm/generated/openapi.js +6 -0
  45. package/dist/esm/http.d.ts +81 -0
  46. package/dist/esm/http.js +297 -0
  47. package/dist/esm/index.d.ts +10 -0
  48. package/dist/esm/index.js +4 -0
  49. package/dist/esm/pagination.d.ts +9 -0
  50. package/dist/esm/pagination.js +19 -0
  51. package/dist/esm/resources/account.d.ts +32 -0
  52. package/dist/esm/resources/account.js +50 -0
  53. package/dist/esm/resources/ads.d.ts +25 -0
  54. package/dist/esm/resources/ads.js +41 -0
  55. package/dist/esm/resources/base.d.ts +12 -0
  56. package/dist/esm/resources/base.js +19 -0
  57. package/dist/esm/resources/comments.d.ts +27 -0
  58. package/dist/esm/resources/comments.js +42 -0
  59. package/dist/esm/resources/platforms.d.ts +24 -0
  60. package/dist/esm/resources/platforms.js +37 -0
  61. package/dist/esm/resources/streams.d.ts +39 -0
  62. package/dist/esm/resources/streams.js +72 -0
  63. package/dist/esm/resources/studio.d.ts +20 -0
  64. package/dist/esm/resources/studio.js +35 -0
  65. package/dist/esm/types.d.ts +124 -0
  66. package/dist/esm/types.js +1 -0
  67. package/dist/esm/version.d.ts +2 -0
  68. package/dist/esm/version.js +2 -0
  69. package/package.json +75 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Изменения
2
+
3
+ Версии — по [SemVer](https://semver.org/lang/ru/), свои у библиотеки, не связаны с версиями StreamFarm.
4
+
5
+ ## 0.1.0 — не выпущена
6
+
7
+ Первая версия.
8
+
9
+ - Все 39 операций публичного API `/api/public/v1`: трансляции, площадки, реклама и оверлей, чат и модерация, студия,
10
+ регионы, подключения, статистика, история эфиров, тариф и платежи.
11
+ - Типы объектов и тел запросов из OpenAPI-документа API.
12
+ - Ошибки по классам статусов с `code`, `details`, `correlationId` и `rateLimit`.
13
+ - Повторы при `429`, обрывах и недоступности сервера; тайм-ауты и отмена через `AbortSignal`.
14
+ - `all()` — перебор страниц; `comments.watch` — слежение за чатом курсором `after`; `streams.waitUntilLive`.
15
+ - `request()` — любой маршрут API, которого библиотека ещё не знает.
16
+ - Ключ в настоящем приватном поле (`console.log` и `JSON.stringify` клиента его не показывают) и проверяется на печатный ASCII; id `.` и `..` отклоняются (адрес запроса превратился бы в адрес трансляции).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 StreamFarm
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,292 @@
1
- # Temporary Holding Version
1
+ # StreamFarm SDK для Node.js
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
+ [![npm](https://img.shields.io/npm/v/@streamfarm/sdk)](https://www.npmjs.com/package/@streamfarm/sdk)
4
+ [![CI](https://github.com/streamfarm/nodejs-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/streamfarm/nodejs-sdk/actions/workflows/ci.yml)
5
+
6
+ > **English.** The official Node.js/TypeScript client for the [StreamFarm public API](https://api.streamfarm.ru/api/public/v1/docs):
7
+ > streams, platforms, ads and the ad overlay, the unified chat with moderation, the studio's guests, statistics and billing.
8
+ > Typed from the API's OpenAPI document, no runtime dependencies, ESM and CommonJS, Node 20+ (also Bun, Deno, Cloudflare Workers).
9
+ > Retries, timeouts, pagination and a chat follower built in. The documentation below is in Russian; the code samples speak for themselves.
10
+
11
+ Библиотека для [публичного API StreamFarm](https://api.streamfarm.ru/api/public/v1/docs): трансляции, площадки, реклама и
12
+ её показ в эфире, единый чат с модерацией, гости студии, статистика и тариф — из вашей программы на Node.js или TypeScript.
13
+
14
+ - типы ответов и запросов — из OpenAPI-документа API, с описаниями полей в подсказках редактора;
15
+ - ни одной зависимости, ESM и CommonJS, Node 20+, а также Bun, Deno и Cloudflare Workers;
16
+ - повторы при сбоях и лимите запросов, тайм-ауты, отмена через `AbortSignal`;
17
+ - перебор страниц, слежение за чатом и ожидание эфира.
18
+
19
+ ## Установка
20
+
21
+ ```bash
22
+ npm install @streamfarm/sdk
23
+ ```
24
+
25
+ ## Ключ API
26
+
27
+ Ключ создаётся в личном кабинете: **Настройки → API-ключи**. Секрет показывается один раз. У ключа свои права (scopes),
28
+ срок и, если нужно, список трансляций, к которым он допущен. Какое право нужно методу, написано в таблице ниже и в его
29
+ подсказке.
30
+
31
+ API рассчитан на серверы и скрипты: **не встраивайте ключ в страницы и приложения, которые попадают к пользователям** —
32
+ с ключом можно управлять трансляциями от имени владельца. Храните его в переменной окружения:
33
+
34
+ ```bash
35
+ export STREAMFARM_API_KEY=sf_…
36
+ ```
37
+
38
+ ## Быстрый старт
39
+
40
+ ```ts
41
+ import { StreamFarm } from '@streamfarm/sdk';
42
+
43
+ const sf = new StreamFarm(); // ключ из STREAMFARM_API_KEY
44
+
45
+ const [region] = await sf.regions.list();
46
+ const stream = await sf.streams.create({ name: 'Вечерний эфир', regionUuid: region.uuid });
47
+
48
+ // Twitch с ключом, сохранённым в кабинете, и свой RTMP-сервер
49
+ await sf.platforms.add(stream.uuid, { type: 'twitch' });
50
+ await sf.platforms.add(stream.uuid, { type: 'custom_1', server: 'rtmp://live.example.org/app', key: 'my-key' });
51
+
52
+ const { rtmp } = await sf.streams.credentials(stream.uuid);
53
+ console.log('OBS:', rtmp.server, rtmp.key);
54
+
55
+ await sf.streams.waitUntilLive(stream.uuid);
56
+
57
+ for await (const event of sf.comments.watch(stream.uuid)) {
58
+ if (event.type === 'comment') console.log(`${event.comment.author}: ${event.comment.message}`);
59
+ }
60
+ ```
61
+
62
+ CommonJS тоже работает: `const { StreamFarm } = require('@streamfarm/sdk')`.
63
+
64
+ Готовые программы — в [`examples/`](examples): трансляция с нуля, модератор чата, реклама в эфире, отчёт за месяц.
65
+ Они на TypeScript: в клоне репозитория `npm ci && npm run build`, затем `node examples/<имя>.ts` (Node 22.18+ запускает
66
+ TypeScript сам).
67
+
68
+ Значения id — UUID из ответов API. Пустой id и `.` или `..` библиотека отклоняет сразу: из `..` адрес запроса
69
+ превратился бы в адрес трансляции.
70
+
71
+ ## Клиент
72
+
73
+ ```ts
74
+ const sf = new StreamFarm({
75
+ apiKey: 'sf_…', // по умолчанию STREAMFARM_API_KEY
76
+ baseUrl: 'https://api.streamfarm.ru/api/public/v1', // по умолчанию; локальный стек: http://localhost:3001/api/public/v1
77
+ timeout: 30_000, // мс на запрос вместе с чтением ответа; 0 — без ограничения
78
+ maxRetries: 2, // повторы при сбоях (см. «Повторы»)
79
+ userAgent: 'my-bot/1.2', // добавляется к User-Agent: streamfarm-node/<версия> my-bot/1.2
80
+ fetch: myFetch, // свой fetch: прокси, тесты, другая среда
81
+ onResponse: (info) => log(info), // каждый ответ: метод, путь, статус, попытка, время, X-Correlation-Id, остаток лимита
82
+ });
83
+ ```
84
+
85
+ Последний аргумент любого запроса — настройки этого вызова: `{ signal, timeout, maxRetries }`. У `comments.watch` и
86
+ `streams.waitUntilLive` свои настройки (см. ниже): их `timeout` — на всё ожидание.
87
+
88
+ ## Методы
89
+
90
+ | Метод | Что делает | Право |
91
+ |---|---|---|
92
+ | `sf.keyInfo()` | Ключ клиента: название, права, трансляции, срок | — |
93
+ | `sf.regions.list()` | Регионы, в которых можно создать трансляцию | — |
94
+ | `sf.connections.list()` | Подключённые соцсети: какие площадки добавляются без сервера и ключа | `connections:read` |
95
+ | `sf.streams.list({ page, size, search })` | Страница трансляций, новые сначала | `streams:read` |
96
+ | `sf.streams.all({ size, search })` | Все трансляции, страница за страницей | `streams:read` |
97
+ | `sf.streams.get(id)` | Трансляция: настройки, идёт ли эфир, лимиты, показатели | `streams:read` |
98
+ | `sf.streams.create({ name, regionUuid, … })` | Создать трансляцию | `streams:write` |
99
+ | `sf.streams.update(id, { … })` | Изменить переданные поля | `streams:write` |
100
+ | `sf.streams.delete(id)` | Удалить, остановив эфир | `streams:write` |
101
+ | `sf.streams.activate(id)` | Сделать активной трансляцию, замороженную сверх тарифа | `streams:write` |
102
+ | `sf.streams.credentials(id)` | Сервер и ключ для энкодера (RTMP и WHIP) | `streams:credentials` |
103
+ | `sf.streams.waitUntilLive(id, { timeout, interval })` | Дождаться эфира | `streams:read` |
104
+ | `sf.platforms.list(streamId)` | Площадки трансляции и их состояние, без ключей | `platforms:read` |
105
+ | `sf.platforms.add(streamId, { type, server?, key?, chat? })` | Добавить площадку | `platforms:write` |
106
+ | `sf.platforms.setDestination(streamId, platformId, { server, key })` | Новый сервер и ключ площадки | `platforms:write` |
107
+ | `sf.platforms.enable(…)` / `disable(…)` | Включить и выключить площадку | `platforms:write` |
108
+ | `sf.platforms.delete(streamId, platformId)` | Убрать площадку | `platforms:write` |
109
+ | `sf.ads.list(streamId)` | Реклама трансляции | `ads:read` |
110
+ | `sf.ads.create(streamId, { title, advertiser, erid })` | Добавить рекламу | `ads:write` |
111
+ | `sf.ads.update(streamId, adId, { … })` | Изменить; `null` очищает рекламодателя или ERID | `ads:write` |
112
+ | `sf.ads.delete(streamId, adId)` | Удалить рекламу не в эфире | `ads:write` |
113
+ | `sf.overlay.get(streamId)` | Что в оверлее сейчас и сколько осталось | `ads:read` |
114
+ | `sf.overlay.show(streamId, { adUuid, durationSec? })` | Показать рекламу в эфире | `overlay:write` |
115
+ | `sf.overlay.hide(streamId)` | Скрыть рекламу | `overlay:write` |
116
+ | `sf.comments.list(streamId, { after, since, limit, platformTypes })` | Комментарии, старые сначала | `comments:read` |
117
+ | `sf.comments.watch(streamId, { … })` | Следить за чатом (см. «Чат») | `comments:read` |
118
+ | `sf.comments.listDeleted(streamId, { since, limit })` | Комментарии, которые удалил стример | `comments:read` |
119
+ | `sf.comments.counts(streamId, { since, platformTypes })` | Сколько комментариев, всего и по площадкам | `comments:read` |
120
+ | `sf.comments.delete(streamId, commentId)` | Удалить комментарий на площадке | `comments:moderate` |
121
+ | `sf.comments.ban(streamId, commentId, { durationSec? })` | Тайм-аут автору или бан навсегда (без `durationSec`) | `comments:moderate` |
122
+ | `sf.studio.get(streamId)` | Комната студии: доступна ли, кто в ней, приглашения | `studio:read` |
123
+ | `sf.studio.participants(streamId)` | Кто в комнате | `studio:read` |
124
+ | `sf.studio.removeParticipant(streamId, identity)` | Удалить гостя из комнаты | `studio:write` |
125
+ | `sf.studio.invites(streamId)` | Приглашения (ссылки — только с `studio:write`) | `studio:read` |
126
+ | `sf.studio.createInvite(streamId, { label, maxUses, expiresInHours })` | Пригласить гостя: `{ invite, url }` | `studio:write` |
127
+ | `sf.studio.revokeInvite(streamId, inviteId)` | Отозвать приглашение | `studio:write` |
128
+ | `sf.studio.hostToken(streamId)` | Токен ведущего для комнаты (LiveKit) | `studio:write` |
129
+ | `sf.stats.get({ from, to, interval, timeZone, streamUuid })` | Время в эфире, трафик, эфиры по дням или месяцам | `streams:read` |
130
+ | `sf.broadcasts.list({ page, size, streamUuid, from, to })` / `all(…)` | История эфиров | `streams:read` |
131
+ | `sf.account.plan()` | Тариф: опции, лимиты и сколько занято, что продаётся | `billing:read` |
132
+ | `sf.account.payments({ page, size })` / `allPayments()` | Платежи | `billing:read` |
133
+
134
+ Методы возвращают сам объект или массив, без обёрток `{ item }` и `{ items }` API. Списки со страницами (`streams.list`,
135
+ `broadcasts.list`, `account.payments`) возвращают `{ items, pagination: { page, size, total, pages } }`. Удаление
136
+ возвращает `undefined`, кроме `comments.delete` — он возвращает удалённый комментарий. Удаление, повторённое после
137
+ обрыва связи, считается сделанным, если объекта уже нет (его удалила первая попытка). Время в ответах — строки ISO 8601 в UTC, как в API; в параметрах можно передавать и `Date`.
138
+
139
+ ## Страницы
140
+
141
+ ```ts
142
+ for await (const stream of sf.streams.all()) {
143
+ console.log(stream.name, stream.live ? 'в эфире' : '');
144
+ }
145
+ ```
146
+
147
+ `all()` запрашивает страницы по очереди и останавливается, когда они кончились или вы вышли из цикла. Трансляция,
148
+ созданная во время перебора, сдвигает список, но одна и та же трансляция не попадётся дважды.
149
+
150
+ ## Чат
151
+
152
+ `comments.watch` выдаёт каждый новый комментарий один раз, со всех площадок, в порядке, в котором StreamFarm их получил,
153
+ и удаления стримера:
154
+
155
+ ```ts
156
+ const stop = new AbortController();
157
+
158
+ for await (const event of sf.comments.watch(streamId, {
159
+ interval: 5000, // как часто читать чат; по умолчанию 5 с
160
+ platformTypes: ['twitch', 'youtube'], // только эти площадки
161
+ includeHistory: false, // true — сначала последние historyLimit (100) комментариев
162
+ deletions: true, // события { type: 'deleted', uuid, deletedAt }
163
+ signal: stop.signal,
164
+ onError: (error) => console.warn(error.message), // сбои, которые watch пережидает
165
+ })) {
166
+ if (event.type === 'comment') show(event.comment);
167
+ else hide(event.uuid);
168
+ }
169
+ ```
170
+
171
+ - Watch читает чат курсором `after` — по времени получения комментария (`receivedAt`), а не публикации на площадке
172
+ (`publishedAt`). YouTube и VK StreamFarm читает раз в 15–60 секунд, поэтому их комментарии приходят позже более новых
173
+ с Twitch; курсор по `publishedAt` такие опоздавшие терял бы. API без `after` (до его выхода) watch читает по `since` с
174
+ запасом в 2 минуты.
175
+ - С удалениями watch делает два запроса за интервал: при 5 с это 24 запроса в минуту из 120 на ключ.
176
+ - Сбои сети, ошибки сервера и лимит запросов watch пережидает (пауза удваивается, до минуты) и сообщает о них в
177
+ `onError`. Остальные ошибки — нет права, нет трансляции, нет единого чата в тарифе (`plan_limit`) — завершают цикл.
178
+ - Цикл бесконечный: выйдите из него `break` или остановите через `signal` (тогда он завершится с `signal.reason`).
179
+ - Пока программа читает чат, StreamFarm читает YouTube так же часто, как для открытой студии.
180
+
181
+ ## Ошибки
182
+
183
+ Всё, что бросает библиотека, — `StreamFarmError`. Если ответил API — `ApiError` с полями `status`, `code`, `message`,
184
+ `details`, `correlationId` (назовите его, если пишете в поддержку) и `rateLimit`. Класс зависит от HTTP-статуса, точная
185
+ причина — в `code`:
186
+
187
+ | Класс | Статус | Например |
188
+ |---|---|---|
189
+ | `AuthenticationError` | 401 | Нет ключа, ключ неверный, отозван или истёк |
190
+ | `PermissionError` | 403 | `insufficient_scope` — нет права (`details.required`), `plan_limit` — лимит тарифа (`details.limit`, `max`, `current`), `forbidden` |
191
+ | `NotFoundError` | 404 | Нет объекта, он чужой или вне трансляций ключа |
192
+ | `ConflictError` | 409 | `stream_not_live`, `connection_required` (`details.type`), `ad_on_air`, `invite_limit`, … |
193
+ | `ValidationError` | 400, 422 | `bad_request` (`details` — где), `ad_incomplete`, `ad_text_too_long`, `not_supported` |
194
+ | `RateLimitError` | 429 | Больше 120 запросов в минуту; `retryAfter` — через сколько секунд можно снова |
195
+ | `ServerError` | 5xx | `core_unavailable`, `platform_unavailable`, `platform_refused`, `platform_quota_exceeded`, … |
196
+ | `ConnectionError` | — | Ответа нет: DNS, TLS, обрыв; `cause` — исходная ошибка |
197
+ | `TimeoutError` | — | Ответа нет дольше `timeout` (подкласс `ConnectionError`) |
198
+ | `WaitTimeoutError` | — | `waitUntilLive` не дождался эфира |
199
+
200
+ ```ts
201
+ import { ConflictError, PermissionError } from '@streamfarm/sdk';
202
+
203
+ try {
204
+ await sf.platforms.add(streamId, { type: 'youtube' });
205
+ } catch (error) {
206
+ if (error instanceof ConflictError && error.code === 'connection_required') {
207
+ console.log('Подключите YouTube в кабинете');
208
+ } else if (error instanceof PermissionError && error.code === 'plan_limit') {
209
+ console.log('Лимит тарифа:', error.details);
210
+ } else {
211
+ throw error;
212
+ }
213
+ }
214
+ ```
215
+
216
+ Все коды и их причины — в [документации API](https://api.streamfarm.ru/api/public/v1/docs). `code` — строка: новые коды
217
+ API не ломают старые версии библиотеки.
218
+
219
+ ## Повторы и лимит запросов
220
+
221
+ Запрос повторяется до `maxRetries` раз (по умолчанию 2) с паузой 0,5 с, 1 с, … :
222
+
223
+ - `429` — любой запрос: сверх лимита API отказывает до того, как что-то сделать. Пауза — из `Retry-After`; если
224
+ API просит ждать дольше минуты, сразу `RateLimitError`;
225
+ - нет ответа, `502` (медиасервер, площадка или сервер комнат не ответили, API перезапускается), `503`, `504` — только
226
+ `GET`, `PUT` и `DELETE`;
227
+ - `POST` и `PATCH` при ошибке сервера не повторяются: реклама могла уже выйти в эфир, автор — получить бан;
228
+ - отказы площадок (`platform_refused`, `platform_quota_exceeded`, `platform_reconnect_required`) не повторяются:
229
+ повтор получит тот же ответ.
230
+
231
+ Лимит — 120 запросов в минуту на ключ. Остаток виден в `onResponse` (`info.rateLimit`) и в `error.rateLimit`.
232
+
233
+ ## Тайм-ауты и отмена
234
+
235
+ ```ts
236
+ const controller = new AbortController();
237
+ setTimeout(() => controller.abort(), 5000);
238
+
239
+ await sf.streams.list({}, { signal: controller.signal, timeout: 10_000 });
240
+ ```
241
+
242
+ Отменённый вызов завершается с `signal.reason`, как `fetch`; не пришедший вовремя — с `TimeoutError`.
243
+
244
+ ## Типы
245
+
246
+ Типы объектов API — `Stream`, `Platform`, `Comment`, `Ad`, `Overlay`, `Credentials`, `Stats`, `Broadcast`, `Plan`,
247
+ `Payment`, `Studio`, `StudioInvite`, … — и тел запросов — `StreamCreateParams`, `PlatformCreateParams`, … —
248
+ экспортируются из пакета. Они сгенерированы из OpenAPI-документа API, описания полей — из его документации:
249
+
250
+ ```ts
251
+ import type { Stream, PlatformType } from '@streamfarm/sdk';
252
+ ```
253
+
254
+ ## Если в API появилось новое
255
+
256
+ Новые поля ответов приходят сразу: библиотека отдаёт ответ как есть. Новый маршрут, которого эта версия ещё не знает,
257
+ можно вызвать через `sf.request` — с ключом, повторами и ошибками библиотеки:
258
+
259
+ ```ts
260
+ const answer = await sf.request('GET', `/streams/${streamId}/something-new`, { query: { limit: 10 } });
261
+ ```
262
+
263
+ ## Совместимость
264
+
265
+ Node.js 20 и новее; Bun, Deno, Cloudflare Workers и другие среды с `fetch` (для них передайте ключ в `apiKey`). В
266
+ браузере не используйте: ключ попадёт к пользователям.
267
+
268
+ Ключ хранится в настоящем приватном поле клиента: `console.log(sf)` и `JSON.stringify(sf)` его не показывают, в тексты
269
+ ошибок он не попадает.
270
+
271
+ ## Разработка
272
+
273
+ ```bash
274
+ npm install
275
+ npm test # тесты, без сети
276
+ npm run lint && npm run typecheck
277
+ npm run build && npm run check:package
278
+ ```
279
+
280
+ - `spec/openapi.json` — снимок OpenAPI-документа API: из него генерируются типы (`src/generated/`), по нему проверяется
281
+ каждый метод (`test/contract.test.ts`). `npm run spec:update` скачивает свежий и перегенерирует типы,
282
+ `npm run spec:check` сравнивает снимок с живым API (раз в неделю это делает GitHub Actions).
283
+ - `npm run test:live` — проверка на настоящем API с ключом из `STREAMFARM_API_KEY` (и `STREAMFARM_BASE_URL`); с
284
+ `STREAMFARM_WRITE=1` создаёт временную трансляцию и удаляет её. Каждый ответ сверяется со схемами документа.
285
+ - Выпуск: версия в `package.json`, `src/version.ts` и `CHANGELOG.md`, затем тег `vX.Y.Z` — GitHub Actions публикует
286
+ пакет в npm через trusted publishing. npm настраивает его только для существующего пакета, поэтому первую версию
287
+ публикуют вручную: `npm ci && npm publish` (с кодом из приложения-аутентификатора), затем на npmjs.com → пакет →
288
+ Settings → Trusted publishing указывают репозиторий и `release.yml`.
289
+
290
+ ## Лицензия
291
+
292
+ [MIT](LICENSE)
@@ -0,0 +1,51 @@
1
+ import { type RequestOptions } from './http.js';
2
+ import type { Comment, CommentListParams, DeletedComment, DeletedCommentListParams, PlatformType } from './types.js';
3
+ /** What `comments.watch` gives: a new comment, or one the streamer deleted. */
4
+ export type ChatEvent = {
5
+ type: 'comment';
6
+ comment: Comment;
7
+ } | {
8
+ type: 'deleted';
9
+ uuid: string;
10
+ deletedAt: string;
11
+ };
12
+ export interface WatchOptions {
13
+ /** How often to read the chat, ms; 5000 by default (with deletions, 24 requests a minute of the key's 120). */
14
+ interval?: number;
15
+ /** Only comments from these kinds of platform. */
16
+ platformTypes?: readonly PlatformType[];
17
+ /** Give the chat's latest comments first (`historyLimit` of them); false by default: only new ones. */
18
+ includeHistory?: boolean;
19
+ /** How many latest comments the start reads; 100 by default. */
20
+ historyLimit?: number;
21
+ /** Also give `deleted` events; true by default. */
22
+ deletions?: boolean;
23
+ /** Stops the watch: the loop then rejects with the signal's reason. */
24
+ signal?: AbortSignal;
25
+ /**
26
+ * Called for an error the watch rides out: no answer, a server error, the
27
+ * request limit. It then tries again after a pause that doubles with each
28
+ * error in a row (from the interval, at least a second, up to a minute). Other errors (no scope, no stream, no
29
+ * chat in the tariff) end the watch.
30
+ */
31
+ onError?: (error: Error) => void;
32
+ }
33
+ /** The comment reads the watch makes: Comments' list and listDeleted. */
34
+ export interface ChatSource {
35
+ list(streamId: string, params?: CommentListParams, options?: RequestOptions): Promise<Comment[]>;
36
+ listDeleted(streamId: string, params?: DeletedCommentListParams, options?: RequestOptions): Promise<DeletedComment[]>;
37
+ }
38
+ /** The most a read takes: a full page means more are waiting. */
39
+ export declare const PAGE_LIMIT = 500;
40
+ /**
41
+ * An API without `after` (backend before the cursor by arrival) is read by
42
+ * `since`, the platforms' own times, which come late from the platforms read
43
+ * every 15–60 s: each read reaches this far back behind the newest.
44
+ */
45
+ export declare const SINCE_LOOKBACK_MS = 120000;
46
+ /**
47
+ * Follows a stream's chat: every new comment once, in the order StreamFarm
48
+ * got them, and the streamer's deletions. Rides out network and server
49
+ * errors; ends on others or when `signal` aborts.
50
+ */
51
+ export declare function watchChat(source: ChatSource, streamId: string, options?: WatchOptions): AsyncGenerator<ChatEvent, void, undefined>;
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SINCE_LOOKBACK_MS = exports.PAGE_LIMIT = void 0;
4
+ exports.watchChat = watchChat;
5
+ const errors_js_1 = require("./errors.js");
6
+ const http_js_1 = require("./http.js");
7
+ /** The most a read takes: a full page means more are waiting. */
8
+ exports.PAGE_LIMIT = 500;
9
+ /**
10
+ * An API without `after` (backend before the cursor by arrival) is read by
11
+ * `since`, the platforms' own times, which come late from the platforms read
12
+ * every 15–60 s: each read reaches this far back behind the newest.
13
+ */
14
+ exports.SINCE_LOOKBACK_MS = 120_000;
15
+ /** The shortest pause after an error: an interval of 0 mustn't turn an outage into a loop of requests. */
16
+ const MIN_ERROR_PAUSE_MS = 1000;
17
+ /** How far deletions are read back behind the last one: a deletion's write can become visible late. */
18
+ const DELETIONS_LOOKBACK_MS = 5000;
19
+ /** How many of the latest comments given a lost cursor falls back to. */
20
+ const CURSOR_FALLBACKS = 3;
21
+ /** The longest pause after errors in a row. */
22
+ const MAX_ERROR_PAUSE_MS = 60_000;
23
+ /** How long a comment given is remembered behind the newest: beyond the API's 5 s reach-back. */
24
+ const REMEMBER_MS = 60_000;
25
+ const time = (iso) => (iso ? Date.parse(iso) || 0 : 0);
26
+ const receivedAt = (comment) => comment.receivedAt;
27
+ /** The comment stored last: the API's order with `after` is receivedAt, then uuid. */
28
+ function lastStored(comments) {
29
+ let last;
30
+ for (const comment of comments) {
31
+ if (!last)
32
+ last = comment;
33
+ else {
34
+ const [a, b] = [time(receivedAt(comment)), time(receivedAt(last))];
35
+ if (a > b || (a === b && comment.uuid > last.uuid))
36
+ last = comment;
37
+ }
38
+ }
39
+ return last;
40
+ }
41
+ /**
42
+ * Follows a stream's chat: every new comment once, in the order StreamFarm
43
+ * got them, and the streamer's deletions. Rides out network and server
44
+ * errors; ends on others or when `signal` aborts.
45
+ */
46
+ async function* watchChat(source, streamId, options = {}) {
47
+ const { interval = 5000, platformTypes, includeHistory = false, historyLimit = 100, deletions = true, signal, onError } = options;
48
+ const request = { signal };
49
+ // Comments given, by uuid, with the time they are ordered by, and the newest of those times.
50
+ const given = new Map();
51
+ let newestGiven = 0;
52
+ // How to read on: by `after` (the API has it), by `since` (it hasn't), or not known yet (no comments seen).
53
+ let mode = 'unknown';
54
+ let cursor;
55
+ let newestPublished = 0;
56
+ let nextPageSince;
57
+ const deletedGiven = new Map();
58
+ let deletedCursor;
59
+ /** Picks how to read on from comments read: their receivedAt says the API has `after`. */
60
+ function settle(comments) {
61
+ if (!comments.length)
62
+ return;
63
+ if (comments.some((comment) => receivedAt(comment) !== undefined)) {
64
+ mode = 'after';
65
+ cursor = lastStored(comments)?.uuid;
66
+ }
67
+ else if (mode === 'unknown') {
68
+ mode = 'since';
69
+ }
70
+ }
71
+ /** The comments not given yet, remembered as given. */
72
+ function fresh(comments) {
73
+ const result = comments.filter((comment) => !given.has(comment.uuid));
74
+ for (const comment of result) {
75
+ const at = mode === 'after' ? time(receivedAt(comment)) : time(comment.publishedAt);
76
+ given.set(comment.uuid, at);
77
+ newestGiven = Math.max(newestGiven, at);
78
+ }
79
+ for (const comment of comments)
80
+ newestPublished = Math.max(newestPublished, time(comment.publishedAt));
81
+ // Forget what the next reads can't return.
82
+ const floor = newestGiven - (mode === 'after' ? REMEMBER_MS : exports.SINCE_LOOKBACK_MS + REMEMBER_MS);
83
+ for (const [uuid, at] of given)
84
+ if (at < floor)
85
+ given.delete(uuid);
86
+ return result;
87
+ }
88
+ /** The newest comments, as at the start: while the API's way is unknown or the cursor was lost. */
89
+ async function readLatest() {
90
+ const comments = await source.list(streamId, { limit: historyLimit, platformTypes }, request);
91
+ settle(comments);
92
+ return comments;
93
+ }
94
+ /** The next comments; `more`: a full page, read on at once. */
95
+ async function readComments() {
96
+ if (mode === 'after' && cursor) {
97
+ let page;
98
+ // The cursor's comment can go (its platform's connection was removed,
99
+ // or it outlived its keeping): then the latest comments given, newest
100
+ // first, are the cursor instead.
101
+ const fallbacks = [...given.entries()].filter(([uuid]) => uuid !== cursor)
102
+ .sort((a, b) => b[1] - a[1]).slice(0, CURSOR_FALLBACKS).map(([uuid]) => uuid);
103
+ for (const candidate of [cursor, ...fallbacks]) {
104
+ try {
105
+ page = await source.list(streamId, { after: candidate, limit: exports.PAGE_LIMIT, platformTypes }, request);
106
+ cursor = candidate;
107
+ break;
108
+ }
109
+ catch (error) {
110
+ if (!(error instanceof errors_js_1.ValidationError))
111
+ throw error;
112
+ }
113
+ }
114
+ if (!page) {
115
+ // None is left: the newest again, without those older than what was given.
116
+ const floor = newestGiven - REMEMBER_MS;
117
+ mode = 'unknown';
118
+ cursor = undefined;
119
+ const latest = await readLatest();
120
+ return { comments: fresh(latest.filter((comment) => time(receivedAt(comment)) >= floor)), more: false };
121
+ }
122
+ // The answer: comments stored up to 5 s before the cursor, the cursor,
123
+ // then up to PAGE_LIMIT stored after it. Its last is the next cursor.
124
+ const at = page.findIndex((comment) => comment.uuid === cursor);
125
+ const later = at >= 0 ? page.length - at - 1 : page.length;
126
+ const comments = fresh(page);
127
+ if (page.length)
128
+ cursor = page[page.length - 1].uuid;
129
+ return { comments, more: later >= exports.PAGE_LIMIT };
130
+ }
131
+ if (mode === 'since') {
132
+ const since = nextPageSince ?? new Date(Math.max(0, newestPublished - exports.SINCE_LOOKBACK_MS)).toISOString();
133
+ const page = await source.list(streamId, { since, limit: exports.PAGE_LIMIT, platformTypes }, request);
134
+ const full = page.length === exports.PAGE_LIMIT;
135
+ nextPageSince = undefined;
136
+ if (full) {
137
+ // Comments of the page's last millisecond may not all have fit: the
138
+ // next page starts a millisecond before it, unless this page started
139
+ // there too (a whole page of one millisecond).
140
+ const last = time(page[page.length - 1].publishedAt);
141
+ nextPageSince = new Date(last - 1 > time(since) ? last - 1 : last).toISOString();
142
+ }
143
+ // Comments with receivedAt: the API has `after` now (it was updated meanwhile).
144
+ if (page.some((comment) => receivedAt(comment) !== undefined))
145
+ settle(page);
146
+ return { comments: fresh(page), more: full };
147
+ }
148
+ return { comments: fresh(await readLatest()), more: false };
149
+ }
150
+ async function readDeletions() {
151
+ // Read back a little behind the last deletion (those given are dropped):
152
+ // two in one millisecond across a page, or a write visible late.
153
+ const since = deletedCursor ? new Date(time(deletedCursor) - DELETIONS_LOOKBACK_MS).toISOString() : undefined;
154
+ const page = await source.listDeleted(streamId, since ? { since, limit: exports.PAGE_LIMIT } : { limit: 100 }, request);
155
+ const deleted = page.filter((row) => !deletedGiven.has(row.uuid));
156
+ for (const row of page) {
157
+ deletedGiven.set(row.uuid, time(row.deletedAt));
158
+ if (!deletedCursor || time(row.deletedAt) > time(deletedCursor))
159
+ deletedCursor = row.deletedAt;
160
+ }
161
+ const floor = time(deletedCursor) - REMEMBER_MS;
162
+ for (const [uuid, at] of deletedGiven)
163
+ if (at < floor)
164
+ deletedGiven.delete(uuid);
165
+ return { deleted, more: page.length === exports.PAGE_LIMIT && deleted.length > 0 };
166
+ }
167
+ // The start in steps, so that a step that failed is the only one done again.
168
+ let history;
169
+ let deletionsStarted = !deletions;
170
+ let started = false;
171
+ // Errors ridden out in a row: the pause after each doubles, up to a minute.
172
+ let failures = 0;
173
+ for (;;) {
174
+ const events = [];
175
+ let more = false;
176
+ let pause = interval;
177
+ try {
178
+ if (!started) {
179
+ if (!history) {
180
+ history = await readLatest();
181
+ fresh(history);
182
+ }
183
+ if (!deletionsStarted) {
184
+ await readDeletions();
185
+ deletionsStarted = true;
186
+ }
187
+ started = true;
188
+ if (includeHistory)
189
+ for (const comment of history)
190
+ events.push({ type: 'comment', comment });
191
+ }
192
+ else {
193
+ const read = await readComments();
194
+ more = read.more;
195
+ for (const comment of read.comments)
196
+ events.push({ type: 'comment', comment });
197
+ if (deletions) {
198
+ const gone = await readDeletions();
199
+ more ||= gone.more;
200
+ for (const { uuid, deletedAt } of gone.deleted)
201
+ events.push({ type: 'deleted', uuid, deletedAt });
202
+ }
203
+ }
204
+ failures = 0;
205
+ }
206
+ catch (error) {
207
+ if (signal?.aborted)
208
+ throw signal.reason;
209
+ const ridden = error instanceof errors_js_1.ConnectionError || error instanceof errors_js_1.ServerError || error instanceof errors_js_1.RateLimitError;
210
+ if (!ridden)
211
+ throw error;
212
+ onError?.(error);
213
+ more = false;
214
+ failures++;
215
+ pause = Math.min(MAX_ERROR_PAUSE_MS, Math.max(MIN_ERROR_PAUSE_MS, interval) * 2 ** failures);
216
+ if (error instanceof errors_js_1.RateLimitError)
217
+ pause = Math.max(pause, (error.retryAfter ?? 1) * 1000);
218
+ }
219
+ for (const event of events)
220
+ yield event;
221
+ if (!more)
222
+ await (0, http_js_1.sleep)(pause, signal);
223
+ }
224
+ }
@@ -0,0 +1,44 @@
1
+ import { type ClientOptions, type HttpMethod, type QueryValue, type RequestOptions } from './http.js';
2
+ import { Account, Broadcasts, Connections, Regions, Stats } from './resources/account.js';
3
+ import { AdOverlay, Ads } from './resources/ads.js';
4
+ import { Comments } from './resources/comments.js';
5
+ import { Platforms } from './resources/platforms.js';
6
+ import { Streams } from './resources/streams.js';
7
+ import { Studio } from './resources/studio.js';
8
+ import type { ApiKeyInfo } from './types.js';
9
+ /**
10
+ * The StreamFarm public API client.
11
+ *
12
+ * ```ts
13
+ * const sf = new StreamFarm(); // the key from STREAMFARM_API_KEY
14
+ * const streams = await sf.streams.list();
15
+ * ```
16
+ */
17
+ export declare class StreamFarm {
18
+ readonly streams: Streams;
19
+ readonly platforms: Platforms;
20
+ readonly ads: Ads;
21
+ readonly overlay: AdOverlay;
22
+ readonly comments: Comments;
23
+ readonly studio: Studio;
24
+ readonly regions: Regions;
25
+ readonly connections: Connections;
26
+ readonly stats: Stats;
27
+ readonly broadcasts: Broadcasts;
28
+ readonly account: Account;
29
+ private readonly transport;
30
+ constructor(options?: ClientOptions);
31
+ /** The API's base URL the client works with. */
32
+ get baseUrl(): string;
33
+ /** The key the client works with: its name, scopes, streams and expiry. Any key may read it. */
34
+ keyInfo(options?: RequestOptions): Promise<ApiKeyInfo>;
35
+ /**
36
+ * Any request to the API, for what this version of the SDK doesn't know
37
+ * yet: the answer as the API sends it, with the SDK's key, retries and
38
+ * errors. `path` is under the base URL: `/streams/<id>/…`.
39
+ */
40
+ request<T = unknown>(method: HttpMethod, path: string, init?: {
41
+ query?: Record<string, QueryValue>;
42
+ body?: unknown;
43
+ }, options?: RequestOptions): Promise<T>;
44
+ }