@superdurable/connector-google-youtube 0.2.0 → 0.2.1

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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # YouTube TypeScript connector
2
2
 
3
- `@superdurable/connector-google-youtube` provides Dex Query Steps for video search, video and channel reads, and playlist pages, plus a playlist Mutation that adds a video at most once and selects `uncertain` when an earlier insert cannot be confirmed. The package follows the Go connector's YouTube Data API v3 request and retry behavior. OAuth credentials are resolved and refreshed through the host-owned connection using the generated authorization declaration.
3
+ `@superdurable/connector-google-youtube` provides Dex Query Steps for video search, video and channel reads, and playlist pages, plus a playlist Mutation that adds a video unless the playlist holds it. After an unknown insert outcome it reads the playlist back and resends while possible inserts stay below the send cap (`maxSends`, default 3), and selects `uncertain` only at the cap when the listing does not show the video. The package follows the Go connector's YouTube Data API v3 request and retry behavior. OAuth credentials are resolved and refreshed through the host-owned connection using the generated authorization declaration.
4
4
 
5
5
  The checked-in [video lookup example](examples/video-lookup/README.md) binds the static `youtube-video-reader` connection and runs a real Dex Flow. Configure Google OAuth in Dex Web Connections. The read-only method is sufficient for the example; `addPlaylistItem` requires the manage method.
6
6
 
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "connectorId": "google-youtube",
3
- "releaseTag": "connectors/google/youtube/go/v0.4.0",
3
+ "releaseTag": "connectors/google/youtube/go/v0.4.1",
4
4
  "package": {
5
5
  "ecosystem": "npm",
6
6
  "name": "@superdurable/connector-google-youtube",
7
- "version": "0.2.0"
7
+ "version": "0.2.1"
8
8
  },
9
9
  "factories": [
10
10
  {
@@ -326,12 +326,14 @@
326
326
  "approval": "recommended",
327
327
  "branches": {
328
328
  "defect": "rejected",
329
- "invalidResponse": "unknown",
329
+ "invalidResponse": "rejected",
330
330
  "notFound": "rejected",
331
331
  "providerRejected": "rejected",
332
332
  "quotaExhausted": "rejected",
333
333
  "uncertain": "unknown"
334
- }
334
+ },
335
+ "repeatOnUnknown": "limited",
336
+ "maxSends": 3
335
337
  },
336
338
  "fields": {
337
339
  "stepType": "stepType",
@@ -28,71 +28,85 @@ var ConfigSchema = z.object({
28
28
  "endpoint": z.string().optional(),
29
29
  "maxResponseBytes": z.number().int().optional()
30
30
  });
31
+ var CredentialMaterialError = class extends TypeError {
32
+ constructor(message) {
33
+ super(message);
34
+ this.name = "CredentialMaterialError";
35
+ }
36
+ };
37
+ var sdkCredentialDecodingFailureMessages = /* @__PURE__ */ new Set([
38
+ "project credential decoding failed",
39
+ "shared project credential decoding failed",
40
+ "project credential decoding failed: this connector version does not support shared credentials"
41
+ ]);
42
+ function isCredentialMaterialError(error) {
43
+ return error instanceof CredentialMaterialError || error instanceof TypeError && sdkCredentialDecodingFailureMessages.has(error.message);
44
+ }
31
45
  function decodeCredentials(value) {
32
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
46
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new CredentialMaterialError("credential fields are invalid");
33
47
  const fields = value;
34
48
  const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "oauth_client_id", "oauth_client_secret", "refresh_token"]);
35
- if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
36
- if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
37
- if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
38
- if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
39
- if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
49
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new CredentialMaterialError("stored credential does not match the connector credential fields");
50
+ if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new CredentialMaterialError("credential access_token has an invalid type");
51
+ if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new CredentialMaterialError("credential oauth_client_id has an invalid type");
52
+ if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new CredentialMaterialError("credential oauth_client_secret has an invalid type");
53
+ if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new CredentialMaterialError("credential refresh_token has an invalid type");
40
54
  const selectedMethod = fields["auth_method"] ?? "";
41
- if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
55
+ if (typeof selectedMethod !== "string") throw new CredentialMaterialError("credential auth_method is invalid");
42
56
  const method = selectedMethod || "google-oauth-readonly";
43
57
  const credentials = { authMethodId: method };
44
58
  if (method === "google-oauth-readonly") {
45
- if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
59
+ if (!fields["oauth_client_id"]) throw new CredentialMaterialError("credential oauth_client_id is required");
46
60
  if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
47
- if (!fields["oauth_client_secret"]) throw new TypeError("credential oauth_client_secret is required");
61
+ if (!fields["oauth_client_secret"]) throw new CredentialMaterialError("credential oauth_client_secret is required");
48
62
  if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new SecretString(fields["oauth_client_secret"]);
49
- if (!fields["access_token"]) throw new TypeError("credential access_token is required");
63
+ if (!fields["access_token"]) throw new CredentialMaterialError("credential access_token is required");
50
64
  if (fields["access_token"]) credentials.accessToken = new SecretString(fields["access_token"]);
51
- if (!fields["refresh_token"]) throw new TypeError("credential refresh_token is required");
65
+ if (!fields["refresh_token"]) throw new CredentialMaterialError("credential refresh_token is required");
52
66
  if (fields["refresh_token"]) credentials.refreshToken = new SecretString(fields["refresh_token"]);
53
67
  } else if (method === "google-oauth-manage") {
54
- if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
68
+ if (!fields["oauth_client_id"]) throw new CredentialMaterialError("credential oauth_client_id is required");
55
69
  if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
56
- if (!fields["oauth_client_secret"]) throw new TypeError("credential oauth_client_secret is required");
70
+ if (!fields["oauth_client_secret"]) throw new CredentialMaterialError("credential oauth_client_secret is required");
57
71
  if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new SecretString(fields["oauth_client_secret"]);
58
- if (!fields["access_token"]) throw new TypeError("credential access_token is required");
72
+ if (!fields["access_token"]) throw new CredentialMaterialError("credential access_token is required");
59
73
  if (fields["access_token"]) credentials.accessToken = new SecretString(fields["access_token"]);
60
- if (!fields["refresh_token"]) throw new TypeError("credential refresh_token is required");
74
+ if (!fields["refresh_token"]) throw new CredentialMaterialError("credential refresh_token is required");
61
75
  if (fields["refresh_token"]) credentials.refreshToken = new SecretString(fields["refresh_token"]);
62
76
  } else {
63
- throw new TypeError("credential auth_method is invalid");
77
+ throw new CredentialMaterialError("credential auth_method is invalid");
64
78
  }
