@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,220 @@
1
+ import { ConnectionError, RateLimitError, ServerError, ValidationError } from './errors.js';
2
+ import { sleep } from './http.js';
3
+ /** The most a read takes: a full page means more are waiting. */
4
+ export const PAGE_LIMIT = 500;
5
+ /**
6
+ * An API without `after` (backend before the cursor by arrival) is read by
7
+ * `since`, the platforms' own times, which come late from the platforms read
8
+ * every 15–60 s: each read reaches this far back behind the newest.
9
+ */
10
+ export const SINCE_LOOKBACK_MS = 120_000;
11
+ /** The shortest pause after an error: an interval of 0 mustn't turn an outage into a loop of requests. */
12
+ const MIN_ERROR_PAUSE_MS = 1000;
13
+ /** How far deletions are read back behind the last one: a deletion's write can become visible late. */
14
+ const DELETIONS_LOOKBACK_MS = 5000;
15
+ /** How many of the latest comments given a lost cursor falls back to. */
16
+ const CURSOR_FALLBACKS = 3;
17
+ /** The longest pause after errors in a row. */
18
+ const MAX_ERROR_PAUSE_MS = 60_000;
19
+ /** How long a comment given is remembered behind the newest: beyond the API's 5 s reach-back. */
20
+ const REMEMBER_MS = 60_000;
21
+ const time = (iso) => (iso ? Date.parse(iso) || 0 : 0);
22
+ const receivedAt = (comment) => comment.receivedAt;
23
+ /** The comment stored last: the API's order with `after` is receivedAt, then uuid. */
24
+ function lastStored(comments) {
25
+ let last;
26
+ for (const comment of comments) {
27
+ if (!last)
28
+ last = comment;
29
+ else {
30
+ const [a, b] = [time(receivedAt(comment)), time(receivedAt(last))];
31
+ if (a > b || (a === b && comment.uuid > last.uuid))
32
+ last = comment;
33
+ }
34
+ }
35
+ return last;
36
+ }
37
+ /**
38
+ * Follows a stream's chat: every new comment once, in the order StreamFarm
39
+ * got them, and the streamer's deletions. Rides out network and server
40
+ * errors; ends on others or when `signal` aborts.
41
+ */
42
+ export async function* watchChat(source, streamId, options = {}) {
43
+ const { interval = 5000, platformTypes, includeHistory = false, historyLimit = 100, deletions = true, signal, onError } = options;
44
+ const request = { signal };
45
+ // Comments given, by uuid, with the time they are ordered by, and the newest of those times.
46
+ const given = new Map();
47
+ let newestGiven = 0;
48
+ // How to read on: by `after` (the API has it), by `since` (it hasn't), or not known yet (no comments seen).
49
+ let mode = 'unknown';
50
+ let cursor;
51
+ let newestPublished = 0;
52
+ let nextPageSince;
53
+ const deletedGiven = new Map();
54
+ let deletedCursor;
55
+ /** Picks how to read on from comments read: their receivedAt says the API has `after`. */
56
+ function settle(comments) {
57
+ if (!comments.length)
58
+ return;
59
+ if (comments.some((comment) => receivedAt(comment) !== undefined)) {
60
+ mode = 'after';
61
+ cursor = lastStored(comments)?.uuid;
62
+ }
63
+ else if (mode === 'unknown') {
64
+ mode = 'since';
65
+ }
66
+ }
67
+ /** The comments not given yet, remembered as given. */
68
+ function fresh(comments) {
69
+ const result = comments.filter((comment) => !given.has(comment.uuid));
70
+ for (const comment of result) {
71
+ const at = mode === 'after' ? time(receivedAt(comment)) : time(comment.publishedAt);
72
+ given.set(comment.uuid, at);
73
+ newestGiven = Math.max(newestGiven, at);
74
+ }
75
+ for (const comment of comments)
76
+ newestPublished = Math.max(newestPublished, time(comment.publishedAt));
77
+ // Forget what the next reads can't return.
78
+ const floor = newestGiven - (mode === 'after' ? REMEMBER_MS : SINCE_LOOKBACK_MS + REMEMBER_MS);
79
+ for (const [uuid, at] of given)
80
+ if (at < floor)
81
+ given.delete(uuid);
82
+ return result;
83
+ }
84
+ /** The newest comments, as at the start: while the API's way is unknown or the cursor was lost. */
85
+ async function readLatest() {
86
+ const comments = await source.list(streamId, { limit: historyLimit, platformTypes }, request);
87
+ settle(comments);
88
+ return comments;
89
+ }
90
+ /** The next comments; `more`: a full page, read on at once. */
91
+ async function readComments() {
92
+ if (mode === 'after' && cursor) {
93
+ let page;
94
+ // The cursor's comment can go (its platform's connection was removed,
95
+ // or it outlived its keeping): then the latest comments given, newest
96
+ // first, are the cursor instead.
97
+ const fallbacks = [...given.entries()].filter(([uuid]) => uuid !== cursor)
98
+ .sort((a, b) => b[1] - a[1]).slice(0, CURSOR_FALLBACKS).map(([uuid]) => uuid);
99
+ for (const candidate of [cursor, ...fallbacks]) {
100
+ try {
101
+ page = await source.list(streamId, { after: candidate, limit: PAGE_LIMIT, platformTypes }, request);
102
+ cursor = candidate;
103
+ break;
104
+ }
105
+ catch (error) {
106
+ if (!(error instanceof ValidationError))
107
+ throw error;
108
+ }
109
+ }
110
+ if (!page) {
111
+ // None is left: the newest again, without those older than what was given.
112
+ const floor = newestGiven - REMEMBER_MS;
113
+ mode = 'unknown';
114
+ cursor = undefined;
115
+ const latest = await readLatest();
116
+ return { comments: fresh(latest.filter((comment) => time(receivedAt(comment)) >= floor)), more: false };
117
+ }
118
+ // The answer: comments stored up to 5 s before the cursor, the cursor,
119
+ // then up to PAGE_LIMIT stored after it. Its last is the next cursor.
120
+ const at = page.findIndex((comment) => comment.uuid === cursor);
121
+ const later = at >= 0 ? page.length - at - 1 : page.length;
122
+ const comments = fresh(page);
123
+ if (page.length)
124
+ cursor = page[page.length - 1].uuid;
125
+ return { comments, more: later >= PAGE_LIMIT };
126
+ }
127
+ if (mode === 'since') {
128
+ const since = nextPageSince ?? new Date(Math.max(0, newestPublished - SINCE_LOOKBACK_MS)).toISOString();
129
+ const page = await source.list(streamId, { since, limit: PAGE_LIMIT, platformTypes }, request);
130
+ const full = page.length === PAGE_LIMIT;
131
+ nextPageSince = undefined;
132
+ if (full) {
133
+ // Comments of the page's last millisecond may not all have fit: the
134
+ // next page starts a millisecond before it, unless this page started
135
+ // there too (a whole page of one millisecond).
136
+ const last = time(page[page.length - 1].publishedAt);
137
+ nextPageSince = new Date(last - 1 > time(since) ? last - 1 : last).toISOString();
138
+ }
139
+ // Comments with receivedAt: the API has `after` now (it was updated meanwhile).
140
+ if (page.some((comment) => receivedAt(comment) !== undefined))
141
+ settle(page);
142
+ return { comments: fresh(page), more: full };
143
+ }
144
+ return { comments: fresh(await readLatest()), more: false };
145
+ }
146
+ async function readDeletions() {
147
+ // Read back a little behind the last deletion (those given are dropped):
148
+ // two in one millisecond across a page, or a write visible late.
149
+ const since = deletedCursor ? new Date(time(deletedCursor) - DELETIONS_LOOKBACK_MS).toISOString() : undefined;
150
+ const page = await source.listDeleted(streamId, since ? { since, limit: PAGE_LIMIT } : { limit: 100 }, request);
151
+ const deleted = page.filter((row) => !deletedGiven.has(row.uuid));
152
+ for (const row of page) {
153
+ deletedGiven.set(row.uuid, time(row.deletedAt));
154
+ if (!deletedCursor || time(row.deletedAt) > time(deletedCursor))
155
+ deletedCursor = row.deletedAt;
156
+ }
157
+ const floor = time(deletedCursor) - REMEMBER_MS;
158
+ for (const [uuid, at] of deletedGiven)
159
+ if (at < floor)
160
+ deletedGiven.delete(uuid);
161
+ return { deleted, more: page.length === PAGE_LIMIT && deleted.length > 0 };
162
+ }
163
+ // The start in steps, so that a step that failed is the only one done again.
164
+ let history;
165
+ let deletionsStarted = !deletions;
166
+ let started = false;
167
+ // Errors ridden out in a row: the pause after each doubles, up to a minute.
168
+ let failures = 0;
169
+ for (;;) {
170
+ const events = [];
171
+ let more = false;
172
+ let pause = interval;
173
+ try {
174
+ if (!started) {
175
+ if (!history) {
176
+ history = await readLatest();
177
+ fresh(history);
178
+ }
179
+ if (!deletionsStarted) {
180
+ await readDeletions();
181
+ deletionsStarted = true;
182
+ }
183
+ started = true;
184
+ if (includeHistory)
185
+ for (const comment of history)
186
+ events.push({ type: 'comment', comment });
187
+ }
188
+ else {
189
+ const read = await readComments();
190
+ more = read.more;
191
+ for (const comment of read.comments)
192
+ events.push({ type: 'comment', comment });
193
+ if (deletions) {
194
+ const gone = await readDeletions();
195
+ more ||= gone.more;
196
+ for (const { uuid, deletedAt } of gone.deleted)
197
+ events.push({ type: 'deleted', uuid, deletedAt });
198
+ }
199
+ }
200
+ failures = 0;
201
+ }
202
+ catch (error) {
203
+ if (signal?.aborted)
204
+ throw signal.reason;
205
+ const ridden = error instanceof ConnectionError || error instanceof ServerError || error instanceof RateLimitError;
206
+ if (!ridden)
207
+ throw error;
208
+ onError?.(error);
209
+ more = false;
210
+ failures++;
211
+ pause = Math.min(MAX_ERROR_PAUSE_MS, Math.max(MIN_ERROR_PAUSE_MS, interval) * 2 ** failures);
212
+ if (error instanceof RateLimitError)
213
+ pause = Math.max(pause, (error.retryAfter ?? 1) * 1000);
214
+ }
215
+ for (const event of events)
216
+ yield event;
217
+ if (!more)
218
+ await sleep(pause, signal);
219
+ }
220
+ }
@@ -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
+ }
@@ -0,0 +1,60 @@
1
+ import { Transport } 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
+ /**
9
+ * The StreamFarm public API client.
10
+ *
11
+ * ```ts
12
+ * const sf = new StreamFarm(); // the key from STREAMFARM_API_KEY
13
+ * const streams = await sf.streams.list();
14
+ * ```
15
+ */
16
+ export class StreamFarm {
17
+ streams;
18
+ platforms;
19
+ ads;
20
+ overlay;
21
+ comments;
22
+ studio;
23
+ regions;
24
+ connections;
25
+ stats;
26
+ broadcasts;
27
+ account;
28
+ transport;
29
+ constructor(options = {}) {
30
+ this.transport = new Transport(options);
31
+ this.streams = new Streams(this.transport);
32
+ this.platforms = new Platforms(this.transport);
33
+ this.ads = new Ads(this.transport);
34
+ this.overlay = new AdOverlay(this.transport);
35
+ this.comments = new Comments(this.transport);
36
+ this.studio = new Studio(this.transport);
37
+ this.regions = new Regions(this.transport);
38
+ this.connections = new Connections(this.transport);
39
+ this.stats = new Stats(this.transport);
40
+ this.broadcasts = new Broadcasts(this.transport);
41
+ this.account = new Account(this.transport);
42
+ }
43
+ /** The API's base URL the client works with. */
44
+ get baseUrl() {
45
+ return this.transport.baseUrl;
46
+ }
47
+ /** The key the client works with: its name, scopes, streams and expiry. Any key may read it. */
48
+ async keyInfo(options) {
49
+ return (await this.transport.request({ method: 'GET', path: '/' }, options)).key;
50
+ }
51
+ /**
52
+ * Any request to the API, for what this version of the SDK doesn't know
53
+ * yet: the answer as the API sends it, with the SDK's key, retries and
54
+ * errors. `path` is under the base URL: `/streams/<id>/…`.
55
+ */
56
+ request(method, path, init = {}, options) {
57
+ const normalized = path.startsWith('/') ? path : `/${path}`;
58
+ return this.transport.request({ method, path: normalized, query: init.query, body: init.body }, options);
59
+ }
60
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * What the SDK throws. Everything is a StreamFarmError:
3
+ *
4
+ * - ApiError and its subclasses: the API answered with an error. The class
5
+ * follows the HTTP status, `code` says exactly why (see ErrorCode);
6
+ * - ConnectionError and TimeoutError: no answer came;
7
+ * - WaitTimeoutError: a waiting helper (`streams.waitUntilLive`) gave up.
8
+ */
9
+ /** The `error.code`s the API answers with (its documentation lists them). New ones may come: compare, don't switch exhaustively. */
10
+ export type ErrorCode = 'bad_request' | 'unauthorized' | 'insufficient_scope' | 'forbidden' | 'not_found' | 'conflict' | 'connection_required' | 'stream_not_live' | 'stream_not_deployed' | 'stream_not_transcoded' | 'paid_promotion_off' | 'ad_on_air' | 'plan_limit' | 'ad_incomplete' | 'ad_text_too_long' | 'rate_limited' | 'internal_error' | 'not_supported' | 'core_unavailable' | 'platform_quota_exceeded' | 'platform_reconnect_required' | 'platform_rate_limited' | 'platform_refused' | 'platform_unavailable' | 'studio_unavailable' | 'invite_limit' | 'studio_server_unavailable' | 'http_error' | (string & {});
11
+ /** The key's request limit, from the answer's X-RateLimit-* headers. */
12
+ export interface RateLimit {
13
+ /** Requests a minute the key may make. */
14
+ limit: number;
15
+ /** Requests left in this minute. */
16
+ remaining: number;
17
+ /** Seconds until the minute starts over. */
18
+ resetSec: number;
19
+ }
20
+ export declare class StreamFarmError extends Error {
21
+ constructor(message: string, options?: {
22
+ cause?: unknown;
23
+ });
24
+ }
25
+ export interface ApiErrorInit {
26
+ status: number;
27
+ code: ErrorCode;
28
+ message: string;
29
+ details?: unknown;
30
+ method: string;
31
+ path: string;
32
+ correlationId: string | null;
33
+ rateLimit: RateLimit | null;
34
+ retryAfter?: number | null;
35
+ }
36
+ /** The API answered with an error: `{ error: { code, message, details? } }`. */
37
+ export declare class ApiError extends StreamFarmError {
38
+ /** The HTTP status. */
39
+ readonly status: number;
40
+ /** Why: `plan_limit`, `insufficient_scope`, … */
41
+ readonly code: ErrorCode;
42
+ /** More about it, by code: `{ required }` for `insufficient_scope`, `{ limit, max, current, plan }` for `plan_limit`, … */
43
+ readonly details: unknown;
44
+ /** The request: method and path under the API's base URL. */
45
+ readonly method: string;
46
+ readonly path: string;
47
+ /** X-Correlation-Id of the answer: name it when you write to support. */
48
+ readonly correlationId: string | null;
49
+ readonly rateLimit: RateLimit | null;
50
+ constructor(init: ApiErrorInit);
51
+ }
52
+ /** 401: no key, or it is wrong, revoked or expired. */
53
+ export declare class AuthenticationError extends ApiError {
54
+ }
55
+ /** 403: the key lacks a scope (`insufficient_scope`), may not make streams (`forbidden`), or the tariff doesn't allow it (`plan_limit`). */
56
+ export declare class PermissionError extends ApiError {
57
+ }
58
+ /** 404: there is no such object, or it is outside the key's streams. */
59
+ export declare class NotFoundError extends ApiError {
60
+ }
61
+ /** 409: the state doesn't allow it now (`stream_not_live`, `connection_required`, `ad_on_air`, …). */
62
+ export declare class ConflictError extends ApiError {
63
+ }
64
+ /** 400 and 422: the request was refused as it is (`bad_request`, `ad_incomplete`, `not_supported`, …). */
65
+ export declare class ValidationError extends ApiError {
66
+ }
67
+ /** 429: over the key's request limit. */
68
+ export declare class RateLimitError extends ApiError {
69
+ /** Seconds to wait before trying again, from Retry-After. */
70
+ readonly retryAfter: number | null;
71
+ constructor(init: ApiErrorInit);
72
+ }
73
+ /** 5xx: the API, the region's media server, the studio's room server or a platform failed. */
74
+ export declare class ServerError extends ApiError {
75
+ }
76
+ /** No answer: DNS, TLS, the connection dropped. `cause` holds what fetch threw. */
77
+ export declare class ConnectionError extends StreamFarmError {
78
+ }
79
+ /** No answer within the request's timeout. */
80
+ export declare class TimeoutError extends ConnectionError {
81
+ }
82
+ /** A waiting helper ran out of time (`streams.waitUntilLive`). */
83
+ export declare class WaitTimeoutError extends StreamFarmError {
84
+ }
85
+ /** The ApiError subclass for an HTTP status. */
86
+ export declare function apiErrorFor(init: ApiErrorInit): ApiError;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * What the SDK throws. Everything is a StreamFarmError:
3
+ *
4
+ * - ApiError and its subclasses: the API answered with an error. The class
5
+ * follows the HTTP status, `code` says exactly why (see ErrorCode);
6
+ * - ConnectionError and TimeoutError: no answer came;
7
+ * - WaitTimeoutError: a waiting helper (`streams.waitUntilLive`) gave up.
8
+ */
9
+ export class StreamFarmError extends Error {
10
+ constructor(message, options) {
11
+ super(message, options);
12
+ this.name = new.target.name;
13
+ }
14
+ }
15
+ /** The API answered with an error: `{ error: { code, message, details? } }`. */
16
+ export class ApiError extends StreamFarmError {
17
+ /** The HTTP status. */
18
+ status;
19
+ /** Why: `plan_limit`, `insufficient_scope`, … */
20
+ code;
21
+ /** More about it, by code: `{ required }` for `insufficient_scope`, `{ limit, max, current, plan }` for `plan_limit`, … */
22
+ details;
23
+ /** The request: method and path under the API's base URL. */
24
+ method;
25
+ path;
26
+ /** X-Correlation-Id of the answer: name it when you write to support. */
27
+ correlationId;
28
+ rateLimit;
29
+ constructor(init) {
30
+ super(`${init.status} ${init.code}: ${init.message} (${init.method} ${init.path})`);
31
+ this.status = init.status;
32
+ this.code = init.code;
33
+ this.details = init.details;
34
+ this.method = init.method;
35
+ this.path = init.path;
36
+ this.correlationId = init.correlationId;
37
+ this.rateLimit = init.rateLimit;
38
+ }
39
+ }
40
+ /** 401: no key, or it is wrong, revoked or expired. */
41
+ export class AuthenticationError extends ApiError {
42
+ }
43
+ /** 403: the key lacks a scope (`insufficient_scope`), may not make streams (`forbidden`), or the tariff doesn't allow it (`plan_limit`). */
44
+ export class PermissionError extends ApiError {
45
+ }
46
+ /** 404: there is no such object, or it is outside the key's streams. */
47
+ export class NotFoundError extends ApiError {
48
+ }
49
+ /** 409: the state doesn't allow it now (`stream_not_live`, `connection_required`, `ad_on_air`, …). */
50
+ export class ConflictError extends ApiError {
51
+ }
52
+ /** 400 and 422: the request was refused as it is (`bad_request`, `ad_incomplete`, `not_supported`, …). */
53
+ export class ValidationError extends ApiError {
54
+ }
55
+ /** 429: over the key's request limit. */
56
+ export class RateLimitError extends ApiError {
57
+ /** Seconds to wait before trying again, from Retry-After. */
58
+ retryAfter;
59
+ constructor(init) {
60
+ super(init);
61
+ this.retryAfter = init.retryAfter ?? null;
62
+ }
63
+ }
64
+ /** 5xx: the API, the region's media server, the studio's room server or a platform failed. */
65
+ export class ServerError extends ApiError {
66
+ }
67
+ /** No answer: DNS, TLS, the connection dropped. `cause` holds what fetch threw. */
68
+ export class ConnectionError extends StreamFarmError {
69
+ }
70
+ /** No answer within the request's timeout. */
71
+ export class TimeoutError extends ConnectionError {
72
+ }
73
+ /** A waiting helper ran out of time (`streams.waitUntilLive`). */
74
+ export class WaitTimeoutError extends StreamFarmError {
75
+ }
76
+ /** The ApiError subclass for an HTTP status. */
77
+ export function apiErrorFor(init) {
78
+ const { status } = init;
79
+ if (status === 401)
80
+ return new AuthenticationError(init);
81
+ if (status === 403)
82
+ return new PermissionError(init);
83
+ if (status === 404)
84
+ return new NotFoundError(init);
85
+ if (status === 409)
86
+ return new ConflictError(init);
87
+ if (status === 400 || status === 422)
88
+ return new ValidationError(init);
89
+ if (status === 429)
90
+ return new RateLimitError(init);
91
+ if (status >= 500)
92
+ return new ServerError(init);
93
+ return new ApiError(init);
94
+ }