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

main
ts 561 lines 18.1 KB
Raw
1 import { withRequestOptions } from "@distilled.cloud/stripe";
2 import {
3 GetShippingRates,
4 GetShippingRate,
5 CreateShippingRate,
6 UpdateShippingRate,
7 type CreateShippingRateRequestFixedAmountCurrencyOptionsMap,
8 type ShippingRate as StripeShippingRate,
9 type ShippingRateFixedAmountCurrencyOptionsMap,
10 type ShippingRateTaxCode,
11 } from "@distilled.cloud/stripe/stripe";
12 import { Unowned } from "alchemy/AdoptPolicy";
13 import { deepEqual, isResolved } from "alchemy/Diff";
14 import { createPhysicalName } from "alchemy/PhysicalName";
15 import * as Provider from "alchemy/Provider";
16 import { Resource } from "alchemy/Resource";
17 import { tagRecord } from "alchemy/Tags";
18 import * as Data from "effect/Data";
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 NAME_MAX_LENGTH = 250;
32 const LIST_PAGE_SIZE = 100;
33 const LIST_MAX_PAGES = 100;
34
35 /** The type of calculation used on the shipping rate. */
36 export type ShippingRateType = "fixed_amount";
37
38 /** Whether the rate is considered inclusive or exclusive of taxes. */
39 export type ShippingRateTaxBehavior = "exclusive" | "inclusive" | "unspecified";
40
41 /** Unit of time for a delivery-estimate bound. */
42 export type ShippingRateDeliveryEstimateUnit = "business_day" | "day" | "hour" | "month" | "week";
43
44 export interface ShippingRateDeliveryEstimateBound {
45 /**
46 * Unit of time for this bound.
47 */
48 unit: ShippingRateDeliveryEstimateUnit;
49 /**
50 * Must be greater than 0.
51 */
52 value: number;
53 }
54
55 export interface ShippingRateDeliveryEstimate {
56 /**
57 * Lower bound of the estimated range. Omit for no lower bound.
58 * Create-only — changing it replaces the shipping rate.
59 */
60 minimum?: ShippingRateDeliveryEstimateBound;
61 /**
62 * Upper bound of the estimated range. Omit for no upper bound.
63 * Create-only — changing it replaces the shipping rate.
64 */
65 maximum?: ShippingRateDeliveryEstimateBound;
66 }
67
68 export interface ShippingRateCurrencyOption {
69 /**
70 * Amount (in the currency's minor units) to charge for this currency.
71 */
72 amount: number;
73 /**
74 * Whether this currency option is inclusive of taxes.
75 */
76 taxBehavior?: ShippingRateTaxBehavior;
77 }
78
79 export interface ShippingRateProps {
80 /**
81 * Customer-facing name shown on Checkout sessions. If omitted, a unique
82 * name is generated from the stack, stage, and logical id. Create-only
83 * — changing it replaces the shipping rate.
84 */
85 displayName?: string;
86 /**
87 * Calculation type. Only `fixed_amount` is supported.
88 * @default "fixed_amount"
89 */
90 type?: ShippingRateType;
91 /**
92 * Amount in the currency's minor units (e.g. cents). Create-only —
93 * changing it replaces the shipping rate.
94 */
95 amount: number;
96 /**
97 * Three-letter ISO currency code, lowercase (e.g. `"usd"`). Create-only
98 * — changing it replaces the shipping rate.
99 */
100 currency: string;
101 /**
102 * Per-currency amounts. Mutable (amounts and tax behavior per currency
103 * can be updated in place).
104 */
105 currencyOptions?: Record<string, ShippingRateCurrencyOption>;
106 /**
107 * Estimated delivery range shown on Checkout sessions. Create-only —
108 * changing it replaces the shipping rate.
109 */
110 deliveryEstimate?: ShippingRateDeliveryEstimate;
111 /**
112 * Whether the rate is considered inclusive of taxes.
113 */
114 taxBehavior?: ShippingRateTaxBehavior;
115 /**
116 * Tax code id (the shipping tax code is `txcd_92010001`). Create-only —
117 * changing it replaces the shipping rate.
118 */
119 taxCode?: string;
120 /**
121 * Whether the shipping rate can be used for new purchases.
122 * @default true
123 */
124 active?: boolean;
125 /**
126 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
127 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
128 * not contain `:`.
129 */
130 metadata?: Record<string, string>;
131 }
132
133 export type ShippingRate = Resource<
134 "Stripe.ShippingRate",
135 ShippingRateProps,
136 {
137 /** Stripe shipping rate id (`shr_…`). */
138 id: string;
139 /** Customer-facing name shown on Checkout sessions. */
140 displayName: string;
141 /** Calculation type (`fixed_amount`). */
142 type: ShippingRateType;
143 /** Amount in the currency's minor units. */
144 amount: number;
145 /** Three-letter ISO currency code. */
146 currency: string;
147 /** Per-currency amounts, if set. */
148 currencyOptions: Record<string, ShippingRateCurrencyOption> | undefined;
149 /** Whether the shipping rate can be used for new purchases. */
150 active: boolean;
151 /** Estimated delivery range, if set. */
152 deliveryEstimate: ShippingRateDeliveryEstimate | undefined;
153 /** Whether the rate is considered inclusive of taxes. */
154 taxBehavior: ShippingRateTaxBehavior | undefined;
155 /** Tax code id, if set. */
156 taxCode: string | undefined;
157 /** User-defined metadata (Alchemy ownership keys stripped). */
158 metadata: Record<string, string>;
159 /** Unix timestamp when the shipping rate was created. */
160 created: number;
161 /** Whether the shipping rate exists in live mode. */
162 livemode: boolean;
163 },
164 never,
165 Providers
166 >;
167
168 /**
169 * A Stripe Shipping Rate — the price of shipping presented to customers
170 * and applied to a purchase. Amount, currency, display name, delivery
171 * estimate, and tax code are immutable (changing them replaces the
172 * rate). `active`, metadata, `taxBehavior`, and per-currency
173 * `currencyOptions` update in place. Shipping rates cannot be deleted;
174 * destroy deactivates them (`active=false`).
175 *
176 * @see https://docs.stripe.com/api/shipping_rates
177 *
178 * ### Creating a Shipping Rate
179 * **Example:** Fixed-amount USD rate
180 * ```typescript
181 * const ground = yield* Stripe.ShippingRate("ground", {
182 * displayName: "Ground",
183 * amount: 500,
184 * currency: "usd",
185 * });
186 * ```
187 *
188 * **Example:** Rate with a delivery estimate
189 * ```typescript
190 * const express = yield* Stripe.ShippingRate("express", {
191 * displayName: "Express",
192 * amount: 1500,
193 * currency: "usd",
194 * deliveryEstimate: {
195 * minimum: { unit: "business_day", value: 1 },
196 * maximum: { unit: "business_day", value: 3 },
197 * },
198 * });
199 * ```
200 *
201 * ### Updating a Shipping Rate
202 * **Example:** Pause the rate and retag
203 * ```typescript
204 * const ground = yield* Stripe.ShippingRate("ground", {
205 * displayName: "Ground",
206 * amount: 500,
207 * currency: "usd",
208 * active: false,
209 * metadata: { region: "us" },
210 * });
211 * ```
212 *
213 * ### Deactivating a Shipping Rate
214 * **Example:** Destroy deactivates rather than deleting
215 * ```typescript
216 * // stack.destroy() / resource removal sets active: false
217 * const ground = yield* Stripe.ShippingRate("ground", {
218 * displayName: "Ground",
219 * amount: 500,
220 * currency: "usd",
221 * });
222 * ```
223 *
224 * @resource
225 * @product Product
226 */
227 export const ShippingRate = Resource<ShippingRate>("Stripe.ShippingRate");
228
229 export class ShippingRateNotResolved extends Data.TaggedError("Stripe.ShippingRateNotResolved")<{
230 displayName: string;
231 currency: string;
232 }> {}
233
234 type ShippingRateAttributes = ShippingRate["Attributes"];
235
236 const userMetadata = (
237 metadata: Record<string, string | undefined> | null | undefined,
238 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
239
240 const taxCodeOf = (taxCode: ShippingRateTaxCode | null | undefined): string | undefined => {
241 if (taxCode == null) return undefined;
242 if (typeof taxCode === "string") return taxCode;
243 return taxCode.id;
244 };
245
246 const fromWireCurrencyOptions = (
247 options: ShippingRateFixedAmountCurrencyOptionsMap | undefined,
248 ): Record<string, ShippingRateCurrencyOption> | undefined => {
249 if (options === undefined) return undefined;
250 const out: Record<string, ShippingRateCurrencyOption> = {};
251 for (const [currency, value] of Object.entries(options)) {
252 if (value === undefined) continue;
253 out[currency] = {
254 amount: value.amount,
255 taxBehavior: value.tax_behavior,
256 };
257 }
258 return Object.keys(out).length > 0 ? out : undefined;
259 };
260
261 const withoutBaseCurrency = <T>(
262 options: Record<string, T> | undefined,
263 currency: string,
264 ): Record<string, T> | undefined => {
265 if (options === undefined) return undefined;
266 const extra = Object.fromEntries(Object.entries(options).filter(([key]) => key !== currency));
267 return Object.keys(extra).length > 0 ? extra : undefined;
268 };
269
270 const toWireCurrencyOptions = (
271 options: Record<string, ShippingRateCurrencyOption> | undefined,
272 ): CreateShippingRateRequestFixedAmountCurrencyOptionsMap | undefined => {
273 if (options === undefined) return undefined;
274 return Object.fromEntries(
275 Object.entries(options).map(([currency, value]) => [
276 currency,
277 {
278 amount: value.amount,
279 ...(value.taxBehavior !== undefined ? { tax_behavior: value.taxBehavior } : {}),
280 },
281 ]),
282 );
283 };
284
285 const fromObservedEstimate = (
286 estimate: StripeShippingRate["delivery_estimate"],
287 ): ShippingRateDeliveryEstimate | undefined => {
288 if (estimate == null) return undefined;
289 const out: ShippingRateDeliveryEstimate = {};
290 if (estimate.minimum != null) {
291 out.minimum = {
292 unit: estimate.minimum.unit,
293 value: estimate.minimum.value,
294 };
295 }
296 if (estimate.maximum != null) {
297 out.maximum = {
298 unit: estimate.maximum.unit,
299 value: estimate.maximum.value,
300 };
301 }
302 return out.minimum !== undefined || out.maximum !== undefined ? out : undefined;
303 };
304
305 const toAttrs = (rate: StripeShippingRate): ShippingRateAttributes => ({
306 id: rate.id,
307 displayName: rate.display_name ?? "",
308 type: rate.type,
309 amount: rate.fixed_amount?.amount ?? 0,
310 currency: rate.fixed_amount?.currency ?? "",
311 currencyOptions: fromWireCurrencyOptions(rate.fixed_amount?.currency_options),
312 active: rate.active,
313 deliveryEstimate: fromObservedEstimate(rate.delivery_estimate),
314 taxBehavior: rate.tax_behavior ?? undefined,
315 taxCode: taxCodeOf(rate.tax_code),
316 metadata: userMetadata(rate.metadata),
317 created: rate.created,
318 livemode: rate.livemode,
319 });
320
321 const toDisplayName = (id: string, displayName: string | undefined, existing?: string) =>
322 Effect.gen(function* () {
323 return (
324 displayName ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }))
325 );
326 });
327
328 const isMissingShippingRate = isMissingStripeResource;
329
330 const getById = (shipping_rate_token: string) =>
331 GetShippingRate({ shipping_rate_token }).pipe(
332 Effect.catchIf(isMissingShippingRate, () => Effect.undefined),
333 );
334
335 const listByActive = Effect.fn(function* (active: boolean) {
336 const rates: StripeShippingRate[] = [];
337 let startingAfter: string | undefined;
338 for (let page = 0; page < LIST_MAX_PAGES; page++) {
339 const response = yield* GetShippingRates({
340 active,
341 limit: LIST_PAGE_SIZE,
342 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
343 });
344 rates.push(...response.data);
345 if (!response.has_more || response.data.length === 0) {
346 break;
347 }
348 startingAfter = response.data[response.data.length - 1]?.id;
349 if (startingAfter === undefined) {
350 break;
351 }
352 }
353 return rates;
354 });
355
356 const listAllShippingRates = Effect.fn(function* () {
357 const [active, inactive] = yield* Effect.all([listByActive(true), listByActive(false)], {
358 concurrency: 2,
359 });
360 const seen = new Set<string>();
361 const rates: StripeShippingRate[] = [];
362 for (const rate of [...active, ...inactive]) {
363 if (seen.has(rate.id)) continue;
364 seen.add(rate.id);
365 rates.push(rate);
366 }
367 return rates;
368 });
369
370 const findByAlchemyId = Effect.fn(function* (id: string) {
371 const rates = yield* listAllShippingRates();
372 const matches: StripeShippingRate[] = [];
373 for (const rate of rates) {
374 if (yield* hasAlchemyMetadata(id, tagRecord(rate.metadata))) {
375 matches.push(rate);
376 }
377 }
378 matches.sort((a, b) => b.created - a.created);
379 return matches[0];
380 });
381
382 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
383 if (input.id !== undefined) {
384 const byId = yield* getById(input.id);
385 if (byId !== undefined) return byId;
386 }
387 return yield* findByAlchemyId(input.logicalId);
388 });
389
390 const desiredMetadata = Effect.fn(function* (
391 id: string,
392 metadata: Record<string, string> | undefined,
393 ) {
394 return {
395 ...toMetadata(metadata),
396 ...(yield* createInternalMetadata(id)),
397 };
398 });
399
400 const shouldReplace = (
401 news: ShippingRateProps,
402 output: ShippingRateAttributes | undefined,
403 ): boolean => {
404 if (output === undefined) return false;
405 if (news.amount !== output.amount) return true;
406 if (news.currency !== output.currency) return true;
407 if ((news.type ?? "fixed_amount") !== output.type) return true;
408 if (news.displayName !== undefined && news.displayName !== output.displayName) {
409 return true;
410 }
411 if (news.taxCode !== undefined && news.taxCode !== (output.taxCode ?? undefined)) {
412 return true;
413 }
414 if (
415 news.deliveryEstimate !== undefined &&
416 !deepEqual(news.deliveryEstimate, output.deliveryEstimate, {
417 stripNullish: true,
418 })
419 ) {
420 return true;
421 }
422 return false;
423 };
424
425 export const ShippingRateProvider = () =>
426 Provider.succeed(ShippingRate, {
427 stables: ["id", "type", "amount", "currency", "created", "livemode"],
428
429 diff: Effect.fn(function* ({ news, output }) {
430 if (!isResolved(news)) return undefined;
431 if (shouldReplace(news, output)) {
432 return { action: "replace" } as const;
433 }
434 return undefined;
435 }),
436
437 read: Effect.fn(function* ({ id, output }) {
438 const existing = yield* observe({
439 id: output?.id,
440 logicalId: id,
441 });
442 if (existing === undefined) return undefined;
443 const attrs = toAttrs(existing);
444 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
445 }),
446
447 list: Effect.fn(function* () {
448 // Default list API can return inactive rates; deactivated rows stay
449 // in Stripe but must not re-enter nuke.
450 const rates = yield* listByActive(true);
451 return rates
452 .filter((rate) => {
453 const metadata = tagRecord(rate.metadata);
454 return metadata[alchemyMetadataKeys.stack] !== undefined;
455 })
456 .map(toAttrs);
457 }),
458
459 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
460 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
461 const metadata = yield* desiredMetadata(id, news.metadata);
462 const desiredActive = news.active ?? true;
463 const desiredType = news.type ?? "fixed_amount";
464 const extraCurrencyOptions = withoutBaseCurrency(news.currencyOptions, news.currency);
465 const currencyOptions = toWireCurrencyOptions(extraCurrencyOptions);
466
467 let current: StripeShippingRate | undefined = yield* observe({
468 id: output?.id,
469 logicalId: id,
470 });
471 // A previous generation (same logical id, different immutable
472 // fields) must not be reused — Stripe shipping rates cannot change
473 // amount, currency, display name, delivery estimate, or tax code.
474 if (current !== undefined && shouldReplace(news, toAttrs(current))) {
475 current = undefined;
476 }
477
478 if (current === undefined) {
479 current = yield* CreateShippingRate({
480 display_name: displayName,
481 type: desiredType,
482 fixed_amount: {
483 amount: news.amount,
484 currency: news.currency,
485 ...(currencyOptions !== undefined ? { currency_options: currencyOptions } : {}),
486 },
487 metadata,
488 ...(news.deliveryEstimate !== undefined
489 ? {
490 delivery_estimate: {
491 ...(news.deliveryEstimate.minimum !== undefined
492 ? { minimum: news.deliveryEstimate.minimum }
493 : {}),
494 ...(news.deliveryEstimate.maximum !== undefined
495 ? { maximum: news.deliveryEstimate.maximum }
496 : {}),
497 },
498 }
499 : {}),
500 ...(news.taxBehavior !== undefined ? { tax_behavior: news.taxBehavior } : {}),
501 ...(news.taxCode !== undefined ? { tax_code: news.taxCode } : {}),
502 }).pipe(
503 withRequestOptions({
504 idempotencyKey: `alchemy-shipping-rate-${instanceId}`,
505 }),
506 );
507 }
508
509 if (current === undefined) {
510 return yield* new ShippingRateNotResolved({
511 displayName,
512 currency: news.currency,
513 });
514 }
515
516 const observedMetadata = tagRecord(current.metadata);
517 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
518 const metadataChanged = upsert.length > 0 || removed.length > 0;
519 const activeChanged = current.active !== desiredActive;
520 const taxBehaviorChanged =
521 news.taxBehavior !== undefined && (current.tax_behavior ?? undefined) !== news.taxBehavior;
522 const observedCurrencyOptions = withoutBaseCurrency(
523 fromWireCurrencyOptions(current.fixed_amount?.currency_options),
524 news.currency,
525 );
526 const currencyOptionsChanged =
527 extraCurrencyOptions !== undefined &&
528 !deepEqual(extraCurrencyOptions, observedCurrencyOptions, {
529 stripNullish: true,
530 });
531
532 if (!activeChanged && !taxBehaviorChanged && !currencyOptionsChanged && !metadataChanged) {
533 return toAttrs(current);
534 }
535
536 const updated = yield* UpdateShippingRate({
537 shipping_rate_token: current.id,
538 ...(activeChanged ? { active: desiredActive } : {}),
539 ...(taxBehaviorChanged ? { tax_behavior: news.taxBehavior } : {}),
540 ...(currencyOptionsChanged ? { fixed_amount: { currency_options: currencyOptions } } : {}),
541 ...(metadataChanged
542 ? {
543 metadata: {
544 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
545 ...Object.fromEntries(removed.map((key) => [key, ""])),
546 },
547 }
548 : {}),
549 });
550 return toAttrs(updated);
551 }),
552
553 delete: Effect.fn(function* ({ output }) {
554 const existing = yield* getById(output.id);
555 if (existing === undefined || !existing.active) return;
556 yield* UpdateShippingRate({
557 shipping_rate_token: existing.id,
558 active: false,
559 }).pipe(Effect.catchIf(isMissingShippingRate, () => Effect.void));
560 }),
561 });