The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { withRequestOptions } from "@distilled.cloud/stripe"; |
| 2 | import { |
| 3 | DeleteAccountExternalAccount, |
| 4 | GetAccounts, |
| 5 | GetAccountExternalAccounts, |
| 6 | GetAccountExternalAccount, |
| 7 | CreateAccountExternalAccount, |
| 8 | UpdateAccountExternalAccount, |
| 9 | type Account as StripeAccount, |
| 10 | type BankAccount as StripeBankAccount, |
| 11 | type Card as StripeCard, |
| 12 | type ExternalAccount as StripeExternalAccount, |
| 13 | } from "@distilled.cloud/stripe/stripe"; |
| 14 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 15 | import { isResolved } from "alchemy/Diff"; |
| 16 | import * as Provider from "alchemy/Provider"; |
| 17 | import { Resource } from "alchemy/Resource"; |
| 18 | import { tagRecord } from "alchemy/Tags"; |
| 19 | import * as Effect from "effect/Effect"; |
| 20 | import { |
| 21 | alchemyMetadataKeys, |
| 22 | createInternalMetadata, |
| 23 | diffMetadata, |
| 24 | hasAlchemyMetadata, |
| 25 | stripInternalMetadata, |
| 26 | toMetadata, |
| 27 | } from "./Metadata.ts"; |
| 28 | import { isMissingStripeResource } from "./missing.ts"; |
| 29 | import type { Providers } from "./Providers.ts"; |
| 30 | |
| 31 | const LIST_PAGE_SIZE = 100; |
| 32 | const LIST_MAX_PAGES = 100; |
| 33 | const LIST_CONCURRENCY = 10; |
| 34 | |
| 35 | /** Entity that holds a bank external account. */ |
| 36 | export type AccountExternalAccountHolderType = "individual" | "company"; |
| 37 | |
| 38 | /** Bank account type. `futsu` / `toza` are Japan-only. */ |
| 39 | export type AccountExternalAccountBankType = "checking" | "savings" | "futsu" | "toza"; |
| 40 | |
| 41 | /** Discriminator for a bank vs card external account. */ |
| 42 | export type AccountExternalAccountObject = "bank_account" | "card"; |
| 43 | |
| 44 | export interface AccountExternalAccountProps { |
| 45 | /** |
| 46 | * Id of the Connect account this external account is attached to |
| 47 | * (`acct_…`). Changing it replaces the external account. |
| 48 | */ |
| 49 | account: string; |
| 50 | /** |
| 51 | * Single-use Stripe token (`btok_…` or `tok_…`) representing a bank |
| 52 | * account or debit card. Used on create; changing it replaces the |
| 53 | * external account. Tokens cannot be reused. |
| 54 | */ |
| 55 | externalAccount: string; |
| 56 | /** |
| 57 | * When true, this becomes the default payout destination for its |
| 58 | * currency. The first external account in a currency is default |
| 59 | * automatically. |
| 60 | */ |
| 61 | defaultForCurrency?: boolean; |
| 62 | /** |
| 63 | * Name of the person or business that owns the bank account (bank |
| 64 | * accounts only). |
| 65 | */ |
| 66 | accountHolderName?: string; |
| 67 | /** |
| 68 | * Type of entity that holds the bank account (`individual` or |
| 69 | * `company`). Bank accounts only. |
| 70 | */ |
| 71 | accountHolderType?: AccountExternalAccountHolderType; |
| 72 | /** |
| 73 | * Bank account type (`checking`, `savings`, `futsu`, or `toza`). Bank |
| 74 | * accounts only. |
| 75 | */ |
| 76 | accountType?: AccountExternalAccountBankType; |
| 77 | /** |
| 78 | * Cardholder name (cards only). |
| 79 | */ |
| 80 | name?: string; |
| 81 | /** |
| 82 | * User-defined metadata. Alchemy ownership keys (`alchemy_stack` / |
| 83 | * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may |
| 84 | * not contain `:`. |
| 85 | */ |
| 86 | metadata?: Record<string, string>; |
| 87 | } |
| 88 | |
| 89 | export type AccountExternalAccount = Resource< |
| 90 | "Stripe.AccountExternalAccount", |
| 91 | AccountExternalAccountProps, |
| 92 | { |
| 93 | /** Stripe external account id (`ba_…` or `card_…`). */ |
| 94 | id: string; |
| 95 | /** Id of the Connect account (`acct_…`). */ |
| 96 | account: string; |
| 97 | /** Whether this is a bank account or a card. */ |
| 98 | object: AccountExternalAccountObject; |
| 99 | /** Last four digits of the account or card number. */ |
| 100 | last4: string; |
| 101 | /** Two-letter ISO country code of the bank or card. */ |
| 102 | country: string; |
| 103 | /** Three-letter ISO currency code, if set. */ |
| 104 | currency: string | undefined; |
| 105 | /** Bank name associated with the routing number (bank accounts only). */ |
| 106 | bankName: string | undefined; |
| 107 | /** Routing transit number (bank accounts only). */ |
| 108 | routingNumber: string | undefined; |
| 109 | /** Name of the person or business that owns the bank account. */ |
| 110 | accountHolderName: string | undefined; |
| 111 | /** Type of entity that holds the bank account. */ |
| 112 | accountHolderType: string | undefined; |
| 113 | /** Bank account type (`checking`, `savings`, …). */ |
| 114 | accountType: string | undefined; |
| 115 | /** Whether this is the default external account for its currency. */ |
| 116 | defaultForCurrency: boolean; |
| 117 | /** Status (`new`, `validated`, `errored`, …). */ |
| 118 | status: string | undefined; |
| 119 | /** Card brand (cards only). */ |
| 120 | brand: string | undefined; |
| 121 | /** Card funding type (`debit`, `credit`, …) (cards only). */ |
| 122 | funding: string | undefined; |
| 123 | /** Cardholder name (cards only). */ |
| 124 | name: string | undefined; |
| 125 | /** Fingerprint uniquely identifying the underlying number. */ |
| 126 | fingerprint: string | undefined; |
| 127 | /** User-defined metadata (Alchemy ownership keys stripped). */ |
| 128 | metadata: Record<string, string>; |
| 129 | }, |
| 130 | never, |
| 131 | Providers |
| 132 | >; |
| 133 | |
| 134 | /** |
| 135 | * A Stripe Account External Account — a bank account or debit card |
| 136 | * attached to a Connect account as a payout destination. Metadata, |
| 137 | * account-holder details, and `defaultForCurrency` update in place. |
| 138 | * Changing `account` or the `externalAccount` token replaces it. |
| 139 | * Destroy deletes it. |
| 140 | * |
| 141 | * @see https://docs.stripe.com/api/external_accounts |
| 142 | * |
| 143 | * ### Creating an External Account |
| 144 | * **Example:** Bank account token on a Connect account |
| 145 | * ```typescript |
| 146 | * const payout = yield* Stripe.AccountExternalAccount("payout-bank", { |
| 147 | * account: connected.id, |
| 148 | * externalAccount: bankToken.id, |
| 149 | * accountHolderName: "Jenny Rosen", |
| 150 | * accountHolderType: "individual", |
| 151 | * metadata: { purpose: "payouts" }, |
| 152 | * }); |
| 153 | * ``` |
| 154 | * |
| 155 | * **Example:** Debit card token |
| 156 | * ```typescript |
| 157 | * const payout = yield* Stripe.AccountExternalAccount("payout-card", { |
| 158 | * account: connected.id, |
| 159 | * externalAccount: debitToken.id, |
| 160 | * defaultForCurrency: true, |
| 161 | * }); |
| 162 | * ``` |
| 163 | * |
| 164 | * ### Updating an External Account |
| 165 | * **Example:** Holder name, default, and metadata |
| 166 | * ```typescript |
| 167 | * const payout = yield* Stripe.AccountExternalAccount("payout-bank", { |
| 168 | * account: connected.id, |
| 169 | * externalAccount: bankToken.id, |
| 170 | * accountHolderName: "Alchemy Tester", |
| 171 | * accountHolderType: "company", |
| 172 | * defaultForCurrency: true, |
| 173 | * metadata: { purpose: "payroll" }, |
| 174 | * }); |
| 175 | * ``` |
| 176 | * |
| 177 | * @resource |
| 178 | * @product Account |
| 179 | */ |
| 180 | export const AccountExternalAccount = Resource<AccountExternalAccount>( |
| 181 | "Stripe.AccountExternalAccount", |
| 182 | ); |
| 183 | |
| 184 | type AccountExternalAccountAttributes = AccountExternalAccount["Attributes"]; |
| 185 | |
| 186 | const userMetadata = ( |
| 187 | metadata: Record<string, string | undefined> | null | undefined, |
| 188 | ): Record<string, string> => stripInternalMetadata(tagRecord(metadata)); |
| 189 | |
| 190 | const isBankAccount = (value: StripeExternalAccount): value is StripeBankAccount => |
| 191 | value.object === "bank_account"; |
| 192 | |
| 193 | const parentAccountId = (ea: StripeExternalAccount, fallback: string): string => { |
| 194 | const raw = ea.account; |
| 195 | if (typeof raw === "string" && raw.length > 0) return raw; |
| 196 | if (raw !== null && raw !== undefined && typeof raw === "object") { |
| 197 | const id = (raw as { id?: unknown }).id; |
| 198 | if (typeof id === "string" && id.length > 0) return id; |
| 199 | } |
| 200 | return fallback; |
| 201 | }; |
| 202 | |
| 203 | const toAttrs = ( |
| 204 | fallbackAccount: string, |
| 205 | ea: StripeExternalAccount, |
| 206 | ): AccountExternalAccountAttributes => { |
| 207 | const account = parentAccountId(ea, fallbackAccount); |
| 208 | const metadata = userMetadata(ea.metadata); |
| 209 | if (!isBankAccount(ea)) { |
| 210 | const card: StripeCard = ea; |
| 211 | return { |
| 212 | id: card.id, |
| 213 | account, |
| 214 | object: "card", |
| 215 | last4: card.last4, |
| 216 | country: card.country ?? "", |
| 217 | currency: card.currency ?? undefined, |
| 218 | bankName: undefined, |
| 219 | routingNumber: undefined, |
| 220 | accountHolderName: undefined, |
| 221 | accountHolderType: undefined, |
| 222 | accountType: undefined, |
| 223 | defaultForCurrency: card.default_for_currency ?? false, |
| 224 | status: card.status ?? undefined, |
| 225 | brand: card.brand, |
| 226 | funding: card.funding, |
| 227 | name: card.name ?? undefined, |
| 228 | fingerprint: card.fingerprint ?? undefined, |
| 229 | metadata, |
| 230 | }; |
| 231 | } |
| 232 | return { |
| 233 | id: ea.id, |
| 234 | account, |
| 235 | object: "bank_account", |
| 236 | last4: ea.last4, |
| 237 | country: ea.country, |
| 238 | currency: ea.currency, |
| 239 | bankName: ea.bank_name ?? undefined, |
| 240 | routingNumber: ea.routing_number ?? undefined, |
| 241 | accountHolderName: ea.account_holder_name ?? undefined, |
| 242 | accountHolderType: ea.account_holder_type ?? undefined, |
| 243 | accountType: ea.account_type ?? undefined, |
| 244 | defaultForCurrency: ea.default_for_currency ?? false, |
| 245 | status: ea.status, |
| 246 | brand: undefined, |
| 247 | funding: undefined, |
| 248 | name: undefined, |
| 249 | fingerprint: ea.fingerprint ?? undefined, |
| 250 | metadata, |
| 251 | }; |
| 252 | }; |
| 253 | |
| 254 | const isMissing = isMissingStripeResource; |
| 255 | |
| 256 | const getById = (account: string, id: string) => |
| 257 | GetAccountExternalAccount({ account, id }).pipe( |
| 258 | Effect.catchIf(isMissing, () => Effect.undefined), |
| 259 | ); |
| 260 | |
| 261 | const listExternalAccounts = Effect.fn(function* (account: string) { |
| 262 | const accounts: StripeExternalAccount[] = []; |
| 263 | let startingAfter: string | undefined; |
| 264 | for (let page = 0; page < LIST_MAX_PAGES; page++) { |
| 265 | const response = yield* GetAccountExternalAccounts({ |
| 266 | account, |
| 267 | limit: LIST_PAGE_SIZE, |
| 268 | ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}), |
| 269 | }).pipe(Effect.catchIf(isMissing, () => Effect.undefined)); |
| 270 | if (response === undefined) { |
| 271 | break; |
| 272 | } |
| 273 | accounts.push(...response.data); |
| 274 | if (!response.has_more || response.data.length === 0) { |
| 275 | break; |
| 276 | } |
| 277 | startingAfter = response.data[response.data.length - 1]?.id; |
| 278 | if (startingAfter === undefined) { |
| 279 | break; |
| 280 | } |
| 281 | } |
| 282 | return accounts; |
| 283 | }); |
| 284 | |
| 285 | const listAllConnectAccounts = Effect.fn(function* () { |
| 286 | const accounts: StripeAccount[] = []; |
| 287 | let startingAfter: string | undefined; |
| 288 | for (let page = 0; page < LIST_MAX_PAGES; page++) { |
| 289 | const response = yield* GetAccounts({ |
| 290 | limit: LIST_PAGE_SIZE, |
| 291 | ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}), |
| 292 | }).pipe( |
| 293 | Effect.catchIf( |
| 294 | (e) => |
| 295 | e._tag === "InvalidRequestError" || e._tag === "Forbidden" || e._tag === "Unauthorized", |
| 296 | () => Effect.undefined, |
| 297 | ), |
| 298 | ); |
| 299 | if (response === undefined) { |
| 300 | break; |
| 301 | } |
| 302 | accounts.push(...response.data); |
| 303 | if (!response.has_more || response.data.length === 0) { |
| 304 | break; |
| 305 | } |
| 306 | startingAfter = response.data[response.data.length - 1]?.id; |
| 307 | if (startingAfter === undefined) { |
| 308 | break; |
| 309 | } |
| 310 | } |
| 311 | return accounts; |
| 312 | }); |
| 313 | |
| 314 | const findByAlchemyId = Effect.fn(function* (logicalId: string, account?: string) { |
| 315 | const search = Effect.fn(function* (accountId: string) { |
| 316 | const eas = yield* listExternalAccounts(accountId); |
| 317 | const matches: StripeExternalAccount[] = []; |
| 318 | for (const ea of eas) { |
| 319 | if (yield* hasAlchemyMetadata(logicalId, tagRecord(ea.metadata))) { |
| 320 | matches.push(ea); |
| 321 | } |
| 322 | } |
| 323 | return matches[0]; |
| 324 | }); |
| 325 | if (account !== undefined) { |
| 326 | return yield* search(account); |
| 327 | } |
| 328 | const accounts = yield* listAllConnectAccounts(); |
| 329 | for (const acct of accounts) { |
| 330 | const found = yield* search(acct.id); |
| 331 | if (found !== undefined) return found; |
| 332 | } |
| 333 | return undefined; |
| 334 | }); |
| 335 | |
| 336 | const observe = Effect.fn(function* (input: { account?: string; id?: string; logicalId: string }) { |
| 337 | if (input.account !== undefined && input.id !== undefined) { |
| 338 | const byId = yield* getById(input.account, input.id); |
| 339 | if (byId !== undefined) return byId; |
| 340 | } |
| 341 | return yield* findByAlchemyId(input.logicalId, input.account); |
| 342 | }); |
| 343 | |
| 344 | const desiredMetadata = Effect.fn(function* ( |
| 345 | id: string, |
| 346 | metadata: Record<string, string> | undefined, |
| 347 | ) { |
| 348 | return { |
| 349 | ...toMetadata(metadata), |
| 350 | ...(yield* createInternalMetadata(id)), |
| 351 | }; |
| 352 | }); |
| 353 | |
| 354 | const shouldReplace = ( |
| 355 | news: AccountExternalAccountProps, |
| 356 | olds: AccountExternalAccountProps | undefined, |
| 357 | output: AccountExternalAccountAttributes | undefined, |
| 358 | ): boolean => { |
| 359 | if (output === undefined) return false; |
| 360 | if (news.account !== output.account) return true; |
| 361 | if ( |
| 362 | olds !== undefined && |
| 363 | olds.externalAccount !== undefined && |
| 364 | news.externalAccount !== olds.externalAccount |
| 365 | ) { |
| 366 | return true; |
| 367 | } |
| 368 | return false; |
| 369 | }; |
| 370 | |
| 371 | export const AccountExternalAccountProvider = () => |
| 372 | Provider.succeed(AccountExternalAccount, { |
| 373 | stables: [ |
| 374 | "id", |
| 375 | "account", |
| 376 | "object", |
| 377 | "last4", |
| 378 | "country", |
| 379 | "currency", |
| 380 | "bankName", |
| 381 | "routingNumber", |
| 382 | "fingerprint", |
| 383 | "brand", |
| 384 | "funding", |
| 385 | ], |
| 386 | nuke: { dependsOn: ["Stripe.Account"] }, |
| 387 | |
| 388 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 389 | if (!isResolved(news)) return undefined; |
| 390 | if (shouldReplace(news, olds, output)) { |
| 391 | return { action: "replace" } as const; |
| 392 | } |
| 393 | return undefined; |
| 394 | }), |
| 395 | |
| 396 | read: Effect.fn(function* ({ id, output, olds }) { |
| 397 | const account = |
| 398 | output?.account ?? (typeof olds?.account === "string" ? olds.account : undefined); |
| 399 | const existing = yield* observe({ |
| 400 | account, |
| 401 | id: output?.id, |
| 402 | logicalId: id, |
| 403 | }); |
| 404 | if (existing === undefined || account === undefined) return undefined; |
| 405 | const attrs = toAttrs(account, existing); |
| 406 | return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs); |
| 407 | }), |
| 408 | |
| 409 | list: Effect.fn(function* () { |
| 410 | const accounts = yield* listAllConnectAccounts(); |
| 411 | const rows = yield* Effect.forEach( |
| 412 | accounts, |
| 413 | (account) => |
| 414 | listExternalAccounts(account.id).pipe( |
| 415 | Effect.map((eas) => |
| 416 | eas |
| 417 | .filter((ea) => tagRecord(ea.metadata)[alchemyMetadataKeys.stack] !== undefined) |
| 418 | .map((ea) => toAttrs(account.id, ea)), |
| 419 | ), |
| 420 | ), |
| 421 | { concurrency: LIST_CONCURRENCY }, |
| 422 | ); |
| 423 | return rows.flat(); |
| 424 | }), |
| 425 | |
| 426 | reconcile: Effect.fn(function* ({ id, news, olds, output, instanceId }) { |
| 427 | const metadata = yield* desiredMetadata(id, news.metadata); |
| 428 | const desiredHolderName = news.accountHolderName ?? ""; |
| 429 | const desiredHolderType = news.accountHolderType ?? ""; |
| 430 | const desiredAccountType = news.accountType; |
| 431 | const desiredName = news.name ?? ""; |
| 432 | const desiredDefault = news.defaultForCurrency; |
| 433 | |
| 434 | let current = yield* observe({ |
| 435 | account: news.account, |
| 436 | id: output?.id, |
| 437 | logicalId: id, |
| 438 | }); |
| 439 | if (current !== undefined && shouldReplace(news, olds, toAttrs(news.account, current))) { |
| 440 | current = undefined; |
| 441 | } |
| 442 | |
| 443 | if (current === undefined) { |
| 444 | current = yield* CreateAccountExternalAccount({ |
| 445 | account: news.account, |
| 446 | external_account: news.externalAccount, |
| 447 | metadata, |
| 448 | ...(desiredDefault !== undefined ? { default_for_currency: desiredDefault } : {}), |
| 449 | }).pipe( |
| 450 | withRequestOptions({ |
| 451 | idempotencyKey: `alchemy-account-external-account-${instanceId}`, |
| 452 | }), |
| 453 | Effect.catchIf( |
| 454 | (e) => e._tag === "InvalidRequestError" || e._tag === "Conflict", |
| 455 | (e) => |
| 456 | observe({ |
| 457 | account: news.account, |
| 458 | logicalId: id, |
| 459 | }).pipe( |
| 460 | Effect.flatMap((found) => |
| 461 | found !== undefined ? Effect.succeed(found) : Effect.fail(e), |
| 462 | ), |
| 463 | ), |
| 464 | ), |
| 465 | ); |
| 466 | } |
| 467 | |
| 468 | const attrs = toAttrs(news.account, current); |
| 469 | const observedMetadata = tagRecord(current.metadata); |
| 470 | const { upsert, removed } = diffMetadata(observedMetadata, metadata); |
| 471 | const metadataChanged = upsert.length > 0 || removed.length > 0; |
| 472 | const defaultChanged = |
| 473 | desiredDefault !== undefined && attrs.defaultForCurrency !== desiredDefault; |
| 474 | const holderNameChanged = |
| 475 | attrs.object === "bank_account" && (attrs.accountHolderName ?? "") !== desiredHolderName; |
| 476 | const holderTypeChanged = |
| 477 | attrs.object === "bank_account" && (attrs.accountHolderType ?? "") !== desiredHolderType; |
| 478 | const accountTypeChanged = |
| 479 | attrs.object === "bank_account" && |
| 480 | desiredAccountType !== undefined && |
| 481 | (attrs.accountType ?? "") !== desiredAccountType; |
| 482 | const nameChanged = attrs.object === "card" && (attrs.name ?? "") !== desiredName; |
| 483 | |
| 484 | if ( |
| 485 | !metadataChanged && |
| 486 | !defaultChanged && |
| 487 | !holderNameChanged && |
| 488 | !holderTypeChanged && |
| 489 | !accountTypeChanged && |
| 490 | !nameChanged |
| 491 | ) { |
| 492 | return attrs; |
| 493 | } |
| 494 | |
| 495 | const updated = yield* UpdateAccountExternalAccount({ |
| 496 | account: news.account, |
| 497 | id: current.id, |
| 498 | ...(holderNameChanged ? { account_holder_name: desiredHolderName } : {}), |
| 499 | ...(holderTypeChanged |
| 500 | ? { |
| 501 | account_holder_type: |
| 502 | desiredHolderType === "" |
| 503 | ? "" |
| 504 | : (desiredHolderType as AccountExternalAccountHolderType), |
| 505 | } |
| 506 | : {}), |
| 507 | ...(accountTypeChanged && desiredAccountType !== undefined |
| 508 | ? { account_type: desiredAccountType } |
| 509 | : {}), |
| 510 | ...(nameChanged ? { name: desiredName } : {}), |
| 511 | ...(defaultChanged && desiredDefault !== undefined |
| 512 | ? { default_for_currency: desiredDefault } |
| 513 | : {}), |
| 514 | ...(metadataChanged |
| 515 | ? { |
| 516 | metadata: { |
| 517 | ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])), |
| 518 | ...Object.fromEntries(removed.map((key) => [key, ""])), |
| 519 | }, |
| 520 | } |
| 521 | : {}), |
| 522 | }); |
| 523 | return toAttrs(news.account, updated); |
| 524 | }), |
| 525 | |
| 526 | delete: Effect.fn(function* ({ output }) { |
| 527 | yield* DeleteAccountExternalAccount({ |
| 528 | account: output.account, |
| 529 | id: output.id, |
| 530 | }).pipe(Effect.catchIf(isMissing, () => Effect.void)); |
| 531 | }), |
| 532 | }); |