@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 364 lines 11.7 KB
Raw
1 import * as recommendationengine from "@distilled.cloud/gcp/recommendationengine_v1beta1";
2 import { Unowned } 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 Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 type CatalogItem,
12 type CategoryHierarchy,
13 type FeatureMap,
14 type ProductCatalogItem,
15 DEFAULT_LOCATION,
16 defaultHierarchies,
17 expandCatalog,
18 getCatalogItem,
19 hierarchiesOf,
20 itemHasOwnership,
21 itemName,
22 listCatalogItems,
23 listProjectCatalogs,
24 normalizeLocation,
25 parseOwnership,
26 parseResourceName,
27 productMetadataOf,
28 replaceOnIdentity,
29 sameJson,
30 sameStringList,
31 sameText,
32 toPhysical,
33 updateMaskOf,
34 userTags,
35 } from "./internal.ts";
36
37 export type {
38 CatalogItemExactPrice,
39 CatalogItemImage,
40 CatalogItemPriceRange,
41 CategoryHierarchy,
42 FeatureMap,
43 ProductCatalogItem,
44 } from "./internal.ts";
45
46 export type CatalogsCatalogItemProps = {
47 /**
48 * Parent catalog resource name
49 * `projects/{project}/locations/{location}/catalogs/{catalog}` or a
50 * catalog id (combined with `location`). Immutable — changing it
51 * replaces the catalog item.
52 * @default "default_catalog"
53 */
54 catalog?: string;
55 /**
56 * Location used when `catalog` is a bare id. Immutable.
57 * Recommendations AI catalogs live at `global`.
58 * @default "global"
59 */
60 location?: string;
61 /**
62 * Catalog item id (max 128 bytes). If omitted, a unique id is
63 * generated. Immutable — changing it replaces the item.
64 */
65 catalogItemId?: string;
66 /**
67 * Catalog item title (max 1 KiB). Defaults to the catalog item id.
68 */
69 title?: string;
70 /**
71 * Catalog item description (max 5 KiB).
72 */
73 description?: string;
74 /**
75 * Parallel category hierarchies. Required by the API. Defaults to a
76 * single `Alchemy` category.
77 * @default [{ categories: ["Alchemy"] }]
78 */
79 categoryHierarchies?: CategoryHierarchy[];
80 /**
81 * Filtering tags (max 1 KiB each).
82 */
83 tags?: string[];
84 /**
85 * Variant group identifier for prediction results (max 128 bytes).
86 */
87 itemGroupId?: string;
88 /**
89 * Deprecated language hint. The model detects language automatically.
90 */
91 languageCode?: string;
92 /**
93 * Retail product metadata (price, stock, images).
94 */
95 productMetadata?: ProductCatalogItem;
96 /**
97 * Extra categorical and numerical features for the recommendation
98 * model.
99 */
100 itemAttributes?: FeatureMap;
101 };
102
103 export type CatalogsCatalogItem = Resource<
104 "GCP.RecommendationEngine.CatalogsCatalogItem",
105 CatalogsCatalogItemProps,
106 {
107 /** Full resource name. */
108 name: string;
109 /** Catalog item id. */
110 catalogItemId: string;
111 /** Parent catalog resource name. */
112 catalog: string;
113 /** Project id. */
114 project: string;
115 /** Location id. */
116 location: string;
117 /** Title. */
118 title: string | undefined;
119 /** Description (a legacy Alchemy ownership prefix is stripped). */
120 description: string | undefined;
121 /** Category hierarchies. */
122 categoryHierarchies: CategoryHierarchy[];
123 /** Tags (legacy Alchemy ownership markers are stripped). */
124 tags: string[];
125 /** Variant group id. */
126 itemGroupId: string | undefined;
127 /** Language code. */
128 languageCode: string | undefined;
129 /** Retail product metadata. */
130 productMetadata: ProductCatalogItem | undefined;
131 /** Extra item attributes. */
132 itemAttributes: FeatureMap | undefined;
133 },
134 never,
135 Providers
136 >;
137
138 /**
139 * A Recommendations AI catalog item.
140 *
141 * Catalog items have no labels field. Their description and tags feed
142 * recommendations, so Alchemy writes no ownership marker into them: a
143 * generated item id identifies the item, and `read` reports an explicit
144 * id it has no state for as unowned.
145 * Catalog, location, and item id are immutable. Title, description,
146 * categories, tags, and product metadata update in place.
147 *
148 * ### Creating a Catalog Item
149 * **Example:** Item on the default catalog
150 * ```typescript
151 * const item = yield* GCP.RecommendationEngine.CatalogsCatalogItem("Shirt", {
152 * title: "Cotton tee",
153 * categoryHierarchies: [{ categories: ["Apparel", "T-Shirts"] }],
154 * productMetadata: {
155 * currencyCode: "USD",
156 * exactPrice: { displayPrice: 20 },
157 * stockState: "IN_STOCK",
158 * },
159 * });
160 * ```
161 *
162 * **Example:** Explicit catalog and item id
163 * ```typescript
164 * const item = yield* GCP.RecommendationEngine.CatalogsCatalogItem("Shirt", {
165 * catalog: "default_catalog",
166 * location: "global",
167 * catalogItemId: "cotton-tee",
168 * title: "Cotton tee",
169 * description: "Soft cotton t-shirt",
170 * });
171 * ```
172 *
173 * ### Updating a Catalog Item
174 * **Example:** Change title and price
175 * ```typescript
176 * const item = yield* GCP.RecommendationEngine.CatalogsCatalogItem("Shirt", {
177 * title: "Linen tee",
178 * categoryHierarchies: [{ categories: ["Apparel", "T-Shirts"] }],
179 * productMetadata: {
180 * currencyCode: "USD",
181 * exactPrice: { displayPrice: 24 },
182 * },
183 * });
184 * ```
185 *
186 * @resource
187 * @category RecommendationEngine
188 */
189 export const CatalogsCatalogItem = Resource<CatalogsCatalogItem>(
190 "GCP.RecommendationEngine.CatalogsCatalogItem",
191 );
192
193 export class CatalogsCatalogItemNotResolved extends Data.TaggedError(
194 "GCP.RecommendationEngine.CatalogsCatalogItemNotResolved",
195 )<{
196 resourceName: string;
197 }> {}
198
199 const toAttrs = (item: CatalogItem, project: string, nameHint?: string) => {
200 const hinted = nameHint && nameHint.includes("/") ? nameHint : "";
201 const parsed = parseResourceName(hinted);
202 const catalogItemId = item.id ?? parsed.id;
203 const location = parsed.location || DEFAULT_LOCATION;
204 const catalog =
205 parsed.catalog.length > 0 ? parsed.catalog : expandCatalog(undefined, project, location);
206 const name =
207 hinted.includes("/catalogItems/") || hinted.includes("/catalogitems/")
208 ? hinted
209 : itemName(catalog, catalogItemId);
210 const ownership = parseOwnership(item.description);
211 return {
212 name,
213 catalogItemId,
214 catalog,
215 project: parsed.project || project,
216 location,
217 title: item.title,
218 description: ownership.text,
219 categoryHierarchies: hierarchiesOf(item.categoryHierarchies),
220 tags: userTags(item.tags),
221 itemGroupId: item.itemGroupId,
222 languageCode: item.languageCode,
223 productMetadata: productMetadataOf(item.productMetadata),
224 itemAttributes: item.itemAttributes,
225 };
226 };
227
228 const toBody = (
229 news: CatalogsCatalogItemProps,
230 catalogItemId: string,
231 description: string,
232 tags: string[],
233 ): CatalogItem => ({
234 id: catalogItemId,
235 title: news.title ?? catalogItemId,
236 description,
237 categoryHierarchies: news.categoryHierarchies ?? defaultHierarchies(),
238 tags,
239 itemGroupId: news.itemGroupId,
240 languageCode: news.languageCode,
241 productMetadata: news.productMetadata,
242 itemAttributes: news.itemAttributes,
243 });
244
245 export const CatalogsCatalogItemProvider = () =>
246 Provider.succeed(CatalogsCatalogItem, {
247 stables: ["name", "catalogItemId", "catalog", "project", "location"],
248
249 diff: Effect.fn(function* ({ news, olds, output }) {
250 if (!isResolved(news)) return undefined;
251 const env = yield* GcpEnvironment.current;
252 const previousParent = olds?.catalog ?? output?.catalog;
253 const nextParent = expandCatalog(
254 news.catalog,
255 env.project,
256 normalizeLocation(news.location ?? output?.location),
257 );
258 return replaceOnIdentity({
259 previousId: olds?.catalogItemId ?? output?.catalogItemId,
260 nextId: news.catalogItemId,
261 previousParent,
262 nextParent,
263 });
264 }),
265
266 read: Effect.fn(function* ({ id, olds, output }) {
267 const env = yield* GcpEnvironment.current;
268 const location = normalizeLocation(olds?.location ?? output?.location);
269 const catalog = output?.catalog ?? expandCatalog(olds?.catalog, env.project, location);
270 const catalogItemId = yield* toPhysical(id, olds?.catalogItemId, output?.catalogItemId);
271 const name = output?.name ?? itemName(catalog, catalogItemId);
272 const existing = yield* getCatalogItem(name);
273 if (existing === undefined) return undefined;
274 const attrs = toAttrs(existing, env.project, name);
275 // Description and tags feed recommendations, so they carry no
276 // ownership marker: a generated id derives from this stack, stage,
277 // logical id and instance; an explicit id is only ours when state
278 // has it.
279 return output !== undefined || olds?.catalogItemId === undefined ? attrs : Unowned(attrs);
280 }),
281
282 list: () =>
283 Effect.gen(function* () {
284 const env = yield* GcpEnvironment.current;
285 const catalogs = yield* listProjectCatalogs(env.project);
286 const pages = yield* Effect.forEach(
287 catalogs,
288 (catalog) =>
289 catalog.name
290 ? listCatalogItems(catalog.name).pipe(
291 Effect.map((items) =>
292 items
293 .filter(itemHasOwnership)
294 .map((item) => toAttrs(item, env.project, catalog.name)),
295 ),
296 )
297 : Effect.succeed([]),
298 { concurrency: 4 },
299 );
300 return pages.flat();
301 }),
302
303 reconcile: Effect.fn(function* ({ id, news, output }) {
304 const env = yield* GcpEnvironment.current;
305 const location = normalizeLocation(news.location ?? output?.location);
306 const catalog = expandCatalog(news.catalog, env.project, location);
307 const catalogItemId = yield* toPhysical(id, news.catalogItemId, output?.catalogItemId);
308 const name = itemName(catalog, catalogItemId);
309 const description = news.description ?? "";
310 const tags = news.tags ?? [];
311 const body = toBody(news, catalogItemId, description, tags);
312
313 let current = yield* getCatalogItem(output?.name ?? name);
314
315 if (current === undefined) {
316 const created = yield* recommendationengine
317 .createProjectsLocationsCatalogsCatalogItems({
318 parent: catalog,
319 body,
320 })
321 .pipe(Effect.catchTag("Conflict", () => getCatalogItem(name)));
322 current = created ?? undefined;
323 }
324
325 if (current === undefined) {
326 return yield* new CatalogsCatalogItemNotResolved({ resourceName: name });
327 }
328
329 const title = news.title ?? catalogItemId;
330 const desiredHierarchies = news.categoryHierarchies ?? defaultHierarchies();
331 const mask = updateMaskOf(
332 sameText(current.title, title) ? undefined : "title",
333 sameText(current.description, description) ? undefined : "description",
334 sameJson(hierarchiesOf(current.categoryHierarchies), desiredHierarchies)
335 ? undefined
336 : "categoryHierarchies",
337 sameStringList(current.tags, tags) ? undefined : "tags",
338 sameText(current.itemGroupId, news.itemGroupId) ? undefined : "itemGroupId",
339 sameText(current.languageCode, news.languageCode) ? undefined : "languageCode",
340 sameJson(productMetadataOf(current.productMetadata), news.productMetadata)
341 ? undefined
342 : "productMetadata",
343 sameJson(current.itemAttributes, news.itemAttributes) ? undefined : "itemAttributes",
344 );
345
346 if (mask.length > 0) {
347 current = yield* recommendationengine.patchProjectsLocationsCatalogsCatalogItems({
348 name,
349 updateMask: mask,
350 body: { ...body, id: catalogItemId },
351 });
352 }
353
354 return toAttrs(current, env.project, name);
355 }),
356
357 delete: Effect.fn(function* ({ output }) {
358 yield* recommendationengine
359 .deleteProjectsLocationsCatalogsCatalogItems({
360 name: output.name,
361 })
362 .pipe(Effect.catchTag("NotFound", () => Effect.void));
363 }),
364 });