@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 539 lines 17.9 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetIssuingPersonalizationDesigns,
4 GetIssuingPersonalizationDesign,
5 CreateIssuingPersonalizationDesign,
6 UpdateIssuingPersonalizationDesign,
7 type IssuingPersonalizationDesign as StripeIssuingPersonalizationDesign,
8 type CreateIssuingPersonalizationDesignRequestCarrierText,
9 } from "@distilled.cloud/stripe/stripe";
10 import { Unowned } from "alchemy/AdoptPolicy";
11 import { deepEqual, 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 Effect from "effect/Effect";
17 import {
18 alchemyMetadataKeys,
19 createInternalMetadata,
20 diffMetadata,
21 hasAlchemyMetadata,
22 stripInternalMetadata,
23 toMetadata,
24 } from "./Metadata.ts";
25 import { isMissingStripeResource } from "./missing.ts";
26 import type { Providers } from "./Providers.ts";
27
28 const NAME_MAX_LENGTH = 250;
29 const LOOKUP_KEY_MAX_LENGTH = 200;
30 const LIST_PAGE_SIZE = 100;
31 const LIST_MAX_PAGES = 100;
32
33 /** Whether this personalization design can be used to create cards. */
34 export type IssuingPersonalizationDesignStatus = "active" | "inactive" | "rejected" | "review";
35
36 /** Reason a card logo was rejected. */
37 export type IssuingPersonalizationDesignCardLogoRejection =
38 | "geographic_location"
39 | "inappropriate"
40 | "network_name"
41 | "non_binary_image"
42 | "non_fiat_currency"
43 | "other"
44 | "other_entity"
45 | "promotional_material";
46
47 /** Reason carrier text was rejected. */
48 export type IssuingPersonalizationDesignCarrierTextRejection =
49 | "geographic_location"
50 | "inappropriate"
51 | "network_name"
52 | "non_fiat_currency"
53 | "other"
54 | "other_entity"
55 | "promotional_material";
56
57 /**
58 * Carrier-letter copy for physical bundles that support carrier text.
59 */
60 export interface IssuingPersonalizationDesignCarrierText {
61 /**
62 * Footer body text of the carrier letter.
63 */
64 footerBody?: string;
65 /**
66 * Footer title text of the carrier letter.
67 */
68 footerTitle?: string;
69 /**
70 * Header body text of the carrier letter.
71 */
72 headerBody?: string;
73 /**
74 * Header title text of the carrier letter.
75 */
76 headerTitle?: string;
77 }
78
79 /**
80 * Whether this design is used when a card is created without a
81 * personalization design.
82 */
83 export interface IssuingPersonalizationDesignPreferences {
84 /**
85 * When true, Stripe uses this design to create cards when one isn't
86 * specified. Connected accounts fall back to the platform default if
87 * none is set.
88 * @default false
89 */
90 isDefault?: boolean;
91 }
92
93 export interface IssuingPersonalizationDesignProps {
94 /**
95 * Id of the physical bundle (`ics_…`) this design ships with. Required.
96 * Mutable — changing it updates the design in place.
97 */
98 physicalBundle: string;
99 /**
100 * Friendly display name. If omitted, a unique name is generated from
101 * the stack, stage, and logical id. Mutable.
102 */
103 name?: string;
104 /**
105 * Lookup key used to retrieve this design from a static string. Unique
106 * per account, max 200 characters. If omitted, a unique key is
107 * generated. Mutable — a change transfers the key onto this design.
108 */
109 lookupKey?: string;
110 /**
111 * File id (`file_…`) of the card logo. Must have purpose
112 * `issuing_logo` (PNG, 1000×200, black on white). Mutable.
113 */
114 cardLogo?: string;
115 /**
116 * Carrier-letter copy. Omit or leave empty to clear. Mutable.
117 */
118 carrierText?: IssuingPersonalizationDesignCarrierText;
119 /**
120 * Default-design preference. Mutable.
121 */
122 preferences?: IssuingPersonalizationDesignPreferences;
123 /**
124 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
125 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
126 * not contain `:`. Mutable.
127 */
128 metadata?: Record<string, string>;
129 }
130
131 export type IssuingPersonalizationDesign = Resource<
132 "Stripe.IssuingPersonalizationDesign",
133 IssuingPersonalizationDesignProps,
134 {
135 /** Stripe personalization design id (`ipcd_…`). */
136 id: string;
137 /** Friendly display name. */
138 name: string;
139 /** Lookup key used to retrieve this design dynamically. */
140 lookupKey: string | undefined;
141 /** Physical bundle id (`ics_…`). */
142 physicalBundle: string;
143 /** Card logo file id, if set. */
144 cardLogo: string | undefined;
145 /** Carrier-letter copy, if set. */
146 carrierText: IssuingPersonalizationDesignCarrierText | undefined;
147 /** Whether this design is the account default. */
148 isDefault: boolean;
149 /**
150 * Whether this design is the Connect platform default. Null on
151 * non-connected accounts.
152 */
153 isPlatformDefault: boolean | undefined;
154 /** Whether this design can be used to create cards. */
155 status: IssuingPersonalizationDesignStatus;
156 /** Reasons the card logo was rejected, if any. */
157 cardLogoRejectionReasons: IssuingPersonalizationDesignCardLogoRejection[] | undefined;
158 /** Reasons the carrier text was rejected, if any. */
159 carrierTextRejectionReasons: IssuingPersonalizationDesignCarrierTextRejection[] | undefined;
160 /** User-defined metadata (Alchemy ownership keys stripped). */
161 metadata: Record<string, string>;
162 /** Unix timestamp when the design was created. */
163 created: number;
164 /** Whether the design exists in live mode. */
165 livemode: boolean;
166 },
167 never,
168 Providers
169 >;
170
171 /**
172 * A Stripe Issuing Personalization Design — a physical bundle, optional
173 * card logo, and optional carrier text that represent a card product
174 * line. Name, lookup key, logo, carrier text, physical bundle,
175 * preferences, and metadata update in place.
176 *
177 * Stripe has no delete, archive, or deactivate API for personalization
178 * designs. Destroy is a no-op; the design remains as residue on the
179 * account (still listed by `list()` via Alchemy metadata). Account-wide
180 * nuke skips this type.
181 *
182 * Creating designs requires the Stripe Issuing entitlement.
183 *
184 * @see https://docs.stripe.com/api/issuing/personalization-designs
185 *
186 * ### Creating a Personalization Design
187 * **Example:** Named design on a physical bundle
188 * ```typescript
189 * const design = yield* Stripe.IssuingPersonalizationDesign("metal-card", {
190 * physicalBundle: "ics_Fiiwz3T83opOUd",
191 * name: "Metal Card",
192 * });
193 * ```
194 *
195 * **Example:** Lookup key, carrier text, and metadata
196 * ```typescript
197 * const design = yield* Stripe.IssuingPersonalizationDesign("metal-card", {
198 * physicalBundle: "ics_Fiiwz3T83opOUd",
199 * name: "Metal Card",
200 * lookupKey: "metal_card_v1",
201 * carrierText: {
202 * headerTitle: "Welcome",
203 * headerBody: "Your card is on its way.",
204 * },
205 * metadata: { line: "metal" },
206 * });
207 * ```
208 *
209 * ### Updating a Personalization Design
210 * **Example:** Rename and retag
211 * ```typescript
212 * const design = yield* Stripe.IssuingPersonalizationDesign("metal-card", {
213 * physicalBundle: "ics_Fiiwz3T83opOUd",
214 * name: "Metal Card v2",
215 * lookupKey: "metal_card_v1",
216 * metadata: { line: "metal", version: "2" },
217 * });
218 * ```
219 *
220 * ### Retrieving a Personalization Design
221 * **Example:** Bind and retrieve
222 * ```typescript
223 * const retrieve = yield* Stripe.RetrieveIssuingPersonalizationDesign(design);
224 * const live = yield* retrieve();
225 * ```
226 *
227 * ### Destroying a Personalization Design
228 * **Example:** Destroy is a no-op
229 * ```typescript
230 * // stack.destroy() leaves the Stripe object in place — there is no
231 * // delete/archive API. Residue stays tagged with alchemy_stack.
232 * const design = yield* Stripe.IssuingPersonalizationDesign("metal-card", {
233 * physicalBundle: "ics_Fiiwz3T83opOUd",
234 * name: "Metal Card",
235 * });
236 * ```
237 *
238 * @resource
239 * @product Issuing
240 */
241 export const IssuingPersonalizationDesign = Resource<IssuingPersonalizationDesign>(
242 "Stripe.IssuingPersonalizationDesign",
243 );
244
245 type IssuingPersonalizationDesignAttributes = IssuingPersonalizationDesign["Attributes"];
246
247 const userMetadata = (
248 metadata: Record<string, string | undefined> | null | undefined,
249 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
250
251 const toName = (id: string, name: string | undefined, existing?: string) =>
252 Effect.gen(function* () {
253 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }));
254 });
255
256 const toLookupKey = (id: string, lookupKey: string | undefined, existing?: string) =>
257 Effect.gen(function* () {
258 if (lookupKey !== undefined && lookupKey.length > 0) return lookupKey;
259 if (existing !== undefined && existing.length > 0) return existing;
260 return yield* createPhysicalName({
261 id,
262 maxLength: LOOKUP_KEY_MAX_LENGTH,
263 lowercase: true,
264 });
265 });
266
267 const idOf = (value: string | { readonly id: string } | null | undefined): string | undefined => {
268 if (value == null) return undefined;
269 return typeof value === "string" ? value : value.id;
270 };
271
272 const compactCarrierText = (
273 input:
274 | {
275 footerBody?: string | null;
276 footerTitle?: string | null;
277 headerBody?: string | null;
278 headerTitle?: string | null;
279 }
280 | null
281 | undefined,
282 ): IssuingPersonalizationDesignCarrierText | undefined => {
283 if (input == null) return undefined;
284 const out: IssuingPersonalizationDesignCarrierText = {};
285 if (input.footerBody) out.footerBody = input.footerBody;
286 if (input.footerTitle) out.footerTitle = input.footerTitle;
287 if (input.headerBody) out.headerBody = input.headerBody;
288 if (input.headerTitle) out.headerTitle = input.headerTitle;
289 return Object.keys(out).length > 0 ? out : undefined;
290 };
291
292 const fromObservedCarrierText = (
293 value: StripeIssuingPersonalizationDesign["carrier_text"],
294 ): IssuingPersonalizationDesignCarrierText | undefined =>
295 compactCarrierText(
296 value == null
297 ? undefined
298 : {
299 footerBody: value.footer_body,
300 footerTitle: value.footer_title,
301 headerBody: value.header_body,
302 headerTitle: value.header_title,
303 },
304 );
305
306 const toWireCarrierText = (
307 input: IssuingPersonalizationDesignCarrierText,
308 ): CreateIssuingPersonalizationDesignRequestCarrierText => ({
309 ...(input.footerBody !== undefined ? { footer_body: input.footerBody } : {}),
310 ...(input.footerTitle !== undefined ? { footer_title: input.footerTitle } : {}),
311 ...(input.headerBody !== undefined ? { header_body: input.headerBody } : {}),
312 ...(input.headerTitle !== undefined ? { header_title: input.headerTitle } : {}),
313 });
314
315 const toAttrs = (
316 design: StripeIssuingPersonalizationDesign,
317 ): IssuingPersonalizationDesignAttributes => ({
318 id: design.id,
319 name: design.name ?? "",
320 lookupKey: design.lookup_key ?? undefined,
321 physicalBundle: idOf(design.physical_bundle) ?? "",
322 cardLogo: idOf(design.card_logo),
323 carrierText: fromObservedCarrierText(design.carrier_text),
324 isDefault: design.preferences.is_default,
325 isPlatformDefault: design.preferences.is_platform_default ?? undefined,
326 status: design.status,
327 cardLogoRejectionReasons: design.rejection_reasons.card_logo ?? undefined,
328 carrierTextRejectionReasons: design.rejection_reasons.carrier_text ?? undefined,
329 metadata: userMetadata(design.metadata),
330 created: design.created,
331 livemode: design.livemode,
332 });
333
334 const isMissingDesign = isMissingStripeResource;
335
336 const getById = (personalizationDesign: string) =>
337 GetIssuingPersonalizationDesign({
338 personalization_design: personalizationDesign,
339 }).pipe(Effect.catchIf(isMissingDesign, () => Effect.undefined));
340
341 const findByLookupKey = Effect.fn(function* (lookupKey: string) {
342 const response = yield* GetIssuingPersonalizationDesigns({
343 lookup_keys: [lookupKey],
344 limit: 1,
345 });
346 return response.data[0];
347 });
348
349 const listAllDesigns = Effect.fn(function* () {
350 const designs: StripeIssuingPersonalizationDesign[] = [];
351 let startingAfter: string | undefined;
352 for (let page = 0; page < LIST_MAX_PAGES; page++) {
353 const response = yield* GetIssuingPersonalizationDesigns({
354 limit: LIST_PAGE_SIZE,
355 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
356 });
357 designs.push(...response.data);
358 if (!response.has_more || response.data.length === 0) {
359 break;
360 }
361 startingAfter = response.data[response.data.length - 1]?.id;
362 if (startingAfter === undefined) {
363 break;
364 }
365 }
366 return designs;
367 });
368
369 const findByAlchemyId = Effect.fn(function* (id: string) {
370 const designs = yield* listAllDesigns();
371 const matches: StripeIssuingPersonalizationDesign[] = [];
372 for (const design of designs) {
373 if (yield* hasAlchemyMetadata(id, tagRecord(design.metadata))) {
374 matches.push(design);
375 }
376 }
377 matches.sort((a, b) => b.created - a.created);
378 return matches[0];
379 });
380
381 const observe = Effect.fn(function* (input: {
382 id?: string;
383 logicalId: string;
384 lookupKey?: string;
385 }) {
386 if (input.id !== undefined) {
387 const byId = yield* getById(input.id);
388 if (byId !== undefined) return byId;
389 }
390 if (input.lookupKey !== undefined) {
391 const byKey = yield* findByLookupKey(input.lookupKey);
392 if (
393 byKey !== undefined &&
394 (yield* hasAlchemyMetadata(input.logicalId, tagRecord(byKey.metadata)))
395 ) {
396 return byKey;
397 }
398 }
399 return yield* findByAlchemyId(input.logicalId);
400 });
401
402 const desiredMetadata = Effect.fn(function* (
403 id: string,
404 metadata: Record<string, string> | undefined,
405 ) {
406 return {
407 ...toMetadata(metadata),
408 ...(yield* createInternalMetadata(id)),
409 };
410 });
411
412 export const IssuingPersonalizationDesignProvider = () =>
413 Provider.succeed(IssuingPersonalizationDesign, {
414 stables: ["id", "created", "livemode"],
415 // Stripe has no delete/archive API; residue would reappear every nuke.
416 nuke: { skip: true },
417
418 diff: Effect.fn(function* ({ news }) {
419 if (!isResolved(news)) return undefined;
420 return undefined;
421 }),
422
423 read: Effect.fn(function* ({ id, output }) {
424 const existing = yield* observe({
425 id: output?.id,
426 logicalId: id,
427 lookupKey: output?.lookupKey,
428 });
429 if (existing === undefined) return undefined;
430 const attrs = toAttrs(existing);
431 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
432 }),
433
434 list: Effect.fn(function* () {
435 const designs = yield* listAllDesigns();
436 return designs
437 .filter((design) => {
438 const metadata = tagRecord(design.metadata);
439 return metadata[alchemyMetadataKeys.stack] !== undefined;
440 })
441 .map(toAttrs);
442 }),
443
444 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
445 const name = yield* toName(id, news.name, output?.name);
446 const lookupKey = yield* toLookupKey(id, news.lookupKey, output?.lookupKey);
447 const metadata = yield* desiredMetadata(id, news.metadata);
448 const desiredCardLogo = news.cardLogo;
449 const desiredCarrierText = compactCarrierText(news.carrierText);
450 const desiredIsDefault = news.preferences?.isDefault ?? false;
451 const desiredPhysicalBundle = news.physicalBundle;
452
453 let current = yield* observe({
454 id: output?.id,
455 logicalId: id,
456 lookupKey,
457 });
458
459 if (current === undefined) {
460 current = yield* CreateIssuingPersonalizationDesign({
461 physical_bundle: desiredPhysicalBundle,
462 name,
463 lookup_key: lookupKey,
464 transfer_lookup_key: true,
465 metadata,
466 ...(desiredCardLogo !== undefined ? { card_logo: desiredCardLogo } : {}),
467 ...(desiredCarrierText !== undefined
468 ? { carrier_text: toWireCarrierText(desiredCarrierText) }
469 : {}),
470 ...(desiredIsDefault ? { preferences: { is_default: true } } : {}),
471 }).pipe(
472 withRequestOptions({
473 idempotencyKey: `alchemy-issuing-personalization-design-${instanceId}`,
474 }),
475 );
476 }
477
478 const observedMetadata = tagRecord(current.metadata);
479 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
480 const metadataChanged = upsert.length > 0 || removed.length > 0;
481 const nameChanged = (current.name ?? "") !== name;
482 const lookupKeyChanged = (current.lookup_key ?? "") !== lookupKey;
483 const physicalBundleChanged = (idOf(current.physical_bundle) ?? "") !== desiredPhysicalBundle;
484 const cardLogoChanged = (idOf(current.card_logo) ?? "") !== (desiredCardLogo ?? "");
485 const carrierTextChanged = !deepEqual(
486 fromObservedCarrierText(current.carrier_text),
487 desiredCarrierText,
488 { stripNullish: true },
489 );
490 const preferencesChanged = current.preferences.is_default !== desiredIsDefault;
491
492 if (
493 !nameChanged &&
494 !lookupKeyChanged &&
495 !physicalBundleChanged &&
496 !cardLogoChanged &&
497 !carrierTextChanged &&
498 !preferencesChanged &&
499 !metadataChanged
500 ) {
501 return toAttrs(current);
502 }
503
504 const updated = yield* UpdateIssuingPersonalizationDesign({
505 personalization_design: current.id,
506 ...(nameChanged ? { name } : {}),
507 ...(lookupKeyChanged ? { lookup_key: lookupKey, transfer_lookup_key: true } : {}),
508 ...(physicalBundleChanged ? { physical_bundle: desiredPhysicalBundle } : {}),
509 ...(cardLogoChanged
510 ? {
511 card_logo: desiredCardLogo !== undefined ? desiredCardLogo : "",
512 }
513 : {}),
514 ...(carrierTextChanged
515 ? {
516 carrier_text:
517 desiredCarrierText !== undefined ? toWireCarrierText(desiredCarrierText) : "",
518 }
519 : {}),
520 ...(preferencesChanged ? { preferences: { is_default: desiredIsDefault } } : {}),
521 ...(metadataChanged
522 ? {
523 metadata: {
524 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
525 ...Object.fromEntries(removed.map((key) => [key, ""])),
526 },
527 }
528 : {}),
529 });
530 return toAttrs(updated);
531 }),
532
533 delete: Effect.fn(function* (_input) {
534 // Stripe has no delete, archive, or deactivate API for Issuing
535 // Personalization Designs. Destroy is a no-op; the object remains
536 // as residue on the account.
537 yield* Effect.void;
538 }),
539 });