@fantastic.dev/better-stripe 0.83.1 → 0.85.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 (35) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalV2/binding.d.ts +3 -0
  4. package/dist/client/billing/renewalV2/binding.d.ts.map +1 -0
  5. package/dist/client/billing/renewalV2/binding.js +18 -0
  6. package/dist/client/billing/renewalV2/binding.js.map +1 -0
  7. package/dist/client/billing/renewalV2/index.d.ts +63 -0
  8. package/dist/client/billing/renewalV2/index.d.ts.map +1 -0
  9. package/dist/client/billing/renewalV2/index.js +124 -0
  10. package/dist/client/billing/renewalV2/index.js.map +1 -0
  11. package/dist/client/billing/renewalV2/receipt.d.ts +36 -0
  12. package/dist/client/billing/renewalV2/receipt.d.ts.map +1 -0
  13. package/dist/client/billing/renewalV2/receipt.js +131 -0
  14. package/dist/client/billing/renewalV2/receipt.js.map +1 -0
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  16. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  17. package/dist/client/renewal.d.ts +2 -0
  18. package/dist/client/renewal.d.ts.map +1 -1
  19. package/dist/client/renewal.js +1 -0
  20. package/dist/client/renewal.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/stateHandlers.d.ts +8 -8
  24. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  25. package/dist/component/earnings/triggers.d.ts +16 -16
  26. package/dist/component/usageCredits/accounting.fixtures.d.ts +16 -16
  27. package/docs/renewal-context-reads.md +134 -0
  28. package/docs/renewal-phase-assembly.md +5 -0
  29. package/package.json +1 -1
  30. package/src/client/billing/renewalV2/binding.ts +25 -0
  31. package/src/client/billing/renewalV2/index.test.ts +414 -0
  32. package/src/client/billing/renewalV2/index.ts +214 -0
  33. package/src/client/billing/renewalV2/receipt.test.ts +289 -0
  34. package/src/client/billing/renewalV2/receipt.ts +163 -0
  35. package/src/client/renewal.ts +13 -0
