@fantastic.dev/better-stripe 0.79.1 → 0.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalPriceReplacement.d.ts +131 -0
  4. package/dist/client/billing/renewalPriceReplacement.d.ts.map +1 -0
  5. package/dist/client/billing/renewalPriceReplacement.js +90 -0
  6. package/dist/client/billing/renewalPriceReplacement.js.map +1 -0
  7. package/dist/client/billing/renewalReplacementSchema.d.ts +124 -0
  8. package/dist/client/billing/renewalReplacementSchema.d.ts.map +1 -0
  9. package/dist/client/billing/renewalReplacementSchema.js +121 -0
  10. package/dist/client/billing/renewalReplacementSchema.js.map +1 -0
  11. package/dist/client/billing/renewalReplacementSnapshot.d.ts +3 -0
  12. package/dist/client/billing/renewalReplacementSnapshot.d.ts.map +1 -0
  13. package/dist/client/billing/renewalReplacementSnapshot.js +69 -0
  14. package/dist/client/billing/renewalReplacementSnapshot.js.map +1 -0
  15. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  16. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  17. package/dist/client/index.d.ts +3 -0
  18. package/dist/client/index.d.ts.map +1 -1
  19. package/dist/client/index.js +1 -0
  20. package/dist/client/index.js.map +1 -1
  21. package/dist/client/usage/observationClient.d.ts +2 -2
  22. package/dist/client/usage/observationClient.d.ts.map +1 -1
  23. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  24. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  25. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  26. package/dist/component/earnings/triggers.d.ts +16 -16
  27. package/docs/client-api.md +5 -0
  28. package/docs/renewal-price-replacements.md +186 -0
  29. package/package.json +1 -1
  30. package/src/client/billing/renewal-price-replacement.test.ts +457 -0
  31. package/src/client/billing/renewalPriceReplacement.ts +127 -0
  32. package/src/client/billing/renewalReplacementSchema.ts +129 -0
  33. package/src/client/billing/renewalReplacementSnapshot.ts +85 -0
  34. package/src/client/index.ts +6 -0
