@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
@@ -0,0 +1,6 @@
1
+ // Generated from spec/openapi.json by `npm run spec:types` (openapi-typescript). Do not edit.
2
+ /**
3
+ * This file was auto-generated by openapi-typescript.
4
+ * Do not make direct changes to the file.
5
+ */
6
+ export {};
@@ -0,0 +1,81 @@
1
+ import { type RateLimit } from './errors.js';
2
+ export declare const DEFAULT_BASE_URL = "https://api.streamfarm.ru/api/public/v1";
3
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
4
+ export declare const DEFAULT_MAX_RETRIES = 2;
5
+ /** A 429 asking to wait longer than this is thrown at once instead of waited out. */
6
+ export declare const MAX_RETRY_AFTER_SEC = 60;
7
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
8
+ /** What every request reports when its answer comes: for logs and metrics. */
9
+ export interface ResponseInfo {
10
+ method: HttpMethod;
11
+ /** The path under the base URL, without the query. */
12
+ path: string;
13
+ status: number;
14
+ /** 0 for the first try, 1 for the first retry, … */
15
+ attempt: number;
16
+ durationMs: number;
17
+ correlationId: string | null;
18
+ rateLimit: RateLimit | null;
19
+ }
20
+ export interface ClientOptions {
21
+ /** The API key, `sf_…`. By default STREAMFARM_API_KEY from the environment. */
22
+ apiKey?: string;
23
+ /** By default https://api.streamfarm.ru/api/public/v1; a local stack: http://localhost:3001/api/public/v1. */
24
+ baseUrl?: string;
25
+ /** Milliseconds a request may take, its answer read included; 0 for none. 30 000 by default. */
26
+ timeout?: number;
27
+ /** How many times a failed request is retried (see README, «Повторы»). 2 by default. */
28
+ maxRetries?: number;
29
+ /** A fetch of your own: a proxy, a test double, another runtime's. */
30
+ fetch?: typeof fetch;
31
+ /** Added to the User-Agent, e.g. `my-bot/1.2`. */
32
+ userAgent?: string;
33
+ /** Called on every answer, retries included. Errors it throws are ignored. */
34
+ onResponse?: (info: ResponseInfo) => void;
35
+ }
36
+ /** Options of a single call, the last argument of every method. */
37
+ export interface RequestOptions {
38
+ /** Aborts the call: it then rejects with the signal's reason. */
39
+ signal?: AbortSignal;
40
+ /** This call's timeout in milliseconds, instead of the client's. */
41
+ timeout?: number;
42
+ /** This call's retries, instead of the client's. */
43
+ maxRetries?: number;
44
+ }
45
+ export type QueryValue = string | number | boolean | Date | readonly string[] | null | undefined;
46
+ export interface RequestSpec {
47
+ method: HttpMethod;
48
+ /** Under the base URL, starting with `/`; ids already encoded. */
49
+ path: string;
50
+ query?: Record<string, QueryValue>;
51
+ /** Sent as JSON; undefined: no body. */
52
+ body?: unknown;
53
+ /**
54
+ * A DELETE answered with 204: a 404 on a retry after a try that got no
55
+ * answer means that try deleted it, so the call is done.
56
+ */
57
+ goneIsDone?: boolean;
58
+ }
59
+ /** The client's transport: one fetch per try, retries, timeouts and errors. */
60
+ export declare class Transport {
61
+ #private;
62
+ readonly baseUrl: string;
63
+ private readonly timeout;
64
+ private readonly maxRetries;
65
+ private readonly fetchImpl;
66
+ private readonly userAgent;
67
+ private readonly onResponse;
68
+ constructor(options: ClientOptions);
69
+ request<T>(spec: RequestSpec, options?: RequestOptions): Promise<T>;
70
+ private once;
71
+ private report;
72
+ }
73
+ export declare function queryString(query: Record<string, QueryValue> | undefined): string;
74
+ /** Waits `ms`, or rejects with the signal's reason once it aborts. */
75
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
76
+ /**
77
+ * A path segment from an id: required, and encoded (a studio participant's
78
+ * identity is free text). `.` and `..` are refused: URLs resolve them, so
79
+ * `ads.delete(streamId, '..')` would become a DELETE of the stream.
80
+ */
81
+ export declare function segment(value: string, name: string): string;
@@ -0,0 +1,297 @@
1
+ import { ConnectionError, NotFoundError, RateLimitError, ServerError, StreamFarmError, TimeoutError, apiErrorFor, } from './errors.js';
2
+ import { VERSION } from './version.js';
3
+ export const DEFAULT_BASE_URL = 'https://api.streamfarm.ru/api/public/v1';
4
+ export const DEFAULT_TIMEOUT_MS = 30_000;
5
+ export const DEFAULT_MAX_RETRIES = 2;
6
+ /** A 429 asking to wait longer than this is thrown at once instead of waited out. */
7
+ export const MAX_RETRY_AFTER_SEC = 60;
8
+ // Methods whose request may be repeated after a failure without doing twice
9
+ // what it does: a POST or PATCH that failed on the server may have shown the
10
+ // ad or banned the author already.
11
+ const IDEMPOTENT = new Set(['GET', 'PUT', 'DELETE']);
12
+ // 502s worth another try: something didn't answer. Not the platforms'
13
+ // refusals and quotas: another try gets the same answer.
14
+ const RETRYABLE_502 = new Set(['core_unavailable', 'platform_unavailable', 'studio_server_unavailable', 'http_error']);
15
+ /** The client's transport: one fetch per try, retries, timeouts and errors. */
16
+ export class Transport {
17
+ baseUrl;
18
+ // A true private field: console.log, util.inspect and JSON.stringify of the
19
+ // client don't show it (a TypeScript `private` would be a plain property).
20
+ #authorization;
21
+ #apiKey;
22
+ timeout;
23
+ maxRetries;
24
+ fetchImpl;
25
+ userAgent;
26
+ onResponse;
27
+ constructor(options) {
28
+ const apiKey = options.apiKey ?? envApiKey();
29
+ if (!apiKey) {
30
+ throw new StreamFarmError('No API key: pass `apiKey` or set STREAMFARM_API_KEY');
31
+ }
32
+ // Printable ASCII only: anything else can't go into a header, and fetch
33
+ // would put the whole key into its error.
34
+ if (!/^[\x21-\x7e]+$/.test(apiKey))
35
+ throw new StreamFarmError('The API key must be printable ASCII without spaces: sf_…');
36
+ this.#apiKey = apiKey;
37
+ this.#authorization = `Bearer ${apiKey}`;
38
+ const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, '');
39
+ try {
40
+ new URL(baseUrl);
41
+ }
42
+ catch {
43
+ throw new StreamFarmError(`baseUrl isn't a URL: ${baseUrl}`);
44
+ }
45
+ this.baseUrl = baseUrl;
46
+ this.timeout = nonNegative(options.timeout, DEFAULT_TIMEOUT_MS, 'timeout');
47
+ this.maxRetries = nonNegative(options.maxRetries, DEFAULT_MAX_RETRIES, 'maxRetries');
48
+ const fetchImpl = options.fetch ?? globalThis.fetch;
49
+ if (typeof fetchImpl !== 'function') {
50
+ throw new StreamFarmError('No fetch in this runtime: pass `fetch` (Node 20+ has one)');
51
+ }
52
+ // Called on its own, not as the transport's method: a browser's or a
53
+ // Worker's fetch throws "Illegal invocation" with another `this`.
54
+ this.fetchImpl = (input, init) => fetchImpl(input, init);
55
+ if (options.userAgent !== undefined && !/^[\x20-\x7e]*$/.test(options.userAgent)) {
56
+ throw new StreamFarmError('userAgent must be printable ASCII');
57
+ }
58
+ this.userAgent = [`streamfarm-node/${VERSION}`, options.userAgent].filter(Boolean).join(' ');
59
+ this.onResponse = options.onResponse;
60
+ }
61
+ async request(spec, options = {}) {
62
+ const maxRetries = nonNegative(options.maxRetries, this.maxRetries, 'maxRetries');
63
+ let unanswered = false;
64
+ for (let attempt = 0;; attempt++) {
65
+ try {
66
+ return await this.once(spec, options, attempt);
67
+ }
68
+ catch (error) {
69
+ if (spec.goneIsDone && unanswered && error instanceof NotFoundError)
70
+ return undefined;
71
+ unanswered ||= error instanceof ConnectionError;
72
+ const wait = attempt < maxRetries ? retryDelay(error, spec.method, attempt) : null;
73
+ if (wait === null)
74
+ throw error;
75
+ await sleep(wait, options.signal);
76
+ }
77
+ }
78
+ }
79
+ async once(spec, options, attempt) {
80
+ const url = this.baseUrl + spec.path + queryString(spec.query);
81
+ const headers = {
82
+ Authorization: this.#authorization,
83
+ Accept: 'application/json',
84
+ 'User-Agent': this.userAgent,
85
+ };
86
+ let body;
87
+ if (spec.body !== undefined) {
88
+ headers['Content-Type'] = 'application/json';
89
+ body = JSON.stringify(spec.body);
90
+ }
91
+ const timeout = nonNegative(options.timeout, this.timeout, 'timeout');
92
+ const abort = abortWithin(options.signal, timeout);
93
+ const started = Date.now();
94
+ try {
95
+ let res;
96
+ try {
97
+ res = await this.fetchImpl(url, { method: spec.method, headers, body, signal: abort.signal });
98
+ }
99
+ catch (error) {
100
+ throw this.#redacted(abort.failure(error, spec));
101
+ }
102
+ const correlationId = res.headers.get('x-correlation-id');
103
+ const rateLimit = readRateLimit(res.headers);
104
+ let text;
105
+ try {
106
+ text = await res.text();
107
+ }
108
+ catch (error) {
109
+ throw this.#redacted(abort.failure(error, spec));
110
+ }
111
+ this.report({
112
+ method: spec.method, path: spec.path, status: res.status, attempt, durationMs: Date.now() - started, correlationId, rateLimit,
113
+ });
114
+ const context = { method: spec.method, path: spec.path, correlationId, rateLimit };
115
+ if (!res.ok)
116
+ throw errorFromAnswer(res, text, context);
117
+ if (res.status === 204 || text === '')
118
+ return undefined;
119
+ try {
120
+ return JSON.parse(text);
121
+ }
122
+ catch {
123
+ throw apiErrorFor({ status: res.status, code: 'http_error', message: 'The answer is not JSON', ...context });
124
+ }
125
+ }
126
+ finally {
127
+ abort.dispose();
128
+ }
129
+ }
130
+ /** An error of ours with the key taken out of its message, should a runtime's error have quoted it. */
131
+ #redacted(error) {
132
+ if (error instanceof StreamFarmError && error.message.includes(this.#apiKey)) {
133
+ error.message = error.message.split(this.#apiKey).join('sf_…');
134
+ }
135
+ return error;
136
+ }
137
+ report(info) {
138
+ if (!this.onResponse)
139
+ return;
140
+ try {
141
+ this.onResponse(info);
142
+ }
143
+ catch {
144
+ // A logging hook must not break the request.
145
+ }
146
+ }
147
+ }
148
+ function envApiKey() {
149
+ // Not every runtime has process (Cloudflare Workers, browsers).
150
+ const env = globalThis.process?.env;
151
+ return env?.STREAMFARM_API_KEY || undefined;
152
+ }
153
+ function nonNegative(value, fallback, name) {
154
+ if (value === undefined)
155
+ return fallback;
156
+ if (!Number.isFinite(value) || value < 0)
157
+ throw new StreamFarmError(`${name} must be a number ≥ 0`);
158
+ return value;
159
+ }
160
+ export function queryString(query) {
161
+ if (!query)
162
+ return '';
163
+ const params = new URLSearchParams();
164
+ for (const [name, value] of Object.entries(query)) {
165
+ if (value === undefined || value === null)
166
+ continue;
167
+ if (value instanceof Date)
168
+ params.set(name, value.toISOString());
169
+ else if (Array.isArray(value)) {
170
+ if (value.length)
171
+ params.set(name, value.join(','));
172
+ }
173
+ else
174
+ params.set(name, String(value));
175
+ }
176
+ const text = params.toString();
177
+ return text ? `?${text}` : '';
178
+ }
179
+ function readRateLimit(headers) {
180
+ const limit = headers.get('x-ratelimit-limit');
181
+ if (limit === null)
182
+ return null;
183
+ return {
184
+ limit: Number(limit),
185
+ remaining: Number(headers.get('x-ratelimit-remaining') ?? 0),
186
+ resetSec: Number(headers.get('x-ratelimit-reset') ?? 0),
187
+ };
188
+ }
189
+ /** Seconds from Retry-After: a number of seconds or an HTTP date. */
190
+ function retryAfterSec(headers) {
191
+ const value = headers.get('retry-after');
192
+ if (value === null || value.trim() === '')
193
+ return null;
194
+ const seconds = Number(value);
195
+ if (Number.isFinite(seconds))
196
+ return Math.max(0, seconds);
197
+ const date = Date.parse(value);
198
+ return Number.isNaN(date) ? null : Math.max(0, Math.ceil((date - Date.now()) / 1000));
199
+ }
200
+ function errorFromAnswer(res, text, context) {
201
+ let code = 'http_error';
202
+ let message = `HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ''}`;
203
+ let details;
204
+ try {
205
+ const parsed = JSON.parse(text);
206
+ if (parsed?.error && typeof parsed.error.code === 'string') {
207
+ code = parsed.error.code;
208
+ if (typeof parsed.error.message === 'string')
209
+ message = parsed.error.message;
210
+ details = parsed.error.details;
211
+ }
212
+ }
213
+ catch {
214
+ // Not the API's JSON: a proxy's page. The status says enough.
215
+ }
216
+ return apiErrorFor({ status: res.status, code, message, details, ...context, retryAfter: retryAfterSec(res.headers) });
217
+ }
218
+ /** How long to wait before retrying after `error`; null: don't retry. */
219
+ function retryDelay(error, method, attempt) {
220
+ // Over the limit, the API refused before doing anything: any method may go again.
221
+ if (error instanceof RateLimitError) {
222
+ const seconds = error.retryAfter ?? 1;
223
+ if (seconds > MAX_RETRY_AFTER_SEC)
224
+ return null;
225
+ return seconds * 1000 + Math.random() * 250;
226
+ }
227
+ if (!IDEMPOTENT.has(method))
228
+ return null;
229
+ const retryable = error instanceof ConnectionError
230
+ || (error instanceof ServerError
231
+ && (error.status === 503 || error.status === 504 || (error.status === 502 && RETRYABLE_502.has(error.code))));
232
+ if (!retryable)
233
+ return null;
234
+ const base = Math.min(8000, 500 * 2 ** attempt);
235
+ return base * (0.75 + Math.random() * 0.5);
236
+ }
237
+ /** An AbortSignal for one try: the caller's signal or the timeout, whichever comes first. */
238
+ function abortWithin(signal, timeoutMs) {
239
+ const controller = new AbortController();
240
+ let timedOut = false;
241
+ const timer = timeoutMs > 0
242
+ ? setTimeout(() => {
243
+ timedOut = true;
244
+ controller.abort();
245
+ }, timeoutMs)
246
+ : undefined;
247
+ const onAbort = () => controller.abort(signal?.reason);
248
+ if (signal?.aborted)
249
+ controller.abort(signal.reason);
250
+ else
251
+ signal?.addEventListener('abort', onAbort, { once: true });
252
+ return {
253
+ signal: controller.signal,
254
+ /** What to throw for an error of fetch or of reading the answer. */
255
+ failure(error, spec) {
256
+ if (timedOut)
257
+ return new TimeoutError(`No answer within ${timeoutMs} ms (${spec.method} ${spec.path})`, { cause: error });
258
+ // The caller aborted: their reason, as fetch does.
259
+ if (signal?.aborted)
260
+ return signal.reason;
261
+ return new ConnectionError(`The request failed: ${error?.message ?? error} (${spec.method} ${spec.path})`, { cause: error });
262
+ },
263
+ dispose() {
264
+ if (timer)
265
+ clearTimeout(timer);
266
+ signal?.removeEventListener('abort', onAbort);
267
+ },
268
+ };
269
+ }
270
+ /** Waits `ms`, or rejects with the signal's reason once it aborts. */
271
+ export function sleep(ms, signal) {
272
+ if (signal?.aborted)
273
+ return Promise.reject(signal.reason);
274
+ return new Promise((resolve, reject) => {
275
+ const onAbort = () => {
276
+ clearTimeout(timer);
277
+ reject(signal?.reason);
278
+ };
279
+ const timer = setTimeout(() => {
280
+ signal?.removeEventListener('abort', onAbort);
281
+ resolve();
282
+ }, ms);
283
+ signal?.addEventListener('abort', onAbort, { once: true });
284
+ });
285
+ }
286
+ /**
287
+ * A path segment from an id: required, and encoded (a studio participant's
288
+ * identity is free text). `.` and `..` are refused: URLs resolve them, so
289
+ * `ads.delete(streamId, '..')` would become a DELETE of the stream.
290
+ */
291
+ export function segment(value, name) {
292
+ if (typeof value !== 'string' || value === '')
293
+ throw new StreamFarmError(`${name} is required`);
294
+ if (value === '.' || value === '..')
295
+ throw new StreamFarmError(`${name} can't be "${value}"`);
296
+ return encodeURIComponent(value);
297
+ }
@@ -0,0 +1,10 @@
1
+ export { StreamFarm } from './client.js';
2
+ export type { ClientOptions, RequestOptions, ResponseInfo, HttpMethod, QueryValue } from './http.js';
3
+ export { DEFAULT_BASE_URL } from './http.js';
4
+ export { StreamFarmError, ApiError, AuthenticationError, PermissionError, NotFoundError, ConflictError, ValidationError, RateLimitError, ServerError, ConnectionError, TimeoutError, WaitTimeoutError, } from './errors.js';
5
+ export type { ErrorCode, RateLimit } from './errors.js';
6
+ export type { ChatEvent, WatchOptions } from './chat.js';
7
+ export type { WaitUntilLiveOptions } from './resources/streams.js';
8
+ export type * from './types.js';
9
+ export type { components, operations, paths } from './generated/openapi.js';
10
+ export { VERSION } from './version.js';
@@ -0,0 +1,4 @@
1
+ export { StreamFarm } from './client.js';
2
+ export { DEFAULT_BASE_URL } from './http.js';
3
+ export { StreamFarmError, ApiError, AuthenticationError, PermissionError, NotFoundError, ConflictError, ValidationError, RateLimitError, ServerError, ConnectionError, TimeoutError, WaitTimeoutError, } from './errors.js';
4
+ export { VERSION } from './version.js';
@@ -0,0 +1,9 @@
1
+ import type { Page } from './types.js';
2
+ /**
3
+ * Every item of a paged list, page by page. The lists are newest first, so
4
+ * a stream made while they are read moves the rest one place down: an item
5
+ * met twice is given once.
6
+ */
7
+ export declare function paginate<T extends {
8
+ uuid: string;
9
+ }>(fetchPage: (page: number) => Promise<Page<T>>): AsyncGenerator<T, void, undefined>;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Every item of a paged list, page by page. The lists are newest first, so
3
+ * a stream made while they are read moves the rest one place down: an item
4
+ * met twice is given once.
5
+ */
6
+ export async function* paginate(fetchPage) {
7
+ const seen = new Set();
8
+ for (let page = 1;; page++) {
9
+ const { items, pagination } = await fetchPage(page);
10
+ for (const item of items) {
11
+ if (seen.has(item.uuid))
12
+ continue;
13
+ seen.add(item.uuid);
14
+ yield item;
15
+ }
16
+ if (items.length === 0 || page >= pagination.pages)
17
+ return;
18
+ }
19
+ }
@@ -0,0 +1,32 @@
1
+ import type { RequestOptions } from '../http.js';
2
+ import type { Broadcast, BroadcastListParams, Connection, Page, PageParams, Payment, Plan, Region, Stats as StatsReport, StatsParams } from '../types.js';
3
+ import { Resource } from './base.js';
4
+ /** The regions a stream can be made in. Any key may read them. */
5
+ export declare class Regions extends Resource {
6
+ list(options?: RequestOptions): Promise<Region[]>;
7
+ }
8
+ /** The account's social network connections (`connections:read`). */
9
+ export declare class Connections extends Resource {
10
+ /** Which platforms can be added without a server and key. */
11
+ list(options?: RequestOptions): Promise<Connection[]>;
12
+ }
13
+ /** Time on air, traffic and broadcasts (`streams:read`). */
14
+ export declare class Stats extends Resource {
15
+ /** A period's totals, by day or month. */
16
+ get(params?: StatsParams, options?: RequestOptions): Promise<StatsReport>;
17
+ }
18
+ /** The broadcast history, newest first (`streams:read`). */
19
+ export declare class Broadcasts extends Resource {
20
+ list(params?: BroadcastListParams, options?: RequestOptions): Promise<Page<Broadcast>>;
21
+ /** Every broadcast that fits, page after page. */
22
+ all(params?: Omit<BroadcastListParams, 'page'>, options?: RequestOptions): AsyncGenerator<Broadcast, void, undefined>;
23
+ }
24
+ /** The account's tariff and payments (`billing:read`). */
25
+ export declare class Account extends Resource {
26
+ /** Its add-ons, limits and how much of them is used, what is on sale. */
27
+ plan(options?: RequestOptions): Promise<Plan>;
28
+ /** A page of payments, newest first. */
29
+ payments(params?: PageParams, options?: RequestOptions): Promise<Page<Payment>>;
30
+ /** Every payment, page after page. */
31
+ allPayments(params?: Omit<PageParams, 'page'>, options?: RequestOptions): AsyncGenerator<Payment, void, undefined>;
32
+ }
@@ -0,0 +1,50 @@
1
+ import { paginate } from '../pagination.js';
2
+ import { Resource } from './base.js';
3
+ /** The regions a stream can be made in. Any key may read them. */
4
+ export class Regions extends Resource {
5
+ async list(options) {
6
+ return this.items({ method: 'GET', path: '/regions' }, options);
7
+ }
8
+ }
9
+ /** The account's social network connections (`connections:read`). */
10
+ export class Connections extends Resource {
11
+ /** Which platforms can be added without a server and key. */
12
+ async list(options) {
13
+ return this.items({ method: 'GET', path: '/connections' }, options);
14
+ }
15
+ }
16
+ /** Time on air, traffic and broadcasts (`streams:read`). */
17
+ export class Stats extends Resource {
18
+ /** A period's totals, by day or month. */
19
+ async get(params = {}, options) {
20
+ const { from, to, interval, timeZone, streamUuid } = params;
21
+ return this.item({ method: 'GET', path: '/stats', query: { from, to, interval, timeZone, streamUuid } }, options);
22
+ }
23
+ }
24
+ /** The broadcast history, newest first (`streams:read`). */
25
+ export class Broadcasts extends Resource {
26
+ async list(params = {}, options) {
27
+ const { page, size, streamUuid, from, to } = params;
28
+ return this.transport.request({ method: 'GET', path: '/broadcasts', query: { page, size, streamUuid, from, to } }, options);
29
+ }
30
+ /** Every broadcast that fits, page after page. */
31
+ all(params = {}, options) {
32
+ return paginate((page) => this.list({ ...params, page }, options));
33
+ }
34
+ }
35
+ /** The account's tariff and payments (`billing:read`). */
36
+ export class Account extends Resource {
37
+ /** Its add-ons, limits and how much of them is used, what is on sale. */
38
+ async plan(options) {
39
+ return this.item({ method: 'GET', path: '/account/plan' }, options);
40
+ }
41
+ /** A page of payments, newest first. */
42
+ async payments(params = {}, options) {
43
+ const { page, size } = params;
44
+ return this.transport.request({ method: 'GET', path: '/account/payments', query: { page, size } }, options);
45
+ }
46
+ /** Every payment, page after page. */
47
+ allPayments(params = {}, options) {
48
+ return paginate((page) => this.payments({ ...params, page }, options));
49
+ }
50
+ }
@@ -0,0 +1,25 @@
1
+ import { type RequestOptions } from '../http.js';
2
+ import type { Ad, AdCreateParams, AdUpdateParams, Overlay, OverlayShowParams } from '../types.js';
3
+ import { Resource } from './base.js';
4
+ /** A stream's ads (with the advertiser and ERID the law asks for). */
5
+ export declare class Ads extends Resource {
6
+ list(streamId: string, options?: RequestOptions): Promise<Ad[]>;
7
+ /** Adds an ad, off air (`ads:write`). To show it, it needs `advertiser` and `erid`. */
8
+ create(streamId: string, params: AdCreateParams, options?: RequestOptions): Promise<Ad>;
9
+ /** Changes the given fields; `null` clears the advertiser or the ERID (`ads:write`). */
10
+ update(streamId: string, adId: string, params: AdUpdateParams, options?: RequestOptions): Promise<Ad>;
11
+ /** Deletes an ad that isn't on air: hide it first, or ConflictError `ad_on_air` (`ads:write`). */
12
+ delete(streamId: string, adId: string, options?: RequestOptions): Promise<void>;
13
+ }
14
+ /** The ad overlay of a live, transcoded stream. */
15
+ export declare class AdOverlay extends Resource {
16
+ /** The ad on air and how long it has left (`ads:read`). */
17
+ get(streamId: string, options?: RequestOptions): Promise<Overlay>;
18
+ /**
19
+ * Puts an ad on air for `durationSec` (by default the ad's own) (`overlay:write`).
20
+ * The stream must be live and transcoded, with paid promotion on.
21
+ */
22
+ show(streamId: string, params: OverlayShowParams, options?: RequestOptions): Promise<Overlay>;
23
+ /** Takes the ad off air; nothing on air is fine too (`overlay:write`). */
24
+ hide(streamId: string, options?: RequestOptions): Promise<Overlay>;
25
+ }
@@ -0,0 +1,41 @@
1
+ import { segment } from '../http.js';
2
+ import { Resource } from './base.js';
3
+ const adsPath = (streamId, adId) => `/streams/${segment(streamId, 'streamId')}/ads`
4
+ + (adId === undefined ? '' : `/${segment(adId, 'adId')}`);
5
+ /** A stream's ads (with the advertiser and ERID the law asks for). */
6
+ export class Ads extends Resource {
7
+ async list(streamId, options) {
8
+ return this.items({ method: 'GET', path: adsPath(streamId) }, options);
9
+ }
10
+ /** Adds an ad, off air (`ads:write`). To show it, it needs `advertiser` and `erid`. */
11
+ async create(streamId, params, options) {
12
+ return this.item({ method: 'POST', path: adsPath(streamId), body: params }, options);
13
+ }
14
+ /** Changes the given fields; `null` clears the advertiser or the ERID (`ads:write`). */
15
+ async update(streamId, adId, params, options) {
16
+ return this.item({ method: 'PATCH', path: adsPath(streamId, adId), body: params }, options);
17
+ }
18
+ /** Deletes an ad that isn't on air: hide it first, or ConflictError `ad_on_air` (`ads:write`). */
19
+ async delete(streamId, adId, options) {
20
+ return this.none({ method: 'DELETE', path: adsPath(streamId, adId) }, options);
21
+ }
22
+ }
23
+ const overlayPath = (streamId) => `/streams/${segment(streamId, 'streamId')}/overlay`;
24
+ /** The ad overlay of a live, transcoded stream. */
25
+ export class AdOverlay extends Resource {
26
+ /** The ad on air and how long it has left (`ads:read`). */
27
+ async get(streamId, options) {
28
+ return this.item({ method: 'GET', path: overlayPath(streamId) }, options);
29
+ }
30
+ /**
31
+ * Puts an ad on air for `durationSec` (by default the ad's own) (`overlay:write`).
32
+ * The stream must be live and transcoded, with paid promotion on.
33
+ */
34
+ async show(streamId, params, options) {
35
+ return this.item({ method: 'POST', path: `${overlayPath(streamId)}/show`, body: params }, options);
36
+ }
37
+ /** Takes the ad off air; nothing on air is fine too (`overlay:write`). */
38
+ async hide(streamId, options) {
39
+ return this.item({ method: 'POST', path: `${overlayPath(streamId)}/hide` }, options);
40
+ }
41
+ }
@@ -0,0 +1,12 @@
1
+ import type { RequestOptions, RequestSpec, Transport } from '../http.js';
2
+ /** A part of the API: its methods share the client's transport. */
3
+ export declare abstract class Resource {
4
+ protected readonly transport: Transport;
5
+ constructor(transport: Transport);
6
+ /** The answer's `item`. */
7
+ protected item<T>(spec: RequestSpec, options?: RequestOptions): Promise<T>;
8
+ /** The answer's `items`. */
9
+ protected items<T>(spec: RequestSpec, options?: RequestOptions): Promise<T[]>;
10
+ /** A request answered with 204 and no body; a DELETE gone on a retry is done. */
11
+ protected none(spec: RequestSpec, options?: RequestOptions): Promise<void>;
12
+ }
@@ -0,0 +1,19 @@
1
+ /** A part of the API: its methods share the client's transport. */
2
+ export class Resource {
3
+ transport;
4
+ constructor(transport) {
5
+ this.transport = transport;
6
+ }
7
+ /** The answer's `item`. */
8
+ async item(spec, options) {
9
+ return (await this.transport.request(spec, options)).item;
10
+ }
11
+ /** The answer's `items`. */
12
+ async items(spec, options) {
13
+ return (await this.transport.request(spec, options)).items;
14
+ }
15
+ /** A request answered with 204 and no body; a DELETE gone on a retry is done. */
16
+ async none(spec, options) {
17
+ await this.transport.request({ ...spec, goneIsDone: spec.method === 'DELETE' }, options);
18
+ }
19
+ }
@@ -0,0 +1,27 @@
1
+ import { type ChatEvent, type WatchOptions } from '../chat.js';
2
+ import { type RequestOptions } from '../http.js';
3
+ import type { Comment, CommentBanParams, CommentCountParams, CommentCounts, CommentListParams, DeletedComment, DeletedCommentListParams } from '../types.js';
4
+ import { Resource } from './base.js';
5
+ /** A stream's chat: comments from every platform. The unified chat comes with the Pro tariff. */
6
+ export declare class Comments extends Resource {
7
+ /**
8
+ * Comments, oldest first (`comments:read`). Without `after` or `since`,
9
+ * the latest `limit`. To follow the chat, use `watch`, or pass the last
10
+ * comment's `uuid` as `after` and drop the ones you have.
11
+ */
12
+ list(streamId: string, params?: CommentListParams, options?: RequestOptions): Promise<Comment[]>;
13
+ /** Comments the streamer deleted, to drop them from a copy of the chat (`comments:read`). */
14
+ listDeleted(streamId: string, params?: DeletedCommentListParams, options?: RequestOptions): Promise<DeletedComment[]>;
15
+ /** How many comments the chat has, in all and by kind of platform (`comments:read`). */
16
+ counts(streamId: string, params?: CommentCountParams, options?: RequestOptions): Promise<CommentCounts>;
17
+ /** Deletes a comment on its platform and returns it, deleted (`comments:moderate`). */
18
+ delete(streamId: string, commentId: string, options?: RequestOptions): Promise<Comment>;
19
+ /** Bans the comment's author on its platform: for `durationSec` (a timeout), or for good without it (`comments:moderate`). */
20
+ ban(streamId: string, commentId: string, params?: CommentBanParams, options?: RequestOptions): Promise<void>;
21
+ /**
22
+ * Follows the chat: `for await (const event of sf.comments.watch(id))`
23
+ * gives each new comment once and the streamer's deletions, until you
24
+ * break out or `signal` aborts (`comments:read`).
25
+ */
26
+ watch(streamId: string, options?: WatchOptions): AsyncGenerator<ChatEvent, void, undefined>;
27
+ }