@keystrokehq/sendgrid 0.0.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.
Files changed (63) hide show
  1. package/README.md +225 -0
  2. package/dist/_official/index.d.mts +2 -0
  3. package/dist/_official/index.mjs +3 -0
  4. package/dist/_runtime/index.d.mts +2 -0
  5. package/dist/_runtime/index.mjs +3 -0
  6. package/dist/alerts.d.mts +193 -0
  7. package/dist/alerts.mjs +101 -0
  8. package/dist/api-keys.d.mts +160 -0
  9. package/dist/api-keys.mjs +113 -0
  10. package/dist/client.d.mts +73 -0
  11. package/dist/client.mjs +261 -0
  12. package/dist/connection.d.mts +2 -0
  13. package/dist/connection.mjs +3 -0
  14. package/dist/domains.d.mts +114 -0
  15. package/dist/domains.mjs +62 -0
  16. package/dist/email-validation.d.mts +134 -0
  17. package/dist/email-validation.mjs +73 -0
  18. package/dist/events.d.mts +69 -0
  19. package/dist/events.mjs +28 -0
  20. package/dist/factory-BSL0D2L0.mjs +25 -0
  21. package/dist/index.d.mts +1 -0
  22. package/dist/index.mjs +1 -0
  23. package/dist/integration-37BovSeK.mjs +23 -0
  24. package/dist/integration-CmJ2TILG.d.mts +57 -0
  25. package/dist/mail-send.d.mts +315 -0
  26. package/dist/mail-send.mjs +218 -0
  27. package/dist/marketing-contacts.d.mts +607 -0
  28. package/dist/marketing-contacts.mjs +277 -0
  29. package/dist/marketing-customfields.d.mts +94 -0
  30. package/dist/marketing-customfields.mjs +70 -0
  31. package/dist/marketing-lists.d.mts +184 -0
  32. package/dist/marketing-lists.mjs +130 -0
  33. package/dist/marketing-segments.d.mts +340 -0
  34. package/dist/marketing-segments.mjs +179 -0
  35. package/dist/marketing-singlesends.d.mts +648 -0
  36. package/dist/marketing-singlesends.mjs +277 -0
  37. package/dist/operations.d.mts +25 -0
  38. package/dist/operations.mjs +69 -0
  39. package/dist/schemas/index.d.mts +1395 -0
  40. package/dist/schemas/index.mjs +3 -0
  41. package/dist/sender-identities.d.mts +218 -0
  42. package/dist/sender-identities.mjs +109 -0
  43. package/dist/senders.d.mts +227 -0
  44. package/dist/senders.mjs +83 -0
  45. package/dist/shared-CQ8JFNXi.mjs +13 -0
  46. package/dist/stats.d.mts +215 -0
  47. package/dist/stats.mjs +107 -0
  48. package/dist/suppressions.d.mts +785 -0
  49. package/dist/suppressions.mjs +539 -0
  50. package/dist/templates.d.mts +451 -0
  51. package/dist/templates.mjs +238 -0
  52. package/dist/triggers.d.mts +35 -0
  53. package/dist/triggers.mjs +98 -0
  54. package/dist/user-account.d.mts +108 -0
  55. package/dist/user-account.mjs +59 -0
  56. package/dist/verification.d.mts +67 -0
  57. package/dist/verification.mjs +72 -0
  58. package/dist/webhooks/event.d.mts +287 -0
  59. package/dist/webhooks/event.mjs +147 -0
  60. package/dist/webhooks/parse.d.mts +172 -0
  61. package/dist/webhooks/parse.mjs +125 -0
  62. package/dist/webhooks-CKdsIikb.mjs +735 -0
  63. package/package.json +162 -0