65
79
  return credentials;
66
80
  }
67
81
  function decodeSharedCredentials(value) {
68
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
82
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new CredentialMaterialError("credential fields are invalid");
69
83
  const fields = value;
70
84
  const allowed = /* @__PURE__ */ new Set(["auth_method", "access_token", "oauth_client_id", "oauth_client_secret", "refresh_token"]);
71
- if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
72
- if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new TypeError("credential access_token has an invalid type");
73
- if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new TypeError("credential oauth_client_id has an invalid type");
74
- if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new TypeError("credential oauth_client_secret has an invalid type");
75
- if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new TypeError("credential refresh_token has an invalid type");
85
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new CredentialMaterialError("stored credential does not match the connector credential fields");
86
+ if (fields["access_token"] != null && !(typeof fields["access_token"] === "string")) throw new CredentialMaterialError("credential access_token has an invalid type");
87
+ if (fields["oauth_client_id"] != null && !(typeof fields["oauth_client_id"] === "string")) throw new CredentialMaterialError("credential oauth_client_id has an invalid type");
88
+ if (fields["oauth_client_secret"] != null && !(typeof fields["oauth_client_secret"] === "string")) throw new CredentialMaterialError("credential oauth_client_secret has an invalid type");
89
+ if (fields["refresh_token"] != null && !(typeof fields["refresh_token"] === "string")) throw new CredentialMaterialError("credential refresh_token has an invalid type");
76
90
  const selectedMethod = fields["auth_method"] ?? "";
77
- if (typeof selectedMethod !== "string") throw new TypeError("credential auth_method is invalid");
91
+ if (typeof selectedMethod !== "string") throw new CredentialMaterialError("credential auth_method is invalid");
78
92
  const method = selectedMethod || "google-oauth-readonly";
79
93
  const credentials = { authMethodId: method };
80
94
  if (method === "google-oauth-readonly") {
81
- if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
95
+ if (!fields["oauth_client_id"]) throw new CredentialMaterialError("credential oauth_client_id is required");
82
96
  if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
83
97
  if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new SecretString(fields["oauth_client_secret"]);
84
- if (!fields["access_token"]) throw new TypeError("credential access_token is required");
98
+ if (!fields["access_token"]) throw new CredentialMaterialError("credential access_token is required");
85
99
  if (fields["access_token"]) credentials.accessToken = new SecretString(fields["access_token"]);
86
100
  if (fields["refresh_token"]) credentials.refreshToken = new SecretString(fields["refresh_token"]);
87
101
  } else if (method === "google-oauth-manage") {
88
- if (!fields["oauth_client_id"]) throw new TypeError("credential oauth_client_id is required");
102
+ if (!fields["oauth_client_id"]) throw new CredentialMaterialError("credential oauth_client_id is required");
89
103
  if (fields["oauth_client_id"]) credentials.oauthClientId = fields["oauth_client_id"];
90
104
  if (fields["oauth_client_secret"]) credentials.oauthClientSecret = new SecretString(fields["oauth_client_secret"]);
91
- if (!fields["access_token"]) throw new TypeError("credential access_token is required");
105
+ if (!fields["access_token"]) throw new CredentialMaterialError("credential access_token is required");
92
106
  if (fields["access_token"]) credentials.accessToken = new SecretString(fields["access_token"]);
93
107
  if (fields["refresh_token"]) credentials.refreshToken = new SecretString(fields["refresh_token"]);
94
108
  } else {
95
- throw new TypeError("credential auth_method is invalid");
109
+ throw new CredentialMaterialError("credential auth_method is invalid");
96
110
  }
97
111
  return credentials;
98
112
  }
@@ -309,11 +323,13 @@ var AddPlaylistItemDefinition = {
309
323
  { id: "notFound", description: "No playlist the account can manage or no visible video has the ID.", optional: true },
310
324
  { id: "quotaExhausted", description: "The project's daily YouTube Data API quota is spent; it resets at midnight Pacific Time.", optional: true },
311
325
  { id: "providerRejected", description: "YouTube conclusively rejected the insert, such as a playlist of another account, a full playlist, or a revoked grant.", optional: true },
312
- { id: "invalidResponse", description: "YouTube returned an invalid or oversized check response, or an invalid item after accepting the insert.", optional: true },
313
- { id: "uncertain", description: "An earlier insert may have added the video, but the playlist listing does not show it; check the playlist before adding it again.", optional: true },
326
+ { id: "invalidResponse", description: "YouTube returned an invalid or oversized response to the check before any insert.", optional: true },
327
+ { id: "uncertain", description: "An insert may have added the video and cannot be confirmed: the listing does not show it at the send cap, including after an accepted insert with an unusable response, or YouTube refused a resend; check the playlist before adding it again.", optional: true },
314
328
  { id: "defect", description: "Local input, connection configuration, or credentials are invalid.", optional: true }
315
329
  ],
316
- stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } }
330
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "sync", executeRetry: { initialIntervalMs: 1e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 5, totalDurationMs: 12e4 } },
331
+ repeatOnUnknown: "limited",
332
+ maxSends: 3
317
333
  };
318
334
  var AddPlaylistItemMetadata = { kind: "mutation", idempotency: "required", authorization: "required" };
319
335
 
