@fantastic.dev/better-stripe 0.83.0 → 0.83.1

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 (44) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/couponJoins.d.ts +1 -1
  4. package/dist/client/billing/renewalAttach/couponJoins.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/couponJoins.js +3 -3
  6. package/dist/client/billing/renewalAttach/couponJoins.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/reader.d.ts.map +1 -1
  8. package/dist/client/billing/renewalAttach/reader.js +5 -8
  9. package/dist/client/billing/renewalAttach/reader.js.map +1 -1
  10. package/dist/client/billing/renewalAttach/wireJson.d.ts +24 -0
  11. package/dist/client/billing/renewalAttach/wireJson.d.ts.map +1 -0
  12. package/dist/client/billing/renewalAttach/wireJson.js +51 -0
  13. package/dist/client/billing/renewalAttach/wireJson.js.map +1 -0
  14. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  15. package/dist/client/connect/payoutSyncTestHelpers.d.ts +16 -16
  16. package/dist/client/helpers.d.ts.map +1 -1
  17. package/dist/client/helpers.js +2 -2
  18. package/dist/client/helpers.js.map +1 -1
  19. package/dist/client/singleAttemptHttpClient.d.ts +1 -1
  20. package/dist/client/singleAttemptHttpClient.d.ts.map +1 -1
  21. package/dist/client/singleAttemptHttpClient.js +1 -1
  22. package/dist/client/singleAttemptHttpClient.js.map +1 -1
  23. package/dist/client/strictStripeTransport.d.ts +4 -0
  24. package/dist/client/strictStripeTransport.d.ts.map +1 -0
  25. package/dist/client/strictStripeTransport.js +7 -0
  26. package/dist/client/strictStripeTransport.js.map +1 -0
  27. package/dist/client/usage/observationClient.d.ts +2 -2
  28. package/dist/client/usage/observationClient.d.ts.map +1 -1
  29. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  30. package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
  31. package/dist/component/earnings/triggers.d.ts +16 -16
  32. package/dist/component/usageCredits/accounting.fixtures.d.ts +16 -16
  33. package/docs/renewal-context-reads.md +33 -0
  34. package/package.json +1 -1
  35. package/src/client/billing/renewalAttach/couponEvidence.test.ts +1 -2
  36. package/src/client/billing/renewalAttach/couponJoins.ts +2 -5
  37. package/src/client/billing/renewalAttach/reader.test.ts +1 -1
  38. package/src/client/billing/renewalAttach/reader.ts +6 -12
  39. package/src/client/billing/renewalAttach/wireJson.test.ts +265 -0
  40. package/src/client/billing/renewalAttach/wireJson.ts +75 -0
  41. package/src/client/helpers.ts +2 -4
  42. package/src/client/singleAttemptHttpClient.ts +1 -1
  43. package/src/client/strictStripeTransport.test.ts +73 -0
  44. package/src/client/strictStripeTransport.ts +11 -0
@@ -60,6 +60,22 @@ export declare const phaseRef: import("convex/values").VObject<{
60
60
  }, "required", "accountId" | "definitionVersion" | "operationId" | "phase" | "providerApiVersion" | "providerKey" | "scopeKey" | "stripeSubscriptionId" | "version">;
61
61
  export type FundingPhaseRef = Infer<typeof phaseRef>;
