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

main
ts 77 lines 2.48 KB
Raw
1 import { createInternalTags, diffTags, hasTags, type Tags } from "alchemy/Tags";
2 import * as Effect from "effect/Effect";
3
4 /**
5 * GCP label keys may contain only lowercase letters, digits, underscores
6 * and dashes (no `:`, no `.`). Alchemy ownership tags
7 * `alchemy::stack` / `alchemy::stage` / `alchemy::id` map onto
8 * `alchemy-stack` / `alchemy-stage` / `alchemy-id`.
9 */
10 export const ALCHEMY_LABEL_PREFIX = "alchemy-";
11
12 export const alchemyLabelKeys = {
13 stack: "alchemy-stack",
14 stage: "alchemy-stage",
15 id: "alchemy-id",
16 } as const;
17
18 const TAG_PREFIX = "alchemy::";
19
20 export const toLabelKey = (tagKey: string): string =>
21 tagKey.startsWith(TAG_PREFIX)
22 ? `${ALCHEMY_LABEL_PREFIX}${tagKey.slice(TAG_PREFIX.length)}`
23 : tagKey;
24
25 export const toTagKey = (labelKey: string): string =>
26 labelKey.startsWith(ALCHEMY_LABEL_PREFIX)
27 ? `${TAG_PREFIX}${labelKey.slice(ALCHEMY_LABEL_PREFIX.length)}`
28 : labelKey;
29
30 export const sanitizeLabelValue = (value: string): string => {
31 const cleaned = value
32 .replaceAll("/", "__")
33 .replace(/[^a-zA-Z0-9_-]/g, "-")
34 .replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, "")
35 .slice(0, 63)
36 .replace(/[^a-zA-Z0-9]+$/g, "")
37 .toLowerCase();
38 return cleaned.length > 0 ? cleaned : "x";
39 };
40
41 export const toLabels = (tags: Record<string, string> | null | undefined): Record<string, string> =>
42 Object.fromEntries(
43 Object.entries(tags ?? {}).map(([key, value]) => [
44 toLabelKey(key)
45 .toLowerCase()
46 .replace(/[^a-z0-9_-]/g, "-"),
47 sanitizeLabelValue(value),
48 ]),
49 );
50
51 export const fromLabels = (
52 labels: Record<string, string> | null | undefined,
53 ): Record<string, string> =>
54 Object.fromEntries(Object.entries(labels ?? {}).map(([key, value]) => [toTagKey(key), value]));
55
56 export const createInternalLabels = Effect.fn(function* (id: string) {
57 return toLabels(yield* createInternalTags(id));
58 });
59
60 export const stripInternalLabels = (
61 labels: Record<string, string> | null | undefined,
62 ): Record<string, string> =>
63 Object.fromEntries(
64 Object.entries(labels ?? {}).filter(([key]) => !key.startsWith(ALCHEMY_LABEL_PREFIX)),
65 );
66
67 export const hasAlchemyLabels = Effect.fn(function* (id: string, labels: Tags | undefined) {
68 const expected = yield* createInternalLabels(id);
69 return hasTags(expected, labels);
70 });
71
72 /**
73 * Diff observed cloud labels against desired labels. Always pass
74 * **observed** labels as `oldLabels` — never `olds.labels` or
75 * `output.labels` — so adoption converges.
76 */
77 export const diffLabels = diffTags;