@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, 06:00 UTC

main
ts 583 lines 18.5 KB
Raw
1 import { withRequestOptions, type StripeOpError } from "@distilled.cloud/stripe";
2 import {
3 GetBillingCreditGrants,
4 GetBillingCreditGrant,
5 CreateBillingCreditGrant,
6 UpdateBillingCreditGrant,
7 CreateBillingCreditGrantVoid,
8 type BillingCreditGrant as StripeCreditGrant,
9 type CreateBillingCreditGrantRequestAmount,
10 type CreateBillingCreditGrantRequestApplicabilityConfig,
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 this amount. Stripe currently only supports monetary credits. */
36 export type CreditGrantAmountType = "monetary";
37
38 /** The category of this credit grant. Tracking only — not shown to customers. */
39 export type CreditGrantCategory = "paid" | "promotional";
40
41 /**
42 * The price type that credit grants can apply to. Stripe currently only
43 * supports metered prices (prices with a Billing Meter).
44 */
45 export type CreditGrantPriceType = "metered";
46
47 export interface CreditGrantMonetaryAmount {
48 /**
49 * Three-letter ISO currency code, lowercase (e.g. `"usd"`).
50 */
51 currency: string;
52 /**
53 * Positive integer amount in the currency's minor units.
54 */
55 value: number;
56 }
57
58 export interface CreditGrantAmount {
59 /**
60 * Amount type. Stripe currently only supports `"monetary"`.
61 */
62 type: CreditGrantAmountType;
63 /**
64 * Monetary amount. Required when `type` is `"monetary"`. Create-only —
65 * changing it replaces the grant.
66 */
67 monetary?: CreditGrantMonetaryAmount;
68 }
69
70 export interface CreditGrantApplicablePrice {
71 /**
72 * Stripe Price id (`price_…`) this grant can apply to. Metered prices
73 * only. Cannot be combined with `priceType`.
74 */
75 id: string;
76 }
77
78 export interface CreditGrantScope {
79 /**
80 * Price type this grant applies to. Cannot be combined with `prices`.
81 * @default "metered"
82 */
83 priceType?: CreditGrantPriceType;
84 /**
85 * Specific metered prices this grant applies to (max 20). Cannot be
86 * combined with `priceType`.
87 */
88 prices?: CreditGrantApplicablePrice[];
89 }
90
91 export interface CreditGrantApplicabilityConfig {
92 /**
93 * Scope of prices this credit grant can apply to.
94 */
95 scope: CreditGrantScope;
96 }
97
98 export interface CreditGrantProps {
99 /**
100 * Id of the customer receiving the billing credits (`cus_…`). Required
101 * unless `customerAccount` is set. Create-only — changing it replaces
102 * the grant.
103 */
104 customer?: string;
105 /**
106 * Id of the account representing the customer receiving the billing
107 * credits. Required unless `customer` is set. Create-only.
108 */
109 customerAccount?: string;
110 /**
111 * Amount of this credit grant. Create-only — changing it replaces the
112 * grant.
113 */
114 amount: CreditGrantAmount;
115 /**
116 * What this credit grant applies to. Stripe currently only supports
117 * metered prices that have a Billing Meter. Create-only.
118 * @default { scope: { priceType: "metered" } }
119 */
120 applicabilityConfig?: CreditGrantApplicabilityConfig;
121 /**
122 * Category of this credit grant. Tracking only — not shown to the
123 * customer. Create-only.
124 * @default "paid"
125 */
126 category?: CreditGrantCategory;
127 /**
128 * Descriptive name shown in the Stripe Dashboard. If omitted, a unique
129 * name is generated from the stack, stage, and logical id. Create-only
130 * (the update API does not accept `name`).
131 */
132 name?: string;
133 /**
134 * Unix timestamp when the credits become eligible for use. Defaults to
135 * the current time. Create-only.
136 */
137 effectiveAt?: number;
138 /**
139 * Unix timestamp when the credits expire. If omitted, they never expire.
140 * Mutable — pass a new timestamp to update.
141 */
142 expiresAt?: number;
143 /**
144 * Priority for applying this grant (0 highest, 100 lowest).
145 * @default 50
146 */
147 priority?: number;
148 /**
149 * User-defined metadata. Alchemy ownership keys (`alchemy_stack` /
150 * `alchemy_stage` / `alchemy_id`) are merged in automatically. Keys may
151 * not contain `:`. Mutable.
152 */
153 metadata?: Record<string, string>;
154 }
155
156 export type CreditGrant = Resource<
157 "Stripe.CreditGrant",
158 CreditGrantProps,
159 {
160 /** Stripe credit grant id (`credgr_…`). */
161 id: string;
162 /** Dashboard name, if set. */
163 name: string | undefined;
164 /** Customer id receiving the credits (`cus_…`). */
165 customer: string | undefined;
166 /** Customer-account id receiving the credits, if set. */
167 customerAccount: string | undefined;
168 /** Amount of this credit grant. */
169 amount: CreditGrantAmount;
170 /** What this credit grant applies to. */
171 applicabilityConfig: CreditGrantApplicabilityConfig;
172 /** Category of this credit grant. */
173 category: CreditGrantCategory;
174 /** Unix timestamp when the credits become eligible for use. */
175 effectiveAt: number | undefined;
176 /** Unix timestamp when the credits expire, if they expire. */
177 expiresAt: number | undefined;
178 /** Priority for applying this grant (0 highest, 100 lowest). */
179 priority: number | undefined;
180 /** Unix timestamp when this grant was voided, if voided. */
181 voidedAt: number | undefined;
182 /** Unix timestamp when the grant was created. */
183 created: number;
184 /** Unix timestamp when the grant was last updated. */
185 updated: number;
186 /** Whether the grant exists in live mode. */
187 livemode: boolean;
188 /** User-defined metadata (Alchemy ownership keys stripped). */
189 metadata: Record<string, string>;
190 },
191 never,
192 Providers
193 >;
194
195 /**
196 * A Stripe Credit Grant — prepaid or promotional billing credits allocated
197 * to a customer and applied against metered prices. Amount, customer,
198 * applicability, category, effective time, and priority are immutable;
199 * changing them replaces the grant. `expiresAt` and `metadata` update in
200 * place. Credit grants cannot be hard-deleted: destroying this resource
201 * voids the grant (`voided_at` is set). Already-voided grants are treated
202 * as success.
203 *
204 * @see https://docs.stripe.com/api/billing/credit-grant
205 *
206 * ### Creating a Credit Grant
207 * **Example:** Promotional credits for metered prices
208 * ```typescript
209 * const customer = yield* Stripe.Customer("alice", {
210 * email: "alice@example.com",
211 * });
212 * const grant = yield* Stripe.CreditGrant("welcome-credits", {
213 * customer: customer.id,
214 * amount: { type: "monetary", monetary: { currency: "usd", value: 1000 } },
215 * applicabilityConfig: { scope: { priceType: "metered" } },
216 * category: "promotional",
217 * name: "Welcome credits",
218 * });
219 * ```
220 *
221 * **Example:** Paid credits scoped to specific prices
222 * ```typescript
223 * const grant = yield* Stripe.CreditGrant("prepaid", {
224 * customer: customer.id,
225 * amount: { type: "monetary", monetary: { currency: "usd", value: 5000 } },
226 * applicabilityConfig: {
227 * scope: { prices: [{ id: price.id }] },
228 * },
229 * category: "paid",
230 * });
231 * ```
232 *
233 * ### Updating a Credit Grant
234 * **Example:** Extend expiry and retag
235 * ```typescript
236 * const grant = yield* Stripe.CreditGrant("welcome-credits", {
237 * customer: customer.id,
238 * amount: { type: "monetary", monetary: { currency: "usd", value: 1000 } },
239 * expiresAt: 4102444800,
240 * metadata: { campaign: "spring" },
241 * });
242 * ```
243 *
244 * ### Voiding a Credit Grant
245 * **Example:** Destroy voids rather than deleting
246 * ```typescript
247 * // stack.destroy() / resource removal calls void
248 * const grant = yield* Stripe.CreditGrant("welcome-credits", {
249 * customer: customer.id,
250 * amount: { type: "monetary", monetary: { currency: "usd", value: 1000 } },
251 * });
252 * ```
253 *
254 * @resource
255 * @product Billing
256 */
257 export const CreditGrant = Resource<CreditGrant>("Stripe.CreditGrant");
258
259 export class CreditGrantNotResolved extends Data.TaggedError("Stripe.CreditGrantNotResolved")<{
260 customer: string | undefined;
261 }> {}
262
263 type CreditGrantAttributes = CreditGrant["Attributes"];
264
265 const DEFAULT_APPLICABILITY: CreditGrantApplicabilityConfig = {
266 scope: { priceType: "metered" },
267 };
268
269 const userMetadata = (
270 metadata: Record<string, string | undefined> | null | undefined,
271 ): Record<string, string> => stripInternalMetadata(tagRecord(metadata));
272
273 const idOf = (value: unknown): string | undefined => {
274 if (typeof value === "string") return value;
275 if (value !== null && typeof value === "object" && "id" in value) {
276 const id = (value as { id?: unknown }).id;
277 if (typeof id === "string") return id;
278 }
279 return undefined;
280 };
281
282 const isVoided = (grant: StripeCreditGrant): boolean => grant.voided_at != null;
283
284 const fromWireAmount = (amount: StripeCreditGrant["amount"]): CreditGrantAmount => ({
285 type: amount.type,
286 ...(amount.monetary != null
287 ? {
288 monetary: {
289 currency: amount.monetary.currency,
290 value: amount.monetary.value,
291 },
292 }
293 : {}),
294 });
295
296 const toWireAmount = (amount: CreditGrantAmount): CreateBillingCreditGrantRequestAmount => ({
297 type: amount.type,
298 ...(amount.monetary !== undefined
299 ? {
300 monetary: {
301 currency: amount.monetary.currency,
302 value: amount.monetary.value,
303 },
304 }
305 : {}),
306 });
307
308 const fromWireApplicability = (
309 config: StripeCreditGrant["applicability_config"],
310 ): CreditGrantApplicabilityConfig => {
311 const prices = config.scope.prices
312 ?.map((price) => (price.id != null ? { id: price.id } : undefined))
313 .filter((price): price is CreditGrantApplicablePrice => price !== undefined);
314 return {
315 scope: {
316 ...(config.scope.price_type !== undefined ? { priceType: config.scope.price_type } : {}),
317 ...(prices !== undefined && prices.length > 0 ? { prices } : {}),
318 },
319 };
320 };
321
322 const toWireApplicability = (
323 config: CreditGrantApplicabilityConfig,
324 ): CreateBillingCreditGrantRequestApplicabilityConfig => ({
325 scope: {
326 ...(config.scope.priceType !== undefined ? { price_type: config.scope.priceType } : {}),
327 ...(config.scope.prices !== undefined
328 ? { prices: config.scope.prices.map((price) => ({ id: price.id })) }
329 : {}),
330 },
331 });
332
333 const toAttrs = (grant: StripeCreditGrant): CreditGrantAttributes => ({
334 id: grant.id,
335 name: grant.name ?? undefined,
336 customer: idOf(grant.customer),
337 customerAccount: grant.customer_account ?? undefined,
338 amount: fromWireAmount(grant.amount),
339 applicabilityConfig: fromWireApplicability(grant.applicability_config),
340 category: grant.category,
341 effectiveAt: grant.effective_at ?? undefined,
342 expiresAt: grant.expires_at ?? undefined,
343 priority: grant.priority ?? undefined,
344 voidedAt: grant.voided_at ?? undefined,
345 created: grant.created,
346 updated: grant.updated,
347 livemode: grant.livemode,
348 metadata: userMetadata(grant.metadata),
349 });
350
351 const toName = (id: string, name: string | undefined, existing?: string) =>
352 Effect.gen(function* () {
353 return name ?? existing ?? (yield* createPhysicalName({ id, maxLength: NAME_MAX_LENGTH }));
354 });
355
356 const isMissingGrant = isMissingStripeResource;
357
358 const alreadyVoided = (error: StripeOpError): boolean =>
359 error._tag === "InvalidRequestError" && (error.message?.toLowerCase().includes("void") ?? false);
360
361 const getById = (id: string) =>
362 GetBillingCreditGrant({ id }).pipe(Effect.catchIf(isMissingGrant, () => Effect.undefined));
363
364 const listAllCreditGrants = Effect.fn(function* () {
365 const grants: StripeCreditGrant[] = [];
366 let startingAfter: string | undefined;
367 for (let page = 0; page < LIST_MAX_PAGES; page++) {
368 const response = yield* GetBillingCreditGrants({
369 limit: LIST_PAGE_SIZE,
370 ...(startingAfter !== undefined ? { starting_after: startingAfter } : {}),
371 });
372 grants.push(...response.data);
373 if (!response.has_more || response.data.length === 0) {
374 break;
375 }
376 startingAfter = response.data[response.data.length - 1]?.id;
377 if (startingAfter === undefined) {
378 break;
379 }
380 }
381 return grants;
382 });
383
384 const findByAlchemyId = Effect.fn(function* (id: string) {
385 const grants = yield* listAllCreditGrants();
386 const matches: StripeCreditGrant[] = [];
387 for (const grant of grants) {
388 if (isVoided(grant)) continue;
389 if (yield* hasAlchemyMetadata(id, tagRecord(grant.metadata))) {
390 matches.push(grant);
391 }
392 }
393 matches.sort((a, b) => b.created - a.created);
394 return matches[0];
395 });
396
397 const observe = Effect.fn(function* (input: { id?: string; logicalId: string }) {
398 if (input.id !== undefined) {
399 const byId = yield* getById(input.id);
400 if (byId !== undefined && !isVoided(byId)) return byId;
401 }
402 return yield* findByAlchemyId(input.logicalId);
403 });
404
405 const desiredMetadata = Effect.fn(function* (
406 id: string,
407 metadata: Record<string, string> | undefined,
408 ) {
409 return {
410 ...toMetadata(metadata),
411 ...(yield* createInternalMetadata(id)),
412 };
413 });
414
415 const replaceOnCreateOnlyChange = (
416 olds: CreditGrantProps | undefined,
417 news: CreditGrantProps,
418 output: CreditGrantAttributes | undefined,
419 ): boolean => {
420 if (output === undefined && olds === undefined) return false;
421 if (
422 !deepEqual(news.amount, output?.amount ?? olds?.amount, {
423 stripNullish: true,
424 })
425 ) {
426 return true;
427 }
428 const desiredApplicability = news.applicabilityConfig ?? DEFAULT_APPLICABILITY;
429 const previousApplicability = output?.applicabilityConfig ?? olds?.applicabilityConfig;
430 if (
431 previousApplicability !== undefined &&
432 !deepEqual(desiredApplicability, previousApplicability, {
433 stripNullish: true,
434 })
435 ) {
436 return true;
437 }
438 const previousCategory = output?.category ?? olds?.category ?? "paid";
439 if ((news.category ?? previousCategory) !== previousCategory) {
440 return true;
441 }
442 const previousCustomer = output?.customer ?? olds?.customer;
443 if (
444 news.customer !== undefined &&
445 previousCustomer !== undefined &&
446 news.customer !== previousCustomer
447 ) {
448 return true;
449 }
450 const previousAccount = output?.customerAccount ?? olds?.customerAccount;
451 if (
452 news.customerAccount !== undefined &&
453 previousAccount !== undefined &&
454 news.customerAccount !== previousAccount
455 ) {
456 return true;
457 }
458 if (
459 news.effectiveAt !== undefined &&
460 news.effectiveAt !== (output?.effectiveAt ?? olds?.effectiveAt)
461 ) {
462 return true;
463 }
464 if (news.priority !== undefined && news.priority !== (output?.priority ?? olds?.priority)) {
465 return true;
466 }
467 return false;
468 };
469
470 export const CreditGrantProvider = () =>
471 Provider.succeed(CreditGrant, {
472 stables: [
473 "id",
474 "customer",
475 "customerAccount",
476 "amount",
477 "applicabilityConfig",
478 "category",
479 "effectiveAt",
480 "priority",
481 "created",
482 "livemode",
483 ],
484
485 diff: Effect.fn(function* ({ olds, news, output }) {
486 if (!isResolved(news)) return undefined;
487 if (replaceOnCreateOnlyChange(olds, news, output)) {
488 return { action: "replace" as const };
489 }
490 return undefined;
491 }),
492
493 read: Effect.fn(function* ({ id, output }) {
494 const existing = yield* observe({
495 id: output?.id,
496 logicalId: id,
497 });
498 if (existing === undefined) return undefined;
499 const attrs = toAttrs(existing);
500 return (yield* hasAlchemyMetadata(id, tagRecord(existing.metadata))) ? attrs : Unowned(attrs);
501 }),
502
503 list: Effect.fn(function* () {
504 const grants = yield* listAllCreditGrants();
505 return grants
506 .filter((grant) => {
507 if (isVoided(grant)) return false;
508 const metadata = tagRecord(grant.metadata);
509 return metadata[alchemyMetadataKeys.stack] !== undefined;
510 })
511 .map(toAttrs);
512 }),
513
514 reconcile: Effect.fn(function* ({ id, news, output, instanceId }) {
515 const metadata = yield* desiredMetadata(id, news.metadata);
516 const name = yield* toName(id, news.name, output?.name);
517 const applicabilityConfig = news.applicabilityConfig ?? DEFAULT_APPLICABILITY;
518
519 let current: StripeCreditGrant | undefined = yield* observe({
520 id: output?.id,
521 logicalId: id,
522 });
523 if (current !== undefined && replaceOnCreateOnlyChange(undefined, news, toAttrs(current))) {
524 current = undefined;
525 }
526
527 if (current === undefined) {
528 current = yield* CreateBillingCreditGrant({
529 amount: toWireAmount(news.amount),
530 applicability_config: toWireApplicability(applicabilityConfig),
531 name,
532 metadata,
533 ...(news.customer !== undefined ? { customer: news.customer } : {}),
534 ...(news.customerAccount !== undefined ? { customer_account: news.customerAccount } : {}),
535 ...(news.category !== undefined ? { category: news.category } : {}),
536 ...(news.effectiveAt !== undefined ? { effective_at: news.effectiveAt } : {}),
537 ...(news.expiresAt !== undefined ? { expires_at: news.expiresAt } : {}),
538 ...(news.priority !== undefined ? { priority: news.priority } : {}),
539 }).pipe(
540 withRequestOptions({
541 idempotencyKey: `alchemy-credit-grant-${instanceId}`,
542 }),
543 );
544 }
545
546 if (current === undefined) {
547 return yield* new CreditGrantNotResolved({ customer: news.customer });
548 }
549
550 const observedMetadata = tagRecord(current.metadata);
551 const { upsert, removed } = diffMetadata(observedMetadata, metadata);
552 const metadataChanged = upsert.length > 0 || removed.length > 0;
553 const expiresAtChanged =
554 news.expiresAt !== undefined && (current.expires_at ?? undefined) !== news.expiresAt;
555
556 if (!metadataChanged && !expiresAtChanged) {
557 return toAttrs(current);
558 }
559
560 const updated = yield* UpdateBillingCreditGrant({
561 id: current.id,
562 ...(expiresAtChanged ? { expires_at: news.expiresAt } : {}),
563 ...(metadataChanged
564 ? {
565 metadata: {
566 ...Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value])),
567 ...Object.fromEntries(removed.map((key) => [key, ""])),
568 },
569 }
570 : {}),
571 });
572 return toAttrs(updated);
573 }),
574
575 delete: Effect.fn(function* ({ output }) {
576 const existing = yield* getById(output.id);
577 if (existing === undefined || isVoided(existing)) return;
578 yield* CreateBillingCreditGrantVoid({ id: existing.id }).pipe(
579 Effect.catchIf(isMissingGrant, () => Effect.void),
580 Effect.catchIf(alreadyVoided, () => Effect.void),
581 );
582 }),
583 });