The best way to control Claude Code, Codex and more from any computer or phone

main
ts 475 lines 15.8 KB
Raw
1 import * as reviews from "@distilled.cloud/gcp/merchantapi_reviews_v1beta";
2 import { unownedUnlessPrevious } 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 { createInternalLabels } from "../Labels.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 accountIdOf,
12 configuredAccountIds,
13 dataSourceNameOf,
14 DEFAULT_COUNTRY,
15 DEFAULT_LANGUAGE,
16 DEFAULT_REVIEW_TIME,
17 findOwnedProductReview,
18 getProductReview,
19 hasAlchemyOwnership,
20 jsonEqual,
21 lastSegment,
22 listProductReviewsAt,
23 normalizeCustomAttributes,
24 ownedByAlchemy,
25 parseOwnership,
26 parentOf,
27 productReviewNameOf,
28 stampCustomAttributes,
29 stripCustomAttributes,
30 toResourceId,
31 type ReviewCustomAttribute,
32 type ReviewLinkProps,
33 } from "./internal.ts";
34
35 export type ProductReviewAttributesProps = {
36 /** GTINs associated with the product. */
37 gtins?: string[];
38 /** Brand names associated with the product. */
39 brands?: string[];
40 /** Minimum possible rating (worst value, not "no rating"). */
41 minRating?: string;
42 /** Name of the reviews aggregator, if any. */
43 aggregatorName?: string;
44 /** Descriptive product names. */
45 productNames?: string[];
46 /** Maximum possible rating (must be greater than `minRating`). */
47 maxRating?: string;
48 /** Advantages from the reviewer. */
49 pros?: string[];
50 /** How the review was collected. */
51 collectionMethod?: reviews.ProductReviewAttributesCollectionMethodEnum | (string & {});
52 /** Whether the review is marked as spam. */
53 isSpam?: boolean;
54 /** Reviewer's overall rating of the product. */
55 rating?: number;
56 /** SKUs associated with the product. */
57 skus?: string[];
58 /** URIs of reviewer-created product images. */
59 reviewerImageLinks?: string[];
60 /** Publisher favicon URI. */
61 publisherFavicon?: string;
62 /** Name of the publisher of the product reviews. */
63 publisherName?: string;
64 /** Name of the reviewer. */
65 reviewerUsername?: string;
66 /** Publisher-system transaction id. */
67 transactionId?: string;
68 /**
69 * Review body, sent verbatim.
70 */
71 content?: string;
72 /** Whether the reviewer's purchase is verified. */
73 isVerifiedPurchase?: boolean;
74 /**
75 * ISO 3166-1 alpha-2 country of the review.
76 * @default "US"
77 */
78 reviewCountry?: string;
79 /** Disadvantages from the reviewer. */
80 cons?: string[];
81 /** URI of the review landing page. */
82 reviewLink?: ReviewLinkProps;
83 /**
84 * BCP-47 language of the review.
85 * @default "en"
86 */
87 reviewLanguage?: string;
88 /** Subclient identifier of the review source. */
89 subclientName?: string;
90 /** Publisher-system identifier for the review author. */
91 reviewerId?: string;
92 /** Title of the review. */
93 title?: string;
94 /** Product landing-page URIs. */
95 productLinks?: string[];
96 /**
97 * Timestamp when the review was written (RFC3339).
98 * @default "2020-01-01T00:00:00Z"
99 */
100 reviewTime?: string;
101 /** ASINs associated with the product. */
102 asins?: string[];
103 /** When true, the reviewer remains anonymous. */
104 reviewerIsAnonymous?: boolean;
105 /** MPNs associated with the product. */
106 mpns?: string[];
107 /** Whether the review is incentivized. */
108 isIncentivizedReview?: boolean;
109 };
110
111 export type ProductReviewProps = {
112 /**
113 * Merchant Center account id (the `{account}` segment of
114 * `accounts/{account}`). Immutable — changing it replaces the review.
115 */
116 account: string;
117 /**
118 * Product-reviews data source. Full name
119 * `accounts/{account}/dataSources/{datasource}` or the data source id.
120 */
121 dataSource: string;
122 /**
123 * Permanent publisher-system product review id. If omitted, a unique
124 * id is generated from the stack, stage, and logical id. Immutable —
125 * changing it replaces the review.
126 */
127 productReviewId?: string;
128 /**
129 * Product review attributes. `reviewTime` is required by the API;
130 * omitted values get defaults. When no product identifier is set,
131 * `skus` defaults to the review id.
132 */
133 productReviewAttributes?: ProductReviewAttributesProps;
134 /**
135 * Custom (merchant-provided) attributes. Alchemy ownership keys are
136 * merged in automatically.
137 */
138 customAttributes?: ReviewCustomAttribute[];
139 };
140
141 export type ProductReview = Resource<
142 "GCP.MerchantApiReviews.ProductReview",
143 ProductReviewProps,
144 {
145 /** Full resource name `accounts/{account}/productReviews/{id}`. */
146 name: string;
147 /** Merchant Center account id. */
148 account: string;
149 /** Publisher-system product review id. */
150 productReviewId: string;
151 /** Primary data source of the review. */
152 dataSource: string | undefined;
153 /** Review attributes with the Alchemy ownership prefix stripped. */
154 productReviewAttributes: ProductReviewAttributesProps | undefined;
155 /** User custom attributes (Alchemy ownership keys stripped). */
156 customAttributes: ReviewCustomAttribute[];
157 /** Server-computed create time. */
158 createTime: string | undefined;
159 /** Server-computed last update time. */
160 lastUpdateTime: string | undefined;
161 },
162 never,
163 Providers
164 >;
165
166 /**
167 * A Merchant Center product review (Merchant API Reviews).
168 *
169 * Reviews have no labels field — Alchemy stamps ownership into
170 * `customAttributes` (never the review text) so `list` / nuke can find
171 * them. `account` and `productReviewId` are identity.
172 * `insertAccountsProductReviews` is a full-document upsert, so updates
173 * replace the review in place. Creating a review requires a Merchant
174 * Center account enrolled in product ratings and a product-reviews
175 * data source.
176 *
177 * ### Creating a Product Review
178 * **Example:** Generated id
179 * ```typescript
180 * const review = yield* GCP.MerchantApiReviews.ProductReview("Tote", {
181 * account: "123456",
182 * dataSource: "accounts/123456/dataSources/789",
183 * productReviewAttributes: {
184 * title: "Sturdy tote",
185 * content: "Holds a laptop and lunch",
186 * rating: 5,
187 * gtins: ["9780007350896"],
188 * },
189 * });
190 * ```
191 *
192 * **Example:** Explicit id
193 * ```typescript
194 * const review = yield* GCP.MerchantApiReviews.ProductReview("Tote", {
195 * account: "123456",
196 * dataSource: "accounts/123456/dataSources/789",
197 * productReviewId: "tote-2020",
198 * productReviewAttributes: {
199 * title: "Sturdy tote",
200 * content: "Holds a laptop and lunch",
201 * rating: 5,
202 * skus: ["tote-navy"],
203 * reviewLanguage: "en",
204 * reviewCountry: "US",
205 * },
206 * });
207 * ```
208 *
209 * ### Updating a Product Review
210 * **Example:** Change the title and rating
211 * ```typescript
212 * const review = yield* GCP.MerchantApiReviews.ProductReview("Tote", {
213 * account: "123456",
214 * dataSource: "accounts/123456/dataSources/789",
215 * productReviewAttributes: {
216 * title: "Roomy tote",
217 * content: "Holds a laptop, lunch, and jacket",
218 * rating: 4,
219 * skus: ["tote-navy"],
220 * },
221 * });
222 * ```
223 *
224 * @resource
225 * @category MerchantApiReviews
226 */
227 export const ProductReview = Resource<ProductReview>("GCP.MerchantApiReviews.ProductReview");
228
229 export class ProductReviewNotResolved extends Data.TaggedError(
230 "GCP.MerchantApiReviews.ProductReviewNotResolved",
231 )<{
232 resourceName: string;
233 }> {}
234
235 const hasProductIdentifier = (attrs: ProductReviewAttributesProps | undefined) =>
236 (attrs?.gtins?.length ?? 0) > 0 ||
237 (attrs?.skus?.length ?? 0) > 0 ||
238 (attrs?.mpns?.length ?? 0) > 0 ||
239 (attrs?.asins?.length ?? 0) > 0;
240
241 const attributesOf = (
242 attrs: reviews.ProductReviewAttributes | undefined,
243 ): ProductReviewAttributesProps | undefined => {
244 if (attrs === undefined) return undefined;
245 return {
246 gtins: attrs.gtins,
247 brands: attrs.brands,
248 minRating: attrs.minRating,
249 aggregatorName: attrs.aggregatorName,
250 productNames: attrs.productNames,
251 maxRating: attrs.maxRating,
252 pros: attrs.pros,
253 collectionMethod: attrs.collectionMethod,
254 isSpam: attrs.isSpam,
255 rating: attrs.rating,
256 skus: attrs.skus,
257 reviewerImageLinks: attrs.reviewerImageLinks,
258 publisherFavicon: attrs.publisherFavicon,
259 publisherName: attrs.publisherName,
260 reviewerUsername: attrs.reviewerUsername,
261 transactionId: attrs.transactionId,
262 content: parseOwnership(attrs.content).text,
263 isVerifiedPurchase: attrs.isVerifiedPurchase,
264 reviewCountry: attrs.reviewCountry,
265 cons: attrs.cons,
266 reviewLink: attrs.reviewLink,
267 reviewLanguage: attrs.reviewLanguage,
268 subclientName: attrs.subclientName,
269 reviewerId: attrs.reviewerId,
270 title: attrs.title,
271 productLinks: attrs.productLinks,
272 reviewTime: attrs.reviewTime,
273 asins: attrs.asins,
274 reviewerIsAnonymous: attrs.reviewerIsAnonymous,
275 mpns: attrs.mpns,
276 isIncentivizedReview: attrs.isIncentivizedReview,
277 };
278 };
279
280 const toAttrs = (review: reviews.ProductReview, account: string, dataSource?: string) => {
281 const productReviewId = review.productReviewId ?? (review.name ? lastSegment(review.name) : "");
282 return {
283 name: review.name ?? productReviewNameOf(account, productReviewId),
284 account: accountIdOf(account),
285 productReviewId,
286 dataSource: review.dataSource ?? dataSource,
287 productReviewAttributes: attributesOf(review.productReviewAttributes),
288 customAttributes: stripCustomAttributes(review.customAttributes),
289 createTime: review.productReviewStatus?.createTime,
290 lastUpdateTime: review.productReviewStatus?.lastUpdateTime,
291 };
292 };
293
294 const desiredAttributes = (input: {
295 productReviewId: string;
296 ownership: Record<string, string>;
297 attrs: ProductReviewAttributesProps | undefined;
298 }): reviews.ProductReviewAttributes => ({
299 gtins: input.attrs?.gtins,
300 brands: input.attrs?.brands,
301 minRating: input.attrs?.minRating,
302 aggregatorName: input.attrs?.aggregatorName,
303 productNames: input.attrs?.productNames,
304 maxRating: input.attrs?.maxRating,
305 pros: input.attrs?.pros,
306 collectionMethod: input.attrs?.collectionMethod,
307 isSpam: input.attrs?.isSpam,
308 rating: input.attrs?.rating,
309 skus: hasProductIdentifier(input.attrs) ? input.attrs?.skus : [input.productReviewId],
310 reviewerImageLinks: input.attrs?.reviewerImageLinks,
311 publisherFavicon: input.attrs?.publisherFavicon,
312 publisherName: input.attrs?.publisherName,
313 reviewerUsername: input.attrs?.reviewerUsername,
314 transactionId: input.attrs?.transactionId,
315 content: input.attrs?.content,
316 isVerifiedPurchase: input.attrs?.isVerifiedPurchase,
317 reviewCountry: input.attrs?.reviewCountry ?? DEFAULT_COUNTRY,
318 cons: input.attrs?.cons,
319 reviewLink: input.attrs?.reviewLink,
320 reviewLanguage: input.attrs?.reviewLanguage ?? DEFAULT_LANGUAGE,
321 subclientName: input.attrs?.subclientName,
322 reviewerId: input.attrs?.reviewerId,
323 title: input.attrs?.title,
324 productLinks: input.attrs?.productLinks,
325 reviewTime: input.attrs?.reviewTime ?? DEFAULT_REVIEW_TIME,
326 asins: input.attrs?.asins,
327 reviewerIsAnonymous: input.attrs?.reviewerIsAnonymous,
328 mpns: input.attrs?.mpns,
329 isIncentivizedReview: input.attrs?.isIncentivizedReview,
330 });
331
332 const desiredBody = (input: {
333 productReviewId: string;
334 attributes: reviews.ProductReviewAttributes;
335 customAttributes: reviews.CustomAttribute[];
336 }): reviews.ProductReview => ({
337 productReviewId: input.productReviewId,
338 productReviewAttributes: input.attributes,
339 customAttributes: input.customAttributes,
340 });
341
342 const reviewNeedsSync = (current: reviews.ProductReview, desired: reviews.ProductReview) =>
343 !jsonEqual(current.productReviewId, desired.productReviewId) ||
344 !jsonEqual(current.productReviewAttributes, desired.productReviewAttributes) ||
345 !jsonEqual(
346 normalizeCustomAttributes(current.customAttributes),
347 normalizeCustomAttributes(desired.customAttributes),
348 );
349
350 export const ProductReviewProvider = () =>
351 Provider.succeed(ProductReview, {
352 stables: ["name", "account", "productReviewId"],
353
354 diff: Effect.fn(function* ({ news, olds, output }) {
355 if (!isResolved(news)) return undefined;
356 const previousAccount = olds?.account ?? output?.account;
357 if (
358 previousAccount !== undefined &&
359 accountIdOf(news.account) !== accountIdOf(previousAccount)
360 ) {
361 return { action: "replace" as const, deleteFirst: false };
362 }
363 const previousId = olds?.productReviewId ?? output?.productReviewId;
364 if (
365 previousId !== undefined &&
366 news.productReviewId !== undefined &&
367 news.productReviewId !== previousId
368 ) {
369 return { action: "replace" as const, deleteFirst: true };
370 }
371 return undefined;
372 }),
373
374 read: Effect.fn(function* ({ id, olds, output, previous }) {
375 const account = olds?.account ?? output?.account ?? "";
376 const productReviewId = yield* toResourceId(
377 id,
378 olds?.productReviewId,
379 output?.productReviewId,
380 );
381 const name = output?.name ?? productReviewNameOf(account, productReviewId);
382 let existing = yield* getProductReview(name);
383 if (existing === undefined && account) {
384 existing = yield* findOwnedProductReview(id, account, productReviewId);
385 }
386 if (existing === undefined) return undefined;
387 const attrs = toAttrs(existing, account, olds?.dataSource ?? output?.dataSource);
388 return (yield* ownedByAlchemy(id, {
389 customAttributes: existing.customAttributes,
390 content: existing.productReviewAttributes?.content,
391 }))
392 ? attrs
393 : unownedUnlessPrevious(attrs, previous, "name");
394 }),
395
396 list: () =>
397 Effect.gen(function* () {
398 const accounts = yield* configuredAccountIds();
399 const pages = yield* Effect.forEach(accounts, (account) => listProductReviewsAt(account), {
400 concurrency: 4,
401 });
402 const attrs = [];
403 for (let i = 0; i < pages.length; i++) {
404 const account = accounts[i]!;
405 for (const review of pages[i] ?? []) {
406 if (
407 !hasAlchemyOwnership({
408 customAttributes: review.customAttributes,
409 content: review.productReviewAttributes?.content,
410 })
411 ) {
412 continue;
413 }
414 attrs.push(toAttrs(review, account, review.dataSource));
415 }
416 }
417 return attrs;
418 }),
419
420 reconcile: Effect.fn(function* ({ id, news, output }) {
421 const account = accountIdOf(news.account);
422 const productReviewId = yield* toResourceId(
423 id,
424 news.productReviewId,
425 output?.productReviewId,
426 );
427 const dataSource = dataSourceNameOf(account, news.dataSource);
428 const name = output?.name ?? productReviewNameOf(account, productReviewId);
429 const ownership = yield* createInternalLabels(id);
430 const attributes = desiredAttributes({
431 productReviewId,
432 ownership,
433 attrs: news.productReviewAttributes,
434 });
435 const customAttributes = stampCustomAttributes(ownership, news.customAttributes);
436 const desired = desiredBody({
437 productReviewId,
438 attributes,
439 customAttributes,
440 });
441
442 let current = yield* getProductReview(name);
443 if (current === undefined) {
444 current = yield* findOwnedProductReview(id, account, productReviewId);
445 }
446
447 const upsert = () =>
448 reviews
449 .insertAccountsProductReviews({
450 parent: parentOf(account),
451 dataSource,
452 body: desired,
453 })
454 .pipe(Effect.catchTag("Conflict", () => getProductReview(name)));
455
456 if (current === undefined) {
457 current = (yield* upsert()) ?? undefined;
458 } else if (reviewNeedsSync(current, desired)) {
459 current = (yield* upsert()) ?? current;
460 }
461
462 if (current === undefined) {
463 return yield* new ProductReviewNotResolved({ resourceName: name });
464 }
465
466 return toAttrs(current, account, dataSource);
467 }),
468
469 delete: Effect.fn(function* ({ output }) {
470 if (!output.name) return;
471 yield* reviews
472 .deleteAccountsProductReviews({ name: output.name })
473 .pipe(Effect.catchTag("NotFound", () => Effect.void));
474 }),
475 });