@distilled.cloud/mailchimp 0.0.0-stage → 1.0.0-rc.19

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 (59) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +106 -2
  3. package/lib/.lazy.json +1 -0
  4. package/lib/_bundle/lazy.js +4 -0
  5. package/lib/_bundle/sdk.js +2 -0
  6. package/lib/_bundle/sdk.js.map +1 -0
  7. package/lib/credentials.d.ts +59 -0
  8. package/lib/credentials.d.ts.map +1 -0
  9. package/lib/credentials.js +1 -0
  10. package/lib/errors.d.ts +68 -0
  11. package/lib/errors.d.ts.map +1 -0
  12. package/lib/errors.js +1 -0
  13. package/lib/index.d.ts +44 -0
  14. package/lib/index.d.ts.map +1 -0
  15. package/lib/index.js +10 -0
  16. package/lib/index.lazy.js +10 -0
  17. package/lib/index.lazy.js.map +1 -0
  18. package/lib/pagination.d.ts +11 -0
  19. package/lib/pagination.d.ts.map +1 -0
  20. package/lib/pagination.js +1 -0
  21. package/lib/protocol.d.ts +25 -0
  22. package/lib/protocol.d.ts.map +1 -0
  23. package/lib/protocol.js +1 -0
  24. package/lib/retry.d.ts +53 -0
  25. package/lib/retry.d.ts.map +1 -0
  26. package/lib/retry.js +1 -0
  27. package/lib/services/index.d.ts +3 -0
  28. package/lib/services/index.d.ts.map +1 -0
  29. package/lib/services/index.js +2 -0
  30. package/lib/services/marketing.d.ts +24805 -0
  31. package/lib/services/marketing.d.ts.map +1 -0
  32. package/lib/services/marketing.js +409 -0
  33. package/lib/services/marketing.js.map +1 -0
  34. package/lib/services/transactional.d.ts +3805 -0
  35. package/lib/services/transactional.d.ts.map +1 -0
  36. package/lib/services/transactional.js +143 -0
  37. package/lib/services/transactional.js.map +1 -0
  38. package/lib/services.lazy/index.js +3 -0
  39. package/lib/services.lazy/marketing.js +3 -0
  40. package/lib/services.lazy/transactional.js +4 -0
  41. package/lib/subscriber-hash.d.ts +11 -0
  42. package/lib/subscriber-hash.d.ts.map +1 -0
  43. package/lib/subscriber-hash.js +2 -0
  44. package/lib/subscriber-hash.js.map +1 -0
  45. package/lib/traits.d.ts +7 -0
  46. package/lib/traits.d.ts.map +1 -0
  47. package/lib/traits.js +1 -0
  48. package/package.json +93 -3
  49. package/src/credentials.ts +156 -0
  50. package/src/errors.ts +81 -0
  51. package/src/index.ts +50 -0
  52. package/src/pagination.ts +69 -0
  53. package/src/protocol.ts +196 -0
  54. package/src/retry.ts +72 -0
  55. package/src/services/index.ts +3 -0
  56. package/src/services/marketing.ts +43348 -0
  57. package/src/services/transactional.ts +7512 -0
  58. package/src/subscriber-hash.ts +87 -0
  59. package/src/traits.ts +40 -0
