@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 608 lines 20.5 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetPaymentMethodConfigurations,
4 GetPaymentMethodConfiguration,
5 CreatePaymentMethodConfiguration,
6 UpdatePaymentMethodConfiguration,
7 type PaymentMethodConfigResourcePaymentMethodProperties,
8 type PaymentMethodConfiguration as StripePaymentMethodConfiguration,
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 * as Data from "effect/Data";
16 import * as Effect from "effect/Effect";
17 import { isMissingStripeResource } from "./missing.ts";
18 import type { Providers } from "./Providers.ts";
19
20 const NAME_MAX_LENGTH = 100;
21 const LIST_PAGE_SIZE = 100;
22 const LIST_MAX_PAGES = 100;
23
24 /** Account preference for whether a payment method is displayed. */
25 export type PaymentMethodPreference = "none" | "off" | "on";
26
27 /** Effective display value after parent/override resolution. */
28 export type PaymentMethodEffectivePreference = "off" | "on";
29
30 export interface PaymentMethodDisplayPreference {
31 /**
32 * Account preference for whether this payment method is displayed at
33 * checkout. `on` shows it, `off` hides it, `none` defers to the parent
34 * configuration or Stripe's default.
35 */
36 preference?: PaymentMethodPreference;
37 }
38
39 export interface PaymentMethodPreferenceInput {
40 /**
41 * Whether or not the payment method should be displayed at checkout.
42 */
43 displayPreference?: PaymentMethodDisplayPreference;
44 }
45
46 export interface PaymentMethodState {
47 /**
48 * Whether this payment method may be offered at checkout. True when
49 * `displayPreference` is `on` and the payment method's capability is
50 * active.
51 */
52 available: boolean;
53 /**
54 * Observed display preference, including the effective value.
55 */
56 displayPreference: {
57 /**
58 * For child configs, whether the connected account may override.
59 */
60 overridable: boolean | undefined;
61 /**
62 * Configured preference (`on` / `off` / `none`).
63 */
64 preference: PaymentMethodPreference;
65 /**
66 * Effective display value after parent/override resolution.
67 */
68 value: PaymentMethodEffectivePreference;
69 };
70 }
71
72 export interface PaymentMethodConfigurationProps {
73 /**
74 * Configuration name. If omitted, a unique name is generated from the
75 * stack, stage, and logical id. Mutable. Max 100 characters. Used as
76 * the lookup key when the Stripe id is missing — this object has no
77 * metadata.
78 */
79 name?: string;
80 /**
81 * Whether the configuration can be used for new payments. New
82 * configurations are created active. Destroy sets this to `false`.
83 * @default true
84 */
85 active?: boolean;
86 /**
87 * Parent configuration id. Specify to create a child configuration for
88 * a connected account. Create-only — changing it replaces the
89 * configuration.
90 */
91 parent?: string;
92 /** Display preference for ACSS Debit. */
93 acssDebit?: PaymentMethodPreferenceInput;
94 /** Display preference for Affirm. */
95 affirm?: PaymentMethodPreferenceInput;
96 /** Display preference for Afterpay / Clearpay. */
97 afterpayClearpay?: PaymentMethodPreferenceInput;
98 /** Display preference for Alipay. */
99 alipay?: PaymentMethodPreferenceInput;
100 /** Display preference for Alma. */
101 alma?: PaymentMethodPreferenceInput;
102 /** Display preference for Amazon Pay. */
103 amazonPay?: PaymentMethodPreferenceInput;
104 /** Display preference for Apple Pay. */
105 applePay?: PaymentMethodPreferenceInput;
106 /** Display preference for AU BECS Debit. */
107 auBecsDebit?: PaymentMethodPreferenceInput;
108 /** Display preference for Bacs Direct Debit. */
109 bacsDebit?: PaymentMethodPreferenceInput;
110 /** Display preference for Bancontact. */
111 bancontact?: PaymentMethodPreferenceInput;
112 /** Display preference for Billie. */
113 billie?: PaymentMethodPreferenceInput;
114 /** Display preference for Bizum. */
115 bizum?: PaymentMethodPreferenceInput;
116 /** Display preference for BLIK. */
117 blik?: PaymentMethodPreferenceInput;
118 /** Display preference for Boleto. */
119 boleto?: PaymentMethodPreferenceInput;
120 /** Display preference for cards. */
121 card?: PaymentMethodPreferenceInput;
122 /** Display preference for Cartes Bancaires. */
123 cartesBancaires?: PaymentMethodPreferenceInput;
124 /** Display preference for Cash App Pay. */
125 cashapp?: PaymentMethodPreferenceInput;
126 /** Display preference for crypto / stablecoin payments. */
127 crypto?: PaymentMethodPreferenceInput;
128 /** Display preference for customer balance (bank transfer). */
129 customerBalance?: PaymentMethodPreferenceInput;
130 /** Display preference for EPS. */
131 eps?: PaymentMethodPreferenceInput;
132 /** Display preference for FPX. */
133 fpx?: PaymentMethodPreferenceInput;
134 /** Display preference for giropay. */
135 giropay?: PaymentMethodPreferenceInput;
136 /** Display preference for Google Pay. */
137 googlePay?: PaymentMethodPreferenceInput;
138 /** Display preference for GrabPay. */
139 grabpay?: PaymentMethodPreferenceInput;
140 /** Display preference for iDEAL. */
141 ideal?: PaymentMethodPreferenceInput;
142 /** Display preference for JCB. */
143 jcb?: PaymentMethodPreferenceInput;
144 /** Display preference for Kakao Pay. */
145 kakaoPay?: PaymentMethodPreferenceInput;
146 /** Display preference for Klarna. */
147 klarna?: PaymentMethodPreferenceInput;
148 /** Display preference for Konbini. */
149 konbini?: PaymentMethodPreferenceInput;
150 /** Display preference for Korean cards. */
151 krCard?: PaymentMethodPreferenceInput;
152 /** Display preference for Link. */
153 link?: PaymentMethodPreferenceInput;
154 /** Display preference for MB WAY. */
155 mbWay?: PaymentMethodPreferenceInput;
156 /** Display preference for MobilePay. */
157 mobilepay?: PaymentMethodPreferenceInput;
158 /** Display preference for Multibanco. */
159 multibanco?: PaymentMethodPreferenceInput;
160 /** Display preference for Naver Pay. */
161 naverPay?: PaymentMethodPreferenceInput;
162 /** Display preference for NZ BECS Debit. */
163 nzBankAccount?: PaymentMethodPreferenceInput;
164 /** Display preference for OXXO. */
165 oxxo?: PaymentMethodPreferenceInput;
166 /** Display preference for Przelewy24. */
167 p24?: PaymentMethodPreferenceInput;
168 /** Display preference for Pay by Bank. */
169 payByBank?: PaymentMethodPreferenceInput;
170 /** Display preference for PAYCO. */
171 payco?: PaymentMethodPreferenceInput;
172 /** Display preference for PayNow. */
173 paynow?: PaymentMethodPreferenceInput;
174 /** Display preference for PayPal. */
175 paypal?: PaymentMethodPreferenceInput;
176 /** Display preference for PayTo. */
177 payto?: PaymentMethodPreferenceInput;
178 /** Display preference for Pix. */
179 pix?: PaymentMethodPreferenceInput;
180 /** Display preference for PromptPay. */
181 promptpay?: PaymentMethodPreferenceInput;
182 /** Display preference for Revolut Pay. */
183 revolutPay?: PaymentMethodPreferenceInput;
184 /** Display preference for Samsung Pay. */
185 samsungPay?: PaymentMethodPreferenceInput;
186 /** Display preference for Satispay. */
187 satispay?: PaymentMethodPreferenceInput;
188 /** Display preference for Scalapay. */
189 scalapay?: PaymentMethodPreferenceInput;
190 /** Display preference for SEPA Debit. */
191 sepaDebit?: PaymentMethodPreferenceInput;
192 /** Display preference for Sofort. */
193 sofort?: PaymentMethodPreferenceInput;
194 /** Display preference for Sunbit. */
195 sunbit?: PaymentMethodPreferenceInput;
196 /** Display preference for Swish. */
197 swish?: PaymentMethodPreferenceInput;
198 /** Display preference for Twint. */
199 twint?: PaymentMethodPreferenceInput;
200 /** Display preference for UPI. */
201 upi?: PaymentMethodPreferenceInput;
202 /** Display preference for US bank account (ACH). */
203 usBankAccount?: PaymentMethodPreferenceInput;
204 /** Display preference for WeChat Pay. */
205 wechatPay?: PaymentMethodPreferenceInput;
206 /** Display preference for Zip. */
207 zip?: PaymentMethodPreferenceInput;
208 }
209
210 type MethodKey = Exclude<keyof PaymentMethodConfigurationProps, "name" | "active" | "parent">;
211
212 type SnakeMethodKey = (typeof METHOD_MAP)[number][1];
213
214 const METHOD_MAP = [
215 ["acssDebit", "acss_debit"],
216 ["affirm", "affirm"],
217 ["afterpayClearpay", "afterpay_clearpay"],
218 ["alipay", "alipay"],
219 ["alma", "alma"],
220 ["amazonPay", "amazon_pay"],
221 ["applePay", "apple_pay"],
222 ["auBecsDebit", "au_becs_debit"],
223 ["bacsDebit", "bacs_debit"],
224 ["bancontact", "bancontact"],
225 ["billie", "billie"],
226 ["bizum", "bizum"],
227 ["blik", "blik"],
228 ["boleto", "boleto"],
229 ["card", "card"],
230 ["cartesBancaires", "cartes_bancaires"],
231 ["cashapp", "cashapp"],
232 ["crypto", "crypto"],
233 ["customerBalance", "customer_balance"],
234 ["eps", "eps"],
235 ["fpx", "fpx"],
236 ["giropay", "giropay"],
237 ["googlePay", "google_pay"],
238 ["grabpay", "grabpay"],
239 ["ideal", "ideal"],
240 ["jcb", "jcb"],
241 ["kakaoPay", "kakao_pay"],
242 ["klarna", "klarna"],
243 ["konbini", "konbini"],
244 ["krCard", "kr_card"],
245 ["link", "link"],
246 ["mbWay", "mb_way"],
247 ["mobilepay", "mobilepay"],
248 ["multibanco", "multibanco"],
249 ["naverPay", "naver_pay"],
250 ["nzBankAccount", "nz_bank_account"],
251 ["oxxo", "oxxo"],
252 ["p24", "p24"],
253 ["payByBank", "pay_by_bank"],
254 ["payco", "payco"],
255 ["paynow", "paynow"],
256 ["paypal", "paypal"],
257 ["payto", "payto"],
258 ["pix", "pix"],
259 ["promptpay", "promptpay"],
260 ["revolutPay", "revolut_pay"],
261 ["samsungPay", "samsung_pay"],
262 ["satispay", "satispay"],
263 ["scalapay", "scalapay"],
264 ["sepaDebit", "sepa_debit"],
265 ["sofort", "sofort"],
266 ["sunbit", "sunbit"],
267 ["swish", "swish"],
268 ["twint", "twint"],
269 ["upi", "upi"],
270 ["usBankAccount", "us_bank_account"],
271 ["wechatPay", "wechat_pay"],
272 ["zip", "zip"],
273 ] as const satisfies ReadonlyArray<readonly [MethodKey, string]>;
274
275 type PaymentMethodAttributes = {
276 [K in MethodKey]: PaymentMethodState | undefined;
277 };
278
279 export type PaymentMethodConfiguration = Resource<
280 "Stripe.PaymentMethodConfiguration",
281 PaymentMethodConfigurationProps,
282 {
283 /** Stripe payment method configuration id (`pmc_…`). */
284 id: string;
285 /** Configuration name. */
286 name: string;
287 /** Whether the configuration can be used for new payments. */
288 active: boolean;
289 /** Whether this is the account's default configuration. */
290 isDefault: boolean;
291 /** Parent configuration id, if this is a child config. */
292 parent: string | undefined;
293 /** Connect application id for child configs, if any. */
294 application: string | undefined;
295 /** Whether the configuration exists in live mode. */
296 livemode: boolean;
297 } & PaymentMethodAttributes,
298 never,
299 Providers
300 >;
301
302 /**
303 * A Stripe Payment Method Configuration — which payment methods Checkout,
304 * PaymentIntents, and SetupIntents show when payment method types are not
305 * set explicitly. `name` and per-method `displayPreference` update in
306 * place. `parent` is create-only and changing it replaces the
307 * configuration.
308 *
309 * Payment method configurations have no metadata field and cannot be
310 * hard-deleted. Destroying this resource deactivates it (`active: false`).
311 * Identity is the Stripe id plus the unique name.
312 *
313 * @see https://docs.stripe.com/api/payment_method_configurations
314 *
315 * ### Creating a Configuration
316 * **Example:** Named checkout configuration
317 * ```typescript
318 * const checkout = yield* Stripe.PaymentMethodConfiguration("checkout", {
319 * name: "Checkout",
320 * card: { displayPreference: { preference: "on" } },
321 * link: { displayPreference: { preference: "on" } },
322 * });
323 * ```
324 *
325 * **Example:** Cards only
326 * ```typescript
327 * const cards = yield* Stripe.PaymentMethodConfiguration("cards", {
328 * name: "Cards only",
329 * card: { displayPreference: { preference: "on" } },
330 * link: { displayPreference: { preference: "off" } },
331 * applePay: { displayPreference: { preference: "off" } },
332 * googlePay: { displayPreference: { preference: "off" } },
333 * });
334 * ```
335 *
336 * ### Updating a Configuration
337 * **Example:** Rename and enable US bank account
338 * ```typescript
339 * const checkout = yield* Stripe.PaymentMethodConfiguration("checkout", {
340 * name: "Checkout (updated)",
341 * card: { displayPreference: { preference: "on" } },
342 * usBankAccount: { displayPreference: { preference: "on" } },
343 * });
344 * ```
345 *
346 * ### Deactivating a Configuration
347 * **Example:** Destroy deactivates rather than deleting
348 * ```typescript
349 * // stack.destroy() / resource removal sets active: false
350 * const checkout = yield* Stripe.PaymentMethodConfiguration("checkout", {
351 * name: "Checkout",
352 * });
353 * ```
354 *
355 * @resource
356 * @product Payment Methods
357 */
358 export const PaymentMethodConfiguration = Resource<PaymentMethodConfiguration>(
359 "Stripe.PaymentMethodConfiguration",
360 );
361
362 export class PaymentMethodConfigurationNotResolved extends Data.TaggedError(
363 "Stripe.PaymentMethodConfigurationNotResolved",
364 )<{
365 resourceName: string;
366 }> {}
367
368 type ConfigurationAttributes = PaymentMethodConfiguration["Attributes"];
369
370 type WireMethod = {
371 display_preference: { preference: PaymentMethodPreference };
372 };
373
374 const toName = (id: string, name: string | undefined, existing?: string) =>
375 Effect.gen(function* () {
376 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }));
377 });
378
379 const toMethodState = (
380 value: PaymentMethodConfigResourcePaymentMethodProperties | undefined,
381 ): PaymentMethodState | undefined => {
382 if (value === undefined) return undefined;
383 return {
384 available: value.available,
385 displayPreference: {
386 overridable: value.display_preference.overridable ?? undefined,
387 preference: value.display_preference.preference,
388 value: value.display_preference.value,
389 },
390 };
391 };
392
393 const readMethod = (
394 configuration: StripePaymentMethodConfiguration,
395 snake: SnakeMethodKey,
396 ): PaymentMethodState | undefined => toMethodState(configuration[snake]);
397
398 const toAttrs = (configuration: StripePaymentMethodConfiguration): ConfigurationAttributes => {
399 const methods = {} as PaymentMethodAttributes;
400 for (const [camel, snake] of METHOD_MAP) {
401 methods[camel] = readMethod(configuration, snake);
402 }
403 return {
404 id: configuration.id,
405 name: configuration.name,
406 active: configuration.active,
407 isDefault: configuration.is_default,
408 parent: configuration.parent ?? undefined,
409 application: configuration.application ?? undefined,
410 livemode: configuration.livemode,
411 ...methods,
412 };
413 };
414
415 const toWireMethods = (
416 news: PaymentMethodConfigurationProps,
417 ): Partial<Record<SnakeMethodKey, WireMethod>> => {
418 const payload: Partial<Record<SnakeMethodKey, WireMethod>> = {};
419 for (const [camel, snake] of METHOD_MAP) {
420 const preference = news[camel]?.displayPreference?.preference;
421 if (preference !== undefined) {
422 payload[snake] = { display_preference: { preference } };
423 }
424 }
425 return payload;
426 };
427
428 const toChangedWireMethods = (
429 news: PaymentMethodConfigurationProps,
430 current: StripePaymentMethodConfiguration,
431 ): Partial<Record<SnakeMethodKey, WireMethod>> => {
432 const payload: Partial<Record<SnakeMethodKey, WireMethod>> = {};
433 for (const [camel, snake] of METHOD_MAP) {
434 const desired = news[camel]?.displayPreference?.preference;
435 if (desired === undefined) continue;
436 const observed = readMethod(current, snake)?.displayPreference.preference;
437 if (desired !== observed) {
438 payload[snake] = { display_preference: { preference: desired } };
439 }
440 }
441 return payload;
442 };
443
444 const isMissingConfiguration = isMissingStripeResource;
445
446 const getById = (configuration: string) =>
447 GetPaymentMethodConfiguration({ configuration }).pipe(
448 Effect.catchIf(isMissingConfiguration, () => Effect.undefined),
449 );
450
451 const listByActive = Effect.fn(function* (active: boolean) {
452 const configurations: StripePaymentMethodConfiguration[] = [];
453 let startingAfter: string | undefined;
454 for (let page = 0; page < LIST_MAX_PAGES; page++) {
455 const response = yield* GetPaymentMethodConfigurations({
456 active,
457 limit: LIST_PAGE_SIZE,
458 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
459 });
460 configurations.push(...response.data);
461 if (!response.has_more || response.data.length === 0) {
462 break;
463 }
464 startingAfter = response.data[response.data.length - 1]?.id;
465 if (startingAfter === undefined) {
466 break;
467 }
468 }
469 return configurations;
470 });
471
472 const listAllConfigurations = Effect.fn(function* () {
473 const [active, inactive] = yield* Effect.all([listByActive(true), listByActive(false)], {
474 concurrency: 2,
475 });
476 const seen = new Set<string>();
477 const configurations: StripePaymentMethodConfiguration[] = [];
478 for (const configuration of [...active, ...inactive]) {
479 if (seen.has(configuration.id)) continue;
480 seen.add(configuration.id);
481 configurations.push(configuration);
482 }
483 return configurations;
484 });
485
486 const findByName = Effect.fn(function* (name: string) {
487 const configurations = yield* listAllConfigurations();
488 const matches = configurations.filter(
489 (configuration) => configuration.name === name && !configuration.is_default,
490 );
491 return matches.find((configuration) => configuration.active) ?? matches[0];
492 });
493
494 const observe = Effect.fn(function* (input: { id?: string; name?: string }) {
495 if (input.id !== undefined) {
496 const byId = yield* getById(input.id);
497 if (byId !== undefined) return byId;
498 }
499 if (input.name !== undefined) {
500 return yield* findByName(input.name);
501 }
502 return undefined;
503 });
504
505 const shouldReplace = (
506 news: PaymentMethodConfigurationProps,
507 output: ConfigurationAttributes | undefined,
508 ): boolean => {
509 if (output === undefined) return false;
510 if (news.parent !== undefined && news.parent !== output.parent) {
511 return true;
512 }
513 return false;
514 };
515
516 export const PaymentMethodConfigurationProvider = () =>
517 Provider.succeed(PaymentMethodConfiguration, {
518 stables: ["id", "parent", "application", "isDefault", "livemode"],
519
520 diff: Effect.fn(function* ({ news, output }) {
521 if (!isResolved(news)) return undefined;
522 if (shouldReplace(news, output)) {
523 return { action: "replace" } as const;
524 }
525 return undefined;
526 }),
527
528 read: Effect.fn(function* ({ output }) {
529 const existing = yield* observe({
530 id: output?.id,
531 name: output?.name,
532 });
533 if (existing === undefined) return undefined;
534 const attrs = toAttrs(existing);
535 // No metadata. Identity is the Stripe id and unique name. Never
536 // take over the account default configuration.
537 return existing.is_default ? Unowned(attrs) : attrs;
538 }),
539
540 list: Effect.fn(function* () {
541 // No metadata on this resource. Default list is active, non-default
542 // configurations; deactivated rows stay in Stripe but must not
543 // re-enter nuke. The account default is never returned.
544 const configurations = yield* listByActive(true);
545 return configurations.filter((configuration) => !configuration.is_default).map(toAttrs);
546 }),
547
548 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
549 const name = yield* toName(id, news.name, output?.name);
550 const desiredActive = news.active ?? true;
551 const wireMethods = toWireMethods(news);
552
553 let current = yield* observe({
554 id: output?.id,
555 name,
556 });
557 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
558 current = undefined;
559 }
560 if (current?.is_default) {
561 current = undefined;
562 }
563
564 if (current === undefined) {
565 current = yield* CreatePaymentMethodConfiguration({
566 name,
567 ...(news.parent !== undefined ? { parent: news.parent } : {}),
568 ...wireMethods,
569 }).pipe(
570 withRequestOptions({
571 idempotencyKey: `alchemy-payment-method-configuration-${instanceId}`,
572 }),
573 );
574 }
575
576 if (current === undefined) {
577 return yield* new PaymentMethodConfigurationNotResolved({ resourceName: name });
578 }
579
580 const nameChanged = current.name !== name;
581 const activeChanged = current.active !== desiredActive;
582 const changedMethods = toChangedWireMethods(news, current);
583 const methodsChanged = Object.keys(changedMethods).length > 0;
584
585 if (!nameChanged && !activeChanged && !methodsChanged) {
586 return toAttrs(current);
587 }
588
589 const updated = yield* UpdatePaymentMethodConfiguration({
590 configuration: current.id,
591 ...(nameChanged ? { name } : {}),
592 ...(activeChanged ? { active: desiredActive } : {}),
593 ...(methodsChanged ? changedMethods : {}),
594 });
595 return toAttrs(updated);
596 }),
597
598 delete: Effect.fn(function* ({ output }) {
599 const existing = yield* getById(output.id);
600 if (existing === undefined || !existing.active || existing.is_default) {
601 return;
602 }
603 yield* UpdatePaymentMethodConfiguration({
604 configuration: existing.id,
605 active: false,
606 }).pipe(Effect.catchIf(isMissingConfiguration, () => Effect.void));
607 }),
608 });