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, 04:45 UTC
| 1 | import * as developerconnect from "@distilled.cloud/gcp/developerconnect_v1"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import { tagRecord } from "alchemy/Tags"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Schedule from "effect/Schedule"; |
| 7 | import * as Stream from "effect/Stream"; |
| 8 | import { stripInternalLabels } from "../Labels.ts"; |
| 9 | import { waitForOperation as waitForGcpOperation } from "../Operation.ts"; |
| 10 | |
| 11 | export const MAX_NAME_LENGTH = 63; |
| 12 | |
| 13 | export class ResourceNotResolved extends Data.TaggedError( |
| 14 | "GCP.DeveloperConnect.ResourceNotResolved", |
| 15 | )<{ |
| 16 | resourceName: string; |
| 17 | }> {} |
| 18 | |
| 19 | export class ResourceStillExists extends Data.TaggedError( |
| 20 | "GCP.DeveloperConnect.ResourceStillExists", |
| 21 | )<{ |
| 22 | resourceName: string; |
| 23 | }> {} |
| 24 | |
| 25 | export const lastSegment = (value: string) => { |
| 26 | const trimmed = value.replace(/\/+$/, ""); |
| 27 | const parts = trimmed.split("/"); |
| 28 | return parts[parts.length - 1] || trimmed; |
| 29 | }; |
| 30 | |
| 31 | export const rfc1035 = (name: string, fallback = "developerconnect"): string => { |
| 32 | let next = name |
| 33 | .toLowerCase() |
| 34 | .replace(/[^a-z0-9-]/g, "-") |
| 35 | .replace(/-+/g, "-") |
| 36 | .replace(/^-+|-+$/g, ""); |
| 37 | if (!/^[a-z]/.test(next)) next = `d${next}`; |
| 38 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 39 | if (next.length === 0) return fallback; |
| 40 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 41 | return next.slice(0, MAX_NAME_LENGTH); |
| 42 | }; |
| 43 | |
| 44 | export const normalizeLocation = (location: string | undefined, defaultLocation: string) => |
| 45 | lastSegment(location ?? defaultLocation).toLowerCase(); |
| 46 | |
| 47 | export const parentOf = (project: string, location: string) => |
| 48 | `projects/${project}/locations/${lastSegment(location).toLowerCase()}`; |
| 49 | |
| 50 | export const toPhysicalId = ( |
| 51 | id: string, |
| 52 | explicit: string | undefined, |
| 53 | existing: string | undefined, |
| 54 | fallback = "developerconnect", |
| 55 | ) => |
| 56 | Effect.gen(function* () { |
| 57 | if (explicit !== undefined) return rfc1035(explicit, fallback); |
| 58 | if (existing !== undefined) return existing; |
| 59 | return rfc1035( |
| 60 | yield* createPhysicalName({ |
| 61 | id, |
| 62 | maxLength: MAX_NAME_LENGTH, |
| 63 | lowercase: true, |
| 64 | }), |
| 65 | fallback, |
| 66 | ); |
| 67 | }); |
| 68 | |
| 69 | export const parseName = (name: string, collection: string, defaultLocation: string) => { |
| 70 | const parts = name.split("/").filter((part) => part.length > 0); |
| 71 | const collectionAt = parts.lastIndexOf(collection); |
| 72 | const locationsAt = parts.lastIndexOf("locations"); |
| 73 | const projectsAt = parts.lastIndexOf("projects"); |
| 74 | return { |
| 75 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 76 | location: |
| 77 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation, |
| 78 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 79 | parent: |
| 80 | collectionAt > 0 |
| 81 | ? parts.slice(0, collectionAt).join("/") |
| 82 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 83 | }; |
| 84 | }; |
| 85 | |
| 86 | export const expandParent = ( |
| 87 | value: string, |
| 88 | project: string, |
| 89 | location: string, |
| 90 | collection: string, |
| 91 | ) => { |
| 92 | if (value.includes("/")) return value.replace(/\/+$/, ""); |
| 93 | return `projects/${project}/locations/${location}/${collection}/${value}`; |
| 94 | }; |
| 95 | |
| 96 | export const userLabels = ( |
| 97 | labels: Record<string, string | undefined> | null | undefined, |
| 98 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 99 | |
| 100 | export const userAnnotations = ( |
| 101 | annotations: Record<string, string | undefined> | null | undefined, |
| 102 | ): Record<string, string> => tagRecord(annotations); |
| 103 | |
| 104 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 105 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 106 | |
| 107 | export const compact = <T extends Record<string, unknown>>(value: T): T => |
| 108 | Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined)) as T; |
| 109 | |
| 110 | export const canonical = (value: unknown): unknown => { |
| 111 | if (value === undefined || value === null) return undefined; |
| 112 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 113 | if (typeof value === "string") { |
| 114 | return value.length === 0 ? undefined : value; |
| 115 | } |
| 116 | if (Array.isArray(value)) { |
| 117 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 118 | return items.length === 0 ? undefined : items; |
| 119 | } |
| 120 | if (typeof value === "object") { |
| 121 | const entries = Object.entries(value as Record<string, unknown>) |
| 122 | .map(([key, item]) => [key, canonical(item)] as const) |
| 123 | .filter(([, item]) => item !== undefined) |
| 124 | .sort(([left], [right]) => left.localeCompare(right)); |
| 125 | if (entries.length === 0) return undefined; |
| 126 | return Object.fromEntries(entries); |
| 127 | } |
| 128 | return undefined; |
| 129 | }; |
| 130 | |
| 131 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 132 | |
| 133 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 134 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 135 | |
| 136 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 137 | (left ?? "") === (right ?? ""); |
| 138 | |
| 139 | export const sameBool = (left: boolean | undefined, right: boolean | undefined) => |
| 140 | (left ?? false) === (right ?? false); |
| 141 | |
| 142 | export const replaceOnIdentity = (input: { |
| 143 | previousId: string | undefined; |
| 144 | nextId: string | undefined; |
| 145 | previousLocation: string; |
| 146 | nextLocation: string; |
| 147 | extra?: boolean; |
| 148 | previousParent?: string; |
| 149 | nextParent?: string; |
| 150 | }) => { |
| 151 | const parentChanged = |
| 152 | (input.previousParent ?? "") !== "" && |
| 153 | (input.nextParent ?? "") !== "" && |
| 154 | (input.previousParent ?? "") !== (input.nextParent ?? ""); |
| 155 | const replace = |
| 156 | (input.extra ?? false) || |
| 157 | parentChanged || |
| 158 | (input.previousId !== undefined && |
| 159 | input.nextId !== undefined && |
| 160 | input.nextId !== input.previousId) || |
| 161 | input.previousLocation !== input.nextLocation; |
| 162 | if (!replace) return undefined; |
| 163 | const samePhysical = |
| 164 | input.previousLocation === input.nextLocation && |
| 165 | !parentChanged && |
| 166 | input.previousId !== undefined && |
| 167 | input.nextId === input.previousId; |
| 168 | return { |
| 169 | action: "replace" as const, |
| 170 | deleteFirst: samePhysical, |
| 171 | }; |
| 172 | }; |
| 173 | |
| 174 | /** |
| 175 | * Wait for a long-running operation. Connections and links settle within a few minutes. ALREADY_EXISTS (code 6) |
| 176 | * counts as success (create race); with `notFoundOk`, so does NOT_FOUND |
| 177 | * (code 5, delete race) and an operation that is already gone. |
| 178 | */ |
| 179 | export const waitForOperation = ( |
| 180 | operation: developerconnect.Operation, |
| 181 | options?: { notFoundOk?: boolean }, |
| 182 | ) => |
| 183 | waitForGcpOperation( |
| 184 | operation, |
| 185 | (name) => developerconnect.getProjectsLocationsOperations({ name }), |
| 186 | { budget: "10 minutes" }, |
| 187 | ).pipe( |
| 188 | Effect.catchIf( |
| 189 | (error) => |
| 190 | (error._tag === "GCP.OperationFailed" && |
| 191 | (error.code === 6 || (options?.notFoundOk === true && error.code === 5))) || |
| 192 | (options?.notFoundOk === true && error._tag === "NotFound"), |
| 193 | () => Effect.succeed(operation), |
| 194 | ), |
| 195 | ); |
| 196 | |
| 197 | export const waitUntilExists = <A, E, R>( |
| 198 | get: Effect.Effect<A | undefined, E, R>, |
| 199 | name: string, |
| 200 | ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> => |
| 201 | get.pipe( |
| 202 | Effect.filterOrFail( |
| 203 | (value): value is NonNullable<A> => value != null, |
| 204 | () => new ResourceNotResolved({ resourceName: name }), |
| 205 | ), |
| 206 | Effect.retry({ |
| 207 | while: (error) => error instanceof ResourceNotResolved, |
| 208 | times: 8, |
| 209 | schedule: Schedule.spaced("1 second"), |
| 210 | }), |
| 211 | ); |
| 212 | |
| 213 | export const waitUntilGone = <A, E, R>( |
| 214 | get: Effect.Effect<A | undefined, E, R>, |
| 215 | name: string, |
| 216 | ): Effect.Effect<void, E | ResourceStillExists, R> => |
| 217 | get.pipe( |
| 218 | Effect.filterOrFail( |
| 219 | (value) => value === undefined, |
| 220 | () => new ResourceStillExists({ resourceName: name }), |
| 221 | ), |
| 222 | Effect.retry({ |
| 223 | while: (error) => error instanceof ResourceStillExists, |
| 224 | times: 10, |
| 225 | schedule: Schedule.spaced("2 seconds"), |
| 226 | }), |
| 227 | Effect.asVoid, |
| 228 | ); |
| 229 | |
| 230 | export const listAtLocation = <A, E, R>( |
| 231 | project: string, |
| 232 | region: string, |
| 233 | list: (parent: string) => Effect.Effect<A[], E, R>, |
| 234 | ): Effect.Effect<A[], E, R> => |
| 235 | // Prefer the all-locations wildcard; fall back to the default region |
| 236 | // (whose error, if any, propagates). |
| 237 | list(`projects/${project}/locations/-`).pipe( |
| 238 | Effect.catch(() => list(`projects/${project}/locations/${region}`)), |
| 239 | ); |
| 240 | |
| 241 | export const listAtNested = <A, E, R>( |
| 242 | project: string, |
| 243 | nested: string, |
| 244 | region: string, |
| 245 | list: (parent: string) => Effect.Effect<A[], E, R>, |
| 246 | ): Effect.Effect<A[], E, R> => |
| 247 | // Prefer the all-locations wildcard; fall back to the default region |
| 248 | // (whose error, if any, propagates). |
| 249 | list(`projects/${project}/locations/-/${nested}`).pipe( |
| 250 | Effect.catch(() => list(`projects/${project}/locations/${region}/${nested}`)), |
| 251 | ); |
| 252 | |
| 253 | export const listLabeledPages = <Page, A, E, R>( |
| 254 | pages: Stream.Stream<Page, E, R>, |
| 255 | items: (page: Page) => readonly A[] | undefined, |
| 256 | labelsOf: (item: A) => Record<string, string | undefined> | null | undefined, |
| 257 | ): Effect.Effect<A[], E, R> => |
| 258 | pages.pipe( |
| 259 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 260 | Stream.filter((item) => hasAlchemyLabelMap(labelsOf(item))), |
| 261 | Stream.runCollect, |
| 262 | Effect.map((chunk) => Array.from(chunk)), |
| 263 | ); |
| 264 | |
| 265 | export const collectPages = <Page, Item, E, R>( |
| 266 | stream: Stream.Stream<Page, E, R>, |
| 267 | pick: (page: Page) => readonly Item[] | undefined, |
| 268 | ): Effect.Effect<Item[], E, R> => |
| 269 | stream.pipe( |
| 270 | Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])), |
| 271 | Stream.runCollect, |
| 272 | Effect.map((chunk) => Array.from(chunk)), |
| 273 | ); |