@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 230 lines 8.3 KB
Raw
1 import * as contacts from "@distilled.cloud/aws/notificationscontacts";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Redacted from "effect/Redacted";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13
14 export interface EmailContactProps {
15 /**
16 * Display name of the contact (1–64 characters). If omitted, a unique
17 * name is generated from the app, stage and logical ID. Contacts have no
18 * update API, so changing the name replaces the contact.
19 */
20 name?: string;
21
22 /**
23 * The email address that receives notifications. Unique per account —
24 * AWS rejects a second contact with the same address. Changing the
25 * address replaces the contact.
26 *
27 * A new contact is created in the unverified `inactive` state; AWS sends
28 * notifications to it only after the address owner confirms the
29 * activation email (`SendActivationCode` / the console).
30 */
31 emailAddress: string;
32
33 /**
34 * User tags to attach to the contact. Merged with internal Alchemy tags.
35 */
36 tags?: Record<string, string>;
37 }
38
39 export interface EmailContact extends Resource<
40 "AWS.NotificationsContacts.EmailContact",
41 EmailContactProps,
42 {
43 /** The ARN of the email contact (regionless). */
44 emailContactArn: string;
45 /** The display name of the contact. */
46 name: string;
47 /** The email address of the contact. */
48 emailAddress: string;
49 /**
50 * Verification status: `inactive` until the address owner confirms the
51 * activation email, then `active`.
52 */
53 status: string;
54 },
55 never,
56 Providers
57 > {}
58
59 /**
60 * An AWS User Notifications Contacts **email contact** — an email address
61 * that can be attached to a notification configuration as a delivery
62 * channel.
63 *
64 * Contacts are created in the unverified `inactive` state; activation is a
65 * human email-confirmation loop (AWS emails the address a confirmation
66 * link), so Alchemy provisions the contact and leaves activation to the
67 * address owner. Contacts are immutable (no update API) — changing the
68 * name or address replaces the contact; tags update in place.
69 *
70 * ### Creating an Email Contact
71 * **Example:** Basic email contact
72 * ```typescript
73 * import * as NotificationsContacts from "@alchemy.run/aws/NotificationsContacts";
74 *
75 * const contact = yield* NotificationsContacts.EmailContact("OnCall", {
76 * emailAddress: "oncall@example.com",
77 * });
78 * // contact.status === "inactive" until the address owner confirms
79 * ```
80 *
81 * **Example:** Named contact with tags
82 * ```typescript
83 * const contact = yield* NotificationsContacts.EmailContact("OnCall", {
84 * name: "platform-oncall",
85 * emailAddress: "oncall@example.com",
86 * tags: { team: "platform" },
87 * });
88 * ```
89 *
90 * @resource
91 */
92 export const EmailContact = Resource<EmailContact>("AWS.NotificationsContacts.EmailContact");
93
94 /** Unwrap distilled `SensitiveString` values into plain strings. */
95 const unwrapSensitive = (value: string | Redacted.Redacted<string>): string =>
96 typeof value === "string" ? value : Redacted.value(value);
97
98 const readContactTags = Effect.fn(function* (arn: string) {
99 return yield* contacts.listTagsForResource({ arn }).pipe(
100 Effect.map((r) => (r.tags ?? {}) as Record<string, string>),
101 Effect.catchTag(["ResourceNotFoundException", "ValidationException"], () =>
102 Effect.succeed({} as Record<string, string>),
103 ),
104 );
105 });
106
107 const syncContactTags = Effect.fn(function* (
108 arn: string,
109 id: string,
110 userTags: Record<string, string> | undefined,
111 ) {
112 const internalTags = yield* createInternalTags(id);
113 const desired = { ...userTags, ...internalTags };
114 const observed = yield* readContactTags(arn);
115 const { upsert, removed } = diffTags(observed, desired);
116 if (upsert.length > 0) {
117 yield* contacts.tagResource({
118 arn,
119 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
120 });
121 }
122 if (removed.length > 0) {
123 yield* contacts.untagResource({ arn, tagKeys: removed });
124 }
125 });
126
127 export const EmailContactProvider = () =>
128 Provider.effect(
129 EmailContact,
130 Effect.gen(function* () {
131 const createName = Effect.fn(function* (id: string, props: EmailContactProps) {
132 return props.name ?? (yield* createPhysicalName({ id }));
133 });
134
135 // Email addresses are unique account-wide (CreateEmailContact rejects
136 // duplicates with ConflictException), so an address scan is a
137 // reliable identity fallback when the ARN cache is missing.
138 const findByAddress = Effect.fn(function* (emailAddress: string) {
139 return yield* contacts.listEmailContacts.items({}).pipe(
140 Stream.filter((contact) => unwrapSensitive(contact.address) === emailAddress),
141 Stream.runHead,
142 Effect.map(Option.getOrUndefined),
143 );
144 });
145
146 const getByArn = Effect.fn(function* (arn: string) {
147 return yield* contacts.getEmailContact({ arn }).pipe(
148 Effect.map((r) => r.emailContact),
149 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
150 );
151 });
152
153 const toAttrs = (live: contacts.EmailContact) => ({
154 emailContactArn: live.arn,
155 name: unwrapSensitive(live.name),
156 emailAddress: unwrapSensitive(live.address),
157 status: live.status,
158 });
159
160 return EmailContact.Provider.of({
161 stables: ["emailContactArn", "name", "emailAddress"],
162
163 list: () =>
164 contacts.listEmailContacts.items({}).pipe(
165 Stream.runCollect,
166 Effect.map((chunk) => Array.from(chunk).map(toAttrs)),
167 ),
168
169 read: Effect.fn(function* ({ id, olds, output }) {
170 const found = output?.emailContactArn
171 ? yield* getByArn(output.emailContactArn)
172 : olds?.emailAddress
173 ? yield* findByAddress(olds.emailAddress)
174 : undefined;
175 if (!found) return undefined;
176 const attrs = toAttrs(found);
177 const tags = yield* readContactTags(found.arn);
178 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
179 }),
180
181 diff: Effect.fn(function* ({ id, news, olds }) {
182 if (!isResolved(news)) return undefined;
183 const oldName = yield* createName(id, olds);
184 const newName = yield* createName(id, news);
185 // No update API — any change to the contact itself replaces it.
186 if (oldName !== newName || news.emailAddress !== olds.emailAddress) {
187 return { action: "replace" } as const;
188 }
189 return undefined;
190 }),
191
192 reconcile: Effect.fn(function* ({ id, news, output, session }) {
193 const name = yield* createName(id, news);
194
195 // OBSERVE — cloud state is authoritative; the cached ARN falls
196 // through to an address scan when it no longer resolves.
197 let live = output?.emailContactArn
198 ? yield* getByArn(output.emailContactArn)
199 : yield* findByAddress(news.emailAddress);
200
201 // ENSURE — create when missing; ConflictException means a
202 // same-address contact already exists (race) → re-observe.
203 if (live === undefined) {
204 const created = yield* contacts
205 .createEmailContact({
206 name,
207 emailAddress: news.emailAddress,
208 tags: news.tags,
209 })
210 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined));
211 live = created ? yield* getByArn(created.arn) : yield* findByAddress(news.emailAddress);
212 }
213 const arn = live!.arn;
214
215 // SYNC tags — the contact itself is immutable; tags are the only
216 // mutable aspect (diffed against observed cloud tags).
217 yield* syncContactTags(arn, id, news.tags);
218
219 yield* session.note(arn);
220 return toAttrs(live!);
221 }),
222
223 delete: Effect.fn(function* ({ output }) {
224 yield* contacts
225 .deleteEmailContact({ arn: output.emailContactArn })
226 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
227 }),
228 });
229 }),
230 );