samva 0.50.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/AGENTS.md +44 -3
  2. package/README.md +136 -7
  3. package/dist/client/sdk.gen.d.ts +12 -11
  4. package/dist/client/sdk.gen.js +1399 -940
  5. package/dist/client/types.gen.d.ts +21 -10
  6. package/dist/effect/agents.d.ts +4 -4
  7. package/dist/effect/api-keys.d.ts +4 -6
  8. package/dist/effect/campaigns.d.ts +166 -174
  9. package/dist/effect/categories.d.ts +2 -2
  10. package/dist/effect/categories.js +6 -4
  11. package/dist/effect/contact-groups.d.ts +4 -4
  12. package/dist/effect/contacts.d.ts +8 -8
  13. package/dist/effect/conversations.d.ts +4 -4
  14. package/dist/effect/email.d.ts +17 -16
  15. package/dist/effect/errors.d.ts +1 -0
  16. package/dist/effect/errors.js +2 -1
  17. package/dist/effect/generated/api-keys.d.ts +0 -15
  18. package/dist/effect/generated/api-keys.js +1 -2
  19. package/dist/effect/generated/campaigns.d.ts +0 -62
  20. package/dist/effect/generated/campaigns.js +3 -9
  21. package/dist/effect/generated/email.d.ts +10 -3
  22. package/dist/effect/generated/email.js +3 -2
  23. package/dist/effect/generated/mailboxes.js +6 -6
  24. package/dist/effect/generated/namespaces.js +1 -1
  25. package/dist/effect/generated/policies.js +2 -2
  26. package/dist/effect/generated/scheduled-messages.d.ts +0 -26
  27. package/dist/effect/generated/scheduled-messages.js +1 -3
  28. package/dist/effect/generated/shared.d.ts +1 -0
  29. package/dist/effect/generated/shared.js +2 -1
  30. package/dist/effect/index.js +2 -1
  31. package/dist/effect/integrations.d.ts +2 -2
  32. package/dist/effect/internal/client.d.ts +19 -2
  33. package/dist/effect/internal/client.js +10 -2
  34. package/dist/effect/internal/email-sender.d.ts +4 -4
  35. package/dist/effect/internal/email-sender.js +5 -3
  36. package/dist/effect/internal/operation.d.ts +11 -0
  37. package/dist/effect/internal/operation.js +10 -6
  38. package/dist/effect/internal/send.d.ts +4 -0
  39. package/dist/effect/internal/send.js +11 -8
  40. package/dist/effect/internal/timeout.d.ts +16 -0
  41. package/dist/effect/internal/timeout.js +20 -0
  42. package/dist/effect/journeys.d.ts +152 -152
  43. package/dist/effect/mailboxes.d.ts +28 -28
  44. package/dist/effect/messages.d.ts +5 -5
  45. package/dist/effect/namespaces.d.ts +4 -4
  46. package/dist/effect/newsletter-domains.d.ts +2 -2
  47. package/dist/effect/operations.d.ts +2 -2
  48. package/dist/effect/scheduled-messages.d.ts +2 -6
  49. package/dist/effect/templates.d.ts +6 -6
  50. package/dist/effect/topics.d.ts +4 -4
  51. package/dist/effect/webhooks.d.ts +4 -4
  52. package/dist/effect/whatsapp-setup-links.d.ts +2 -2
  53. package/dist/index.js +2 -2
  54. package/dist/package.js +1 -1
  55. package/dist/promises/client.d.ts +5 -0
  56. package/dist/promises/client.js +12 -8
  57. package/dist/promises/errors.gen.d.ts +12 -1
  58. package/dist/promises/errors.gen.js +21 -2
  59. package/dist/promises/index.js +2 -2
  60. package/dist/promises/request.d.ts +31 -2
  61. package/dist/promises/request.js +42 -7
  62. package/dist/request-policy.d.ts +9 -0
  63. package/dist/request-policy.js +16 -1
  64. package/package.json +2 -2