@@ -0,0 +1,160 @@
1
+ import { z } from "zod";
2
+ import * as _keystrokehq_core_credential_set0 from "@keystrokehq/core/credential-set";
3
+ import * as _keystrokehq_core0 from "@keystrokehq/core";
4
+
5
+ //#region src/api-keys.d.ts
6
+ declare const createApiKey: _keystrokehq_core0.Operation<z.ZodObject<{
7
+ name: z.ZodString;
8
+ scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
9
+ }, z.core.$strip>, z.ZodObject<{
10
+ api_key_id: z.ZodString;
11
+ name: z.ZodString;
12
+ scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
13
+ api_key: z.ZodOptional<z.ZodString>;
14
+ }, z.core.$catchall<z.ZodUnknown>>, readonly [_keystrokehq_core0.CredentialSet<"sendgrid", z.ZodObject<{
15
+ SENDGRID_API_KEY: z.ZodString;
16
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
17
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
18
+ global: "global";
19
+ eu: "eu";
20
+ }>>;
21
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
22
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
23
+ }, z.core.$strip>, readonly _keystrokehq_core_credential_set0.CredentialConnection<z.ZodObject<{
24
+ SENDGRID_API_KEY: z.ZodString;
25
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
26
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
27
+ global: "global";
28
+ eu: "eu";
29
+ }>>;
30
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
31
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
32
+ }, z.core.$strip>>[] | undefined>], undefined>;
33
+ declare const listApiKeys: _keystrokehq_core0.Operation<z.ZodOptional<z.ZodObject<{}, z.core.$strip>>, z.ZodObject<{
34
+ result: z.ZodArray<z.ZodObject<{
35
+ api_key_id: z.ZodString;
36
+ name: z.ZodString;
37
+ scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
38
+ }, z.core.$catchall<z.ZodUnknown>>>;
39
+ }, z.core.$strip>, readonly [_keystrokehq_core0.CredentialSet<"sendgrid", z.ZodObject<{
40
+ SENDGRID_API_KEY: z.ZodString;
41
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
42
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
43
+ global: "global";
44
+ eu: "eu";
45
+ }>>;
46
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
47
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
48
+ }, z.core.$strip>, readonly _keystrokehq_core_credential_set0.CredentialConnection<z.ZodObject<{
49
+ SENDGRID_API_KEY: z.ZodString;
50
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
51
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
52
+ global: "global";
53
+ eu: "eu";
54
+ }>>;
55
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
56
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
57
+ }, z.core.$strip>>[] | undefined>], undefined>;
58
+ declare const getApiKey: _keystrokehq_core0.Operation<z.ZodObject<{
59
+ apiKeyId: z.ZodString;
60
+ }, z.core.$strip>, z.ZodObject<{
61
+ api_key_id: z.ZodString;
62
+ name: z.ZodString;
63
+ scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
64
+ }, z.core.$catchall<z.ZodUnknown>>, readonly [_keystrokehq_core0.CredentialSet<"sendgrid", z.ZodObject<{
65
+ SENDGRID_API_KEY: z.ZodString;
66
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
67
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
68
+ global: "global";
69
+ eu: "eu";
70
+ }>>;
71
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
72
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
73
+ }, z.core.$strip>, readonly _keystrokehq_core_credential_set0.CredentialConnection<z.ZodObject<{
74
+ SENDGRID_API_KEY: z.ZodString;
75
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
76
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
77
+ global: "global";
78
+ eu: "eu";
79
+ }>>;
80
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
81
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
82
+ }, z.core.$strip>>[] | undefined>], undefined>;
83
+ declare const updateApiKeyName: _keystrokehq_core0.Operation<z.ZodObject<{
84
+ apiKeyId: z.ZodString;
85
+ name: z.ZodString;
86
+ }, z.core.$strip>, z.ZodObject<{
87
+ api_key_id: z.ZodString;
88
+ name: z.ZodString;
89
+ scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
90
+ }, z.core.$catchall<z.ZodUnknown>>, readonly [_keystrokehq_core0.CredentialSet<"sendgrid", z.ZodObject<{
91
+ SENDGRID_API_KEY: z.ZodString;
92
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
93
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
94
+ global: "global";
95
+ eu: "eu";
96
+ }>>;
97
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
98
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
99
+ }, z.core.$strip>, readonly _keystrokehq_core_credential_set0.CredentialConnection<z.ZodObject<{
100
+ SENDGRID_API_KEY: z.ZodString;
101
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
102
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
103
+ global: "global";
104
+ eu: "eu";
105
+ }>>;
106
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
107
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
108
+ }, z.core.$strip>>[] | undefined>], undefined>;
109
+ declare const updateApiKeyNameAndScopes: _keystrokehq_core0.Operation<z.ZodObject<{
110
+ apiKeyId: z.ZodString;
111
+ name: z.ZodString;
112
+ scopes: z.ZodArray<z.ZodString>;
113
+ }, z.core.$strip>, z.ZodObject<{
114
+ api_key_id: z.ZodString;
115
+ name: z.ZodString;
116
+ scopes: z.ZodOptional<z.ZodArray<z.ZodString>>;
117
+ }, z.core.$catchall<z.ZodUnknown>>, readonly [_keystrokehq_core0.CredentialSet<"sendgrid", z.ZodObject<{
118
+ SENDGRID_API_KEY: z.ZodString;
119
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
120
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
121
+ global: "global";
122
+ eu: "eu";
123
+ }>>;
124
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
125
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
126
+ }, z.core.$strip>, readonly _keystrokehq_core_credential_set0.CredentialConnection<z.ZodObject<{
127
+ SENDGRID_API_KEY: z.ZodString;
128
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
129
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
130
+ global: "global";
131
+ eu: "eu";
132
+ }>>;
133
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
134
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
135
+ }, z.core.$strip>>[] | undefined>], undefined>;
136
+ declare const deleteApiKey: _keystrokehq_core0.Operation<z.ZodObject<{
137
+ apiKeyId: z.ZodString;
138
+ }, z.core.$strip>, z.ZodObject<{
139
+ success: z.ZodBoolean;
140
+ }, z.core.$strip>, readonly [_keystrokehq_core0.CredentialSet<"sendgrid", z.ZodObject<{
141
+ SENDGRID_API_KEY: z.ZodString;
142
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
143
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
144
+ global: "global";
145
+ eu: "eu";
146
+ }>>;
147
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
148
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
149
+ }, z.core.$strip>, readonly _keystrokehq_core_credential_set0.CredentialConnection<z.ZodObject<{
150
+ SENDGRID_API_KEY: z.ZodString;
151
+ SENDGRID_SUBUSER: z.ZodOptional<z.ZodString>;
152
+ SENDGRID_ACCOUNT_REGION: z.ZodDefault<z.ZodEnum<{
153
+ global: "global";
154
+ eu: "eu";
155
+ }>>;
156
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY: z.ZodOptional<z.ZodString>;
157
+ SENDGRID_INBOUND_PARSE_TOKEN: z.ZodOptional<z.ZodString>;
158
+ }, z.core.$strip>>[] | undefined>], undefined>;
159
+ //#endregion
160
+ export { createApiKey, deleteApiKey, getApiKey, listApiKeys, updateApiKeyName, updateApiKeyNameAndScopes };
@@ -0,0 +1,113 @@
1
+ import { n as __exportAll, t as sendgridOperation } from "./factory-BSL0D2L0.mjs";
2
+ import { n as omitUndefined } from "./shared-CQ8JFNXi.mjs";
3
+ import { createSendGridClient } from "./client.mjs";
4
+ import { Qt as sendgridApiKeyWithKeySchema, Xt as sendgridApiKeySchema, Yt as sendgridApiKeyListSchema, on as sendgridIdSchema } from "./webhooks-CKdsIikb.mjs";
5
+ import { z } from "zod";
6
+
7
+ //#region src/api-keys.ts
8
+ var api_keys_exports = /* @__PURE__ */ __exportAll({
9
+ createApiKey: () => createApiKey,
10
+ deleteApiKey: () => deleteApiKey,
11
+ getApiKey: () => getApiKey,
12
+ listApiKeys: () => listApiKeys,
13
+ updateApiKeyName: () => updateApiKeyName,
14
+ updateApiKeyNameAndScopes: () => updateApiKeyNameAndScopes
15
+ });
16
+ const createApiKey = sendgridOperation({
17
+ id: "create_api_key",
18
+ name: "Create API Key",
19
+ description: "Create a new SendGrid API key. Returns the full key value only at creation time — store it safely.",
20
+ input: z.object({
21
+ name: z.string().min(1),
22
+ scopes: z.array(z.string()).optional()
23
+ }),
24
+ output: sendgridApiKeyWithKeySchema,
25
+ needsApproval: true,
26
+ run: async (input, credentials) => {
27
+ const response = await createSendGridClient(credentials).request("/api_keys", {
28
+ method: "POST",
29
+ body: omitUndefined({
30
+ name: input.name,
31
+ scopes: input.scopes
32
+ })
33
+ });
34
+ return sendgridApiKeyWithKeySchema.parse(response);
35
+ }
36
+ });
37
+ const listApiKeys = sendgridOperation({
38
+ id: "list_api_keys",
39
+ name: "List API Keys",
40
+ description: "List all API keys on the account (values are not returned).",
41
+ input: z.object({}).optional(),
42
+ output: sendgridApiKeyListSchema,
43
+ run: async (_input, credentials) => {
44
+ const response = await createSendGridClient(credentials).request("/api_keys");
45
+ return sendgridApiKeyListSchema.parse(response ?? { result: [] });
46
+ }
47
+ });
48
+ const getApiKey = sendgridOperation({
49
+ id: "get_api_key",
50
+ name: "Get API Key",
51
+ description: "Retrieve an API key record by ID (the secret value is never returned).",
52
+ input: z.object({ apiKeyId: sendgridIdSchema }),
53
+ output: sendgridApiKeySchema,
54
+ run: async (input, credentials) => {
55
+ const response = await createSendGridClient(credentials).request(`/api_keys/${encodeURIComponent(input.apiKeyId)}`);
56
+ return sendgridApiKeySchema.parse(response);
57
+ }
58
+ });
59
+ const updateApiKeyName = sendgridOperation({
60
+ id: "update_api_key_name",
61
+ name: "Update API Key Name",
62
+ description: "Rename an API key without changing its scopes.",
63
+ input: z.object({
64
+ apiKeyId: sendgridIdSchema,
65
+ name: z.string().min(1)
66
+ }),
67
+ output: sendgridApiKeySchema,
68
+ needsApproval: true,
69
+ run: async (input, credentials) => {
70
+ const response = await createSendGridClient(credentials).request(`/api_keys/${encodeURIComponent(input.apiKeyId)}`, {
71
+ method: "PATCH",
72
+ body: { name: input.name }
73
+ });
74
+ return sendgridApiKeySchema.parse(response);
75
+ }
76
+ });
77
+ const updateApiKeyNameAndScopes = sendgridOperation({
78
+ id: "update_api_key_name_and_scopes",
79
+ name: "Update API Key Name and Scopes",
80
+ description: "Update an API key by replacing the full set of scopes.",
81
+ input: z.object({
82
+ apiKeyId: sendgridIdSchema,
83
+ name: z.string().min(1),
84
+ scopes: z.array(z.string()).min(1)
85
+ }),
86
+ output: sendgridApiKeySchema,
87
+ needsApproval: true,
88
+ run: async (input, credentials) => {
89
+ const response = await createSendGridClient(credentials).request(`/api_keys/${encodeURIComponent(input.apiKeyId)}`, {
90
+ method: "PUT",
91
+ body: {
92
+ name: input.name,
93
+ scopes: input.scopes
94
+ }
95
+ });
96
+ return sendgridApiKeySchema.parse(response);
97
+ }
98
+ });
99
+ const deleteApiKey = sendgridOperation({
100
+ id: "delete_api_key",
101
+ name: "Delete API Key",
102
+ description: "Delete (revoke) an API key.",
103
+ input: z.object({ apiKeyId: sendgridIdSchema }),
104
+ output: z.object({ success: z.boolean() }),
105
+ needsApproval: true,
106
+ run: async (input, credentials) => {
107
+ await createSendGridClient(credentials).request(`/api_keys/${encodeURIComponent(input.apiKeyId)}`, { method: "DELETE" });
108
+ return { success: true };
109
+ }
110
+ });
111
+
112
+ //#endregion
113
+ export { createApiKey, deleteApiKey, getApiKey, listApiKeys, api_keys_exports as t, updateApiKeyName, updateApiKeyNameAndScopes };
@@ -0,0 +1,73 @@
1
+ import { t as SendGridCredentials } from "./integration-CmJ2TILG.mjs";
2
+
3
+ //#region src/client.d.ts
4
+ type Primitive = string | number | boolean;
5
+ type QueryValue = Primitive | readonly Primitive[] | undefined | null;
6
+ type SendGridHttpMethod = 'DELETE' | 'GET' | 'PATCH' | 'POST' | 'PUT';
7
+ interface SendGridRequestOptions {
8
+ readonly body?: unknown;
9
+ readonly method?: SendGridHttpMethod;
10
+ readonly query?: Record<string, QueryValue>;
11
+ /** Override `on-behalf-of` for a single request (rare; defaults to credential subuser). */
12
+ readonly onBehalfOf?: string;
13
+ /** Send as `application/x-www-form-urlencoded` instead of JSON. */
14
+ readonly form?: Record<string, Primitive>;
15
+ /** Raw text body (e.g. CSV upload via PUT presigned URL responses). */
16
+ readonly rawBody?: string;
17
+ /** Disable retry for this call (e.g. idempotent-write guards). */
18
+ readonly noRetry?: boolean;
19
+ }
20
+ type SendGridErrorKind = 'auth' | 'forbidden' | 'not_found' | 'rate_limit' | 'server' | 'validation' | 'network';
21
+ interface SendGridProviderError {
22
+ readonly message: string;
23
+ readonly field?: string;
24
+ readonly errorId?: string;
25
+ readonly help?: string;
26
+ }
27
+ declare class SendGridError extends Error {
28
+ readonly kind: SendGridErrorKind;
29
+ readonly status: number;
30
+ readonly body: unknown;
31
+ readonly providerErrors: readonly SendGridProviderError[];
32
+ readonly requestId: string | undefined;
33
+ readonly retryable: boolean;
34
+ constructor(init: {
35
+ kind: SendGridErrorKind;
36
+ status: number;
37
+ body: unknown;
38
+ providerErrors: readonly SendGridProviderError[];
39
+ requestId?: string;
40
+ retryable: boolean;
41
+ message: string;
42
+ });
43
+ }
44
+ declare function isSendGridError(value: unknown): value is SendGridError;
45
+ interface SendGridClientConfig {
46
+ readonly maxRetries?: number;
47
+ readonly fetchImpl?: typeof fetch;
48
+ }
49
+ declare function createSendGridClient(credentials: SendGridCredentials, config?: SendGridClientConfig): {
50
+ request: <T>(path: string, options?: SendGridRequestOptions) => Promise<T>;
51
+ credentials: {
52
+ SENDGRID_API_KEY: string;
53
+ SENDGRID_ACCOUNT_REGION: "global" | "eu";
54
+ SENDGRID_SUBUSER?: string | undefined;
55
+ SENDGRID_EVENT_WEBHOOK_PUBLIC_KEY?: string | undefined;
56
+ SENDGRID_INBOUND_PARSE_TOKEN?: string | undefined;
57
+ };
58
+ baseUrl: string;
59
+ };
60
+ type SendGridClient = ReturnType<typeof createSendGridClient>;
61
+ /**
62
+ * Iterate a paginated SendGrid endpoint, yielding individual items.
63
+ *
64
+ * Implemented as a standalone function rather than a client method because
65
+ * the client is wrapped in an error-normalizing `Proxy` which does not play
66
+ * well with async iterators returned from method calls.
67
+ */
68
+ declare function paginateSendGrid<TItem>(client: SendGridClient, path: string, options?: {
69
+ readonly query?: Record<string, QueryValue>;
70
+ readonly itemsKey?: string;
71
+ }): AsyncIterableIterator<TItem>;
72
+ //#endregion
73
+ export { SendGridClient, SendGridClientConfig, SendGridError, SendGridErrorKind, SendGridHttpMethod, SendGridProviderError, SendGridRequestOptions, createSendGridClient, isSendGridError, paginateSendGrid };
@@ -0,0 +1,261 @@
1
+ import { t as sendgrid } from "./integration-37BovSeK.mjs";
2
+ import { r as stringIfPresent, t as asRecord } from "./shared-CQ8JFNXi.mjs";
3
+ import { CredentialRevokedError } from "@keystrokehq/core/errors";
4
+ import { createErrorNormalizingProxy } from "@keystrokehq/integration-authoring";
5
+
6
+ //#region src/client.ts
7
+ const SENDGRID_GLOBAL_BASE = "https://api.sendgrid.com/v3";
8
+ const SENDGRID_EU_BASE = "https://api.eu.sendgrid.com/v3";
9
+ const CONNECT_HINT = "If you haven't connected SendGrid yet, create an API key in the SendGrid console and save it as `SENDGRID_API_KEY`.";
10
+ var SendGridError = class extends Error {
11
+ kind;
12
+ status;
13
+ body;
14
+ providerErrors;
15
+ requestId;
16
+ retryable;
17
+ constructor(init) {
18
+ super(init.message);
19
+ this.name = "SendGridError";
20
+ this.kind = init.kind;
21
+ this.status = init.status;
22
+ this.body = init.body;
23
+ this.providerErrors = init.providerErrors;
24
+ this.requestId = init.requestId;
25
+ this.retryable = init.retryable;
26
+ }
27
+ };
28
+ function isSendGridError(value) {
29
+ return value instanceof SendGridError;
30
+ }
31
+ function parseProviderErrors(body) {
32
+ const errors = asRecord(body).errors;
33
+ if (!Array.isArray(errors)) return [];
34
+ return errors.map((entry) => {
35
+ const rec = asRecord(entry);
36
+ const message = stringIfPresent(rec.message);
37
+ if (!message) return null;
38
+ const field = stringIfPresent(rec.field);
39
+ const errorId = stringIfPresent(rec.error_id);
40
+ const help = stringIfPresent(rec.help);
41
+ return {
42
+ message,
43
+ ...field !== void 0 ? { field } : {},
44
+ ...errorId !== void 0 ? { errorId } : {},
45
+ ...help !== void 0 ? { help } : {}
46
+ };
47
+ }).filter((entry) => entry !== null);
48
+ }
49
+ function classifyStatus(status) {
50
+ if (status === 401) return {
51
+ kind: "auth",
52
+ retryable: false
53
+ };
54
+ if (status === 403) return {
55
+ kind: "forbidden",
56
+ retryable: false
57
+ };
58
+ if (status === 404) return {
59
+ kind: "not_found",
60
+ retryable: false
61
+ };
62
+ if (status === 429) return {
63
+ kind: "rate_limit",
64
+ retryable: true
65
+ };
66
+ if (status >= 500) return {
67
+ kind: "server",
68
+ retryable: true
69
+ };
70
+ if (status >= 400) return {
71
+ kind: "validation",
72
+ retryable: false
73
+ };
74
+ return {
75
+ kind: "server",
76
+ retryable: true
77
+ };
78
+ }
79
+ function joinErrorMessages(status, providerErrors) {
80
+ if (providerErrors.length === 0) return `HTTP ${status}`;
81
+ return providerErrors.map((entry) => entry.message).join("; ");
82
+ }
83
+ function isAuthFlavoredError(error) {
84
+ if (!isSendGridError(error)) return false;
85
+ if (error.kind === "auth") return true;
86
+ if (error.kind === "forbidden") return error.providerErrors.map((entry) => entry.message.toLowerCase()).some((msg) => msg.includes("invalid api key") || msg.includes("authorization") || msg.includes("authentication"));
87
+ return false;
88
+ }
89
+ function normalizeSendGridError(error, context) {
90
+ if (isAuthFlavoredError(error)) return new CredentialRevokedError(sendgrid.id, `SendGrid authentication failed while calling \`${context.methodPath}\`. The stored credentials for ${sendgrid.id} may be revoked or missing required scopes. ${CONNECT_HINT}`);
91
+ if (isSendGridError(error)) return new Error(`SendGrid API call failed while calling \`${context.methodPath}\` (${error.status} ${error.kind}): ${error.message}`, { cause: error });
92
+ if (error instanceof Error) return new Error(`SendGrid API call failed while calling \`${context.methodPath}\`: ${error.message}`, { cause: error });
93
+ return /* @__PURE__ */ new Error(`SendGrid API call failed while calling \`${context.methodPath}\`.`);
94
+ }
95
+ function resolveBaseUrl(region) {
96
+ return region === "eu" ? SENDGRID_EU_BASE : SENDGRID_GLOBAL_BASE;
97
+ }
98
+ function appendQuery(searchParams, query) {
99
+ if (!query) return;
100
+ for (const [key, value] of Object.entries(query)) {
101
+ if (value === void 0 || value === null) continue;
102
+ if (Array.isArray(value)) {
103
+ if (value.length === 0) continue;
104
+ searchParams.set(key, value.map(String).join(","));
105
+ continue;
106
+ }
107
+ searchParams.set(key, String(value));
108
+ }
109
+ }
110
+ function parseRetryAfterMs(header) {
111
+ if (!header) return void 0;
112
+ const seconds = Number(header);
113
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds * 1e3);
114
+ const whenMs = Date.parse(header);
115
+ if (Number.isFinite(whenMs)) return Math.max(0, whenMs - Date.now());
116
+ }
117
+ async function sleep(ms) {
118
+ await new Promise((resolve) => {
119
+ setTimeout(resolve, ms);
120
+ });
121
+ }
122
+ function computeBackoffMs(attempt, retryAfterMs) {
123
+ if (retryAfterMs !== void 0) return retryAfterMs;
124
+ return 500 * 2 ** Math.min(attempt, 5) + Math.random() * 250;
125
+ }
126
+ async function parseResponseBody(response) {
127
+ if (response.status === 204 || response.status === 205) return {
128
+ body: void 0,
129
+ text: ""
130
+ };
131
+ const contentType = response.headers.get("content-type") ?? "";
132
+ const text = await response.text();
133
+ if (text.length === 0) return {
134
+ body: void 0,
135
+ text
136
+ };
137
+ if (contentType.includes("application/json")) try {
138
+ return {
139
+ body: JSON.parse(text),
140
+ text
141
+ };
142
+ } catch {
143
+ return {
144
+ body: text,
145
+ text
146
+ };
147
+ }
148
+ return {
149
+ body: text,
150
+ text
151
+ };
152
+ }
153
+ function createSendGridApiClient(credentials, config) {
154
+ const apiKey = credentials.SENDGRID_API_KEY.trim();
155
+ if (apiKey.length === 0) throw new Error(`SendGrid authentication failed at client initialization. ${CONNECT_HINT}`);
156
+ const baseUrl = resolveBaseUrl(credentials.SENDGRID_ACCOUNT_REGION ?? "global");
157
+ const defaultSubuser = credentials.SENDGRID_SUBUSER;
158
+ const maxRetries = config?.maxRetries ?? 3;
159
+ const fetchImpl = config?.fetchImpl ?? fetch;
160
+ async function request(path, options = {}) {
161
+ const url = new URL(`${baseUrl}${path}`);
162
+ appendQuery(url.searchParams, options.query);
163
+ const headers = {
164
+ Authorization: `Bearer ${apiKey}`,
165
+ Accept: "application/json"
166
+ };
167
+ const subuser = options.onBehalfOf ?? defaultSubuser;
168
+ if (subuser !== void 0 && subuser.length > 0) headers["on-behalf-of"] = subuser;
169
+ let body;
170
+ if (options.rawBody !== void 0) body = options.rawBody;
171
+ else if (options.form !== void 0) {
172
+ const params = new URLSearchParams();
173
+ for (const [key, value] of Object.entries(options.form)) params.set(key, String(value));
174
+ body = params.toString();
175
+ headers["Content-Type"] = "application/x-www-form-urlencoded";
176
+ } else if (options.body !== void 0) {
177
+ body = JSON.stringify(options.body);
178
+ headers["Content-Type"] = "application/json";
179
+ }
180
+ const method = options.method ?? "GET";
181
+ const maxAttempts = options.noRetry ? 1 : Math.max(1, maxRetries + 1);
182
+ let lastError;
183
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
184
+ let response;
185
+ try {
186
+ response = await fetchImpl(url, {
187
+ method,
188
+ headers,
189
+ ...body !== void 0 ? { body } : {}
190
+ });
191
+ } catch (cause) {
192
+ const networkError = new SendGridError({
193
+ kind: "network",
194
+ status: 0,
195
+ body: void 0,
196
+ providerErrors: [],
197
+ retryable: true,
198
+ message: cause instanceof Error ? cause.message : "Network error calling SendGrid"
199
+ });
200
+ lastError = networkError;
201
+ if (attempt + 1 >= maxAttempts) throw networkError;
202
+ await sleep(computeBackoffMs(attempt));
203
+ continue;
204
+ }
205
+ if (response.ok) return (await parseResponseBody(response)).body;
206
+ const parsed = await parseResponseBody(response);
207
+ const providerErrors = parseProviderErrors(parsed.body);
208
+ const { kind, retryable } = classifyStatus(response.status);
209
+ const requestId = response.headers.get("x-message-id") ?? response.headers.get("x-request-id") ?? void 0;
210
+ const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
211
+ const err = new SendGridError({
212
+ kind,
213
+ status: response.status,
214
+ body: parsed.body,
215
+ providerErrors,
216
+ ...requestId !== void 0 ? { requestId } : {},
217
+ retryable,
218
+ message: joinErrorMessages(response.status, providerErrors)
219
+ });
220
+ if (!retryable || attempt + 1 >= maxAttempts) throw err;
221
+ lastError = err;
222
+ await sleep(computeBackoffMs(attempt, retryAfterMs));
223
+ }
224
+ throw lastError ?? /* @__PURE__ */ new Error("SendGrid request exhausted retries without a response.");
225
+ }
226
+ return {
227
+ request,
228
+ credentials,
229
+ baseUrl
230
+ };
231
+ }
232
+ function createSendGridClient(credentials, config) {
233
+ return createErrorNormalizingProxy(createSendGridApiClient(credentials, config), normalizeSendGridError);
234
+ }
235
+ /**
236
+ * Iterate a paginated SendGrid endpoint, yielding individual items.
237
+ *
238
+ * Implemented as a standalone function rather than a client method because
239
+ * the client is wrapped in an error-normalizing `Proxy` which does not play
240
+ * well with async iterators returned from method calls.
241
+ */
242
+ async function* paginateSendGrid(client, path, options = {}) {
243
+ const itemsKey = options.itemsKey ?? "result";
244
+ let nextPath = path;
245
+ let nextQuery = options.query;
246
+ while (nextPath !== void 0) {
247
+ const record = asRecord(await client.request(nextPath, { query: nextQuery }));
248
+ const items = record[itemsKey];
249
+ if (Array.isArray(items)) for (const item of items) yield item;
250
+ const nextUrl = stringIfPresent(asRecord(record._metadata).next);
251
+ if (!nextUrl) nextPath = void 0;
252
+ else {
253
+ const parsed = new URL(nextUrl);
254
+ nextPath = `${parsed.pathname.replace(/^\/v3/u, "")}${parsed.search}`;
255
+ nextQuery = void 0;
256
+ }
257
+ }
258
+ }
259
+
260
+ //#endregion
261
+ export { SendGridError, createSendGridClient, isSendGridError, paginateSendGrid };
@@ -0,0 +1,2 @@
1
+ import { i as sendgridOfficialIntegration, n as sendgrid, t as SendGridCredentials } from "./integration-CmJ2TILG.mjs";
2
+ export { type SendGridCredentials, sendgrid, sendgridOfficialIntegration };
@@ -0,0 +1,3 @@
1
+ import { r as sendgridOfficialIntegration, t as sendgrid } from "./integration-37BovSeK.mjs";
2
+
3
+ export { sendgrid, sendgridOfficialIntegration };