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

main
ts 227 lines 8.59 KB
Raw
1 import * as translate from "@distilled.cloud/aws/translate";
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, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { readTranslateTags, syncTranslateTags } from "./internal.ts";
13
14 export interface TerminologyProps {
15 /**
16 * Name of the terminology — up to 256 characters of letters, digits, and
17 * hyphens (`^([A-Za-z0-9-]_?)+$`). If omitted, a unique name is generated
18 * from the app, stage, and logical ID. Changing the name replaces the
19 * terminology.
20 */
21 terminologyName?: string;
22 /**
23 * Description of the terminology.
24 */
25 description?: string;
26 /**
27 * The terminology file content — term pairs in the given `format`. For
28 * `CSV`, the first row is the language-code header (e.g. `en,es`) and each
29 * subsequent row is a term pair. Updatable in place — `ImportTerminology`
30 * is a true upsert (`MergeStrategy: OVERWRITE`); an overwrite takes up to
31 * 10 minutes to fully propagate to translations.
32 */
33 file: string;
34 /**
35 * Format of the terminology `file`: `CSV`, `TMX`, or `TSV`.
36 */
37 format: "CSV" | "TMX" | "TSV";
38 /**
39 * Directionality of the terminology: `UNI` (source→targets, the default)
40 * or `MULTI` (any listed language is a valid source).
41 * @default "UNI"
42 */
43 directionality?: "UNI" | "MULTI";
44 /**
45 * Id of the customer-managed KMS key used to encrypt the terminology.
46 * If omitted, Translate uses an AWS-owned key.
47 */
48 encryptionKeyId?: string;
49 /**
50 * User-defined tags for the terminology.
51 */
52 tags?: Record<string, string>;
53 }
54
55 export interface Terminology extends Resource<
56 "AWS.Translate.Terminology",
57 TerminologyProps,
58 {
59 /**
60 * Name of the terminology — pass it as `TerminologyNames` to
61 * `TranslateText`/`TranslateDocument` or batch translation jobs.
62 */
63 terminologyName: string;
64 /**
65 * ARN of the terminology, e.g.
66 * `arn:aws:translate:us-east-1:123456789012:terminology/brand-glossary`.
67 */
68 terminologyArn: string;
69 /** Source language code declared by the terminology file, e.g. `en`. */
70 sourceLanguageCode: string | undefined;
71 /** Target language codes declared by the terminology file. */
72 targetLanguageCodes: string[] | undefined;
73 /** Number of terms imported. */
74 termCount: number | undefined;
75 /** Number of terms skipped during import (malformed rows). */
76 skippedTermCount: number | undefined;
77 /** Size of the imported file in bytes. */
78 sizeBytes: number | undefined;
79 /** Directionality of the terminology (`UNI` or `MULTI`). */
80 directionality: string | undefined;
81 },
82 never,
83 Providers
84 > {}
85
86 /**
87 * An Amazon Translate custom terminology — a glossary of term pairs (CSV,
88 * TMX, or TSV) that pins how specific words and phrases (brand names,
89 * product names, domain jargon) are translated. Reference it by name from
90 * `TranslateText`, `TranslateDocument`, or batch translation jobs.
91 *
92 * ### Managing Terminologies
93 * **Example:** Import a CSV terminology
94 * ```typescript
95 * const glossary = yield* AWS.Translate.Terminology("BrandGlossary", {
96 * file: ["en,es", "Alchemy,Alquimia"].join("\n"),
97 * format: "CSV",
98 * });
99 * ```
100 *
101 * **Example:** Translate text with the terminology applied
102 * ```typescript
103 * const translateText = yield* AWS.Translate.TranslateText();
104 * const result = yield* translateText({
105 * Text: "Alchemy deploys infrastructure.",
106 * SourceLanguageCode: "en",
107 * TargetLanguageCode: "es",
108 * TerminologyNames: [glossary.terminologyName],
109 * });
110 * ```
111 *
112 * @resource
113 */
114 export const Terminology = Resource<Terminology>("AWS.Translate.Terminology");
115
116 const toAttributes = (props: translate.TerminologyProperties) => ({
117 terminologyName: props.Name!,
118 terminologyArn: props.Arn!,
119 sourceLanguageCode: props.SourceLanguageCode,
120 targetLanguageCodes: props.TargetLanguageCodes ? [...props.TargetLanguageCodes] : undefined,
121 termCount: props.TermCount,
122 skippedTermCount: props.SkippedTermCount,
123 sizeBytes: props.SizeBytes,
124 directionality: props.Directionality,
125 });
126
127 export const TerminologyProvider = () =>
128 Provider.effect(
129 Terminology,
130 Effect.gen(function* () {
131 const createName = Effect.fn(function* (id: string, props: TerminologyProps) {
132 // Translate names must match ^([A-Za-z0-9-]_?)+$ (≤ 256 chars);
133 // createPhysicalName's hyphenated output satisfies it directly.
134 return props.terminologyName ?? (yield* createPhysicalName({ id, maxLength: 256 }));
135 });
136
137 const getOne = Effect.fn(function* (name: string) {
138 return yield* translate
139 .getTerminology({ Name: name })
140 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
141 });
142
143 return {
144 stables: ["terminologyName", "terminologyArn"],
145
146 diff: Effect.fn(function* ({ id, olds, news }) {
147 if (!isResolved(news)) return undefined;
148 if ((yield* createName(id, olds)) !== (yield* createName(id, news))) {
149 return { action: "replace" } as const;
150 }
151 }),
152
153 read: Effect.fn(function* ({ id, olds, output }) {
154 const name =
155 output?.terminologyName ?? (yield* createName(id, olds ?? { file: "", format: "CSV" }));
156 const found = yield* getOne(name);
157 if (found?.TerminologyProperties === undefined) return undefined;
158 const attrs = toAttributes(found.TerminologyProperties);
159 const tags = yield* readTranslateTags(attrs.terminologyArn);
160 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
161 }),
162
163 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
164 const name = output?.terminologyName ?? (yield* createName(id, news));
165 const internalTags = yield* createInternalTags(id);
166 const desiredTags = { ...internalTags, ...news.tags };
167
168 // Observe — cloud state is authoritative.
169 const observed = yield* getOne(name);
170
171 // GetTerminology returns a presigned download location rather than
172 // the file content, so `olds` is the hint for skipping a no-op
173 // import; adoption (olds undefined) always imports to converge.
174 const changed =
175 olds === undefined ||
176 olds.file !== news.file ||
177 olds.format !== news.format ||
178 (olds.directionality ?? "UNI") !== (news.directionality ?? "UNI") ||
179 (olds.description ?? undefined) !== (news.description ?? undefined) ||
180 (olds.encryptionKeyId ?? undefined) !== (news.encryptionKeyId ?? undefined);
181
182 if (observed?.TerminologyProperties === undefined || changed) {
183 const bytes = yield* Effect.sync(() => new TextEncoder().encode(news.file));
184 yield* translate.importTerminology({
185 Name: name,
186 MergeStrategy: "OVERWRITE",
187 Description: news.description,
188 TerminologyData: {
189 // The File schema is a SensitiveBlob — the encoder unwraps
190 // the Redacted back to raw bytes on the wire.
191 File: Redacted.make(bytes),
192 Format: news.format,
193 Directionality: news.directionality,
194 },
195 EncryptionKey: news.encryptionKeyId
196 ? { Type: "KMS", Id: news.encryptionKeyId }
197 : undefined,
198 });
199 }
200
201 const final = yield* getOne(name);
202 const attrs = toAttributes(final!.TerminologyProperties!);
203 yield* session.note(name);
204 yield* syncTranslateTags(attrs.terminologyArn, desiredTags);
205 return attrs;
206 }),
207
208 delete: Effect.fn(function* ({ output }) {
209 // Idempotent — the terminology may already be gone.
210 yield* translate
211 .deleteTerminology({ Name: output.terminologyName })
212 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
213 }),
214
215 list: () =>
216 translate.listTerminologies.pages({}).pipe(
217 Stream.runCollect,
218 Effect.map((chunk) =>
219 Array.from(chunk)
220 .flatMap((page) => page.TerminologyPropertiesList ?? [])
221 .filter((props) => props.Name && props.Arn)
222 .map(toAttributes),
223 ),
224 ),
225 };
226 }),
227 );