@@ -35,7 +35,7 @@ export declare const list: ((input?: {
35
35
  readonly updatedAt: string;
36
36
  }[];
37
37
  readonly nextCursor: string | null;
38
- }, import("./errors.js").FlagDisabledError | import("./errors.js").ForbiddenError | import("./errors.js").GatewayTimeoutError | import("effect/http/HttpClientError").HttpClientError | import("./errors.js").InternalError | import("./errors.js").MalformedRequestError | import("effect/Schema").SchemaError | import("./errors.js").UnauthorizedError | import("./errors.js").ValidationError, import("./client.js").Service>;
38
+ }, import("./errors.js").FlagDisabledError | import("./errors.js").ForbiddenError | import("./errors.js").GatewayTimeoutError | import("effect/http/HttpClientError").HttpClientError | import("./errors.js").InternalError | import("./errors.js").MalformedRequestError | import("./errors.js").SamvaTimeoutError | import("effect/Schema").SchemaError | import("./errors.js").UnauthorizedError | import("./errors.js").ValidationError, import("./client.js").Service>;
39
39
  readonly items: (input?: {
40
40
  readonly limit?: number | null | undefined;
41
41
  readonly cursor?: string | undefined;
@@ -56,7 +56,7 @@ export declare const list: ((input?: {
56
56
  readonly revokedAt: string | null;
57
57
  readonly createdAt: string;
58
58
  readonly updatedAt: string;
59
- }, import("./errors.js").FlagDisabledError | import("./errors.js").ForbiddenError | import("./errors.js").GatewayTimeoutError | import("effect/http/HttpClientError").HttpClientError | import("./errors.js").InternalError | import("./errors.js").MalformedRequestError | import("effect/Schema").SchemaError | import("./errors.js").UnauthorizedError | import("./errors.js").ValidationError, import("./client.js").Service>;
59
+ }, import("./errors.js").FlagDisabledError | import("./errors.js").ForbiddenError | import("./errors.js").GatewayTimeoutError | import("effect/http/HttpClientError").HttpClientError | import("./errors.js").InternalError | import("./errors.js").MalformedRequestError | import("./errors.js").SamvaTimeoutError | import("effect/Schema").SchemaError | import("./errors.js").UnauthorizedError | import("./errors.js").ValidationError, import("./client.js").Service>;
60
60
  };
61
61
  export declare const get: (input: {
62
62
  readonly linkId: string;
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, fromApiError } from "./promises/errors.gen.js";
1
+ import { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTimeoutError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, fromApiError } from "./promises/errors.gen.js";
2
2
  import { MediaUploadError } from "./inline-attachments.js";
3
3
  import { MailboxEventStream, MailboxEventStreamError } from "./mailbox-events.js";
4
4
  import { createClient } from "./promises/client.js";
5
- export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxEventStream, MailboxEventStreamError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, MediaUploadError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, createClient, fromApiError };
5
+ export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxEventStream, MailboxEventStreamError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, MediaUploadError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTimeoutError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, createClient, fromApiError };
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.50.0";
2
+ var version = "0.51.0";
3
3
  export { version };
4
4
 
5
5
  //# sourceMappingURL=package.js.map
@@ -54,6 +54,11 @@ type MessageSendRequestOptions<ThrowOnError extends boolean = false> = Omit<NonN
54
54
  type MessageSendOptions<ThrowOnError extends boolean = false> = MessageSendRequestOptions<ThrowOnError> & {
55
55
  /** Sent as the `idempotency-key` header; defaults to a fresh UUID per call. */
56
56
  readonly idempotencyKey?: string | undefined;
57
+ /**
58
+ * Overrides the client's `uploadTimeoutMs` for the storage puts of oversized inline
59
+ * attachments; `undefined` inherits it.
60
+ */
61
+ readonly uploadTimeoutMs?: number | null | undefined;
57
62
  };
58
63
  type MessageSendResponse<ThrowOnError extends boolean = false> = ReturnType<typeof messages.send<ThrowOnError>>;
59
64
  /** The send's own promise, or the promise that resolves to the same value once uploads finish. */
@@ -2,8 +2,8 @@ import { CLIENT_ATTRIBUTION_HEADER, clientAttribution } from "../client-attribut
2
2
  import { mergeHeaders } from "../client/client/utils.gen.js";
3
3
  import { createClient as createClient$1 } from "../client/client/client.gen.js";
4
4
  import { SamvaOperations } from "../effect/generated-metadata.js";
5
- import { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, fromApiError } from "./errors.gen.js";
6
- import { configureRequests } from "./request.js";
5
+ import { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTimeoutError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, fromApiError } from "./errors.gen.js";
6
+ import { configureRequests, startAttempt, uploadTimeout } from "./request.js";
7
7
  import { Accounts, Agents, Analytics, ApiKeys, ApprovalRequests, Attachments, Brands, Campaigns, ContactEvents, ContactGroups, Contacts, Conversations, CustomFields, Email, Events, Feedback, IntegrationCatalog, Integrations, Journeys, Mailboxes, Media, Messages, Namespaces, Newsletters, Operations, Organizations, Policies, ScheduledMessages, Subscriptions, TemplateRegistrations, TemplateShareLinks, Templates, TopicForms, Topics, Webhooks, Whatsapp, WhatsappFlows, WhatsappSetupLinks, Whoami } from "../client/sdk.gen.js";
8
8
  import { MediaUploadError, mediaCreateBody, planInlineUploads, withUploadedAttachments } from "../inline-attachments.js";
9
9
  import { MailboxEventStream } from "../mailbox-events.js";
@@ -51,7 +51,7 @@ async function uploadOversizedAttachments(clientInstance, payload, requestOption
51
51
  const directMedia = createDirectService(createBoundService(Media, clientInstance));
52
52
  for (const upload of plan) {
53
53
  const created = await directMedia.create(mediaCreateBody(upload), requestOptions);
54
- await putUpload(clientInstance, upload, created, requestOptions.signal ?? void 0);
54
+ await putUpload(clientInstance, upload, created, requestOptions);
55
55
  await directMedia.complete({ id: created.id }, requestOptions);
56
56
  uploaded.set(upload.index, {
57
57
  mediaId: created.id,
@@ -72,23 +72,27 @@ function sendWithUploads(clientInstance, payload, requestOptions, send) {
72
72
  async function sendAfterUploads(clientInstance, payload, requestOptions, send) {
73
73
  return await send(await uploadOversizedAttachments(clientInstance, payload, requestOptions));
74
74
  }
75
- async function putUpload(clientInstance, upload, created, signal) {
75
+ /** A put that outlasts its `uploadTimeoutMs` fails as `MediaUploadError` caused by `SamvaTimeoutError`. */
76
+ async function putUpload(clientInstance, upload, created, options) {
76
77
  const fail = (status, cause) => new MediaUploadError({
77
78
  filename: upload.filename,
78
79
  mediaId: created.id,
79
80
  status,
80
81
  cause
81
82
  });
83
+ const attempt = startAttempt(options.signal ?? clientInstance.getConfig().signal, uploadTimeout(clientInstance, options.uploadTimeoutMs));
82
84
  let response;
83
85
  try {
84
86
  response = await (clientInstance.getConfig().fetch ?? globalThis.fetch)(new Request(created.upload.url, {
85
87
  method: created.upload.method,
86
88
  headers: created.upload.headers,
87
89
  body: upload.bytes,
88
- signal: signal ?? null
90
+ signal: attempt.signal ?? null
89
91
  }));
90
92
  } catch (error) {
91
- throw fail(void 0, error);
93
+ throw fail(void 0, attempt.timedOut() ?? error);
94
+ } finally {
95
+ attempt.end();
92
96
  }
93
97
  if (!response.ok) throw fail(response.status);
94
98
  }
@@ -169,7 +173,7 @@ async function unwrap(method, arguments_) {
169
173
  try {
170
174
  result = await method(...arguments_);
171
175
  } catch (error) {
172
- if (error instanceof MediaUploadError) throw error;
176
+ if (error instanceof MediaUploadError || error instanceof RangeError) throw error;
173
177
  throw fromApiError(error);
174
178
  }
175
179
  if (!isObject(result)) throw new SamvaTransportError(result);
@@ -339,6 +343,6 @@ function makeClient(config) {
339
343
  }));
340
344
  return result;
341
345
  }
342
- export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, clientWithIdempotency, createBoundClient, createClient, fromApiError };
346
+ export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTimeoutError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, clientWithIdempotency, createBoundClient, createClient, fromApiError };
343
347
 
344
348
  //# sourceMappingURL=client.js.map
@@ -14,13 +14,22 @@ export declare abstract class SamvaApiError<Tag extends SamvaApiErrorTag = Samva
14
14
  }
15
15
  /** A transport or malformed-response failure that is not part of the API error contract. */
16
16
  export declare class SamvaTransportError extends Error {
17
- readonly _tag: "SamvaTransportError";
17
+ readonly _tag: "SamvaTransportError" | "SamvaTimeoutError";
18
18
  readonly request: Request | undefined;
19
19
  readonly response: Response | undefined;
20
20
  readonly status: number | undefined;
21
21
  readonly cause: unknown;
22
22
  constructor(cause: unknown, context?: SamvaApiErrorContext);
23
23
  }
24
+ /**
25
+ * A request attempt that did not finish within its `timeoutMs`. The request may still have
26
+ * reached the API, so a keyed write retries with the same idempotency key.
27
+ */
28
+ export declare class SamvaTimeoutError extends SamvaTransportError {
29
+ readonly _tag: "SamvaTimeoutError";
30
+ readonly timeoutMs: number;
31
+ constructor(timeoutMs: number);
32
+ }
24
33
  type AnalyticsQueryErrorPayload = {
25
34
  readonly _tag: "AnalyticsQueryError";
26
35
  readonly message: string;
@@ -127,11 +136,13 @@ export declare class ForbiddenError extends SamvaApiError<"ForbiddenError"> {
127
136
  }
128
137
  type FromAddressRequiredErrorPayload = {
129
138
  readonly _tag: "FromAddressRequiredError";
139
+ readonly addresses: Array<string>;
130
140
  readonly message: string;
131
141
  readonly verifiedDomains: Array<string>;
132
142
  };
133
143
  export declare class FromAddressRequiredError extends SamvaApiError<"FromAddressRequiredError"> {
134
144
  readonly _tag: "FromAddressRequiredError";
145
+ readonly "addresses": Array<string>;
135
146
  readonly "verifiedDomains": Array<string>;
136
147
  constructor(payload: Omit<FromAddressRequiredErrorPayload, "_tag">, context?: SamvaApiErrorContext);
137
148
  }
@@ -29,6 +29,20 @@ var SamvaTransportError = class extends Error {
29
29
  this.status = context.response?.status;
30
30
  }
31
31
  };
32
+ /**
33
+ * A request attempt that did not finish within its `timeoutMs`. The request may still have
34
+ * reached the API, so a keyed write retries with the same idempotency key.
35
+ */
36
+ var SamvaTimeoutError = class extends SamvaTransportError {
37
+ _tag = "SamvaTimeoutError";
38
+ timeoutMs;
39
+ constructor(timeoutMs) {
40
+ super(void 0);
41
+ this.name = "SamvaTimeoutError";
42
+ this.message = "Samva request did not finish within " + timeoutMs + " ms";
43
+ this.timeoutMs = timeoutMs;
44
+ }
45
+ };
32
46
  const messageOf = (tag, payload) => {
33
47
  const message = payload.message;
34
48
  return typeof message === "string" ? message : tag;
@@ -522,12 +536,17 @@ const payloadSchemas = {
522
536
  verifiedDomains: {
523
537
  type: "array",
524
538
  items: { type: "string" }
539
+ },
540
+ addresses: {
541
+ type: "array",
542
+ items: { type: "string" }
525
543
  }
526
544
  },
527
545
  required: [
528
546
  "_tag",
529
547
  "message",
530
- "verifiedDomains"
548
+ "verifiedDomains",
549
+ "addresses"
531
550
  ],
532
551
  additionalProperties: false,
533
552
  "x-category": ["validation"],
@@ -2072,6 +2091,6 @@ function fromApiError(error, context = {}) {
2072
2091
  }
2073
2092
  return new SamvaTransportError(error, context);
2074
2093
  }
2075
- export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, fromApiError };
2094
+ export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTimeoutError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, fromApiError };
2076
2095
 
