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

main
ts 325 lines 10.5 KB
Raw
1 import * as apihub from "@distilled.cloud/gcp/apihub_v1";
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 ApihubNotResolved,
11 createOwnership,
12 encodeOwnership,
13 hasOwnershipMarker,
14 listAttributes,
15 locationParent,
16 normalizeLocation,
17 ownedByAlchemy,
18 parseOwnership,
19 parseResourceName,
20 replaceOnIdentity,
21 sameJson,
22 sameText,
23 toPhysicalId,
24 updateMaskOf,
25 } from "./internal.ts";
26
27 export type AllowedValue = {
28 /** Allowed value id. Generated from the display name when omitted. */
29 id?: string;
30 /** Display name. Required. */
31 displayName: string;
32 /** Description of the allowed value. */
33 description?: string;
34 /** When true, the value cannot be updated or deleted. */
35 immutable?: boolean;
36 };
37
38 export type AttributeProps = {
39 /**
40 * Attribute id (the `{attribute}` segment of
41 * `projects/{project}/locations/{location}/attributes/{attribute}`). If
42 * omitted, a unique id is generated. Immutable — changing it replaces
43 * the attribute.
44 */
45 attributeId?: string;
46 /**
47 * Location (`us-central1`, …). Immutable — changing it replaces the
48 * attribute.
49 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
50 */
51 location?: string;
52 /**
53 * Display name. Required.
54 */
55 displayName: string;
56 /**
57 * Human-readable description. Attributes have no labels field, so
58 * Alchemy stamps ownership into a `[alchemy …]` prefix and strips it
59 * from attributes.
60 */
61 description?: string;
62 /**
63 * Data type. Immutable — changing it replaces the attribute.
64 */
65 dataType: "DATA_TYPE_UNSPECIFIED" | "ENUM" | "JSON" | "STRING" | "URI" | (string & {});
66 /**
67 * Resource this attribute can attach to. Immutable — changing it
68 * replaces the attribute.
69 */
70 scope:
71 | "SCOPE_UNSPECIFIED"
72 | "API"
73 | "VERSION"
74 | "SPEC"
75 | "API_OPERATION"
76 | "DEPLOYMENT"
77 | "DEPENDENCY"
78 | "DEFINITION"
79 | "EXTERNAL_API"
80 | "PLUGIN"
81 | (string & {});
82 /**
83 * Maximum number of values when associated with a resource (1-20).
84 * Cardinality can only be increased.
85 * @default 1
86 */
87 cardinality?: number;
88 /**
89 * Allowed values when `dataType` is `ENUM`.
90 */
91 allowedValues?: AllowedValue[];
92 };
93
94 export type Attribute = Resource<
95 "GCP.ApiHub.Attribute",
96 AttributeProps,
97 {
98 /** Full resource name. */
99 name: string;
100 /** Attribute id (last path segment). */
101 attributeId: string;
102 /** Project id. */
103 project: string;
104 /** Location id. */
105 location: string;
106 /** Display name. */
107 displayName: string | undefined;
108 /** User description with the Alchemy ownership prefix stripped. */
109 description: string | undefined;
110 /** Data type. */
111 dataType: string | undefined;
112 /** Scope. */
113 scope: string | undefined;
114 /** Cardinality. */
115 cardinality: number | undefined;
116 /** Allowed enum values. */
117 allowedValues: AllowedValue[];
118 /** Whether the attribute is mandatory. */
119 mandatory: boolean;
120 /** Definition type (`SYSTEM_DEFINED` or `USER_DEFINED`). */
121 definitionType: string | undefined;
122 /** RFC3339 creation timestamp. */
123 createTime: string | undefined;
124 /** RFC3339 last-update timestamp. */
125 updateTime: string | undefined;
126 },
127 never,
128 Providers
129 >;
130
131 /**
132 * A user-defined attribute in API Hub. System-defined attributes cannot
133 * be created or deleted through this resource.
134 *
135 * Location, id, data type, and scope are immutable. Display name,
136 * description, allowed values, and cardinality (increase only) update in
137 * place. Attributes have no labels field — Alchemy stamps ownership into
138 * the description.
139 *
140 * ### Creating an Attribute
141 * **Example:** String attribute on APIs
142 * ```typescript
143 * const attribute = yield* GCP.ApiHub.Attribute("OwnerTeam", {
144 * displayName: "owner-team",
145 * dataType: "STRING",
146 * scope: "API",
147 * });
148 * ```
149 *
150 * **Example:** Enum attribute
151 * ```typescript
152 * const attribute = yield* GCP.ApiHub.Attribute("Tier", {
153 * displayName: "tier",
154 * dataType: "ENUM",
155 * scope: "API",
156 * allowedValues: [
157 * { id: "gold", displayName: "gold" },
158 * { id: "silver", displayName: "silver" },
159 * ],
160 * });
161 * ```
162 *
163 * @resource
164 * @category ApiHub
165 */
166 export const Attribute = Resource<Attribute>("GCP.ApiHub.Attribute");
167
168 const resourceName = (project: string, location: string, attributeId: string) =>
169 `${locationParent(project, location)}/attributes/${attributeId}`;
170
171 const toAllowed = (
172 values: apihub.GoogleCloudApihubV1AllowedValueList | undefined,
173 ): AllowedValue[] =>
174 (values ?? [])
175 .filter((value) => (value.displayName ?? "").length > 0)
176 .map((value) => ({
177 id: value.id,
178 displayName: value.displayName!,
179 description: value.description,
180 immutable: value.immutable,
181 }));
182
183 const toAttrs = (
184 attribute: apihub.GoogleCloudApihubV1Attribute,
185 project: string,
186 region: string,
187 ) => {
188 const name = attribute.name ?? "";
189 const parsed = parseResourceName(name, "attributes", region);
190 return {
191 name,
192 attributeId: parsed.id,
193 project: parsed.project || project,
194 location: parsed.location,
195 displayName: attribute.displayName,
196 description: parseOwnership(attribute.description).text,
197 dataType: attribute.dataType,
198 scope: attribute.scope,
199 cardinality: attribute.cardinality,
200 allowedValues: toAllowed(attribute.allowedValues),
201 mandatory: attribute.mandatory === true,
202 definitionType: attribute.definitionType,
203 createTime: attribute.createTime,
204 updateTime: attribute.updateTime,
205 };
206 };
207
208 const getByName = (name: string) =>
209 name.length === 0
210 ? Effect.undefined
211 : apihub
212 .getProjectsLocationsAttributes({ name })
213 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
214
215 export const AttributeProvider = () =>
216 Provider.succeed(Attribute, {
217 stables: ["name", "attributeId", "project", "location", "dataType", "scope", "createTime"],
218
219 diff: Effect.fn(function* ({ news, olds, output }) {
220 if (!isResolved(news)) return undefined;
221 const env = yield* GcpEnvironment.current;
222 return replaceOnIdentity({
223 previousId: olds?.attributeId ?? output?.attributeId,
224 nextId: news.attributeId ?? olds?.attributeId ?? output?.attributeId,
225 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
226 nextLocation: normalizeLocation(
227 news.location ?? olds?.location ?? output?.location,
228 env.region,
229 ),
230 extra:
231 (news.dataType ?? olds?.dataType) !== (olds?.dataType ?? output?.dataType) ||
232 (news.scope ?? olds?.scope) !== (olds?.scope ?? output?.scope),
233 });
234 }),
235
236 read: Effect.fn(function* ({ id, olds, output }) {
237 const env = yield* GcpEnvironment.current;
238 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
239 const attributeId = yield* toPhysicalId(id, olds?.attributeId, output?.attributeId);
240 const name = output?.name ?? resourceName(env.project, location, attributeId);
241 const existing = yield* getByName(name);
242 if (existing === undefined) return undefined;
243 const attrs = toAttrs(existing, env.project, env.region);
244 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
245 }),
246
247 list: () =>
248 Effect.gen(function* () {
249 const env = yield* GcpEnvironment.current;
250 const items = yield* listAttributes(locationParent(env.project, env.region));
251 return items
252 .filter((item) => hasOwnershipMarker(item.description))
253 .map((item) => toAttrs(item, env.project, env.region));
254 }),
255
256 reconcile: Effect.fn(function* ({ id, news, output }) {
257 const env = yield* GcpEnvironment.current;
258 const location = normalizeLocation(news.location ?? output?.location, env.region);
259 const parent = locationParent(env.project, location);
260 const attributeId = yield* toPhysicalId(id, news.attributeId, output?.attributeId);
261 const name = output?.name ?? resourceName(env.project, location, attributeId);
262 const ownership = yield* createOwnership(id);
263 const description = encodeOwnership(ownership, news.description);
264 const allowedValues = news.allowedValues;
265 const cardinality = news.cardinality;
266
267 let current = yield* getByName(name);
268
269 if (current === undefined) {
270 const created = yield* apihub
271 .createProjectsLocationsAttributes({
272 parent,
273 attributeId,
274 body: {
275 displayName: news.displayName,
276 description,
277 dataType: news.dataType,
278 scope: news.scope,
279 cardinality,
280 allowedValues,
281 },
282 })
283 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
284 current = created ?? undefined;
285 }
286
287 if (current === undefined) {
288 return yield* new ApihubNotResolved({ resourceName: name });
289 }
290
291 const currentName = current.name ?? name;
292 const displayChanged = !sameText(current.displayName, news.displayName);
293 const descriptionChanged = !sameText(current.description, description);
294 const allowedChanged = !sameJson(toAllowed(current.allowedValues), allowedValues ?? []);
295 const cardinalityChanged =
296 cardinality !== undefined && (current.cardinality ?? 1) !== cardinality;
297
298 if (displayChanged || descriptionChanged || allowedChanged || cardinalityChanged) {
299 current = yield* apihub.patchProjectsLocationsAttributes({
300 name: currentName,
301 updateMask: updateMaskOf(
302 displayChanged ? "display_name" : undefined,
303 descriptionChanged ? "description" : undefined,
304 allowedChanged ? "allowed_values" : undefined,
305 cardinalityChanged ? "cardinality" : undefined,
306 ),
307 body: {
308 name: currentName,
309 displayName: news.displayName,
310 description,
311 allowedValues,
312 cardinality,
313 },
314 });
315 }
316
317 return toAttrs(current, env.project, env.region);
318 }),
319
320 delete: Effect.fn(function* ({ output }) {
321 yield* apihub
322 .deleteProjectsLocationsAttributes({ name: output.name })
323 .pipe(Effect.catchTag("NotFound", () => Effect.void));
324 }),
325 });