@@ -353,6 +369,8 @@ function newProjectCredentialProvider(project, connectionName, decode, encode, d
353
369
 
354
370
  export {
355
371
  ConfigSchema,
372
+ CredentialMaterialError,
373
+ isCredentialMaterialError,
356
374
  decodeCredentials,
357
375
  decodeSharedCredentials,
358
376
  SearchVideosInputSchema,
@@ -26,6 +26,12 @@ interface Credentials {
26
26
  /** Secret long-lived refresh token returned by Google because offline access is requested; Dex stores and rotates it automatically, and blank means reauthorization is required. */
27
27
  refreshToken: SecretString;
28
28
  }
29
+ /** Stored credential material that fails the connector credential checks, so no retry can succeed. */
30
+ declare class CredentialMaterialError extends TypeError {
31
+ constructor(message: string);
32
+ }
33
+ /** Report malformed stored credential material, also behind the SDK provider's decoding TypeError. */
34
+ declare function isCredentialMaterialError(error: unknown): boolean;
29
35
  /** Decode private credential fields for the selected authorization method. */
30
36
  declare function decodeCredentials(value: unknown): Credentials;
31
37
  /** Decode shared credential fields for the selected authorization method. */
@@ -329,4 +335,4 @@ declare function newConnection(client: Operations, reference: ConnectionRef): Co
329
335
  /** Bind scripted operations to a named connection. */
330
336
  declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
331
337
 
332
- export { type AddPlaylistItemInput as A, Connection as C, type GetChannelInput as G, type ListPlaylistItemsInput as L, type Operations as O, type PlaylistItemPage as P, type SearchVideosInput as S, type Video as V, type AddedPlaylistItem as a, type Channel as b, type GetVideoInput as c, type VideoSearchPage as d, type CredentialSource as e, type Config as f, AddPlaylistItemInputSchema as g, AddedPlaylistItemSchema as h, ChannelSchema as i, ConfigSchema as j, type Credentials as k, GetChannelInputSchema as l, GetVideoInputSchema as m, ListPlaylistItemsInputSchema as n, type PlaylistItem as o, PlaylistItemPageSchema as p, PlaylistItemSchema as q, SearchVideosInputSchema as r, VideoSchema as s, VideoSearchPageSchema as t, type VideoSearchResult as u, VideoSearchResultSchema as v, decodeCredentials as w, decodeSharedCredentials as x, newConnection as y, newConnectionWithOperations as z };
338
+ export { type AddPlaylistItemInput as A, newConnection as B, Connection as C, newConnectionWithOperations as D, type GetChannelInput as G, type ListPlaylistItemsInput as L, type Operations as O, type PlaylistItemPage as P, type SearchVideosInput as S, type Video as V, type AddedPlaylistItem as a, type Channel as b, type GetVideoInput as c, type VideoSearchPage as d, type CredentialSource as e, type Config as f, AddPlaylistItemInputSchema as g, AddedPlaylistItemSchema as h, ChannelSchema as i, ConfigSchema as j, CredentialMaterialError as k, type Credentials as l, GetChannelInputSchema as m, GetVideoInputSchema as n, ListPlaylistItemsInputSchema as o, type PlaylistItem as p, PlaylistItemPageSchema as q, PlaylistItemSchema as r, SearchVideosInputSchema as s, VideoSchema as t, VideoSearchPageSchema as u, type VideoSearchResult as v, VideoSearchResultSchema as w, decodeCredentials as x, decodeSharedCredentials as y, isCredentialMaterialError as z };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { A as AddPlaylistItemInput, a as AddedPlaylistItem, C as Connection, G as GetChannelInput, b as Channel, c as GetVideoInput, V as Video, L as ListPlaylistItemsInput, P as PlaylistItemPage, S as SearchVideosInput, d as VideoSearchPage, e as CredentialSource, f as Config, O as Operations } from './connection-cA6SHIc_.js';
2
- export { g as AddPlaylistItemInputSchema, h as AddedPlaylistItemSchema, i as ChannelSchema, j as ConfigSchema, k as Credentials, l as GetChannelInputSchema, m as GetVideoInputSchema, n as ListPlaylistItemsInputSchema, o as PlaylistItem, p as PlaylistItemPageSchema, q as PlaylistItemSchema, r as SearchVideosInputSchema, s as VideoSchema, t as VideoSearchPageSchema, u as VideoSearchResult, v as VideoSearchResultSchema, w as decodeCredentials, x as decodeSharedCredentials, y as newConnection, z as newConnectionWithOperations } from './connection-cA6SHIc_.js';
1
+ import { A as AddPlaylistItemInput, a as AddedPlaylistItem, C as Connection, G as GetChannelInput, b as Channel, c as GetVideoInput, V as Video, L as ListPlaylistItemsInput, P as PlaylistItemPage, S as SearchVideosInput, d as VideoSearchPage, e as CredentialSource, f as Config, O as Operations } from './connection-DxS18Qoi.js';
2
+ export { g as AddPlaylistItemInputSchema, h as AddedPlaylistItemSchema, i as ChannelSchema, j as ConfigSchema, k as CredentialMaterialError, l as Credentials, m as GetChannelInputSchema, n as GetVideoInputSchema, o as ListPlaylistItemsInputSchema, p as PlaylistItem, q as PlaylistItemPageSchema, r as PlaylistItemSchema, s as SearchVideosInputSchema, t as VideoSchema, u as VideoSearchPageSchema, v as VideoSearchResult, w as VideoSearchResultSchema, x as decodeCredentials, y as decodeSharedCredentials, z as isCredentialMaterialError, B as newConnection, D as newConnectionWithOperations } from './connection-DxS18Qoi.js';
3
3
  import * as _superdurable_connectors_sdk from '@superdurable/connectors-sdk';
4
4
  import { MutationDefinition, QueryDefinition, MutationStepConfig, Mutation, MutationResult, QueryStepConfig, Query, QueryResult, MutationStep, QueryStep, Call, QueryAttempt, MutationAttempt } from '@superdurable/connectors-sdk';
5
5
  import { StepTarget } from '@superdurable/dex';
@@ -143,9 +143,9 @@ declare const AddPlaylistItemBranchNotFound: "notFound";
143
143
  declare const AddPlaylistItemBranchQuotaExhausted: "quotaExhausted";
144
144
  /** YouTube conclusively rejected the insert, such as a playlist of another account, a full playlist, or a revoked grant. */
145
145
  declare const AddPlaylistItemBranchProviderRejected: "providerRejected";
146
- /** YouTube returned an invalid or oversized check response, or an invalid item after accepting the insert. */
146
+ /** YouTube returned an invalid or oversized response to the check before any insert. */
147
147
  declare const AddPlaylistItemBranchInvalidResponse: "invalidResponse";
148
- /** An earlier insert may have added the video, but the playlist listing does not show it; check the playlist before adding it again. */
148
+ /** An insert may have added the video and cannot be confirmed: the listing does not show it at the send cap, including after an accepted insert with an unusable response, or YouTube refused a resend; check the playlist before adding it again. */
149
149
  declare const AddPlaylistItemBranchUncertain: "uncertain";
150
150
  /** Local input, connection configuration, or credentials are invalid. */
151
151
  declare const AddPlaylistItemBranchDefect: "defect";
@@ -264,9 +264,9 @@ interface AddPlaylistItemStepConfig<StepInput, OperationInput = AddPlaylistItemI
264
264
  quotaExhausted?: StepTarget<MutationResult<OperationOutput>>;
265
265
  /** YouTube conclusively rejected the insert, such as a playlist of another account, a full playlist, or a revoked grant. */
266
266
  providerRejected?: StepTarget<MutationResult<OperationOutput>>;
267
- /** YouTube returned an invalid or oversized check response, or an invalid item after accepting the insert. */
267
+ /** YouTube returned an invalid or oversized response to the check before any insert. */
268
268
  invalidResponse?: StepTarget<MutationResult<OperationOutput>>;
269
- /** An earlier insert may have added the video, but the playlist listing does not show it; check the playlist before adding it again. */
269
+ /** An insert may have added the video and cannot be confirmed: the listing does not show it at the send cap, including after an accepted insert with an unusable response, or YouTube refused a resend; check the playlist before adding it again. */
270
270
  uncertain?: StepTarget<MutationResult<OperationOutput>>;
271
271
  /** Local input, connection configuration, or credentials are invalid. */
272
272
  defect?: StepTarget<MutationResult<OperationOutput>>;
@@ -304,17 +304,27 @@ declare class ListPlaylistItemsOperation implements Query<ListPlaylistItemsInput
304
304
  }
305
305
  /** Add a video once after checking playlist membership. */
306
306
  /**
307
- * Add a video at most once per Step call after checking the playlist for it. YouTube has no idempotency key
308
- * and its listing can lag behind an insert, so a single-dispatch fence forbids a second insert after one that
309
- * may have reached YouTube; such a later attempt only reads the playlist back.
307
+ * Add a video after checking the playlist for it. YouTube has no idempotency key and its listing can lag behind
308
+ * an insert, so a single-dispatch fence counts the inserts that may have reached YouTube. After an unknown
309
+ * outcome a later attempt lists the playlist first and inserts again only while possible inserts stay below the
310
+ * send cap; at the cap, or after an accepted insert, it only reads the playlist back.
310
311
  */
311
312
  declare class AddPlaylistItemOperation implements Mutation<AddPlaylistItemInput, AddedPlaylistItem> {
312
313
  private readonly client;
313
314
  /** Bind a client. */ constructor(client: YouTubeClient);
314
- /** Return manifest definition. */ definition(): _superdurable_connectors_sdk.QueryDefinition;
315
+ /** Return manifest definition. */ definition(): _superdurable_connectors_sdk.MutationDefinition;
315
316
  /** Use the stable Call ID as the Dex idempotency key; YouTube does not accept it. */ idempotencyKey(callID: string): string;
316
- /** Check membership and insert at most once per Step call. */ invoke(call: Call, input: AddPlaylistItemInput): Promise<MutationAttempt<AddedPlaylistItem>>;
317
- /** List the playlist after an attempt that may have inserted; only a shown item confirms it. */
317
+ /** Check membership and insert; an unknown insert outcome is resent below the send cap. */ invoke(call: Call, input: AddPlaylistItemInput): Promise<MutationAttempt<AddedPlaylistItem>>;
318
+ /**
319
+ * List the playlist after YouTube accepted this insert with an unusable body; it is never resent. A saved item ID,
320
+ * or the saved acceptance itself, makes later attempts list again up to the send cap; uncertain is selected here
321
+ * only when neither could be saved.
322
+ */
323
+ private confirmAcceptedInsert;
324
+ /**
325
+ * List the playlist after an attempt that may have inserted, and never insert. Only a shown item confirms it;
326
+ * otherwise it retries below the cap, where a saved item ID brings the next attempt back here, and selects uncertain at the cap.
327
+ */
318
328
  private confirmEarlierInsert;
319
329
  }
320
330
 
@@ -323,12 +333,13 @@ interface YouTubeClientOptions {
323
333
  send?: (request: ProviderRequest) => Promise<ProviderResponse>;
324
334
  now?: () => Date;
325
335
  }
326
- /** One provider exchange. */
336
+ /** One provider exchange. `isErrorBodyTooLarge` marks a non-2xx body dropped for its size. */
327
337
  interface YouTubeResponse {
328
338
  status: number;
329
339
  headers: ProviderResponse['headers'];
330
340
  body: Uint8Array;
331
341
  isTooLarge: boolean;
342
+ isErrorBodyTooLarge?: boolean;
332
343
  }
333
344
  /** YouTube API client using the generated OAuth refresh declaration. */
334
345
  declare class YouTubeClient {
@@ -352,7 +363,8 @@ declare class YouTubeClient {
352
363
  exchange(call: Call, operation: string, path: string, query: Record<string, string>, requiresManage?: boolean, body?: string, writeFence?: Fence): Promise<YouTubeResponse>;
353
364
  /**
354
365
  * Send once, resending after one refreshed 401, and classify the response. A fenced write retries as
355
- * unprocessed only after a rate-limit refusal or a connection that never opened; any other failure, including 503, may have applied it.
366
+ * unprocessed only after a rate-limit refusal, 503, or a connection that never opened; any other failure may have
367
+ * applied it. A 2xx whose body cannot be read is accepted and never resent.
356
368
  */
357
369
  private sendAndClassify;
358
370
  private request;
package/dist/index.js CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  ConfigSchema,
16
16
  Connection,
17
17
  ConnectorID,
18
+ CredentialMaterialError,
18
19
  GetChannelBranch,
19
20
  GetChannelBranchDefect,
20
21
  GetChannelBranchFound,
@@ -62,11 +63,12 @@ import {
62
63
  VideoSearchResultSchema,
63
64
  decodeCredentials,
64
65
  decodeSharedCredentials,
66
+ isCredentialMaterialError,
65
67
  newConnection,
66
68
  newConnectionWithOperations,
67
69
  newProjectConnection,
68
70
  newProjectCredentialProvider
69
- } from "./chunk-UAP7AK3Z.js";
71
+ } from "./chunk-6UPNDJRQ.js";
70
72
 
71
73
  // src/generated/steps.ts
72
74
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
@@ -132,8 +134,9 @@ function newAddPlaylistItemStep(configuration) {
132
134
  }
133
135
 
134
136
  // src/client.ts
135
- import { BodyTooLargeError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
137
+ import { BodyTooLargeError, ProviderStalledError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
136
138
  import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
139
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
137
140
  import { ReauthorizationRequiredError, resolveCredential, resolveCredentialAfterRejection } from "@superdurable/connectors-sdk";
138
141
  import { CheckpointError, DispatchNotAllowedError, InsufficientTimeError } from "@superdurable/connectors-sdk/singledispatch";
139
142
 
@@ -270,7 +273,7 @@ var CredentialFields = {
270
273
  };
271
274
 
272
275
  // src/operations.ts
273
- import { newQueryBranch, newQueryRetry, newMutationBranch, newMutationRetry, newMutationUncertain, zeroReceipt } from "@superdurable/connectors-sdk";
276
+ import { definitionMaxSends, newQueryBranch, newQueryRetry, newMutationBranch, newMutationRetry, newMutationUncertain, zeroReceipt } from "@superdurable/connectors-sdk";
274
277
  import { Fence } from "@superdurable/connectors-sdk/singledispatch";
275
278
  var videoID = /^[A-Za-z0-9_-]{11}$/;
276
279
  var channelID = /^UC[A-Za-z0-9_-]{22}$/;
@@ -304,6 +307,21 @@ function mutationError(operation, error, call, objectID) {
304
307
  if (error.disposition === "retry") return newMutationRetry(detail, error.retryAfterMs);
305
308
  return newMutationBranch(error.disposition, zeroAdded, error.response || error.message.startsWith("addPlaylistItem requires") ? receipt(call, objectID, error.response) : zeroReceipt(), detail);
306
309
  }
310
+ function resendOrSelectUncertain(canResendUnknownOutcome, detail, retryAfterMs, draft) {
311
+ if (canResendUnknownOutcome) return newMutationRetry(detail, retryAfterMs);
312
+ return newMutationUncertain(zeroAdded, { ...detail, message: `${detail.message}; the send cap is reached, so check the playlist before adding the video again` }, draft);
313
+ }
314
+ function rejectOrSelectUncertain(hasPossibleEarlierSend, operation, error, call, objectID, uncertainPrefix) {
315
+ if (!(error instanceof YouTubeExchangeError) || error.disposition === "retry" || !hasPossibleEarlierSend) return mutationError(operation, error, call, objectID);
316
+ const draft = error.response || error.message.startsWith("addPlaylistItem requires") ? receipt(call, objectID, error.response) : zeroReceipt();
317
+ return newMutationUncertain(zeroAdded, failure(operation, error.kind, `${uncertainPrefix}${error.message}`), draft);
318
+ }
319
+ function failBeforeInsertOrSelectUncertain(hasPossibleEarlierSend, operation, error, call, objectID, uncertainPrefix) {
320
+ if (!(error instanceof YouTubeExchangeError) || error.disposition === "retry" || !hasPossibleEarlierSend) return mutationError(operation, error, call, objectID);
321
+ if (error.disposition === "providerRejected" && error.kind === "AUTHENTICATION") return rejectOrSelectUncertain(true, operation, error, call, objectID, uncertainPrefix);
322
+ return newMutationRetry(failure(operation, error.kind, `${uncertainPrefix}${error.message}`), error.retryAfterMs);
323
+ }
324
+ var acceptedInsertWithoutItemID = "dex:acceptedWithoutItemId";
307
325
  function defect(operation, empty, message) {
308
326
  return newQueryBranch("defect", empty, zeroReceipt(), failure(operation, "VALIDATION", message));
309
327
  }
@@ -598,36 +616,44 @@ var AddPlaylistItemOperation = class {
598
616
  idempotencyKey(callID) {
599
617
  return callID;
600
618
  }
601
- /** Check membership and insert at most once per Step call. */
619
+ /** Check membership and insert; an unknown insert outcome is resent below the send cap. */
602
620
  async invoke(call, input) {
603
621
  const operation = "addPlaylistItem", listInput = { playlistId: input.playlistId, videoId: input.videoId, maxResults: 1 }, encoded = playlistQuery(listInput);
604
622
  if (encoded.error || !input.videoId) return newMutationBranch("defect", zeroAdded, zeroReceipt(), failure(operation, "VALIDATION", encoded.error ?? "videoId must be an 11-character YouTube video ID"));
623
+ const operationMaxSends = definitionMaxSends(AddPlaylistItemDefinition);
605
624
  let fence;
606
625
  try {
607
- fence = new Fence(call, AddPlaylistItemDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4);
626
+ fence = new Fence(call, AddPlaylistItemDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4, { maxSends: operationMaxSends });
608
627
  } catch {
609
628
  return newMutationBranch("defect", zeroAdded, zeroReceipt(), failure(operation, "LOCAL_DEFECT", "the YouTube dispatch fence is unavailable"));
610
629
  }
611
630
  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());
631
+ if (decision.kind === "failClosed") return newMutationRetry(failure(operation, "AVAILABILITY", "the YouTube dispatch checkpoint is unreadable; nothing was inserted in this attempt"));
632
+ if (decision.kind === "readBackRequired" || decision.marker?.providerId)
633
+ return this.confirmEarlierInsert(call, listInput, encoded.query, decision.kind === "readBackRequired");
634
+ const priorSendUpperBound = decision.priorSendUpperBound ?? 0;
635
+ const canResendUnknownOutcome = priorSendUpperBound + 1 < (operationMaxSends >= 2 ? call.maxSendsOverride ?? operationMaxSends : 1);
636
+ const hasPossibleEarlierSend = priorSendUpperBound > 0;
637
+ const readBackPrefix = "an earlier attempt may have added the video, and the playlist could not be read back: ";
614
638
  let response;
615
639
  try {
616
640
  response = await this.client.exchange(call, operation, "/playlistItems", encoded.query, true);
617
641
  } catch (cause) {
618
- if (cause instanceof YouTubeExchangeError && cause.disposition === "retry") {
642
+ const isRetryable = cause instanceof YouTubeExchangeError && (cause.disposition === "retry" || cause.isTransientCredentialFailure);
643
+ if (isRetryable && decision.kind === "sendAllowed" && !hasPossibleEarlierSend) {
619
644
  try {
620
645
  await fence.recordNotSent();
621
646
  } catch {
622
647
  }
623
648
  }
624
- return mutationError(operation, cause, call, input.playlistId);
649
+ if (isRetryable) return newMutationRetry(failure(operation, cause.kind, cause.message), cause.retryAfterMs);
650
+ return failBeforeInsertOrSelectUncertain(hasPossibleEarlierSend, operation, cause, call, input.playlistId, readBackPrefix);
625
651
  }
626
652
  let page;
627
653
  try {
628
654
  page = playlistPage(response, listInput);
629
655
  } catch {
630
- return newMutationBranch("invalidResponse", zeroAdded, receipt(call, input.playlistId, response), failure(operation, "PROTOCOL", "YouTube returned an incomplete playlist page"));
656
+ return failBeforeInsertOrSelectUncertain(hasPossibleEarlierSend, operation, new YouTubeExchangeError("invalidResponse", "PROTOCOL", "YouTube returned an incomplete playlist page", response), call, input.playlistId, readBackPrefix);
631
657
  }
632
658
  if (page.items?.length) return newMutationBranch("added", { item: page.items[0], wasAlreadyPresent: true }, receipt(call, page.items[0].id, response));
633
659
  const body = JSON.stringify({ snippet: { playlistId: input.playlistId, resourceId: { kind: "youtube#video", videoId: input.videoId } } });
@@ -641,21 +667,43 @@ var AddPlaylistItemOperation = class {
641
667
  }
642
668
  return newMutationRetry(failure(operation, cause.kind, cause.message), cause.retryAfterMs);
643
669
  }
644
- if (cause instanceof YouTubeExchangeError && cause.disposition === "writeUnconfirmed") return newMutationRetry(failure(operation, cause.kind, cause.message));
645
- return mutationError(operation, cause, call, input.playlistId);
670
+ if (cause instanceof YouTubeExchangeError && cause.disposition === "writeUnconfirmed")
671
+ return resendOrSelectUncertain(canResendUnknownOutcome, failure(operation, cause.kind, cause.message), cause.retryAfterMs, receipt(call, input.playlistId, cause.response));
672
+ if (cause instanceof YouTubeExchangeError && cause.disposition === "acceptedUnreadable")
673
+ return this.confirmAcceptedInsert(call, fence, listInput, encoded.query, failure(operation, cause.kind, cause.message), insertedItemID(cause.response?.body));
674
+ if (cause instanceof YouTubeExchangeError && cause.isTransientCredentialFailure) {
675
+ if (decision.kind === "sendAllowed" && !hasPossibleEarlierSend) {
676
+ try {
677
+ await fence.recordNotSent();
678
+ } catch {
679
+ }
680
+ }
681
+ try {
682
+ await fence.recordCanResend();
683
+ } catch {
684
+ }
685
+ return newMutationRetry(failure(operation, cause.kind, cause.message));
686
+ }
687
+ if (cause instanceof YouTubeExchangeError && cause.disposition !== "retry" && !hasPossibleEarlierSend) {
688
+ try {
689
+ await fence.recordCanResend();
690
+ } catch {
691
+ }
692
+ }
693
+ return rejectOrSelectUncertain(hasPossibleEarlierSend, operation, cause, call, input.playlistId, "an earlier attempt may have added the video, and YouTube refused the resend: ");
646
694
  }
647
695
  let inserted;
648
696
  try {
649
697
  inserted = decoded(response);
650
698
  } catch {
651
- return newMutationRetry(failure(operation, "PROTOCOL", "YouTube returned a malformed insert response; the next attempt reads the playlist back"));
699
+ return this.confirmAcceptedInsert(call, fence, listInput, encoded.query, failure(operation, "PROTOCOL", "YouTube returned a malformed insert response"), insertedItemID(response.body));
652
700
  }
653
701
  let item;
654
702
  try {
655
703
  item = playlistItem(inserted, input.playlistId);
656
704
  if (item.videoId !== input.videoId) throw new TypeError("YouTube returned an item for a different video");
657
705
  } catch {
658
- return newMutationBranch("invalidResponse", zeroAdded, receipt(call, input.playlistId, response), failure(operation, "PROTOCOL", "YouTube returned an invalid or different inserted item"));
706
+ return this.confirmAcceptedInsert(call, fence, listInput, encoded.query, failure(operation, "PROTOCOL", "YouTube returned an invalid or different inserted item"), insertedItemID(response.body));
659
707
  }
660
708
  try {
661
709
  await fence.recordProviderId(item.id);
@@ -663,9 +711,44 @@ var AddPlaylistItemOperation = class {
663
711
  }
664
712
  return newMutationBranch("added", { item, wasAlreadyPresent: false }, receipt(call, item.id, response));
665
713
  }
666
- /** List the playlist after an attempt that may have inserted; only a shown item confirms it. */
667
- async confirmEarlierInsert(call, listInput, query) {
714
+ /**
715
+ * List the playlist after YouTube accepted this insert with an unusable body; it is never resent. A saved item ID,
716
+ * or the saved acceptance itself, makes later attempts list again up to the send cap; uncertain is selected here
717
+ * only when neither could be saved.
718
+ */
719
+ async confirmAcceptedInsert(call, fence, listInput, query, acceptance, acceptedItemID) {
720
+ let isAcceptanceSaved = true;
721
+ try {
722
+ await fence.recordProviderId(acceptedItemID || acceptedInsertWithoutItemID);
723
+ } catch {
724
+ isAcceptanceSaved = false;
725
+ }
726
+ let readBackReceipt = receipt(call, listInput.playlistId);
727
+ try {
728
+ const response = await this.client.exchange(call, "addPlaylistItem", "/playlistItems", query, true);
729
+ readBackReceipt = receipt(call, listInput.playlistId, response);
730
+ const page = playlistPage(response, listInput);
731
+ if (page.items?.length) {
732
+ try {
733
+ await fence.recordProviderId(page.items[0].id);
734
+ } catch {
735
+ }
736
+ return newMutationBranch("added", { item: page.items[0], wasAlreadyPresent: false }, receipt(call, page.items[0].id, response));
737
+ }
738
+ } catch (cause) {
739
+ if (cause instanceof YouTubeExchangeError && cause.response) readBackReceipt = receipt(call, listInput.playlistId, cause.response);
740
+ }
741
+ if (isAcceptanceSaved)
742
+ return newMutationRetry({ ...acceptance, message: `${acceptance.message}; YouTube accepted the insert, so it is not sent again, and the playlist listing does not show it yet; the next attempt lists again` });
743
+ return newMutationUncertain(zeroAdded, { ...acceptance, message: `${acceptance.message}; YouTube accepted the insert, so it is not sent again, the playlist listing does not show it, and its acceptance checkpoint failed; check the playlist` }, readBackReceipt);
744
+ }
745
+ /**
746
+ * List the playlist after an attempt that may have inserted, and never insert. Only a shown item confirms it;
747
+ * otherwise it retries below the cap, where a saved item ID brings the next attempt back here, and selects uncertain at the cap.
748
+ */
749
+ async confirmEarlierInsert(call, listInput, query, isAtSendCap) {
668
750
  const operation = "addPlaylistItem";
751
+ const retryOrSelectUncertain = (detail, draft) => isAtSendCap ? newMutationUncertain(zeroAdded, detail, draft) : newMutationRetry(detail);
669
752
  let response;
670
753
  try {
671
754
  response = await this.client.exchange(call, operation, "/playlistItems", query, true);
@@ -673,16 +756,16 @@ var AddPlaylistItemOperation = class {
673
756
  if (!(cause instanceof YouTubeExchangeError)) throw cause;
674
757
  if (cause.disposition === "retry") return newMutationRetry(failure(operation, cause.kind, cause.message), cause.retryAfterMs);
675
758
  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);
759
+ return retryOrSelectUncertain(failure(operation, cause.kind, `an earlier attempt may have added the video, and the playlist could not be read back: ${cause.message}`), readBackReceipt);
677
760
  }
678
761
  let page;
679
762
  try {
680
763
  page = playlistPage(response, listInput);
681
764
  } 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));
765
+ return retryOrSelectUncertain(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
766
  }
684
767
  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));
768
+ return retryOrSelectUncertain(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
769
  }
687
770
  };
688
771
 
@@ -691,17 +774,19 @@ var defaultEndpoint = "https://www.googleapis.com/youtube/v3";
691
774
  var defaultResponseBytes = 4194304;
692
775
  var defaultTimeoutMs = 25e3;
693
776
  var YouTubeExchangeError = class extends Error {
694
- constructor(disposition, kind, message, response, retryAfterMs = 0) {
777
+ constructor(disposition, kind, message, response, retryAfterMs = 0, isTransientCredentialFailure = false) {
695
778
  super(message);
696
779
  this.disposition = disposition;
697
780
  this.kind = kind;
698
781
  this.response = response;
699
782
  this.retryAfterMs = retryAfterMs;
783
+ this.isTransientCredentialFailure = isTransientCredentialFailure;
700
784
  }
701
785
  disposition;
702
786
  kind;
703
787
  response;
704
788
  retryAfterMs;
789
+ isTransientCredentialFailure;
705
790
  };
706
791
  var YouTubeClient = class {
707
792
  /** Validate the connection and bind host-owned renewable credentials. */
@@ -749,8 +834,8 @@ var YouTubeClient = class {
749
834
  try {
750
835
  credentials = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
751
836
  } 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");
837
+ if (isTerminalCredentialError(error)) throw new YouTubeExchangeError("providerRejected", "AUTHENTICATION", "the YouTube connection must be authorized again");
838
+ throw new YouTubeExchangeError("retry", "AUTHENTICATION", "YouTube connection credentials are temporarily unavailable", void 0, 0, true);
754
839
  }
755
840
  if (!credentials.accessToken || !isHeaderSafeCredential(credentials.accessToken.reveal())) throw new YouTubeExchangeError("defect", "AUTHENTICATION", "YouTube connection credentials are unavailable or invalid");
756
841
  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");
@@ -767,7 +852,8 @@ var YouTubeClient = class {
767
852
  }
768
853
  /**
769
854
  * 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.
855
+ * unprocessed only after a rate-limit refusal, 503, or a connection that never opened; any other failure may have
856
+ * applied it. A 2xx whose body cannot be read is accepted and never resent.
771
857
  */
772
858
  async sendAndClassify(call, operation, url, initialCredentials, body, signal, isFencedWrite) {
773
859
  let credentials = initialCredentials;
@@ -778,15 +864,22 @@ var YouTubeClient = class {
778
864
  response = await this.request(url, credentials.accessToken.reveal(), body, signal, isFencedWrite);
779
865
  } catch (error) {
780
866
  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");
867
+ if (isTerminalCredentialError(error)) throw new YouTubeExchangeError("providerRejected", "AUTHENTICATION", "the YouTube connection must be authorized again");
868
+ throw new YouTubeExchangeError("retry", "AUTHENTICATION", "YouTube connection credentials are temporarily unavailable", void 0, 0, true);
783
869
  }
784
870
  }
785
- if (response.isTooLarge) throw new YouTubeExchangeError(isFencedWrite ? "writeUnconfirmed" : "invalidResponse", "RESPONSE_TOO_LARGE", "YouTube response exceeds the configured size limit", response);
871
+ if (response.isTooLarge) throw new YouTubeExchangeError(isFencedWrite ? "acceptedUnreadable" : "invalidResponse", "RESPONSE_TOO_LARGE", "YouTube response exceeds the configured size limit", response);
786
872
  if (response.status >= 200 && response.status < 300) return response;
787
873
  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);
874
+ if (!isFencedWrite) throw classified;
875
+ if (insertedItemID(response.body)) throw new YouTubeExchangeError("acceptedUnreadable", classified.kind, classified.message, response);
876
+ if (classified.disposition === "retry") {
877
+ const isUnprocessed = classified.kind === "RATE_LIMIT" || response.status === 503;
878
+ throw new YouTubeExchangeError(isUnprocessed ? "retryUnprocessed" : "writeUnconfirmed", classified.kind, classified.message, response, classified.retryAfterMs);
879
+ }
880
+ if (classified.disposition !== "quotaExhausted" && (!definiteRefusalStatuses.has(response.status) || response.isErrorBodyTooLarge))
881
+ throw new YouTubeExchangeError("writeUnconfirmed", classified.kind, classified.message, response);
882
+ throw classified;
790
883
  }
791
884
  async request(url, token, body, signal, isFencedWrite) {
792
885
  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 };
@@ -794,17 +887,35 @@ var YouTubeClient = class {
794
887
  return { ...await this.send(request), isTooLarge: false };
795
888
  } catch (error) {
796
889
  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 };
890
+ if (error.status < 200 || error.status >= 300) return { status: error.status, headers: error.headers, body: new Uint8Array(), isTooLarge: false, isErrorBodyTooLarge: true };
798
891
  return { status: error.status, headers: error.headers, body: new Uint8Array(), isTooLarge: true };
799
892
  }