2077
2096
  //# sourceMappingURL=errors.gen.js.map
@@ -1,5 +1,5 @@
1
- import { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, fromApiError } from "./errors.gen.js";
1
+ import { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTimeoutError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, fromApiError } from "./errors.gen.js";
2
2
  import { MediaUploadError } from "../inline-attachments.js";
3
3
  import { MailboxEventStream, MailboxEventStreamError } from "../mailbox-events.js";
4
4
  import { createClient } from "./client.js";
5
- export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxEventStream, MailboxEventStreamError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, MediaUploadError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, createClient, fromApiError };
5
+ export { AnalyticsQueryError, BillingProviderError, BrandAddressRequiredError, CampaignFooterRequiredError, ConflictError, CredentialsError, DeliveryUnavailableError, EmailChannelError, ExternalServiceError, FlagDisabledError, ForbiddenError, FromAddressRequiredError, GatewayTimeoutError, InternalError, MailboxEventStream, MailboxEventStreamError, MailboxSendConflictError, MailboxSendRefusedError, MalformedRequestError, MediaUploadError, OnboardingReviewRequiredError, PaymentRequiredError, RateLimitedError, ResourceNotFoundError, SamvaApiError, SamvaTimeoutError, SamvaTransportError, SenderNotReadyError, ServiceUnavailableError, ShareLinkUnavailable, SlugTaken, TemplateInUseError, TemplateSourceError, UnauthorizedError, ValidationError, WhatsAppChannelError, WhatsAppServiceWindowClosedError, WhatsAppSetupLinkUnavailableError, createClient, fromApiError };
@@ -1,15 +1,44 @@
1
1
  import { type Client, mergeHeaders } from "../client/client/index.js";
