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

main
ts 361 lines 12.8 KB
Raw
1 import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3";
2 import * as essentialcontacts from "@distilled.cloud/gcp/essentialcontacts_v1";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Data from "effect/Data";
5 import * as Effect from "effect/Effect";
6 import * as Stream from "effect/Stream";
7 import { GcpEnvironment } from "../Environment.ts";
8 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
9
10 export type NotificationCategory =
11 essentialcontacts.GoogleCloudEssentialcontactsV1ContactNotificationCategorySubscriptionsItemEnum;
12
13 export type DistilledContact = essentialcontacts.GoogleCloudEssentialcontactsV1Contact;
14
15 export const DEFAULT_LANGUAGE_TAG = "en-US";
16 export const DEFAULT_CATEGORIES: NotificationCategory[] = ["ALL"];
17 export const UPDATE_MASK = "notificationCategorySubscriptions,languageTag";
18
19 const OWNERSHIP_TOKEN = "alc";
20 const MAX_LOCAL_PART = 64;
21
22 export class FolderRequired extends Data.TaggedError("GCP.EssentialContacts.FolderRequired")<{
23 project: string;
24 }> {}
25
26 export class OrganizationRequired extends Data.TaggedError(
27 "GCP.EssentialContacts.OrganizationRequired",
28 )<{
29 project: string;
30 }> {}
31
32 export const lastSegment = (value: string) => {
33 const trimmed = value.replace(/\/+$/, "");
34 const parts = trimmed.split("/");
35 return parts[parts.length - 1] || trimmed;
36 };
37
38 export const parentOfName = (name: string) => {
39 const parts = name.split("/").filter((part) => part.length > 0);
40 const index = parts.lastIndexOf("contacts");
41 if (index <= 0) return "";
42 return parts.slice(0, index).join("/");
43 };
44
45 export const contactIdOf = (name: string) => lastSegment(name);
46
47 export const projectParent = (project: string) =>
48 project.startsWith("projects/") ? project : `projects/${project}`;
49
50 export const folderParent = (folderId: string) =>
51 folderId.startsWith("folders/") ? folderId : `folders/${lastSegment(folderId)}`;
52
53 export const organizationParent = (value: string) =>
54 value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`;
55
56 export const sameText = (left: string | undefined, right: string | undefined) =>
57 (left ?? "") === (right ?? "");
58
59 export const normalizeEmail = (email: string | undefined) => (email ?? "").trim().toLowerCase();
60
61 export const sortedCategories = (values: readonly string[] | undefined): NotificationCategory[] =>
62 [...(values ?? [])]
63 .map((value) => value as NotificationCategory)
64 .slice()
65 .sort();
66
67 export const sameCategories = (
68 left: readonly string[] | undefined,
69 right: readonly string[] | undefined,
70 ) => JSON.stringify(sortedCategories(left)) === JSON.stringify(sortedCategories(right));
71
72 const markerOf = (stack: string, stage: string, id: string) =>
73 `${OWNERSHIP_TOKEN}.${stack}.${stage}.${id}`;
74
75 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
76 let stack = labels[alchemyLabelKeys.stack] ?? "x";
77 let stage = labels[alchemyLabelKeys.stage] ?? "x";
78 let id = labels[alchemyLabelKeys.id] ?? "x";
79 let marker = markerOf(stack, stage, id);
80 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
81 if (id.length >= stack.length && id.length >= stage.length) {
82 id = id.slice(0, -1);
83 } else if (stack.length >= stage.length) {
84 stack = stack.slice(0, -1);
85 } else {
86 stage = stage.slice(0, -1);
87 }
88 marker = markerOf(stack, stage, id);
89 }
90 return marker.slice(0, maxLength);
91 };
92
93 const splitEmail = (email: string) => {
94 const trimmed = email.trim();
95 const at = trimmed.lastIndexOf("@");
96 if (at <= 0) return { local: trimmed, domain: "" };
97 return { local: trimmed.slice(0, at), domain: trimmed.slice(at + 1) };
98 };
99
100 const stripOwnershipLocal = (local: string) => {
101 const token = `+${OWNERSHIP_TOKEN}.`;
102 const index = local.lastIndexOf(token);
103 return index >= 0 ? local.slice(0, index) : local;
104 };
105
106 /**
107 * Essential Contacts have no labels or description, so Alchemy stamps
108 * ownership into the email local-part as `+alc.{stack}.{stage}.{id}`.
109 */
110 export const encodeEmail = (labels: Record<string, string>, email: string): string => {
111 const { local, domain } = splitEmail(email);
112 if (domain.length === 0) return email.trim();
113 const base = stripOwnershipLocal(local);
114 const reserved = base.length + 1;
115 const marker = fitMarker(labels, Math.max(8, MAX_LOCAL_PART - reserved));
116 const next = `${base}+${marker}`.slice(0, MAX_LOCAL_PART);
117 return `${next}@${domain}`;
118 };
119
120 export const parseEmail = (
121 email: string | undefined,
122 ): {
123 labels: Record<string, string>;
124 email: string | undefined;
125 } => {
126 if (!email) return { labels: {}, email };
127 const { local, domain } = splitEmail(email);
128 const token = `+${OWNERSHIP_TOKEN}.`;
129 const index = local.lastIndexOf(token);
130 if (index < 0) return { labels: {}, email };
131 const tag = local.slice(index + token.length);
132 const [stack, stage, ...idParts] = tag.split(".");
133 const base = local.slice(0, index);
134 const restored = domain.length > 0 ? `${base}@${domain}` : base.length > 0 ? base : email;
135 return {
136 labels: {
137 [alchemyLabelKeys.stack]: stack ?? "",
138 [alchemyLabelKeys.stage]: stage ?? "",
139 [alchemyLabelKeys.id]: idParts.join("."),
140 },
141 email: restored,
142 };
143 };
144
145 export const hasOwnershipMarker = (email: string | undefined) =>
146 Object.keys(parseEmail(email).labels).some((key) => key.startsWith("alchemy-"));
147
148 const prefixMatch = (expected: string, observed: string) =>
149 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
150
151 export const ownedByAlchemy = (id: string, email: string | undefined) =>
152 Effect.gen(function* () {
153 const expected = yield* createInternalLabels(id);
154 const { labels } = parseEmail(email);
155 if (!hasOwnershipMarker(email)) return false;
156 const exact = yield* hasAlchemyLabels(id, labels);
157 if (exact) return true;
158 return (
159 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
160 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
161 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
162 );
163 });
164
165 export const ownershipLabels = (id: string) => createInternalLabels(id);
166
167 export const toEmail = (id: string, requested: string | undefined, existing: string | undefined) =>
168 Effect.gen(function* () {
169 if (requested !== undefined && requested.length > 0) return requested;
170 if (existing !== undefined && existing.length > 0) return existing;
171 const generated = yield* createPhysicalName({
172 id,
173 maxLength: 32,
174 lowercase: true,
175 });
176 const local = generated.replace(/[^a-z0-9]/g, "").slice(0, 32) || "alchemy";
177 return `${local}@example.com`;
178 });
179
180 export const toCreateBody = (args: {
181 email: string;
182 languageTag: string;
183 notificationCategorySubscriptions: NotificationCategory[];
184 }): DistilledContact => ({
185 email: args.email,
186 languageTag: args.languageTag,
187 notificationCategorySubscriptions: args.notificationCategorySubscriptions,
188 });
189
190 export type ContactCoreAttrs = {
191 name: string;
192 contactId: string;
193 parent: string;
194 project: string;
195 email: string;
196 languageTag: string;
197 notificationCategorySubscriptions: NotificationCategory[];
198 validationState: string | undefined;
199 validateTime: string | undefined;
200 };
201
202 export const toCoreAttrs = (
203 contact: DistilledContact,
204 parent: string,
205 project: string,
206 ): ContactCoreAttrs => {
207 const name = contact.name ?? "";
208 const parsed = parseEmail(contact.email);
209 return {
210 name,
211 contactId: contactIdOf(name),
212 parent: parentOfName(name) || parent,
213 project,
214 email: parsed.email ?? contact.email ?? "",
215 languageTag: contact.languageTag ?? DEFAULT_LANGUAGE_TAG,
216 notificationCategorySubscriptions: sortedCategories(contact.notificationCategorySubscriptions),
217 validationState: contact.validationState,
218 validateTime: contact.validateTime,
219 };
220 };
221
222 export const findOwnedContact = (
223 contacts: readonly DistilledContact[],
224 id: string,
225 name?: string,
226 email?: string,
227 ) =>
228 Effect.gen(function* () {
229 if (name) {
230 const exact = contacts.find((contact) => contact.name === name);
231 if (exact !== undefined) return exact;
232 }
233 const desired = email ? normalizeEmail(parseEmail(email).email ?? email) : undefined;
234 let owned: DistilledContact | undefined;
235 for (const contact of contacts) {
236 if (!(yield* ownedByAlchemy(id, contact.email))) continue;
237 const observed = normalizeEmail(parseEmail(contact.email).email ?? contact.email ?? "");
238 if (desired !== undefined) {
239 if (observed === desired) return contact;
240 continue;
241 }
242 if (owned === undefined) owned = contact;
243 }
244 return desired !== undefined ? undefined : owned;
245 });
246
247 const emptyList = <A>() => Effect.succeed([] as A[]);
248
249 export const collectPages = <A, Page, E, R>(
250 pages: Stream.Stream<Page, E, R>,
251 pick: (page: Page) => readonly A[] | undefined,
252 ) =>
253 pages.pipe(
254 Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])),
255 Stream.runCollect,
256 Effect.map((chunk) => Array.from(chunk)),
257 );
258
259 export const listContacts = <E extends { readonly _tag: string }, R>(
260 pages: Stream.Stream<essentialcontacts.GoogleCloudEssentialcontactsV1ListContactsResponse, E, R>,
261 ) =>
262 collectPages(pages, (page) => page.contacts).pipe(
263 Effect.catchIf(
264 (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound",
265 () => emptyList<DistilledContact>(),
266 ),
267 );
268
269 const parentOfResource = (name: string) =>
270 name.startsWith("projects/")
271 ? resourcemanager.getProjects({ name }).pipe(
272 Effect.map((resource) => resource.parent),
273 Effect.catchTag("NotFound", () => Effect.undefined),
274 )
275 : name.startsWith("folders/")
276 ? resourcemanager.getFolders({ name }).pipe(
277 Effect.map((folder) => folder.parent),
278 Effect.catchTag("NotFound", () => Effect.undefined),
279 )
280 : Effect.undefined;
281
282 export const lookupProjectFolderId = (project: string) =>
283 resourcemanager.getProjects({ name: `projects/${project}` }).pipe(
284 Effect.map((resource) => {
285 const parent = resource.parent ?? "";
286 return parent.startsWith("folders/") ? lastSegment(parent) : undefined;
287 }),
288 Effect.catchTag("NotFound", () => Effect.undefined),
289 );
290
291 export const tryResolveFolder = () =>
292 Effect.gen(function* () {
293 const env = yield* GcpEnvironment.current;
294 const folderId = yield* lookupProjectFolderId(env.project);
295 return folderId !== undefined ? folderParent(folderId) : undefined;
296 });
297
298 export const resolveFolder = (explicit: string | undefined, existing: string | undefined) =>
299 Effect.gen(function* () {
300 if (explicit !== undefined && explicit.length > 0) {
301 return folderParent(explicit);
302 }
303 if (existing !== undefined && existing.length > 0) {
304 return folderParent(existing);
305 }
306 const resolved = yield* tryResolveFolder();
307 if (resolved === undefined) {
308 const env = yield* GcpEnvironment.current;
309 return yield* new FolderRequired({ project: env.project });
310 }
311 return resolved;
312 });
313
314 export const listFolderParents = () =>
315 Effect.gen(function* () {
316 const env = yield* GcpEnvironment.current;
317 const ids = new Set<string>();
318 const fromProject = yield* lookupProjectFolderId(env.project);
319 if (fromProject !== undefined) ids.add(folderParent(fromProject));
320 return [...ids];
321 });
322
323 export const tryResolveOrganization = () =>
324 Effect.gen(function* () {
325 const env = yield* GcpEnvironment.current;
326 let current: string | undefined = `projects/${env.project}`;
327 for (let i = 0; i < 8; i++) {
328 if (current === undefined) return undefined;
329 if (current.startsWith("organizations/")) return current;
330 current = yield* parentOfResource(current);
331 }
332 return undefined;
333 });
334
335 export const resolveOrganization = (explicit: string | undefined, existing: string | undefined) =>
336 Effect.gen(function* () {
337 if (explicit !== undefined && explicit.length > 0) {
338 return organizationParent(explicit);
339 }
340 if (existing !== undefined && existing.length > 0) {
341 return organizationParent(existing);
342 }
343 const resolved = yield* tryResolveOrganization();
344 if (resolved === undefined) {
345 const env = yield* GcpEnvironment.current;
346 return yield* new OrganizationRequired({ project: env.project });
347 }
348 return resolved;
349 });
350
351 export const listOrganizationParents = () =>
352 Effect.gen(function* () {
353 const resolved = yield* tryResolveOrganization();
354 return resolved === undefined ? [] : [resolved];
355 });
356
357 export const desiredLanguage = (value: string | undefined) =>
358 value && value.length > 0 ? value : DEFAULT_LANGUAGE_TAG;
359
360 export const desiredCategories = (values: readonly NotificationCategory[] | undefined) =>
361 values !== undefined && values.length > 0 ? sortedCategories(values) : DEFAULT_CATEGORIES;