62
62
  export declare const workflowStartResult: import("convex/values").VUnion<{
63
+ reason: "history_incomplete" | "provider_outcome_unknown";
64
+ retryable: false;
65
+ status: "unknown";
66
+ } | {
67
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
68
+ retryable: false;
69
+ status: "conflict";
70
+ } | {
71
+ reason: "invalid_scope" | "policy_invalid" | "unsupported_source";
72
+ retryable: false;
73
+ status: "rejected";
74
+ } | {
75
+ reason: "provider_pending";
76
+ retryable: true;
77
+ status: "not_ready";
78
+ } | {
63
79
  operation: {
64
80
  accountId: string;
65
81
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -76,22 +92,6 @@ export declare const workflowStartResult: import("convex/values").VUnion<{
76
92
  version: number;
77
93
  };
78
94
  status: "canceled";
79
- } | {
80
- reason: "history_incomplete" | "provider_outcome_unknown";
81
- retryable: false;
82
- status: "unknown";
83
- } | {
84
- reason: "identity_changed" | "revision_changed" | "scope_busy";
85
- retryable: false;
86
- status: "conflict";
87
- } | {
88
- reason: "invalid_scope" | "policy_invalid" | "unsupported_source";
89
- retryable: false;
90
- status: "rejected";
91
- } | {
92
- reason: "provider_pending";
93
- retryable: true;
94
- status: "not_ready";
95
95
  }, [import("convex/values").VObject<{
96
96
  operation: {
97
97
  accountId: string;
@@ -372,14 +372,6 @@ export declare const mutation: import("convex-helpers/server/customFunctions").C
372
372
  preparationId: import("convex/values").GenericId<"balanceFundingPreparations">;
373
373
  requestKey: string;
374
374
  result?: {
375
- reason: "identity_changed" | "revision_changed" | "scope_busy";
376
- retryable: false;
377
- status: "conflict";
378
- } | {
379
- reason: "policy_invalid";
380
- retryable: false;
381
- status: "rejected";
382
- } | {
383
375
  operation: {
384
376
  accountId: string;
385
377
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -390,6 +382,14 @@ export declare const mutation: import("convex-helpers/server/customFunctions").C
390
382
  } | {
391
383
  enabled: boolean;
392
384
  status: "unchanged";
385
+ } | {
386
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
387
+ retryable: false;
388
+ status: "conflict";
389
+ } | {
390
+ reason: "policy_invalid";
391
+ retryable: false;
392
+ status: "rejected";
393
393
  } | {
394
394
  reason: "provider_pending";
395
395
  retryable: true;
@@ -3270,14 +3270,6 @@ export declare const mutation: import("convex-helpers/server/customFunctions").C
3270
3270
  preparationId: import("convex/values").GenericId<"balanceFundingPreparations">;
3271
3271
  requestKey: string;
3272
3272
  result?: {
3273
- reason: "identity_changed" | "revision_changed" | "scope_busy";
3274
- retryable: false;
3275
- status: "conflict";
3276
- } | {
3277
- reason: "policy_invalid";
3278
- retryable: false;
3279
- status: "rejected";
3280
- } | {
3281
3273
  operation: {
3282
3274
  accountId: string;
3283
3275
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -3288,6 +3280,14 @@ export declare const mutation: import("convex-helpers/server/customFunctions").C
3288
3280
  } | {
3289
3281
  enabled: boolean;
3290
3282
  status: "unchanged";
3283
+ } | {
3284
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
3285
+ retryable: false;
3286
+ status: "conflict";
3287
+ } | {
3288
+ reason: "policy_invalid";
3289
+ retryable: false;
3290
+ status: "rejected";
3291
3291
  } | {
3292
3292
  reason: "provider_pending";
3293
3293
  retryable: true;
@@ -2351,6 +2351,14 @@ export declare function setupCredits(): Promise<{
2351
2351
  preparationId: import("convex/values").GenericId<"balanceFundingPreparations">;
2352
2352
  requestKey: string;
2353
2353
  result?: {
2354
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
2355
+ retryable: false;
2356
+ status: "conflict";
2357
+ } | {
2358
+ reason: "policy_invalid";
2359
+ retryable: false;
2360
+ status: "rejected";
2361
+ } | {
2354
2362
  operation: {
2355
2363
  accountId: string;
2356
2364
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -2361,14 +2369,6 @@ export declare function setupCredits(): Promise<{
2361
2369
  } | {
2362
2370
  enabled: boolean;
2363
2371
  status: "unchanged";
2364
- } | {
2365
- reason: "identity_changed" | "revision_changed" | "scope_busy";
2366
- retryable: false;
2367
- status: "conflict";
2368
- } | {
2369
- reason: "policy_invalid";
2370
- retryable: false;
2371
- status: "rejected";
2372
2372
  } | {
2373
2373
  reason: "provider_pending";
2374
2374
  retryable: true;
@@ -2379,6 +2379,14 @@ export declare function setupCredits(): Promise<{
2379
2379
  payload: import("convex/values").VString<string, "required">;
2380
2380
  preparationId: import("convex/values").VId<import("convex/values").GenericId<"balanceFundingPreparations">, "required">;
2381
2381
  result: import("convex/values").VUnion<{
2382
+ reason: "identity_changed" | "revision_changed" | "scope_busy";
2383
+ retryable: false;
2384
+ status: "conflict";
2385
+ } | {
2386
+ reason: "policy_invalid";
2387
+ retryable: false;
2388
+ status: "rejected";
2389
+ } | {
2382
2390
  operation: {
2383
2391
  accountId: string;
2384
2392
  operationId: import("convex/values").GenericId<"balanceFundingOperations">;
@@ -2389,14 +2397,6 @@ export declare function setupCredits(): Promise<{
2389
2397
  } | {
2390
2398
  enabled: boolean;
2391
2399
  status: "unchanged";
2392
- } | {
2393
- reason: "identity_changed" | "revision_changed" | "scope_busy";
2394
- retryable: false;
2395
- status: "conflict";
2396
- } | {
2397
- reason: "policy_invalid";
2398
- retryable: false;
2399
- status: "rejected";
2400
2400
  } | {
2401
2401
  reason: "provider_pending";
2402
2402
  retryable: true;
@@ -111,3 +111,36 @@ See the [replacement contract](renewal-price-replacements.md) and
111
111
  [phase assembly](renewal-phase-assembly.md) for baseline, replay and observation
112
112
  boundaries. Read comparison is best effort and cannot exclude concurrent
113
113
  Dashboard or other provider writers.
114
+
115
+ ## Wire JSON and transport status
116
+
117
+ Renewal reads use Stripe's public `rawRequest` for a fixed set of subscription,
118
+ Price, Customer and coupon GET endpoints. Each resource ID is encoded as one path
119
+ segment. Dot-only coupon IDs `.` and `..` are rejected before dispatch because
120
+ URL parsing would normalize them into different resource paths. The subscription's
121
+ fixed ordered expansion query is in the GET path,
122
+ with no GET body. Callers cannot supply endpoints, headers or expansion options.
123
+ The API version, platform scope and zero automatic network retries remain fixed.
124
+
125
+ Typed Stripe resource methods can convert decimal strings into SDK `Decimal`
126
+ objects. The raw request boundary preserves the parsed wire JSON instead,
127
+ including decimal string spelling, required native Plan fields and unknown
128
+ provider fields. The strict bounded JSON snapshot validator is unchanged. No
129
+ `Decimal.toString()` conversion, financial calculation or selective field
130
+ replacement makes unsupported evidence acceptable. This preserves JSON values,
131
+ not the original response whitespace or numeric token spelling.
132
+
133
+ A fulfilled SDK promise alone does not establish HTTP success. Each renewal
134
+ response must have actual successful transport status metadata. Fetch exposes
135
+ `lastResponse.status`; Node exposes `lastResponse.statusCode`. Missing, malformed,
136
+ contradictory or non-2xx metadata rejects the read. This nonenumerable transport
137
+ metadata stays outside the canonical provider body. Provider errors stay visible,
138
+ and these read checks do not acknowledge a schedule mutation.
139
+
140
+ The shared single-attempt client rejects fetch redirects as well as Stripe's
141
+ closed-connection retry exception. A 307 or 308 cannot silently replay a POST.
142
+ The ordinary client route keeps its existing transport behavior. Rejected
143
+ redirects and broken connections can leave a remote outcome unknown; callers
144
+ must retain the original request identity rather than rotate or resend
145
+ automatically. These transport safeguards do not qualify a renewal provider
146
+ profile or authorize attachment, configuration or entitlement changes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.83.0",
3
+ "version": "0.83.1",
4
4
  "description": "Convex component for Stripe Accounts v2, subscriptions, metered billing and Connect marketplaces, with React workflows.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -28,7 +28,7 @@ function controlled(value: unknown) {
28
28
  "stripe-version": apiVersion,
29
29
  }),
30
30
  toJSON: async () => structuredClone(value),
31
- getRawResponse: () => ({}),
31
+ getRawResponse: () => ({ statusCode: 200 }),
32
32
  toStream: () => null,
33
33
  } as unknown as Stripe.HttpClientResponse;
34
34
  },
@@ -42,7 +42,6 @@ function controlled(value: unknown) {
42
42
  source as Record<string, unknown>,
43
43
  item as Record<string, unknown>,
44
44
  false,
45
- { apiVersion, maxNetworkRetries: 0 },
46
45
  ),
47
46
  };
48
47
  }
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import type Stripe from "stripe";
3
3
  import { equal, object, unsupported } from "../renewalAggregate/shared.js";
4
- import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
4
+ import { readRenewalWireJSON } from "./wireJson.js";
5
5
 
6
6
  const id = z.string().min(1).max(255).regex(/\S/);
7
7
  const discount = z
@@ -32,7 +32,6 @@ export async function joinRenewalCoupons(
32
32
  subscription: Record<string, unknown>,
33
33
  item: Record<string, unknown>,
34
34
  livemode: boolean,
35
- options: Stripe.RequestOptions,
36
35
  ) {
37
36
  const lists = [subscription.discounts, item.discounts].map((value) => {
38
37
  const parsed = z.array(discount).max(20).safeParse(value);
@@ -59,9 +58,7 @@ export async function joinRenewalCoupons(
59
58
  : redemption.source.coupon.id;
60
59
  let coupon = coupons.get(couponId);
61
60
  if (!coupon) {
62
- coupon = object(
63
- renewalSnapshot(await stripe.coupons.retrieve(couponId, {}, options)),
64
- );
61
+ coupon = object(await readRenewalWireJSON(stripe, "coupon", couponId));
65
62
  if (
66
63
  coupon.id !== couponId ||
67
64
  coupon.object !== "coupon" ||
@@ -71,7 +71,7 @@ function harness(
71
71
  "stripe-version": API_VERSION,
72
72
  }),
73
73
  toJSON: async () => structuredClone(data),
74
- getRawResponse: () => ({}),
74
+ getRawResponse: () => ({ statusCode: 200 }),
75
75
  toStream: () => {
76
76
  throw Error("not used");
77
77
  },
@@ -16,6 +16,7 @@ import {
16
16
  timestamp,
17
17
  } from "../renewalAggregate/shared.js";
18
18
  import { joinRenewalCoupons } from "./couponJoins.js";
19
+ import { readRenewalWireJSON } from "./wireJson.js";
19
20
 
20
21
  const input = z.object({ expected: renewalExpected }).strict();
21
22
  export type ReadRenewalPriceReplacementContextOptions = z.infer<typeof input>;
@@ -42,16 +43,12 @@ export async function readRenewalPriceReplacementContext(
42
43
  const args = input.parse(renewalSnapshot(options));
43
44
  supportedVersion(apiVersion);
44
45
  const expected = args.expected;
45
- const requestOptions = {
46
- apiVersion: "2026-09-30.endive" as const,
47
- maxNetworkRetries: 0,
48
- };
49
46
  const subscription = readSubscription.parse(
50
47
  renewalSnapshot(
51
- await stripe.subscriptions.retrieve(
48
+ await readRenewalWireJSON(
49
+ stripe,
50
+ "subscription",
52
51
  expected.subscriptionId,
53
- { expand: ["discounts", "items.data.discounts", "items.data.price"] },
54
- requestOptions,
55
52
  ),
56
53
  ),
57
54
  );
@@ -75,7 +72,7 @@ export async function readRenewalPriceReplacementContext(
75
72
  unsupported("original_read_identity_mismatch");
76
73
  const targetPrice = renewalPrice.parse(
77
74
  renewalSnapshot(
78
- await stripe.prices.retrieve(expected.targetPriceId, {}, requestOptions),
75
+ await readRenewalWireJSON(stripe, "price", expected.targetPriceId),
79
76
  ),
80
77
  );
81
78
  if (
@@ -91,9 +88,7 @@ export async function readRenewalPriceReplacementContext(
91
88
  context,
92
89
  );
93
90
  const billingCustomer = renewalBillingCustomer.parse(
94
- renewalSnapshot(
95
- await stripe.customers.retrieve(customerId, {}, requestOptions),
96
- ),
91
+ renewalSnapshot(await readRenewalWireJSON(stripe, "customer", customerId)),
97
92
  );
98
93
  if (
99
94
  billingCustomer.id !== customerId ||
@@ -106,7 +101,6 @@ export async function readRenewalPriceReplacementContext(
106
101
  subscription,
107
102
  item,
108
103
  expected.livemode,
109
- requestOptions,
110
104
  );
111
105
  const normalizedSubscription = {
112
106
  ...subscription,
@@ -0,0 +1,265 @@
1
+ import { it, expect } from "vitest";
2
+ import Stripe from "stripe";
3
+ import { SingleAttemptHttpClient } from "../../singleAttemptHttpClient.js";
4
+ import {
5
+ fixture,
6
+ API_VERSION,
7
+ } from "../../../../tests/renewalAggregate/fixtures.js";
8
+ import { readRenewalPriceReplacementContext } from "./reader.js";
9
+ import { readRenewalWireJSON } from "./wireJson.js";
10
+ export function wireHarness(status = 200, withDecimals = true) {
11
+ const f = fixture();
12
+ const sub = JSON.parse(JSON.stringify(f.subscription));
13
+ const p = {
14
+ ...sub.items.data[0].price,
15
+ unit_amount: 1000,
16
+ unit_amount_decimal: withDecimals ? "1000.00" : null,
17
+ created: 1,
18
+ metadata: { keep: "wire" },
19
+ nickname: null,
20
+ tiers_mode: null,
21
+ transform_quantity: null,
22
+ };
23
+ sub.items.data[0].price = p;
24
+ sub.items.data[0].plan = {
25
+ id: p.id,
26
+ object: "plan",
27
+ active: p.active,
28
+ amount: 1000,
29
+ amount_decimal: withDecimals ? "1000.00" : null,
30
+ billing_scheme: p.billing_scheme,
31
+ created: 1,
32
+ currency: p.currency,
33
+ interval: p.recurring.interval,
34
+ interval_count: p.recurring.interval_count,
35
+ livemode: p.livemode,
36
+ metadata: { keep: "wire" },
37
+ meter: null,
38
+ nickname: null,
39
+ product: p.product,
40
+ tiers_mode: null,
41
+ transform_usage: null,
42
+ trial_period_days: null,
43
+ usage_type: "licensed",
44
+ };
45
+ sub.opaque = { facts: ["keep", "all"] };
46
+ const target = {
47
+ ...f.targetPrice,
48
+ unit_amount_decimal: withDecimals ? "2000.00" : null,
49
+ opaque: { keep: "yes" },
50
+ };
51
+ const calls: {
52
+ path: string;
53
+ method: string;
54
+ version: string | null;
55
+ connected: string | null;
56
+ body: string;
57
+ }[] = [];
58
+ const coupons = new Map(
59
+ [...f.subscription.discounts, ...f.originalItem.discounts].map((d) => [
60
+ d.source.coupon.id,
61
+ d.source.coupon,
62
+ ]),
63
+ );
64
+ const stripe = new Stripe("sk_test_ONLY_CONTROLLED_WIRE", {
65
+ apiVersion: API_VERSION,
66
+ maxNetworkRetries: 0,
67
+ httpClient: new SingleAttemptHttpClient(
68
+ Stripe.createFetchHttpClient(async (url, init) => {
69
+ const u = new URL(String(url)),
70
+ headers = new Headers(init?.headers);
71
+ calls.push({
72
+ path: u.pathname + u.search,
73
+ method: String(init?.method),
74
+ version: headers.get("stripe-version"),
75
+ connected: headers.get("stripe-account"),
76
+ body: String(init?.body ?? ""),
77
+ });
78
+ const body = u.pathname.startsWith("/v1/subscriptions/")
79
+ ? sub
80
+ : u.pathname.startsWith("/v1/prices/")
81
+ ? target
82
+ : u.pathname.startsWith("/v1/customers/")
83
+ ? f.billingCustomer
84
+ : coupons.get(decodeURIComponent(u.pathname.slice(12)));
85
+ return new Response(JSON.stringify(body), {
86
+ status,
87
+ headers: {
88
+ "content-type": "application/json",
89
+ "request-id": "req_controlledwire",
90
+ "stripe-version": API_VERSION,
91
+ },
92
+ });
93
+ }),
94
+ ),
95
+ });
96
+ return {
97
+ f,
98
+ sub,
99
+ target,
100
+ calls,
101
+ stripe,
102
+ read: () =>
103
+ readRenewalPriceReplacementContext(
104
+ stripe,
105
+ { expected: f.prepared.expected },
106
+ API_VERSION,
107
+ ),
108
+ };
109
+ }
110
+ it("reader preserves actualSDK nativePlan/Price decimal stringlexemes and every opaqueJSONfact", async () => {
111
+ const h = wireHarness();
112
+ const r = await h.read();
113
+ expect(
114
+ (
115
+ (r.subscription.items.data[0] as Record<string, unknown>).plan as {
116
+ amount_decimal: string;
117
+ }
118
+ ).amount_decimal,
119
+ ).toBe("1000.00");
120
+ expect(r.subscription.items.data[0].price.unit_amount_decimal).toBe(
121
+ "1000.00",
122
+ );
123
+ expect(r.subscription).toEqual(h.sub);
124
+ expect(r.targetPrice).toEqual(h.target);
125
+ expect(h.calls).toHaveLength(5);
126
+ expect(
127
+ h.calls.every(
128
+ (c) =>
129
+ c.method === "GET" &&
130
+ c.version === API_VERSION &&
131
+ c.connected === null &&
132
+ c.body === "",
133
+ ),
134
+ ).toBe(true);
135
+ const first = new URL(h.calls[0].path, "https://api.stripe.com");
136
+ expect([...first.searchParams]).toEqual([
137
+ ["expand[0]", "discounts"],
138
+ ["expand[1]", "items.data.discounts"],
139
+ ["expand[2]", "items.data.price"],
140
+ ]);
141
+ });
142
+ it.each([201, 204, 299])(
143
+ "admitsvalid2xx JSON or failsclosed onbodyless%s",
144
+ async (status) => {
145
+ // 201/299 are valid2xx. The fixedbody stillneeds schema; unlike204 they preserveJSON.
146
+ const h = wireHarness(status);
147
+ if (status === 204) await expect(h.read()).rejects.toBeDefined();
148
+ else expect((await h.read()).subscription.id).toBe("sub_original");
149
+ },
150
+ );
151
+ it.each([307, 308, 400, 500])(
152
+ "rejects fulfillednon2xx JSONstatus%s before acquiring otherresources",
153
+ async (status) => {
154
+ const h = wireHarness(status, false);
155
+ await expect(h.read()).rejects.toBeDefined();
156
+ expect(h.calls).toHaveLength(1);
157
+ },
158
+ );
159
+
160
+ it.each([
161
+ {},
162
+ { status: "200" },
163
+ { statusCode: "200" },
164
+ { status: 200, statusCode: 201 },
165
+ { status: 200, statusCode: 500 },
166
+ { status: NaN },
167
+ ])("rejects missing/invalid/contradictory statusmetadata %j", async (meta) => {
168
+ const f = fixture();
169
+ const stripe = new Stripe("sk_test_CONTROLLED_META", {
170
+ apiVersion: API_VERSION,
171
+ maxNetworkRetries: 0,
172
+ httpClient: {
173
+ getClientName: () => "controlledmeta",
174
+ makeRequest: async () => ({
175
+ getStatusCode: () => 200,
176
+ getHeaders: () => ({ "request-id": "req_meta" }),
177
+ getRawResponse: () => meta,
178
+ toJSON: async () => JSON.parse(JSON.stringify(f.billingCustomer)),
179
+ toStream: () => {
180
+ throw Error("unused");
181
+ },
182
+ }),
183
+ },
184
+ });
185
+ await expect(
186
+ readRenewalWireJSON(stripe, "customer", "cus_buyer"),
187
+ ).rejects.toMatchObject({
188
+ message: expect.stringContaining("provider_http_status"),
189
+ });
190
+ });
191
+ it.each([
192
+ { status: 200 },
193
+ { statusCode: 200 },
194
+ { status: 200, statusCode: 200 },
195
+ ])("admits supported successfultransportmetadata %j", async (meta) => {
196
+ const f = fixture();
197
+ const stripe = new Stripe("sk_test_CONTROLLED_META_VALID", {
198
+ apiVersion: API_VERSION,
199
+ maxNetworkRetries: 0,
200
+ httpClient: {
201
+ getClientName: () => "controlledmeta",
202
+ makeRequest: async () => ({
203
+ getStatusCode: () => 200,
204
+ getHeaders: () => ({ "request-id": "req_meta" }),
205
+ getRawResponse: () => meta,
206
+ toJSON: async () => JSON.parse(JSON.stringify(f.billingCustomer)),
207
+ toStream: () => {
208
+ throw Error("unused");
209
+ },
210
+ }),
211
+ },
212
+ });
213
+ expect(await readRenewalWireJSON(stripe, "customer", "cus_buyer")).toEqual(
214
+ f.billingCustomer,
215
+ );
216
+ });
217
+ it("encodes arbitrary supported customcoupon IDs into one fixedpath segment", async () => {
218
+ const paths: string[] = [];
219
+ const stripe = new Stripe("sk_test_CONTROLLED_ENCODE", {
220
+ apiVersion: API_VERSION,
221
+ maxNetworkRetries: 0,
222
+ httpClient: {
223
+ getClientName: () => "controlledencoding",
224
+ makeRequest: async (...args) => {
225
+ paths.push(args[2]);
226
+ return {
227
+ getStatusCode: () => 200,
228
+ getHeaders: () => ({}),
229
+ getRawResponse: () => ({ statusCode: 200 }),
230
+ toJSON: async () => ({ id: "custom /?#%", object: "coupon" }),
231
+ toStream: () => {
232
+ throw Error("unused");
233
+ },
234
+ };
235
+ },
236
+ },
237
+ });
238
+ expect(await readRenewalWireJSON(stripe, "coupon", "custom /?#%")).toEqual({
239
+ id: "custom /?#%",
240
+ object: "coupon",
241
+ });
242
+ expect(paths).toEqual(["/v1/coupons/custom%20%2F%3F%23%25"]);
243
+ });
244
+
245
+ it.each([".", ".."])(
246
+ "rejects dot-only coupon selector %s before actualSDK issues anyrequest",
247
+ async (id) => {
248
+ let requests = 0;
249
+ const stripe = new Stripe("sk_test_CONTROLLED_DOT_SEGMENT", {
250
+ apiVersion: API_VERSION,
251
+ maxNetworkRetries: 0,
252
+ httpClient: Stripe.createFetchHttpClient(async () => {
253
+ requests++;
254
+ return new Response(JSON.stringify({ id, object: "coupon" }), {
255
+ status: 200,
256
+ headers: { "content-type": "application/json" },
257
+ });
258
+ }),
259
+ });
260
+ await expect(
261
+ readRenewalWireJSON(stripe, "coupon", id),
262
+ ).rejects.toBeDefined();
263
+ expect(requests).toBe(0);
264
+ },
265
+ );
@@ -0,0 +1,75 @@
1
+ import { z } from "zod";
2
+ import type Stripe from "stripe";
3
+ import { renewalSnapshot } from "../renewalReplacementSnapshot.js";
4
+ import { resourceId, unsupported } from "../renewalAggregate/shared.js";
5
+
6
+ const resources = {
7
+ subscription: { path: "subscriptions", id: resourceId("sub") },
8
+ price: { path: "prices", id: resourceId("price") },
9
+ customer: { path: "customers", id: resourceId("cus") },
10
+ coupon: {
11
+ path: "coupons",
12
+ id: z
13
+ .string()
14
+ .min(1)
15
+ .max(255)
16
+ .regex(/\S/)
17
+ .refine(
18
+ (value) => value !== "." && value !== "..",
19
+ "Coupon ID must not be a URL dot segment.",
20
+ ),
21
+ },
22
+ } as const;
23
+ const expansions = ["discounts", "items.data.discounts", "items.data.price"];
24
+
25
+ /** Fixed renewal GETs only. rawRequest bypasses typed resource Decimal coercion. */
26
+ export async function readRenewalWireJSON(
27
+ stripe: Stripe,
28
+ resource: keyof typeof resources,
29
+ id: string,
30
+ ) {
31
+ const spec = resources[resource];
32
+ const selectedId = spec.id.parse(id);
33
+ const query =
34
+ resource === "subscription"
35
+ ? `?${new URLSearchParams(expansions.map((value, i) => [`expand[${i}]`, value]))}`
36
+ : "";
37
+ const reply: unknown = await stripe.rawRequest(
38
+ "GET",
39
+ `/v1/${spec.path}/${encodeURIComponent(selectedId)}${query}`,
40
+ undefined,
41
+ { apiVersion: "2026-09-30.endive", maxNetworkRetries: 0 },
42
+ );
43
+ if (!reply || typeof reply !== "object")
44
+ unsupported("missing_provider_http_status");
45
+ const descriptor = Object.getOwnPropertyDescriptor(reply, "lastResponse");
46
+ if (
47
+ !descriptor ||
48
+ descriptor.enumerable ||
49
+ !("value" in descriptor) ||
50
+ !descriptor.value ||
51
+ typeof descriptor.value !== "object"
52
+ )
53
+ unsupported("missing_provider_http_status");
54
+ // Fetch's public Response uses status; Node IncomingMessage uses statusCode.
55
+ // Neither is provider JSON. If both are present they must agree.
56
+ const meta = descriptor.value as { status?: unknown; statusCode?: unknown };
57
+ const codes = [meta.status, meta.statusCode].filter(
58
+ (code) => code !== undefined,
59
+ );
60
+ if (
61
+ !codes.length ||
62
+ codes.some(
63
+ (code) =>
64
+ typeof code !== "number" ||
65
+ !Number.isInteger(code) ||
66
+ code < 200 ||
67
+ code >= 300,
68
+ ) ||
69
+ codes.some((code) => code !== codes[0])
70
+ )
71
+ unsupported("unverified_provider_http_status");
72
+ // Strict JSON copy remains unchanged. Nonenumerable transport metadata is
73
+ // excluded; every enumerable wire-body fact, including unknown fields, remains.
74
+ return renewalSnapshot(reply);
75
+ }
@@ -4,7 +4,7 @@ import type {
4
4
  OptionalRestArgs,
5
5
  } from "convex/server";
6
6
  import Stripe from "stripe";
7
- import { SingleAttemptHttpClient } from "./singleAttemptHttpClient.js";
7
+ import { createSingleAttemptHttpClient } from "./strictStripeTransport.js";
8
8
 
9
9
  import type { ComponentApi } from "../component/_generated/component.js";
10
10
  import { STRIPE_API_VERSION } from "./constants.js";
@@ -58,9 +58,7 @@ export function getStripeClient(
58
58
  ...(policy?.singleAttempt
59
59
  ? {
60
60
  maxNetworkRetries: 0,
61
- httpClient: new SingleAttemptHttpClient(
62
- Stripe.createFetchHttpClient(),
63
- ),
61
+ httpClient: createSingleAttemptHttpClient(),
64
62
  }
65
63
  : {}),
66
64
  });