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

main
ts 326 lines 10.1 KB
Raw
1 import * as translate from "@distilled.cloud/gcp/translate_v3";
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 * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import {
10 DEFAULT_LOCATION,
11 ResourceNotResolved,
12 expandParent,
13 normalizeLocation,
14 parseResourceName,
15 replaceOnIdentity,
16 resourceNameOf,
17 retryTransient,
18 sameJson,
19 sameText,
20 waitUntilGone,
21 } from "./internal.ts";
22
23 export type GlossaryTermProps = {
24 /**
25 * Glossary term text.
26 */
27 text?: string;
28 /**
29 * BCP-47 language code for this term, for example `"en"`.
30 */
31 languageCode?: string;
32 };
33
34 export type GlossaryTermsPairProps = {
35 /**
36 * Source term matched in input text (unidirectional glossaries).
37 */
38 sourceTerm?: GlossaryTermProps;
39 /**
40 * Replacement term written into the translation.
41 */
42 targetTerm?: GlossaryTermProps;
43 };
44
45 export type GlossaryTermsSetProps = {
46 /**
47 * Equivalent terms that may replace each other (equivalent-term
48 * glossaries).
49 */
50 terms?: GlossaryTermProps[];
51 };
52
53 export type GlossariesGlossaryEntryProps = {
54 /**
55 * Parent glossary resource name
56 * `projects/{project}/locations/{location}/glossaries/{glossary}`
57 * or the glossary id (combined with `location`). Immutable — changing
58 * it replaces the entry.
59 */
60 parent: string;
61 /**
62 * Location used when `parent` is a bare glossary id. Immutable —
63 * changing it replaces the entry.
64 * @default "us-central1"
65 */
66 location?: string;
67 /**
68 * Server-assigned integer entry id (the `{entry}` segment of
69 * `.../glossaries/{glossary}/glossaryEntries/{entry}`). Leave blank on
70 * create. Immutable — changing it replaces the entry.
71 */
72 glossaryEntryId?: string;
73 /**
74 * Human-readable description.
75 */
76 description?: string;
77 /**
78 * Unidirectional source/target term pair. Mutually exclusive with
79 * `termsSet`.
80 */
81 termsPair?: GlossaryTermsPairProps;
82 /**
83 * Equivalent term set. Mutually exclusive with `termsPair`.
84 */
85 termsSet?: GlossaryTermsSetProps;
86 };
87
88 export type GlossariesGlossaryEntry = Resource<
89 "GCP.Translate.GlossariesGlossaryEntry",
90 GlossariesGlossaryEntryProps,
91 {
92 /** Full resource name `projects/{project}/locations/{location}/glossaries/{glossary}/glossaryEntries/{entry}`. */
93 name: string;
94 /** Entry id (last path segment). */
95 glossaryEntryId: string;
96 /** Parent glossary resource name. */
97 parent: string;
98 /** Project id. */
99 project: string;
100 /** Location id. */
101 location: string;
102 /** Description. */
103 description: string | undefined;
104 /** Unidirectional term pair, if set. */
105 termsPair: GlossaryTermsPairProps | undefined;
106 /** Equivalent term set, if set. */
107 termsSet: GlossaryTermsSetProps | undefined;
108 },
109 never,
110 Providers
111 >;
112
113 /**
114 * A single Cloud Translation glossary entry under a parent glossary.
115 *
116 * Without labels, ownership rests on the deterministic id: `read` reports a
117 * resource it finds without prior state as unowned (adopt it with `--adopt`).
118 * Entries are nested under a glossary and have no labels field. Term pair /
119 * term set and description update in place via patch. Parent glossary and
120 * entry id are identity — changing them replaces the entry.
121 *
122 * ### Creating an Entry
123 * **Example:** Unidirectional term pair
124 * ```typescript
125 * const entry = yield* GCP.Translate.GlossariesGlossaryEntry("Hello", {
126 * parent: glossary.name,
127 * termsPair: {
128 * sourceTerm: { languageCode: "en", text: "hello" },
129 * targetTerm: { languageCode: "es", text: "hola" },
130 * },
131 * });
132 * ```
133 *
134 * **Example:** Description
135 * ```typescript
136 * const entry = yield* GCP.Translate.GlossariesGlossaryEntry("Hello", {
137 * parent: glossary.name,
138 * description: "greeting",
139 * termsPair: {
140 * sourceTerm: { languageCode: "en", text: "hello" },
141 * targetTerm: { languageCode: "es", text: "hola" },
142 * },
143 * });
144 * ```
145 *
146 * ### Updating an Entry
147 * **Example:** Change the target term
148 * ```typescript
149 * // Same logical id as before; only the changed props differ.
150 * const entry = yield* GCP.Translate.GlossariesGlossaryEntry("Hello", {
151 * parent: glossary.name,
152 * termsPair: {
153 * sourceTerm: { languageCode: "en", text: "hello" },
154 * targetTerm: { languageCode: "es", text: "buenas" },
155 * },
156 * });
157 * ```
158 *
159 * @resource
160 * @category Translate
161 */
162 export const GlossariesGlossaryEntry = Resource<GlossariesGlossaryEntry>(
163 "GCP.Translate.GlossariesGlossaryEntry",
164 );
165
166 const toTerm = (term: translate.GlossaryTerm | undefined): GlossaryTermProps | undefined => {
167 if (term === undefined) return undefined;
168 return {
169 text: term.text,
170 languageCode: term.languageCode,
171 };
172 };
173
174 const toTermsPair = (
175 pair: translate.GlossaryTermsPair | undefined,
176 ): GlossaryTermsPairProps | undefined => {
177 if (pair === undefined) return undefined;
178 return {
179 sourceTerm: toTerm(pair.sourceTerm),
180 targetTerm: toTerm(pair.targetTerm),
181 };
182 };
183
184 const toTermsSet = (
185 set: translate.GlossaryTermsSet | undefined,
186 ): GlossaryTermsSetProps | undefined => {
187 if (set === undefined) return undefined;
188 return {
189 terms: (set.terms ?? []).map((term) => ({
190 text: term.text,
191 languageCode: term.languageCode,
192 })),
193 };
194 };
195
196 const toAttrs = (entry: translate.GlossaryEntry, project: string) => {
197 const name = entry.name ?? "";
198 const parsed = parseResourceName(name, "glossaryEntries");
199 return {
200 name,
201 glossaryEntryId: parsed.id,
202 parent: parsed.parent,
203 project: parsed.project || project,
204 location: parsed.location,
205 description: entry.description,
206 termsPair: toTermsPair(entry.termsPair),
207 termsSet: toTermsSet(entry.termsSet),
208 };
209 };
210
211 const getByName = (name: string) =>
212 name.length === 0
213 ? Effect.undefined
214 : translate
215 .getProjectsLocationsGlossariesGlossaryEntries({ name })
216 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
217
218 const glossaryParentOf = (project: string, location: string, parent: string) =>
219 expandParent(parent, project, location, "glossaries");
220
221 export const GlossariesGlossaryEntryProvider = () =>
222 Provider.succeed(GlossariesGlossaryEntry, {
223 stables: ["name", "glossaryEntryId", "parent", "project", "location"],
224
225 diff: Effect.fn(function* ({ news, olds, output }) {
226 if (!isResolved(news)) return undefined;
227 const previousParent = olds?.parent ?? output?.parent;
228 const nextParent = news.parent;
229 return replaceOnIdentity({
230 previousId: olds?.glossaryEntryId ?? output?.glossaryEntryId,
231 nextId: news.glossaryEntryId,
232 previousLocation: olds?.location ?? output?.location,
233 nextLocation: news.location ?? olds?.location ?? output?.location,
234 previousParent,
235 nextParent,
236 });
237 }),
238
239 read: Effect.fn(function* ({ olds, output }) {
240 const env = yield* GcpEnvironment.current;
241 const location = normalizeLocation(olds?.location ?? output?.location);
242 const parent = glossaryParentOf(env.project, location, olds?.parent ?? output?.parent ?? "");
243 const glossaryEntryId = olds?.glossaryEntryId ?? output?.glossaryEntryId;
244 const name =
245 output?.name ??
246 (glossaryEntryId ? resourceNameOf(parent, "glossaryEntries", glossaryEntryId) : "");
247 // Server-assigned id: only a recorded entry can be observed.
248 const existing = yield* getByName(name);
249 if (existing === undefined) return undefined;
250 const attrs = toAttrs(existing, env.project);
251 return output !== undefined ? attrs : Unowned(attrs);
252 }),
253
254 reconcile: Effect.fn(function* ({ news, output }) {
255 const env = yield* GcpEnvironment.current;
256 const location = normalizeLocation(news.location ?? output?.location ?? DEFAULT_LOCATION);
257 const parent = glossaryParentOf(env.project, location, news.parent);
258 if (
259 parent.length === 0 ||
260 parent.endsWith("/glossaries") ||
261 parent.includes("/locations/global/")
262 ) {
263 return yield* new ResourceNotResolved({
264 resourceName: parent || news.parent,
265 });
266 }
267 const glossaryEntryId = news.glossaryEntryId ?? output?.glossaryEntryId;
268 const name = glossaryEntryId
269 ? resourceNameOf(parent, "glossaryEntries", glossaryEntryId)
270 : (output?.name ?? "");
271 const description = news.description;
272 const hinted = output?.name ?? name;
273 const body: translate.GlossaryEntry = {
274 ...(name.length > 0 ? { name } : {}),
275 description,
276 termsPair: news.termsPair,
277 termsSet: news.termsSet,
278 };
279
280 let current = yield* getByName(hinted);
281
282 if (current === undefined) {
283 const created = yield* retryTransient(
284 translate.createProjectsLocationsGlossariesGlossaryEntries({
285 parent,
286 body,
287 }),
288 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
289 current = created ?? undefined;
290 }
291
292 if (current === undefined) {
293 return yield* new ResourceNotResolved({ resourceName: hinted || name });
294 }
295
296 const currentName = current.name ?? hinted;
297 const descriptionChanged = !sameText(current.description, description);
298 const pairChanged = !sameJson(current.termsPair, news.termsPair);
299 const setChanged = !sameJson(current.termsSet, news.termsSet);
300 if (descriptionChanged || pairChanged || setChanged) {
301 current = yield* retryTransient(
302 translate.patchProjectsLocationsGlossariesGlossaryEntries({
303 name: currentName,
304 body: {
305 name: currentName,
306 description,
307 termsPair: news.termsPair,
308 termsSet: news.termsSet,
309 },
310 }),
311 );
312 }
313
314 return toAttrs(current, env.project);
315 }),
316
317 delete: Effect.fn(function* ({ output }) {
318 if (!output.name) return;
319 yield* retryTransient(
320 translate.deleteProjectsLocationsGlossariesGlossaryEntries({
321 name: output.name,
322 }),
323 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
324 yield* waitUntilGone(getByName(output.name), output.name);
325 }),
326 });