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

main
ts 383 lines 12.8 KB
Raw
1 import { unwrapRedactedDeep } from "@distilled.cloud/core/protocol-rest";
2 import { withRequestOptions } from "@distilled.cloud/stripe";
3 import {
4 DeleteWebhookEndpoint,
5 GetWebhookEndpoints,
6 GetWebhookEndpoint,
7 CreateWebhookEndpoint,
8 UpdateWebhookEndpoint,
9 type WebhookEndpoint as StripeWebhookEndpoint,
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 { arrayEquals } from "alchemy/Util/equal";
17 import * as Effect from "effect/Effect";
18 import * as Redacted from "effect/Redacted";
19 import {
20 alchemyMetadataKeys,
21 createInternalMetadata,
22 diffMetadata,
23 hasAlchemyMetadata,
24 stripInternalMetadata,
25 toMetadata,
26 } from "./Metadata.ts";
27 import { isMissingStripeResource } from "./missing.ts";
28 import type { Providers } from "./Providers.ts";
29
30 const LIST_PAGE_SIZE = 100;
31 const LIST_MAX_PAGES = 100;
32
33 export type WebhookEndpointStatus = "enabled" | "disabled";
34
35 /**
36 * A Stripe event type string (`"customer.created"`) or an event class
37 * (`Stripe.CustomerCreated`) whose static `type` is used.
38 */
39 export type WebhookEnabledEvent = string | { readonly type: string };
40
41 const enabledEventTypes = (events: readonly WebhookEnabledEvent[]): string[] =>
42 events.map((event) => (typeof event === "string" ? event : event.type));
43
44 export interface WebhookEndpointProps {
45 /**
46 * HTTPS URL Stripe POSTs event payloads to.
47 */
48 url: string;
49 /**
50 * Event types this endpoint receives. Pass Stripe event classes
51 * (`Stripe.CustomerCreated`) or type strings (`"customer.created"`).
52 * `["*"]` enables every event except those that require explicit
53 * selection.
54 */
55 enabledEvents: WebhookEnabledEvent[];
56 /**
57 * Optional description of what the webhook is used for.
58 */
59 description?: string;
60 /**
61 * Stripe API version event payloads are rendered as. Create-only —
62 * changing it replaces the endpoint. Defaults to the account version.
63 */
64 apiVersion?: string;
65 /**
66 * When true, receive events from connected accounts instead of this
67 * account. Create-only — changing it replaces the endpoint.
68 * @default false
69 */
70 connect?: boolean;
71 /**
72 * When true, the endpoint is disabled and does not receive events.
73 * @default false
74 */
75 disabled?: boolean;
76 /**
77 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
78 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
79 * not contain `:`.
80 */
81 metadata?: Record<string, string>;
82 }
83
84 export type WebhookEndpoint = Resource<
85 "Stripe.WebhookEndpoint",
86 WebhookEndpointProps,
87 {
88 /** Stripe webhook endpoint id (`we_…`). */
89 id: string;
90 /** HTTPS URL Stripe POSTs event payloads to. */
91 url: string;
92 /** Event types this endpoint receives. */
93 enabledEvents: string[];
94 /** Optional description of what the webhook is used for. */
95 description: string | undefined;
96 /** Stripe API version event payloads are rendered as, if set. */
97 apiVersion: string | undefined;
98 /** Associated Connect application id, if this is a Connect endpoint. */
99 application: string | undefined;
100 /** Whether this endpoint receives events from connected accounts. */
101 connect: boolean;
102 /** Whether the endpoint is currently receiving events. */
103 status: WebhookEndpointStatus;
104 /**
105 * Signing secret, returned only at creation and preserved in state.
106 * Never log this value.
107 */
108 secret: Redacted.Redacted<string> | undefined;
109 /** User-defined metadata (Alchemy ownership keys stripped). */
110 metadata: Record<string, string>;
111 /** Unix timestamp when the endpoint was created. */
112 created: number;
113 /** Whether the endpoint exists in live mode. */
114 livemode: boolean;
115 },
116 never,
117 Providers
118 >;
119
120 /**
121 * A Stripe webhook endpoint — the HTTPS destination Stripe POSTs
122 * event payloads to. URL, enabled events, description, disabled, and
123 * metadata update in place. The signing `secret` is returned only on
124 * create and is stored as `Redacted`. Deleting the resource deletes
125 * the endpoint.
126 *
127 * @see https://docs.stripe.com/api/webhook_endpoints
128 *
129 * ### Creating an endpoint
130 * **Example:** Charge events
131 * ```typescript
132 * const webhook = yield* Stripe.WebhookEndpoint("Charges", {
133 * url: "https://example.com/alchemy-stripe-webhook",
134 * enabledEvents: ["charge.succeeded", "charge.failed"],
135 * });
136 * ```
137 *
138 * **Example:** Event classes, for a Worker URL you already have
139 * ```typescript
140 * const webhook = yield* Stripe.WebhookEndpoint("Events", {
141 * url: Output.interpolate`${api.url}/webhooks/stripe`,
142 * enabledEvents: [Stripe.CustomerCreated, Stripe.InvoicePaid],
143 * });
144 * yield* Stripe.bindWebhookSecret(api, webhook.secret);
145 * ```
146 *
147 * On a Worker, prefer `consumeEvents` — it provisions this endpoint and
148 * binds the secret for you.
149 *
150 * **Example:** Description, metadata, and all events
151 * ```typescript
152 * const webhook = yield* Stripe.WebhookEndpoint("AllEvents", {
153 * url: "https://example.com/alchemy-stripe-webhook",
154 * enabledEvents: ["*"],
155 * description: "Alchemy test webhook",
156 * metadata: { purpose: "billing" },
157 * });
158 * ```
159 *
160 * ### Disabling an endpoint
161 * **Example:** Disable without deleting
162 * ```typescript
163 * const webhook = yield* Stripe.WebhookEndpoint("Charges", {
164 * url: "https://example.com/alchemy-stripe-webhook",
165 * enabledEvents: ["charge.succeeded"],
166 * disabled: true,
167 * });
168 * ```
169 *
170 * @resource
171 * @product Webhook
172 */
173 export const WebhookEndpoint = Resource<WebhookEndpoint>("Stripe.WebhookEndpoint");
174
175 const userMetadata = (
176 metadata: Record<string, string | undefined> | null | undefined,
177 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
178
179 const redactSecret = (
180 secret: string | Redacted.Redacted<string> | undefined,
181 ): Redacted.Redacted<string> | undefined => {
182 if (secret === undefined) return undefined;
183 if (typeof secret === "string") return Redacted.make(secret);
184 // Distilled and alchemy can resolve different `effect` copies, so a
185 // SDK-wrapped Redacted is not readable via alchemy's WeakMap. Unwrap
186 // with distilled first, then wrap with ours so state encoding works.
187 try {
188 return secret.pipe(Redacted.value, Redacted.make);
189 } catch {
190 const unwrapped = unwrapRedactedDeep(secret);
191 return typeof unwrapped === "string" ? Redacted.make(unwrapped) : undefined;
192 }
193 };
194
195 const toAttrs = (endpoint: StripeWebhookEndpoint, previousSecret?: Redacted.Redacted<string>) => ({
196 id: endpoint.id,
197 url: endpoint.url,
198 enabledEvents: endpoint.enabled_events,
199 description: endpoint.description ?? undefined,
200 apiVersion: endpoint.api_version ?? undefined,
201 application: endpoint.application ?? undefined,
202 connect: endpoint.application != null,
203 status: (endpoint.status === "disabled" ? "disabled" : "enabled") as WebhookEndpointStatus,
204 secret: redactSecret(endpoint.secret) ?? previousSecret,
205 metadata: userMetadata(endpoint.metadata),
206 created: endpoint.created,
207 livemode: endpoint.livemode,
208 });
209
210 const isMissingWebhookEndpoint = isMissingStripeResource;
211
212 const getById = (webhookEndpoint: string) =>
213 GetWebhookEndpoint({
214 webhook_endpoint: webhookEndpoint,
215 }).pipe(Effect.catchIf(isMissingWebhookEndpoint, () => Effect.undefined));
216
217 const listAllWebhookEndpoints = Effect.fn(function* () {
218 const endpoints: StripeWebhookEndpoint[] = [];
219 let startingAfter: string | undefined;
220 for (let page = 0; page < LIST_MAX_PAGES; page++) {
221 const response = yield* GetWebhookEndpoints({
222 limit: LIST_PAGE_SIZE,
223 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
224 });
225 endpoints.push(...response.data);
226 if (!response.has_more || response.data.length === 0) {
227 break;
228 }
229 startingAfter = response.data[response.data.length - 1]?.id;
230 if (startingAfter === undefined) {
231 break;
232 }
233 }
234 return endpoints;
235 });
236
237 const findByAlchemyId = Effect.fn(function* (id: string) {
238 const endpoints = yield* listAllWebhookEndpoints();
239 const matches: StripeWebhookEndpoint[] = [];
240 for (const endpoint of endpoints) {
241 if (yield* hasAlchemyMetadata(id, tagRecord(endpoint.metadata))) {
242 matches.push(endpoint);
243 }
244 }
245 matches.sort((a, b) => b.created - a.created);
246 return matches[0];
247 });
248
249 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
250 if (input.id !== undefined) {
251 const byId = yield* getById(input.id);
252 if (byId !== undefined) return byId;
253 }
254 return yield* findByAlchemyId(input.logicalId);
255 });
256
257 const desiredMetadata = Effect.fn(function* (
258 id: string,
259 metadata: Record<string, string> | undefined,
260 ) {
261 return {
262 ...toMetadata(metadata),
263 ...(yield* createInternalMetadata(id)),
264 };
265 });
266
267 const shouldReplace = (
268 news: WebhookEndpointProps,
269 output: WebhookEndpoint["Attributes"] | undefined,
270 ) => {
271 if (output === undefined) return false;
272 if (news.apiVersion !== undefined && news.apiVersion !== output.apiVersion) {
273 return true;
274 }
275 if (news.connect !== undefined && news.connect !== output.connect) {
276 return true;
277 }
278 return false;
279 };
280
281 export const WebhookEndpointProvider = () =>
282 Provider.succeed(WebhookEndpoint, {
283 stables: ["id", "secret", "apiVersion", "connect", "application", "created", "livemode"],
284
285 diff: Effect.fn(function* ({ news, output }) {
286 if (!isResolved(news)) return undefined;
287 if (shouldReplace(news, output)) {
288 return { action: "replace" } as const;
289 }
290 return undefined;
291 }),
292
293 read: Effect.fn(function* ({ id, output }) {
294 const existing = yield* observe({
295 id: output?.id,
296 logicalId: id,
297 });
298 if (existing === undefined) return undefined;
299 const attrs = toAttrs(existing, output?.secret);
300 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
301 }),
302
303 list: Effect.fn(function* () {
304 const endpoints = yield* listAllWebhookEndpoints();
305 return endpoints
306 .filter((endpoint) => {
307 const metadata = tagRecord(endpoint.metadata);
308 return metadata[alchemyMetadataKeys.stack] !== undefined;
309 })
310 .map((endpoint) => toAttrs(endpoint));
311 }),
312
313 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
314 const metadata = yield* desiredMetadata(id, news.metadata);
315 const desiredDescription = news.description ?? "";
316 const desiredDisabled = news.disabled ?? false;
317 const desiredUrl = news.url;
318 const desiredEvents = enabledEventTypes(news.enabledEvents);
319 const previousSecret = output?.secret;
320
321 let current = yield* observe({
322 id: output?.id,
323 logicalId: id,
324 });
325
326 if (current === undefined) {
327 current = yield* CreateWebhookEndpoint({
328 url: desiredUrl,
329 enabled_events: desiredEvents,
330 ...(desiredDescription.length > 0 ? { description: desiredDescription } : {}),
331 ...(news.apiVersion !== undefined ? { api_version: news.apiVersion } : {}),
332 ...(news.connect !== undefined ? { connect: news.connect } : {}),
333 metadata,
334 }).pipe(
335 withRequestOptions({
336 idempotencyKey: `alchemy-webhook-endpoint-${instanceId}`,
337 }),
338 );
339 }
340
341 const observedMetadata = tagRecord(current.metadata);
342 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
343 const metadataChanged = upsert.length > 0 || removed.length > 0;
344 const urlChanged = current.url !== desiredUrl;
345 const eventsChanged = !arrayEquals(current.enabled_events, desiredEvents);
346 const descriptionChanged = (current.description ?? "") !== desiredDescription;
347 const observedDisabled = current.status === "disabled";
348 const disabledChanged = observedDisabled !== desiredDisabled;
349
350 if (
351 !urlChanged &&
352 !eventsChanged &&
353 !descriptionChanged &&
354 !disabledChanged &&
355 !metadataChanged
356 ) {
357 return toAttrs(current, previousSecret);
358 }
359
360 const updated = yield* UpdateWebhookEndpoint({
361 webhook_endpoint: current.id,
362 ...(urlChanged ? { url: desiredUrl } : {}),
363 ...(eventsChanged ? { enabled_events: desiredEvents } : {}),
364 ...(descriptionChanged ? { description: desiredDescription } : {}),
365 ...(disabledChanged ? { disabled: desiredDisabled } : {}),
366 ...(metadataChanged
367 ? {
368 metadata: {
369 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
370 ...Object.fromEntries(removed.map((key) => [key, ""])),
371 },
372 }
373 : {}),
374 });
375 return toAttrs(updated, previousSecret);
376 }),
377
378 delete: Effect.fn(function* ({ output }) {
379 yield* DeleteWebhookEndpoint({
380 webhook_endpoint: output.id,
381 }).pipe(Effect.catchIf(isMissingWebhookEndpoint, () => Effect.void));
382 }),
383 });