@caasx/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js ADDED
@@ -0,0 +1,708 @@
1
+ export class CaasxError extends Error {
2
+ status;
3
+ code;
4
+ constructor(status, code, message) {
5
+ super(message);
6
+ this.name = "CaasxError";
7
+ this.status = status;
8
+ this.code = code;
9
+ }
10
+ }
11
+ export class CaasxProtocolError extends Error {
12
+ constructor() {
13
+ super("Invalid caasX response");
14
+ this.name = "CaasxProtocolError";
15
+ }
16
+ }
17
+ function isRecord(value) {
18
+ return typeof value === "object" && value !== null && !Array.isArray(value);
19
+ }
20
+ function isNullableString(value) {
21
+ return value === null || typeof value === "string";
22
+ }
23
+ function isNullableNumber(value) {
24
+ return value === null || (typeof value === "number" && Number.isFinite(value));
25
+ }
26
+ function isCount(value) {
27
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
28
+ }
29
+ function isUser(value) {
30
+ return (isRecord(value) &&
31
+ value.kind === "user" &&
32
+ typeof value.display_name === "string" &&
33
+ isNullableString(value.badge));
34
+ }
35
+ function isLikeState(value) {
36
+ return isRecord(value) && isCount(value.likes) && typeof value.liked === "boolean";
37
+ }
38
+ function isInteractions(value) {
39
+ return (isRecord(value) &&
40
+ isRecord(value.entries) &&
41
+ Object.values(value.entries).every((entry) => isLikeState(entry) &&
42
+ isRecord(entry) &&
43
+ isCount(entry.comments) &&
44
+ isNullableString(entry.poll)));
45
+ }
46
+ function isEntryComment(value) {
47
+ return (isRecord(value) &&
48
+ typeof value.id === "string" &&
49
+ isNullableString(value.parent) &&
50
+ typeof value.display_name === "string" &&
51
+ isNullableString(value.badge) &&
52
+ typeof value.text === "string" &&
53
+ typeof value.created_at === "string" &&
54
+ typeof value.mine === "boolean");
55
+ }
56
+ function isCommentPage(value) {
57
+ return (isRecord(value) &&
58
+ Array.isArray(value.items) &&
59
+ value.items.every(isEntryComment) &&
60
+ isNullableString(value.next));
61
+ }
62
+ function isEntryPoll(value) {
63
+ return (isRecord(value) &&
64
+ typeof value.id === "string" &&
65
+ typeof value.question === "string" &&
66
+ isNullableString(value.opens_at) &&
67
+ isNullableString(value.closes_at) &&
68
+ typeof value.open === "boolean" &&
69
+ isNullableString(value.choice) &&
70
+ Array.isArray(value.options) &&
71
+ value.options.every((option) => isRecord(option) &&
72
+ typeof option.id === "string" &&
73
+ typeof option.label === "string" &&
74
+ isCount(option.votes)));
75
+ }
76
+ function isCatalog(value) {
77
+ return (isRecord(value) &&
78
+ typeof value.catalog_version === "number" &&
79
+ Number.isSafeInteger(value.catalog_version) &&
80
+ value.catalog_version >= 0);
81
+ }
82
+ function isPage(value) {
83
+ return (isCatalog(value) &&
84
+ isRecord(value) &&
85
+ Array.isArray(value.items) &&
86
+ isNullableString(value.next));
87
+ }
88
+ function isEntry(value) {
89
+ return (isRecord(value) &&
90
+ typeof value.id === "string" &&
91
+ isNullableString(value.external_id) &&
92
+ typeof value.created_at === "string" &&
93
+ isNullableString(value.updated_at) &&
94
+ isNullableString(value.published_at));
95
+ }
96
+ function isImage(value) {
97
+ return (isRecord(value) &&
98
+ typeof value.id === "string" &&
99
+ isNullableString(value.url) &&
100
+ isNullableNumber(value.width) &&
101
+ isNullableNumber(value.height));
102
+ }
103
+ const themeStyleFields = [
104
+ "primaryColor",
105
+ "secondaryColor",
106
+ "backgroundColor",
107
+ "surfaceColor",
108
+ "textColor",
109
+ "textMutedColor",
110
+ "borderColor",
111
+ "borderRadius",
112
+ "fontFamily",
113
+ "fontSize",
114
+ ];
115
+ function isTheme(value) {
116
+ return (isCatalog(value) &&
117
+ isRecord(value) &&
118
+ typeof value.name === "string" &&
119
+ typeof value.slug === "string" &&
120
+ themeStyleFields.every((field) => value[field] == null || typeof value[field] === "string"));
121
+ }
122
+ function isRailContent(value) {
123
+ return (isRecord(value) &&
124
+ typeof value.slug === "string" &&
125
+ isNullableString(value.title) &&
126
+ typeof value.layout === "string" &&
127
+ Array.isArray(value.items) &&
128
+ value.items.every((item) => isRecord(item) &&
129
+ isNullableString(item.title) &&
130
+ (item.subtitle === undefined || isNullableString(item.subtitle)) &&
131
+ (item.badge === undefined || isNullableString(item.badge)) &&
132
+ (item.image === null || isImage(item.image)) &&
133
+ (item.sponsored === undefined ||
134
+ (isRecord(item.sponsored) &&
135
+ typeof item.sponsored.sponsor_name === "string" &&
136
+ typeof item.sponsored.click_url === "string")) &&
137
+ isRecord(item.target) &&
138
+ typeof item.target.type === "string" &&
139
+ typeof item.target.id === "string"));
140
+ }
141
+ function withCardDefaults(rail) {
142
+ return {
143
+ ...rail,
144
+ items: rail.items.map((item) => ({
145
+ ...item,
146
+ subtitle: item.subtitle ?? null,
147
+ badge: item.badge ?? null,
148
+ })),
149
+ };
150
+ }
151
+ function isRail(value) {
152
+ return isCatalog(value) && isRailContent(value);
153
+ }
154
+ function isScreen(value) {
155
+ return (isCatalog(value) &&
156
+ isRecord(value) &&
157
+ typeof value.slug === "string" &&
158
+ Array.isArray(value.rails) &&
159
+ value.rails.every(isRailContent));
160
+ }
161
+ function isPlayback(value) {
162
+ if (!isRecord(value) || typeof value.id !== "string" || !isNullableNumber(value.duration_ms)) {
163
+ return false;
164
+ }
165
+ if (value.status !== "ready") {
166
+ return (typeof value.status === "string" &&
167
+ ["reserved", "uploading", "processing", "failed"].includes(value.status) &&
168
+ value.playback === null);
169
+ }
170
+ const playback = value.playback;
171
+ return (isRecord(playback) &&
172
+ typeof playback.hls_url === "string" &&
173
+ typeof playback.expires_at === "number" &&
174
+ Number.isFinite(playback.expires_at) &&
175
+ isNullableString(playback.thumbnail_url) &&
176
+ Array.isArray(playback.captions) &&
177
+ playback.captions.every((caption) => isRecord(caption) &&
178
+ typeof caption.srclang === "string" &&
179
+ typeof caption.label === "string" &&
180
+ typeof caption.url === "string"));
181
+ }
182
+ function isPrerollDecision(value) {
183
+ return (isRecord(value) &&
184
+ typeof value.id === "string" &&
185
+ typeof value.sponsor_name === "string" &&
186
+ typeof value.click_url === "string" &&
187
+ isRecord(value.creative) &&
188
+ value.creative.status === "ready" &&
189
+ isPlayback(value.creative));
190
+ }
191
+ function isPlaybackSession(value) {
192
+ return (isRecord(value) &&
193
+ isPlayback(value) &&
194
+ (value.preroll === null || isPrerollDecision(value.preroll)));
195
+ }
196
+ function clientUrl(url) {
197
+ let parsed;
198
+ let pathname;
199
+ try {
200
+ parsed = new URL(url);
201
+ pathname = decodeURIComponent(parsed.pathname);
202
+ }
203
+ catch {
204
+ throw new TypeError("url must be an HTTP(S) origin or path prefix");
205
+ }
206
+ if (typeof url !== "string" ||
207
+ /[?#\\\s]/.test(url) ||
208
+ /^[a-z][a-z\d+.-]*:\/\/[^/]*@/i.test(url) ||
209
+ !["http:", "https:"].includes(parsed.protocol) ||
210
+ parsed.username ||
211
+ parsed.password ||
212
+ /\/v1(?:\/|$)/.test(pathname)) {
213
+ throw new TypeError("url must be an HTTP(S) origin or path prefix without credentials, query or fragment");
214
+ }
215
+ parsed.pathname = `${parsed.pathname.replace(/\/+$/, "")}/v1/`;
216
+ return parsed.href;
217
+ }
218
+ function pathSegment(value) {
219
+ if (typeof value !== "string" || value.length === 0 || value === "." || value === "..") {
220
+ throw new TypeError("Request path segments must be nonempty and cannot be dot segments");
221
+ }
222
+ return encodeURIComponent(value);
223
+ }
224
+ function filterValue(value) {
225
+ if (typeof value !== "string" &&
226
+ typeof value !== "boolean" &&
227
+ !(typeof value === "number" && Number.isFinite(value))) {
228
+ throw new TypeError("Filter values must be strings, finite numbers or booleans");
229
+ }
230
+ return String(value);
231
+ }
232
+ const filterOperators = [
233
+ "eq",
234
+ "in",
235
+ "lt",
236
+ "lte",
237
+ "gt",
238
+ "gte",
239
+ "null",
240
+ "has",
241
+ ];
242
+ function includeParameters(parameters, include) {
243
+ if (!include?.length) {
244
+ return;
245
+ }
246
+ if (include.some((path) => typeof path !== "string" || !path || path.includes(","))) {
247
+ throw new TypeError("include paths must be nonempty strings without commas");
248
+ }
249
+ parameters.set("include", include.join(","));
250
+ }
251
+ function queryParameters(options) {
252
+ const parameters = new URLSearchParams();
253
+ if (options.limit !== undefined) {
254
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 100) {
255
+ throw new TypeError("limit must be an integer between 1 and 100");
256
+ }
257
+ parameters.set("limit", String(options.limit));
258
+ }
259
+ if (options.cursor !== undefined && options.cursor !== null) {
260
+ parameters.set("cursor", options.cursor);
261
+ }
262
+ if (options.sort !== undefined) {
263
+ parameters.set("sort", options.sort);
264
+ }
265
+ includeParameters(parameters, options.include);
266
+ for (const filter of options.filter ?? []) {
267
+ if (typeof filter.field !== "string" || !filter.field || /[[\]]/.test(filter.field)) {
268
+ throw new TypeError("Filter fields must be nonempty strings without brackets");
269
+ }
270
+ if (!filterOperators.includes(filter.op)) {
271
+ throw new TypeError("Unknown filter operator");
272
+ }
273
+ const name = `filter[${filter.field}][${filter.op}]`;
274
+ if (filter.op === "in") {
275
+ if (!Array.isArray(filter.value) || filter.value.length === 0) {
276
+ throw new TypeError("in filters require a nonempty array");
277
+ }
278
+ for (const value of filter.value) {
279
+ parameters.append(name, filterValue(value));
280
+ }
281
+ }
282
+ else {
283
+ if (filter.op === "null" && typeof filter.value !== "boolean") {
284
+ throw new TypeError("null filters require a boolean");
285
+ }
286
+ if (filter.op === "has" && (typeof filter.value !== "string" || !filter.value)) {
287
+ throw new TypeError("has filters require a nonempty string");
288
+ }
289
+ parameters.append(name, filterValue(filter.value));
290
+ }
291
+ }
292
+ return parameters;
293
+ }
294
+ function redact(value, credentials) {
295
+ const exact = [...credentials]
296
+ .sort((left, right) => right.length - left.length)
297
+ .map((credential) => `${credential.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}[A-Za-z0-9_-]*`);
298
+ const pattern = new RegExp([...exact, "(?:pk_|sk_)[A-Za-z0-9_-]{43}", "vt_[A-Za-z0-9_-]+"].join("|"), "g");
299
+ return value.replace(pattern, "[redacted]");
300
+ }
301
+ function searchParameters(query, options) {
302
+ if (typeof query !== "string") {
303
+ throw new TypeError("query must be a string");
304
+ }
305
+ const parameters = new URLSearchParams({ q: query });
306
+ if (options.type !== undefined) {
307
+ if (typeof options.type !== "string" || options.type.length === 0) {
308
+ throw new TypeError("type must be a nonempty string");
309
+ }
310
+ parameters.set("type", options.type);
311
+ }
312
+ if (options.cursor !== undefined && options.cursor !== null) {
313
+ parameters.set("cursor", options.cursor);
314
+ }
315
+ if (options.limit !== undefined) {
316
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 50) {
317
+ throw new TypeError("limit must be an integer between 1 and 50");
318
+ }
319
+ parameters.set("limit", String(options.limit));
320
+ }
321
+ includeParameters(parameters, options.include);
322
+ return parameters;
323
+ }
324
+ function untilAborted(value, signal) {
325
+ if (signal === undefined) {
326
+ return value;
327
+ }
328
+ return new Promise((resolve, reject) => {
329
+ const abort = () => reject(signal.reason);
330
+ signal.addEventListener("abort", abort, { once: true });
331
+ value.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
332
+ if (signal.aborted) {
333
+ abort();
334
+ }
335
+ });
336
+ }
337
+ function isPromiseLike(value) {
338
+ return ((typeof value === "object" || typeof value === "function") &&
339
+ value !== null &&
340
+ typeof value.then === "function");
341
+ }
342
+ function sendableToken(token) {
343
+ if (token === null || token === undefined || token === "") {
344
+ return undefined;
345
+ }
346
+ if (typeof token !== "string" || !/^[!-~]+$/.test(token)) {
347
+ throw new TypeError("identity must return a token without spaces or control characters");
348
+ }
349
+ return token;
350
+ }
351
+ function httpError(status, body, credentials) {
352
+ const message = isRecord(body) && typeof body.error === "string" ? body.error : `HTTP ${status}`;
353
+ const code = isRecord(body) && typeof body.reason === "string" ? body.reason : message;
354
+ return new CaasxError(status, redact(code, credentials), redact(message, credentials));
355
+ }
356
+ function watchCatalog(catalog, options) {
357
+ const intervalMs = options.intervalMs ?? 15000;
358
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0 || intervalMs > 2147483647) {
359
+ throw new TypeError("intervalMs must be positive and at most 2147483647");
360
+ }
361
+ if (options.since !== undefined && (!Number.isSafeInteger(options.since) || options.since < 0)) {
362
+ throw new TypeError("since must be a nonnegative safe integer");
363
+ }
364
+ let previousVersion = options.since;
365
+ let etag;
366
+ let stopped = false;
367
+ let timer;
368
+ let controller;
369
+ async function poll() {
370
+ controller = new AbortController();
371
+ try {
372
+ const result = await catalog(controller.signal, etag);
373
+ if (stopped || result.body === null) {
374
+ return;
375
+ }
376
+ const previous = previousVersion;
377
+ if (previous !== undefined && previous !== result.body.catalog_version) {
378
+ options.onChange(result.body.catalog_version, previous);
379
+ }
380
+ previousVersion = result.body.catalog_version;
381
+ etag = result.etag ?? undefined;
382
+ }
383
+ catch (error) {
384
+ if (!stopped) {
385
+ try {
386
+ options.onError?.(error);
387
+ }
388
+ catch {
389
+ return;
390
+ }
391
+ }
392
+ }
393
+ finally {
394
+ controller = undefined;
395
+ if (!stopped) {
396
+ timer = setTimeout(() => void poll(), intervalMs);
397
+ }
398
+ }
399
+ }
400
+ void poll();
401
+ return {
402
+ stop() {
403
+ if (stopped) {
404
+ return;
405
+ }
406
+ stopped = true;
407
+ clearTimeout(timer);
408
+ controller?.abort();
409
+ },
410
+ };
411
+ }
412
+ export function createClient(options) {
413
+ if (typeof options.key !== "string" ||
414
+ options.key.length !== 46 ||
415
+ !/^pk_[A-Za-z0-9_-]{43}$/.test(options.key)) {
416
+ throw new TypeError("key must be a publishable pk_ key with 43 URL-safe characters");
417
+ }
418
+ const baseUrl = clientUrl(options.url);
419
+ const key = options.key;
420
+ const identity = options.identity;
421
+ if (identity !== undefined && typeof identity !== "function") {
422
+ throw new TypeError("identity must be a function");
423
+ }
424
+ const fetcher = options.fetch ?? globalThis.fetch?.bind(globalThis);
425
+ if (typeof fetcher !== "function") {
426
+ throw new TypeError("fetch is required");
427
+ }
428
+ async function request(path, signal, parameters = new URLSearchParams(), { ifNoneMatch, method = "GET", body: jsonBody, auth, staleAuth, } = {}) {
429
+ const credentials = [key, auth, staleAuth].filter((credential) => credential !== undefined);
430
+ const url = new URL(`${baseUrl}${path}`);
431
+ url.search = parameters.toString();
432
+ const response = await fetcher(url.href, {
433
+ method,
434
+ headers: {
435
+ Authorization: `Bearer ${key}`,
436
+ Accept: "application/json",
437
+ ...(ifNoneMatch === undefined ? {} : { "If-None-Match": ifNoneMatch }),
438
+ ...(jsonBody === undefined ? {} : { "Content-Type": "application/json" }),
439
+ ...(auth === undefined ? {} : { "X-Caasx-Auth": auth }),
440
+ },
441
+ credentials: "omit",
442
+ redirect: "error",
443
+ signal,
444
+ ...(jsonBody === undefined ? {} : { body: JSON.stringify(jsonBody) }),
445
+ });
446
+ const etag = response.headers.get("ETag");
447
+ if (response.status === 304 && ifNoneMatch !== undefined) {
448
+ return { status: response.status, etag, body: undefined };
449
+ }
450
+ if (response.status === 204) {
451
+ return { status: response.status, etag, body: undefined };
452
+ }
453
+ const text = await response.text();
454
+ let body;
455
+ try {
456
+ body = JSON.parse(text);
457
+ }
458
+ catch {
459
+ if (!response.ok) {
460
+ throw httpError(response.status, undefined, credentials);
461
+ }
462
+ throw new CaasxProtocolError();
463
+ }
464
+ if (!response.ok) {
465
+ throw httpError(response.status, body, credentials);
466
+ }
467
+ return { status: response.status, etag, body };
468
+ }
469
+ function authToken(options) {
470
+ if (identity === undefined) {
471
+ return undefined;
472
+ }
473
+ const token = identity(options);
474
+ return isPromiseLike(token) ? Promise.resolve(token).then(sendableToken) : sendableToken(token);
475
+ }
476
+ async function communityRequest(path, signal, parameters, init = {}) {
477
+ const pending = authToken({ forceRefresh: false });
478
+ const token = pending instanceof Promise ? await untilAborted(pending, signal) : pending;
479
+ try {
480
+ return await request(path, signal, parameters, { ...init, auth: token });
481
+ }
482
+ catch (error) {
483
+ if (token === undefined ||
484
+ !(error instanceof CaasxError) ||
485
+ error.status !== 401 ||
486
+ error.code !== "auth_invalid") {
487
+ throw error;
488
+ }
489
+ const refreshed = await untilAborted(Promise.resolve(authToken({ forceRefresh: true, rejectedToken: token })), signal);
490
+ if (refreshed === token) {
491
+ throw error;
492
+ }
493
+ return request(path, signal, parameters, {
494
+ ...init,
495
+ auth: refreshed,
496
+ staleAuth: token,
497
+ });
498
+ }
499
+ }
500
+ async function catalog(options = {}) {
501
+ const { body } = await request("catalog", options.signal);
502
+ if (!isCatalog(body)) {
503
+ throw new CaasxProtocolError();
504
+ }
505
+ return body;
506
+ }
507
+ async function conditionalCatalog(signal, etag) {
508
+ const result = await request("catalog", signal, undefined, { ifNoneMatch: etag });
509
+ if (result.status === 304) {
510
+ return { body: null, etag: result.etag };
511
+ }
512
+ if (!isCatalog(result.body)) {
513
+ throw new CaasxProtocolError();
514
+ }
515
+ return { body: result.body, etag: result.etag };
516
+ }
517
+ return {
518
+ async me(options = {}) {
519
+ const { body } = await communityRequest("me", options.signal);
520
+ if (!isUser(body)) {
521
+ throw new CaasxProtocolError();
522
+ }
523
+ return body;
524
+ },
525
+ async like(entryId, options = {}) {
526
+ const { body } = await communityRequest(`entries/${pathSegment(entryId)}/like`, options.signal, undefined, { method: "PUT" });
527
+ if (!isLikeState(body)) {
528
+ throw new CaasxProtocolError();
529
+ }
530
+ return body;
531
+ },
532
+ async unlike(entryId, options = {}) {
533
+ const { body } = await communityRequest(`entries/${pathSegment(entryId)}/like`, options.signal, undefined, { method: "DELETE" });
534
+ if (!isLikeState(body)) {
535
+ throw new CaasxProtocolError();
536
+ }
537
+ return body;
538
+ },
539
+ async interactions(entryIds, options = {}) {
540
+ if (!Array.isArray(entryIds) ||
541
+ entryIds.length < 1 ||
542
+ entryIds.length > 100 ||
543
+ Array.from(entryIds).some((id) => typeof id !== "string" || id.length === 0 || id.includes(","))) {
544
+ throw new TypeError("entries must contain 1 to 100 nonempty ids without commas");
545
+ }
546
+ const { body } = await communityRequest("interactions", options.signal, new URLSearchParams({ entries: entryIds.join(",") }));
547
+ if (!isInteractions(body)) {
548
+ throw new CaasxProtocolError();
549
+ }
550
+ return body;
551
+ },
552
+ async comments(entryId, options = {}) {
553
+ const parameters = new URLSearchParams();
554
+ if (options.cursor !== undefined && options.cursor !== null) {
555
+ parameters.set("cursor", options.cursor);
556
+ }
557
+ if (options.limit !== undefined) {
558
+ if (!Number.isInteger(options.limit) || options.limit < 1 || options.limit > 50) {
559
+ throw new TypeError("limit must be an integer between 1 and 50");
560
+ }
561
+ parameters.set("limit", String(options.limit));
562
+ }
563
+ const { body } = await communityRequest(`entries/${pathSegment(entryId)}/comments`, options.signal, parameters);
564
+ if (!isCommentPage(body)) {
565
+ throw new CaasxProtocolError();
566
+ }
567
+ return body;
568
+ },
569
+ async comment(entryId, options) {
570
+ const { body } = await communityRequest(`entries/${pathSegment(entryId)}/comments`, options.signal, undefined, {
571
+ method: "POST",
572
+ body: {
573
+ text: options.text,
574
+ ...(options.parent === undefined ? {} : { parent: options.parent }),
575
+ },
576
+ });
577
+ if (!isEntryComment(body)) {
578
+ throw new CaasxProtocolError();
579
+ }
580
+ return body;
581
+ },
582
+ async report(commentId, options = {}) {
583
+ const { status } = await communityRequest(`comments/${pathSegment(commentId)}/report`, options.signal, undefined, { method: "POST" });
584
+ if (status !== 204) {
585
+ throw new CaasxProtocolError();
586
+ }
587
+ },
588
+ async poll(entryId, options = {}) {
589
+ const { body } = await communityRequest(`entries/${pathSegment(entryId)}/poll`, options.signal, undefined);
590
+ if (!isEntryPoll(body)) {
591
+ throw new CaasxProtocolError();
592
+ }
593
+ return body;
594
+ },
595
+ async vote(pollId, optionId, options = {}) {
596
+ const { body } = await communityRequest(`polls/${pathSegment(pollId)}/vote`, options.signal, undefined, {
597
+ method: "POST",
598
+ body: { option: optionId },
599
+ });
600
+ if (!isEntryPoll(body)) {
601
+ throw new CaasxProtocolError();
602
+ }
603
+ return body;
604
+ },
605
+ async list(type, options = {}) {
606
+ const { body } = await request(pathSegment(type), options.signal, queryParameters(options));
607
+ if (!isPage(body) || !body.items.every(isEntry)) {
608
+ throw new CaasxProtocolError();
609
+ }
610
+ return body;
611
+ },
612
+ async get(type, id, options = {}) {
613
+ const { body } = await request(`${pathSegment(type)}/${pathSegment(id)}`, options.signal, queryParameters({ include: options.include }));
614
+ if (!isPage(body) ||
615
+ body.next !== null ||
616
+ body.items.length !== 1 ||
617
+ !isEntry(body.items[0])) {
618
+ throw new CaasxProtocolError();
619
+ }
620
+ return body.items[0];
621
+ },
622
+ async search(query, options = {}) {
623
+ const { body } = await request("search", options.signal, searchParameters(query, options));
624
+ if (!isPage(body) ||
625
+ !body.items.every((item) => isRecord(item) && typeof item.type === "string" && isEntry(item.entry))) {
626
+ throw new CaasxProtocolError();
627
+ }
628
+ return body;
629
+ },
630
+ async taxonomy(slug, options = {}) {
631
+ const { body } = await request(`taxonomies/${pathSegment(slug)}`, options.signal);
632
+ if (!isPage(body) || body.next !== null) {
633
+ throw new CaasxProtocolError();
634
+ }
635
+ const items = [];
636
+ const nodes = new Map();
637
+ for (const row of body.items) {
638
+ if (!isRecord(row) ||
639
+ typeof row.id !== "string" ||
640
+ typeof row.slug !== "string" ||
641
+ typeof row.label !== "string" ||
642
+ !isNullableString(row.parent) ||
643
+ nodes.has(row.id)) {
644
+ throw new CaasxProtocolError();
645
+ }
646
+ const node = {
647
+ id: row.id,
648
+ slug: row.slug,
649
+ label: row.label,
650
+ parent: row.parent,
651
+ children: [],
652
+ };
653
+ if (node.parent === null) {
654
+ items.push(node);
655
+ }
656
+ else {
657
+ const parent = nodes.get(node.parent);
658
+ if (!parent) {
659
+ throw new CaasxProtocolError();
660
+ }
661
+ parent.children.push(node);
662
+ }
663
+ nodes.set(node.id, node);
664
+ }
665
+ return { items, catalog_version: body.catalog_version };
666
+ },
667
+ async rail(slug, options = {}) {
668
+ const { body } = await request(`rails/${pathSegment(slug)}`, options.signal);
669
+ if (!isRail(body)) {
670
+ throw new CaasxProtocolError();
671
+ }
672
+ return withCardDefaults(body);
673
+ },
674
+ async screen(slug, options = {}) {
675
+ const { body } = await request(`screens/${pathSegment(slug)}`, options.signal);
676
+ if (!isScreen(body)) {
677
+ throw new CaasxProtocolError();
678
+ }
679
+ return { ...body, rails: body.rails.map(withCardDefaults) };
680
+ },
681
+ async theme(slug, options = {}) {
682
+ const { body } = await request(`themes/${pathSegment(slug)}`, options.signal);
683
+ if (!isTheme(body)) {
684
+ throw new CaasxProtocolError();
685
+ }
686
+ return body;
687
+ },
688
+ async play(id, options = {}) {
689
+ const { body } = await request(`videos/${pathSegment(id)}/play`, options.signal);
690
+ const session = isRecord(body) ? { ...body, preroll: body.preroll ?? null } : body;
691
+ if (!isPlaybackSession(session)) {
692
+ throw new CaasxProtocolError();
693
+ }
694
+ return session;
695
+ },
696
+ catalog,
697
+ async model(options = {}) {
698
+ const { body } = await request("model", options.signal);
699
+ if (!isPage(body) || body.next !== null) {
700
+ throw new CaasxProtocolError();
701
+ }
702
+ return body;
703
+ },
704
+ watchCatalog(options) {
705
+ return watchCatalog(conditionalCatalog, options);
706
+ },
707
+ };
708
+ }