Skip to content

Commit f243f86

Browse files
fix(cli): billing cancels its in-flight plan, price and checkout reads once the wait ends
Paying on the page or the timeout aborts the pending requests, so no checkout is created or link printed after the command has seen payment, and the command ends without waiting for a held response.
1 parent 20eaced commit f243f86

3 files changed

Lines changed: 70 additions & 26 deletions

File tree

‎packages/cli/src/commands/billing.test.ts‎

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ const state = vi.hoisted(() => ({
1313
enterHeld: false,
1414
noPrice: false,
1515
proPrices: [] as number[],
16+
offerReads: 0,
17+
offersHeldFrom: Infinity,
1618
}));
1719

1820
vi.mock("../auth/browser.js", () => ({
@@ -33,20 +35,22 @@ vi.mock("../heygen/plan.js", async (importOriginal) => {
3335
return {
3436
...real,
3537
readPlan: async () => (state.plans.length ? state.plans.shift()! : state.afterPlans),
36-
readOffer: async () =>
37-
state.noPrice
38-
? {}
39-
: {
40-
pro: { amount: state.proPrices.shift() ?? 2500, currency: "usd" },
41-
addon: {
42-
unitsPerBlock: 1000,
43-
unitAmount: 100,
44-
currency: "usd",
45-
min: 1,
46-
max: 100,
47-
recommended: 25,
38+
readOffer: async (stop?: AbortSignal) =>
39+
state.offerReads++ >= state.offersHeldFrom
40+
? new Promise((resolve) => stop?.addEventListener("abort", () => resolve({})))
41+
: state.noPrice
42+
? {}
43+
: {
44+
pro: { amount: state.proPrices.shift() ?? 2500, currency: "usd" },
45+
addon: {
46+
unitsPerBlock: 1000,
47+
unitAmount: 100,
48+
currency: "usd",
49+
min: 1,
50+
max: 100,
51+
recommended: 25,
52+
},
4853
},
49-
},
5054
createCheckout: async (kind: string, _offer: unknown, missing?: number) => {
5155
checkouts.push({ kind, missing });
5256
return "https://checkout.stripe.com/c/pay/cs_test_1";
@@ -64,6 +68,7 @@ afterEach(() => {
6468
checkouts.length = 0;
6569
Object.assign(state, {
6670
...{ afterPlans: pro(1_000_000), enters: 0, enterHeld: false, noPrice: false, proPrices: [] },
71+
...{ offerReads: 0, offersHeldFrom: Infinity },
6772
});
6873
vi.restoreAllMocks();
6974
vi.useRealTimers();
@@ -163,6 +168,28 @@ describe("billing subscribe", () => {
163168
expect(checkouts).toEqual([]);
164169
});
165170

171+
it("prepares no checkout link when the page is paid while the price is still loading", async () => {
172+
state.offersHeldFrom = 0;
173+
const out = await billingRun([free, pro(0)], true);
174+
expect(out).toContain("✓ Done");
175+
expect(out).not.toContain("Checkout link");
176+
expect(checkouts).toEqual([]);
177+
});
178+
179+
it("prepares no checkout when the page is paid while Enter's price read is pending", async () => {
180+
state.offersHeldFrom = 1;
181+
const out = await billingRun([free, free, pro(0)], false);
182+
expect(out).toContain("✓ Done");
183+
expect(state.enters).toBe(1);
184+
expect(checkouts).toEqual([]);
185+
});
186+
187+
it("times out, preparing no checkout, while Enter's price read is pending", async () => {
188+
Object.assign(state, { offersHeldFrom: 1, afterPlans: free });
189+
await expect(billingRun([free], false, ["subscribe", "--timeout", "1"])).rejects.toThrow();
190+
expect(checkouts).toEqual([]);
191+
});
192+
166193
it("times out while the Enter prompt is still waiting", async () => {
167194
Object.assign(state, { enterHeld: true, afterPlans: free });
168195
await expect(billingRun([free], false, ["subscribe", "--timeout", "1"])).rejects.toThrow();

‎packages/cli/src/commands/billing.ts‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,19 +49,20 @@ async function payOrShowTheNewPrice(
4949
stop: AbortSignal,
5050
needed?: number,
5151
): Promise<string | undefined> {
52-
const now = await readPlan();
52+
const now = await readPlan(stop);
5353
if (stop.aborted) return undefined;
5454
if (!readFromTheServer(now)) return void console.log(NO_PLAN);
5555
if (done(now)) return undefined;
56-
const offer = await readOffer();
56+
const offer = await readOffer(stop);
57+
if (stop.aborted) return undefined;
5758
const missing = needed ? needed - now.credits : undefined;
5859
const line = priceLine(kind, offer, missing, needed);
5960
if (!line) return void console.log(NO_PRICE);
6061
if (line !== shown) {
6162
console.log(line);
6263
return line;
6364
}
64-
const link = await createCheckout(kind, offer, missing);
65+
const link = await createCheckout(kind, offer, missing, stop);
6566
if (!stop.aborted) await openBrowser(link);
6667
return undefined;
6768
}
@@ -87,6 +88,16 @@ async function checkoutOnEnterAtTheCurrentPrice(
8788
}
8889
}
8990

91+
async function printTheCheckoutLink(
92+
kind: "plans" | "credits",
93+
offer: Offer,
94+
stop: AbortSignal,
95+
missing?: number,
96+
) {
97+
const link = await createCheckout(kind, offer, missing, stop);
98+
if (!stop.aborted) console.log(`Checkout link: ${c.accent(link)}`);
99+
}
100+
90101
async function offerCheckoutOrPrintTheLink(
91102
kind: "plans" | "credits",
92103
before: Plan | null,
@@ -95,17 +106,19 @@ async function offerCheckoutOrPrintTheLink(
95106
needed?: number,
96107
) {
97108
if (!readFromTheServer(before)) return void console.log(NO_PLAN);
98-
const offer = await readOffer();
109+
const offer = await readOffer(stop);
110+
if (stop.aborted) return;
99111
const missing = needed ? needed - before.credits : undefined;
100112
const line = priceLine(kind, offer, missing, needed);
101113
if (!line) return void console.log(NO_PRICE);
102114
console.log(line);
103115
try {
104-
if (isUnattended())
105-
console.log(`Checkout link: ${c.accent(await createCheckout(kind, offer, missing))}`);
106-
else await checkoutOnEnterAtTheCurrentPrice(kind, done, line, stop, needed);
116+
await (isUnattended()
117+
? printTheCheckoutLink(kind, offer, stop, missing)
118+
: checkoutOnEnterAtTheCurrentPrice(kind, done, line, stop, needed));
107119
} catch (error) {
108-
console.error(c.error(error instanceof Error ? error.message : String(error)));
120+
if (!stop.aborted)
121+
console.error(c.error(error instanceof Error ? error.message : String(error)));
109122
}
110123
}
111124

‎packages/cli/src/heygen/plan.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,14 @@ function mockPlan(): Plan | null {
2525
// Payment routes live on api2, beside the OAuth ones; the v3 generation routes stay on api.
2626
const billingBaseUrl = () => resolveCloudBaseUrl().replace("://api.", "://api2.");
2727

28-
export async function readPlan(): Promise<Plan | null> {
28+
const timeoutOrStop = (ms: number, stop?: AbortSignal) =>
29+
stop ? AbortSignal.any([stop, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
30+
31+
export async function readPlan(stop?: AbortSignal): Promise<Plan | null> {
2932
try {
3033
const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/subscription`, {
3134
headers: { ...(await resolveCloudAuthHeaders()), accept: "application/json" },
32-
signal: AbortSignal.timeout(15_000),
35+
signal: timeoutOrStop(15_000, stop),
3336
});
3437
const body: unknown = await res.json().catch(() => null);
3538
const data = isRecord(body) && isRecord(body.data) ? body.data : body;
@@ -82,11 +85,11 @@ export interface Offer {
8285
const int = (v: unknown) =>
8386
Number.isSafeInteger(v) && (v as number) > 0 ? (v as number) : undefined;
8487

85-
export async function readOffer(): Promise<Offer> {
88+
export async function readOffer(stop?: AbortSignal): Promise<Offer> {
8689
try {
8790
const res = await fetch(`${billingBaseUrl()}/v1/payment/hyperframes/plans`, {
8891
headers: { ...(await resolveCloudAuthHeaders()), accept: "application/json" },
89-
signal: AbortSignal.timeout(15_000),
92+
signal: timeoutOrStop(15_000, stop),
9093
});
9194
const body: unknown = await res.json().catch(() => null);
9295
const data = isRecord(body) && isRecord(body.data) ? body.data : body;
@@ -144,6 +147,7 @@ export async function createCheckout(
144147
kind: "plans" | "credits",
145148
offer: Offer,
146149
missing?: number,
150+
stop?: AbortSignal,
147151
): Promise<string> {
148152
const addon = kind === "credits" ? offer.addon : undefined;
149153
if (kind === "credits" && !addon)
@@ -165,7 +169,7 @@ export async function createCheckout(
165169
"content-type": "application/json",
166170
},
167171
body: JSON.stringify(body),
168-
signal: AbortSignal.timeout(20_000),
172+
signal: timeoutOrStop(20_000, stop),
169173
},
170174
);
171175
const reply: unknown = await res.json().catch(() => null);

0 commit comments

Comments
 (0)