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

main
ts 309 lines 10.1 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 * as Stream from "effect/Stream";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 ApihubNotResolved,
12 encodeOwnership,
13 hasOwnershipMarker,
14 locationParent,
15 MAX_LONG_ID_LENGTH,
16 normalizeLocation,
17 ownedByAlchemy,
18 ownershipLabels,
19 parseName,
20 parseOwnership,
21 replaceOnIdentity,
22 sameJson,
23 sameStringList,
24 sameText,
25 toPhysicalId,
26 updateMaskOf,
27 } from "./internal.ts";
28
29 type AttributeValuesMap = apihub.GoogleCloudApihubV1AttributeValuesMap;
30 type Documentation = apihub.GoogleCloudApihubV1Documentation;
31
32 export type ExternalApiProps = {
33 /**
34 * External API id (the `{externalApi}` segment of
35 * `projects/{project}/locations/{location}/externalApis/{externalApi}`).
36 * If omitted, a unique id is generated. Immutable — changing it replaces
37 * the External API.
38 */
39 externalApiId?: string;
40 /**
41 * Location of the API Hub instance (`us-central1`, …). Immutable —
42 * changing it replaces the External API.
43 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
44 */
45 location?: string;
46 /**
47 * Display name. Max 63 characters.
48 */
49 displayName?: string;
50 /**
51 * Human-readable description. External APIs have no labels field, so
52 * Alchemy stamps ownership into a `[alchemy …]` prefix and strips it
53 * from attributes.
54 */
55 description?: string;
56 /**
57 * Documentation URI.
58 */
59 documentation?: Documentation;
60 /**
61 * Endpoints on which this API is accessible.
62 */
63 endpoints?: string[];
64 /**
65 * Paths served by this API.
66 */
67 paths?: string[];
68 /**
69 * User-defined attributes keyed by attribute resource name.
70 */
71 attributes?: AttributeValuesMap;
72 };
73
74 export type ExternalApi = Resource<
75 "GCP.ApiHub.ExternalApi",
76 ExternalApiProps,
77 {
78 /** Full resource name. */
79 name: string;
80 /** External API id (last path segment). */
81 externalApiId: string;
82 /** Project id. */
83 project: string;
84 /** Location id. */
85 location: string;
86 /** Display name. */
87 displayName: string | undefined;
88 /** User description with the Alchemy ownership prefix stripped. */
89 description: string | undefined;
90 /** Documentation. */
91 documentation: Documentation | undefined;
92 /** Endpoints. */
93 endpoints: string[];
94 /** Paths. */
95 paths: string[];
96 /** User-defined attributes. */
97 attributes: AttributeValuesMap | undefined;
98 /** RFC3339 creation timestamp. */
99 createTime: string | undefined;
100 /** RFC3339 last-update timestamp. */
101 updateTime: string | undefined;
102 },
103 never,
104 Providers
105 >;
106
107 /**
108 * An API Hub External API — a third-party API modeled so it can be
109 * referenced from dependencies.
110 *
111 * External APIs have no labels, so Alchemy stamps ownership into the
112 * description for `list` / nuke. Location and id are identity — changing
113 * them replaces the resource. Display name, description, documentation,
114 * endpoints, and paths update in place.
115 *
116 * ### Creating an External API
117 * **Example:** Generated id
118 * ```typescript
119 * const stripe = yield* GCP.ApiHub.ExternalApi("Stripe", {
120 * displayName: "Stripe",
121 * endpoints: ["https://api.stripe.com"],
122 * paths: ["/v1/charges"],
123 * });
124 * ```
125 *
126 * **Example:** Named External API
127 * ```typescript
128 * const stripe = yield* GCP.ApiHub.ExternalApi("Stripe", {
129 * externalApiId: "stripe-prod",
130 * displayName: "Stripe",
131 * description: "payments",
132 * endpoints: ["https://api.stripe.com"],
133 * });
134 * ```
135 *
136 * ### Updating an External API
137 * **Example:** Change description and paths
138 * ```typescript
139 * const stripe = yield* GCP.ApiHub.ExternalApi("Stripe", {
140 * displayName: "Stripe",
141 * description: "payments (updated)",
142 * paths: ["/v1/charges", "/v1/customers"],
143 * });
144 * ```
145 *
146 * @resource
147 * @category ApiHub
148 */
149 export const ExternalApi = Resource<ExternalApi>("GCP.ApiHub.ExternalApi");
150
151 const resourceName = (project: string, location: string, externalApiId: string) =>
152 `${locationParent(project, location)}/externalApis/${externalApiId}`;
153
154 const toAttrs = (api: apihub.GoogleCloudApihubV1ExternalApi, project: string, region: string) => {
155 const name = api.name ?? "";
156 const parsed = parseName(name, "externalApis", region);
157 const { text } = parseOwnership(api.description);
158 return {
159 name,
160 externalApiId: parsed.id,
161 project: parsed.project || project,
162 location: parsed.location,
163 displayName: api.displayName,
164 description: text,
165 documentation: api.documentation,
166 endpoints: [...(api.endpoints ?? [])],
167 paths: [...(api.paths ?? [])],
168 attributes: api.attributes,
169 createTime: api.createTime,
170 updateTime: api.updateTime,
171 };
172 };
173
174 const getByName = (name: string) =>
175 name.length === 0
176 ? Effect.undefined
177 : apihub
178 .getProjectsLocationsExternalApis({ name })
179 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
180
181 const listAt = (parent: string, project: string, region: string) =>
182 apihub.listProjectsLocationsExternalApis.pages({ parent, pageSize: 1000 }).pipe(
183 Stream.flatMap((page) => Stream.fromIterable(page.externalApis ?? [])),
184 Stream.filter((item) => hasOwnershipMarker(item.description)),
185 Stream.map((item) => toAttrs(item, project, region)),
186 Stream.runCollect,
187 Effect.map((chunk) => Array.from(chunk)),
188 Effect.catchTag("NotFound", () => Effect.succeed([])),
189 );
190
191 export const ExternalApiProvider = () =>
192 Provider.succeed(ExternalApi, {
193 stables: ["name", "externalApiId", "project", "location", "createTime"],
194
195 diff: Effect.fn(function* ({ news, olds, output }) {
196 if (!isResolved(news)) return undefined;
197 const env = yield* GcpEnvironment.current;
198 return replaceOnIdentity({
199 previousId: olds?.externalApiId ?? output?.externalApiId,
200 nextId: news.externalApiId ?? olds?.externalApiId ?? output?.externalApiId,
201 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
202 nextLocation: normalizeLocation(
203 news.location ?? olds?.location ?? output?.location,
204 env.region,
205 ),
206 });
207 }),
208
209 read: Effect.fn(function* ({ id, olds, output }) {
210 const env = yield* GcpEnvironment.current;
211 const externalApiId = yield* toPhysicalId(
212 id,
213 olds?.externalApiId,
214 output?.externalApiId,
215 MAX_LONG_ID_LENGTH,
216 );
217 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
218 const name = output?.name ?? resourceName(env.project, location, externalApiId);
219 const existing = yield* getByName(name);
220 if (existing === undefined) return undefined;
221 const attrs = toAttrs(existing, env.project, env.region);
222 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
223 }),
224
225 list: () =>
226 Effect.gen(function* () {
227 const env = yield* GcpEnvironment.current;
228 return yield* listAt(locationParent(env.project, env.region), env.project, env.region);
229 }),
230
231 reconcile: Effect.fn(function* ({ id, news, output }) {
232 const env = yield* GcpEnvironment.current;
233 const location = normalizeLocation(news.location ?? output?.location, env.region);
234 const externalApiId = yield* toPhysicalId(
235 id,
236 news.externalApiId,
237 output?.externalApiId,
238 MAX_LONG_ID_LENGTH,
239 );
240 const name = resourceName(env.project, location, externalApiId);
241 const ownership = yield* ownershipLabels(id);
242 const description = encodeOwnership(ownership, news.description);
243 const displayName = (news.displayName ?? externalApiId).slice(0, 63);
244 const parent = locationParent(env.project, location);
245
246 let current = yield* getByName(output?.name ?? name);
247
248 if (current === undefined) {
249 const created = yield* apihub
250 .createProjectsLocationsExternalApis({
251 parent,
252 externalApiId,
253 body: {
254 displayName,
255 description,
256 documentation: news.documentation,
257 endpoints: news.endpoints,
258 paths: news.paths,
259 attributes: news.attributes,
260 },
261 })
262 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
263 current = created ?? (yield* getByName(name));
264 }
265
266 if (current === undefined) {
267 return yield* new ApihubNotResolved({ resourceName: name });
268 }
269
270 const currentName = current.name ?? name;
271 const observed = parseOwnership(current.description).text;
272 const displayChanged = !sameText(current.displayName, displayName);
273 const descriptionChanged = !sameText(observed, news.description);
274 const documentationChanged = !sameJson(current.documentation, news.documentation);
275 const endpointsChanged = !sameStringList(current.endpoints, news.endpoints);
276 const pathsChanged = !sameStringList(current.paths, news.paths);
277
278 const updateMask = updateMaskOf(
279 displayChanged ? "display_name" : undefined,
280 descriptionChanged ? "description" : undefined,
281 documentationChanged ? "documentation" : undefined,
282 endpointsChanged ? "endpoints" : undefined,
283 pathsChanged ? "paths" : undefined,
284 );
285
286 if (updateMask.length > 0) {
287 current = yield* apihub.patchProjectsLocationsExternalApis({
288 name: currentName,
289 updateMask,
290 body: {
291 name: currentName,
292 displayName,
293 description,
294 documentation: news.documentation,
295 endpoints: news.endpoints,
296 paths: news.paths,
297 },
298 });
299 }
300
301 return toAttrs(current, env.project, env.region);
302 }),
303
304 delete: Effect.fn(function* ({ output }) {
305 yield* apihub
306 .deleteProjectsLocationsExternalApis({ name: output.name })
307 .pipe(Effect.catchTag("NotFound", () => Effect.void));
308 }),
309 });