@superdurable/connector-hootsuite 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,563 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CredentialMaterialError,
6
+ ListScheduledPostsBranch,
7
+ ListScheduledPostsBranchDefect,
8
+ ListScheduledPostsBranchInvalidResponse,
9
+ ListScheduledPostsBranchListed,
10
+ ListScheduledPostsBranchProviderRejected,
11
+ ListScheduledPostsDefinition,
12
+ ListScheduledPostsInputSchema,
13
+ ListScheduledPostsMetadata,
14
+ ListSocialProfilesBranch,
15
+ ListSocialProfilesBranchDefect,
16
+ ListSocialProfilesBranchInvalidResponse,
17
+ ListSocialProfilesBranchListed,
18
+ ListSocialProfilesBranchProviderRejected,
19
+ ListSocialProfilesDefinition,
20
+ ListSocialProfilesInputSchema,
21
+ ListSocialProfilesMetadata,
22
+ ProviderID,
23
+ SchedulePostBranch,
24
+ SchedulePostBranchDefect,
25
+ SchedulePostBranchProviderRejected,
26
+ SchedulePostBranchScheduled,
27
+ SchedulePostBranchUncertain,
28
+ SchedulePostDefinition,
29
+ SchedulePostInputSchema,
30
+ SchedulePostMetadata,
31
+ ScheduledPostReceiptSchema,
32
+ ScheduledPostSchema,
33
+ ScheduledPostsPageSchema,
34
+ SocialProfileSchema,
35
+ SocialProfilesPageSchema,
36
+ decodeCredentials,
37
+ decodeSharedCredentials,
38
+ isCredentialMaterialError,
39
+ newConnection,
40
+ newConnectionWithOperations,
41
+ newProjectCredentialProvider
42
+ } from "./chunk-IDMDRTUF.js";
43
+
44
+ // src/generated/steps.ts
45
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
46
+ function newListSocialProfilesStep(configuration) {
47
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
48
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
49
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listSocialProfiles(), connection: connection.reference, branches: [
50
+ goToBranch("listed", listed),
51
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
52
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
53
+ ...defect ? [goToBranch("defect", defect)] : []
54
+ ] });
55
+ }
56
+ function newListScheduledPostsStep(configuration) {
57
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
58
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
59
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listScheduledPosts(), connection: connection.reference, branches: [
60
+ goToBranch("listed", listed),
61
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
62
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
63
+ ...defect ? [goToBranch("defect", defect)] : []
64
+ ] });
65
+ }
66
+ function newSchedulePostStep(configuration) {
67
+ const { connection, connectionName, scheduled, providerRejected, uncertain, defect, ...stepConfiguration } = configuration;
68
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
69
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.schedulePost(), connection: connection.reference, branches: [
70
+ goToBranch("scheduled", scheduled),
71
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
72
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : [],
73
+ ...defect ? [goToBranch("defect", defect)] : []
74
+ ] });
75
+ }
76
+
77
+ // src/client.ts
78
+ import { definitionMaxSends, SecretString, ReauthorizationRequiredError, resolveCredential, newQueryBranch, newQueryRetry, newMutationBranch, newMutationRetry, newMutationUncertain } from "@superdurable/connectors-sdk";
79
+ import { ManifestCredentialRefreshDriver } from "@superdurable/connectors-sdk/oauthtoken";
80
+ import { BodyTooLargeError, ProviderStalledError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
81
+ import { CheckpointError, DispatchNotAllowedError, InsufficientTimeError, newFence } from "@superdurable/connectors-sdk/singledispatch";
82
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
83
+
84
+ // src/generated/refresh.ts
85
+ var Authorization = {
86
+ "fields": [
87
+ {
88
+ "name": "oauth_client_id",
89
+ "required": true,
90
+ "type": "string"
91
+ },
92
+ {
93
+ "name": "oauth_client_secret",
94
+ "required": true,
95
+ "type": "secretString"
96
+ },
97
+ {
98
+ "name": "access_token",
99
+ "required": true,
100
+ "type": "secretString"
101
+ },
102
+ {
103
+ "name": "refresh_token",
104
+ "required": true,
105
+ "type": "secretString"
106
+ }
107
+ ],
108
+ "oauth2": {
109
+ "clientIDCredential": "oauth_client_id",
110
+ "clientSecretCredential": "oauth_client_secret",
111
+ "credentialMappings": [
112
+ {
113
+ "credential": "access_token",
114
+ "source": "access_token"
115
+ },
116
+ {
117
+ "credential": "refresh_token",
118
+ "source": "refresh_token"
119
+ }
120
+ ],
121
+ "refresh": {
122
+ "missingExpiry": "reject",
123
+ "storedMissingExpiry": "refresh",
124
+ "terminalErrorCodes": [
125
+ "invalid_grant",
126
+ "invalid_client",
127
+ "unauthorized_client"
128
+ ],
129
+ "tokenExchangeTimeout": "15s"
130
+ },
131
+ "scopes": [
132
+ "offline"
133
+ ],
134
+ "tokenEndpoint": "https://platform.hootsuite.com/oauth2/token",
135
+ "tokenEndpointAuthMethod": "client_secret_basic"
136
+ },
137
+ "refreshable": true,
138
+ "type": "oauth2"
139
+ };
140
+ var CredentialFields = {
141
+ "access_token": "accessToken",
142
+ "oauth_client_id": "oauthClientId",
143
+ "oauth_client_secret": "oauthClientSecret",
144
+ "refresh_token": "refreshToken"
145
+ };
146
+
147
+ // src/client.ts
148
+ var emptyProfiles = () => ({ profiles: [] });
149
+ var emptyScheduledPosts = () => ({ posts: [], nextCursor: "" });
150
+ var emptyReceipt = () => ({ id: "", state: "", socialProfileId: "" });
151
+ var numericID = /^[0-9]{1,40}$/;
152
+ var utcInstant = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;
153
+ var HootsuiteClient = class {
154
+ /** Validate configuration without contacting Hootsuite. */
155
+ constructor(config, credentials, options = {}) {
156
+ this.credentials = credentials;
157
+ if (!config || !credentials) throw new TypeError("Hootsuite configuration and credentials are required");
158
+ this.baseURL = validateBaseURL(config.baseUrl || "https://platform.hootsuite.com");
159
+ this.timeoutMs = config.timeoutMs || 15e3;
160
+ this.maxResponseBytes = config.maxResponseBytes || 1048576;
161
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0) throw new TypeError("Hootsuite request limits are invalid");
162
+ this.refreshDriver = options.refreshDriver ?? new ManifestCredentialRefreshDriver({
163
+ providerName: "Hootsuite",
164
+ auth: Authorization,
165
+ credentialFields: CredentialFields
166
+ });
167
+ this.sendRequest = options.send ?? sendProviderRequest;
168
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
169
+ }
170
+ credentials;
171
+ baseURL;
172
+ timeoutMs;
173
+ maxResponseBytes;
174
+ refreshDriver;
175
+ sendRequest;
176
+ now;
177
+ /** Bind the social profile Query. */
178
+ listSocialProfiles() {
179
+ return new ListSocialProfilesOperation(this);
180
+ }
181
+ /** Bind the scheduled message Query. */
182
+ listScheduledPosts() {
183
+ return new ListScheduledPostsOperation(this);
184
+ }
185
+ /** Bind the scheduled message Mutation. */
186
+ schedulePost() {
187
+ return new SchedulePostOperation(this);
188
+ }
189
+ /** Resolve a header-safe access token for the current call, classified as for a write. */
190
+ async resolveToken(call) {
191
+ return this.resolveTokenClassifying(call, isTerminalCredentialError);
192
+ }
193
+ /**
194
+ * Resolve a header-safe access token for a write. A revoked, missing, unselected, or broker-refused
195
+ * connection is `credential`; any other read failure is `refresh` and may succeed on a later attempt.
196
+ */
197
+ async resolveWriteToken(call) {
198
+ return this.resolveTokenClassifying(call, isTerminalCredentialError);
199
+ }
200
+ async resolveTokenClassifying(call, isTerminal) {
201
+ try {
202
+ const resolved = await resolveCredential(this.credentials, call, this.refreshDriver, call.context.cancellationSignal);
203
+ const token = resolved.accessToken instanceof SecretString ? resolved.accessToken.reveal() : "";
204
+ return token && isHeaderSafeCredential(token) ? token : failedExchange("credential");
205
+ } catch (error) {
206
+ return failedExchange(isTerminal(error) ? "credential" : "refresh");
207
+ }
208
+ }
209
+ /** Read one bounded provider response for a Query. */
210
+ async get(call, path) {
211
+ const token = await this.resolveToken(call);
212
+ if (typeof token !== "string") return token;
213
+ return this.send("GET", path, token, call.context.cancellationSignal);
214
+ }
215
+ /** Send one authenticated request; the caller owns dispatch fencing for writes. */
216
+ async send(method, path, token, signal, body) {
217
+ const request = {
218
+ url: this.baseURL + path,
219
+ method,
220
+ headers: {
221
+ Accept: "application/json",
222
+ Authorization: `Bearer ${token}`,
223
+ "User-Agent": "Dex Connector (https://superdurable.io)",
224
+ ...body === void 0 ? {} : { "Content-Type": "application/json;charset=utf-8" }
225
+ },
226
+ ...body === void 0 ? {} : { body },
227
+ maxResponseBytes: this.maxResponseBytes,
228
+ timeoutMs: this.timeoutMs,
229
+ addressPolicy: this.baseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
230
+ signal
231
+ };
232
+ let response;
233
+ try {
234
+ response = await this.sendRequest(request);
235
+ } catch (error) {
236
+ if (error instanceof BodyTooLargeError && error.status !== void 0) return {
237
+ ...failedExchange("tooLarge"),
238
+ status: error.status,
239
+ requestSent: true,
240
+ retryAfterMs: parseRetryAfter(header(error.headers ?? {}, "retry-after"), this.now())
241
+ };
242
+ if ((error instanceof ProviderTransportError && !error.isProvablyNotSent || error instanceof ProviderStalledError) && error.status !== void 0 && error.status >= 100) return {
243
+ ...failedExchange("read"),
244
+ status: error.status,
245
+ requestSent: true,
246
+ retryAfterMs: parseRetryAfter(header(error.headers ?? {}, "retry-after"), this.now())
247
+ };
248
+ if (error instanceof ProviderTransportError) return { ...failedExchange("request"), requestSent: !error.isProvablyNotSent };
249
+ return { ...failedExchange("request"), requestSent: true };
250
+ }
251
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"), this.now());
252
+ if (Buffer.from(response.body).includes(token)) return { ...failedExchange("credential"), status: response.status, requestSent: true, retryAfterMs };
253
+ if (response.body.length > this.maxResponseBytes) return { ...failedExchange("tooLarge"), status: response.status, requestSent: true, retryAfterMs };
254
+ return { status: response.status, body: response.body, retryAfterMs, requestSent: true };
255
+ }
256
+ };
257
+ var ListSocialProfilesOperation = class {
258
+ /** Bind the provider client. */
259
+ constructor(client) {
260
+ this.client = client;
261
+ }
262
+ client;
263
+ /** Return the generated Query definition. */
264
+ definition() {
265
+ return ListSocialProfilesDefinition;
266
+ }
267
+ /** Project one bounded provider response. */
268
+ async invoke(call, input) {
269
+ if (!input || typeof input !== "object") return queryBranch("listSocialProfiles", "defect", "VALIDATION", "social profile input is invalid", emptyProfiles());
270
+ const exchange = await this.client.get(call, "/v1/socialProfiles");
271
+ const decision = queryFailure("listSocialProfiles", exchange, emptyProfiles());
272
+ if (decision) return decision;
273
+ const document = parseJSON(exchange.body);
274
+ if (!isObject(document) || !Array.isArray(document.data) || document.data.length > 1e3) return queryBranch("listSocialProfiles", "invalidResponse", "PROTOCOL", "Hootsuite returned invalid social profile JSON", emptyProfiles());
275
+ const profiles = [];
276
+ for (const item of document.data) {
277
+ if (!isObject(item) || typeof item.id !== "string" || !item.id || typeof item.type !== "string" || !item.type || typeof item.socialNetworkUsername !== "string" || !item.socialNetworkUsername) return queryBranch("listSocialProfiles", "invalidResponse", "PROTOCOL", "Hootsuite returned incomplete social profile metadata", emptyProfiles());
278
+ profiles.push({ id: item.id, type: item.type, username: item.socialNetworkUsername });
279
+ }
280
+ return newQueryBranch("listed", { profiles });
281
+ }
282
+ };
283
+ var ListScheduledPostsOperation = class {
284
+ /** Bind the provider client. */
285
+ constructor(client) {
286
+ this.client = client;
287
+ }
288
+ client;
289
+ /** Return the generated Query definition. */
290
+ definition() {
291
+ return ListScheduledPostsDefinition;
292
+ }
293
+ /** Read one UTC interval of at most four weeks. */
294
+ async invoke(call, input) {
295
+ const start = utcTime(input?.startTime);
296
+ const end = utcTime(input?.endTime);
297
+ if (start === void 0 || end === void 0 || end <= start || end - start > 28 * 24 * 60 * 60 * 1e3 || typeof input.socialProfileId !== "string" && input.socialProfileId !== void 0 || typeof input.cursor !== "string" && input.cursor !== void 0 || (input.socialProfileId?.length ?? 0) > 40 || (input.cursor?.length ?? 0) > 4096 || !safeQueryValue(input.socialProfileId ?? "") || !safeQueryValue(input.cursor ?? "")) return queryBranch("listScheduledPosts", "defect", "VALIDATION", "scheduled post interval or filter is invalid", emptyScheduledPosts());
298
+ const query = new URLSearchParams({ startTime: input.startTime, endTime: input.endTime, state: "SCHEDULED", limit: "100" });
299
+ if (input.socialProfileId) query.set("socialProfileIds", input.socialProfileId);
300
+ if (input.cursor) query.set("cursor", input.cursor);
301
+ const exchange = await this.client.get(call, `/v1/messages?${query}`);
302
+ const decision = queryFailure("listScheduledPosts", exchange, emptyScheduledPosts());
303
+ if (decision) return decision;
304
+ const document = parseJSON(exchange.body);
305
+ if (!isObject(document) || !Array.isArray(document.data) || document.data.length > 100) return queryBranch("listScheduledPosts", "invalidResponse", "PROTOCOL", "Hootsuite returned invalid scheduled message JSON", emptyScheduledPosts());
306
+ const posts = [];
307
+ for (const item of document.data) {
308
+ if (!isObject(item) || typeof item.id !== "string" || !item.id || item.state !== "SCHEDULED" || typeof item.scheduledSendTime !== "string" || !item.scheduledSendTime || !isObject(item.socialProfile) || typeof item.socialProfile.id !== "string" || !item.socialProfile.id) return queryBranch("listScheduledPosts", "invalidResponse", "PROTOCOL", "Hootsuite returned incomplete scheduled message metadata", emptyScheduledPosts());
309
+ posts.push({ id: item.id, state: item.state, socialProfileId: item.socialProfile.id, scheduledSendTime: item.scheduledSendTime });
310
+ }
311
+ const metadata = document.metadata ?? {};
312
+ if (!isObject(metadata)) return queryBranch("listScheduledPosts", "invalidResponse", "PROTOCOL", "Hootsuite returned an invalid page cursor", emptyScheduledPosts());
313
+ const cursor = metadata.cursor ?? {};
314
+ if (!isObject(cursor)) return queryBranch("listScheduledPosts", "invalidResponse", "PROTOCOL", "Hootsuite returned an invalid page cursor", emptyScheduledPosts());
315
+ const nextCursor = cursor.next ?? "";
316
+ if (typeof nextCursor !== "string" || nextCursor.length > 4096 || !safeQueryValue(nextCursor)) return queryBranch("listScheduledPosts", "invalidResponse", "PROTOCOL", "Hootsuite returned an invalid page cursor", emptyScheduledPosts());
317
+ return newQueryBranch("listed", { posts, nextCursor });
318
+ }
319
+ };
320
+ var SchedulePostOperation = class {
321
+ /** Bind the provider client. */
322
+ constructor(client) {
323
+ this.client = client;
324
+ }
325
+ client;
326
+ /** Return the generated Mutation definition. */
327
+ definition() {
328
+ return SchedulePostDefinition;
329
+ }
330
+ /** Record the Call ID; Hootsuite does not deduplicate this key. */
331
+ idempotencyKey(callID) {
332
+ return callID;
333
+ }
334
+ /**
335
+ * Schedule under a single-dispatch fence. Hootsuite has no message idempotency key, so an unknown
336
+ * outcome retries while possible sends stay below the send cap and selects uncertain at the cap.
337
+ * A definite refusal is never resent.
338
+ */
339
+ async invoke(call, input) {
340
+ const operation = "schedulePost";
341
+ const empty = emptyReceipt();
342
+ if (!input || typeof input.text !== "string" || !input.text.trim() || Buffer.from(input.text, "utf8").toString("utf8") !== input.text || Buffer.byteLength(input.text, "utf8") > 1e4 || typeof input.socialProfileId !== "string" || !numericID.test(input.socialProfileId) || utcTime(input.scheduledSendTime) === void 0) return newMutationBranch("defect", empty, {}, failure(operation, "VALIDATION", "scheduled message text, profile ID, or UTC time is invalid"));
343
+ const operationMaxSends = definitionMaxSends(SchedulePostDefinition);
344
+ let fence;
345
+ try {
346
+ fence = newFence(call, SchedulePostDefinition.stepDefaults.executeMethodTimeoutMs ?? 3e4, { maxSends: operationMaxSends });
347
+ } catch {
348
+ return newMutationBranch("defect", empty, {}, failure(operation, "LOCAL_DEFECT", "Hootsuite dispatch fence is unavailable"));
349
+ }
350
+ const decision = fence.decide();
351
+ if (decision.kind === "failClosed") return newMutationRetry(failure(operation, "AVAILABILITY", "Hootsuite dispatch checkpoint is unreadable; no message was scheduled in this attempt"));
352
+ if (decision.kind === "readBackRequired") return newMutationUncertain(empty, failure(operation, "TRANSPORT", "an earlier attempt may have scheduled the Hootsuite message, and the send cap is reached; inspect Planner before resending"));
353
+ if (decision.kind === "readBackThenResendAllowed" && decision.marker?.providerId) return newMutationUncertain(empty, failure(operation, "TRANSPORT", "an earlier attempt scheduled the Hootsuite message, but its confirmation was lost"));
354
+ const priorSendUpperBound = decision.priorSendUpperBound ?? 0;
355
+ const canResendUnknownOutcome = priorSendUpperBound + 1 < effectiveMaxSends(call, operationMaxSends);
356
+ const hasPossibleEarlierSend = priorSendUpperBound > 0;
357
+ const token = await this.client.resolveWriteToken(call);
358
+ if (typeof token !== "string") {
359
+ if (token.error === "credential") return localScheduleFailure(fence, hasPossibleEarlierSend, failure(operation, "AUTHENTICATION", "connection credentials are unavailable or require reauthorization"));
360
+ if (!hasPossibleEarlierSend) {
361
+ try {
362
+ await fence.recordNotSent();
363
+ } catch {
364
+ }
365
+ }
366
+ return newMutationRetry(failure(operation, "TRANSPORT", "connection refresh failed"));
367
+ }
368
+ const body = Buffer.from(JSON.stringify({ text: input.text, socialProfileIds: [input.socialProfileId], scheduledSendTime: input.scheduledSendTime }));
369
+ let exchange;
370
+ try {
371
+ exchange = await fence.dispatch((signal) => this.client.send("POST", "/v1/messages", token, signal, body));
372
+ } catch (error) {
373
+ if (error instanceof CheckpointError || error instanceof InsufficientTimeError || error instanceof DispatchNotAllowedError || isFenceInsufficientTimeAggregateError(error)) return newMutationRetry(failure(operation, "TRANSPORT", "Hootsuite dispatch did not start"));
374
+ return resendOrSelectUncertain(canResendUnknownOutcome, failure(operation, "TRANSPORT", "Hootsuite schedule outcome is unknown"));
375
+ }
376
+ if (exchange.error === "request") {
377
+ if (!exchange.requestSent) {
378
+ try {
379
+ await fence.recordCanResend();
380
+ } catch {
381
+ }
382
+ return newMutationRetry(failure(operation, "TRANSPORT", "Hootsuite could not be reached before sending"));
383
+ }
384
+ return resendOrSelectUncertain(canResendUnknownOutcome, failure(operation, "TRANSPORT", "Hootsuite schedule outcome is unknown"));
385
+ }
386
+ if (exchange.status === 429 || exchange.status === 503) {
387
+ try {
388
+ await fence.recordCanResend();
389
+ } catch {
390
+ return newMutationRetry(failure(operation, "AVAILABILITY", "Hootsuite retry checkpoint is unavailable"));
391
+ }
392
+ const kind = exchange.status === 429 ? "RATE_LIMIT" : "AVAILABILITY";
393
+ return newMutationRetry(failure(operation, kind, "Hootsuite did not schedule the message"), exchange.retryAfterMs);
394
+ }
395
+ const isSuccessStatus = exchange.status >= 200 && exchange.status < 300;
396
+ const isBodyReadable = !exchange.error;
397
+ const document = isBodyReadable ? parseJSON(exchange.body) : void 0;
398
+ const data = isObject(document) ? document.data : void 0;
399
+ const first = Array.isArray(data) && isObject(data[0]) ? data[0] : void 0;
400
+ const messageID = first && typeof first.id === "string" ? first.id : "";
401
+ if (isSuccessStatus && !isBodyReadable) return newMutationUncertain(empty, failure(operation, "TRANSPORT", "Hootsuite accepted the request, but its response could not be read"));
402
+ if (isSuccessStatus && !messageID) return newMutationUncertain(empty, failure(operation, "PROTOCOL", "Hootsuite accepted the request, but its response is malformed"));
403
+ if (!isSuccessStatus && messageID) return newMutationUncertain(empty, failure(operation, "PROTOCOL", "Hootsuite returned a contradictory schedule response"));
404
+ if (!isSuccessStatus) {
405
+ if (isBodyReadable && definiteRefusalStatuses.has(exchange.status)) return rejectOrSelectUncertain(fence, hasPossibleEarlierSend, failure(operation, rejectionKind(exchange.status), `Hootsuite rejected HTTP ${exchange.status}`));
406
+ return resendOrSelectUncertain(canResendUnknownOutcome, failure(operation, "AVAILABILITY", `Hootsuite schedule outcome is unknown after HTTP ${exchange.status}`), exchange.retryAfterMs);
407
+ }
408
+ if (!first || !Array.isArray(data)) return newMutationUncertain(empty, failure(operation, "PROTOCOL", "Hootsuite accepted the request, but its response is malformed"));
409
+ try {
410
+ await fence.recordProviderId(messageID);
411
+ } catch {
412
+ }
413
+ if (exchange.status !== 200 || data.length !== 1 || typeof first.state !== "string" || !first.state) return newMutationUncertain(empty, failure(operation, "PROTOCOL", "Hootsuite accepted the request but returned an unexpected schedule response"));
414
+ const socialProfile = first.socialProfile ?? {};
415
+ if (!isObject(socialProfile) || socialProfile.id && socialProfile.id !== input.socialProfileId) return newMutationUncertain(empty, failure(operation, "PROTOCOL", "Hootsuite returned an unexpected social profile"));
416
+ return newMutationBranch("scheduled", { id: messageID, state: first.state, socialProfileId: input.socialProfileId });
417
+ }
418
+ };
419
+ var definiteRefusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
420
+ function effectiveMaxSends(call, operationMaxSends) {
421
+ return operationMaxSends >= 2 ? call.maxSendsOverride ?? operationMaxSends : 1;
422
+ }
423
+ function resendOrSelectUncertain(canResendUnknownOutcome, unknownFailure, delay = 0) {
424
+ return canResendUnknownOutcome ? newMutationRetry(unknownFailure, delay) : newMutationUncertain(emptyReceipt(), unknownFailure);
425
+ }
426
+ async function rejectOrSelectUncertain(fence, hasPossibleEarlierSend, rejection) {
427
+ if (hasPossibleEarlierSend) return newMutationUncertain(emptyReceipt(), rejection);
428
+ try {
429
+ await fence.recordCanResend();
430
+ } catch {
431
+ }
432
+ return newMutationBranch("providerRejected", emptyReceipt(), {}, rejection);
433
+ }
434
+ async function localScheduleFailure(fence, hasPossibleEarlierSend, localFailure) {
435
+ if (hasPossibleEarlierSend) return newMutationUncertain(emptyReceipt(), { ...localFailure, message: `${localFailure.message}; an earlier attempt may have scheduled the message` });
436
+ try {
437
+ await fence.recordNotSent();
438
+ } catch {
439
+ }
440
+ return newMutationBranch("defect", emptyReceipt(), {}, localFailure);
441
+ }
442
+ function isTerminalCredentialError(error) {
443
+ return error instanceof ReauthorizationRequiredError || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError || isCredentialMaterialError(error);
444
+ }
445
+ function rejectionKind(status) {
446
+ return status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION";
447
+ }
448
+ function failure(operation, kind, message) {
449
+ return { provider: "hootsuite", operation, kind, message };
450
+ }
451
+ function queryBranch(operation, branch, kind, message, empty) {
452
+ return newQueryBranch(branch, empty, {}, failure(operation, kind, message));
453
+ }
454
+ function queryRetry(operation, kind, message, delay = 0) {
455
+ return newQueryRetry(failure(operation, kind, message), delay);
456
+ }
457
+ function queryFailure(operation, exchange, empty) {
458
+ if (exchange.error === "credential") return queryBranch(operation, "defect", "AUTHENTICATION", "connection credentials are unavailable or invalid", empty);
459
+ if (exchange.error === "request" || exchange.error === "refresh" || exchange.error === "read") return queryRetry(operation, "TRANSPORT", "Hootsuite request failed");
460
+ if (exchange.status === 429) return queryRetry(operation, "RATE_LIMIT", "Hootsuite rate limited the request", exchange.retryAfterMs);
461
+ if (exchange.status === 408 || exchange.status >= 500) return queryRetry(operation, "AVAILABILITY", "Hootsuite is temporarily unavailable", exchange.retryAfterMs);
462
+ if (exchange.status !== 200) return queryBranch(operation, "providerRejected", "PROVIDER_REJECTION", `Hootsuite rejected HTTP ${exchange.status}`, empty);
463
+ if (exchange.error === "tooLarge") return queryBranch(operation, "invalidResponse", "RESPONSE_TOO_LARGE", "Hootsuite response exceeded the configured limit", empty);
464
+ return void 0;
465
+ }
466
+ function failedExchange(error) {
467
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error, requestSent: false };
468
+ }
469
+ function isObject(value) {
470
+ return typeof value === "object" && value !== null && !Array.isArray(value);
471
+ }
472
+ function parseJSON(body) {
473
+ try {
474
+ return JSON.parse(Buffer.from(body).toString("utf8"));
475
+ } catch {
476
+ return void 0;
477
+ }
478
+ }
479
+ function safeQueryValue(value) {
480
+ return ![...value].some((character) => {
481
+ const code = character.charCodeAt(0);
482
+ return code < 32 || code === 127;
483
+ });
484
+ }
485
+ function utcTime(value) {
486
+ if (typeof value !== "string" || !utcInstant.test(value)) return void 0;
487
+ const parsed = Date.parse(value);
488
+ return Number.isNaN(parsed) ? void 0 : parsed;
489
+ }
490
+ function header(headers, name) {
491
+ const value = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
492
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
493
+ }
494
+ function isFenceInsufficientTimeAggregateError(error) {
495
+ return error instanceof AggregateError && error.errors.some((cause) => cause instanceof InsufficientTimeError);
496
+ }
497
+
498
+ // src/project.ts
499
+ function encodeCredentials(credentials) {
500
+ return {
501
+ oauth_client_id: credentials.oauthClientId,
502
+ oauth_client_secret: credentials.oauthClientSecret.reveal(),
503
+ access_token: credentials.accessToken.reveal(),
504
+ refresh_token: credentials.refreshToken.reveal()
505
+ };
506
+ }
507
+ function newProjectConnection(project, connectionName, options = {}) {
508
+ if (!project) throw new TypeError("Hootsuite project is required");
509
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === "hootsuite" && entry.connectionName === connectionName);
510
+ if (!selected || selected.provider !== "hootsuite") throw new TypeError("Hootsuite project connection is not configured");
511
+ const config = ConfigSchema.parse(selected.configuration);
512
+ const provider = newProjectCredentialProvider(project, connectionName, decodeCredentials, encodeCredentials, decodeSharedCredentials);
513
+ return newConnection(new HootsuiteClient(config, provider, options), { provider: "hootsuite", name: connectionName });
514
+ }
515
+ export {
516
+ ConfigSchema,
517
+ Connection,
518
+ ConnectorID,
519
+ CredentialMaterialError,
520
+ HootsuiteClient,
521
+ ListScheduledPostsBranch,
522
+ ListScheduledPostsBranchDefect,
523
+ ListScheduledPostsBranchInvalidResponse,
524
+ ListScheduledPostsBranchListed,
525
+ ListScheduledPostsBranchProviderRejected,
526
+ ListScheduledPostsDefinition,
527
+ ListScheduledPostsInputSchema,
528
+ ListScheduledPostsMetadata,
529
+ ListScheduledPostsOperation,
530
+ ListSocialProfilesBranch,
531
+ ListSocialProfilesBranchDefect,
532
+ ListSocialProfilesBranchInvalidResponse,
533
+ ListSocialProfilesBranchListed,
534
+ ListSocialProfilesBranchProviderRejected,
535
+ ListSocialProfilesDefinition,
536
+ ListSocialProfilesInputSchema,
537
+ ListSocialProfilesMetadata,
538
+ ListSocialProfilesOperation,
539
+ ProviderID,
540
+ SchedulePostBranch,
541
+ SchedulePostBranchDefect,
542
+ SchedulePostBranchProviderRejected,
543
+ SchedulePostBranchScheduled,
544
+ SchedulePostBranchUncertain,
545
+ SchedulePostDefinition,
546
+ SchedulePostInputSchema,
547
+ SchedulePostMetadata,
548
+ SchedulePostOperation,
549
+ ScheduledPostReceiptSchema,
550
+ ScheduledPostSchema,
551
+ ScheduledPostsPageSchema,
552
+ SocialProfileSchema,
553
+ SocialProfilesPageSchema,
554
+ decodeCredentials,
555
+ decodeSharedCredentials,
556
+ isCredentialMaterialError,
557
+ newConnection,
558
+ newConnectionWithOperations,
559
+ newListScheduledPostsStep,
560
+ newListSocialProfilesStep,
561
+ newProjectConnection,
562
+ newSchedulePostStep
563
+ };
package/dist/mock.d.ts ADDED
@@ -0,0 +1,75 @@
1
+ import { MockQuery, MockMutation, Case } from '@superdurable/connectors-sdk/connectormock';
2
+ import { Failure } from '@superdurable/connectors-sdk';
3
+ import { O as Operations, C as Connection, a as ListSocialProfilesInput, b as SocialProfilesPage, L as ListScheduledPostsInput, S as ScheduledPostsPage, c as SchedulePostInput, d as ScheduledPostReceipt, m as ScheduledPost, q as SocialProfile } from './connection-DZkHHYyF.js';
4
+ import 'zod';
5
+
6
+ /** Go zero value for ListSocialProfilesInput in scripted cases. */
7
+ declare const emptyListSocialProfilesInput: ListSocialProfilesInput;
8
+ /** Go zero value for SocialProfile in scripted cases. */
9
+ declare const emptySocialProfile: SocialProfile;
10
+ /** Go zero value for SocialProfilesPage in scripted cases. */
11
+ declare const emptySocialProfilesPage: SocialProfilesPage;
12
+ /** Go zero value for ListScheduledPostsInput in scripted cases. */
13
+ declare const emptyListScheduledPostsInput: ListScheduledPostsInput;
14
+ /** Go zero value for ScheduledPost in scripted cases. */
15
+ declare const emptyScheduledPost: ScheduledPost;
16
+ /** Go zero value for ScheduledPostsPage in scripted cases. */
17
+ declare const emptyScheduledPostsPage: ScheduledPostsPage;
18
+ /** Go zero value for SchedulePostInput in scripted cases. */
19
+ declare const emptySchedulePostInput: SchedulePostInput;
20
+ /** Go zero value for ScheduledPostReceipt in scripted cases. */
21
+ declare const emptyScheduledPostReceipt: ScheduledPostReceipt;
22
+ /** Script the listed branch. */
23
+ declare function listSocialProfilesListed(value: SocialProfilesPage, failure?: Failure): Case<SocialProfilesPage>;
24
+ /** Script the providerRejected branch. */
25
+ declare function listSocialProfilesProviderRejected(value: SocialProfilesPage, failure?: Failure): Case<SocialProfilesPage>;
26
+ /** Script the invalidResponse branch. */
27
+ declare function listSocialProfilesInvalidResponse(value: SocialProfilesPage, failure?: Failure): Case<SocialProfilesPage>;
28
+ /** Script the defect branch. */
29
+ declare function listSocialProfilesDefect(value: SocialProfilesPage, failure?: Failure): Case<SocialProfilesPage>;
30
+ /** Script a safe retry of listSocialProfiles. */
31
+ declare function listSocialProfilesRetry(failure: Failure, retryAfterMs?: number): Case<SocialProfilesPage>;
32
+ /** Manifest scenario listedDefault for listSocialProfiles. */
33
+ declare function listSocialProfilesListedDefault(): Case<SocialProfilesPage>;
34
+ /** Default listSocialProfiles scenario. */
35
+ declare function listSocialProfilesDefault(): Case<SocialProfilesPage>;
36
+ /** Script the listed branch. */
37
+ declare function listScheduledPostsListed(value: ScheduledPostsPage, failure?: Failure): Case<ScheduledPostsPage>;
38
+ /** Script the providerRejected branch. */
39
+ declare function listScheduledPostsProviderRejected(value: ScheduledPostsPage, failure?: Failure): Case<ScheduledPostsPage>;
40
+ /** Script the invalidResponse branch. */
41
+ declare function listScheduledPostsInvalidResponse(value: ScheduledPostsPage, failure?: Failure): Case<ScheduledPostsPage>;
42
+ /** Script the defect branch. */
43
+ declare function listScheduledPostsDefect(value: ScheduledPostsPage, failure?: Failure): Case<ScheduledPostsPage>;
44
+ /** Script a safe retry of listScheduledPosts. */
45
+ declare function listScheduledPostsRetry(failure: Failure, retryAfterMs?: number): Case<ScheduledPostsPage>;
46
+ /** Manifest scenario listedDefault for listScheduledPosts. */
47
+ declare function listScheduledPostsListedDefault(): Case<ScheduledPostsPage>;
48
+ /** Default listScheduledPosts scenario. */
49
+ declare function listScheduledPostsDefault(): Case<ScheduledPostsPage>;
50
+ /** Script the scheduled branch. */
51
+ declare function schedulePostScheduled(value: ScheduledPostReceipt, failure?: Failure): Case<ScheduledPostReceipt>;
52
+ /** Script the providerRejected branch. */
53
+ declare function schedulePostProviderRejected(value: ScheduledPostReceipt, failure?: Failure): Case<ScheduledPostReceipt>;
54
+ /** Script the defect branch. */
55
+ declare function schedulePostDefect(value: ScheduledPostReceipt, failure?: Failure): Case<ScheduledPostReceipt>;
56
+ /** Script a safe retry of schedulePost. */
57
+ declare function schedulePostRetry(failure: Failure, retryAfterMs?: number): Case<ScheduledPostReceipt>;
58
+ /** Script an uncertain schedulePost attempt. */
59
+ declare function schedulePostUncertain(value: ScheduledPostReceipt, failure: Failure): Case<ScheduledPostReceipt>;
60
+ /** Manifest scenario scheduledDefault for schedulePost. */
61
+ declare function schedulePostScheduledDefault(): Case<ScheduledPostReceipt>;
62
+ /** Default schedulePost scenario. */
63
+ declare function schedulePostDefault(): Case<ScheduledPostReceipt>;
64
+ /** Scripted operations and manifest defaults for this connector. */
65
+ declare class GeneratedMock implements Operations {
66
+ #private;
67
+ constructor(connectionName: string);
68
+ connection(): Connection;
69
+ listSocialProfiles(): MockQuery<ListSocialProfilesInput, SocialProfilesPage>;
70
+ listScheduledPosts(): MockQuery<ListScheduledPostsInput, ScheduledPostsPage>;
71
+ schedulePost(): MockMutation<SchedulePostInput, ScheduledPostReceipt>;
72
+ assertNoFailures(): void;
73
+ }
74
+
75
+ export { GeneratedMock, GeneratedMock as Mock, emptyListScheduledPostsInput, emptyListSocialProfilesInput, emptySchedulePostInput, emptyScheduledPost, emptyScheduledPostReceipt, emptyScheduledPostsPage, emptySocialProfile, emptySocialProfilesPage, listScheduledPostsDefault, listScheduledPostsDefect, listScheduledPostsInvalidResponse, listScheduledPostsListed, listScheduledPostsListedDefault, listScheduledPostsProviderRejected, listScheduledPostsRetry, listSocialProfilesDefault, listSocialProfilesDefect, listSocialProfilesInvalidResponse, listSocialProfilesListed, listSocialProfilesListedDefault, listSocialProfilesProviderRejected, listSocialProfilesRetry, schedulePostDefault, schedulePostDefect, schedulePostProviderRejected, schedulePostRetry, schedulePostScheduled, schedulePostScheduledDefault, schedulePostUncertain };