@@ -0,0 +1,414 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { createHash, webcrypto } from "node:crypto";
3
+ import {
4
+ prepareRenewalPriceReplacementV2 as prepare,
5
+ prepareRenewalScheduleAttachmentV2 as attach,
6
+ } from "./index.js";
7
+ import { prepareRenewalPriceReplacement as legacy } from "../renewalPriceReplacement.js";
8
+ import { prepareRenewalScheduleAttachment as legacyAttach } from "../renewalAttach/request.js";
9
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
10
+
11
+ const apiVersion = "2026-09-30.endive";
12
+ const firstDispatchedAt = 1700000001;
13
+ const c = (v: unknown) => JSON.stringify(renewalSnapshot(v));
14
+ const digest = (family: string, v: unknown) =>
15
+ `${family}:v2:sha256:${createHash("sha256")
16
+ .update(c(["betterstripe-renewal-binding", 2, family, v]), "utf8")
17
+ .digest("hex")}`;
18
+ const unsigned = (p: any) => {
19
+ const {
20
+ status: _status,
21
+ preservation: _preservation,
22
+ requestIdentity: _requestIdentity,
23
+ ...bound
24
+ } = p;
25
+ return bound;
26
+ };
27
+ const args = (prepared: any) => ({
28
+ prepared,
29
+ apiVersion,
30
+ attachKey: "attach:explicit",
31
+ firstDispatchedAt,
32
+ });
33
+ afterEach(() => vi.unstubAllGlobals());
34
+ it("constructs exact C1 bytes and all original semantic facts", async () => {
35
+ const raw = input();
36
+ const old = legacy(raw);
37
+ const p = await prepare(raw);
38
+ expect(p).toEqual({
39
+ ...old,
40
+ version: 2,
41
+ requestIdentity: {
42
+ key: old.requestIdentity.key,
43
+ binding: digest("renewal", { ...unsigned(old), version: 2 }),
44
+ },
45
+ });
46
+ expect(old.version).toBe(1);
47
+ expect(old.requestIdentity.binding.startsWith("renewal:v1:")).toBe(true);
48
+ });
49
+ it("constructs exact complete C2 request, key and first-dispatch bytes", async () => {
50
+ const p: any = await prepare(input());
51
+ const r = await attach(args(p));
52
+ const { requestIdentity, ...body } = r;
53
+ expect(body).toEqual({
54
+ version: 2,
55
+ stage: "attach",
56
+ scope: "platform",
57
+ apiVersion,
58
+ logicalBinding: p.requestIdentity.binding,
59
+ method: "POST",
60
+ path: "/v1/subscription_schedules",
61
+ payload: { from_subscription: "sub_original" },
62
+ key: "attach:explicit",
63
+ firstDispatchedAt,
64
+ });
65
+ expect(requestIdentity).toEqual({
66
+ key: body.key,
67
+ binding: digest("renewal-attach", body),
68
+ });
69
+ });
70
+ it.each([
71
+ "scope",
72
+ "version",
73
+ "status",
74
+ "preservation",
75
+ "quantity",
76
+ "expected",
77
+ "providerSnapshot",
78
+ "requestIdentity",
79
+ "extra",
80
+ ])(
81
+ "rejects tampered retained prepared %s by full recomputation",
82
+ async (field) => {
83
+ const p: any = await prepare(input());
84
+ if (field === "scope") p.scope = "connected";
85
+ else if (field === "version") p.version = 1;
86
+ else if (field === "quantity") p.quantity = 99;
87
+ else if (field === "expected") p.expected.targetPriceId = "price_foreign";
88
+ else if (field === "providerSnapshot")
89
+ p.providerSnapshot.subscription.metadata.original = "changed";
90
+ else if (field === "requestIdentity")
91
+ p.requestIdentity.binding = "renewal:v2:sha256:" + "0".repeat(64);
92
+ else p[field] = "tampered";
93
+ await expect(attach(args(p))).rejects.toThrow();
94
+ },
95
+ );
96
+ it("does not adopt or migrate a V1 prepared record", async () => {
97
+ await expect(attach(args(legacy(input())))).rejects.toThrow();
98
+ });
99
+ it.each(["method", "path", "scope", "payload", "unexpected"])(
100
+ "rejects caller request override %s",
101
+ async (field) => {
102
+ const a: any = args(await prepare(input()));
103
+ a[field] = field === "method" ? "GET" : "override";
104
+ await expect(attach(a)).rejects.toThrow();
105
+ },
106
+ );
107
+ it.each(["apiVersion", "attachKey", "firstDispatchedAt"])(
108
+ "binds changed valid C2 %s or rejects unsupported values",
109
+ async (field) => {
110
+ const p: any = await prepare(input());
111
+ const a = args(p);
112
+ const original = await attach(a);
113
+ const changed: any = { ...a };
114
+ if (field === "apiVersion") {
115
+ changed.apiVersion = "2025-01-01.acacia";
116
+ await expect(attach(changed)).rejects.toThrow();
117
+ return;
118
+ }
119
+ changed[field] =
120
+ field === "attachKey" ? "attach:second" : firstDispatchedAt + 1;
121
+ expect((await attach(changed)).requestIdentity.binding).not.toBe(
122
+ original.requestIdentity.binding,
123
+ );
124
+ },
125
+ );
126
+ it.each(["", "\rkey", "x".repeat(256)])(
127
+ "rejects invalid attach key",
128
+ async (key) => {
129
+ await expect(
130
+ attach({ ...args(await prepare(input())), attachKey: key }),
131
+ ).rejects.toThrow();
132
+ },
133
+ );
134
+ it("retains ordinary product metadata including PAN-like and credential-like text", async () => {
135
+ const raw = input();
136
+ raw.subscription.metadata = {
137
+ note: "4111111111111111",
138
+ client_secret: "ordinary synthetic metadata",
139
+ } as any;
140
+ const p = await prepare(raw);
141
+ expect(p.providerSnapshot.subscription.metadata).toEqual(
142
+ raw.subscription.metadata,
143
+ );
144
+ });
145
+ it("uses reviewed Unicode, numeric-index, escaping and negative-zero bytes", async () => {
146
+ const raw = input();
147
+ raw.subscription.metadata = {
148
+ "10": "ten",
149
+ "2": "two",
150
+ z: "雪😀\ud800",
151
+ a: '"\\\n',
152
+ zero: -0,
153
+ } as any;
154
+ const p = await prepare(raw);
155
+ expect(p.requestIdentity.binding).toBe(digest("renewal", unsigned(p)));
156
+ });
157
+ it.each(["target", "period", "quantity", "mode"])(
158
+ "retains V1 semantic rejection for invalid %s",
159
+ async (kind) => {
160
+ const raw = input();
161
+ if (kind === "target") raw.targetPrice.active = false;
162
+ else if (kind === "period")
163
+ raw.expected.periodEnd = raw.expected.periodStart;
164
+ else if (kind === "quantity") raw.subscription.items.data[0].quantity = 0;
165
+ else raw.targetPrice.livemode = true;
166
+ expect(() => legacy(raw)).toThrow();
167
+ await expect(prepare(raw)).rejects.toThrow();
168
+ },
169
+ );
170
+ it("captures before awaiting hash and never rereads live input", async () => {
171
+ let release!: () => void;
172
+ let entered!: () => void;
173
+ const started = new Promise<void>((r) => (entered = r));
174
+ const hold = new Promise<void>((r) => (release = r));
175
+ vi.stubGlobal("crypto", {
176
+ subtle: {
177
+ digest: async (name: any, bytes: any) => {
178
+ entered();
179
+ await hold;
180
+ return webcrypto.subtle.digest(name, bytes);
181
+ },
182
+ },
183
+ });
184
+ const raw = input();
185
+ const original = structuredClone(raw);
186
+ const pending = prepare(raw);
187
+ await Promise.race([started, pending]);
188
+ raw.subscription.metadata.original = "MUTATED";
189
+ raw.expected.targetPriceId = "price_foreign";
190
+ release();
191
+ const result = await pending;
192
+ expect(
193
+ (result.providerSnapshot.subscription.metadata as Record<string, unknown>)
194
+ .original,
195
+ ).toBe(original.subscription.metadata.original);
196
+ expect(result.requestIdentity.binding).toBe(
197
+ digest("renewal", unsigned(result)),
198
+ );
199
+ });
200
+ it("captures full attach record before C1 verification awaits", async () => {
201
+ const p: any = await prepare(input());
202
+ let release!: () => void;
203
+ let entered!: () => void;
204
+ const started = new Promise<void>((r) => (entered = r));
205
+ const hold = new Promise<void>((r) => (release = r));
206
+ vi.stubGlobal("crypto", {
207
+ subtle: {
208
+ digest: async (name: any, bytes: any) => {
209
+ entered();
210
+ await hold;
211
+ return webcrypto.subtle.digest(name, bytes);
212
+ },
213
+ },
214
+ });
215
+ const a = args(p);
216
+ const pending = attach(a);
217
+ await Promise.race([started, pending]);
218
+ a.attachKey = "changed";
219
+ a.firstDispatchedAt++;
220
+ p.providerSnapshot.subscription.metadata.original = "changed";
221
+ release();
222
+ const r = await pending;
223
+ expect(r.key).toBe("attach:explicit");
224
+ expect(r.firstDispatchedAt).toBe(firstDispatchedAt);
225
+ });
226
+ it.each(["missing", "rejected"])(
227
+ "fails closed with %s WebCrypto and no fallback",
228
+ async (mode) => {
229
+ vi.stubGlobal(
230
+ "crypto",
231
+ mode === "missing"
232
+ ? undefined
233
+ : {
234
+ subtle: {
235
+ digest: () =>
236
+ Promise.reject(new Error("synthetic digest refusal")),
237
+ },
238
+ },
239
+ );
240
+ await expect(prepare(input())).rejects.toThrow();
241
+ },
242
+ );
243
+ it("enforces UTF8 cap on exact domain tuple at 500000 bytes including domain overhead", async () => {
244
+ const raw = input();
245
+ raw.subscription.metadata = { pad: "" } as any;
246
+ const base = legacy(raw);
247
+ const overhead = Buffer.byteLength(
248
+ c([
249
+ "betterstripe-renewal-binding",
250
+ 2,
251
+ "renewal",
252
+ { ...unsigned(base), version: 2 },
253
+ ]),
254
+ "utf8",
255
+ );
256
+ raw.subscription.metadata = { pad: "x".repeat(500000 - overhead) } as any;
257
+ let calls = 0;
258
+ vi.stubGlobal("crypto", {
259
+ subtle: {
260
+ digest: async (n: any, b: any) => {
261
+ calls++;
262
+ expect(b.byteLength).toBeLessThanOrEqual(500000);
263
+ return webcrypto.subtle.digest(n, b);
264
+ },
265
+ },
266
+ });
267
+ expect((await prepare(raw)).version).toBe(2);
268
+ expect(calls).toBe(1);
269
+ raw.subscription.metadata = { pad: "x".repeat(500001 - overhead) } as any;
270
+ await expect(prepare(raw)).rejects.toThrow();
271
+ expect(calls).toBe(1);
272
+ });
273
+ it("rejects multibyte preimage exceeding UTF8 cap before hashing while V1 character input fits", async () => {
274
+ const raw = input();
275
+ raw.subscription.metadata = { pad: "雪".repeat(170000) } as any;
276
+ expect(legacy(raw).version).toBe(1);
277
+ const spy = vi.fn();
278
+ vi.stubGlobal("crypto", { subtle: { digest: spy } });
279
+ await expect(prepare(raw)).rejects.toThrow();
280
+ expect(spy).not.toHaveBeenCalled();
281
+ });
282
+ it("keeps V1 attach output unchanged", () => {
283
+ const old = legacy(input());
284
+ expect(legacyAttach(args(old))).toMatchObject({
285
+ version: 1,
286
+ scope: "platform",
287
+ payload: { from_subscription: "sub_original" },
288
+ });
289
+ });
290
+
291
+ it("keeps logical preparation key separate from C1 digest", async () => {
292
+ const a = input();
293
+ const b = input();
294
+ b.key = "another:logical-key";
295
+ const x = await prepare(a),
296
+ y = await prepare(b);
297
+ expect(x.requestIdentity.binding).toBe(y.requestIdentity.binding);
298
+ expect(x.requestIdentity.key).not.toBe(y.requestIdentity.key);
299
+ });
300
+ it("exports additive V2 functions through the actual public SDK barrel", async () => {
301
+ const sdk = await import("../../index.js");
302
+ expect(sdk).toHaveProperty("prepareRenewalPriceReplacementV2", prepare);
303
+ expect(sdk).toHaveProperty("prepareRenewalScheduleAttachmentV2", attach);
304
+ expect(sdk.prepareRenewalPriceReplacement).toBe(legacy);
305
+ expect(sdk).not.toHaveProperty("renewalBindingV2");
306
+ });
307
+
308
+ it.each(["nonfinite", "cycle", "accessor", "sparse"])(
309
+ "rejects unsupported JSON %s before digest",
310
+ async (kind) => {
311
+ const raw = input() as any;
312
+ const spy = vi.fn();
313
+ vi.stubGlobal("crypto", { subtle: { digest: spy } });
314
+ if (kind === "nonfinite") raw.subscription.metadata = { n: Infinity };
315
+ else if (kind === "cycle") raw.subscription.metadata = raw;
316
+ else if (kind === "accessor") {
317
+ raw.subscription.metadata = {};
318
+ Object.defineProperty(raw.subscription.metadata, "danger", {
319
+ enumerable: true,
320
+ get() {
321
+ throw Error("getter must not execute");
322
+ },
323
+ });
324
+ } else raw.subscription.metadata = { a: new Array(2) };
325
+ await expect(prepare(raw)).rejects.toThrow();
326
+ expect(spy).not.toHaveBeenCalled();
327
+ },
328
+ );
329
+ it("does not perform network access in either public pure constructor", async () => {
330
+ const fetch = vi.fn(() => {
331
+ throw Error("network forbidden");
332
+ });
333
+ vi.stubGlobal("fetch", fetch);
334
+ const p: any = await prepare(input());
335
+ await attach(args(p));
336
+ expect(fetch).not.toHaveBeenCalled();
337
+ });
338
+
339
+ it.each(["", "\ninvalid", "k".repeat(256)])(
340
+ "keeps original logical-key validation",
341
+ async (key) => {
342
+ await expect(prepare({ ...input(), key })).rejects.toThrow();
343
+ },
344
+ );
345
+
346
+ const expected = {
347
+ customerAccountId: "acct_buyer",
348
+ subscriptionId: "sub_original",
349
+ itemId: "si_original",
350
+ currentPriceId: "price_original",
351
+ currentProductId: "prod_original",
352
+ targetPriceId: "price_target",
353
+ targetProductId: "prod_other",
354
+ periodStart: 1700000000,
355
+ periodEnd: 1702592000,
356
+ livemode: false,
357
+ };
358
+
359
+ function price(id = "price_original", product = "prod_original") {
360
+ return {
361
+ id,
362
+ product,
363
+ object: "price",
364
+ active: true,
365
+ livemode: false,
366
+ type: "recurring",
367
+ currency: "usd",
368
+ billing_scheme: "per_unit",
369
+ recurring: { interval: "month", interval_count: 1, usage_type: "licensed" },
370
+ };
371
+ }
372
+ function input() {
373
+ return {
374
+ expected: structuredClone(expected),
375
+ key: "renewal:original-operation",
376
+ subscription: {
377
+ id: "sub_original",
378
+ object: "subscription",
379
+ customer_account: "acct_buyer",
380
+ status: "active",
381
+ currency: "usd",
382
+ livemode: false,
383
+ schedule: null,
384
+ cancel_at: null,
385
+ cancel_at_period_end: false,
386
+ pause_collection: null,
387
+ pending_update: null,
388
+ default_source: null,
389
+ payment_settings: {
390
+ payment_method_options: null,
391
+ payment_method_types: null,
392
+ save_default_payment_method: "off",
393
+ },
394
+ application_fee_percent: null,
395
+ trial_end: 1690000000,
396
+ items: {
397
+ has_more: false,
398
+ data: [
399
+ {
400
+ id: "si_original",
401
+ object: "subscription_item",
402
+ subscription: "sub_original",
403
+ current_period_start: expected.periodStart,
404
+ current_period_end: expected.periodEnd,
405
+ quantity: 3,
406
+ price: price(),
407
+ },
408
+ ],
409
+ },
410
+ metadata: { original: "keep" },
411
+ },
412
+ targetPrice: price("price_target", "prod_other"),
413
+ };
414
+ }
@@ -0,0 +1,214 @@
1
+ import { z } from "zod";
2
+ import {
3
+ prepareRenewalPriceReplacement,
4
+ type PrepareRenewalPriceReplacementOptions,
5
+ type PreparedRenewalPriceReplacement,
6
+ } from "../renewalPriceReplacement.js";
7
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
8
+ import {
9
+ supportedVersion,
10
+ timestamp,
11
+ resourceId,
12
+ equal,
13
+ } from "../renewalAggregate/shared.js";
14
+ import { idempotencyOptions } from "../../core/idempotency.js";
15
+ import { renewalBindingV2 } from "./binding.js";
16
+ import {
17
+ captureAttachmentReceipt,
18
+ assertAttachmentIdentity,
19
+ } from "./receipt.js";
20
+
21
+ export type PrepareRenewalPriceReplacementV2Options =
22
+ PrepareRenewalPriceReplacementOptions;
23
+ export type PreparedRenewalPriceReplacementV2 = Omit<
24
+ PreparedRenewalPriceReplacement,
25
+ "version" | "requestIdentity"
26
+ > & {
27
+ version: 2;
28
+ requestIdentity: { key: string; binding: string };
29
+ };
30
+
31
+ /** Pure preparation. Protect retained full records under host authorization. */
32
+ export async function prepareRenewalPriceReplacementV2(
33
+ options: PrepareRenewalPriceReplacementV2Options,
34
+ ): Promise<PreparedRenewalPriceReplacementV2> {
35
+ // Reuse the existing raw constructor's semantic checks, not a stored V1 claim.
36
+ const original = prepareRenewalPriceReplacement(renewalSnapshot(options));
37
+ const { status, preservation, requestIdentity, ...source } = original;
38
+ const bound = { ...source, version: 2 as const };
39
+ const binding = await renewalBindingV2("renewal", bound);
40
+ return {
41
+ ...bound,
42
+ status,
43
+ preservation,
44
+ requestIdentity: { key: requestIdentity.key, binding },
45
+ };
46
+ }
47
+
48
+ export type PrepareRenewalScheduleAttachmentV2Options = {
49
+ prepared: unknown;
50
+ apiVersion: string;
51
+ attachKey: string;
52
+ firstDispatchedAt: number;
53
+ };
54
+ export type PreparedRenewalScheduleAttachmentV2 = {
55
+ version: 2;
56
+ stage: "attach";
57
+ scope: "platform";
58
+ apiVersion: string;
59
+ logicalBinding: string;
60
+ method: "POST";
61
+ path: "/v1/subscription_schedules";
62
+ payload: { from_subscription: string };
63
+ key: string;
64
+ firstDispatchedAt: number;
65
+ requestIdentity: { key: string; binding: string };
66
+ };
67
+ const attachInput = z
68
+ .object({
69
+ prepared: z.unknown(),
70
+ apiVersion: z.string(),
71
+ attachKey: z.string(),
72
+ firstDispatchedAt: timestamp,
73
+ })
74
+ .strict();
75
+ const record = z.record(z.string(), z.unknown());
76
+
77
+ /** Pure C2 request. No dispatch, receipt, provider qualification or V1 migration. */
78
+ export async function prepareRenewalScheduleAttachmentV2(
79
+ options: PrepareRenewalScheduleAttachmentV2Options,
80
+ ): Promise<PreparedRenewalScheduleAttachmentV2> {
81
+ // This detached capture includes every option and retained fact before await.
82
+ const args = attachInput.parse(renewalSnapshot(options));
83
+ supportedVersion(args.apiVersion);
84
+ const key = idempotencyOptions(args.attachKey)?.idempotencyKey;
85
+ if (!key) throw new Error("Renewal V2 requires an explicit attachment key.");
86
+ const candidate = record.parse(args.prepared);
87
+ if (candidate.version !== 2)
88
+ throw new Error("Renewal V2 requires a V2 preparation.");
89
+ const source = record.parse(candidate.providerSnapshot);
90
+ const identity = record.parse(candidate.requestIdentity);
91
+ const rebuilt = await prepareRenewalPriceReplacementV2({
92
+ subscription: source.subscription,
93
+ targetPrice: source.targetPrice,
94
+ ...(source.billingCustomer === undefined
95
+ ? {}
96
+ : { billingCustomer: source.billingCustomer }),
97
+ expected:
98
+ candidate.expected as PrepareRenewalPriceReplacementOptions["expected"],
99
+ key: z.string().parse(identity.key),
100
+ });
101
+ if (
102
+ JSON.stringify(renewalSnapshot(rebuilt)) !==
103
+ JSON.stringify(renewalSnapshot(candidate))
104
+ )
105
+ throw new Error("Renewal V2 preparation does not match its full source.");
106
+ const request = {
107
+ version: 2 as const,
108
+ stage: "attach" as const,
109
+ scope: "platform" as const,
110
+ apiVersion: args.apiVersion,
111
+ logicalBinding: rebuilt.requestIdentity.binding,
112
+ method: "POST" as const,
113
+ path: "/v1/subscription_schedules" as const,
114
+ payload: { from_subscription: rebuilt.expected.subscriptionId },
115
+ key,
116
+ firstDispatchedAt: args.firstDispatchedAt,
117
+ };
118
+ const binding = await renewalBindingV2("renewal-attach", request);
119
+ return { ...request, requestIdentity: { key, binding } };
120
+ }
121
+
122
+ export type ConstructRenewalScheduleAttachmentReceiptV2Options = {
123
+ attachRequest: {
124
+ preparation: PrepareRenewalPriceReplacementV2Options;
125
+ apiVersion: string;
126
+ attachKey: string;
127
+ firstDispatchedAt: number;
128
+ };
129
+ actualDispatch: Pick<
130
+ PreparedRenewalScheduleAttachmentV2,
131
+ | "scope"
132
+ | "apiVersion"
133
+ | "method"
134
+ | "path"
135
+ | "payload"
136
+ | "key"
137
+ | "firstDispatchedAt"
138
+ >;
139
+ providerSnapshot: Record<string, unknown>;
140
+ };
141
+ export type RenewalScheduleAttachmentReceiptV2 = {
142
+ version: 2;
143
+ stage: "attached_unconfigured";
144
+ scope: "platform";
145
+ logicalBinding: string;
146
+ request: PreparedRenewalScheduleAttachmentV2;
147
+ scheduleId: string;
148
+ subscriptionId: string;
149
+ customerAccountId: string;
150
+ livemode: boolean;
151
+ providerSnapshot: Record<string, unknown>;
152
+ binding: string;
153
+ };
154
+
155
+ /** Pure unsigned consistency data. Does not authenticate or acknowledge a POST. */
156
+ export async function constructRenewalScheduleAttachmentReceiptV2(
157
+ options: ConstructRenewalScheduleAttachmentReceiptV2Options,
158
+ ): Promise<RenewalScheduleAttachmentReceiptV2> {
159
+ const args = captureAttachmentReceipt(options);
160
+ const prepared = await prepareRenewalPriceReplacementV2({
161
+ ...args.attachRequest.preparation,
162
+ expected: args.attachRequest.preparation
163
+ .expected as PrepareRenewalPriceReplacementOptions["expected"],
164
+ });
165
+ const request = await prepareRenewalScheduleAttachmentV2({
166
+ prepared,
167
+ apiVersion: args.attachRequest.apiVersion,
168
+ attachKey: args.attachRequest.attachKey,
169
+ firstDispatchedAt: args.attachRequest.firstDispatchedAt,
170
+ });
171
+ const { scope, apiVersion, method, path, payload, key, firstDispatchedAt } =
172
+ request;
173
+ if (
174
+ !equal(args.actualDispatch, {
175
+ scope,
176
+ apiVersion,
177
+ method,
178
+ path,
179
+ payload,
180
+ key,
181
+ firstDispatchedAt,
182
+ })
183
+ )
184
+ throw Error(
185
+ "Renewal attachment dispatch does not match its complete request.",
186
+ );
187
+ const billingCustomer = prepared.providerSnapshot.billingCustomer;
188
+ if (!billingCustomer)
189
+ throw Error("Renewal attachment requires its retained billing Customer.");
190
+ const scheduleId = resourceId("sub_sched").parse(args.providerSnapshot.id);
191
+ assertAttachmentIdentity(args.providerSnapshot, {
192
+ scheduleId,
193
+ subscriptionId: prepared.expected.subscriptionId,
194
+ billingCustomerId: billingCustomer.id,
195
+ customerAccountId: prepared.expected.customerAccountId,
196
+ livemode: prepared.expected.livemode,
197
+ });
198
+ const receipt = {
199
+ version: 2 as const,
200
+ stage: "attached_unconfigured" as const,
201
+ scope: "platform" as const,
202
+ logicalBinding: prepared.requestIdentity.binding,
203
+ request,
204
+ scheduleId,
205
+ subscriptionId: prepared.expected.subscriptionId,
206
+ customerAccountId: prepared.expected.customerAccountId,
207
+ livemode: prepared.expected.livemode,
208
+ providerSnapshot: args.providerSnapshot,
209
+ };
210
+ return {
211
+ ...receipt,
212
+ binding: await renewalBindingV2("renewal-attach-receipt", receipt),
213
+ };
214
+ }