@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 397 lines 13.4 KB
Raw
1 import * as recommendationengine from "@distilled.cloud/gcp/recommendationengine_v1beta1";
2 import { createPhysicalName } from "alchemy/PhysicalName";
3 import * as Effect from "effect/Effect";
4 import * as Stream from "effect/Stream";
5 import { alchemyLabelKeys } from "../Labels.ts";
6
7 export const DEFAULT_LOCATION = "global";
8 export const DEFAULT_CATALOG = "default_catalog";
9 export const DEFAULT_CATEGORY = "Alchemy";
10 export const MAX_ITEM_ID_LENGTH = 128;
11 export const LIST_LOCATIONS = ["global"] as const;
12
13 export type CategoryHierarchy = {
14 /** Category path from least to most specific. */
15 categories?: string[];
16 };
17
18 export type CatalogItemImage = {
19 /** Image URI. */
20 uri: string;
21 /** Height in pixels. */
22 height?: number;
23 /** Width in pixels. */
24 width?: number;
25 };
26
27 export type CatalogItemExactPrice = {
28 /** Display price. */
29 displayPrice?: number;
30 /** Price before discount. */
31 originalPrice?: number;
32 };
33
34 export type CatalogItemPriceRange = {
35 /** Minimum price. */
36 min?: number;
37 /** Maximum price. */
38 max?: number;
39 };
40
41 export type ProductCatalogItem = {
42 /** Cost map, e.g. `{ manufacturing: 45.5 }`. */
43 costs?: Record<string, number | undefined>;
44 /** Online stock state. */
45 stockState?:
46 | "STOCK_STATE_UNSPECIFIED"
47 | "IN_STOCK"
48 | "OUT_OF_STOCK"
49 | "PREORDER"
50 | "BACKORDER"
51 | (string & {});
52 /** Product images. */
53 images?: CatalogItemImage[];
54 /** Exact product price. */
55 exactPrice?: CatalogItemExactPrice;
56 /** Canonical product detail URI. */
57 canonicalProductUri?: string;
58 /** Price range for variants. */
59 priceRange?: CatalogItemPriceRange;
60 /** ISO-4217 currency code. Required when a price is set. */
61 currencyCode?: string;
62 /** Available quantity (int64 as a decimal string). */
63 availableQuantity?: string;
64 };
65
66 export type FeatureMap = {
67 /** Categorical features (`{ colors: { value: ["yellow"] } }`). */
68 categoricalFeatures?: Record<string, { value?: string[] } | undefined>;
69 /** Numerical features (`{ lengths_cm: { value: [2.3] } }`). */
70 numericalFeatures?: Record<string, { value?: number[] } | undefined>;
71 };
72
73 export type CatalogItem = recommendationengine.GoogleCloudRecommendationengineV1beta1CatalogItem;
74
75 const emptyList = <A>() => Effect.succeed([] as A[]);
76
77 export const lastSegment = (value: string) => {
78 const trimmed = value.replace(/\/+$/, "");
79 const parts = trimmed.split("/");
80 return parts[parts.length - 1] || trimmed;
81 };
82
83 export const parentOf = (name: string, collection?: string) => {
84 if (collection !== undefined) {
85 const marker = `/${collection}/`;
86 const index = name.lastIndexOf(marker);
87 return index >= 0 ? name.slice(0, index) : name;
88 }
89 const parts = name.split("/").filter((part) => part.length > 0);
90 return parts.slice(0, -2).join("/");
91 };
92
93 export const normalizeLocation = (location: string | undefined) =>
94 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
95
96 export const normalizeCatalog = (catalog: string | undefined) =>
97 lastSegment(catalog ?? DEFAULT_CATALOG);
98
99 export const locationParent = (project: string, location: string) =>
100 `projects/${project}/locations/${location}`;
101
102 export const catalogName = (project: string, location: string, catalogId: string) =>
103 `${locationParent(project, location)}/catalogs/${catalogId}`;
104
105 export const expandCatalog = (value: string | undefined, project: string, location: string) => {
106 const raw = (value ?? DEFAULT_CATALOG).replace(/\/+$/, "");
107 if (raw.includes("/")) return raw;
108 return catalogName(project, location, raw);
109 };
110
111 export const itemName = (catalog: string, catalogItemId: string) =>
112 `${catalog}/catalogItems/${catalogItemId}`;
113
114 export const parseResourceName = (name: string) => {
115 const parts = name.split("/").filter((part) => part.length > 0);
116 const itemsAt = Math.max(parts.lastIndexOf("catalogItems"), parts.lastIndexOf("catalogitems"));
117 const locationsAt = parts.lastIndexOf("locations");
118 const projectsAt = parts.lastIndexOf("projects");
119 const catalogsAt = parts.lastIndexOf("catalogs");
120 return {
121 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
122 location:
123 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
124 catalogId: catalogsAt >= 0 && parts[catalogsAt + 1] ? parts[catalogsAt + 1]! : DEFAULT_CATALOG,
125 catalog:
126 catalogsAt >= 0 ? parts.slice(0, catalogsAt + 2).join("/") : parentOf(name, "catalogItems"),
127 id: itemsAt >= 0 && parts[itemsAt + 1] ? parts[itemsAt + 1]! : lastSegment(name),
128 parent:
129 itemsAt > 0
130 ? parts.slice(0, itemsAt).join("/")
131 : parts.slice(0, Math.max(0, parts.length - 1)).join("/"),
132 };
133 };
134
135 export const catalogItemIdOf = (name: string, maxLength = MAX_ITEM_ID_LENGTH) => {
136 let next = name
137 .toLowerCase()
138 .replace(/[^a-z0-9_-]/g, "-")
139 .replace(/-+/g, "-")
140 .replace(/^-+|-+$/g, "");
141 if (!/^[a-z]/.test(next)) next = `c${next}`;
142 next = next.slice(0, maxLength).replace(/[-_]+$/g, "");
143 return next.length > 0 ? next : "catalogitem";
144 };
145
146 export const toPhysical = (
147 id: string,
148 explicit: string | undefined,
149 existing: string | undefined,
150 ) =>
151 Effect.gen(function* () {
152 if (explicit !== undefined && explicit.length > 0) return explicit;
153 if (existing !== undefined && existing.length > 0) return existing;
154 return catalogItemIdOf(
155 yield* createPhysicalName({
156 id,
157 maxLength: MAX_ITEM_ID_LENGTH,
158 lowercase: true,
159 }),
160 );
161 });
162
163 const parseOwnershipMarker = (text: string) => {
164 const labels: Record<string, string> = {};
165 const end = text.indexOf("]");
166 if (end < 0) return { labels, rest: text };
167 for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) {
168 const eq = part.indexOf("=");
169 if (eq > 0) {
170 labels[part.slice(0, eq)] = part.slice(eq + 1);
171 }
172 }
173 return { labels, rest: text.slice(end + 1) };
174 };
175
176 const parseCompactMarker = (text: string) => {
177 const end = text.indexOf("]");
178 if (!text.startsWith("[alc ") || end < 0) {
179 return { labels: {} as Record<string, string>, rest: text };
180 }
181 const parts = text.slice("[alc ".length, end).split("|");
182 const labels: Record<string, string> = {};
183 if (parts[0]) labels[alchemyLabelKeys.stack] = parts[0];
184 if (parts[1]) labels[alchemyLabelKeys.stage] = parts[1];
185 if (parts[2]) labels[alchemyLabelKeys.id] = parts[2];
186 return { labels, rest: text.slice(end + 1) };
187 };
188
189 export const parseOwnership = (
190 text: string | undefined,
191 ): {
192 labels: Record<string, string>;
193 text: string | undefined;
194 } => {
195 if (!text) return { labels: {}, text };
196 const compactAt = text.indexOf("[alc ");
197 const verboseAt = text.indexOf("[alchemy ");
198 if (verboseAt >= 0 && (compactAt < 0 || verboseAt <= compactAt)) {
199 const before = text.slice(0, verboseAt).trim();
200 const parsed = parseOwnershipMarker(text.slice(verboseAt));
201 const after = parsed.rest.replace(/^[\s\n]+/, "");
202 const combined = [before, after].filter((part) => part.length > 0).join(" ");
203 return {
204 labels: parsed.labels,
205 text: combined.length > 0 ? combined : undefined,
206 };
207 }
208 if (compactAt >= 0) {
209 const before = text.slice(0, compactAt).trim();
210 const parsed = parseCompactMarker(text.slice(compactAt));
211 const after = parsed.rest.replace(/^[\s\n]+/, "");
212 const combined = [before, after].filter((part) => part.length > 0).join(" ");
213 return {
214 labels: parsed.labels,
215 text: combined.length > 0 ? combined : undefined,
216 };
217 }
218 return { labels: {}, text };
219 };
220
221 export const hasOwnershipMarker = (text: string | undefined) =>
222 Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"));
223
224 export const canonical = (value: unknown): unknown => {
225 if (value === undefined || value === null) return undefined;
226 if (typeof value === "boolean" || typeof value === "number") return value;
227 if (typeof value === "string") {
228 return value.length === 0 ? undefined : value;
229 }
230 if (Array.isArray(value)) {
231 const items = value.map(canonical).filter((item) => item !== undefined);
232 return items.length === 0 ? undefined : items;
233 }
234 if (typeof value === "object") {
235 const entries = Object.entries(value as Record<string, unknown>)
236 .map(([key, item]) => [key, canonical(item)] as const)
237 .filter(([, item]) => item !== undefined)
238 .sort(([left], [right]) => left.localeCompare(right));
239 if (entries.length === 0) return undefined;
240 return Object.fromEntries(entries);
241 }
242 return undefined;
243 };
244
245 export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
246
247 export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right);
248
249 export const sameStringList = (
250 left: readonly string[] | undefined,
251 right: readonly string[] | undefined,
252 ) => fingerprint([...(left ?? [])].sort()) === fingerprint([...(right ?? [])].sort());
253
254 export const sameText = (left: string | undefined, right: string | undefined) =>
255 (left ?? "") === (right ?? "");
256
257 export const updateMaskOf = (...fields: Array<string | undefined>) =>
258 fields.filter((field): field is string => field !== undefined).join(",");
259
260 export const replaceOnIdentity = (input: {
261 previousId?: string;
262 nextId?: string;
263 previousParent?: string;
264 nextParent?: string;
265 }) => {
266 const idChanged =
267 input.previousId !== undefined &&
268 input.nextId !== undefined &&
269 input.previousId !== input.nextId;
270 const parentChanged =
271 (input.previousParent ?? "") !== "" &&
272 (input.nextParent ?? "") !== "" &&
273 (input.previousParent ?? "") !== (input.nextParent ?? "");
274 if (!idChanged && !parentChanged) return undefined;
275 return {
276 action: "replace" as const,
277 deleteFirst: false,
278 };
279 };
280
281 export const collectPages = <Page, Item, E, R>(
282 pages: Stream.Stream<Page, E, R>,
283 items: (page: Page) => readonly Item[] | null | undefined,
284 ) =>
285 pages.pipe(
286 Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])),
287 Stream.runCollect,
288 Effect.map((chunk) => Array.from(chunk) as Item[]),
289 );
290
291 export const listCatalogs = (project: string, location: string) =>
292 collectPages(
293 recommendationengine.listProjectsLocationsCatalogs.pages({
294 parent: locationParent(project, location),
295 pageSize: 100,
296 }),
297 (page) => page.catalogs,
298 ).pipe(
299 Effect.catchTag("NotFound", () =>
300 emptyList<recommendationengine.GoogleCloudRecommendationengineV1beta1Catalog>(),
301 ),
302 );
303
304 export const listProjectCatalogs = (project: string) =>
305 Effect.forEach(LIST_LOCATIONS, (location) => listCatalogs(project, location), {
306 concurrency: 2,
307 }).pipe(
308 Effect.map((groups) => {
309 const seen = new Set<string>();
310 const catalogs: recommendationengine.GoogleCloudRecommendationengineV1beta1Catalog[] = [];
311 for (const catalog of groups.flat()) {
312 const name = catalog.name ?? "";
313 if (name.length === 0 || seen.has(name)) continue;
314 seen.add(name);
315 catalogs.push(catalog);
316 }
317 return catalogs;
318 }),
319 );
320
321 export const listCatalogItems = (parent: string) =>
322 parent.length === 0
323 ? emptyList<CatalogItem>()
324 : collectPages(
325 recommendationengine.listProjectsLocationsCatalogsCatalogItems.pages({
326 parent,
327 pageSize: 100,
328 }),
329 (page) => page.catalogItems,
330 ).pipe(Effect.catchTag("NotFound", () => emptyList<CatalogItem>()));
331
332 export const itemHasOwnership = (item: CatalogItem) =>
333 hasOwnershipMarker(item.description) || (item.tags ?? []).some((tag) => hasOwnershipMarker(tag));
334
335 export const getCatalogItem = (name: string) =>
336 name.length === 0
337 ? Effect.undefined
338 : recommendationengine
339 .getProjectsLocationsCatalogsCatalogItems({ name })
340 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
341
342 export const userTags = (tags: readonly string[] | undefined) =>
343 (tags ?? []).filter((tag) => !tag.includes("[alc ") && !tag.includes("[alchemy "));
344
345 export const hierarchiesOf = (
346 hierarchies:
347 | readonly recommendationengine.GoogleCloudRecommendationengineV1beta1CatalogItemCategoryHierarchy[]
348 | readonly CategoryHierarchy[]
349 | undefined,
350 ): CategoryHierarchy[] =>
351 (hierarchies ?? [])
352 .map((hierarchy) => ({
353 categories: [...(hierarchy.categories ?? [])],
354 }))
355 .filter((hierarchy) => (hierarchy.categories?.length ?? 0) > 0);
356
357 export const defaultHierarchies = (): CategoryHierarchy[] => [{ categories: [DEFAULT_CATEGORY] }];
358
359 export const imagesOf = (
360 images:
361 | readonly recommendationengine.GoogleCloudRecommendationengineV1beta1Image[]
362 | readonly CatalogItemImage[]
363 | undefined,
364 ): CatalogItemImage[] =>
365 (images ?? [])
366 .filter((image) => (image.uri ?? "").length > 0)
367 .map((image) => ({
368 uri: image.uri ?? "",
369 height: image.height,
370 width: image.width,
371 }));
372
373 export const productMetadataOf = (
374 meta:
375 | recommendationengine.GoogleCloudRecommendationengineV1beta1ProductCatalogItem
376 | ProductCatalogItem
377 | undefined,
378 ): ProductCatalogItem | undefined =>
379 meta === undefined
380 ? undefined
381 : {
382 costs: meta.costs,
383 stockState: meta.stockState,
384 images: imagesOf(meta.images),
385 exactPrice: meta.exactPrice
386 ? {
387 displayPrice: meta.exactPrice.displayPrice,
388 originalPrice: meta.exactPrice.originalPrice,
389 }
390 : undefined,
391 canonicalProductUri: meta.canonicalProductUri,
392 priceRange: meta.priceRange
393 ? { min: meta.priceRange.min, max: meta.priceRange.max }
394 : undefined,
395 currencyCode: meta.currencyCode,
396 availableQuantity: meta.availableQuantity,
397 };