@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 273 lines 8.58 KB
Raw
1 import * as apigee from "@distilled.cloud/gcp/apigee_v1";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import {
10 emptyOnMissing,
11 environmentIdOf,
12 environmentNameOf,
13 lastSegment,
14 listProjectEnvironments,
15 missingToUndefined,
16 organizationIdOf,
17 stripRevision,
18 toResourceId,
19 } from "./common.ts";
20
21 const MAX_NAME_LENGTH = 255;
22 const DEFAULT_TYPE = "js";
23
24 export type EnvironmentsResourcefileProps = {
25 /**
26 * Apigee organization id or `organizations/{org}`. Defaults to the
27 * current GCP project id. Immutable — changing it replaces the file.
28 */
29 organization?: string;
30 /**
31 * Environment id or `organizations/{org}/environments/{env}`. Immutable —
32 * changing it replaces the file.
33 */
34 environment: string;
35 /**
36 * Resource file type (`js`, `java`, `properties`, `py`, `xsl`, `wsdl`,
37 * `xsd`, …). Immutable — changing it replaces the file.
38 * @default "js"
39 */
40 fileType?: string;
41 /**
42 * File id. If omitted, a unique name is generated from the stack, stage,
43 * and logical id. Immutable — changing it replaces the file.
44 */
45 fileId?: string;
46 /**
47 * File contents as UTF-8 text. Sent as `google.api.HttpBody`.
48 */
49 content?: string;
50 };
51
52 export type EnvironmentsResourcefile = Resource<
53 "GCP.Apigee.EnvironmentsResourcefile",
54 EnvironmentsResourcefileProps,
55 {
56 /** Parent environment `organizations/{org}/environments/{env}`. */
57 parent: string;
58 /** File id. */
59 fileId: string;
60 /** Resource file type. */
61 fileType: string;
62 /** Apigee organization id. */
63 organizationId: string;
64 /** Environment id. */
65 environmentId: string;
66 },
67 never,
68 Providers
69 >;
70
71 /**
72 * An environment-scoped Apigee resource file (JavaScript, Java, XSL, …).
73 *
74 * Resource files have no labels. `list` enumerates files in Apigee
75 * environments mapped to this GCP project. Type and name are identity;
76 * `content` updates in place.
77 *
78 * ### Creating a JavaScript File
79 * **Example:** Generated name
80 * ```typescript
81 * const file = yield* GCP.Apigee.EnvironmentsResourcefile("Helper", {
82 * environment: "eval",
83 * fileType: "js",
84 * content: "function helper() { return 1; }",
85 * });
86 * ```
87 *
88 * @resource
89 * @category Apigee
90 */
91 export const EnvironmentsResourcefile = Resource<EnvironmentsResourcefile>(
92 "GCP.Apigee.EnvironmentsResourcefile",
93 );
94
95 export class EnvironmentsResourcefileNotResolved extends Data.TaggedError(
96 "GCP.Apigee.EnvironmentsResourcefileNotResolved",
97 )<{
98 parent: string;
99 fileType: string;
100 fileId: string;
101 }> {}
102
103 const fileTypeOf = (value: string | undefined) => value ?? DEFAULT_TYPE;
104
105 const toAttrs = (
106 fileId: string,
107 fileType: string,
108 organizationId: string,
109 environmentId: string,
110 ) => ({
111 parent: environmentNameOf(organizationId, environmentId),
112 fileId,
113 fileType,
114 organizationId,
115 environmentId,
116 });
117
118 const toHttpBody = (content: string) =>
119 Effect.sync((): apigee.GoogleApiHttpBody => ({
120 contentType: "application/octet-stream",
121 data: Buffer.from(content, "utf8").toString("base64"),
122 }));
123
124 const getById = (parent: string, type: string, name: string) =>
125 missingToUndefined(
126 apigee.getOrganizationsEnvironmentsResourcefiles({
127 parent,
128 type,
129 name,
130 }),
131 );
132
133 const listFiles = (parent: string, type?: string) =>
134 emptyOnMissing(
135 apigee.listOrganizationsEnvironmentsResourcefiles({
136 parent,
137 type,
138 }),
139 { resourceFile: [] as apigee.GoogleCloudApigeeV1ResourceFileList },
140 );
141
142 const hasFile = (
143 files: readonly apigee.GoogleCloudApigeeV1ResourceFile[] | undefined,
144 fileId: string,
145 fileType: string,
146 ) =>
147 (files ?? []).some(
148 (file) =>
149 lastSegment(stripRevision(file.name ?? "")) === fileId &&
150 (file.type === undefined || file.type === fileType),
151 );
152
153 export const EnvironmentsResourcefileProvider = () =>
154 Provider.succeed(EnvironmentsResourcefile, {
155 stables: ["parent", "fileId", "fileType", "organizationId", "environmentId"],
156
157 diff: Effect.fn(function* ({ news, olds, output }) {
158 if (!isResolved(news)) return undefined;
159 const previousId = olds?.fileId ?? output?.fileId;
160 const previousType = olds?.fileType ?? output?.fileType;
161 const previousOrg = olds?.organization ?? output?.organizationId;
162 const previousEnv = olds?.environment ?? output?.environmentId;
163 const idChanged =
164 previousId !== undefined && news.fileId !== undefined && news.fileId !== previousId;
165 const typeChanged =
166 previousType !== undefined &&
167 news.fileType !== undefined &&
168 fileTypeOf(news.fileType) !== fileTypeOf(previousType);
169 const orgChanged =
170 previousOrg !== undefined &&
171 news.organization !== undefined &&
172 organizationIdOf(news.organization, "") !== organizationIdOf(previousOrg, "");
173 const envChanged =
174 previousEnv !== undefined &&
175 environmentIdOf(news.environment) !== environmentIdOf(previousEnv);
176 if (idChanged || typeChanged || orgChanged || envChanged) {
177 return { action: "replace" as const, deleteFirst: false };
178 }
179 return undefined;
180 }),
181
182 read: Effect.fn(function* ({ id, olds, output }) {
183 const { project } = yield* GcpEnvironment.current;
184 const organizationId = organizationIdOf(
185 olds?.organization ?? output?.organizationId,
186 project,
187 );
188 const environmentId = environmentIdOf(olds?.environment ?? output?.environmentId ?? "");
189 const fileType = fileTypeOf(olds?.fileType ?? output?.fileType);
190 const fileId = yield* toResourceId(id, olds?.fileId, output?.fileId, {
191 maxLength: MAX_NAME_LENGTH,
192 });
193 const parent = output?.parent ?? environmentNameOf(organizationId, environmentId);
194 const existing = yield* getById(parent, fileType, fileId);
195 if (existing === undefined) return undefined;
196 return toAttrs(fileId, fileType, organizationId, environmentId);
197 }),
198
199 list: () =>
200 Effect.gen(function* () {
201 const environments = yield* listProjectEnvironments();
202 const found: EnvironmentsResourcefile["Attributes"][] = [];
203 for (const item of environments) {
204 const page = yield* listFiles(item.parent);
205 for (const file of page.resourceFile ?? []) {
206 if (!file.name) continue;
207 found.push(
208 toAttrs(
209 lastSegment(stripRevision(file.name)),
210 file.type ?? DEFAULT_TYPE,
211 item.organizationId,
212 item.environmentId,
213 ),
214 );
215 }
216 }
217 return found;
218 }),
219
220 reconcile: Effect.fn(function* ({ id, news, output }) {
221 const { project } = yield* GcpEnvironment.current;
222 const organizationId = organizationIdOf(news.organization, project);
223 const environmentId = environmentIdOf(news.environment);
224 const fileType = fileTypeOf(news.fileType);
225 const fileId = yield* toResourceId(id, news.fileId, output?.fileId, {
226 maxLength: MAX_NAME_LENGTH,
227 });
228 const parent = environmentNameOf(organizationId, environmentId);
229 const body = yield* toHttpBody(news.content ?? "");
230
231 let current = yield* getById(parent, fileType, fileId);
232
233 if (current === undefined) {
234 yield* apigee
235 .createOrganizationsEnvironmentsResourcefiles({
236 parent,
237 type: fileType,
238 name: fileId,
239 body,
240 })
241 .pipe(Effect.catchTag("Conflict", () => getById(parent, fileType, fileId)));
242 current = yield* getById(parent, fileType, fileId);
243 } else if (news.content !== undefined) {
244 yield* apigee.updateOrganizationsEnvironmentsResourcefiles({
245 parent,
246 type: fileType,
247 name: fileId,
248 body,
249 });
250 }
251
252 const listed = yield* listFiles(parent, fileType);
253 if (current === undefined && !hasFile(listed.resourceFile, fileId, fileType)) {
254 return yield* new EnvironmentsResourcefileNotResolved({
255 parent,
256 fileType,
257 fileId,
258 });
259 }
260
261 return toAttrs(fileId, fileType, organizationId, environmentId);
262 }),
263
264 delete: Effect.fn(function* ({ output }) {
265 yield* apigee
266 .deleteOrganizationsEnvironmentsResourcefiles({
267 parent: output.parent,
268 type: output.fileType,
269 name: output.fileId,
270 })
271 .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void));
272 }),
273 });