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

main
ts 305 lines 9.17 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 DeleteCustomer,
4 GetCustomers,
5 GetCustomer,
6 CreateCustomer,
7 UpdateCustomer,
8 type Customer as StripeCustomer,
9 type DeletedCustomer,
10 } from "@distilled.cloud/stripe/stripe";
11 import { Unowned } from "alchemy/AdoptPolicy";
12 import { isResolved } from "alchemy/Diff";
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 LIST_PAGE_SIZE = 100;
29 const LIST_MAX_PAGES = 100;
30
31 export interface CustomerProps {
32 /**
33 * Customer's email address. Displayed in the Stripe dashboard and
34 * useful for searching. At most 512 characters.
35 */
36 email?: string;
37 /**
38 * The customer's full name or business name.
39 */
40 name?: string;
41 /**
42 * An arbitrary string attached to the customer. Displayed alongside
43 * the customer in the dashboard.
44 */
45 description?: string;
46 /**
47 * The customer's phone number.
48 */
49 phone?: string;
50 /**
51 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
52 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
53 * not contain `:`.
54 */
55 metadata?: Record<string, string>;
56 }
57
58 export type Customer = Resource<
59 "Stripe.Customer",
60 CustomerProps,
61 {
62 /** Stripe customer id (`cus_…`). */
63 id: string;
64 /** Customer's email address, if set. */
65 email: string | undefined;
66 /** The customer's full name or business name, if set. */
67 name: string | undefined;
68 /** Arbitrary description displayed in the dashboard, if set. */
69 description: string | undefined;
70 /** The customer's phone number, if set. */
71 phone: string | undefined;
72 /** User-defined metadata (Alchemy ownership keys stripped). */
73 metadata: Record<string, string>;
74 /** Unix timestamp when the customer was created. */
75 created: number;
76 /** Whether the customer exists in live mode. */
77 livemode: boolean;
78 },
79 never,
80 Providers
81 >;
82
83 /**
84 * A Stripe Customer — the billing identity invoices, subscriptions, and
85 * Checkout sessions attach to. Email, name, description, phone, and
86 * metadata are updated in place. Deleting a customer is permanent and
87 * immediately cancels any active subscriptions.
88 *
89 * @see https://docs.stripe.com/api/customers
90 *
91 * ### Creating a Customer
92 * **Example:** Email and name
93 * ```typescript
94 * const customer = yield* Stripe.Customer("alice", {
95 * email: "alice@example.com",
96 * name: "Alice Example",
97 * });
98 * ```
99 *
100 * **Example:** Description, phone, and metadata
101 * ```typescript
102 * const customer = yield* Stripe.Customer("alice", {
103 * email: "alice@example.com",
104 * name: "Alice Example",
105 * description: "Beta tester",
106 * phone: "+15555550100",
107 * metadata: { plan: "pro" },
108 * });
109 * ```
110 *
111 * ### Updating a Customer
112 * **Example:** Change email and metadata
113 * ```typescript
114 * const customer = yield* Stripe.Customer("alice", {
115 * email: "alice+updated@example.com",
116 * name: "Alice Example",
117 * metadata: { plan: "enterprise" },
118 * });
119 * ```
120 *
121 * @resource
122 * @product Customer
123 */
124 export const Customer = Resource<Customer>("Stripe.Customer");
125
126 const userMetadata = (
127 metadata: Record<string, string | undefined> | null | undefined,
128 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
129
130 const isDeletedCustomer = (value: StripeCustomer | DeletedCustomer): value is DeletedCustomer =>
131 "deleted" in value && value.deleted === true;
132
133 const asCustomer = (
134 value: StripeCustomer | DeletedCustomer | undefined,
135 ): StripeCustomer | undefined => {
136 if (value === undefined || isDeletedCustomer(value)) return undefined;
137 return value;
138 };
139
140 const toAttrs = (customer: StripeCustomer) => ({
141 id: customer.id,
142 email: customer.email ?? undefined,
143 name: customer.name ?? undefined,
144 description: customer.description ?? undefined,
145 phone: customer.phone ?? undefined,
146 metadata: userMetadata(customer.metadata),
147 created: customer.created,
148 livemode: customer.livemode,
149 });
150
151 const isMissingCustomer = isMissingStripeResource;
152
153 const getById = (customer: string) =>
154 GetCustomer({ customer }).pipe(
155 Effect.map(asCustomer),
156 Effect.catchIf(isMissingCustomer, () => Effect.undefined),
157 );
158
159 const listAllCustomers = Effect.fn(function* () {
160 const customers: StripeCustomer[] = [];
161 let startingAfter: string | undefined;
162 for (let page = 0; page < LIST_MAX_PAGES; page++) {
163 const response = yield* GetCustomers({
164 limit: LIST_PAGE_SIZE,
165 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
166 });
167 customers.push(...response.data);
168 if (!response.has_more || response.data.length === 0) {
169 break;
170 }
171 startingAfter = response.data[response.data.length - 1]?.id;
172 if (startingAfter === undefined) {
173 break;
174 }
175 }
176 return customers;
177 });
178
179 const findByAlchemyId = Effect.fn(function* (id: string) {
180 const customers = yield* listAllCustomers();
181 const matches: StripeCustomer[] = [];
182 for (const customer of customers) {
183 if (yield* hasAlchemyMetadata(id, tagRecord(customer.metadata))) {
184 matches.push(customer);
185 }
186 }
187 matches.sort((a, b) => b.created - a.created);
188 return matches[0];
189 });
190
191 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
192 if (input.id !== undefined) {
193 const byId = yield* getById(input.id);
194 if (byId !== undefined) return byId;
195 }
196 return yield* findByAlchemyId(input.logicalId);
197 });
198
199 const desiredMetadata = Effect.fn(function* (
200 id: string,
201 metadata: Record<string, string> | undefined,
202 ) {
203 return {
204 ...toMetadata(metadata),
205 ...(yield* createInternalMetadata(id)),
206 };
207 });
208
209 export const CustomerProvider = () =>
210 Provider.succeed(Customer, {
211 stables: ["id", "created", "livemode"],
212
213 diff: Effect.fn(function* ({ news }) {
214 if (!isResolved(news)) return undefined;
215 return undefined;
216 }),
217
218 read: Effect.fn(function* ({ id, output }) {
219 const existing = yield* observe({
220 id: output?.id,
221 logicalId: id,
222 });
223 if (existing === undefined) return undefined;
224 const attrs = toAttrs(existing);
225 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
226 }),
227
228 list: Effect.fn(function* () {
229 const customers = yield* listAllCustomers();
230 return customers
231 .filter((customer) => {
232 const metadata = tagRecord(customer.metadata);
233 return metadata[alchemyMetadataKeys.stack] !== undefined;
234 })
235 .map(toAttrs);
236 }),
237
238 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
239 const metadata = yield* desiredMetadata(id, news.metadata);
240 const desiredEmail = news.email ?? "";
241 const desiredName = news.name ?? "";
242 const desiredDescription = news.description ?? "";
243 const desiredPhone = news.phone ?? "";
244
245 let current = yield* observe({
246 id: output?.id,
247 logicalId: id,
248 });
249
250 if (current === undefined) {
251 current = yield* CreateCustomer({
252 ...(desiredEmail.length > 0 ? { email: desiredEmail } : {}),
253 ...(desiredName.length > 0 ? { name: desiredName } : {}),
254 ...(desiredDescription.length > 0 ? { description: desiredDescription } : {}),
255 ...(desiredPhone.length > 0 ? { phone: desiredPhone } : {}),
256 metadata,
257 }).pipe(
258 withRequestOptions({
259 idempotencyKey: `alchemy-customer-${instanceId}`,
260 }),
261 );
262 }
263
264 const observedMetadata = tagRecord(current.metadata);
265 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
266 const metadataChanged = upsert.length > 0 || removed.length > 0;
267 const emailChanged = (current.email ?? "") !== desiredEmail;
268 const nameChanged = (current.name ?? "") !== desiredName;
269 const descriptionChanged = (current.description ?? "") !== desiredDescription;
270 const phoneChanged = (current.phone ?? "") !== desiredPhone;
271
272 if (
273 !emailChanged &&
274 !nameChanged &&
275 !descriptionChanged &&
276 !phoneChanged &&
277 !metadataChanged
278 ) {
279 return toAttrs(current);
280 }
281
282 const updated = yield* UpdateCustomer({
283 customer: current.id,
284 ...(emailChanged ? { email: desiredEmail } : {}),
285 ...(nameChanged ? { name: desiredName } : {}),
286 ...(descriptionChanged ? { description: desiredDescription } : {}),
287 ...(phoneChanged ? { phone: desiredPhone } : {}),
288 ...(metadataChanged
289 ? {
290 metadata: {
291 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
292 ...Object.fromEntries(removed.map((key) => [key, ""])),
293 },
294 }
295 : {}),
296 });
297 return toAttrs(updated);
298 }),
299
300 delete: Effect.fn(function* ({ output }) {
301 yield* DeleteCustomer({ customer: output.id }).pipe(
302 Effect.catchIf(isMissingCustomer, () => Effect.void),
303 );
304 }),
305 });