2
2
  import { SamvaOperations } from "../effect/generated-metadata.js";
3
+ import { type TimeoutSetting } from "../request-policy.js";
4
+ import { SamvaTimeoutError } from "./errors.gen.js";
3
5
  export interface RequestPolicy {
4
6
  readonly maxRetries?: number | undefined;
5
7
  readonly idempotency?: ((operation: string) => string) | undefined;
8
+ /**
9
+ * Milliseconds each request attempt may take before it fails with `SamvaTimeoutError`
10
+ * (default 30 000). `null` disables the bound.
11
+ */
12
+ readonly timeoutMs?: number | null | undefined;
13
+ /**
14
+ * Milliseconds each put of attachment bytes to storage may take (default 300 000). `null`
15
+ * disables the bound.
16
+ */
17
+ readonly uploadTimeoutMs?: number | null | undefined;
6
18
  }
7
19
  export interface CallOptions {
8
20
  readonly idempotencyKey?: string | undefined;
9
21
  readonly maxRetries?: number | undefined;
22
+ /** Overrides the client's `timeoutMs` for this call; `undefined` inherits it. */
23
+ readonly timeoutMs?: number | null | undefined;
10
24
  readonly headers?: Parameters<typeof mergeHeaders>[0];
11
25
  readonly signal?: AbortSignal | null | undefined;
12
26
  }