800
893
  if (isFencedWrite && error instanceof ProviderTransportError && error.isProvablyNotSent) throw new YouTubeExchangeError("retryUnprocessed", "TRANSPORT", "YouTube could not be reached before sending");
894
+ const statusBeforeFailure = error instanceof ProviderTransportError || error instanceof ProviderStalledError ? error.status : void 0;
895
+ if (isFencedWrite && statusBeforeFailure !== void 0 && statusBeforeFailure >= 200 && statusBeforeFailure < 300)
896
+ throw new YouTubeExchangeError("acceptedUnreadable", "TRANSPORT", "YouTube accepted the insert but its response body could not be read");
801
897
  throw new YouTubeExchangeError(isFencedWrite ? "writeUnconfirmed" : "retry", "TRANSPORT", "YouTube did not return a complete response");
802
898
  }
803
899
  }
804
900
  };
901
+ var definiteRefusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
902
+ function insertedItemID(body) {
903
+ if (!body) return "";
904
+ try {
905
+ const value = JSON.parse(new TextDecoder().decode(body));
906
+ if (!value || typeof value !== "object" || Array.isArray(value)) return "";
907
+ const id = value.id;
908
+ return typeof id === "string" ? id : "";
909
+ } catch {
910
+ return "";
911
+ }
912
+ }
805
913
  function goQueryEscape(value) {
806
914
  return encodeURIComponent(value).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%20/g, "+");
