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

main
ts 197 lines 6.71 KB
Raw
1 import { createPhysicalName } from "alchemy/PhysicalName";
2 import * as Data from "effect/Data";
3 import * as Effect from "effect/Effect";
4 import * as Schedule from "effect/Schedule";
5 import { isTransientGcpError } from "../Errors.ts";
6
7 // Translation Advanced glossaries, AutoML models, and Adaptive MT live only in us-central1 (or global).
8 export const DEFAULT_LOCATION = "us-central1";
9 const MAX_DISPLAY_NAME_LENGTH = 32;
10 const MAX_ID_LENGTH = 63;
11
12 export class ResourceNotResolved extends Data.TaggedError("GCP.Translate.ResourceNotResolved")<{
13 resourceName: string;
14 }> {}
15
16 export class ResourceStillExists extends Data.TaggedError("GCP.Translate.ResourceStillExists")<{
17 resourceName: string;
18 }> {}
19
20 const lastSegment = (value: string) => {
21 const trimmed = value.replace(/\/+$/, "");
22 const parts = trimmed.split("/");
23 return parts[parts.length - 1] || trimmed;
24 };
25
26 export const normalizeLocation = (location: string | undefined) =>
27 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
28
29 export const locationParent = (project: string, location: string | undefined) =>
30 `projects/${project}/locations/${normalizeLocation(location)}`;
31
32 export const locationParentOf = (name: string) => {
33 const parts = name.split("/").filter((part) => part.length > 0);
34 const locationsAt = parts.lastIndexOf("locations");
35 if (locationsAt >= 0 && parts[locationsAt + 1]) {
36 return parts.slice(0, locationsAt + 2).join("/");
37 }
38 return parts.slice(0, Math.max(0, parts.length - 2)).join("/");
39 };
40
41 export const parseResourceName = (name: string, collection: string) => {
42 const parts = name.split("/").filter((part) => part.length > 0);
43 const collectionAt = parts.lastIndexOf(collection);
44 const locationsAt = parts.lastIndexOf("locations");
45 const projectsAt = parts.lastIndexOf("projects");
46 return {
47 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
48 location:
49 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
50 id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name),
51 parent:
52 collectionAt > 0
53 ? parts.slice(0, collectionAt).join("/")
54 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
55 };
56 };
57
58 export const expandParent = (
59 value: string,
60 project: string,
61 location: string,
62 collection: string,
63 ) => {
64 const trimmed = value.replace(/\/+$/, "");
65 if (trimmed.length === 0) {
66 return `${locationParent(project, location)}/${collection}`;
67 }
68 if (trimmed.includes("/")) return trimmed;
69 return `${locationParent(project, location)}/${collection}/${trimmed}`;
70 };
71
72 export const resourceNameOf = (parent: string, collection: string, id: string) => {
73 if (id.length === 0) return "";
74 if (id.includes(`/${collection}/`)) return id.replace(/\/+$/, "");
75 return `${parent}/${collection}/${lastSegment(id)}`;
76 };
77
78 export const sameText = (left: string | undefined, right: string | undefined) =>
79 (left ?? "") === (right ?? "");
80
81 const canonical = (value: unknown): unknown => {
82 if (value === undefined || value === null) return undefined;
83 if (typeof value === "boolean" || typeof value === "number") return value;
84 if (typeof value === "string") {
85 return value.length === 0 ? undefined : value;
86 }
87 if (Array.isArray(value)) {
88 const items = value.map(canonical).filter((item) => item !== undefined);
89 return items.length === 0 ? undefined : items;
90 }
91 if (typeof value === "object") {
92 const entries = Object.entries(value as Record<string, unknown>)
93 .map(([key, item]) => [key, canonical(item)] as const)
94 .filter(([, item]) => item !== undefined)
95 .sort(([left], [right]) => left.localeCompare(right));
96 if (entries.length === 0) return undefined;
97 return Object.fromEntries(entries);
98 }
99 return undefined;
100 };
101
102 const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
103
104 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
105
106 export const replaceOnIdentity = (input: {
107 previousId?: string;
108 nextId?: string;
109 previousLocation?: string;
110 nextLocation?: string;
111 previousParent?: string;
112 nextParent?: string;
113 extra?: boolean;
114 }) => {
115 const previousLocation =
116 input.previousLocation !== undefined ? normalizeLocation(input.previousLocation) : undefined;
117 const nextLocation =
118 input.nextLocation !== undefined ? normalizeLocation(input.nextLocation) : undefined;
119 const replace =
120 (input.extra ?? false) ||
121 (input.previousId !== undefined &&
122 input.nextId !== undefined &&
123 input.nextId !== input.previousId) ||
124 (previousLocation !== undefined &&
125 nextLocation !== undefined &&
126 previousLocation !== nextLocation) ||
127 (input.previousParent !== undefined &&
128 input.nextParent !== undefined &&
129 input.previousParent !== input.nextParent);
130 if (!replace) return undefined;
131 const samePhysical =
132 (previousLocation === undefined || previousLocation === nextLocation) &&
133 (input.previousParent === undefined || input.previousParent === input.nextParent) &&
134 input.previousId !== undefined &&
135 input.nextId === input.previousId;
136 return {
137 action: "replace" as const,
138 deleteFirst: samePhysical,
139 };
140 };
141
142 export const toPhysicalId = (
143 id: string,
144 explicit: string | undefined,
145 existing: string | undefined,
146 maxLength = MAX_ID_LENGTH,
147 ) =>
148 Effect.gen(function* () {
149 if (explicit !== undefined && explicit.length > 0) {
150 return lastSegment(explicit);
151 }
152 if (existing !== undefined && existing.length > 0) {
153 return existing;
154 }
155 return yield* createPhysicalName({
156 id,
157 maxLength,
158 lowercase: true,
159 });
160 });
161
162 /**
163 * Adaptive MT datasets and custom models only accept display names of
164 * A-Z, a-z, 0-9, and underscore, max 32 characters.
165 */
166 export const toRestrictedDisplayName = (
167 text: string,
168 maxLength = MAX_DISPLAY_NAME_LENGTH,
169 ): string => (text.replace(/[^A-Za-z0-9_]/g, "_").slice(0, maxLength) || "_").slice(0, maxLength);
170
171 export const retryTransient = <A, E extends { readonly _tag: string }, R>(
172 effect: Effect.Effect<A, E, R>,
173 ) =>
174 effect.pipe(
175 Effect.retry({
176 while: isTransientGcpError,
177 times: 8,
178 schedule: Schedule.exponential("250 millis"),
179 }),
180 );
181
182 export const waitUntilGone = <A, E extends { readonly _tag: string }, R>(
183 get: Effect.Effect<A | undefined, E, R>,
184 name: string,
185 ): Effect.Effect<void, E | ResourceStillExists, R> =>
186 get.pipe(
187 Effect.filterOrFail(
188 (value) => value === undefined,
189 () => new ResourceStillExists({ resourceName: name }),
190 ),
191 Effect.retry({
192 while: (error) => error._tag === "GCP.Translate.ResourceStillExists",
193 times: 10,
194 schedule: Schedule.spaced("2 seconds"),
195 }),
196 Effect.asVoid,
197 );