13
27
  export declare const configureRequests: (client: Client, policy: RequestPolicy) => void;
14
- /** The key belongs to a logical call, so all attempts share it and each invocation gets a fresh one. */
15
- export declare function requestWithPolicy<Result>(client: Client, operation: keyof typeof SamvaOperations, options: CallOptions | undefined, send: (headers: Record<string, string | null | undefined>) => Promise<Result>, input?: unknown): Promise<Result>;
28
+ /** The bound on one storage put: the call's `uploadTimeoutMs`, else the client's, else the default. */
29
+ export declare const uploadTimeout: (client: Client, call: TimeoutSetting) => number | null;
30
+ export interface Attempt {
31
+ /** The caller's signal joined with this attempt's own timer. */
32
+ readonly signal: AbortSignal | undefined;
33
+ /** The timeout, when the attempt's timer (not the caller) ended it. */
34
+ readonly timedOut: () => SamvaTimeoutError | undefined;
35
+ readonly end: () => void;
36
+ }
37
+ /** Each attempt gets a fresh timer, so a retry has the whole bound again. */
38
+ export declare const startAttempt: (signal: AbortSignal | null | undefined, timeoutMs: number | null) => Attempt;
39
+ /**
40
+ * The key belongs to a logical call, so all attempts share it and each invocation gets a fresh one.
41
+ * Each attempt runs under its own `timeoutMs` timer joined with the caller's signal; a timed-out
42
+ * attempt fails with `SamvaTimeoutError` and retries only where a transport failure would.
43
+ */
44
+ export declare function requestWithPolicy<Result>(client: Client, operation: keyof typeof SamvaOperations, options: CallOptions | undefined, send: (headers: Record<string, string | null | undefined>, signal: AbortSignal | undefined) => Promise<Result>, input?: unknown): Promise<Result>;
@@ -1,19 +1,40 @@
1
1
  import { mergeHeaders } from "../client/client/utils.gen.js";
