@superdurable/connector-google-youtube 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/LICENSE +21 -0
- package/README.md +10 -2
- package/dex-connector.json +400 -0
- package/dist/chunk-UAP7AK3Z.js +422 -0
- package/dist/connection-cA6SHIc_.d.ts +332 -0
- package/dist/index.d.ts +364 -0
- package/dist/index.js +953 -0
- package/dist/mock.d.ts +163 -0
- package/dist/mock.js +397 -0
- package/package.json +64 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,953 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AddPlaylistItemBranch,
|
|
3
|
+
AddPlaylistItemBranchAdded,
|
|
4
|
+
AddPlaylistItemBranchDefect,
|
|
5
|
+
AddPlaylistItemBranchInvalidResponse,
|
|
6
|
+
AddPlaylistItemBranchNotFound,
|
|
7
|
+
AddPlaylistItemBranchProviderRejected,
|
|
8
|
+
AddPlaylistItemBranchQuotaExhausted,
|
|
9
|
+
AddPlaylistItemBranchUncertain,
|
|
10
|
+
AddPlaylistItemDefinition,
|
|
11
|
+
AddPlaylistItemInputSchema,
|
|
12
|
+
AddPlaylistItemMetadata,
|
|
13
|
+
AddedPlaylistItemSchema,
|
|
14
|
+
ChannelSchema,
|
|
15
|
+
ConfigSchema,
|
|
16
|
+
Connection,
|
|
17
|
+
ConnectorID,
|
|
18
|
+
GetChannelBranch,
|
|
19
|
+
GetChannelBranchDefect,
|
|
20
|
+
GetChannelBranchFound,
|
|
21
|
+
GetChannelBranchInvalidResponse,
|
|
22
|
+
GetChannelBranchNotFound,
|
|
23
|
+
GetChannelBranchProviderRejected,
|
|
24
|
+
GetChannelBranchQuotaExhausted,
|
|
25
|
+
GetChannelDefinition,
|
|
26
|
+
GetChannelInputSchema,
|
|
27
|
+
GetChannelMetadata,
|
|
28
|
+
GetVideoBranch,
|
|
29
|
+
GetVideoBranchDefect,
|
|
30
|
+
GetVideoBranchFound,
|
|
31
|
+
GetVideoBranchInvalidResponse,
|
|
32
|
+
GetVideoBranchNotFound,
|
|
33
|
+
GetVideoBranchProviderRejected,
|
|
34
|
+
GetVideoBranchQuotaExhausted,
|
|
35
|
+
GetVideoDefinition,
|
|
36
|
+
GetVideoInputSchema,
|
|
37
|
+
GetVideoMetadata,
|
|
38
|
+
ListPlaylistItemsBranch,
|
|
39
|
+
ListPlaylistItemsBranchDefect,
|
|
40
|
+
ListPlaylistItemsBranchInvalidResponse,
|
|
41
|
+
ListPlaylistItemsBranchListed,
|
|
42
|
+
ListPlaylistItemsBranchNotFound,
|
|
43
|
+
ListPlaylistItemsBranchProviderRejected,
|
|
44
|
+
ListPlaylistItemsBranchQuotaExhausted,
|
|
45
|
+
ListPlaylistItemsDefinition,
|
|
46
|
+
ListPlaylistItemsInputSchema,
|
|
47
|
+
ListPlaylistItemsMetadata,
|
|
48
|
+
PlaylistItemPageSchema,
|
|
49
|
+
PlaylistItemSchema,
|
|
50
|
+
ProviderID,
|
|
51
|
+
SearchVideosBranch,
|
|
52
|
+
SearchVideosBranchDefect,
|
|
53
|
+
SearchVideosBranchInvalidResponse,
|
|
54
|
+
SearchVideosBranchProviderRejected,
|
|
55
|
+
SearchVideosBranchQuotaExhausted,
|
|
56
|
+
SearchVideosBranchSearched,
|
|
57
|
+
SearchVideosDefinition,
|
|
58
|
+
SearchVideosInputSchema,
|
|
59
|
+
SearchVideosMetadata,
|
|
60
|
+
VideoSchema,
|
|
61
|
+
VideoSearchPageSchema,
|
|
62
|
+
VideoSearchResultSchema,
|
|
63
|
+
decodeCredentials,
|
|
64
|
+
decodeSharedCredentials,
|
|
65
|
+
newConnection,
|
|
66
|
+
newConnectionWithOperations,
|
|
67
|
+
newProjectConnection,
|
|
68
|
+
newProjectCredentialProvider
|
|
69
|
+
} from "./chunk-UAP7AK3Z.js";
|
|
70
|
+
|
|
71
|
+
// src/generated/steps.ts
|
|
72
|
+
import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
|
|
73
|
+
function newSearchVideosStep(configuration) {
|
|
74
|
+
const { connection, connectionName, searched, quotaExhausted, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
75
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
76
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.searchVideos(), connection: connection.reference, branches: [
|
|
77
|
+
goToBranch("searched", searched),
|
|
78
|
+
...quotaExhausted ? [goToBranch("quotaExhausted", quotaExhausted)] : [],
|
|
79
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
80
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
81
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
82
|
+
] });
|
|
83
|
+
}
|
|
84
|
+
function newGetVideoStep(configuration) {
|
|
85
|
+
const { connection, connectionName, found, notFound, quotaExhausted, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
86
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
87
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.getVideo(), connection: connection.reference, branches: [
|
|
88
|
+
goToBranch("found", found),
|
|
89
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
90
|
+
...quotaExhausted ? [goToBranch("quotaExhausted", quotaExhausted)] : [],
|
|
91
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
92
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
93
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
94
|
+
] });
|
|
95
|
+
}
|
|
96
|
+
function newGetChannelStep(configuration) {
|
|
97
|
+
const { connection, connectionName, found, notFound, quotaExhausted, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
98
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
99
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.getChannel(), connection: connection.reference, branches: [
|
|
100
|
+
goToBranch("found", found),
|
|
101
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
102
|
+
...quotaExhausted ? [goToBranch("quotaExhausted", quotaExhausted)] : [],
|
|
103
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
104
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
105
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
106
|
+
] });
|
|
107
|
+
}
|
|
108
|
+
function newListPlaylistItemsStep(configuration) {
|
|
109
|
+
const { connection, connectionName, listed, notFound, quotaExhausted, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
|
|
110
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
111
|
+
return newQueryStep({ ...stepConfiguration, operation: connection.operations.listPlaylistItems(), connection: connection.reference, branches: [
|
|
112
|
+
goToBranch("listed", listed),
|
|
113
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
114
|
+
...quotaExhausted ? [goToBranch("quotaExhausted", quotaExhausted)] : [],
|
|
115
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
116
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
117
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
118
|
+
] });
|
|
119
|
+
}
|
|
120
|
+
function newAddPlaylistItemStep(configuration) {
|
|
121
|
+
const { connection, connectionName, added, notFound, quotaExhausted, providerRejected, invalidResponse, uncertain, defect: defect2, ...stepConfiguration } = configuration;
|
|
122
|
+
if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
|
|
123
|
+
return newMutationStep({ ...stepConfiguration, operation: connection.operations.addPlaylistItem(), connection: connection.reference, branches: [
|
|
124
|
+
goToBranch("added", added),
|
|
125
|
+
...notFound ? [goToBranch("notFound", notFound)] : [],
|
|
126
|
+
...quotaExhausted ? [goToBranch("quotaExhausted", quotaExhausted)] : [],
|
|
127
|
+
...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
|
|
128
|
+
...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
|
|
129
|
+
...uncertain ? [goToBranch("uncertain", uncertain)] : [],
|
|
130
|
+
...defect2 ? [goToBranch("defect", defect2)] : []
|
|
131
|
+
] });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/client.ts
|
|
135
|
+
import { BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
|
|
136
|
+
import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
|
|
137
|
+
import { ReauthorizationRequiredError, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
|
|
138
|
+
import { CheckpointError, DispatchNotAllowedError, InsufficientTimeError } from "@superdurable/connectors-sdk/singledispatch";
|
|
139
|
+
|
|
140
|
+
// src/generated/refresh.ts
|
|
141
|
+
var Authorization = {
|
|
142
|
+
"defaultMethod": "google-oauth-readonly",
|
|
143
|
+
"methods": [
|
|
144
|
+
{
|
|
145
|
+
"fields": [
|
|
146
|
+
{
|
|
147
|
+
"name": "oauth_client_id",
|
|
148
|
+
"required": true,
|
|
149
|
+
"type": "string"
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
"name": "oauth_client_secret",
|
|
153
|
+
"required": true,
|
|
154
|
+
"type": "secretString"
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
"name": "access_token",
|
|
158
|
+
"required": true,
|
|
159
|
+
"type": "secretString"
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
"name": "refresh_token",
|
|
163
|
+
"required": true,
|
|
164
|
+
"type": "secretString"
|
|
165
|
+
}
|
|
166
|
+
],
|
|
167
|
+
"id": "google-oauth-readonly",
|
|
168
|
+
"oauth2": {
|
|
169
|
+
"clientIDCredential": "oauth_client_id",
|
|
170
|
+
"clientSecretCredential": "oauth_client_secret",
|
|
171
|
+
"credentialMappings": [
|
|
172
|
+
{
|
|
173
|
+
"credential": "access_token",
|
|
174
|
+
"source": "access_token"
|
|
175
|
+
},
|
|
176
|
+
{
|
|
177
|
+
"credential": "refresh_token",
|
|
178
|
+
"source": "refresh_token"
|
|
179
|
+
}
|
|
180
|
+
],
|
|
181
|
+
"refresh": {
|
|
182
|
+
"acceptedScopeSets": [
|
|
183
|
+
[
|
|
184
|
+
"https://www.googleapis.com/auth/youtube.readonly"
|
|
185
|
+
],
|
|
186
|
+
[
|
|
187
|
+
"https://www.googleapis.com/auth/youtube"
|
|
188
|
+
]
|
|
189
|
+
],
|
|
190
|
+
"missingExpiry": "reject",
|
|
191
|
+
"scopeSeparators": "whitespaceAndComma",
|
|
192
|
+
"storedMissingExpiry": "refresh",
|
|
193
|
+
"terminalErrorCodes": [
|
|
194
|
+
"invalid_grant",
|
|
195
|
+
"invalid_client",
|
|
196
|
+
"unauthorized_client"
|
|
197
|
+
],
|
|
198
|
+
"tokenExchangeTimeout": "25s"
|
|
199
|
+
},
|
|
200
|
+
"scopes": [
|
|
201
|
+
"https://www.googleapis.com/auth/youtube.readonly"
|
|
202
|
+
],
|
|
203
|
+
"tokenEndpoint": "https://oauth2.googleapis.com/token"
|
|
204
|
+
},
|
|
205
|
+
"type": "oauth2"
|
|
206
|
+
},
|
|
207
|
+
{
|
|
208
|
+
"fields": [
|
|
209
|
+
{
|
|
210
|
+
"name": "oauth_client_id",
|
|
211
|
+
"required": true,
|
|
212
|
+
"type": "string"
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
"name": "oauth_client_secret",
|
|
216
|
+
"required": true,
|
|
217
|
+
"type": "secretString"
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
"name": "access_token",
|
|
221
|
+
"required": true,
|
|
222
|
+
"type": "secretString"
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
"name": "refresh_token",
|
|
226
|
+
"required": true,
|
|
227
|
+
"type": "secretString"
|
|
228
|
+
}
|
|
229
|
+
],
|
|
230
|
+
"id": "google-oauth-manage",
|
|
231
|
+
"oauth2": {
|
|
232
|
+
"clientIDCredential": "oauth_client_id",
|
|
233
|
+
"clientSecretCredential": "oauth_client_secret",
|
|
234
|
+
"credentialMappings": [
|
|
235
|
+
{
|
|
236
|
+
"credential": "access_token",
|
|
237
|
+
"source": "access_token"
|
|
238
|
+
},
|
|
239
|
+
{
|
|
240
|
+
"credential": "refresh_token",
|
|
241
|
+
"source": "refresh_token"
|
|
242
|
+
}
|
|
243
|
+
],
|
|
244
|
+
"refresh": {
|
|
245
|
+
"missingExpiry": "reject",
|
|
246
|
+
"scopeSeparators": "whitespaceAndComma",
|
|
247
|
+
"storedMissingExpiry": "refresh",
|
|
248
|
+
"terminalErrorCodes": [
|
|
249
|
+
"invalid_grant",
|
|
250
|
+
"invalid_client",
|
|
251
|
+
"unauthorized_client"
|
|
252
|
+
],
|
|
253
|
+
"tokenExchangeTimeout": "25s"
|
|
254
|
+
},
|
|
255
|
+
"scopes": [
|
|
256
|
+
"https://www.googleapis.com/auth/youtube"
|
|
257
|
+
],
|
|
258
|
+
"tokenEndpoint": "https://oauth2.googleapis.com/token"
|
|
259
|
+
},
|
|
260
|
+
"type": "oauth2"
|
|
261
|
+
}
|
|
262
|
+
],
|
|
263
|
+
"refreshable": true
|
|
264
|
+
};
|
|
265
|
+
var CredentialFields = {
|
|
266
|
+
"access_token": "accessToken",
|
|
267
|
+
"oauth_client_id": "oauthClientId",
|
|
268
|
+
"oauth_client_secret": "oauthClientSecret",
|
|
269
|
+
"refresh_token": "refreshToken"
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
// src/operations.ts
|
|
273
|
+
import { newQueryBranch, newQueryRetry, newMutationBranch, newMutationRetry, newMutationUncertain, zeroReceipt } from "@superdurable/connectors-sdk";
|
|
274
|
+
import { Fence } from "@superdurable/connectors-sdk/singledispatch";
|
|
275
|
+
var videoID = /^[A-Za-z0-9_-]{11}$/;
|
|
276
|
+
var channelID = /^UC[A-Za-z0-9_-]{22}$/;
|
|
277
|
+
var playlistID = /^[A-Za-z0-9_-]{2,64}$/;
|
|
278
|
+
var handle = /^@?[A-Za-z0-9._-]{3,30}$/;
|
|
279
|
+
var pageToken = /^[A-Za-z0-9_-]+$/;
|
|
280
|
+
var zeroSearch = { results: [], totalResults: 0 };
|
|
281
|
+
var zeroVideo = { id: "", channelId: "", channelTitle: "", title: "", description: "", publishedAt: "0001-01-01T00:00:00Z", privacyStatus: "" };
|
|
282
|
+
var zeroChannel = { id: "", title: "", description: "", publishedAt: "0001-01-01T00:00:00Z", uploadsPlaylistId: "" };
|
|
283
|
+
var zeroPage = { items: [], totalResults: 0 };
|
|
284
|
+
var zeroItem = { id: "", playlistId: "", videoId: "", title: "", position: 0, addedAt: "0001-01-01T00:00:00Z" };
|
|
285
|
+
var zeroAdded = { item: zeroItem, wasAlreadyPresent: false };
|
|
286
|
+
function failure(operation, kind, message) {
|
|
287
|
+
return { kind, provider: "youtube", operation, message };
|
|
288
|
+
}
|
|
289
|
+
function receipt(call, objectID, response) {
|
|
290
|
+
const headers = response?.headers;
|
|
291
|
+
const requestIDValue = headers?.["x-goog-request-id"];
|
|
292
|
+
const requestID = Array.isArray(requestIDValue) ? requestIDValue[0] : requestIDValue;
|
|
293
|
+
return { callId: call.id, ...call.idempotencyKey ? { idempotencyKey: call.idempotencyKey } : {}, provider: "youtube", providerObjectId: objectID, observedAt: (/* @__PURE__ */ new Date()).toISOString(), ...requestID && requestID.length <= 128 && pageToken.test(requestID) ? { providerRequestId: requestID } : {} };
|
|
294
|
+
}
|
|
295
|
+
function queryError(operation, error, empty, call, objectID, notFound = false) {
|
|
296
|
+
if (!(error instanceof YouTubeExchangeError)) throw error;
|
|
297
|
+
const detail = failure(operation, error.kind, error.message);
|
|
298
|
+
if (error.disposition === "retry") return newQueryRetry(detail, error.retryAfterMs);
|
|
299
|
+
return newQueryBranch(error.disposition === "notFound" && !notFound ? "providerRejected" : error.disposition, empty, error.response ? receipt(call, objectID, error.response) : zeroReceipt(), detail);
|
|
300
|
+
}
|
|
301
|
+
function mutationError(operation, error, call, objectID) {
|
|
302
|
+
if (!(error instanceof YouTubeExchangeError)) throw error;
|
|
303
|
+
const detail = failure(operation, error.kind, error.message);
|
|
304
|
+
if (error.disposition === "retry") return newMutationRetry(detail, error.retryAfterMs);
|
|
305
|
+
return newMutationBranch(error.disposition, zeroAdded, error.response || error.message.startsWith("addPlaylistItem requires") ? receipt(call, objectID, error.response) : zeroReceipt(), detail);
|
|
306
|
+
}
|
|
307
|
+
function defect(operation, empty, message) {
|
|
308
|
+
return newQueryBranch("defect", empty, zeroReceipt(), failure(operation, "VALIDATION", message));
|
|
309
|
+
}
|
|
310
|
+
function invalid(operation, empty, message, call, objectID, response) {
|
|
311
|
+
return newQueryBranch("invalidResponse", empty, receipt(call, objectID, response), failure(operation, "PROTOCOL", message));
|
|
312
|
+
}
|
|
313
|
+
function object(value) {
|
|
314
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("invalid provider object");
|
|
315
|
+
return value;
|
|
316
|
+
}
|
|
317
|
+
function field(source, name) {
|
|
318
|
+
const value = source[name];
|
|
319
|
+
if (value === void 0 || value === null) return "";
|
|
320
|
+
if (typeof value !== "string") throw new TypeError(`invalid provider ${name}`);
|
|
321
|
+
return value;
|
|
322
|
+
}
|
|
323
|
+
function integer(source, name) {
|
|
324
|
+
const value = source[name];
|
|
325
|
+
if (value === void 0 || value === null) return 0;
|
|
326
|
+
if (!Number.isSafeInteger(value)) throw new TypeError(`invalid provider ${name}`);
|
|
327
|
+
return value;
|
|
328
|
+
}
|
|
329
|
+
function optionalCount(source, name) {
|
|
330
|
+
const value = source[name];
|
|
331
|
+
if (value === void 0 || value === null) return void 0;
|
|
332
|
+
if (typeof value !== "string" || !/^[+-]?\d+$/.test(value)) throw new TypeError("invalid statistic");
|
|
333
|
+
const count = Number(value);
|
|
334
|
+
if (!Number.isSafeInteger(count) || count < 0) throw new TypeError("invalid statistic");
|
|
335
|
+
return count;
|
|
336
|
+
}
|
|
337
|
+
function timestamp(value) {
|
|
338
|
+
if (!value.trim()) throw new TypeError("missing timestamp");
|
|
339
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
340
|
+
if (!match) throw new TypeError("invalid timestamp");
|
|
341
|
+
const year = Number(match[1]), month = Number(match[2]), day = Number(match[3]), hour = Number(match[4]), minute = Number(match[5]), second = Number(match[6]);
|
|
342
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
343
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 30];
|
|
344
|
+
if (month < 1 || month > 12 || day < 1 || day > days[month - 1] || hour > 23 || minute > 59 || second > 59 || match[8] !== "Z" && Number(match[8].slice(-2)) > 59) throw new TypeError("invalid timestamp");
|
|
345
|
+
const fraction = (match[7] ?? "").slice(0, 9).replace(/0+$/, "");
|
|
346
|
+
const calendar = /* @__PURE__ */ new Date(`${value.slice(0, 19)}Z`);
|
|
347
|
+
if (Number.isNaN(calendar.getTime())) throw new TypeError("invalid timestamp");
|
|
348
|
+
const offset = match[8];
|
|
349
|
+
const minutes = offset === "Z" ? 0 : (Number(offset.slice(1, 3)) * 60 + Number(offset.slice(4, 6))) * (offset[0] === "+" ? 1 : -1);
|
|
350
|
+
const parsed = new Date(calendar.getTime() - minutes * 6e4);
|
|
351
|
+
const milliseconds = parsed.toISOString().slice(0, 19);
|
|
352
|
+
return `${milliseconds}${fraction ? `.${fraction}` : ""}Z`;
|
|
353
|
+
}
|
|
354
|
+
function optionalTimestamp(value) {
|
|
355
|
+
return value.trim() ? timestamp(value) : void 0;
|
|
356
|
+
}
|
|
357
|
+
function decoded(response) {
|
|
358
|
+
return object(JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(response.body)));
|
|
359
|
+
}
|
|
360
|
+
function pageFields(source) {
|
|
361
|
+
if (!Array.isArray(source.items) || !source.pageInfo) throw new TypeError("incomplete page");
|
|
362
|
+
const next = field(source, "nextPageToken");
|
|
363
|
+
if (next && (next.length > 256 || !pageToken.test(next))) throw new TypeError("invalid nextPageToken");
|
|
364
|
+
return { ...next ? { nextPageToken: next } : {}, totalResults: integer(object(source.pageInfo), "totalResults"), items: source.items };
|
|
365
|
+
}
|
|
366
|
+
function validatePage(query, maxResults, token) {
|
|
367
|
+
const size = maxResults ?? 0;
|
|
368
|
+
if (!Number.isSafeInteger(size) || size < 0 || size > 50) return "maxResults must be from 1 through 50, or zero for YouTube's default of 5";
|
|
369
|
+
if (size) query.maxResults = String(size);
|
|
370
|
+
if (token) {
|
|
371
|
+
if (token.length > 256 || !pageToken.test(token)) return "pageToken must be a nextPageToken returned by YouTube";
|
|
372
|
+
query.pageToken = token;
|
|
373
|
+
}
|
|
374
|
+
return void 0;
|
|
375
|
+
}
|
|
376
|
+
function playlistQuery(input) {
|
|
377
|
+
if (!playlistID.test(input.playlistId)) return { error: "playlistId must be a YouTube playlist ID" };
|
|
378
|
+
const query = { part: "snippet,contentDetails", playlistId: input.playlistId };
|
|
379
|
+
if (input.videoId) {
|
|
380
|
+
if (!videoID.test(input.videoId)) return { error: "videoId must be an 11-character YouTube video ID" };
|
|
381
|
+
query.videoId = input.videoId;
|
|
382
|
+
}
|
|
383
|
+
const error = validatePage(query, input.maxResults, input.pageToken);
|
|
384
|
+
return error ? { error } : { query };
|
|
385
|
+
}
|
|
386
|
+
function playlistItem(value, playlist) {
|
|
387
|
+
const item = object(value), snippet = object(item.snippet ?? {}), resource = object(snippet.resourceId ?? {}), content = object(item.contentDetails ?? {});
|
|
388
|
+
const id = field(item, "id"), video = field(resource, "videoId"), position = integer(snippet, "position");
|
|
389
|
+
if (!id || id.length > 128 || !pageToken.test(id)) throw new TypeError("invalid item ID");
|
|
390
|
+
if (field(snippet, "playlistId") !== playlist || field(resource, "kind") !== "youtube#video" || !videoID.test(video) || position < 0) throw new TypeError("invalid playlist item");
|
|
391
|
+
const result = { id, playlistId: playlist, videoId: video, title: field(snippet, "title"), position, addedAt: timestamp(field(snippet, "publishedAt")) };
|
|
392
|
+
const published = optionalTimestamp(field(content, "videoPublishedAt"));
|
|
393
|
+
if (published) result.videoPublishedAt = published;
|
|
394
|
+
return result;
|
|
395
|
+
}
|
|
396
|
+
function playlistPage(response, input) {
|
|
397
|
+
const fields = pageFields(decoded(response));
|
|
398
|
+
if (fields.items.length > 50) throw new TypeError("too many items");
|
|
399
|
+
const items = fields.items.map((value) => playlistItem(value, input.playlistId));
|
|
400
|
+
if (input.videoId && items.some((item) => item.videoId !== input.videoId)) throw new TypeError("wrong video");
|
|
401
|
+
return { items, totalResults: fields.totalResults, ...fields.nextPageToken ? { nextPageToken: fields.nextPageToken } : {} };
|
|
402
|
+
}
|
|
403
|
+
var SearchVideosOperation = class {
|
|
404
|
+
/** Bind a client. */
|
|
405
|
+
constructor(client) {
|
|
406
|
+
this.client = client;
|
|
407
|
+
}
|
|
408
|
+
client;
|
|
409
|
+
/** Return manifest definition. */
|
|
410
|
+
definition() {
|
|
411
|
+
return SearchVideosDefinition;
|
|
412
|
+
}
|
|
413
|
+
/** Invoke the search query. */
|
|
414
|
+
async invoke(call, input) {
|
|
415
|
+
const operation = "searchVideos", query = { part: "snippet", type: "video" };
|
|
416
|
+
if (!input.query?.trim() && !input.channelId) return defect(operation, zeroSearch, "query or channelId must be set");
|
|
417
|
+
if ([...input.query ?? ""].length > 500) return defect(operation, zeroSearch, "query must be valid UTF-8 of at most 500 characters");
|
|
418
|
+
if (input.query?.trim()) query.q = input.query;
|
|
419
|
+
if (input.channelId) {
|
|
420
|
+
if (!channelID.test(input.channelId)) return defect(operation, zeroSearch, "channelId must be a YouTube channel ID: UC followed by 22 characters");
|
|
421
|
+
query.channelId = input.channelId;
|
|
422
|
+
}
|
|
423
|
+
if (input.order) {
|
|
424
|
+
if (!["relevance", "date", "viewCount", "rating", "title"].includes(input.order)) return defect(operation, zeroSearch, "order must be relevance, date, viewCount, rating, or title");
|
|
425
|
+
query.order = input.order;
|
|
426
|
+
}
|
|
427
|
+
if (input.publishedAfter) query.publishedAfter = new Date(input.publishedAfter).toISOString().replace(".000Z", "Z");
|
|
428
|
+
const error = validatePage(query, input.maxResults, input.pageToken);
|
|
429
|
+
if (error) return defect(operation, zeroSearch, error);
|
|
430
|
+
let response;
|
|
431
|
+
try {
|
|
432
|
+
response = await this.client.exchange(call, operation, "/search", query);
|
|
433
|
+
} catch (cause) {
|
|
434
|
+
return queryError(operation, cause, zeroSearch, call, input.channelId ?? "");
|
|
435
|
+
}
|
|
436
|
+
try {
|
|
437
|
+
const fields = pageFields(decoded(response));
|
|
438
|
+
if (fields.items.length > Math.max(input.maxResults ?? 0, 5) && fields.items.length > 50) throw new TypeError("too many results");
|
|
439
|
+
const results = fields.items.map((value) => {
|
|
440
|
+
const item = object(value), id = object(item.id ?? {}), snippet = object(item.snippet ?? {});
|
|
441
|
+
if (field(id, "kind") !== "youtube#video" || !videoID.test(field(id, "videoId")) || !channelID.test(field(snippet, "channelId"))) throw new TypeError("invalid video");
|
|
442
|
+
return { videoId: field(id, "videoId"), channelId: field(snippet, "channelId"), channelTitle: field(snippet, "channelTitle"), title: field(snippet, "title"), description: field(snippet, "description"), publishedAt: timestamp(field(snippet, "publishedAt")) };
|
|
443
|
+
});
|
|
444
|
+
return newQueryBranch("searched", { results, totalResults: fields.totalResults, ...fields.nextPageToken ? { nextPageToken: fields.nextPageToken } : {} }, receipt(call, input.channelId ?? "", response));
|
|
445
|
+
} catch {
|
|
446
|
+
return invalid(operation, zeroSearch, "YouTube returned an incomplete search page", call, input.channelId ?? "", response);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
};
|
|
450
|
+
var GetVideoOperation = class {
|
|
451
|
+
/** Bind a client. */
|
|
452
|
+
constructor(client) {
|
|
453
|
+
this.client = client;
|
|
454
|
+
}
|
|
455
|
+
client;
|
|
456
|
+
/** Return manifest definition. */
|
|
457
|
+
definition() {
|
|
458
|
+
return GetVideoDefinition;
|
|
459
|
+
}
|
|
460
|
+
/** Invoke the video query. */
|
|
461
|
+
async invoke(call, input) {
|
|
462
|
+
const operation = "getVideo";
|
|
463
|
+
if (!videoID.test(input.videoId)) return defect(operation, zeroVideo, "videoId must be an 11-character YouTube video ID");
|
|
464
|
+
let response;
|
|
465
|
+
try {
|
|
466
|
+
response = await this.client.exchange(call, operation, "/videos", { id: input.videoId, part: "snippet,contentDetails,status,statistics" });
|
|
467
|
+
} catch (cause) {
|
|
468
|
+
return queryError(operation, cause, zeroVideo, call, input.videoId, true);
|
|
469
|
+
}
|
|
470
|
+
let items;
|
|
471
|
+
try {
|
|
472
|
+
const parsed = decoded(response);
|
|
473
|
+
if (!Array.isArray(parsed.items)) throw new TypeError();
|
|
474
|
+
items = parsed.items;
|
|
475
|
+
} catch {
|
|
476
|
+
return invalid(operation, zeroVideo, "YouTube returned a malformed video list", call, input.videoId, response);
|
|
477
|
+
}
|
|
478
|
+
if (!items.length) return newQueryBranch("notFound", zeroVideo, receipt(call, input.videoId, response), failure(operation, "NOT_FOUND", "no visible YouTube video has the ID"));
|
|
479
|
+
try {
|
|
480
|
+
if (items.length !== 1) throw new TypeError();
|
|
481
|
+
const item = object(items[0]), snippet = object(item.snippet ?? {}), content = object(item.contentDetails ?? {}), status = object(item.status ?? {}), stats = object(item.statistics ?? {});
|
|
482
|
+
if (field(item, "id") !== input.videoId || !channelID.test(field(snippet, "channelId"))) throw new TypeError();
|
|
483
|
+
const result = { id: input.videoId, channelId: field(snippet, "channelId"), channelTitle: field(snippet, "channelTitle"), title: field(snippet, "title"), description: field(snippet, "description"), publishedAt: timestamp(field(snippet, "publishedAt")), privacyStatus: field(status, "privacyStatus") };
|
|
484
|
+
const duration = field(content, "duration");
|
|
485
|
+
if (duration) result.duration = duration;
|
|
486
|
+
for (const [source, destination] of [["viewCount", "viewCount"], ["likeCount", "likeCount"], ["commentCount", "commentCount"]]) {
|
|
487
|
+
const count = optionalCount(stats, source);
|
|
488
|
+
if (count !== void 0) result[destination] = count;
|
|
489
|
+
}
|
|
490
|
+
return newQueryBranch("found", result, receipt(call, input.videoId, response));
|
|
491
|
+
} catch {
|
|
492
|
+
return invalid(operation, zeroVideo, "YouTube returned a different or invalid video", call, input.videoId, response);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
};
|
|
496
|
+
var GetChannelOperation = class {
|
|
497
|
+
/** Bind a client. */
|
|
498
|
+
constructor(client) {
|
|
499
|
+
this.client = client;
|
|
500
|
+
}
|
|
501
|
+
client;
|
|
502
|
+
/** Return manifest definition. */
|
|
503
|
+
definition() {
|
|
504
|
+
return GetChannelDefinition;
|
|
505
|
+
}
|
|
506
|
+
/** Invoke the channel query. */
|
|
507
|
+
async invoke(call, input) {
|
|
508
|
+
const operation = "getChannel", query = { part: "snippet,contentDetails,statistics" };
|
|
509
|
+
let objectID = "";
|
|
510
|
+
let selectors = 0;
|
|
511
|
+
if (input.channelId) {
|
|
512
|
+
selectors++;
|
|
513
|
+
if (!channelID.test(input.channelId)) return defect(operation, zeroChannel, "channelId must be a YouTube channel ID: UC followed by 22 characters");
|
|
514
|
+
query.id = input.channelId;
|
|
515
|
+
objectID = input.channelId;
|
|
516
|
+
}
|
|
517
|
+
if (input.handle) {
|
|
518
|
+
selectors++;
|
|
519
|
+
if (!handle.test(input.handle)) return defect(operation, zeroChannel, "handle must be a YouTube handle of 3 to 30 letters, digits, periods, hyphens, or underscores");
|
|
520
|
+
objectID = `@${input.handle.replace(/^@/, "")}`;
|
|
521
|
+
query.forHandle = objectID;
|
|
522
|
+
}
|
|
523
|
+
if (input.mine) {
|
|
524
|
+
selectors++;
|
|
525
|
+
query.mine = "true";
|
|
526
|
+
}
|
|
527
|
+
if (selectors !== 1) return defect(operation, zeroChannel, "set exactly one of channelId, handle, and mine");
|
|
528
|
+
let response;
|
|
529
|
+
try {
|
|
530
|
+
response = await this.client.exchange(call, operation, "/channels", query);
|
|
531
|
+
} catch (cause) {
|
|
532
|
+
return queryError(operation, cause, zeroChannel, call, objectID, true);
|
|
533
|
+
}
|
|
534
|
+
try {
|
|
535
|
+
const parsed = decoded(response), items = parsed.items === void 0 || parsed.items === null ? [] : parsed.items;
|
|
536
|
+
if (!Array.isArray(items)) throw new TypeError();
|
|
537
|
+
if (!items.length) return newQueryBranch("notFound", zeroChannel, receipt(call, objectID, response), failure(operation, "NOT_FOUND", "no YouTube channel matches the request"));
|
|
538
|
+
if (items.length !== 1) throw new TypeError();
|
|
539
|
+
const item = object(items[0]), snippet = object(item.snippet ?? {}), content = object(item.contentDetails ?? {}), related = object(content.relatedPlaylists ?? {}), stats = object(item.statistics ?? {}), id = field(item, "id"), uploads = field(related, "uploads");
|
|
540
|
+
if (!channelID.test(id) || input.channelId && id !== input.channelId || !playlistID.test(uploads)) throw new TypeError();
|
|
541
|
+
const result = { id, title: field(snippet, "title"), description: field(snippet, "description"), publishedAt: timestamp(field(snippet, "publishedAt")), uploadsPlaylistId: uploads };
|
|
542
|
+
const custom = field(snippet, "customUrl");
|
|
543
|
+
if (custom) result.customUrl = custom;
|
|
544
|
+
const hidden = stats.hiddenSubscriberCount;
|
|
545
|
+
if (hidden !== void 0 && hidden !== null && typeof hidden !== "boolean") throw new TypeError();
|
|
546
|
+
if (!hidden) {
|
|
547
|
+
const count = optionalCount(stats, "subscriberCount");
|
|
548
|
+
if (count !== void 0) result.subscriberCount = count;
|
|
549
|
+
}
|
|
550
|
+
for (const key of ["videoCount", "viewCount"]) {
|
|
551
|
+
const count = optionalCount(stats, key);
|
|
552
|
+
if (count !== void 0) result[key] = count;
|
|
553
|
+
}
|
|
554
|
+
return newQueryBranch("found", result, receipt(call, id, response));
|
|
555
|
+
} catch {
|
|
556
|
+
return invalid(operation, zeroChannel, "YouTube returned a different channel or an invalid channel ID", call, objectID, response);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
var ListPlaylistItemsOperation = class {
|
|
561
|
+
/** Bind a client. */
|
|
562
|
+
constructor(client) {
|
|
563
|
+
this.client = client;
|
|
564
|
+
}
|
|
565
|
+
client;
|
|
566
|
+
/** Return manifest definition. */
|
|
567
|
+
definition() {
|
|
568
|
+
return ListPlaylistItemsDefinition;
|
|
569
|
+
}
|
|
570
|
+
/** Invoke the playlist query. */
|
|
571
|
+
async invoke(call, input) {
|
|
572
|
+
const operation = "listPlaylistItems", encoded = playlistQuery(input);
|
|
573
|
+
if (encoded.error) return defect(operation, zeroPage, encoded.error);
|
|
574
|
+
let response;
|
|
575
|
+
try {
|
|
576
|
+
response = await this.client.exchange(call, operation, "/playlistItems", encoded.query);
|
|
577
|
+
} catch (cause) {
|
|
578
|
+
return queryError(operation, cause, zeroPage, call, input.playlistId, true);
|
|
579
|
+
}
|
|
580
|
+
try {
|
|
581
|
+
return newQueryBranch("listed", playlistPage(response, input), receipt(call, input.playlistId, response));
|
|
582
|
+
} catch {
|
|
583
|
+
return invalid(operation, zeroPage, "YouTube returned an incomplete playlist page", call, input.playlistId, response);
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
};
|
|
587
|
+
var AddPlaylistItemOperation = class {
|
|
588
|
+
/** Bind a client. */
|
|
589
|
+
constructor(client) {
|
|
590
|
+
this.client = client;
|
|
591
|
+
}
|
|
592
|
+
client;
|
|
593
|
+
/** Return manifest definition. */
|
|
594
|
+
definition() {
|
|
595
|
+
return AddPlaylistItemDefinition;
|
|
596
|
+
}
|
|
597
|
+
/** Use the stable Call ID as the Dex idempotency key; YouTube does not accept it. */
|
|
598
|
+
idempotencyKey(callID) {
|
|
599
|
+
return callID;
|
|
600
|
+
}
|
|
601
|
+
/** Check membership and insert at most once per Step call. */
|
|
602
|
+
async invoke(call, input) {
|
|
603
|
+
const operation = "addPlaylistItem", listInput = { playlistId: input.playlistId, videoId: input.videoId, maxResults: 1 }, encoded = playlistQuery(listInput);
|
|
604
|
+
if (encoded.error || !input.videoId) return newMutationBranch("defect", zeroAdded, zeroReceipt(), failure(operation, "VALIDATION", encoded.error ?? "videoId must be an 11-character YouTube video ID"));
|
|
605
|
+
let fence;
|
|
606
|
+
try {
|
|
607
|
+
fence = new Fence(call, AddPlaylistItemDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
|
|
608
|
+
} catch {
|
|
609
|
+
return newMutationBranch("defect", zeroAdded, zeroReceipt(), failure(operation, "LOCAL_DEFECT", "the YouTube dispatch fence is unavailable"));
|
|
610
|
+
}
|
|
611
|
+
const decision = fence.decide();
|
|
612
|
+
if (decision.kind === "readBackRequired") return this.confirmEarlierInsert(call, listInput, encoded.query);
|
|
613
|
+
if (decision.kind !== "sendAllowed") return newMutationUncertain(zeroAdded, failure(operation, "TRANSPORT", "the YouTube dispatch checkpoint is unreadable, so an earlier insert cannot be ruled out; check the playlist before adding the video again"), zeroReceipt());
|
|
614
|
+
let response;
|
|
615
|
+
try {
|
|
616
|
+
response = await this.client.exchange(call, operation, "/playlistItems", encoded.query, true);
|
|
617
|
+
} catch (cause) {
|
|
618
|
+
if (cause instanceof YouTubeExchangeError && cause.disposition === "retry") {
|
|
619
|
+
try {
|
|
620
|
+
await fence.recordNotSent();
|
|
621
|
+
} catch {
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
return mutationError(operation, cause, call, input.playlistId);
|
|
625
|
+
}
|
|
626
|
+
let page;
|
|
627
|
+
try {
|
|
628
|
+
page = playlistPage(response, listInput);
|
|
629
|
+
} catch {
|
|
630
|
+
return newMutationBranch("invalidResponse", zeroAdded, receipt(call, input.playlistId, response), failure(operation, "PROTOCOL", "YouTube returned an incomplete playlist page"));
|
|
631
|
+
}
|
|
632
|
+
if (page.items?.length) return newMutationBranch("added", { item: page.items[0], wasAlreadyPresent: true }, receipt(call, page.items[0].id, response));
|
|
633
|
+
const body = JSON.stringify({ snippet: { playlistId: input.playlistId, resourceId: { kind: "youtube#video", videoId: input.videoId } } });
|
|
634
|
+
try {
|
|
635
|
+
response = await this.client.exchange(call, operation, "/playlistItems", { part: "snippet,contentDetails" }, true, body, fence);
|
|
636
|
+
} catch (cause) {
|
|
637
|
+
if (cause instanceof YouTubeExchangeError && cause.disposition === "retryUnprocessed") {
|
|
638
|
+
try {
|
|
639
|
+
await fence.recordCanResend();
|
|
640
|
+
} catch {
|
|
641
|
+
}
|
|
642
|
+
return newMutationRetry(failure(operation, cause.kind, cause.message), cause.retryAfterMs);
|
|
643
|
+
}
|
|
644
|
+
if (cause instanceof YouTubeExchangeError && cause.disposition === "writeUnconfirmed") return newMutationRetry(failure(operation, cause.kind, cause.message));
|
|
645
|
+
return mutationError(operation, cause, call, input.playlistId);
|
|
646
|
+
}
|
|
647
|
+
let inserted;
|
|
648
|
+
try {
|
|
649
|
+
inserted = decoded(response);
|
|
650
|
+
} catch {
|
|
651
|
+
return newMutationRetry(failure(operation, "PROTOCOL", "YouTube returned a malformed insert response; the next attempt reads the playlist back"));
|
|
652
|
+
}
|
|
653
|
+
let item;
|
|
654
|
+
try {
|
|
655
|
+
item = playlistItem(inserted, input.playlistId);
|
|
656
|
+
if (item.videoId !== input.videoId) throw new TypeError("YouTube returned an item for a different video");
|
|
657
|
+
} catch {
|
|
658
|
+
return newMutationBranch("invalidResponse", zeroAdded, receipt(call, input.playlistId, response), failure(operation, "PROTOCOL", "YouTube returned an invalid or different inserted item"));
|
|
659
|
+
}
|
|
660
|
+
try {
|
|
661
|
+
await fence.recordProviderId(item.id);
|
|
662
|
+
} catch {
|
|
663
|
+
}
|
|
664
|
+
return newMutationBranch("added", { item, wasAlreadyPresent: false }, receipt(call, item.id, response));
|
|
665
|
+
}
|
|
666
|
+
/** List the playlist after an attempt that may have inserted; only a shown item confirms it. */
|
|
667
|
+
async confirmEarlierInsert(call, listInput, query) {
|
|
668
|
+
const operation = "addPlaylistItem";
|
|
669
|
+
let response;
|
|
670
|
+
try {
|
|
671
|
+
response = await this.client.exchange(call, operation, "/playlistItems", query, true);
|
|
672
|
+
} catch (cause) {
|
|
673
|
+
if (!(cause instanceof YouTubeExchangeError)) throw cause;
|
|
674
|
+
if (cause.disposition === "retry") return newMutationRetry(failure(operation, cause.kind, cause.message), cause.retryAfterMs);
|
|
675
|
+
const readBackReceipt = cause.response || cause.message.startsWith("addPlaylistItem requires") ? receipt(call, listInput.playlistId, cause.response) : zeroReceipt();
|
|
676
|
+
return newMutationUncertain(zeroAdded, failure(operation, cause.kind, `an earlier attempt may have added the video, and the playlist could not be read back: ${cause.message}`), readBackReceipt);
|
|
677
|
+
}
|
|
678
|
+
let page;
|
|
679
|
+
try {
|
|
680
|
+
page = playlistPage(response, listInput);
|
|
681
|
+
} catch {
|
|
682
|
+
return newMutationUncertain(zeroAdded, failure(operation, "PROTOCOL", "an earlier attempt may have added the video, and the playlist could not be read back: YouTube returned an incomplete playlist page"), receipt(call, listInput.playlistId, response));
|
|
683
|
+
}
|
|
684
|
+
if (page.items?.length) return newMutationBranch("added", { item: page.items[0], wasAlreadyPresent: true }, receipt(call, page.items[0].id, response));
|
|
685
|
+
return newMutationUncertain(zeroAdded, failure(operation, "TRANSPORT", "an earlier attempt may have added the video, and the playlist listing does not show it yet; check the playlist before adding the video again"), receipt(call, listInput.playlistId, response));
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
|
|
689
|
+
// src/client.ts
|
|
690
|
+
var defaultEndpoint = "https://www.googleapis.com/youtube/v3";
|
|
691
|
+
var defaultResponseBytes = 4194304;
|
|
692
|
+
var defaultTimeoutMs = 25e3;
|
|
693
|
+
var YouTubeExchangeError = class extends Error {
|
|
694
|
+
constructor(disposition, kind, message, response, retryAfterMs = 0) {
|
|
695
|
+
super(message);
|
|
696
|
+
this.disposition = disposition;
|
|
697
|
+
this.kind = kind;
|
|
698
|
+
this.response = response;
|
|
699
|
+
this.retryAfterMs = retryAfterMs;
|
|
700
|
+
}
|
|
701
|
+
disposition;
|
|
702
|
+
kind;
|
|
703
|
+
response;
|
|
704
|
+
retryAfterMs;
|
|
705
|
+
};
|
|
706
|
+
var YouTubeClient = class {
|
|
707
|
+
/** Validate the connection and bind host-owned renewable credentials. */
|
|
708
|
+
constructor(config, credentials, options = {}) {
|
|
709
|
+
this.credentials = credentials;
|
|
710
|
+
if (!credentials) throw new TypeError("YouTube credential source is required");
|
|
711
|
+
this.endpoint = validateBaseURL(config.endpoint || defaultEndpoint);
|
|
712
|
+
this.maxResponseBytes = config.maxResponseBytes || defaultResponseBytes;
|
|
713
|
+
this.timeoutMs = config.timeoutMs || defaultTimeoutMs;
|
|
714
|
+
if (!Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("YouTube maxResponseBytes must be positive");
|
|
715
|
+
if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0) throw new TypeError("YouTube timeout must be positive");
|
|
716
|
+
this.send = options.send ?? sendProviderRequest;
|
|
717
|
+
this.now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
718
|
+
}
|
|
719
|
+
credentials;
|
|
720
|
+
endpoint;
|
|
721
|
+
maxResponseBytes;
|
|
722
|
+
timeoutMs;
|
|
723
|
+
now;
|
|
724
|
+
send;
|
|
725
|
+
refreshDriver = new ManifestCredentialRefreshDriver({ providerName: "YouTube", auth: Authorization, credentialFields: CredentialFields });
|
|
726
|
+
/** Bind the search query. */
|
|
727
|
+
searchVideos() {
|
|
728
|
+
return new SearchVideosOperation(this);
|
|
729
|
+
}
|
|
730
|
+
/** Bind the video query. */
|
|
731
|
+
getVideo() {
|
|
732
|
+
return new GetVideoOperation(this);
|
|
733
|
+
}
|
|
734
|
+
/** Bind the channel query. */
|
|
735
|
+
getChannel() {
|
|
736
|
+
return new GetChannelOperation(this);
|
|
737
|
+
}
|
|
738
|
+
/** Bind the playlist query. */
|
|
739
|
+
listPlaylistItems() {
|
|
740
|
+
return new ListPlaylistItemsOperation(this);
|
|
741
|
+
}
|
|
742
|
+
/** Bind the playlist mutation. */
|
|
743
|
+
addPlaylistItem() {
|
|
744
|
+
return new AddPlaylistItemOperation(this);
|
|
745
|
+
}
|
|
746
|
+
/** Send one request, resolving and refreshing credentials as the host requires; a write fence sends it at most once. */
|
|
747
|
+
async exchange(call, operation, path, query, requiresManage = false, body, writeFence) {
|
|
748
|
+
let credentials;
|
|
749
|
+
try {
|
|
750
|
+
credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
|
|
751
|
+
} catch (error) {
|
|
752
|
+
if (error instanceof ReauthorizationRequiredError) throw new YouTubeExchangeError("providerRejected", "AUTHENTICATION", "the YouTube connection must be authorized again");
|
|
753
|
+
throw new YouTubeExchangeError("defect", "AUTHENTICATION", "YouTube connection credentials are unavailable or invalid");
|
|
754
|
+
}
|
|
755
|
+
if (!credentials.accessToken || !isHeaderSafeCredential(credentials.accessToken.reveal())) throw new YouTubeExchangeError("defect", "AUTHENTICATION", "YouTube connection credentials are unavailable or invalid");
|
|
756
|
+
if (requiresManage && credentials.authMethodId !== "google-oauth-manage") throw new YouTubeExchangeError("providerRejected", "AUTHORIZATION", "addPlaylistItem requires a YouTube connection authorized with the google-oauth-manage method and its youtube scope");
|
|
757
|
+
const encoded = Object.keys(query).sort((left, right) => Buffer.compare(Buffer.from(left), Buffer.from(right))).map((key) => `${goQueryEscape(key)}=${goQueryEscape(query[key])}`).join("&");
|
|
758
|
+
const url = `${this.endpoint}${path}${encoded ? `?${encoded}` : ""}`;
|
|
759
|
+
if (!writeFence) return this.sendAndClassify(call, operation, url, credentials, body, call.context.cancellationSignal, false);
|
|
760
|
+
try {
|
|
761
|
+
return await writeFence.dispatch((signal) => this.sendAndClassify(call, operation, url, credentials, body, signal, true));
|
|
762
|
+
} catch (error) {
|
|
763
|
+
if (error instanceof CheckpointError || error instanceof InsufficientTimeError || error instanceof DispatchNotAllowedError || error instanceof AggregateError)
|
|
764
|
+
throw new YouTubeExchangeError("retry", "TRANSPORT", "the YouTube insert was not started");
|
|
765
|
+
throw error;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Send once, resending after one refreshed 401, and classify the response. A fenced write retries as
|
|
770
|
+
* unprocessed only after a rate-limit refusal or a connection that never opened; any other failure, including 503, may have applied it.
|
|
771
|
+
*/
|
|
772
|
+
async sendAndClassify(call, operation, url, initialCredentials, body, signal, isFencedWrite) {
|
|
773
|
+
let credentials = initialCredentials;
|
|
774
|
+
let response = await this.request(url, credentials.accessToken.reveal(), body, signal, isFencedWrite);
|
|
775
|
+
if (response.status === 401 && "resolveAfterRejection" in this.credentials) {
|
|
776
|
+
try {
|
|
777
|
+
credentials = await resolveCredentialAfterRejection(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
|
|
778
|
+
response = await this.request(url, credentials.accessToken.reveal(), body, signal, isFencedWrite);
|
|
779
|
+
} catch (error) {
|
|
780
|
+
if (error instanceof YouTubeExchangeError) throw error;
|
|
781
|
+
if (error instanceof ReauthorizationRequiredError) throw new YouTubeExchangeError("providerRejected", "AUTHENTICATION", "the YouTube connection must be authorized again");
|
|
782
|
+
throw new YouTubeExchangeError("defect", "AUTHENTICATION", "YouTube connection credentials are unavailable or invalid");
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
if (response.isTooLarge) throw new YouTubeExchangeError(isFencedWrite ? "writeUnconfirmed" : "invalidResponse", "RESPONSE_TOO_LARGE", "YouTube response exceeds the configured size limit", response);
|
|
786
|
+
if (response.status >= 200 && response.status < 300) return response;
|
|
787
|
+
const classified = classifyError(response, operation, this.now());
|
|
788
|
+
if (!isFencedWrite || classified.disposition !== "retry") throw classified;
|
|
789
|
+
throw new YouTubeExchangeError(classified.kind === "RATE_LIMIT" ? "retryUnprocessed" : "writeUnconfirmed", classified.kind, classified.message, response, classified.retryAfterMs);
|
|
790
|
+
}
|
|
791
|
+
async request(url, token, body, signal, isFencedWrite) {
|
|
792
|
+
const request = { url, method: body === void 0 ? "GET" : "POST", headers: { Accept: "application/json", Authorization: `Bearer ${token}`, ...body === void 0 ? {} : { "Content-Type": "application/json" } }, ...body === void 0 ? {} : { body: new TextEncoder().encode(body) }, addressPolicy: this.endpoint.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP", maxResponseBytes: this.maxResponseBytes, timeoutMs: this.timeoutMs, signal };
|
|
793
|
+
try {
|
|
794
|
+
return { ...await this.send(request), isTooLarge: false };
|
|
795
|
+
} catch (error) {
|
|
796
|
+
if (error instanceof BodyTooLargeError && error.status !== void 0 && error.headers !== void 0) {
|
|
797
|
+
if (error.status < 200 || error.status >= 300) return { status: error.status, headers: error.headers, body: new Uint8Array(), isTooLarge: false };
|
|
798
|
+
return { status: error.status, headers: error.headers, body: new Uint8Array(), isTooLarge: true };
|
|
799
|
+
}
|
|
800
|
+
if (isFencedWrite && error instanceof ProviderTransportError && error.isProvablyNotSent) throw new YouTubeExchangeError("retryUnprocessed", "TRANSPORT", "YouTube could not be reached before sending");
|
|
801
|
+
throw new YouTubeExchangeError(isFencedWrite ? "writeUnconfirmed" : "retry", "TRANSPORT", "YouTube did not return a complete response");
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
};
|
|
805
|
+
function goQueryEscape(value) {
|
|
806
|
+
return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
|
|
807
|
+
}
|
|
808
|
+
function header(response, name) {
|
|
809
|
+
const value = response.headers[name.toLowerCase()];
|
|
810
|
+
return Array.isArray(value) ? value[0] ?? "" : value ?? "";
|
|
811
|
+
}
|
|
812
|
+
var documentedReasons = /* @__PURE__ */ new Set(["quotaExceeded", "dailyLimitExceeded", "rateLimitExceeded", "userRateLimitExceeded", "forbidden", "insufficientPermissions", "authError", "invalidCredentials", "badRequest", "invalidParameter", "videoNotFound", "playlistNotFound", "channelNotFound", "playlistItemsNotAccessible", "playlistContainsMaximumNumberOfVideos", "manualSortRequired", "videoAlreadyInPlaylist", "backendError", "notFound", "youtubeSignupRequired"]);
|
|
813
|
+
function classifyError(response, _operation, now) {
|
|
814
|
+
let reason = "";
|
|
815
|
+
try {
|
|
816
|
+
const parsed = JSON.parse(new TextDecoder().decode(response.body));
|
|
817
|
+
const candidate = parsed.error?.errors?.[0]?.reason;
|
|
818
|
+
if (typeof candidate === "string" && documentedReasons.has(candidate)) reason = candidate;
|
|
819
|
+
} catch {
|
|
820
|
+
}
|
|
821
|
+
const detail = reason ? `, ${reason}` : "";
|
|
822
|
+
const status = response.status;
|
|
823
|
+
const retryAfterMs = parseRetryAfter(header(response, "retry-after"), now);
|
|
824
|
+
if (reason === "quotaExceeded" || reason === "dailyLimitExceeded") return new YouTubeExchangeError("quotaExhausted", "QUOTA_EXHAUSTED", `the project's daily YouTube Data API quota is spent (HTTP ${status}${detail})`, response);
|
|
825
|
+
if (status === 429 || reason === "rateLimitExceeded" || reason === "userRateLimitExceeded") return new YouTubeExchangeError("retry", "RATE_LIMIT", `YouTube rate limited the request (HTTP ${status}${detail})`, response, retryAfterMs);
|
|
826
|
+
if (status === 408 || status >= 500 && status !== 501) return new YouTubeExchangeError("retry", "AVAILABILITY", `YouTube is temporarily unavailable (HTTP ${status}${detail})`, response, retryAfterMs);
|
|
827
|
+
if (status === 401) return new YouTubeExchangeError("providerRejected", "AUTHENTICATION", `Google rejected the access token after one refresh (HTTP 401${detail})`, response);
|
|
828
|
+
if (status === 404) return new YouTubeExchangeError("notFound", "NOT_FOUND", `YouTube found no such video, channel, or playlist (HTTP 404${detail})`, response);
|
|
829
|
+
if (status === 403) return new YouTubeExchangeError("providerRejected", "AUTHORIZATION", `YouTube denied access: check the youtube scope and that the account owns the playlist (HTTP 403${detail})`, response);
|
|
830
|
+
if (status === 400 || status === 409) return new YouTubeExchangeError("providerRejected", "VALIDATION", `YouTube rejected the request as invalid (HTTP ${status}${detail})`, response);
|
|
831
|
+
if (status >= 300 && status < 400) return new YouTubeExchangeError("providerRejected", "PROTOCOL", `YouTube redirected the request (HTTP ${status})`, response);
|
|
832
|
+
return new YouTubeExchangeError("providerRejected", "PROVIDER_REJECTION", `YouTube rejected the request (HTTP ${status}${detail})`, response);
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
// src/project.ts
|
|
836
|
+
function encodeCredentials(credentials) {
|
|
837
|
+
return {
|
|
838
|
+
oauth_client_id: credentials.oauthClientId ?? "",
|
|
839
|
+
oauth_client_secret: credentials.oauthClientSecret?.reveal() ?? "",
|
|
840
|
+
access_token: credentials.accessToken.reveal(),
|
|
841
|
+
refresh_token: credentials.refreshToken?.reveal() ?? ""
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
function newProjectConnection2(project, connectionName, options = {}) {
|
|
845
|
+
return newProjectConnection(project, connectionName, (loadedProject, name) => {
|
|
846
|
+
const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "google-youtube" && entry.connectionName === name);
|
|
847
|
+
if (!selected) throw new TypeError("YouTube project connection is not configured");
|
|
848
|
+
const raw = selected.configuration;
|
|
849
|
+
const settings = ConfigSchema.parse({
|
|
850
|
+
...raw,
|
|
851
|
+
...raw.timeout !== void 0 ? { timeoutMs: typeof raw.timeout === "number" ? Math.ceil(raw.timeout / 1e6) : parseDurationMilliseconds(raw.timeout) } : {}
|
|
852
|
+
});
|
|
853
|
+
const config = {
|
|
854
|
+
...settings.endpoint !== void 0 ? { endpoint: settings.endpoint } : {},
|
|
855
|
+
...raw.timeout !== void 0 ? { timeoutMs: typeof raw.timeout === "number" ? Math.ceil(raw.timeout / 1e6) : parseDurationMilliseconds(raw.timeout) } : {},
|
|
856
|
+
...settings.maxResponseBytes !== void 0 ? { maxResponseBytes: settings.maxResponseBytes } : {}
|
|
857
|
+
};
|
|
858
|
+
return new YouTubeClient(config, newProjectCredentialProvider(loadedProject, name, decodeCredentials, encodeCredentials, decodeSharedCredentials), options);
|
|
859
|
+
});
|
|
860
|
+
}
|
|
861
|
+
function parseDurationMilliseconds(value) {
|
|
862
|
+
if (typeof value !== "string") throw new TypeError("YouTube timeout must be a positive Go duration");
|
|
863
|
+
let remaining = value;
|
|
864
|
+
let milliseconds = 0;
|
|
865
|
+
const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
|
|
866
|
+
while (remaining) {
|
|
867
|
+
const component = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
|
|
868
|
+
if (!component) throw new TypeError("YouTube timeout must be a positive Go duration");
|
|
869
|
+
milliseconds += Number(component[1]) * (units[component[2] ?? ""] ?? NaN);
|
|
870
|
+
remaining = remaining.slice(component[0].length);
|
|
871
|
+
}
|
|
872
|
+
if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("YouTube timeout must resolve to positive whole milliseconds");
|
|
873
|
+
return milliseconds;
|
|
874
|
+
}
|
|
875
|
+
export {
|
|
876
|
+
AddPlaylistItemBranch,
|
|
877
|
+
AddPlaylistItemBranchAdded,
|
|
878
|
+
AddPlaylistItemBranchDefect,
|
|
879
|
+
AddPlaylistItemBranchInvalidResponse,
|
|
880
|
+
AddPlaylistItemBranchNotFound,
|
|
881
|
+
AddPlaylistItemBranchProviderRejected,
|
|
882
|
+
AddPlaylistItemBranchQuotaExhausted,
|
|
883
|
+
AddPlaylistItemBranchUncertain,
|
|
884
|
+
AddPlaylistItemDefinition,
|
|
885
|
+
AddPlaylistItemInputSchema,
|
|
886
|
+
AddPlaylistItemMetadata,
|
|
887
|
+
AddPlaylistItemOperation,
|
|
888
|
+
AddedPlaylistItemSchema,
|
|
889
|
+
ChannelSchema,
|
|
890
|
+
ConfigSchema,
|
|
891
|
+
Connection,
|
|
892
|
+
ConnectorID,
|
|
893
|
+
GetChannelBranch,
|
|
894
|
+
GetChannelBranchDefect,
|
|
895
|
+
GetChannelBranchFound,
|
|
896
|
+
GetChannelBranchInvalidResponse,
|
|
897
|
+
GetChannelBranchNotFound,
|
|
898
|
+
GetChannelBranchProviderRejected,
|
|
899
|
+
GetChannelBranchQuotaExhausted,
|
|
900
|
+
GetChannelDefinition,
|
|
901
|
+
GetChannelInputSchema,
|
|
902
|
+
GetChannelMetadata,
|
|
903
|
+
GetChannelOperation,
|
|
904
|
+
GetVideoBranch,
|
|
905
|
+
GetVideoBranchDefect,
|
|
906
|
+
GetVideoBranchFound,
|
|
907
|
+
GetVideoBranchInvalidResponse,
|
|
908
|
+
GetVideoBranchNotFound,
|
|
909
|
+
GetVideoBranchProviderRejected,
|
|
910
|
+
GetVideoBranchQuotaExhausted,
|
|
911
|
+
GetVideoDefinition,
|
|
912
|
+
GetVideoInputSchema,
|
|
913
|
+
GetVideoMetadata,
|
|
914
|
+
GetVideoOperation,
|
|
915
|
+
ListPlaylistItemsBranch,
|
|
916
|
+
ListPlaylistItemsBranchDefect,
|
|
917
|
+
ListPlaylistItemsBranchInvalidResponse,
|
|
918
|
+
ListPlaylistItemsBranchListed,
|
|
919
|
+
ListPlaylistItemsBranchNotFound,
|
|
920
|
+
ListPlaylistItemsBranchProviderRejected,
|
|
921
|
+
ListPlaylistItemsBranchQuotaExhausted,
|
|
922
|
+
ListPlaylistItemsDefinition,
|
|
923
|
+
ListPlaylistItemsInputSchema,
|
|
924
|
+
ListPlaylistItemsMetadata,
|
|
925
|
+
ListPlaylistItemsOperation,
|
|
926
|
+
PlaylistItemPageSchema,
|
|
927
|
+
PlaylistItemSchema,
|
|
928
|
+
ProviderID,
|
|
929
|
+
SearchVideosBranch,
|
|
930
|
+
SearchVideosBranchDefect,
|
|
931
|
+
SearchVideosBranchInvalidResponse,
|
|
932
|
+
SearchVideosBranchProviderRejected,
|
|
933
|
+
SearchVideosBranchQuotaExhausted,
|
|
934
|
+
SearchVideosBranchSearched,
|
|
935
|
+
SearchVideosDefinition,
|
|
936
|
+
SearchVideosInputSchema,
|
|
937
|
+
SearchVideosMetadata,
|
|
938
|
+
SearchVideosOperation,
|
|
939
|
+
VideoSchema,
|
|
940
|
+
VideoSearchPageSchema,
|
|
941
|
+
VideoSearchResultSchema,
|
|
942
|
+
YouTubeClient,
|
|
943
|
+
decodeCredentials,
|
|
944
|
+
decodeSharedCredentials,
|
|
945
|
+
newAddPlaylistItemStep,
|
|
946
|
+
newConnection,
|
|
947
|
+
newConnectionWithOperations,
|
|
948
|
+
newGetChannelStep,
|
|
949
|
+
newGetVideoStep,
|
|
950
|
+
newListPlaylistItemsStep,
|
|
951
|
+
newProjectConnection2 as newProjectConnection,
|
|
952
|
+
newSearchVideosStep
|
|
953
|
+
};
|