@@ -0,0 +1,457 @@
1
+ import { expect, it } from "vitest";
2
+ import * as sdk from "../index.js";
3
+
4
+ const expected = {
5
+ customerAccountId: "acct_buyer",
6
+ subscriptionId: "sub_original",
7
+ itemId: "si_original",
8
+ currentPriceId: "price_original",
9
+ currentProductId: "prod_original",
10
+ targetPriceId: "price_target",
11
+ targetProductId: "prod_other",
12
+ periodStart: 1700000000,
13
+ periodEnd: 1702592000,
14
+ livemode: false,
15
+ };
16
+ function price(id = "price_original", product = "prod_original") {
17
+ return {
18
+ id,
19
+ product,
20
+ object: "price",
21
+ active: true,
22
+ livemode: false,
23
+ type: "recurring",
24
+ currency: "usd",
25
+ billing_scheme: "per_unit",
26
+ recurring: { interval: "month", interval_count: 1, usage_type: "licensed" },
27
+ };
28
+ }
29
+ function input() {
30
+ return {
31
+ expected,
32
+ key: "renewal:original-operation",
33
+ subscription: {
34
+ id: "sub_original",
35
+ object: "subscription",
36
+ customer_account: "acct_buyer",
37
+ status: "active",
38
+ currency: "usd",
39
+ livemode: false,
40
+ schedule: null,
41
+ cancel_at: null,
42
+ cancel_at_period_end: false,
43
+ pause_collection: null,
44
+ pending_update: null,
45
+ default_source: null,
46
+ payment_settings: {
47
+ payment_method_options: null,
48
+ payment_method_types: null,
49
+ save_default_payment_method: "off",
50
+ },
51
+ application_fee_percent: null,
52
+ trial_end: 1690000000,
53
+ items: {
54
+ has_more: false,
55
+ data: [
56
+ {
57
+ id: "si_original",
58
+ object: "subscription_item",
59
+ subscription: "sub_original",
60
+ current_period_start: expected.periodStart,
61
+ current_period_end: expected.periodEnd,
62
+ quantity: 3,
63
+ price: price(),
64
+ },
65
+ ],
66
+ },
67
+ metadata: { original: "keep" },
68
+ },
69
+ targetPrice: price("price_target", "prod_other"),
70
+ };
71
+ }
72
+
73
+ it("exports read-only renewal preparation without exposing a schedule writer", () => {
74
+ expect(sdk).toHaveProperty(
75
+ "prepareRenewalPriceReplacement",
76
+ expect.any(Function),
77
+ );
78
+ });
79
+
80
+ it("prepares an exact cross-product renewal snapshot without changing the paid item", () => {
81
+ const args = input();
82
+ const before = structuredClone(args);
83
+ const result = sdk.prepareRenewalPriceReplacement(args);
84
+ expect(result).toMatchObject({
85
+ version: 1,
86
+ status: "prepared",
87
+ scope: "platform",
88
+ expected,
89
+ quantity: 3,
90
+ requestIdentity: { key: args.key, binding: expect.any(String) },
91
+ preservation: "requires_schedule_validation",
92
+ });
93
+ expect(result.providerSnapshot.subscription.items.data[0].price.id).toBe(
94
+ "price_original",
95
+ );
96
+ expect(result.providerSnapshot.targetPrice.id).toBe("price_target");
97
+ expect(args).toEqual(before);
98
+ args.subscription.metadata.original = "changed after preparation";
99
+ expect(result.providerSnapshot.subscription).toMatchObject({
100
+ metadata: { original: "keep" },
101
+ });
102
+ });
103
+
104
+ it("binds material source settings and complete target data with stable object ordering", () => {
105
+ const args = input();
106
+ const first = sdk.prepareRenewalPriceReplacement(args);
107
+ const reordered = {
108
+ ...args,
109
+ subscription: Object.fromEntries(
110
+ Object.entries(args.subscription).reverse(),
111
+ ),
112
+ };
113
+ expect(sdk.prepareRenewalPriceReplacement(reordered).requestIdentity).toEqual(
114
+ first.requestIdentity,
115
+ );
116
+ args.subscription.metadata.original = "different";
117
+ expect(
118
+ sdk.prepareRenewalPriceReplacement(args).requestIdentity.binding,
119
+ ).not.toBe(first.requestIdentity.binding);
120
+ args.targetPrice.recurring.interval_count = 2;
121
+ expect(
122
+ sdk.prepareRenewalPriceReplacement(args).requestIdentity.binding,
123
+ ).not.toBe(first.requestIdentity.binding);
124
+ });
125
+
126
+ it.each([
127
+ ["customerAccountId", "acct_foreign"],
128
+ ["subscriptionId", "sub_foreign"],
129
+ ["itemId", "si_foreign"],
130
+ ["currentPriceId", "price_foreign"],
131
+ ["currentProductId", "prod_foreign"],
132
+ ["targetPriceId", "price_foreign"],
133
+ ["targetProductId", "prod_foreign"],
134
+ ["periodStart", 1699999999],
135
+ ["periodEnd", 1702592001],
136
+ ["livemode", true],
137
+ ] as const)(
138
+ "rejects a mismatched original/target selector %s",
139
+ (field, value) => {
140
+ const args = input();
141
+ expect(() =>
142
+ sdk.prepareRenewalPriceReplacement({
143
+ ...args,
144
+ expected: { ...expected, [field]: value },
145
+ }),
146
+ ).toThrow();
147
+ },
148
+ );
149
+
150
+ it.each([
151
+ ["schedule", "sub_sched_unrelated"],
152
+ ["cancel_at_period_end", true],
153
+ ["cancel_at", expected.periodEnd + 100],
154
+ ["pause_collection", { behavior: "void" }],
155
+ ["pending_update", {}],
156
+ ["default_source", "card_legacy"],
157
+ ["application_fee_percent", 0],
158
+ ["status", "trialing"],
159
+ ["payment_settings", { payment_method_types: ["card"] }],
160
+ ] as const)(
161
+ "rejects unsupported pre-attach state %s without a writer",
162
+ (field, value) => {
163
+ const args = input();
164
+ expect(() =>
165
+ sdk.prepareRenewalPriceReplacement({
166
+ ...args,
167
+ subscription: { ...args.subscription, [field]: value },
168
+ }),
169
+ ).toThrow();
170
+ },
171
+ );
172
+
173
+ it("rejects incomplete/multi-item reads and an unexpanded original price", () => {
174
+ const args = input();
175
+ expect(() =>
176
+ sdk.prepareRenewalPriceReplacement({
177
+ ...args,
178
+ subscription: {
179
+ ...args.subscription,
180
+ items: { ...args.subscription.items, has_more: true },
181
+ },
182
+ }),
183
+ ).toThrow();
184
+ expect(() =>
185
+ sdk.prepareRenewalPriceReplacement({
186
+ ...args,
187
+ subscription: {
188
+ ...args.subscription,
189
+ items: {
190
+ has_more: false,
191
+ data: [
192
+ ...args.subscription.items.data,
193
+ ...args.subscription.items.data,
194
+ ],
195
+ },
196
+ },
197
+ }),
198
+ ).toThrow();
199
+ expect(() =>
200
+ sdk.prepareRenewalPriceReplacement({
201
+ ...args,
202
+ subscription: {
203
+ ...args.subscription,
204
+ items: {
205
+ has_more: false,
206
+ data: [
207
+ { ...args.subscription.items.data[0], price: "price_original" },
208
+ ],
209
+ },
210
+ },
211
+ }),
212
+ ).toThrow();
213
+ });
214
+
215
+ it.each(["", " ", "bad\nkey", "a".repeat(256)])(
216
+ "requires an explicit valid retained key %j",
217
+ (key) => {
218
+ expect(() =>
219
+ sdk.prepareRenewalPriceReplacement({ ...input(), key }),
220
+ ).toThrow();
221
+ },
222
+ );
223
+
224
+ it("rejects an unexpected connected scope instead of silently assuming platform scope", () => {
225
+ expect(() =>
226
+ sdk.prepareRenewalPriceReplacement({
227
+ ...input(),
228
+ connectedAccountId: "acct_other",
229
+ } as Parameters<typeof sdk.prepareRenewalPriceReplacement>[0]),
230
+ ).toThrow(/Unrecognized|scope/);
231
+ });
232
+
233
+ it("rejects sparse JSON arrays instead of silently converting holes to null", () => {
234
+ const args = input();
235
+ expect(() =>
236
+ sdk.prepareRenewalPriceReplacement({
237
+ ...args,
238
+ subscription: {
239
+ ...args.subscription,
240
+ metadata: { sparse: new Array(1) },
241
+ },
242
+ }),
243
+ ).toThrow(/JSON/);
244
+ });
245
+
246
+ it("rejects enumerable accessors without executing them while copying provider data", () => {
247
+ const args = input();
248
+ let evaluated = false;
249
+ Object.defineProperty(args.subscription, "metadata", {
250
+ enumerable: true,
251
+ get() {
252
+ evaluated = true;
253
+ return { original: "getter" };
254
+ },
255
+ });
256
+ expect(() => sdk.prepareRenewalPriceReplacement(args)).toThrow(/JSON/);
257
+ expect(evaluated).toBe(false);
258
+ });
259
+
260
+ it("accepts a full provider read with an empty billing_schedules list", () => {
261
+ const args = input();
262
+ expect(
263
+ sdk.prepareRenewalPriceReplacement({
264
+ ...args,
265
+ subscription: { ...args.subscription, billing_schedules: [] },
266
+ }).status,
267
+ ).toBe("prepared");
268
+ });
269
+
270
+ it("retains a provider default-null payment setting without certifying preservation", () => {
271
+ const args = input();
272
+ expect(
273
+ sdk.prepareRenewalPriceReplacement({
274
+ ...args,
275
+ subscription: {
276
+ ...args.subscription,
277
+ payment_settings: {
278
+ ...args.subscription.payment_settings,
279
+ save_default_payment_method: null,
280
+ },
281
+ },
282
+ }),
283
+ ).toMatchObject({
284
+ preservation: "requires_schedule_validation",
285
+ providerSnapshot: {
286
+ subscription: { payment_settings: { save_default_payment_method: null } },
287
+ },
288
+ });
289
+ });
290
+
291
+ it("bounds array traversal before inspecting its elements", () => {
292
+ const args = input();
293
+ let inspected = 0;
294
+ const large = Array.from({ length: 10_001 }, () => ({}));
295
+ for (const value of large)
296
+ Object.defineProperty(value, "data", {
297
+ enumerable: true,
298
+ get() {
299
+ inspected++;
300
+ return "x";
301
+ },
302
+ });
303
+ expect(() =>
304
+ sdk.prepareRenewalPriceReplacement({
305
+ ...args,
306
+ subscription: { ...args.subscription, metadata: { large } },
307
+ }),
308
+ ).toThrow(/too large|budget/);
309
+ expect(inspected).toBe(0);
310
+ });
311
+
312
+ const billingCustomer = {
313
+ id: "cus_buyer",
314
+ object: "customer",
315
+ customer_account: "acct_buyer",
316
+ livemode: false,
317
+ discount: null,
318
+ invoice_settings: { default_payment_method: null },
319
+ };
320
+
321
+ it("binds the correlated billing-customer bridge without claiming discount hierarchy proof", () => {
322
+ const args = input();
323
+ const result = sdk.prepareRenewalPriceReplacement({
324
+ ...args,
325
+ subscription: { ...args.subscription, customer: "cus_buyer" },
326
+ billingCustomer,
327
+ });
328
+ expect(result.providerSnapshot).toMatchObject({ billingCustomer });
329
+ expect(result.preservation).toBe("requires_schedule_validation");
330
+ const changed = sdk.prepareRenewalPriceReplacement({
331
+ ...args,
332
+ subscription: { ...args.subscription, customer: "cus_buyer" },
333
+ billingCustomer: {
334
+ ...billingCustomer,
335
+ invoice_settings: { default_payment_method: "pm_changed" },
336
+ },
337
+ });
338
+ expect(changed.requestIdentity.binding).not.toBe(
339
+ result.requestIdentity.binding,
340
+ );
341
+ });
342
+
343
+ it.each([
344
+ ["id", "cus_foreign"],
345
+ ["customer_account", "acct_foreign"],
346
+ ["livemode", true],
347
+ ["deleted", true],
348
+ ] as const)(
349
+ "rejects foreign/deleted billing-customer evidence %s",
350
+ (field, value) => {
351
+ const args = input();
352
+ expect(() =>
353
+ sdk.prepareRenewalPriceReplacement({
354
+ ...args,
355
+ subscription: { ...args.subscription, customer: "cus_buyer" },
356
+ billingCustomer: { ...billingCustomer, [field]: value },
357
+ }),
358
+ ).toThrow();
359
+ },
360
+ );
361
+
362
+ it("requires an explicit discount read in supplied ancestor evidence", () => {
363
+ const args = input();
364
+ expect(() =>
365
+ sdk.prepareRenewalPriceReplacement({
366
+ ...args,
367
+ subscription: { ...args.subscription, customer: "cus_buyer" },
368
+ billingCustomer: {
369
+ id: "cus_buyer",
370
+ object: "customer",
371
+ customer_account: "acct_buyer",
372
+ livemode: false,
373
+ },
374
+ }),
375
+ ).toThrow();
376
+ });
377
+
378
+ it("accepts an expanded original customer and retains an expanded existing redemption as evidence only", () => {
379
+ const args = input();
380
+ const customer = {
381
+ ...billingCustomer,
382
+ discount: {
383
+ id: "di_existing",
384
+ object: "discount",
385
+ start: 1690000000,
386
+ end: null,
387
+ source: {
388
+ type: "coupon",
389
+ coupon: { id: "coupon_existing", duration: "once" },
390
+ },
391
+ },
392
+ };
393
+ expect(
394
+ sdk.prepareRenewalPriceReplacement({
395
+ ...args,
396
+ subscription: { ...args.subscription, customer: billingCustomer },
397
+ billingCustomer: customer,
398
+ }),
399
+ ).toMatchObject({
400
+ preservation: "requires_schedule_validation",
401
+ providerSnapshot: { billingCustomer: customer },
402
+ });
403
+ });
404
+
405
+ it("rejects a deleted expanded original customer even when the separate billing read matches its ID", () => {
406
+ const args = input();
407
+ expect(() =>
408
+ sdk.prepareRenewalPriceReplacement({
409
+ ...args,
410
+ subscription: {
411
+ ...args.subscription,
412
+ customer: { ...billingCustomer, deleted: true },
413
+ },
414
+ billingCustomer,
415
+ }),
416
+ ).toThrow(/does not match/);
417
+ });
418
+
419
+ it.each([
420
+ ["nonfinite", Number.POSITIVE_INFINITY],
421
+ ["undefined", undefined],
422
+ ["function", () => 1],
423
+ ["bigint", 1n],
424
+ ["symbol", Symbol("value")],
425
+ ["class instance", new Date(0)],
426
+ ["oversized string", "x".repeat(500_001)],
427
+ ])("rejects %s in private provider JSON", (_label, value) => {
428
+ const args = input();
429
+ expect(() =>
430
+ sdk.prepareRenewalPriceReplacement({
431
+ ...args,
432
+ subscription: { ...args.subscription, metadata: { value } },
433
+ }),
434
+ ).toThrow(/JSON/);
435
+ });
436
+
437
+ it("rejects a cyclic provider snapshot", () => {
438
+ const args = input();
439
+ const cyclic: Record<string, unknown> = {};
440
+ cyclic.self = cyclic;
441
+ expect(() =>
442
+ sdk.prepareRenewalPriceReplacement({
443
+ ...args,
444
+ subscription: { ...args.subscription, metadata: cyclic },
445
+ }),
446
+ ).toThrow(/JSON/);
447
+ });
448
+
449
+ it("rejects an alternative subscription currency even when both default price currencies match", () => {
450
+ const args = input();
451
+ expect(() =>
452
+ sdk.prepareRenewalPriceReplacement({
453
+ ...args,
454
+ subscription: { ...args.subscription, currency: "eur" },
455
+ }),
456
+ ).toThrow(/currency/);
457
+ });
@@ -0,0 +1,127 @@
1
+ import { idempotencyOptions } from "../core/idempotency.js";
2
+ import {
3
+ renewalExpected,
4
+ renewalBillingCustomer,
5
+ renewalPreparationInput,
6
+ renewalPrice,
7
+ renewalSubscription,
8
+ type RenewalPriceReplacementExpected,
9
+ } from "./renewalReplacementSchema.js";
10
+ import { renewalSnapshot } from "./renewalReplacementSnapshot.js";
11
+
12
+ export type PrepareRenewalPriceReplacementOptions = {
13
+ subscription: unknown;
14
+ targetPrice: unknown;
15
+ billingCustomer?: unknown;
16
+ expected: RenewalPriceReplacementExpected;
17
+ key: string;
18
+ };
19
+
20
+ /**
21
+ * Pure read qualification, not write authorization or proof of preservation.
22
+ * Supply fresh full provider reads on the trusted server. Persist the result
23
+ * under host-owned immutable authorization before any later dispatch.
24
+ */
25
+ export function prepareRenewalPriceReplacement(
26
+ options: PrepareRenewalPriceReplacementOptions,
27
+ ) {
28
+ const args = renewalPreparationInput.parse(renewalSnapshot(options));
29
+ const key = idempotencyOptions(args.key)?.idempotencyKey;
30
+ if (!key) throw new Error("Renewal preparation requires an explicit key.");
31
+ const expected = renewalExpected.parse(args.expected);
32
+ const source = renewalSnapshot({
33
+ subscription: args.subscription,
34
+ targetPrice: args.targetPrice,
35
+ });
36
+ const subscription = renewalSubscription.parse(source.subscription);
37
+ const targetPrice = renewalPrice.parse(source.targetPrice);
38
+ const billingCustomer =
39
+ args.billingCustomer === undefined
40
+ ? undefined
41
+ : renewalBillingCustomer.parse(args.billingCustomer);
42
+ if (billingCustomer !== undefined) {
43
+ const reference = subscription.customer;
44
+ const referenceId =
45
+ typeof reference === "string"
46
+ ? reference
47
+ : typeof reference === "object" &&
48
+ reference !== null &&
49
+ "id" in reference &&
50
+ "object" in reference &&
51
+ reference.object === "customer" &&
52
+ !("deleted" in reference && reference.deleted === true)
53
+ ? reference.id
54
+ : undefined;
55
+ if (
56
+ referenceId !== billingCustomer.id ||
57
+ billingCustomer.customer_account !== expected.customerAccountId ||
58
+ billingCustomer.livemode !== expected.livemode
59
+ )
60
+ throw new Error(
61
+ "Billing customer evidence does not match the original subscription account.",
62
+ );
63
+ }
64
+ const item = subscription.items.data[0];
65
+ const current = item.price;
66
+ const productId = (p: typeof current.product) =>
67
+ typeof p === "string" ? p : p.id;
68
+ if (
69
+ subscription.id !== expected.subscriptionId ||
70
+ subscription.customer_account !== expected.customerAccountId ||
71
+ item.subscription !== expected.subscriptionId ||
72
+ item.id !== expected.itemId ||
73
+ current.id !== expected.currentPriceId ||
74
+ productId(current.product) !== expected.currentProductId ||
75
+ targetPrice.id !== expected.targetPriceId ||
76
+ productId(targetPrice.product) !== expected.targetProductId ||
77
+ item.current_period_start !== expected.periodStart ||
78
+ item.current_period_end !== expected.periodEnd ||
79
+ [subscription.livemode, current.livemode, targetPrice.livemode].some(
80
+ (mode) => mode !== expected.livemode,
81
+ )
82
+ )
83
+ throw new Error(
84
+ "Renewal replacement does not match the authorized original and target.",
85
+ );
86
+ if (
87
+ !targetPrice.active ||
88
+ current.id === targetPrice.id ||
89
+ subscription.currency !== current.currency ||
90
+ current.currency !== targetPrice.currency
91
+ )
92
+ throw new Error(
93
+ "The target must be a different active recurring price in the original subscription currency; alternative currency_options require separate validation.",
94
+ );
95
+ for (const field of [
96
+ "pending_invoice_item_interval",
97
+ "pending_setup_intent",
98
+ "pause_schedules",
99
+ ])
100
+ if (subscription[field] != null)
101
+ throw new Error(`Renewal replacement does not support ${field}.`);
102
+ const providerSnapshot = renewalSnapshot({
103
+ subscription,
104
+ targetPrice,
105
+ ...(billingCustomer === undefined ? {} : { billingCustomer }),
106
+ });
107
+ const bound = {
108
+ version: 1 as const,
109
+ scope: "platform" as const,
110
+ expected,
111
+ quantity: item.quantity,
112
+ providerSnapshot,
113
+ };
114
+ return {
115
+ ...bound,
116
+ status: "prepared" as const,
117
+ preservation: "requires_schedule_validation" as const,
118
+ requestIdentity: {
119
+ key,
120
+ binding: `renewal:v1:${JSON.stringify(renewalSnapshot(bound))}`,
121
+ },
122
+ };
123
+ }
124
+
125
+ export type PreparedRenewalPriceReplacement = ReturnType<
126
+ typeof prepareRenewalPriceReplacement
127
+ >;
@@ -0,0 +1,129 @@
1
+ import { z } from "zod";
2
+
3
+ const id = (prefix: string) =>
4
+ z
5
+ .string()
6
+ .max(255)
7
+ .regex(new RegExp(`^${prefix}_[A-Za-z0-9_]+$`));
8
+ const integer = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
9
+ const product = z.union([
10
+ id("prod"),
11
+ z
12
+ .object({ id: id("prod"), deleted: z.literal(false).optional() })
13
+ .passthrough(),
14
+ ]);
15
+ export const renewalPrice = z
16
+ .object({
17
+ id: id("price"),
18
+ object: z.literal("price"),
19
+ product,
20
+ active: z.boolean(),
21
+ livemode: z.boolean(),
22
+ type: z.literal("recurring"),
23
+ currency: z.string().regex(/^[a-z]{3}$/),
24
+ billing_scheme: z.literal("per_unit"),
25
+ recurring: z
26
+ .object({
27
+ interval: z.enum(["day", "week", "month", "year"]),
28
+ interval_count: integer,
29
+ usage_type: z.literal("licensed"),
30
+ })
31
+ .passthrough(),
32
+ })
33
+ .passthrough();
34
+
35
+ export const renewalExpected = z
36
+ .object({
37
+ customerAccountId: id("acct"),
38
+ subscriptionId: id("sub"),
39
+ itemId: id("si"),
40
+ currentPriceId: id("price"),
41
+ currentProductId: id("prod"),
42
+ targetPriceId: id("price"),
43
+ targetProductId: id("prod"),
44
+ periodStart: integer,
45
+ periodEnd: integer,
46
+ livemode: z.boolean(),
47
+ })
48
+ .strict()
49
+ .refine((v) => v.periodEnd > v.periodStart, "Invalid original period.");
50
+
51
+ export const renewalSubscription = z
52
+ .object({
53
+ id: id("sub"),
54
+ object: z.literal("subscription"),
55
+ customer_account: id("acct"),
56
+ status: z.literal("active"),
57
+ currency: z.string().regex(/^[a-z]{3}$/),
58
+ livemode: z.boolean(),
59
+ schedule: z.null(),
60
+ cancel_at: z.null(),
61
+ cancel_at_period_end: z.literal(false),
62
+ pause_collection: z.null(),
63
+ pending_update: z.null(),
64
+ default_source: z.null(),
65
+ application_fee_percent: z.null(),
66
+ payment_settings: z.union([
67
+ z.null(),
68
+ z
69
+ .object({
70
+ payment_method_options: z.null(),
71
+ payment_method_types: z.null(),
72
+ save_default_payment_method: z.literal("off").nullable(),
73
+ })
74
+ .strict(),
75
+ ]),
76
+ billing_schedules: z.array(z.unknown()).length(0).optional(),
77
+ items: z
78
+ .object({
79
+ has_more: z.literal(false),
80
+ data: z.tuple([
81
+ z
82
+ .object({
83
+ id: id("si"),
84
+ object: z.literal("subscription_item"),
85
+ subscription: id("sub"),
86
+ current_period_start: integer,
87
+ current_period_end: integer,
88
+ quantity: integer,
89
+ price: renewalPrice,
90
+ })
91
+ .passthrough(),
92
+ ]),
93
+ })
94
+ .passthrough(),
95
+ })
96
+ .passthrough();
97
+
98
+ /** Trusted host selectors from the original authorized operation, not browser claims. */
99
+ export type RenewalPriceReplacementExpected = z.infer<typeof renewalExpected>;
100
+
101
+ export const renewalBillingCustomer = z
102
+ .object({
103
+ id: id("cus"),
104
+ object: z.literal("customer"),
105
+ customer_account: id("acct"),
106
+ livemode: z.boolean(),
107
+ deleted: z.literal(false).optional(),
108
+ discount: z.union([
109
+ z.null(),
110
+ z
111
+ .object({
112
+ id: id("di"),
113
+ object: z.literal("discount"),
114
+ deleted: z.literal(false).optional(),
115
+ })
116
+ .passthrough(),
117
+ ]),
118
+ })
119
+ .passthrough();
120
+
121
+ export const renewalPreparationInput = z
122
+ .object({
123
+ subscription: z.unknown(),
124
+ targetPrice: z.unknown(),
125
+ billingCustomer: z.unknown().optional(),
126
+ expected: renewalExpected,
127
+ key: z.string(),
128
+ })
129
+ .strict();