2
2
  import { SamvaErrorMetadata, SamvaOperations } from "../effect/generated-metadata.js";
3
- import { isRetrySafe } from "../request-policy.js";
4
- import { SamvaTransportError, fromApiError } from "./errors.gen.js";
3
+ import { DEFAULT_TIMEOUT_MS, DEFAULT_UPLOAD_TIMEOUT_MS, isRetrySafe, resolveTimeout, validateTimeout } from "../request-policy.js";
4
+ import { SamvaTimeoutError, SamvaTransportError, fromApiError } from "./errors.gen.js";
5
5
  // src/promises/request.ts
6
6
  const policies = /* @__PURE__ */ new WeakMap();
7
7
  const configureRequests = (client, policy) => {
8
8
  if (policy.maxRetries !== void 0) validateRetries(policy.maxRetries);
9
+ validateTimeout("timeoutMs", policy.timeoutMs);
10
+ validateTimeout("uploadTimeoutMs", policy.uploadTimeoutMs);
9
11
  policies.set(client, policy);
10
12
  };
13
+ /** The bound on one storage put: the call's `uploadTimeoutMs`, else the client's, else the default. */
14
+ const uploadTimeout = (client, call) => resolveTimeout("uploadTimeoutMs", call, policies.get(client)?.uploadTimeoutMs, DEFAULT_UPLOAD_TIMEOUT_MS);
15
+ /** Each attempt gets a fresh timer, so a retry has the whole bound again. */
16
+ const startAttempt = (signal, timeoutMs) => {
17
+ if (timeoutMs === null) return {
18
+ signal: signal ?? void 0,
19
+ timedOut: () => void 0,
20
+ end: () => {}
21
+ };
22
+ const timer = new AbortController();
23
+ const handle = setTimeout(() => timer.abort(new SamvaTimeoutError(timeoutMs)), timeoutMs);
24
+ const joined = signal ? AbortSignal.any([signal, timer.signal]) : timer.signal;
25
+ return {
26
+ signal: joined,
27
+ timedOut: () => joined.reason instanceof SamvaTimeoutError ? joined.reason : void 0,
28
+ end: () => clearTimeout(handle)
29
+ };
30
+ };
11
31
  const validateRetries = (value) => {
12
32
  if (!Number.isInteger(value) || value < 0) throw new RangeError("maxRetries must be a nonnegative integer");
13
33
  return value;
14
34
  };
