The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as androidenterprise from "@distilled.cloud/gcp/androidenterprise_v1"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import * as Config from "effect/Config"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as Option from "effect/Option"; |
| 6 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 7 | |
| 8 | export const DEFAULT_LOCALE = "en-US"; |
| 9 | export const DEFAULT_DISPLAY_MODE = "standalone"; |
| 10 | export const MAX_NAME_LENGTH = 256; |
| 11 | export const MAX_TITLE_LENGTH = 100; |
| 12 | |
| 13 | /** Whitespace/comma-separated list setting from the ConfigProvider (env by default). */ |
| 14 | const listSetting = (keys: readonly string[]) => |
| 15 | Effect.gen(function* () { |
| 16 | const values: string[] = []; |
| 17 | for (const key of keys) { |
| 18 | const raw = Option.getOrUndefined(yield* Config.option(Config.String(key)))?.trim(); |
| 19 | if (!raw) continue; |
| 20 | for (const part of raw.split(/[,\s]+/)) { |
| 21 | if (part.length > 0) values.push(part); |
| 22 | } |
| 23 | } |
| 24 | return values; |
| 25 | }); |
| 26 | |
| 27 | /** Enterprises swept by `list` (nuke): `GCP_ANDROIDENTERPRISE_ENTERPRISE_IDS`. */ |
| 28 | const configuredEnterpriseIds = () => |
| 29 | listSetting([ |
| 30 | "GCP_ANDROIDENTERPRISE_ENTERPRISE_ID", |
| 31 | "GCP_ANDROIDENTERPRISE_ENTERPRISE_IDS", |
| 32 | "GCP_ANDROID_ENTERPRISE_ID", |
| 33 | ]); |
| 34 | |
| 35 | /** Domain whose enterprises `list` sweeps: `GCP_ANDROIDENTERPRISE_DOMAIN`. */ |
| 36 | const configuredDomain = () => |
| 37 | listSetting(["GCP_ANDROIDENTERPRISE_DOMAIN"]).pipe(Effect.map((values) => values[0] ?? "")); |
| 38 | |
| 39 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 40 | (left ?? "") === (right ?? ""); |
| 41 | |
| 42 | export const jsonEqual = (left: unknown, right: unknown) => |
| 43 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 44 | |
| 45 | export const sameStringList = ( |
| 46 | left: readonly string[] | undefined, |
| 47 | right: readonly string[] | undefined, |
| 48 | ) => jsonEqual([...(left ?? [])].slice().sort(), [...(right ?? [])].slice().sort()); |
| 49 | |
| 50 | const emptyList = <A>() => Effect.succeed([] as A[]); |
| 51 | |
| 52 | const isMissing = <E extends { readonly _tag: string }>( |
| 53 | error: E, |
| 54 | ): error is Extract<E, { readonly _tag: "NotFound" }> => error._tag === "NotFound"; |
| 55 | |
| 56 | export const catchMissing = <A, E extends { readonly _tag: string }, R>( |
| 57 | effect: Effect.Effect<A, E, R>, |
| 58 | ) => effect.pipe(Effect.catchIf(isMissing, () => Effect.undefined)); |
| 59 | |
| 60 | export const ignoreList = |
| 61 | <A>(fallback: A) => |
| 62 | <A1, E extends { readonly _tag: string }, R>( |
| 63 | self: Effect.Effect<A1, E, R>, |
| 64 | ): Effect.Effect<A1 | A, E, R> => |
| 65 | self.pipe(Effect.catchIf(isMissing, () => Effect.succeed(fallback))); |
| 66 | |
| 67 | const markerOf = (_labels: Record<string, string>, stack: string, stage: string, id: string) => |
| 68 | `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`; |
| 69 | |
| 70 | const fitMarker = (labels: Record<string, string>, maxLength: number) => { |
| 71 | let stack = labels[alchemyLabelKeys.stack] ?? "x"; |
| 72 | let stage = labels[alchemyLabelKeys.stage] ?? "x"; |
| 73 | let id = labels[alchemyLabelKeys.id] ?? "x"; |
| 74 | let marker = markerOf(labels, stack, stage, id); |
| 75 | while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) { |
| 76 | if (stack.length >= stage.length && stack.length >= id.length) { |
| 77 | stack = stack.slice(0, -1); |
| 78 | } else if (stage.length >= id.length) { |
| 79 | stage = stage.slice(0, -1); |
| 80 | } else { |
| 81 | id = id.slice(0, -1); |
| 82 | } |
| 83 | marker = markerOf(labels, stack, stage, id); |
| 84 | } |
| 85 | return marker.slice(0, maxLength); |
| 86 | }; |
| 87 | |
| 88 | export const encodeOwnershipLine = ( |
| 89 | labels: Record<string, string>, |
| 90 | text: string | undefined, |
| 91 | maxLength = MAX_NAME_LENGTH, |
| 92 | ): string => { |
| 93 | const trimmed = text?.replace(/[\r\n]+/g, " ").trim(); |
| 94 | if (!trimmed) return fitMarker(labels, maxLength); |
| 95 | const minMarker = 24; |
| 96 | const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker)); |
| 97 | const marker = fitMarker(labels, maxLength - reserved); |
| 98 | return `${marker} ${trimmed}`.slice(0, maxLength); |
| 99 | }; |
| 100 | |
| 101 | export const parseOwnership = ( |
| 102 | text: string | undefined, |
| 103 | ): { |
| 104 | labels: Record<string, string>; |
| 105 | text: string | undefined; |
| 106 | } => { |
| 107 | if (!text?.startsWith("[alchemy ")) { |
| 108 | return { labels: {}, text }; |
| 109 | } |
| 110 | const end = text.indexOf("]"); |
| 111 | if (end < 0) return { labels: {}, text }; |
| 112 | const labels: Record<string, string> = {}; |
| 113 | for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) { |
| 114 | const eq = part.indexOf("="); |
| 115 | if (eq > 0) { |
| 116 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 117 | } |
| 118 | } |
| 119 | const rest = text.slice(end + 1).replace(/^[\s\n]+/, ""); |
| 120 | return { labels, text: rest.length > 0 ? rest : undefined }; |
| 121 | }; |
| 122 | |
| 123 | export const hasOwnershipMarker = (text: string | undefined) => |
| 124 | Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-")); |
| 125 | |
| 126 | const prefixMatch = (expected: string, observed: string) => |
| 127 | expected === observed || expected.startsWith(observed) || observed.startsWith(expected); |
| 128 | |
| 129 | export const ownedByAlchemy = (id: string, text: string | undefined) => |
| 130 | Effect.gen(function* () { |
| 131 | const expected = yield* createInternalLabels(id); |
| 132 | const { labels } = parseOwnership(text); |
| 133 | if (!hasOwnershipMarker(text)) return false; |
| 134 | const exact = yield* hasAlchemyLabels(id, labels); |
| 135 | if (exact) return true; |
| 136 | return ( |
| 137 | prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") && |
| 138 | prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") && |
| 139 | prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "") |
| 140 | ); |
| 141 | }); |
| 142 | |
| 143 | export const toDisplayName = ( |
| 144 | id: string, |
| 145 | requested: string | undefined, |
| 146 | existing: string | undefined, |
| 147 | maxLength = MAX_NAME_LENGTH, |
| 148 | ) => |
| 149 | Effect.gen(function* () { |
| 150 | if (requested !== undefined && requested.length > 0) { |
| 151 | return requested.slice(0, maxLength); |
| 152 | } |
| 153 | if (existing !== undefined && existing.length > 0) { |
| 154 | return existing.slice(0, maxLength); |
| 155 | } |
| 156 | const generated = yield* createPhysicalName({ |
| 157 | id, |
| 158 | maxLength: Math.min(40, maxLength), |
| 159 | lowercase: true, |
| 160 | delimiter: "-", |
| 161 | }); |
| 162 | return /^[a-z]/.test(generated) ? generated : `a${generated}`.slice(0, maxLength); |
| 163 | }); |
| 164 | |
| 165 | /** |
| 166 | * Localized names as given (or one default-locale entry). Names are shown |
| 167 | * to device users, so no ownership marker is written into them. |
| 168 | */ |
| 169 | export const defaultNames = ( |
| 170 | names: readonly androidenterprise.LocalizedText[] | undefined, |
| 171 | fallback: string, |
| 172 | ): androidenterprise.LocalizedText[] => |
| 173 | names && names.length > 0 |
| 174 | ? names.map((entry) => ({ |
| 175 | ...entry, |
| 176 | locale: entry.locale ?? DEFAULT_LOCALE, |
| 177 | })) |
| 178 | : [{ locale: DEFAULT_LOCALE, text: fallback }]; |
| 179 | |
| 180 | export const publicNames = ( |
| 181 | names: readonly androidenterprise.LocalizedText[] | undefined, |
| 182 | ): androidenterprise.LocalizedText[] | undefined => { |
| 183 | if (names === undefined) return undefined; |
| 184 | return names.map((entry) => ({ |
| 185 | ...entry, |
| 186 | text: parseOwnership(entry.text).text, |
| 187 | })); |
| 188 | }; |
| 189 | |
| 190 | export const ownershipTextFromNames = ( |
| 191 | names: readonly androidenterprise.LocalizedText[] | undefined, |
| 192 | ) => names?.[0]?.text; |
| 193 | |
| 194 | /** Title as given; shown to device users, so it carries no marker. */ |
| 195 | export const defaultTitle = (title: string | undefined, fallback: string) => |
| 196 | (title ?? fallback).slice(0, MAX_TITLE_LENGTH); |
| 197 | |
| 198 | export const getPage = (enterpriseId: string, pageId: string) => |
| 199 | enterpriseId.length === 0 || pageId.length === 0 |
| 200 | ? Effect.undefined |
| 201 | : catchMissing(androidenterprise.getStorelayoutpages({ enterpriseId, pageId })); |
| 202 | |
| 203 | export const getCluster = (enterpriseId: string, pageId: string, clusterId: string) => |
| 204 | enterpriseId.length === 0 || pageId.length === 0 || clusterId.length === 0 |
| 205 | ? Effect.undefined |
| 206 | : catchMissing( |
| 207 | androidenterprise.getStorelayoutclusters({ |
| 208 | enterpriseId, |
| 209 | pageId, |
| 210 | clusterId, |
| 211 | }), |
| 212 | ); |
| 213 | |
| 214 | export const getWebapp = (enterpriseId: string, webAppId: string) => |
| 215 | enterpriseId.length === 0 || webAppId.length === 0 |
| 216 | ? Effect.undefined |
| 217 | : catchMissing(androidenterprise.getWebapps({ enterpriseId, webAppId })); |
| 218 | |
| 219 | export const listPagesAt = (enterpriseId: string) => |
| 220 | enterpriseId.length === 0 |
| 221 | ? emptyList<androidenterprise.StorePage>() |
| 222 | : androidenterprise.listStorelayoutpages({ enterpriseId }).pipe( |
| 223 | Effect.map((page) => page.page ?? []), |
| 224 | ignoreList([] as androidenterprise.StorePage[]), |
| 225 | ); |
| 226 | |
| 227 | export const listClustersAt = (enterpriseId: string, pageId: string) => |
| 228 | enterpriseId.length === 0 || pageId.length === 0 |
| 229 | ? emptyList<androidenterprise.StoreCluster>() |
| 230 | : androidenterprise.listStorelayoutclusters({ enterpriseId, pageId }).pipe( |
| 231 | Effect.map((page) => page.cluster ?? []), |
| 232 | ignoreList([] as androidenterprise.StoreCluster[]), |
| 233 | ); |
| 234 | |
| 235 | export const listWebappsAt = (enterpriseId: string) => |
| 236 | enterpriseId.length === 0 |
| 237 | ? emptyList<androidenterprise.WebApp>() |
| 238 | : androidenterprise.listWebapps({ enterpriseId }).pipe( |
| 239 | Effect.map((page) => page.webApp ?? []), |
| 240 | ignoreList([] as androidenterprise.WebApp[]), |
| 241 | ); |
| 242 | |
| 243 | const listEnterprisesAtDomain = (domain: string) => |
| 244 | domain.length === 0 |
| 245 | ? emptyList<androidenterprise.Enterprise>() |
| 246 | : androidenterprise.listEnterprises({ domain }).pipe( |
| 247 | Effect.map((page) => page.enterprise ?? []), |
| 248 | ignoreList([] as androidenterprise.Enterprise[]), |
| 249 | ); |
| 250 | |
| 251 | export const listEnterpriseIds = () => |
| 252 | Effect.gen(function* () { |
| 253 | const fromEnv = yield* configuredEnterpriseIds(); |
| 254 | const domain = yield* configuredDomain(); |
| 255 | if (domain.length === 0) return fromEnv; |
| 256 | const lookedUp = yield* listEnterprisesAtDomain(domain); |
| 257 | const ids = lookedUp |
| 258 | .map((enterprise) => enterprise.id) |
| 259 | .filter((id): id is string => id !== undefined && id.length > 0); |
| 260 | return [...new Set([...fromEnv, ...ids])]; |
| 261 | }); |
| 262 | |
| 263 | export const findOwnedPage = (id: string, enterpriseId: string) => |
| 264 | Effect.gen(function* () { |
| 265 | const pages = yield* listPagesAt(enterpriseId); |
| 266 | for (const page of pages) { |
| 267 | if (yield* ownedByAlchemy(id, ownershipTextFromNames(page.name))) { |
| 268 | return page; |
| 269 | } |
| 270 | } |
| 271 | return undefined; |
| 272 | }); |
| 273 | |
| 274 | export const findOwnedCluster = (id: string, enterpriseId: string, pageId?: string) => |
| 275 | Effect.gen(function* () { |
| 276 | const pageIds = pageId |
| 277 | ? [pageId] |
| 278 | : (yield* listPagesAt(enterpriseId)) |
| 279 | .map((page) => page.id) |
| 280 | .filter((value): value is string => value !== undefined); |
| 281 | for (const currentPageId of pageIds) { |
| 282 | const clusters = yield* listClustersAt(enterpriseId, currentPageId); |
| 283 | for (const cluster of clusters) { |
| 284 | if (yield* ownedByAlchemy(id, ownershipTextFromNames(cluster.name))) { |
| 285 | return { cluster, pageId: currentPageId }; |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | return undefined; |
| 290 | }); |
| 291 | |
| 292 | export const findOwnedWebapp = (id: string, enterpriseId: string) => |
| 293 | Effect.gen(function* () { |
| 294 | const webapps = yield* listWebappsAt(enterpriseId); |
| 295 | for (const webapp of webapps) { |
| 296 | if (yield* ownedByAlchemy(id, webapp.title)) { |
| 297 | return webapp; |
| 298 | } |
| 299 | } |
| 300 | return undefined; |
| 301 | }); |
| 302 | |
| 303 | export const listOwnedPages = () => |
| 304 | Effect.gen(function* () { |
| 305 | const enterpriseIds = yield* listEnterpriseIds(); |
| 306 | const pages = yield* Effect.forEach( |
| 307 | enterpriseIds, |
| 308 | (enterpriseId) => |
| 309 | listPagesAt(enterpriseId).pipe( |
| 310 | Effect.map((items) => |
| 311 | items |
| 312 | .filter((page) => hasOwnershipMarker(ownershipTextFromNames(page.name))) |
| 313 | .map((page) => ({ page, enterpriseId })), |
| 314 | ), |
| 315 | ), |
| 316 | { concurrency: 4 }, |
| 317 | ); |
| 318 | return pages.flat(); |
| 319 | }); |
| 320 | |
| 321 | export const listOwnedClusters = () => |
| 322 | Effect.gen(function* () { |
| 323 | const enterpriseIds = yield* listEnterpriseIds(); |
| 324 | const pages = yield* Effect.forEach( |
| 325 | enterpriseIds, |
| 326 | (enterpriseId) => |
| 327 | Effect.gen(function* () { |
| 328 | const storePages = yield* listPagesAt(enterpriseId); |
| 329 | const clusters = yield* Effect.forEach( |
| 330 | storePages, |
| 331 | (page) => |
| 332 | page.id |
| 333 | ? listClustersAt(enterpriseId, page.id).pipe( |
| 334 | Effect.map((items) => |
| 335 | items |
| 336 | .filter((cluster) => |
| 337 | hasOwnershipMarker(ownershipTextFromNames(cluster.name)), |
| 338 | ) |
| 339 | .map((cluster) => ({ |
| 340 | cluster, |
| 341 | enterpriseId, |
| 342 | pageId: page.id ?? "", |
| 343 | })), |
| 344 | ), |
| 345 | ) |
| 346 | : Effect.succeed( |
| 347 | [] as Array<{ |
| 348 | cluster: androidenterprise.StoreCluster; |
| 349 | enterpriseId: string; |
| 350 | pageId: string; |
| 351 | }>, |
| 352 | ), |
| 353 | { concurrency: 4 }, |
| 354 | ); |
| 355 | return clusters.flat(); |
| 356 | }), |
| 357 | { concurrency: 4 }, |
| 358 | ); |
| 359 | return pages.flat(); |
| 360 | }); |
| 361 | |
| 362 | export const listOwnedWebapps = () => |
| 363 | Effect.gen(function* () { |
| 364 | const enterpriseIds = yield* listEnterpriseIds(); |
| 365 | const pages = yield* Effect.forEach( |
| 366 | enterpriseIds, |
| 367 | (enterpriseId) => |
| 368 | listWebappsAt(enterpriseId).pipe( |
| 369 | Effect.map((items) => |
| 370 | items |
| 371 | .filter((webapp) => hasOwnershipMarker(webapp.title)) |
| 372 | .map((webapp) => ({ webapp, enterpriseId })), |
| 373 | ), |
| 374 | ), |
| 375 | { concurrency: 4 }, |
| 376 | ); |
| 377 | return pages.flat(); |
| 378 | }); |