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

main
ts 298 lines 9.26 KB
Raw
1 import * as firebase from "@distilled.cloud/gcp/firebase_v1beta1";
2 import { unownedUnlessPrevious } 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 hasOwnershipMarker,
11 lastSegment,
12 listAndroidApps,
13 ownedByAlchemy,
14 ownedDisplayName,
15 packageNameOf,
16 parseDisplayName,
17 projectParent,
18 ResourceNotResolved,
19 waitForOperation,
20 } from "./internal.ts";
21
22 export type AndroidAppProps = {
23 /**
24 * Canonical Android package name (`com.example.app`). Immutable —
25 * changing it replaces the app. If omitted, a unique
26 * `com.alchemy.test.{id}` name is generated.
27 */
28 packageName?: string;
29 /**
30 * User-assigned display name. Android apps have no labels field, so
31 * Alchemy stamps ownership into a `[alchemy …]` prefix and strips it
32 * from attributes.
33 */
34 displayName?: string;
35 /**
36 * SHA-1 certificate hashes.
37 */
38 sha1Hashes?: string[];
39 /**
40 * SHA-256 certificate hashes.
41 */
42 sha256Hashes?: string[];
43 /**
44 * Google-assigned API key uid. Firebase associates one automatically
45 * when omitted.
46 */
47 apiKeyId?: string;
48 };
49
50 export type AndroidApp = Resource<
51 "GCP.Firebase.AndroidApp",
52 AndroidAppProps,
53 {
54 /** Full resource name `projects/{project}/androidApps/{appId}`. */
55 name: string;
56 /** Firebase-assigned app id. */
57 appId: string;
58 /** Parent project id. */
59 projectId: string;
60 /** Android package name. */
61 packageName: string | undefined;
62 /** User display name with the Alchemy ownership prefix stripped. */
63 displayName: string | undefined;
64 /** SHA-1 hashes. */
65 sha1Hashes: string[] | undefined;
66 /** SHA-256 hashes. */
67 sha256Hashes: string[] | undefined;
68 /** Lifecycle state. */
69 state: string | undefined;
70 /** Associated API key uid. */
71 apiKeyId: string | undefined;
72 /** Server etag. */
73 etag: string | undefined;
74 /** Expire time when the app is in `DELETED`. */
75 expireTime: string | undefined;
76 },
77 never,
78 Providers
79 >;
80
81 /**
82 * A Firebase Android app in a Firebase project.
83 *
84 * Apps have no labels — Alchemy stamps ownership into `displayName`.
85 * `packageName` is immutable. Delete uses `androidApps.remove` with
86 * `immediate: true` so tests do not leave a 30-day tombstone.
87 *
88 * ### Creating an Android App
89 * **Example:** Generated package name
90 * ```typescript
91 * const app = yield* GCP.Firebase.AndroidApp("Mobile", {
92 * displayName: "mobile",
93 * });
94 * ```
95 *
96 * **Example:** Explicit package
97 * ```typescript
98 * const app = yield* GCP.Firebase.AndroidApp("Mobile", {
99 * packageName: "com.example.mobile",
100 * displayName: "mobile",
101 * });
102 * ```
103 *
104 * @resource
105 * @category Firebase
106 */
107 export const AndroidApp = Resource<AndroidApp>("GCP.Firebase.AndroidApp");
108
109 const toAttrs = (app: firebase.AndroidApp) => ({
110 name: app.name ?? "",
111 appId: app.appId ?? lastSegment(app.name ?? ""),
112 projectId: app.projectId ?? "",
113 packageName: app.packageName,
114 displayName: parseDisplayName(app.displayName).displayName,
115 sha1Hashes: app.sha1Hashes,
116 sha256Hashes: app.sha256Hashes,
117 state: app.state,
118 apiKeyId: app.apiKeyId,
119 etag: app.etag,
120 expireTime: app.expireTime,
121 });
122
123 const getByName = (name: string) =>
124 name.length === 0
125 ? Effect.undefined
126 : firebase
127 .getProjectsAndroidApps({ name })
128 .pipe(Effect.catchTag(["NotFound", "AndroidAppNotFound"], () => Effect.undefined));
129
130 const findOwned = (project: string, displayName: string, packageName?: string) =>
131 listAndroidApps(project).pipe(
132 Effect.map((apps) =>
133 apps.find(
134 (app) =>
135 app.displayName === displayName ||
136 (packageName !== undefined && app.packageName === packageName),
137 ),
138 ),
139 );
140
141 const sameList = (left: readonly string[] | undefined, right: readonly string[] | undefined) =>
142 JSON.stringify([...(left ?? [])].sort()) === JSON.stringify([...(right ?? [])].sort());
143
144 export const AndroidAppProvider = () =>
145 Provider.succeed(AndroidApp, {
146 stables: ["name", "appId", "projectId", "packageName"],
147
148 diff: Effect.fn(function* ({ news, olds, output }) {
149 if (!isResolved(news)) return undefined;
150 const previousPackage = olds?.packageName ?? output?.packageName;
151 if (
152 previousPackage !== undefined &&
153 news.packageName !== undefined &&
154 news.packageName !== previousPackage
155 ) {
156 return { action: "replace" as const, deleteFirst: true };
157 }
158 return undefined;
159 }),
160
161 read: Effect.fn(function* ({ id, olds, output, previous }) {
162 const env = yield* GcpEnvironment.current;
163 let existing = yield* getByName(output?.name ?? "");
164 if (existing === undefined) {
165 const displayName = yield* ownedDisplayName(
166 id,
167 olds?.displayName,
168 parseDisplayName(output?.displayName).displayName,
169 );
170 existing = yield* findOwned(
171 env.project,
172 displayName,
173 olds?.packageName ?? output?.packageName,
174 );
175 }
176 if (existing === undefined || existing.state === "DELETED") {
177 return undefined;
178 }
179 const attrs = toAttrs(existing);
180 return (yield* ownedByAlchemy(id, existing.displayName))
181 ? attrs
182 : unownedUnlessPrevious(attrs, previous, "name");
183 }),
184
185 list: () =>
186 Effect.gen(function* () {
187 const env = yield* GcpEnvironment.current;
188 const apps = yield* listAndroidApps(env.project);
189 return apps
190 .filter((app) => hasOwnershipMarker(app.displayName) && app.state !== "DELETED")
191 .map(toAttrs);
192 }),
193
194 reconcile: Effect.fn(function* ({ id, news, output }) {
195 const env = yield* GcpEnvironment.current;
196 const displayName = yield* ownedDisplayName(
197 id,
198 news.displayName,
199 parseDisplayName(output?.displayName).displayName,
200 );
201 const packageName = yield* packageNameOf(id, news.packageName, output?.packageName);
202
203 let current = yield* getByName(output?.name ?? "");
204 if (current === undefined) {
205 current = yield* findOwned(env.project, displayName, packageName);
206 }
207
208 if (current === undefined) {
209 const operation = yield* firebase
210 .createProjectsAndroidApps({
211 parent: projectParent(env.project),
212 body: {
213 packageName,
214 displayName,
215 sha1Hashes: news.sha1Hashes,
216 sha256Hashes: news.sha256Hashes,
217 apiKeyId: news.apiKeyId,
218 },
219 })
220 .pipe(
221 Effect.catchTag("Conflict", () =>
222 findOwned(env.project, displayName, packageName).pipe(
223 Effect.map((app) =>
224 app
225 ? ({
226 done: true,
227 response: { name: app.name },
228 } satisfies firebase.Operation)
229 : undefined,
230 ),
231 ),
232 ),
233 );
234 if (operation) {
235 const done = yield* waitForOperation(operation);
236 const name =
237 (typeof done.response?.name === "string" ? done.response.name : undefined) ??
238 output?.name ??
239 "";
240 current =
241 (yield* getByName(name)) ?? (yield* findOwned(env.project, displayName, packageName));
242 }
243 }
244
245 if (current === undefined) {
246 return yield* new ResourceNotResolved({
247 resourceName: output?.name ?? packageName,
248 });
249 }
250
251 const name = current.name ?? "";
252 const displayChanged = current.displayName !== displayName;
253 const sha1Changed =
254 news.sha1Hashes !== undefined && !sameList(current.sha1Hashes, news.sha1Hashes);
255 const sha256Changed =
256 news.sha256Hashes !== undefined && !sameList(current.sha256Hashes, news.sha256Hashes);
257 const apiKeyChanged = news.apiKeyId !== undefined && current.apiKeyId !== news.apiKeyId;
258 const updateMask = [
259 displayChanged ? "displayName" : undefined,
260 sha1Changed ? "sha1Hashes" : undefined,
261 sha256Changed ? "sha256Hashes" : undefined,
262 apiKeyChanged ? "apiKeyId" : undefined,
263 ].filter((field): field is string => field !== undefined);
264
265 if (updateMask.length > 0) {
266 current = yield* firebase.patchProjectsAndroidApps({
267 name,
268 updateMask: updateMask.join(","),
269 body: {
270 displayName,
271 sha1Hashes: news.sha1Hashes,
272 sha256Hashes: news.sha256Hashes,
273 apiKeyId: news.apiKeyId,
274 },
275 });
276 }
277
278 return toAttrs(current);
279 }),
280
281 delete: Effect.fn(function* ({ output }) {
282 if (!output.name) return;
283 const operation = yield* firebase
284 .removeProjectsAndroidApps({
285 name: output.name,
286 body: { immediate: true, allowMissing: true },
287 })
288 .pipe(Effect.catchTag(["NotFound", "AndroidAppNotFound"], () => Effect.undefined));
289 if (operation) {
290 yield* waitForOperation(operation).pipe(
291 Effect.catchIf(
292 (error) => error._tag === "GCP.OperationFailed" && error.code === 5,
293 () => Effect.void,
294 ),
295 );
296 }
297 }),
298 });