15
35
  const object = (value) => typeof value === "object" && value !== null;
16
36
  const retryable = (error) => {
37
+ if (error instanceof SamvaTimeoutError) return true;
17
38
  if (error instanceof SamvaTransportError) return error.response === void 0 && error.cause instanceof TypeError;
18
39
  if (!object(error) || typeof error._tag !== "string") return false;
19
40
  if (error._tag === "EmailChannelError") return error.reason === "transport" || error.reason === "rate_limited";
@@ -35,7 +56,11 @@ const pause = (milliseconds, signal) => new Promise((resolve, reject) => {
35
56
  }, milliseconds);
36
57
  signal?.addEventListener("abort", abort, { once: true });
37
58
  });
38
- /** The key belongs to a logical call, so all attempts share it and each invocation gets a fresh one. */
59
+ /**
60
+ * The key belongs to a logical call, so all attempts share it and each invocation gets a fresh one.
61
+ * Each attempt runs under its own `timeoutMs` timer joined with the caller's signal; a timed-out
62
+ * attempt fails with `SamvaTimeoutError` and retries only where a transport failure would.
63
+ */
39
64
  async function requestWithPolicy(client, operation, options, send, input) {
40
65
  const metadata = SamvaOperations[operation];
41
66
  const policy = policies.get(client);
@@ -49,27 +74,37 @@ async function requestWithPolicy(client, operation, options, send, input) {
49
74
  headers["idempotency-key"] = options?.idempotencyKey ?? policy?.idempotency?.(operation) ?? crypto.randomUUID();
50
75
  }
51
76
  const maxRetries = validateRetries(options?.maxRetries ?? policy?.maxRetries ?? 3);
77
+ const timeoutMs = resolveTimeout("timeoutMs", options?.timeoutMs, policy?.timeoutMs, DEFAULT_TIMEOUT_MS);
52
78
  const safe = isRetrySafe(metadata, input);
53
79
  for (let retry = 0;; retry++) {
54
80
  let failure;
55
81
  let result;
82
+ const attempt = startAttempt(signal, timeoutMs);
56
83
  try {
57
- result = await send(headers);
84
+ result = await send(headers, attempt.signal);
58
85
  if (!object(result) || result.error === void 0) return result;
59
- failure = fromApiError(result.error, {
86
+ const timeout = attempt.timedOut();
87
+ failure = fromApiError(timeout ?? result.error, {
60
88
  request: result.request instanceof Request ? result.request : void 0,
61
89
  response: result.response instanceof Response ? result.response : void 0
62
90
  });
63
- } catch (error) {
91
+ if (timeout !== void 0) result = {
92
+ ...result,
93
+ error: timeout
94
+ };
95
+ } catch (thrown) {
96
+ const error = attempt.timedOut() ?? thrown;
64
97
  failure = fromApiError(error);
65
98
  if (!safe || retry >= maxRetries || !retryable(failure) || signal?.aborted) throw error;
66
99
  await pause(delay(failure, retry), signal);
67
100
  continue;
101
+ } finally {
102
+ attempt.end();
68
103
  }
69
104
  if (!safe || retry >= maxRetries || !retryable(failure) || signal?.aborted) return result;
70
105
  await pause(delay(failure, retry), signal);
71
106
  }
72
107
  }
73
- export { configureRequests, requestWithPolicy };
108
+ export { configureRequests, requestWithPolicy, startAttempt, uploadTimeout };
74
109
 
75
110
  //# sourceMappingURL=request.js.map
@@ -9,3 +9,12 @@ export interface RetryPolicyMetadata {
9
9
  }
10
10
  /** Some endpoints admit both replayable requests and generation-fenced mutations. */
11
11
  export declare const isRetrySafe: (metadata: RetryPolicyMetadata, input: unknown) => boolean;
12
+ /** The per-attempt bound on an API request when neither the client nor the call sets one. */
13
+ export declare const DEFAULT_TIMEOUT_MS = 30000;
14
+ /** The per-attempt bound on putting attachment bytes to storage, which carries the large bodies. */
15
+ export declare const DEFAULT_UPLOAD_TIMEOUT_MS = 300000;
16
+ /** A timeout setting: milliseconds, `null` for no bound, `undefined` to inherit. */
17
+ export type TimeoutSetting = number | null | undefined;
18
+ export declare const validateTimeout: (name: string, value: TimeoutSetting) => TimeoutSetting;
19
+ /** The call's setting wins over the client's; `null` at either level disables the bound. */
20
+ export declare const resolveTimeout: (name: string, call: TimeoutSetting, client: TimeoutSetting, fallback: number) => number | null;
@@ -9,6 +9,21 @@ const isRetrySafe = (metadata, input) => {
9
9
  if (typeof input !== "object" || input === null) return false;
10
10
  return input[condition.field] === condition.equals;
11
11
  };
12
- export { isRetrySafe };
12
+ /** The per-attempt bound on an API request when neither the client nor the call sets one. */
13
+ const DEFAULT_TIMEOUT_MS = 3e4;
14
+ /** The per-attempt bound on putting attachment bytes to storage, which carries the large bodies. */
15
+ const DEFAULT_UPLOAD_TIMEOUT_MS = 3e5;
16
+ const MAX_TIMER_MS = 2147483647;
17
+ const validateTimeout = (name, value) => {
18
+ if (value === null || value === void 0) return value;
19
+ if (!Number.isFinite(value) || value <= 0 || value > MAX_TIMER_MS) throw new RangeError(`${name} must be a positive number of milliseconds up to ${MAX_TIMER_MS}, or null`);
20
+ return value;
21
+ };
22
+ /** The call's setting wins over the client's; `null` at either level disables the bound. */
23
+ const resolveTimeout = (name, call, client, fallback) => {
24
+ const value = validateTimeout(name, call !== void 0 ? call : client);
25
+ return value === void 0 ? fallback : value;
26
+ };
27
+ export { DEFAULT_TIMEOUT_MS, DEFAULT_UPLOAD_TIMEOUT_MS, isRetrySafe, resolveTimeout, validateTimeout };
13
28
 
14
29
  //# sourceMappingURL=request-policy.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "samva",
3
- "version": "0.50.0",
3
+ "version": "0.51.0",
4
4
  "description": "TypeScript SDK for the Samva email and WhatsApp API",
5
5
  "keywords": [
6
6
  "api-client",
@@ -261,7 +261,7 @@
261
261
  "typecheck": "slot 'effect-tsgo tsrs --noEmit && effect-tsgo tsrs --noEmit -p codegen/tsconfig.json && effect-tsgo tsrs --noEmit -p tests/tsconfig.json && effect-tsgo tsrs --noEmit --project tests/parity/tsconfig.json \"$@\"'"
262
262
  },
263
263
  "dependencies": {
264
- "@samva/webhooks": "0.50.0"
264
+ "@samva/webhooks": "0.51.0"
265
265
  },
266
266
  "devDependencies": {
267
267
  "@effect/openapi-generator": "^4.1.4",