@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, 04:45 UTC

main
ts 310 lines 11.1 KB
Raw
1 import * as androiddeviceprovisioning from "@distilled.cloud/gcp/androiddeviceprovisioning_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 * as Stream from "effect/Stream";
7 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
8
9 export const CUSTOMER_PREFIX = "customers/";
10 export const MAX_CONFIGURATION_NAME_LENGTH = 100;
11 export const DEFAULT_IS_DEFAULT = false;
12 export const PROBE_CUSTOMER = "customers/0";
13 export const PROBE_CONFIGURATION = `${PROBE_CUSTOMER}/configurations/0`;
14 export const ANDROID_DEVICE_POLICY_PACKAGE = "com.google.android.apps.work.clouddpc";
15
16 export const lastSegment = (value: string) => {
17 const trimmed = value.replace(/\/+$/, "");
18 const parts = trimmed.split("/");
19 return parts[parts.length - 1] || trimmed;
20 };
21
22 export const parentOf = (name: string) => {
23 const parts = name.split("/").filter((part) => part.length > 0);
24 return parts.slice(0, -2).join("/");
25 };
26
27 export const normalizeName = (value: string) => value.replace(/\/+$/, "").trim();
28
29 export const toCustomerName = (value: string) => {
30 const trimmed = normalizeName(value);
31 if (trimmed.length === 0) return "";
32 const customersIdx = trimmed.lastIndexOf("/customers/");
33 if (customersIdx >= 0) {
34 const rest = trimmed.slice(customersIdx + "/customers/".length);
35 const id = rest.split("/")[0] ?? "";
36 return id.length > 0 ? `${CUSTOMER_PREFIX}${id}` : "";
37 }
38 if (trimmed.startsWith(CUSTOMER_PREFIX)) {
39 const id = trimmed.slice(CUSTOMER_PREFIX.length).split("/")[0] ?? "";
40 return id.length > 0 ? `${CUSTOMER_PREFIX}${id}` : trimmed;
41 }
42 return `${CUSTOMER_PREFIX}${lastSegment(trimmed)}`;
43 };
44
45 export const toConfigurationName = (parent: string, configurationId?: string) => {
46 if (configurationId !== undefined && configurationId.includes("/configurations/")) {
47 return normalizeName(configurationId);
48 }
49 const customer = toCustomerName(parent);
50 if (configurationId !== undefined && configurationId.length > 0 && customer.length > 0) {
51 return `${customer}/configurations/${lastSegment(configurationId)}`;
52 }
53 return "";
54 };
55
56 export const toDpcName = (parent: string, value: string) => {
57 const trimmed = normalizeName(value);
58 if (trimmed.includes("/dpcs/")) return trimmed;
59 const customer = toCustomerName(parent);
60 if (customer.length === 0 || trimmed.length === 0) return trimmed;
61 return `${customer}/dpcs/${lastSegment(trimmed)}`;
62 };
63
64 export const sameText = (left: string | undefined, right: string | undefined) =>
65 (left ?? "") === (right ?? "");
66
67 export const sameBoolean = (left: boolean | undefined, right: boolean | undefined) =>
68 left === right;
69
70 export const updateMaskOf = (...fields: Array<string | undefined>) =>
71 fields.filter((field): field is string => field !== undefined).join(",");
72
73 export const replaceOnIdentity = (input: {
74 previousParent?: string;
75 nextParent: string;
76 previousId?: string;
77 nextId?: string;
78 }) => {
79 if (
80 input.previousParent !== undefined &&
81 input.previousParent.length > 0 &&
82 toCustomerName(input.previousParent) !== toCustomerName(input.nextParent)
83 ) {
84 return { action: "replace" as const, deleteFirst: false };
85 }
86 if (
87 input.previousId !== undefined &&
88 input.nextId !== undefined &&
89 lastSegment(input.previousId) !== lastSegment(input.nextId)
90 ) {
91 return { action: "replace" as const, deleteFirst: false };
92 }
93 return undefined;
94 };
95
96 const markerOf = (stack: string, stage: string, id: string) =>
97 `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`;
98
99 const fitMarker = (labels: Record<string, string>, maxLength: number) => {
100 let stack = labels[alchemyLabelKeys.stack] ?? "x";
101 let stage = labels[alchemyLabelKeys.stage] ?? "x";
102 let id = labels[alchemyLabelKeys.id] ?? "x";
103 let marker = markerOf(stack, stage, id);
104 while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) {
105 if (stack.length >= stage.length && stack.length >= id.length) {
106 stack = stack.slice(0, -1);
107 } else if (stage.length >= id.length) {
108 stage = stage.slice(0, -1);
109 } else {
110 id = id.slice(0, -1);
111 }
112 marker = markerOf(stack, stage, id);
113 }
114 return marker.slice(0, maxLength);
115 };
116
117 export const encodeOwnershipLine = (
118 labels: Record<string, string>,
119 text: string | undefined,
120 maxLength = MAX_CONFIGURATION_NAME_LENGTH,
121 ): string => {
122 const trimmed = text?.replace(/[\r\n]+/g, " ").trim();
123 if (!trimmed) return fitMarker(labels, maxLength);
124 const minMarker = 24;
125 const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker));
126 const marker = fitMarker(labels, maxLength - reserved);
127 return `${marker} ${trimmed}`.slice(0, maxLength);
128 };
129
130 export const parseOwnership = (
131 text: string | undefined,
132 ): {
133 labels: Record<string, string>;
134 text: string | undefined;
135 } => {
136 if (!text?.startsWith("[alchemy ")) {
137 return { labels: {}, text };
138 }
139 const end = text.indexOf("]");
140 if (end < 0) return { labels: {}, text };
141 const labels: Record<string, string> = {};
142 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
143 const eq = part.indexOf("=");
144 if (eq > 0) {
145 labels[part.slice(0, eq)] = part.slice(eq + 1);
146 }
147 }
148 const rest = text.slice(end + 1).replace(/^[\s\n]+/, "");
149 return { labels, text: rest.length > 0 ? rest : undefined };
150 };
151
152 export const hasOwnershipMarker = (text: string | undefined) =>
153 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
154
155 const prefixMatch = (expected: string, observed: string) =>
156 expected === observed || expected.startsWith(observed) || observed.startsWith(expected);
157
158 export const ownedByAlchemy = (id: string, text: string | undefined) =>
159 Effect.gen(function* () {
160 const expected = yield* createInternalLabels(id);
161 const { labels } = parseOwnership(text);
162 if (!hasOwnershipMarker(text)) return false;
163 const exact = yield* hasAlchemyLabels(id, labels);
164 if (exact) return true;
165 return (
166 prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") &&
167 prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") &&
168 prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "")
169 );
170 });
171
172 export const ownershipLabels = (id: string) => createInternalLabels(id);
173
174 export const toDisplayName = (
175 id: string,
176 requested: string | undefined,
177 existing: string | undefined,
178 maxLength = MAX_CONFIGURATION_NAME_LENGTH,
179 ) =>
180 Effect.gen(function* () {
181 if (requested !== undefined && requested.length > 0) {
182 return requested.slice(0, maxLength);
183 }
184 if (existing !== undefined && existing.length > 0) {
185 return existing.slice(0, maxLength);
186 }
187 return yield* createPhysicalName({
188 id,
189 maxLength: Math.min(40, maxLength),
190 lowercase: true,
191 });
192 });
193
194 const emptyList = <A>() => Effect.succeed([] as A[]);
195
196 export const collectPages = <Page, A, E, R>(
197 pages: Stream.Stream<Page, E, R>,
198 items: (page: Page) => readonly A[] | undefined,
199 ) =>
200 pages.pipe(
201 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
202 Stream.runCollect,
203 Effect.map((chunk) => Array.from(chunk)),
204 );
205
206 export const getConfiguration = (name: string) =>
207 name.length === 0
208 ? Effect.undefined
209 : androiddeviceprovisioning
210 .getCustomersConfigurations({ name })
211 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
212
213 export const listConfigurationsAt = (parent: string) =>
214 parent.length === 0
215 ? emptyList<androiddeviceprovisioning.Configuration>()
216 : androiddeviceprovisioning
217 .listCustomersConfigurations({ parent: toCustomerName(parent) })
218 .pipe(
219 Effect.map((page) => page.configurations ?? []),
220 Effect.catchTag("NotFound", () => emptyList<androiddeviceprovisioning.Configuration>()),
221 );
222
223 export const listDpcsAt = (parent: string) =>
224 parent.length === 0
225 ? emptyList<androiddeviceprovisioning.Dpc>()
226 : androiddeviceprovisioning.listCustomersDpcs({ parent: toCustomerName(parent) }).pipe(
227 Effect.map((page) => page.dpcs ?? []),
228 Effect.catchTag("NotFound", () => emptyList<androiddeviceprovisioning.Dpc>()),
229 );
230
231 export const pickDpcName = (parent: string) =>
232 Effect.gen(function* () {
233 const dpcs = yield* listDpcsAt(parent);
234 const preferred = dpcs.find(
235 (dpc) => dpc.packageName === ANDROID_DEVICE_POLICY_PACKAGE && dpc.name,
236 );
237 return preferred?.name ?? dpcs.find((dpc) => dpc.name)?.name;
238 });
239
240 /** Whitespace/comma-separated list setting from the ConfigProvider (env by default). */
241 const listSetting = (keys: readonly string[]) =>
242 Effect.gen(function* () {
243 const values: string[] = [];
244 for (const key of keys) {
245 const raw = Option.getOrUndefined(yield* Config.option(Config.String(key)))?.trim();
246 if (!raw) continue;
247 for (const part of raw.split(/[,\s]+/)) {
248 if (part.length > 0) values.push(part);
249 }
250 }
251 return values;
252 });
253
254 /** Extra customers for `list` (nuke), e.g. `GCP_ANDROIDDEVICEPROVISIONING_CUSTOMERS`. */
255 export const configuredCustomers = () =>
256 listSetting([
257 "GCP_ANDROIDDEVICEPROVISIONING_CUSTOMER",
258 "GCP_ANDROIDDEVICEPROVISIONING_CUSTOMER_ID",
259 "GCP_ANDROIDDEVICEPROVISIONING_CUSTOMERS",
260 ]).pipe(
261 Effect.map((values) => [
262 ...new Set(values.map(toCustomerName).filter((name) => name.length > 0)),
263 ]),
264 );
265
266 export const listCustomersAt = () =>
267 collectPages(
268 androiddeviceprovisioning.listCustomers.pages({ pageSize: 100 }),
269 (page) => page.customers,
270 ).pipe(Effect.catchTag("NotFound", () => emptyList<androiddeviceprovisioning.Company>()));
271
272 export const listCustomerNames = () =>
273 Effect.gen(function* () {
274 const configured = yield* configuredCustomers();
275 const names = new Set(configured);
276 const listed = yield* listCustomersAt();
277 for (const company of listed) {
278 const fromName = company.name ? toCustomerName(company.name) : "";
279 const fromId = company.companyId ? toCustomerName(company.companyId) : "";
280 if (fromName.length > 0) names.add(fromName);
281 else if (fromId.length > 0) names.add(fromId);
282 }
283 return [...names];
284 });
285
286 export const findOwnedConfiguration = (id: string, parent: string) =>
287 Effect.gen(function* () {
288 const rows = yield* listConfigurationsAt(parent);
289 for (const row of rows) {
290 if (yield* ownedByAlchemy(id, row.configurationName)) {
291 return row;
292 }
293 }
294 return undefined;
295 });
296
297 export const findConfigurationByName = (configurationName: string, parent: string) =>
298 Effect.gen(function* () {
299 const rows = yield* listConfigurationsAt(parent);
300 return rows.find((row) => row.configurationName === configurationName);
301 });
302
303 export const listOwnedConfigurations = () =>
304 Effect.gen(function* () {
305 const parents = yield* listCustomerNames();
306 const pages = yield* Effect.forEach(parents, (parent) => listConfigurationsAt(parent), {
307 concurrency: 4,
308 });
309 return pages.flat().filter((row) => hasOwnershipMarker(row.configurationName));
310 });