807
915
  }
916
+ function isTerminalCredentialError(error) {
917
+ return error instanceof ReauthorizationRequiredError || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || isCredentialMaterialError(error);
918
+ }
808
919
  function header(response, name) {
809
920
  const value = response.headers[name.toLowerCase()];
810
921
  return Array.isArray(value) ? value[0] ?? "" : value ?? "";
@@ -890,6 +1001,7 @@ export {
890
1001
  ConfigSchema,
891
1002
  Connection,
892
1003
  ConnectorID,
1004
+ CredentialMaterialError,
893
1005
  GetChannelBranch,
894
1006
  GetChannelBranchDefect,
895
1007
  GetChannelBranchFound,
@@ -942,6 +1054,7 @@ export {
942
1054
  YouTubeClient,
943
1055
  decodeCredentials,
944
1056
  decodeSharedCredentials,
1057
+ isCredentialMaterialError,
945
1058
  newAddPlaylistItemStep,
946
1059
  newConnection,
947
1060
  newConnectionWithOperations,
package/dist/mock.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { MockQuery, MockMutation, Case } from '@superdurable/connectors-sdk/connectormock';
2
2
  import { Failure } from '@superdurable/connectors-sdk';
3
- import { O as Operations, C as Connection, S as SearchVideosInput, d as VideoSearchPage, c as GetVideoInput, V as Video, G as GetChannelInput, b as Channel, L as ListPlaylistItemsInput, P as PlaylistItemPage, A as AddPlaylistItemInput, a as AddedPlaylistItem, o as PlaylistItem, u as VideoSearchResult } from './connection-cA6SHIc_.js';
3
+ import { O as Operations, C as Connection, S as SearchVideosInput, d as VideoSearchPage, c as GetVideoInput, V as Video, G as GetChannelInput, b as Channel, L as ListPlaylistItemsInput, P as PlaylistItemPage, A as AddPlaylistItemInput, a as AddedPlaylistItem, p as PlaylistItem, v as VideoSearchResult } from './connection-DxS18Qoi.js';
4
4
  import 'zod';
5
5
 
6
6
  /** Go zero value for SearchVideosInput in scripted cases. */
package/dist/mock.js CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  VideoSearchPageSchema,
20
20
  VideoSearchResultSchema,
21
21
  newConnectionWithOperations
22
- } from "./chunk-UAP7AK3Z.js";
22
+ } from "./chunk-6UPNDJRQ.js";
23
23
 
24
24
  // src/generated/mock.ts
25
25
  import { branchCase, retryCase, uncertainCase, newMutation, newQuery } from "@superdurable/connectors-sdk/connectormock";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@superdurable/connector-google-youtube",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "YouTube Data API connector for Dex TypeScript Flows",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,7 +47,7 @@
47
47
  "example:video-lookup:start": "npm run build && tsx examples/video-lookup/start.ts"
48
48
  },
49
49
  "dependencies": {
50
- "@superdurable/connectors-sdk": "0.7.0",
50
+ "@superdurable/connectors-sdk": "0.12.0",
51
51
  "@superdurable/dex": ">=1.28.0",
52
52
  "zod": "^4.1.0"
53
53
  },