@fantastic.dev/better-stripe 0.101.0 → 0.103.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 (55) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/renewalAttach/internal/c10/appendAck.d.ts +7 -0
  4. package/dist/client/billing/renewalAttach/internal/c10/appendAck.d.ts.map +1 -1
  5. package/dist/client/billing/renewalAttach/internal/c10/appendAck.js +13 -1
  6. package/dist/client/billing/renewalAttach/internal/c10/appendAck.js.map +1 -1
  7. package/dist/client/billing/renewalAttach/internal/c10/configureEvents.d.ts +23 -0
  8. package/dist/client/billing/renewalAttach/internal/c10/configureEvents.d.ts.map +1 -1
  9. package/dist/client/billing/renewalAttach/internal/c10/configureEvents.js +34 -2
  10. package/dist/client/billing/renewalAttach/internal/c10/configureEvents.js.map +1 -1
  11. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts +2 -0
  12. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.d.ts.map +1 -1
  13. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js +16 -0
  14. package/dist/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.js.map +1 -1
  15. package/dist/client/billing/renewalAttach/internal/producer/configureAdmission.d.ts +7 -0
  16. package/dist/client/billing/renewalAttach/internal/producer/configureAdmission.d.ts.map +1 -0
  17. package/dist/client/billing/renewalAttach/internal/producer/configureAdmission.js +117 -0
  18. package/dist/client/billing/renewalAttach/internal/producer/configureAdmission.js.map +1 -0
  19. package/dist/client/billing/renewalAttach/internal/producer/configureJournalData.d.ts +53 -0
  20. package/dist/client/billing/renewalAttach/internal/producer/configureJournalData.d.ts.map +1 -0
  21. package/dist/client/billing/renewalAttach/internal/producer/configureJournalData.js +198 -0
  22. package/dist/client/billing/renewalAttach/internal/producer/configureJournalData.js.map +1 -0
  23. package/dist/client/billing/renewalAttach/internal/producer/configureJournalWork.d.ts +6 -0
  24. package/dist/client/billing/renewalAttach/internal/producer/configureJournalWork.d.ts.map +1 -0
  25. package/dist/client/billing/renewalAttach/internal/producer/configureJournalWork.js +49 -0
  26. package/dist/client/billing/renewalAttach/internal/producer/configureJournalWork.js.map +1 -0
  27. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.d.ts +959 -0
  28. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.d.ts.map +1 -0
  29. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.js +115 -0
  30. package/dist/client/billing/renewalAttach/internal/producer/configureLineage.js.map +1 -0
  31. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts +2 -0
  32. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.d.ts.map +1 -1
  33. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js +4 -0
  34. package/dist/client/billing/renewalAttach/internal/producer/invocationProducer.js.map +1 -1
  35. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts +1 -0
  36. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.d.ts.map +1 -1
  37. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js +1 -0
  38. package/dist/client/billing/renewalAttach/internal/producer/lineageAuthority.js.map +1 -1
  39. package/docs/renewal-context-reads.md +81 -3
  40. package/package.json +1 -1
  41. package/src/client/billing/renewalAttach/internal/c10/appendAck.ts +17 -0
  42. package/src/client/billing/renewalAttach/internal/c10/configureEvents.ts +45 -2
  43. package/src/client/billing/renewalAttach/internal/producer/classOwnedActionRoot.ts +21 -0
  44. package/src/client/billing/renewalAttach/internal/producer/configureAdmission.ts +179 -0
  45. package/src/client/billing/renewalAttach/internal/producer/configureJournalData.ts +248 -0
  46. package/src/client/billing/renewalAttach/internal/producer/configureJournalWork.ts +53 -0
  47. package/src/client/billing/renewalAttach/internal/producer/configureLineage.ts +166 -0
  48. package/src/client/billing/renewalAttach/internal/producer/invocationProducer.ts +13 -0
  49. package/src/client/billing/renewalAttach/internal/producer/lineageAuthority.ts +2 -0
  50. package/src/client/billing/renewalAttach/internal/producer/producerConfigureAdmission.integration.test.ts +203 -0
  51. package/src/client/billing/renewalAttach/internal/producer/producerConfigureChannelControls.integration.test.ts +542 -0
  52. package/src/client/billing/renewalAttach/internal/producer/producerConfigureChannels.integration.test.ts +321 -0
  53. package/src/client/billing/renewalAttach/internal/producer/producerConfigureControls.integration.test.ts +566 -0
  54. package/src/client/billing/renewalAttach/internal/test-fixtures/producerConfigureAdmission.ts +353 -0
  55. package/src/client/billing/renewalAttach/internal/test-fixtures/producerInitialOperation.ts +61 -3
