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

main
ts 389 lines 11.6 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeleteRadarValueList,
4 GetRadarValueLists,
5 GetRadarValueList,
6 CreateRadarValueList,
7 UpdateRadarValueList,
8 type RadarValueList as StripeRadarValueList,
9 } from "@distilled.cloud/stripe/stripe";
10 import { Unowned } from "alchemy/AdoptPolicy";
11 import { isResolved } from "alchemy/Diff";
12 import { createPhysicalName } from "alchemy/PhysicalName";
13 import * as Provider from "alchemy/Provider";
14 import { Resource } from "alchemy/Resource";
15 import { tagRecord } from "alchemy/Tags";
16 import * as Data from "effect/Data";
17 import * as Effect from "effect/Effect";
18 import {
19 alchemyMetadataKeys,
20 createInternalMetadata,
21 diffMetadata,
22 hasAlchemyMetadata,
23 stripInternalMetadata,
24 toMetadata,
25 } from "./Metadata.ts";
26 import { isMissingStripeResource } from "./missing.ts";
27 import type { Providers } from "./Providers.ts";
28
29 const NAME_MAX_LENGTH = 250;
30 const ALIAS_MAX_LENGTH = 100;
31 const LIST_PAGE_SIZE = 100;
32 const LIST_MAX_PAGES = 100;
33
34 /**
35 * Type of items stored in a Radar value list. Create-only — changing it
36 * replaces the list.
37 */
38 export type RadarValueListItemType =
39 | "account"
40 | "card_bin"
41 | "card_fingerprint"
42 | "case_sensitive_string"
43 | "country"
44 | "crypto_fingerprint"
45 | "customer_id"
46 | "email"
47 | "ip_address"
48 | "sepa_debit_fingerprint"
49 | "string"
50 | "us_bank_account_fingerprint";
51
52 export interface RadarValueListProps {
53 /**
54 * Alias used to reference this list in Radar rules. Unique per account;
55 * alphanumeric characters and underscores only, max 100 characters. If
56 * omitted, a unique alias is generated from the stack, stage, and
57 * logical id. Create-only — changing it replaces the list.
58 */
59 alias?: string;
60 /**
61 * Human-readable name shown in the Stripe Dashboard. If omitted, a unique
62 * name is generated from the stack, stage, and logical id. Mutable.
63 */
64 name?: string;
65 /**
66 * Type of items stored in this list. Immutable after create.
67 * @default "string"
68 */
69 itemType?: RadarValueListItemType;
70 /**
71 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
72 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
73 * not contain `:`. Mutable.
74 */
75 metadata?: Record<string, string>;
76 }
77
78 export type RadarValueList = Resource<
79 "Stripe.RadarValueList",
80 RadarValueListProps,
81 {
82 /** Stripe Radar value list id (`rsl_…`). */
83 id: string;
84 /** Alias used to reference this list in Radar rules. */
85 alias: string;
86 /** Human-readable name shown in the Stripe Dashboard. */
87 name: string;
88 /** Type of items stored in this list. */
89 itemType: RadarValueListItemType;
90 /** Name or email of the user who created this list. */
91 createdBy: string;
92 /** User-defined metadata (Alchemy ownership keys stripped). */
93 metadata: Record<string, string>;
94 /** Unix timestamp when the list was created. */
95 created: number;
96 /** Whether the list exists in live mode. */
97 livemode: boolean;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A Stripe Radar Value List — a named collection of values (emails, IPs,
105 * card fingerprints, …) referenced from Radar rules. `alias` and
106 * `itemType` are immutable and changing them replaces the list. Name and
107 * metadata update in place. Destroy deletes the list and its items; a
108 * list referenced by a Radar rule cannot be deleted.
109 *
110 * Radar custom lists may require Radar for Fraud Teams.
111 *
112 * @see https://docs.stripe.com/api/radar/value_lists
113 *
114 * ### Creating a Value List
115 * **Example:** Generated alias
116 * ```typescript
117 * const blocked = yield* Stripe.RadarValueList("blocked-emails", {
118 * itemType: "email",
119 * });
120 * ```
121 *
122 * **Example:** Named list with alias
123 * ```typescript
124 * const blocked = yield* Stripe.RadarValueList("blocked-emails", {
125 * alias: "custom_email_blocklist",
126 * name: "Blocked emails",
127 * itemType: "email",
128 * });
129 * ```
130 *
131 * ### Updating a Value List
132 * **Example:** Rename and retag
133 * ```typescript
134 * const blocked = yield* Stripe.RadarValueList("blocked-emails", {
135 * alias: "custom_email_blocklist",
136 * name: "Blocked emails (updated)",
137 * itemType: "email",
138 * metadata: { team: "fraud" },
139 * });
140 * ```
141 *
142 * ### Replacing a Value List
143 * **Example:** Changing item type replaces the list
144 * ```typescript
145 * const blocked = yield* Stripe.RadarValueList("blocked", {
146 * alias: "custom_blocklist",
147 * itemType: "ip_address",
148 * });
149 * ```
150 *
151 * @resource
152 * @product Radar
153 */
154 export const RadarValueList = Resource<RadarValueList>("Stripe.RadarValueList");
155
156 export class RadarValueListNotResolved extends Data.TaggedError(
157 "Stripe.RadarValueListNotResolved",
158 )<{
159 alias: string;
160 }> {}
161
162 type RadarValueListAttributes = RadarValueList["Attributes"];
163
164 const userMetadata = (
165 metadata: Record<string, string | undefined> | null | undefined,
166 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
167
168 const toName = (id: string, name: string | undefined, existing?: string) =>
169 Effect.gen(function* () {
170 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }));
171 });
172
173 const toAlias = (id: string, alias: string | undefined, existing?: string) =>
174 Effect.gen(function* () {
175 if (alias !== undefined) return alias;
176 if (existing !== undefined) return existing;
177 const generated = yield* createPhysicalName({
178 id,
179 maxLength: ALIAS_MAX_LENGTH,
180 lowercase: true,
181 delimiter: "_",
182 });
183 // Stripe aliases allow only [A-Za-z0-9_]; physical names may still
184 // contain hyphens from the stack/stage prefix.
185 return generated.replaceAll("-", "_");
186 });
187
188 const toAttrs = (list: StripeRadarValueList): RadarValueListAttributes => ({
189 id: list.id,
190 alias: list.alias,
191 name: list.name,
192 itemType: list.item_type,
193 createdBy: list.created_by,
194 metadata: userMetadata(list.metadata),
195 created: list.created,
196 livemode: list.livemode,
197 });
198
199 const isMissingValueList = isMissingStripeResource;
200
201 const getById = (valueList: string) =>
202 GetRadarValueList({ value_list: valueList }).pipe(
203 Effect.catchIf(isMissingValueList, () => Effect.undefined),
204 );
205
206 const findByAlias = (alias: string) =>
207 Effect.gen(function* () {
208 const response = yield* GetRadarValueLists({
209 alias,
210 limit: 1,
211 });
212 return response.data[0];
213 });
214
215 const listAllValueLists = Effect.fn(function* () {
216 const lists: StripeRadarValueList[] = [];
217 let startingAfter: string | undefined;
218 for (let page = 0; page < LIST_MAX_PAGES; page++) {
219 const response = yield* GetRadarValueLists({
220 limit: LIST_PAGE_SIZE,
221 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
222 });
223 lists.push(...response.data);
224 if (!response.has_more || response.data.length === 0) {
225 break;
226 }
227 startingAfter = response.data[response.data.length - 1]?.id;
228 if (startingAfter === undefined) {
229 break;
230 }
231 }
232 return lists;
233 });
234
235 const findByAlchemyId = Effect.fn(function* (id: string) {
236 const lists = yield* listAllValueLists();
237 const matches: StripeRadarValueList[] = [];
238 for (const list of lists) {
239 if (yield* hasAlchemyMetadata(id, tagRecord(list.metadata))) {
240 matches.push(list);
241 }
242 }
243 matches.sort((a, b) => b.created - a.created);
244 return matches[0];
245 });
246
247 const observe = Effect.fn(function* (input: { id?: string; logicalId: string; alias?: string }) {
248 if (input.id !== undefined) {
249 const byId = yield* getById(input.id);
250 if (byId !== undefined) return byId;
251 }
252 if (input.alias !== undefined) {
253 const byAlias = yield* findByAlias(input.alias);
254 if (
255 byAlias !== undefined &&
256 (yield* hasAlchemyMetadata(input.logicalId, tagRecord(byAlias.metadata)))
257 ) {
258 return byAlias;
259 }
260 }
261 return yield* findByAlchemyId(input.logicalId);
262 });
263
264 const desiredMetadata = Effect.fn(function* (
265 id: string,
266 metadata: Record<string, string> | undefined,
267 ) {
268 return {
269 ...toMetadata(metadata),
270 ...(yield* createInternalMetadata(id)),
271 };
272 });
273
274 const shouldReplace = (
275 news: RadarValueListProps,
276 output: RadarValueListAttributes | undefined,
277 ): boolean => {
278 if (output === undefined) return false;
279 if (news.alias !== undefined && news.alias !== output.alias) {
280 return true;
281 }
282 if (news.itemType !== undefined && news.itemType !== output.itemType) {
283 return true;
284 }
285 return false;
286 };
287
288 export const RadarValueListProvider = () =>
289 Provider.succeed(RadarValueList, {
290 stables: ["id", "alias", "itemType", "created", "createdBy", "livemode"],
291
292 diff: Effect.fn(function* ({ olds, news, output }) {
293 if (!isResolved(news)) return undefined;
294 if (shouldReplace(news, output)) {
295 const previousAlias = output?.alias ?? olds?.alias;
296 return {
297 action: "replace" as const,
298 deleteFirst: news.alias !== undefined && news.alias === previousAlias,
299 };
300 }
301 return undefined;
302 }),
303
304 read: Effect.fn(function* ({ id, output, previous }) {
305 const existing = yield* observe({
306 id: output?.id,
307 logicalId: id,
308 alias: output?.alias,
309 });
310 if (existing === undefined) return undefined;
311 // A create-first replacement finds the list it is replacing under the
312 // same logical id: that is not the replacement.
313 if (output === undefined && existing.id === previous?.id) return undefined;
314 const attrs = toAttrs(existing);
315 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
316 }),
317
318 list: Effect.fn(function* () {
319 const lists = yield* listAllValueLists();
320 return lists
321 .filter((list) => {
322 const metadata = tagRecord(list.metadata);
323 return metadata[alchemyMetadataKeys.stack] !== undefined;
324 })
325 .map(toAttrs);
326 }),
327
328 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
329 const alias = yield* toAlias(id, news.alias, output?.alias);
330 const name = yield* toName(id, news.name, output?.name);
331 const metadata = yield* desiredMetadata(id, news.metadata);
332 const itemType = news.itemType ?? output?.itemType ?? "string";
333
334 let current: StripeRadarValueList | undefined = yield* observe({
335 id: output?.id,
336 logicalId: id,
337 alias,
338 });
339 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
340 current = undefined;
341 }
342
343 if (current === undefined) {
344 current = yield* CreateRadarValueList({
345 alias,
346 name,
347 item_type: itemType,
348 metadata,
349 }).pipe(
350 withRequestOptions({
351 idempotencyKey: `alchemy-radar-value-list-${instanceId}`,
352 }),
353 );
354 }
355
356 if (current === undefined) {
357 return yield* new RadarValueListNotResolved({ alias });
358 }
359
360 const observedMetadata = tagRecord(current.metadata);
361 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
362 const metadataChanged = upsert.length > 0 || removed.length > 0;
363 const nameChanged = current.name !== name;
364
365 if (!nameChanged && !metadataChanged) {
366 return toAttrs(current);
367 }
368
369 const updated = yield* UpdateRadarValueList({
370 value_list: current.id,
371 ...(nameChanged ? { name } : {}),
372 ...(metadataChanged
373 ? {
374 metadata: {
375 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
376 ...Object.fromEntries(removed.map((key) => [key, ""])),
377 },
378 }
379 : {}),
380 });
381 return toAttrs(updated);
382 }),
383
384 delete: Effect.fn(function* ({ output }) {
385 yield* DeleteRadarValueList({ value_list: output.id }).pipe(
386 Effect.catchIf(isMissingValueList, () => Effect.void),
387 );
388 }),
389 });