The best way to control Claude Code, Codex and more from any computer or phone

main
ts 352 lines 12.3 KB
Raw
1 import * as socialmessaging from "@distilled.cloud/aws/socialmessaging";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags, type Tags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as EffectStream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 export class LinkedWhatsAppBusinessAccountInvalidProps extends Data.TaggedError(
13 "LinkedWhatsAppBusinessAccountInvalidProps",
14 )<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 export type RegistrationStatus = socialmessaging.RegistrationStatus;
20 export type WhatsAppPhoneNumberSummary = socialmessaging.WhatsAppPhoneNumberSummary;
21
22 /**
23 * An event destination (Amazon SNS topic) that AWS End User Messaging Social
24 * publishes WhatsApp events (messages, message status updates) to.
25 */
26 export interface LinkedWhatsAppBusinessAccountEventDestination {
27 /**
28 * ARN of the SNS topic that receives WhatsApp events for this account.
29 */
30 eventDestinationArn: string;
31 /**
32 * ARN of an IAM role the service assumes to publish to the topic. Omit to
33 * publish with a service principal.
34 */
35 roleArn?: string;
36 }
37
38 export interface LinkedWhatsAppBusinessAccountProps {
39 /**
40 * The unique identifier of the WhatsApp Business Account already linked to
41 * your AWS account (format `waba-...`).
42 *
43 * WhatsApp Business onboarding requires the Meta embedded-signup OAuth flow
44 * in the AWS console and cannot be automated — this resource adopts and
45 * manages an account that has already been linked. Changing the identifier
46 * replaces the resource.
47 */
48 accountId: string;
49 /**
50 * Event destinations (SNS topics) to publish WhatsApp events to. When set,
51 * the full list is synced (the API replaces the whole list). When omitted,
52 * existing event destinations are left untouched.
53 */
54 eventDestinations?: LinkedWhatsAppBusinessAccountEventDestination[];
55 /**
56 * Tags to associate with the linked WhatsApp Business Account.
57 */
58 tags?: Record<string, string>;
59 }
60
61 export interface LinkedWhatsAppBusinessAccount extends Resource<
62 "AWS.SocialMessaging.LinkedWhatsAppBusinessAccount",
63 LinkedWhatsAppBusinessAccountProps,
64 {
65 /**
66 * ARN of the linked WhatsApp Business Account.
67 */
68 arn: string;
69 /**
70 * The unique identifier of the linked WhatsApp Business Account
71 * (`waba-...`).
72 */
73 id: string;
74 /**
75 * The WhatsApp Business Account ID from Meta.
76 */
77 wabaId: string;
78 /**
79 * The name of the WhatsApp Business Account.
80 */
81 wabaName: string;
82 /**
83 * Registration status of the linked account (`COMPLETE` | `INCOMPLETE`).
84 */
85 registrationStatus: RegistrationStatus;
86 /**
87 * ISO-8601 date the WhatsApp Business Account was linked.
88 */
89 linkDate: string;
90 /**
91 * Event destinations currently configured on the account.
92 */
93 eventDestinations: LinkedWhatsAppBusinessAccountEventDestination[];
94 /**
95 * Phone numbers registered to the WhatsApp Business Account.
96 */
97 phoneNumbers: WhatsAppPhoneNumberSummary[];
98 /**
99 * Current tags reported for the account.
100 */
101 tags: Record<string, string>;
102 },
103 never,
104 Providers
105 > {}
106
107 /**
108 * A WhatsApp Business Account (WABA) linked to your AWS account through
109 * AWS End User Messaging Social.
110 *
111 * :::caution
112 * Linking a WhatsApp Business Account requires the Meta embedded-signup
113 * OAuth flow in the AWS console and cannot be automated. This resource
114 * adopts an already-linked account by its `waba-...` identifier and manages
115 * its event destinations and tags. Destroying the resource disassociates
116 * the WhatsApp Business Account from your AWS account.
117 * :::
118 * ### Managing a Linked Account
119 * **Example:** Adopt a console-linked WABA and route events to SNS
120 * ```typescript
121 * import * as AWS from "@alchemy.run/aws";
122 *
123 * const events = yield* AWS.SNS.Topic("WhatsAppEvents", {});
124 *
125 * const waba = yield* AWS.SocialMessaging.LinkedWhatsAppBusinessAccount(
126 * "Business",
127 * {
128 * // from the AWS End User Messaging Social console after onboarding
129 * accountId: "waba-0123456789abcdef0123456789abcdef",
130 * eventDestinations: [{ eventDestinationArn: events.topicArn }],
131 * tags: { team: "growth" },
132 * },
133 * );
134 * ```
135 *
136 * ### Consuming WhatsApp Events
137 * **Example:** Handle Inbound Messages in a Lambda
138 * WhatsApp events (inbound messages, message status updates) are delivered
139 * exclusively to the SNS topics listed in `eventDestinations` — there is no
140 * separate event source for this service. Compose the resource with
141 * `AWS.SNS.consumeTopicNotifications` on the destination topic:
142 * ```typescript
143 * const events = yield* AWS.SNS.Topic("WhatsAppEvents", {});
144 *
145 * const waba = yield* AWS.SocialMessaging.LinkedWhatsAppBusinessAccount(
146 * "Business",
147 * {
148 * accountId: "waba-0123456789abcdef0123456789abcdef",
149 * eventDestinations: [{ eventDestinationArn: events.topicArn }],
150 * },
151 * );
152 *
153 * // inside a Lambda Function's init effect
154 * yield* AWS.SNS.consumeTopicNotifications(events, (stream) =>
155 * stream.pipe(
156 * Stream.runForEach((notification) =>
157 * Effect.log("whatsapp event", notification.Message),
158 * ),
159 * ),
160 * );
161 * ```
162 *
163 * @resource
164 */
165 export const LinkedWhatsAppBusinessAccount = Resource<LinkedWhatsAppBusinessAccount>(
166 "AWS.SocialMessaging.LinkedWhatsAppBusinessAccount",
167 );
168
169 /**
170 * The referenced WhatsApp Business Account is not linked to this AWS
171 * account. Linking requires the Meta embedded-signup flow in the AWS
172 * console and cannot be performed by the provider.
173 */
174 export class WhatsAppBusinessAccountNotLinked extends Data.TaggedError(
175 "WhatsAppBusinessAccountNotLinked",
176 )<{
177 readonly accountId: string;
178 }> {}
179
180 const fetchTags = Effect.fn(function* (arn: string) {
181 const response = yield* socialmessaging.listTagsForResource({
182 resourceArn: arn,
183 });
184 return Object.fromEntries(
185 (response.tags ?? []).flatMap((tag) =>
186 tag.value === undefined ? [] : [[tag.key, tag.value] as const],
187 ),
188 );
189 });
190
191 interface LinkedAccountState {
192 attrs: LinkedWhatsAppBusinessAccount["Attributes"];
193 account: socialmessaging.LinkedWhatsAppBusinessAccount;
194 }
195
196 const readLinkedAccount = Effect.fn(function* (accountId: string) {
197 const response = yield* socialmessaging
198 .getLinkedWhatsAppBusinessAccount({ id: accountId })
199 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
200 const account = response?.account;
201 if (account === undefined) return undefined;
202 const state: LinkedAccountState = {
203 account,
204 attrs: {
205 arn: account.arn,
206 id: account.id,
207 wabaId: account.wabaId,
208 wabaName: account.wabaName,
209 registrationStatus: account.registrationStatus,
210 linkDate: account.linkDate.toISOString(),
211 eventDestinations: account.eventDestinations.map((destination) => ({
212 eventDestinationArn: destination.eventDestinationArn,
213 roleArn: destination.roleArn,
214 })),
215 phoneNumbers: account.phoneNumbers.map((phone) => ({ ...phone })),
216 tags: yield* fetchTags(account.arn),
217 },
218 };
219 return state;
220 });
221
222 const sortDestinations = (destinations: LinkedWhatsAppBusinessAccountEventDestination[]) =>
223 destinations
224 .map((destination) => ({
225 eventDestinationArn: destination.eventDestinationArn,
226 roleArn: destination.roleArn,
227 }))
228 .sort((l, r) => l.eventDestinationArn.localeCompare(r.eventDestinationArn));
229
230 const destinationsDrifted = (
231 observed: LinkedWhatsAppBusinessAccountEventDestination[],
232 desired: LinkedWhatsAppBusinessAccountEventDestination[],
233 ) => {
234 const left = sortDestinations(observed);
235 const right = sortDestinations(desired);
236 return (
237 left.length !== right.length ||
238 left.some(
239 (destination, index) =>
240 destination.eventDestinationArn !== right[index].eventDestinationArn ||
241 destination.roleArn !== right[index].roleArn,
242 )
243 );
244 };
245
246 export const LinkedWhatsAppBusinessAccountProvider = () =>
247 Provider.effect(
248 LinkedWhatsAppBusinessAccount,
249 Effect.gen(function* () {
250 return {
251 stables: ["arn", "id", "wabaId"],
252 list: () =>
253 Effect.gen(function* () {
254 const summaries = yield* socialmessaging.listLinkedWhatsAppBusinessAccounts
255 .pages({})
256 .pipe(
257 EffectStream.runCollect,
258 Effect.map((chunk) =>
259 Array.from(chunk).flatMap((page) => page.linkedAccounts ?? []),
260 ),
261 );
262 const hydrated = yield* Effect.forEach(
263 summaries,
264 (summary) => readLinkedAccount(summary.id),
265 { concurrency: 5 },
266 );
267 return hydrated.flatMap((state) => (state === undefined ? [] : [state.attrs]));
268 }),
269 read: Effect.fn(function* ({ id, olds, output }) {
270 const accountId = output?.id ?? olds?.accountId;
271 if (accountId === undefined) return undefined;
272 const state = yield* readLinkedAccount(accountId);
273 if (state === undefined) return undefined;
274 return (yield* hasAlchemyTags(id, state.attrs.tags as Tags))
275 ? state.attrs
276 : Unowned(state.attrs);
277 }),
278 diff: Effect.fn(function* ({ news, olds }) {
279 if (!isResolved(news)) return;
280 if (olds === undefined) return;
281 // The linked account identity is fixed by Meta onboarding.
282 if (news.accountId !== olds.accountId) {
283 return { action: "replace" } as const;
284 }
285 }),
286 reconcile: Effect.fn(function* ({ id, news, output, session }) {
287 if (!news?.accountId) {
288 return yield* new LinkedWhatsAppBusinessAccountInvalidProps({
289 message:
290 "LinkedWhatsAppBusinessAccount requires an accountId (link the WABA in the AWS console first)",
291 });
292 }
293 const accountId = output?.id ?? news.accountId;
294 const internalTags = yield* createInternalTags(id);
295 const desiredTags = { ...internalTags, ...news.tags };
296
297 // Observe — onboarding is console-only, so the account must already
298 // be linked; there is no create path to fall through to.
299 const state = yield* readLinkedAccount(accountId);
300 if (state === undefined) {
301 return yield* new WhatsAppBusinessAccountNotLinked({ accountId });
302 }
303
304 // Sync event destinations — the API replaces the full list.
305 if (
306 news.eventDestinations !== undefined &&
307 destinationsDrifted(state.attrs.eventDestinations, news.eventDestinations)
308 ) {
309 yield* socialmessaging.putWhatsAppBusinessAccountEventDestinations({
310 id: state.attrs.id,
311 eventDestinations: news.eventDestinations.map((destination) => ({
312 eventDestinationArn: destination.eventDestinationArn,
313 roleArn: destination.roleArn,
314 })),
315 });
316 yield* session.note(`Updated event destinations for ${state.attrs.id}`);
317 }
318
319 // Sync tags — diff against observed cloud tags.
320 const { removed, upsert } = diffTags(state.attrs.tags, desiredTags);
321 if (removed.length > 0) {
322 yield* socialmessaging.untagResource({
323 resourceArn: state.attrs.arn,
324 tagKeys: removed,
325 });
326 }
327 if (upsert.length > 0) {
328 yield* socialmessaging.tagResource({
329 resourceArn: state.attrs.arn,
330 tags: upsert.map(({ Key, Value }) => ({
331 key: Key,
332 value: Value,
333 })),
334 });
335 }
336
337 yield* session.note(state.attrs.arn);
338
339 const final = yield* readLinkedAccount(accountId);
340 if (final === undefined) {
341 return yield* new WhatsAppBusinessAccountNotLinked({ accountId });
342 }
343 return final.attrs;
344 }),
345 delete: Effect.fn(function* ({ output }) {
346 yield* socialmessaging
347 .disassociateWhatsAppBusinessAccount({ id: output.id })
348 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
349 }),
350 };
351 }),
352 );