@@ -0,0 +1,353 @@
1
+ import assert from "node:assert/strict";
2
+ import { afterEach, beforeEach, vi } from "vitest";
3
+ import { initialOperations } from "./producerInitialOperation.js";
4
+ import { makeConfigureReadNativeBaseline } from "./configureReadNativeBaseline.js";
5
+ import { captureRetainedInput } from "../material/capture.js";
6
+ import { captureInitialInvocationCore } from "../producer/invocationProducer.js";
7
+ import { createClassActionOperationJournal } from "../operationJournal.js";
8
+ import { components } from "../../../../../../example/convex/_generated/api.js";
9
+ import { BetterStripe } from "../../../../index.js";
10
+ import { renewalSnapshot } from "../../../renewalReplacementSnapshot.js";
11
+ import {
12
+ prepareRenewalPriceReplacementV2,
13
+ prepareRenewalScheduleAttachmentV2,
14
+ projectRenewalConfigurationV2,
15
+ constructRenewalConfigurationReceiptV2,
16
+ } from "../../../renewalV2/index.js";
17
+ import { INITIAL_NS } from "./producerInitialDeclarations.js";
18
+
19
+ const controls = vi.hoisted(() => ({
20
+ entries: [{ coversRetained: () => true, coversFresh: () => true }],
21
+ recovery: [] as { originalEntry: unknown; coversReplay(): boolean }[],
22
+ legacy: 0,
23
+ selectors: 0,
24
+ }));
25
+ vi.mock("../operations/sourceOperations.js", () => {
26
+ const poison = () => {
27
+ controls.legacy++;
28
+ throw Error("LEGACY_SOURCE_POISON");
29
+ };
30
+ return {
31
+ COMPILED_INITIAL_ENTRIES: controls.entries,
32
+ COMPILED_RECOVERY_ENTRIES: controls.recovery,
33
+ ORIGINAL_ORIGIN_ASSOCIATION: null,
34
+ loadFixedInitialOperation: poison,
35
+ loadFixedExplicitRecoveryOperation: poison,
36
+ loadOwnedTransportSource: poison,
37
+ loadInitialOwnedTransportSource: poison,
38
+ loadRecoveryOwnedTransportSource: poison,
39
+ };
40
+ });
41
+ vi.mock("../originalOwner.js", () => {
42
+ const poison = () => {
43
+ controls.legacy++;
44
+ throw Error("LEGACY_OWNER_POISON");
45
+ };
46
+ return {
47
+ OWNER: Object.freeze({
48
+ get basis() {
49
+ return poison();
50
+ },
51
+ check: poison,
52
+ sample: poison,
53
+ subscribe: poison,
54
+ retire: poison,
55
+ }),
56
+ };
57
+ });
58
+ vi.mock("../../../../helpers.js", async (original) => {
59
+ const actual = await original<typeof import("../../../../helpers.js")>();
60
+ return {
61
+ ...actual,
62
+ getStripeClient(...args: Parameters<typeof actual.getStripeClient>) {
63
+ controls.selectors++;
64
+ return actual.getStripeClient(...args);
65
+ },
66
+ };
67
+ });
68
+ export const admissionControls = controls;
69
+ const canonical = (value: unknown) => JSON.stringify(renewalSnapshot(value));
70
+ beforeEach(() => {
71
+ controls.legacy = 0;
72
+ controls.selectors = 0;
73
+ controls.entries.splice(0, controls.entries.length, {
74
+ coversRetained: () => true,
75
+ coversFresh: () => true,
76
+ });
77
+ controls.recovery.splice(0, controls.recovery.length, {
78
+ originalEntry: controls.entries[0],
79
+ coversReplay: () => true,
80
+ });
81
+ vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
82
+ vi.setSystemTime(
83
+ (makeConfigureReadNativeBaseline().clockPlan.attachSeconds + 1) * 1000,
84
+ );
85
+ vi.spyOn(process.hrtime, "bigint").mockReturnValue(INITIAL_NS);
86
+ });
87
+ afterEach(() => {
88
+ vi.useRealTimers();
89
+ vi.unstubAllGlobals();
90
+ vi.restoreAllMocks();
91
+ });
92
+
93
+ async function setup(
94
+ input: Parameters<Parameters<typeof initialOperations>[0]>[0],
95
+ completion: { mode: string; posts: number },
96
+ ) {
97
+ const { journal, fresh, sdk, ctx, index } = input;
98
+ assert(fresh.result.disposition === "acquired" && fresh.call);
99
+ const parentReservation = fresh.result.reservation;
100
+ const baseline = makeConfigureReadNativeBaseline();
101
+ const source = captureRetainedInput(baseline.original);
102
+ const calls: { method: string; path: string }[] = [];
103
+ const routes = new Map<string, unknown>([
104
+ ["/v1/subscriptions/sub_original", source.originalBundle.wireSubscription],
105
+ ["/v1/prices/price_target", source.originalBundle.wireTargetPrice],
106
+ ["/v1/customers/cus_buyer", source.originalBundle.wireBillingCustomer],
107
+ ...source.originalBundle.couponReads.map((row): [string, unknown] => [
108
+ "/v1/coupons/" + encodeURIComponent(String(row.couponId)),
109
+ row.wireCoupon,
110
+ ]),
111
+ ]);
112
+ vi.stubGlobal("fetch", async (url: RequestInfo | URL, init?: RequestInit) => {
113
+ const path = new URL(String(url)).pathname;
114
+ const method = init?.method ?? "";
115
+ calls.push({ method, path });
116
+ if (method === "POST") {
117
+ completion.posts++;
118
+ if (completion.mode === "replay" && completion.posts === 1)
119
+ throw Error("CONTROLLED_LOST_RESPONSE");
120
+ }
121
+ const body = method === "POST" ? baseline.schedule : routes.get(path);
122
+ assert(body);
123
+ assert(
124
+ method === "GET" ||
125
+ (method === "POST" && path === "/v1/subscription_schedules"),
126
+ );
127
+ return new Response(JSON.stringify(body), {
128
+ status: 200,
129
+ headers: {
130
+ "content-type": "application/json",
131
+ "request-id": "req_synthetic_admission",
132
+ },
133
+ });
134
+ });
135
+ const core = await captureInitialInvocationCore(fresh.call, journal);
136
+ let childOrdinal = 0;
137
+ async function child(
138
+ options: {
139
+ sdk?: BetterStripe;
140
+ stage?: "attach" | "configure";
141
+ ctx?: typeof ctx;
142
+ change?: (record: Record<string, unknown>) => void;
143
+ } = {},
144
+ ) {
145
+ const ordinal = ++childOrdinal;
146
+ const loaded = await journal.loadAuthorizedOperation();
147
+ assert(loaded);
148
+ const parent = JSON.parse(loaded.recordJSON);
149
+ const prepared = await prepareRenewalPriceReplacementV2(
150
+ source.attachRequest.preparation,
151
+ );
152
+ const attach = await prepareRenewalScheduleAttachmentV2({
153
+ prepared,
154
+ apiVersion: source.attachRequest.apiVersion,
155
+ attachKey: source.attachRequest.attachKey,
156
+ firstDispatchedAt: source.attachRequest.firstDispatchedAt,
157
+ });
158
+ const configuration = {
159
+ preparation: source.attachRequest.preparation,
160
+ attachReceipt: {
161
+ attachRequest: source.attachRequest,
162
+ actualDispatch: {
163
+ scope: attach.scope,
164
+ apiVersion: attach.apiVersion,
165
+ method: attach.method,
166
+ path: attach.path,
167
+ payload: attach.payload,
168
+ key: attach.key,
169
+ firstDispatchedAt: attach.firstDispatchedAt,
170
+ },
171
+ providerSnapshot: baseline.schedule,
172
+ },
173
+ freshSubscription: {
174
+ ...source.attachRequest.preparation.subscription,
175
+ schedule: baseline.schedule.id,
176
+ },
177
+ targetPrice: source.attachRequest.preparation.targetPrice,
178
+ billingCustomer: source.attachRequest.preparation.billingCustomer,
179
+ schedule: baseline.schedule,
180
+ apiVersion: source.attachRequest.apiVersion,
181
+ observedAt: baseline.configurationTime,
182
+ firstDispatchedAt: baseline.configurationTime,
183
+ configureKey: "configure:admission:root" + index + ":" + ordinal,
184
+ };
185
+ const request = await projectRenewalConfigurationV2(configuration);
186
+ assert("requestIdentity" in request);
187
+ const { scope, apiVersion, method, path, payload, key, firstDispatchedAt } =
188
+ request;
189
+ const known = await journal.readProviderAcknowledgement();
190
+ assert(known);
191
+ const record = {
192
+ schemaVersion: 2,
193
+ authorization: {
194
+ scope: "configure-child-host",
195
+ id: "configure-consent-root" + index + "-" + ordinal,
196
+ revision: 1,
197
+ },
198
+ logicalOperationId: "configure-child-root" + index + "-" + ordinal,
199
+ stage: "configure",
200
+ account: parent.account,
201
+ apiVersion,
202
+ requestBinding: request.requestIdentity.binding,
203
+ dispatch: {
204
+ scope,
205
+ apiVersion,
206
+ method,
207
+ path,
208
+ payload,
209
+ key,
210
+ firstDispatchedAt,
211
+ },
212
+ parentAttachment: {
213
+ operationId: parentReservation.operationId,
214
+ attemptId: parentReservation.attemptId,
215
+ sourcePayloadId: parentReservation.payloadId,
216
+ receiptBinding: known.retention.receiptBinding,
217
+ },
218
+ configureRecord: {
219
+ configuration,
220
+ request,
221
+ attachReceipt: JSON.parse(known.receiptJSON),
222
+ originalBundle: source.originalBundle,
223
+ },
224
+ timingPolicy: { ...parent.timingPolicy, firstDispatchedAt },
225
+ };
226
+ options.change?.(record);
227
+ const recordJSON = canonical(record);
228
+ const selectedCtx = options.ctx ?? ctx;
229
+ const refs = components.betterStripe.renewalOperations;
230
+ const created = await selectedCtx.runMutation(
231
+ refs.mutations.createAuthorizedOperation,
232
+ {
233
+ authorizationScope: record.authorization.scope,
234
+ authorizationRevision: 1,
235
+ logicalOperationId: record.logicalOperationId,
236
+ recordJSON,
237
+ },
238
+ );
239
+ assert(created.status === "created");
240
+ const childJournal = await createClassActionOperationJournal(
241
+ options.sdk ?? sdk,
242
+ { actualActionCtx: selectedCtx, operationId: created.operationId },
243
+ );
244
+ const reserveArgs = {
245
+ expectedRevision: 0,
246
+ stage: options.stage ?? "configure",
247
+ expectedRequestBinding: record.requestBinding,
248
+ recordJSON,
249
+ };
250
+ const childFresh = await childJournal.reserveFreshAttempt(reserveArgs);
251
+ assert(childFresh.result.disposition === "acquired" && childFresh.call);
252
+ return {
253
+ journal: childJournal,
254
+ fresh: childFresh,
255
+ record,
256
+ reserveArgs,
257
+ created,
258
+ };
259
+ }
260
+ async function complete(mode: "initial" | "replay" | "resume" = "initial") {
261
+ completion.mode = mode;
262
+ if (mode === "initial") return core.initialAttach().invoke();
263
+ try {
264
+ await core.initialAttach().invoke();
265
+ } catch (error) {
266
+ if (mode !== "replay") throw error;
267
+ }
268
+ return core.recoverAttach().invoke();
269
+ }
270
+ async function eventsFor(value: Awaited<ReturnType<typeof child>>) {
271
+ const request = value.record.configureRecord.request;
272
+ const transport = {
273
+ status: 200,
274
+ requestId: "req_synthetic_configure_channel",
275
+ };
276
+ const receipt = await constructRenewalConfigurationReceiptV2({
277
+ configuration: value.record.configureRecord.configuration,
278
+ actualDispatch: value.record.dispatch,
279
+ providerSnapshot: baseline.schedule,
280
+ transport,
281
+ });
282
+ return {
283
+ dispatch: { event: "dispatch", stage: "configure", request },
284
+ response: {
285
+ event: "response",
286
+ stage: "configure",
287
+ request,
288
+ body: baseline.schedule,
289
+ transport,
290
+ },
291
+ receiptEvent: { event: "receipt", stage: "configure", request, receipt },
292
+ receipt,
293
+ };
294
+ }
295
+ return {
296
+ ...input,
297
+ core,
298
+ child,
299
+ calls,
300
+ baseline,
301
+ source,
302
+ complete,
303
+ eventsFor,
304
+ };
305
+ }
306
+ export async function configureAdmissionFixture(
307
+ work: (h: Awaited<ReturnType<typeof setup>>) => Promise<void>,
308
+ options: {
309
+ count?: number;
310
+ keys?: readonly string[];
311
+ afterBind?: (reply: unknown) => Promise<void>;
312
+ afterQuery?: (
313
+ reply: unknown,
314
+ reference: string,
315
+ args: unknown,
316
+ ) => Promise<void>;
317
+ afterAppend?: () => Promise<void>;
318
+ beforeAppend?: () => Promise<void>;
319
+ } = {},
320
+ ) {
321
+ const baseline = makeConfigureReadNativeBaseline();
322
+ const completion = { mode: "initial", posts: 0, appends: 0 };
323
+ await initialOperations(
324
+ async (input) => {
325
+ const h = await setup(input, completion);
326
+ try {
327
+ await work(h);
328
+ } finally {
329
+ h.core.owner.retire();
330
+ }
331
+ },
332
+ options.count ?? 1,
333
+ {
334
+ keys: options.keys,
335
+ source: captureRetainedInput(baseline.original),
336
+ afterBind: options.afterBind,
337
+ afterQuery: options.afterQuery,
338
+ beforeAppend: options.beforeAppend,
339
+ afterAppend: async () => {
340
+ completion.appends++;
341
+ if (completion.mode === "resume" && completion.appends === 2)
342
+ throw Error("CONTROLLED_APPEND_REPLY_REJECTION");
343
+ await options.afterAppend?.();
344
+ },
345
+ workEndWallMs:
346
+ (baseline.clockPlan.attachSeconds + baseline.clockPlan.workSeconds) *
347
+ 1000,
348
+ endWallMs:
349
+ (baseline.clockPlan.attachSeconds + baseline.clockPlan.endSeconds) *
350
+ 1000,
351
+ },
352
+ );
353
+ }
@@ -1,10 +1,13 @@
1
1
  import assert from "node:assert/strict";