@@ -0,0 +1,196 @@
1
+ import * as API from "@distilled.cloud/core/api";
2
+ import type {
3
+ API_ERRORS,
4
+ ConfigError,
5
+ DefaultErrors,
6
+ InvalidInput,
7
+ } from "@distilled.cloud/core/errors";
8
+ import { makeRestProtocol } from "@distilled.cloud/core/protocol-rest";
9
+ import type { SdkError } from "@distilled.cloud/core/sdk-error";
10
+ /**
11
+ * MailchimpProtocol -- hand-written.
12
+ *
13
+ * Plain JSON REST with no response envelope. Failures are RFC 7807 problem
14
+ * documents:
15
+ *
16
+ * { "type": "https://mailchimp.com/developer/marketing/docs/errors/",
17
+ * "title": "Resource Not Found", "status": 404,
18
+ * "detail": "The requested resource could not be found.",
19
+ * "instance": "995c5cb0-3280-4a6e-808b-3b096d0bb219" }
20
+ *
21
+ * A 400 from a write adds `errors: [{ field, message }]`, which is folded into
22
+ * the message because the core status classes carry nothing else.
23
+ *
24
+ * MailchimpTransactionalProtocol is JSON over POST: every call carries the
25
+ * key in its body, and failures are
26
+ *
27
+ * { "status": "error", "code": 401, "name": "Invalid_Key",
28
+ * "message": "Invalid API key" }
29
+ *
30
+ * under a real HTTP status, so they map by status too; `name` is kept in the
31
+ * message (`Invalid_Key: Invalid API key`).
32
+ */
33
+ import * as Effect from "effect/Effect";
34
+ import type * as HttpClient from "effect/http/HttpClient";
35
+ import type * as HttpClientError from "effect/http/HttpClientError";
36
+ import type * as HttpClientRequest from "effect/http/HttpClientRequest";
37
+ import * as Layer from "effect/Layer";
38
+ import * as Redacted from "effect/Redacted";
39
+ import {
40
+ Credentials,
41
+ TransactionalCredentials,
42
+ type Config,
43
+ type TransactionalConfig,
44
+ } from "./credentials.ts";
45
+ import {
46
+ MailchimpApiError,
47
+ MailchimpParseError,
48
+ MailchimpTransactionalError,
49
+ UnknownMailchimpError,
50
+ } from "./errors.ts";
51
+
52
+ export type MailchimpOpError =
53
+ | InstanceType<(typeof API_ERRORS)[number]>
54
+ | MailchimpApiError
55
+ | UnknownMailchimpError
56
+ | MailchimpParseError
57
+ | ConfigError
58
+ | HttpClientError.HttpClientError
59
+ | InvalidInput
60
+ | SdkError;
61
+
62
+ export type MailchimpOpContext = Credentials | HttpClient.HttpClient;
63
+
64
+ const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
65
+
66
+ const str = (v: unknown): string | undefined => (typeof v === "string" && v !== "" ? v : undefined);
67
+
68
+ const fieldErrors = (body: Record<string, unknown>): string[] =>
69
+ Array.isArray(body.errors)
70
+ ? body.errors.flatMap((e) =>
71
+ isRecord(e) && str(e.message)
72
+ ? [str(e.field) ? `${e.field}: ${e.message}` : String(e.message)]
73
+ : [],
74
+ )
75
+ : [];
76
+
77
+ const problemMessage = (body: unknown): string | undefined => {
78
+ if (!isRecord(body)) return undefined;
79
+ const head = str(body.detail) ?? str(body.title);
80
+ if (head === undefined) return undefined;
81
+ const fields = fieldErrors(body);
82
+ return fields.length ? `${head} (${fields.join("; ")})` : head;
83
+ };
84
+
85
+ export const MailchimpProtocol: Layer.Layer<API.Protocol> = /*@__PURE__*/ makeRestProtocol<Config>({
86
+ // Resolved on the calling fiber per request.
87
+ credentials: /*@__PURE__*/ Effect.flatMap(Credentials, (resolve) => resolve),
88
+ baseUrl: (creds) => creds.apiBaseUrl,
89
+ // Basic auth: Mailchimp ignores the username.
90
+ headers: (creds) => ({
91
+ Authorization: `Basic ${btoa(`anystring:${Redacted.value(creds.apiKey)}`)}`,
92
+ }),
93
+ errorEnvelope: (body) => {
94
+ const message = problemMessage(body);
95
+ return message === undefined ? undefined : { message };
96
+ },
97
+ unknownError: ({ status, message, body }) => {
98
+ const problem = isRecord(body) ? body : undefined;
99
+ const fields = {
100
+ status,
101
+ type: str(problem?.type),
102
+ title: str(problem?.title),
103
+ message,
104
+ instance: str(problem?.instance),
105
+ body,
106
+ };
107
+ return problemMessage(body) !== undefined
108
+ ? new MailchimpApiError(fields)
109
+ : new UnknownMailchimpError(fields);
110
+ },
111
+ parseError: ({ body, cause }) => new MailchimpParseError({ body, cause }),
112
+ });
113
+
114
+ // ------------- Transactional -------------
115
+
116
+ /**
117
+ * Only the always-possible failures. Each operation adds the classes its
118
+ * declared statuses map to (`NotFound`, `PaymentRequired`, ...).
119
+ */
120
+ export type MailchimpTransactionalOpError =
121
+ | DefaultErrors
122
+ | MailchimpTransactionalError
123
+ | UnknownMailchimpError
124
+ | MailchimpParseError
125
+ | ConfigError
126
+ | HttpClientError.HttpClientError
127
+ | InvalidInput
128
+ | SdkError;
129
+
130
+ export type MailchimpTransactionalOpContext = TransactionalCredentials | HttpClient.HttpClient;
131
+
132
+ const resolveTransactional = /*@__PURE__*/ Effect.flatMap(
133
+ TransactionalCredentials,
134
+ (resolve) => resolve,
135
+ );
136
+
137
+ const transactionalFailure = (body: unknown): Record<string, unknown> | undefined =>
138
+ isRecord(body) && body.status === "error" ? body : undefined;
139
+
140
+ const transactionalMessage = (failure: Record<string, unknown>): string | undefined => {
141
+ const name = str(failure.name);
142
+ const message = str(failure.message);
143
+ return name !== undefined && message !== undefined ? `${name}: ${message}` : (name ?? message);
144
+ };
145
+
146
+ const TransactionalRest: Layer.Layer<API.Protocol> =
147
+ /*@__PURE__*/ makeRestProtocol<TransactionalConfig>({
148
+ credentials: resolveTransactional,
149
+ baseUrl: (creds) => creds.apiBaseUrl,
150
+ headers: () => ({}),
151
+ errorEnvelope: (body) => {
152
+ const failure = transactionalFailure(body);
153
+ if (failure === undefined) return undefined;
154
+ const message = transactionalMessage(failure);
155
+ return message === undefined
156
+ ? undefined
157
+ : { message, code: typeof failure.code === "number" ? failure.code : undefined };
158
+ },
159
+ unknownError: ({ status, code, message, body }) => {
160
+ const failure = transactionalFailure(body);
161
+ return failure !== undefined
162
+ ? new MailchimpTransactionalError({
163
+ status,
164
+ code: typeof code === "number" ? code : undefined,
165
+ name: str(failure.name),
166
+ message,
167
+ body,
168
+ })
169
+ : new UnknownMailchimpError({ status, message, body });
170
+ },
171
+ parseError: ({ body, cause }) => new MailchimpParseError({ body, cause }),
172
+ });
173
+
174
+ /**
175
+ * The key rides in the JSON body, not a header. It is added to the input
176
+ * here so the generated request shapes never carry it; the REST encoder
177
+ * sends members the schema does not know as body fields, and unwraps the
178
+ * `Redacted` key on the way out.
179
+ */
180
+ export const MailchimpTransactionalProtocol: Layer.Layer<API.Protocol> = /*@__PURE__*/ Layer.effect(
181
+ API.Protocol,
182
+ Effect.gen(function* () {
183
+ const rest = yield* API.Protocol;
184
+ return API.Protocol.of({
185
+ encode: (args) =>
186
+ Effect.gen(function* () {
187
+ const creds = yield* resolveTransactional;
188
+ return yield* rest.encode({
189
+ ...args,
190
+ input: { ...(isRecord(args.input) ? args.input : {}), key: creds.apiKey },
191
+ });
192
+ }) as Effect.Effect<HttpClientRequest.HttpClientRequest>,
193
+ decode: rest.decode,
194
+ });
195
+ }),
196
+ ).pipe(Layer.provide(TransactionalRest));
package/src/retry.ts ADDED
@@ -0,0 +1,72 @@
1
+ import * as Retries from "@distilled.cloud/core/retry";
2
+ /**
3
+ * Mailchimp retry surface -- a veneer over `@distilled.cloud/core/retry`.
4
+ *
5
+ * Mailchimp allows 10 simultaneous connections per key and answers 429 past
6
+ * that; `throttling` is the policy that recovers it.
7
+ *
8
+ * The `Retry` service tag is threaded into every generated operation via
9
+ * `API.make({ retry: Retry })`, so a caller-installed policy applies to all
10
+ * Mailchimp calls below it and core's `makeDefault` is the fallback when none is
11
+ * provided.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import * as Mailchimp from "@distilled.cloud/mailchimp";
16
+ *
17
+ * myEffect.pipe(Mailchimp.Retry.throttling);
18
+ * ```
19
+ */
20
+ import * as Context from "effect/Context";
21
+ import * as Effect from "effect/Effect";
22
+ import * as Layer from "effect/Layer";
23
+
24
+ export type Options = Retries.Options;
25
+ export type Factory = Retries.Factory;
26
+ export type Policy = Retries.Policy;
27
+
28
+ /** Context tag for configuring retry behavior of Mailchimp API calls. */
29
+ export class Retry extends /*@__PURE__*/ Context.Service<Retry, Policy>()("MailchimpRetry") {}
30
+
31
+ /** Provides a custom retry policy to every Mailchimp API call below it. */
32
+ export const policy: {
33
+ (
34
+ options: Options,
35
+ ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Retry>>;
36
+ (
37
+ factory: Factory,
38
+ ): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Retry>>;
39
+ } = (optionsOrFactory: Options | Factory) => Effect.provide(Layer.succeed(Retry, optionsOrFactory));
40
+
41
+ /** Disables all automatic retries. */
42
+ export const none: <A, E, R>(
43
+ effect: Effect.Effect<A, E, R>,
44
+ ) => Effect.Effect<A, E, Exclude<R, Retry>> = /*@__PURE__*/ Effect.provide(
45
+ /*@__PURE__*/ Layer.succeed(Retry, { while: () => false }),
46
+ );
47
+
48
+ /**
49
+ * The default retry policy (core's): transient/throttling/retryable errors,
50
+ * capped exponential backoff with jitter, server `retryAfter` hints honored
51
+ * with precedence.
52
+ */
53
+ export const makeDefault: Factory = Retries.makeDefault;
54
+
55
+ export const jittered = Retries.jittered;
56
+ export const capped = Retries.capped;
57
+
58
+ /** Retry options that retry all throttling errors indefinitely. */
59
+ export const throttlingOptions: Options = Retries.throttlingOptions;
60
+
61
+ /** Retries all throttling errors indefinitely (honoring server hints). */
62
+ export const throttling: <A, E, R>(
63
+ effect: Effect.Effect<A, E, R>,
64
+ ) => Effect.Effect<A, E, Exclude<R, Retry>> = /*@__PURE__*/ policy(Retries.throttlingFactory);
65
+
66
+ /** Retry options that retry all transient errors indefinitely. */
67
+ export const transientOptions: Options = Retries.transientOptions;
68
+
69
+ /** Retries all transient errors indefinitely. */
70
+ export const transient: <A, E, R>(
71
+ effect: Effect.Effect<A, E, R>,
72
+ ) => Effect.Effect<A, E, Exclude<R, Retry>> = /*@__PURE__*/ policy(Retries.transientFactory);
@@ -0,0 +1,3 @@
1
+ // AUTO-GENERATED by scripts/generate.ts. Do not edit.
2
+ export * as marketing from "./marketing.ts";
3
+ export * as transactional from "./transactional.ts";