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

main
ts 324 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 type AttributeValues,
12 type AttributeValuesMap,
13 type Documentation,
14 MAX_DISPLAY_NAME_LENGTH,
15 createOwnership,
16 encodeContents,
17 encodeOwnershipLine,
18 hasOwnershipMarker,
19 listApis,
20 listChildResources,
21 listSpecs,
22 listVersions,
23 normalizeLocation,
24 openApiSpecType,
25 ownedByAlchemy,
26 parseOwnership,
27 parseResourceName,
28 replaceOnIdentity,
29 sameJson,
30 sameText,
31 toPhysicalId,
32 updateMaskOf,
33 } from "./internal.ts";
34
35 export type SpecContents = {
36 /**
37 * Spec document. Raw UTF-8 is base64-encoded before it is sent.
38 */
39 contents: string;
40 /**
41 * MIME type (`application/yaml`, `application/json`, …).
42 */
43 mimeType: string;
44 };
45
46 export type ApisVersionsSpecProps = {
47 /**
48 * Parent version. Full name
49 * `projects/{project}/locations/{location}/apis/{api}/versions/{version}`.
50 * Immutable — changing it replaces the spec.
51 */
52 version: string;
53 /**
54 * Spec id (the `{spec}` segment of
55 * `.../versions/{version}/specs/{spec}`). If omitted, a unique id is
56 * generated. Immutable — changing it replaces the spec.
57 */
58 specId?: string;
59 /**
60 * Location used when parsing parent names.
61 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
62 */
63 location?: string;
64 /**
65 * Display name (often the file name). Specs have no labels field, so
66 * Alchemy stamps ownership into this field for `list` / nuke.
67 */
68 displayName?: string;
69 /**
70 * URI of the spec in an external version-control system.
71 */
72 sourceUri?: string;
73 /**
74 * Spec document. Required on create when `sourceUri` is omitted.
75 * Input-only — subsequent updates send a new document when this field
76 * changes.
77 */
78 contents?: SpecContents;
79 /**
80 * Spec type. Defaults to the system OpenAPI enum when `contents` is
81 * provided.
82 */
83 specType?: AttributeValues;
84 /**
85 * OpenAPI parsing mode.
86 */
87 parsingMode?: "PARSING_MODE_UNSPECIFIED" | "RELAXED" | "STRICT" | (string & {});
88 /**
89 * External documentation.
90 */
91 documentation?: Documentation;
92 /**
93 * User-defined attributes keyed by attribute resource name.
94 */
95 attributes?: AttributeValuesMap;
96 };
97
98 export type ApisVersionsSpec = Resource<
99 "GCP.ApiHub.ApisVersionsSpec",
100 ApisVersionsSpecProps,
101 {
102 /** Full resource name. */
103 name: string;
104 /** Spec id (last path segment). */
105 specId: string;
106 /** Parent version resource name. */
107 version: string;
108 /** Project id. */
109 project: string;
110 /** Location id. */
111 location: string;
112 /** Display name with the Alchemy ownership prefix stripped. */
113 displayName: string | undefined;
114 /** Source URI. */
115 sourceUri: string | undefined;
116 /** Spec type. */
117 specType: AttributeValues | undefined;
118 /** Parsed spec details. */
119 details: apihub.GoogleCloudApihubV1SpecDetails | undefined;
120 /** Documentation. */
121 documentation: Documentation | undefined;
122 /** User-defined attributes. */
123 attributes: AttributeValuesMap | undefined;
124 /** RFC3339 creation timestamp. */
125 createTime: string | undefined;
126 /** RFC3339 last-update timestamp. */
127 updateTime: string | undefined;
128 },
129 never,
130 Providers
131 >;
132
133 /**
134 * A spec attached to an API Hub version. Adding an OpenAPI spec parses
135 * operations onto the version.
136 *
137 * Parent version and id are immutable. Display name, source URI, contents,
138 * spec type, and attributes update in place. Specs have no labels field —
139 * Alchemy stamps ownership into the display name.
140 *
141 * ### Creating a Spec
142 * **Example:** OpenAPI YAML
143 * ```typescript
144 * const spec = yield* GCP.ApiHub.ApisVersionsSpec("OpenApi", {
145 * version: version.name,
146 * displayName: "openapi.yaml",
147 * contents: {
148 * contents: "openapi: 3.0.0\ninfo:\n title: pets\n version: 1.0.0\npaths: {}\n",
149 * mimeType: "application/yaml",
150 * },
151 * });
152 * ```
153 *
154 * @resource
155 * @category ApiHub
156 */
157 export const ApisVersionsSpec = Resource<ApisVersionsSpec>("GCP.ApiHub.ApisVersionsSpec");
158
159 const resourceName = (version: string, specId: string) => `${version}/specs/${specId}`;
160
161 const toAttrs = (
162 spec: apihub.GoogleCloudApihubV1Spec,
163 project: string,
164 region: string,
165 ): ApisVersionsSpec["Attributes"] => {
166 const name = spec.name ?? "";
167 const parsed = parseResourceName(name, "specs", region);
168 return {
169 name,
170 specId: parsed.id,
171 version: parsed.parent,
172 project: parsed.project || project,
173 location: parsed.location,
174 displayName: parseOwnership(spec.displayName).text,
175 sourceUri: spec.sourceUri,
176 specType: spec.specType,
177 details: spec.details,
178 documentation: spec.documentation,
179 attributes: spec.attributes,
180 createTime: spec.createTime,
181 updateTime: spec.updateTime,
182 };
183 };
184
185 const getByName = (name: string) =>
186 name.length === 0
187 ? Effect.undefined
188 : apihub
189 .getProjectsLocationsApisVersionsSpecs({ name })
190 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
191
192 export const ApisVersionsSpecProvider = () =>
193 Provider.succeed(ApisVersionsSpec, {
194 stables: ["name", "specId", "version", "project", "location", "createTime"],
195
196 diff: Effect.fn(function* ({ news, olds, output }) {
197 if (!isResolved(news)) return undefined;
198 const env = yield* GcpEnvironment.current;
199 return replaceOnIdentity({
200 previousId: olds?.specId ?? output?.specId,
201 nextId: news.specId ?? olds?.specId ?? output?.specId,
202 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
203 nextLocation: normalizeLocation(
204 news.location ?? olds?.location ?? output?.location,
205 env.region,
206 ),
207 previousParent: olds?.version ?? output?.version,
208 nextParent: news.version ?? olds?.version ?? output?.version,
209 });
210 }),
211
212 read: Effect.fn(function* ({ id, olds, output }) {
213 const env = yield* GcpEnvironment.current;
214 const version = olds?.version ?? output?.version ?? "";
215 const specId = yield* toPhysicalId(id, olds?.specId, output?.specId);
216 const name = output?.name ?? resourceName(version, specId);
217 const existing = yield* getByName(name);
218 if (existing === undefined) return undefined;
219 const attrs = toAttrs(existing, env.project, env.region);
220 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
221 }),
222
223 list: () =>
224 Effect.gen(function* () {
225 const env = yield* GcpEnvironment.current;
226 const apis = yield* listApis(`projects/${env.project}/locations/${env.region}`);
227 const versions = yield* listChildResources(apis, listVersions);
228 const specs = yield* listChildResources(versions, listSpecs);
229 return specs
230 .filter((item) => hasOwnershipMarker(item.displayName))
231 .map((item) => toAttrs(item, env.project, env.region));
232 }),
233
234 reconcile: Effect.fn(function* ({ id, news, olds, output }) {
235 const env = yield* GcpEnvironment.current;
236 const version = news.version.replace(/\/+$/, "");
237 const specId = yield* toPhysicalId(id, news.specId, output?.specId);
238 const name = output?.name ?? resourceName(version, specId);
239 const ownership = yield* createOwnership(id);
240 const displayName = encodeOwnershipLine(
241 ownership,
242 news.displayName ?? specId,
243 MAX_DISPLAY_NAME_LENGTH,
244 );
245 const location = normalizeLocation(news.location ?? output?.location, env.region);
246 const specType =
247 news.specType ?? (news.contents ? openApiSpecType(env.project, location) : undefined);
248 const encodedContents =
249 news.contents === undefined
250 ? undefined
251 : {
252 contents: yield* encodeContents(news.contents.contents),
253 mimeType: news.contents.mimeType,
254 };
255
256 let current = yield* getByName(name);
257
258 if (current === undefined) {
259 const created = yield* apihub
260 .createProjectsLocationsApisVersionsSpecs({
261 parent: version,
262 specId,
263 body: {
264 displayName,
265 sourceUri: news.sourceUri,
266 contents: encodedContents,
267 specType,
268 parsingMode: news.parsingMode,
269 documentation: news.documentation,
270 attributes: news.attributes,
271 },
272 })
273 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
274 current = created ?? undefined;
275 }
276
277 if (current === undefined) {
278 return yield* new ApihubNotResolved({ resourceName: name });
279 }
280
281 const currentName = current.name ?? name;
282 const displayChanged = !sameText(current.displayName, displayName);
283 const sourceChanged = !sameText(current.sourceUri, news.sourceUri);
284 const contentsChanged =
285 news.contents !== undefined && !sameJson(news.contents, olds?.contents);
286 const typeChanged = specType !== undefined && !sameJson(current.specType, specType);
287 const attributesChanged = !sameJson(current.attributes, news.attributes);
288
289 if (
290 displayChanged ||
291 sourceChanged ||
292 contentsChanged ||
293 (contentsChanged && typeChanged) ||
294 attributesChanged
295 ) {
296 current = yield* apihub.patchProjectsLocationsApisVersionsSpecs({
297 name: currentName,
298 updateMask: updateMaskOf(
299 displayChanged ? "display_name" : undefined,
300 sourceChanged ? "source_uri" : undefined,
301 contentsChanged ? "contents" : undefined,
302 contentsChanged || typeChanged ? "spec_type" : undefined,
303 attributesChanged ? "attributes" : undefined,
304 ),
305 body: {
306 name: currentName,
307 displayName,
308 sourceUri: news.sourceUri,
309 contents: contentsChanged ? encodedContents : undefined,
310 specType: contentsChanged || typeChanged ? specType : undefined,
311 attributes: news.attributes,
312 },
313 });
314 }
315
316 return toAttrs(current, env.project, env.region);
317 }),
318
319 delete: Effect.fn(function* ({ output }) {
320 yield* apihub
321 .deleteProjectsLocationsApisVersionsSpecs({ name: output.name })
322 .pipe(Effect.catchTag("NotFound", () => Effect.void));
323 }),
324 });