2
+ import { v } from "convex/values";
2
3
  import { convexTest } from "convex-test";
3
4
  import {
4
5
  actionGeneric,
5
6
  defineSchema,
6
7
  makeFunctionReference,
7
8
  getFunctionAddress,
9
+ type GenericActionCtx,
10
+ type GenericDataModel,
8
11
  } from "convex/server";
9
12
  import { BetterStripe } from "../../../../index.js";
10
13
  import { components } from "../../../../../../example/convex/_generated/api.js";
@@ -28,13 +31,22 @@ export async function initialOperations(
28
31
  fresh: Fresh;
29
32
  sdk: BetterStripe;
30
33
  index: number;
34
+ ctx: GenericActionCtx<GenericDataModel>;
35
+ inAnotherAction(
36
+ work: (ctx: GenericActionCtx<GenericDataModel>) => Promise<void>,
37
+ ): Promise<void>;
31
38
  }) => Promise<void>,
32
39
  count = 1,
33
40
  options: {
34
41
  epochMs?: number;
35
42
  workEndWallMs?: number;
36
43
  endWallMs?: number;
37
- afterBind?: () => Promise<void>;
44
+ afterBind?: (reply: unknown) => Promise<void>;
45
+ afterQuery?: (
46
+ reply: unknown,
47
+ reference: string,
48
+ args: unknown,
49
+ ) => Promise<void>;
38
50
  afterAppend?: () => Promise<void>;
39
51
  beforeAppend?: () => Promise<void>;
40
52
  afterRetain?: () => Promise<void>;
@@ -158,11 +170,37 @@ export async function initialOperations(
158
170
  new BetterStripe(components.betterStripe, { STRIPE_SECRET_KEY: key }),
159
171
  );
160
172
  const refs = components.betterStripe.renewalOperations;
173
+ const secondaryWork = new Map<
174
+ string,
175
+ (ctx: GenericActionCtx<GenericDataModel>) => Promise<void>
176
+ >();
177
+ let secondaryId = 0;
161
178
  const host = {
179
+ secondary: actionGeneric({
180
+ args: { id: v.string() },
181
+ handler: async (ctx, args): Promise<null> => {
182
+ const work = secondaryWork.get(args.id);
183
+ assert(work);
184
+ secondaryWork.delete(args.id);
185
+ await work(ctx);
186
+ return null;
187
+ },
188
+ }),
162
189
  run: actionGeneric({
163
190
  args: {},
164
191
  handler: async (ctx): Promise<null> => {
165
192
  const runMutation = ctx.runMutation;
193
+ const runQuery = ctx.runQuery;
194
+ if (options.afterQuery)
195
+ ctx.runQuery = async (ref, ...args) => {
196
+ const reply = await runQuery(ref, ...args);
197
+ await options.afterQuery?.(
198
+ reply,
199
+ getFunctionAddress(ref).reference ?? "",
200
+ args[0],
201
+ );
202
+ return reply;
203
+ };
166
204
  if (
167
205
  options.afterBind ||
168
206
  options.afterAppend ||
@@ -184,7 +222,7 @@ export async function initialOperations(
184
222
  ) &&
185
223
  options.afterBind
186
224
  )
187
- await options.afterBind();
225
+ await options.afterBind(result);
188
226
  if (
189
227
  getFunctionAddress(ref).reference?.endsWith(
190
228
  "/appendStageEvent",
@@ -232,7 +270,27 @@ export async function initialOperations(
232
270
  recordJSON,
233
271
  });
234
272
  assert(fresh.result.disposition === "acquired" && fresh.call);
235
- await work({ journal, fresh, sdk: selectedSDK, index });
273
+ await work({
274
+ journal,
275
+ fresh,
276
+ sdk: selectedSDK,
277
+ index,
278
+ ctx,
279
+ async inAnotherAction(work) {
280
+ const id = String(++secondaryId);
281
+ secondaryWork.set(id, work);
282
+ try {
283
+ await ctx.runAction(
284
+ makeFunctionReference<"action", { id: string }, null>(
285
+ "initialOwner:secondary",
286
+ ),
287
+ { id },
288
+ );
289
+ } finally {
290
+ secondaryWork.delete(id);
291
+ }
292
+ },
293
+ });
236
294
  }),
237
295
  );
238
296
  return null;