@pithy-sh/payments 0.6.1 → 0.7.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 (87) hide show
  1. package/README.md +6 -1
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +13 -7
  4. package/dist/admin/read.d.ts +60 -0
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +86 -2
  7. package/dist/audit/actions.d.ts +5 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +6 -1
  10. package/dist/capability.d.ts +3 -3
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +14 -7
  13. package/dist/client/api.d.ts +25 -9
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +68 -12
  16. package/dist/client/hooks.d.ts +27 -39
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +166 -315
  19. package/dist/client/projection.d.ts +25 -18
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/client/railChoice.d.ts +46 -0
  22. package/dist/client/railChoice.d.ts.map +1 -0
  23. package/dist/client/railChoice.js +48 -0
  24. package/dist/data/webhookEvent.d.ts +67 -0
  25. package/dist/data/webhookEvent.d.ts.map +1 -1
  26. package/dist/data/webhookEvent.js +76 -1
  27. package/dist/http/responses.d.ts +64 -0
  28. package/dist/http/responses.d.ts.map +1 -1
  29. package/dist/http/responses.js +34 -1
  30. package/dist/http/routes.d.ts +1 -0
  31. package/dist/http/routes.d.ts.map +1 -1
  32. package/dist/http/routes.js +64 -11
  33. package/dist/http/schemas.d.ts +19 -0
  34. package/dist/http/schemas.d.ts.map +1 -1
  35. package/dist/http/schemas.js +18 -1
  36. package/dist/http/scopes.d.ts +15 -6
  37. package/dist/http/scopes.d.ts.map +1 -1
  38. package/dist/http/scopes.js +55 -5
  39. package/dist/http/view.d.ts +9 -2
  40. package/dist/http/view.d.ts.map +1 -1
  41. package/dist/http/view.js +29 -1
  42. package/dist/http/webhookGuard.d.ts +7 -1
  43. package/dist/http/webhookGuard.d.ts.map +1 -1
  44. package/dist/http/webhookGuard.js +3 -2
  45. package/dist/migrations/0003_webhook_targets.d.ts +19 -0
  46. package/dist/migrations/0003_webhook_targets.d.ts.map +1 -0
  47. package/dist/migrations/0003_webhook_targets.js +29 -0
  48. package/dist/processing/activities.d.ts +9 -0
  49. package/dist/processing/activities.d.ts.map +1 -0
  50. package/dist/processing/activities.js +30 -0
  51. package/dist/projection/orphans.d.ts.map +1 -1
  52. package/dist/projection/orphans.js +15 -6
  53. package/dist/projection/targets.d.ts +50 -0
  54. package/dist/projection/targets.d.ts.map +1 -0
  55. package/dist/projection/targets.js +50 -0
  56. package/dist/purge/contribution.d.ts +32 -0
  57. package/dist/purge/contribution.d.ts.map +1 -0
  58. package/dist/purge/contribution.js +120 -0
  59. package/dist/version.generated.d.ts +1 -1
  60. package/dist/version.generated.js +1 -1
  61. package/dist/workflows/paddleSweep.d.ts.map +1 -1
  62. package/dist/workflows/paddleSweep.js +20 -9
  63. package/docs/lemon-squeezy.md +1 -1
  64. package/docs/paddle.md +2 -0
  65. package/package.json +6 -4
  66. package/src/admin/coverage.ts +13 -9
  67. package/src/admin/read.ts +135 -0
  68. package/src/audit/actions.ts +5 -0
  69. package/src/capability.ts +25 -15
  70. package/src/client/api.ts +74 -11
  71. package/src/client/hooks.ts +206 -301
  72. package/src/client/projection.ts +25 -18
  73. package/src/client/railChoice.ts +72 -0
  74. package/src/data/webhookEvent.ts +115 -0
  75. package/src/http/responses.ts +66 -0
  76. package/src/http/routes.ts +73 -11
  77. package/src/http/schemas.ts +26 -0
  78. package/src/http/scopes.ts +58 -6
  79. package/src/http/view.ts +31 -1
  80. package/src/http/webhookGuard.ts +23 -3
  81. package/src/migrations/0003_webhook_targets.ts +34 -0
  82. package/src/processing/activities.ts +34 -0
  83. package/src/projection/orphans.ts +28 -11
  84. package/src/projection/targets.ts +66 -0
  85. package/src/purge/contribution.ts +135 -0
  86. package/src/version.generated.ts +1 -1
  87. package/src/workflows/paddleSweep.ts +39 -14
@@ -1,7 +1,9 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
- import { useCallback, useEffect, useRef, useState } from "react";
4
+ import { useAction } from "@pithy-sh/ui-core/src/action";
5
+ import { useRead } from "@pithy-sh/ui-core/src/read";
6
+ import { useCallback, useRef, useState } from "react";
5
7
  import {
6
8
  type AllowancesView,
7
9
  type EntitlementView,
@@ -9,11 +11,13 @@ import {
9
11
  getEntitlements,
10
12
  openBillingPortal,
11
13
  openStoreSubscriptions,
14
+ PAYMENTS_UNREADABLE,
12
15
  type PaddleCheckoutHandoff,
13
16
  type PaymentsClientOptions,
14
17
  type PaymentsClientRail,
15
18
  type PaymentsFailure,
16
19
  type PaymentsHostedRail,
20
+ type PaymentsResult,
17
21
  type PurchaseView,
18
22
  restorePurchases,
19
23
  resumeCheckout,
@@ -49,8 +53,9 @@ import { readPaddleLinkTransaction } from "./paddleLink";
49
53
  * (`@pithy-sh/payments/src/client/hooks`). It is deliberately absent from `src/index.ts` — that is what
50
54
  * keeps React out of a Worker bundle that composes payments.
51
55
  *
52
- * Cookie/session throughout, because `./api` is: same-origin, `credentials: "include"`, no token in web
53
- * storage, no bearer header. Bearer stays the mobile path.
56
+ * The transport is whatever the options name, because `./api` decides it: with no `origin`, same-origin
57
+ * with `credentials: "include"` and no token in web storage; with an `origin` and the bearer session's
58
+ * `fetch`, a native app's request that sends no cookie. These hooks hold no credential either way.
54
59
  *
55
60
  * **Nothing here throws, and nothing here is a security boundary.** A refusal is a message to render, and
56
61
  * the server's `requireEntitlement()` is the gate; these exist so a user is sent to the paywall rather than
@@ -66,10 +71,9 @@ import { readPaddleLinkTransaction } from "./paddleLink";
66
71
  /**
67
72
  * Hold the newest value without making it a dependency.
68
73
  *
69
- * Every hook below takes an options object, and a caller writing `useEntitlement("pro", { basePath })`
70
- * inline creates a new object every render. Depending on it would re-run the effect forever. So the
71
- * effects depend on the one thing that can actually change the request — `basePath`, a string — and read
72
- * the rest through this.
74
+ * Every hook below takes an options object, and a caller writing `useEntitlement("pro", { basePath })` inline
75
+ * creates a new object every render. So each read is keyed on the one thing that can actually change the
76
+ * request — `basePath`, a string — and reads the rest through this.
73
77
  */
74
78
  function useLatest<T>(value: T): { current: T } {
75
79
  const ref = useRef(value);
@@ -77,16 +81,23 @@ function useLatest<T>(value: T): { current: T } {
77
81
  return ref;
78
82
  }
79
83
 
80
- /** Whether a component is still mounted. Every async completion checks it before setting state. */
81
- function useLive(): { current: boolean } {
82
- const live = useRef(true);
83
- useEffect(() => {
84
- live.current = true;
85
- return () => {
86
- live.current = false;
87
- };
88
- }, []);
89
- return live;
84
+ /** A refusal carried as a thrown failure through `useRead` and `useAction`, so the last answer survives it. */
85
+ class Refused extends Error {
86
+ constructor(readonly failure: PaymentsFailure) {
87
+ super(failure.message);
88
+ }
89
+ }
90
+
91
+ /** The value of a result, or its refusal thrown as {@link Refused}. */
92
+ function unwrap<T>(result: PaymentsResult<T>): T {
93
+ if (result.ok) return result.value;
94
+ throw new Refused(result.failure);
95
+ }
96
+
97
+ /** The refusal behind a failure. The calls here resolve rather than throw, so anything else is unreadable. */
98
+ function refusalOf(failure: Error | null): PaymentsFailure | null {
99
+ if (failure === null) return null;
100
+ return failure instanceof Refused ? failure.failure : PAYMENTS_UNREADABLE;
90
101
  }
91
102
 
92
103
  /** What {@link useEntitlement} gives a screen. */
@@ -119,30 +130,17 @@ export interface UseEntitlement {
119
130
  * plan instead of locking it must not inherit this choice; see {@link useSubscription}.
120
131
  */
121
132
  export function useEntitlement(key: string, options?: PaymentsClientOptions): UseEntitlement {
122
- const [entitled, setEntitled] = useState(false);
123
- const [loading, setLoading] = useState(true);
124
- const [readFailure, setReadFailure] = useState<PaymentsFailure | null>(null);
125
133
  const latest = useLatest(options);
126
- const live = useLive();
127
134
  const basePath = options?.basePath;
128
-
129
- const refresh = useCallback(() => {
130
- setLoading(true);
131
- // `basePath` is read here rather than off the ref, so it is a real dependency: it is the one option
132
- // that changes the request, and a project that moved its routes must re-read. Everything else comes
133
- // through the ref, which is why an inline options object does not restart this on every render.
134
- void getEntitlements({ ...latest.current, basePath }).then((result) => {
135
- if (!live.current) return;
136
- // Fail closed on the answer, report the failure beside it. Both, not either.
137
- setEntitled(result.ok && result.value.some((entitlement) => entitlement.key === key && entitlement.granted));
138
- setReadFailure(result.ok ? null : result.failure);
139
- setLoading(false);
140
- });
141
- }, [key, basePath, latest, live]);
142
-
143
- useEffect(refresh, [refresh]);
144
-
145
- return { entitled, loading, readFailure, refresh };
135
+ // The result itself is the value, so a failed read replaces the last answer: a lock fails closed on it.
136
+ const read = useRead(`entitlements:${basePath ?? ""}`, () => getEntitlements({ ...latest.current, basePath }));
137
+ const result = read.value;
138
+ return {
139
+ entitled: result?.ok === true && result.value.some((entitlement) => entitlement.key === key && entitlement.granted),
140
+ loading: read.loading,
141
+ readFailure: result?.ok === false ? result.failure : refusalOf(read.failure),
142
+ refresh: read.refresh,
143
+ };
146
144
  }
147
145
 
148
146
  /** What {@link useAllowances} gives a paywall screen. */
@@ -165,26 +163,17 @@ export interface UseAllowances {
165
163
  * the kit's meters are what refuse.
166
164
  */
167
165
  export function useAllowances(options?: PaymentsClientOptions): UseAllowances {
168
- const [allowances, setAllowances] = useState<AllowancesView | null>(null);
169
- const [loading, setLoading] = useState(true);
170
- const [readFailure, setReadFailure] = useState<PaymentsFailure | null>(null);
171
166
  const latest = useLatest(options);
172
- const live = useLive();
173
167
  const basePath = options?.basePath;
174
-
175
- const refresh = useCallback(() => {
176
- setLoading(true);
177
- void getAllowances({ ...latest.current, basePath }).then((result) => {
178
- if (!live.current) return;
179
- if (result.ok) setAllowances(result.value);
180
- setReadFailure(result.ok ? null : result.failure);
181
- setLoading(false);
182
- });
183
- }, [basePath, latest, live]);
184
-
185
- useEffect(refresh, [refresh]);
186
-
187
- return { allowances, loading, readFailure, refresh };
168
+ const read = useRead(`allowances:${basePath ?? ""}`, async () =>
169
+ unwrap(await getAllowances({ ...latest.current, basePath })),
170
+ );
171
+ return {
172
+ allowances: read.value ?? null,
173
+ loading: read.loading,
174
+ readFailure: refusalOf(read.failure),
175
+ refresh: read.refresh,
176
+ };
188
177
  }
189
178
 
190
179
  /** What {@link useSubscription} gives a subscription screen. */
@@ -217,6 +206,8 @@ export interface UseSubscription {
217
206
  readFailure: PaymentsFailure | null;
218
207
  }
219
208
 
209
+ const NO_ENTITLEMENTS: readonly EntitlementView[] = [];
210
+
220
211
  /**
221
212
  * The caller's standing entitlements, and the one action a subscriber needs.
222
213
  *
@@ -225,41 +216,21 @@ export interface UseSubscription {
225
216
  * subscriptions are managed in their own apps, which a web screen can only link to.
226
217
  */
227
218
  export function useSubscription(options?: PaymentsClientOptions): UseSubscription {
228
- const [entitlements, setEntitlements] = useState<readonly EntitlementView[]>([]);
229
- const [loading, setLoading] = useState(true);
230
- const [managing, setManaging] = useState(false);
231
- const [failure, setFailure] = useState<PaymentsFailure | null>(null);
232
- const [readFailure, setReadFailure] = useState<PaymentsFailure | null>(null);
233
219
  const latest = useLatest(options);
234
- const live = useLive();
235
220
  const basePath = options?.basePath;
236
-
237
- const refresh = useCallback(() => {
238
- setLoading(true);
239
- // `basePath` explicitly, for the reason `useEntitlement` gives: it is the option that changes the
240
- // request, so it has to be a dependency rather than something read off a ref.
241
- void getEntitlements({ ...latest.current, basePath }).then((result) => {
242
- if (!live.current) return;
243
- // A refusal leaves the previous list alone rather than blanking it — the same rule `usePurchase`
244
- // follows. What a screen must not do is read the untouched list as this account's current plan,
245
- // which is what `readFailure` is there to stop.
246
- if (result.ok) setEntitlements(result.value);
247
- setReadFailure(result.ok ? null : result.failure);
248
- setLoading(false);
249
- });
250
- }, [basePath, latest, live]);
251
-
252
- useEffect(refresh, [refresh]);
253
-
254
- const manage = useCallback(async () => {
255
- setManaging(true);
256
- setFailure(null);
221
+ // A refusal leaves the previous list alone rather than blanking it. What a screen must not do is read the
222
+ // untouched list as this account's current plan, which is what `readFailure` is there to stop.
223
+ const read = useRead(`subscription:${basePath ?? ""}`, async () =>
224
+ unwrap(await getEntitlements({ ...latest.current, basePath })),
225
+ );
226
+ const portal = useAction(async () => {
257
227
  const refused = await openBillingPortal(latest.current);
258
- if (!live.current) return;
259
- setManaging(false);
260
- // On success the browser is already leaving; setting state is harmless and keeps the two paths one shape.
261
- if (refused) setFailure(refused);
262
- }, [latest, live]);
228
+ if (refused) throw new Refused(refused);
229
+ });
230
+ const run = portal.run;
231
+ const manage = useCallback(async () => {
232
+ await run();
233
+ }, [run]);
263
234
 
264
235
  const manageStore = useCallback(
265
236
  (rail: "apple" | "google") => {
@@ -270,16 +241,17 @@ export function useSubscription(options?: PaymentsClientOptions): UseSubscriptio
270
241
  [latest],
271
242
  );
272
243
 
244
+ const entitlements = read.value ?? NO_ENTITLEMENTS;
273
245
  return {
274
246
  entitlements,
275
247
  subscribed: entitlements.some((entitlement) => entitlement.granted),
276
- loading,
277
- refresh,
248
+ loading: read.loading,
249
+ refresh: read.refresh,
278
250
  manage,
279
251
  manageStore,
280
- managing,
281
- failure,
282
- readFailure,
252
+ managing: portal.pending,
253
+ failure: refusalOf(portal.failure),
254
+ readFailure: refusalOf(read.failure),
283
255
  };
284
256
  }
285
257
 
@@ -301,7 +273,7 @@ export interface UseCheckout {
301
273
  *
302
274
  * Null on a redirect rail, because the browser has already left and there is nothing for a screen to
303
275
  * hold. Pass it to {@link usePaddleCheckout}, which opens it; a screen that never composes Paddle reads
304
- * null forever and renders exactly as it did before this field existed.
276
+ * null forever and never needs to read it.
305
277
  */
306
278
  handoff: PaddleCheckoutHandoff | null;
307
279
  }
@@ -319,33 +291,35 @@ export interface UseCheckout {
319
291
  * {@link usePaddleCheckout}.
320
292
  */
321
293
  export function useCheckout(options?: PaymentsClientOptions): UseCheckout {
322
- const [starting, setStarting] = useState(false);
323
- const [failure, setFailure] = useState<PaymentsFailure | null>(null);
324
- const [handoff, setHandoff] = useState<PaddleCheckoutHandoff | null>(null);
325
294
  const latest = useLatest(options);
326
- const live = useLive();
327
-
328
- const start = useCallback(
329
- async (productId: string, choices?: { rail?: PaymentsHostedRail; discountCode?: string }) => {
330
- setStarting(true);
331
- setFailure(null);
332
- setHandoff(null);
295
+ const checkout = useAction(
296
+ async (_signal, productId: string, choices?: { rail?: PaymentsHostedRail; discountCode?: string }) => {
333
297
  const outcome = await startCheckout(
334
298
  { productId, rail: choices?.rail, discountCode: choices?.discountCode },
335
299
  latest.current,
336
300
  );
337
- if (!live.current) return;
338
- setStarting(false);
339
301
  // Exhaustive on `kind` rather than truthiness. `left` is the browser already going; `paddle` is the
340
302
  // one outcome a screen must act on; `refused` is the only one that is a failure. Reading any of the
341
303
  // three as another is how a buyer ends up on a page whose button did nothing.
342
- if (outcome.kind === "refused") setFailure(outcome.failure);
343
- else if (outcome.kind === "paddle") setHandoff(outcome.handoff);
304
+ if (outcome.kind === "refused") throw new Refused(outcome.failure);
305
+ return outcome.kind === "paddle" ? outcome.handoff : null;
344
306
  },
345
- [latest, live],
307
+ );
308
+ const run = checkout.run;
309
+ const start = useCallback(
310
+ async (productId: string, choices?: { rail?: PaymentsHostedRail; discountCode?: string }) => {
311
+ await run(productId, choices);
312
+ },
313
+ [run],
346
314
  );
347
315
 
348
- return { start, starting, failure, handoff };
316
+ return {
317
+ start,
318
+ starting: checkout.pending,
319
+ failure: refusalOf(checkout.failure),
320
+ // Each attempt mints a new transaction, so the last one's handoff is nobody's while the next is out.
321
+ handoff: checkout.pending || checkout.failure !== null ? null : (checkout.value ?? null),
322
+ };
349
323
  }
350
324
 
351
325
  /** What {@link usePaddleCheckout} gives the screen that composes Paddle. */
@@ -367,53 +341,38 @@ export interface UsePaddleCheckout {
367
341
  /**
368
342
  * Open the handoff {@link useCheckout} produced, with Paddle.js, over this page or inside it.
369
343
  *
370
- * **In an effect, and that is the whole reason this is a hook rather than a line in a click handler.**
371
- * Inline checkout renders into an element the screen provides, and Paddle finds it by class name at the
372
- * moment `open` is called. Called from the handler that starts the checkout, the container React is about
344
+ * **After the render that revealed the container, which is why this is a hook rather than a line in a click
345
+ * handler.** Inline checkout renders into an element the screen provides, and Paddle finds it by class name at
346
+ * the moment `open` is called. Called from the handler that starts the checkout, the container React is about
373
347
  * to render does not exist yet — and what Paddle does then is throw `TypeError: Cannot read properties of
374
- * undefined (reading 'appendChild')` out of the click, which is not a sentence anyone can act on. An
375
- * effect runs after the commit that revealed the container, so the element is there.
348
+ * undefined (reading 'appendChild')` out of the click, which is not a sentence anyone can act on. A read runs
349
+ * after the commit, so the element is there.
376
350
  *
377
- * One open per handoff. `start` mints a new transaction on every attempt, so the transaction id is what a
378
- * fresh attempt looks like; a re-render with the same handoff must not open a second checkout over the
379
- * first — and neither must a second *mount* of the same one. React's `StrictMode` runs every effect,
380
- * cleans it up and runs it again, and that is the mode `pithy ui add` scaffolds: `client.tsx` wraps the
381
- * router in it. So the transaction that has been opened is remembered, rather than the effect trusting
382
- * that it runs once. The remembered id is the last one opened, not a flag — a buyer who closed the
383
- * overlay and clicked Buy again arrives with a new transaction, and that one must open.
351
+ * One open per handoff, keyed on its transaction id and run once per key, so a re-render, a second mount under
352
+ * `StrictMode` (the mode `pithy ui add` scaffolds) and an inline handoff object all open one checkout. A buyer who
353
+ * closed the overlay and clicked Buy again arrives with a new transaction, and that one opens.
384
354
  */
385
355
  export function usePaddleCheckout(
386
356
  handoff: PaddleCheckoutHandoff | null,
387
357
  options?: PaddleCheckoutOptions,
388
358
  ): UsePaddleCheckout {
389
- const [opening, setOpening] = useState(false);
390
- const [failure, setFailure] = useState<PaymentsFailure | null>(null);
391
359
  const latest = useLatest(options);
392
360
  const latestHandoff = useLatest(handoff);
393
- const live = useLive();
394
361
  const transactionId = handoff?.transactionId;
395
- /** The transaction this hook has already opened, so a second effect pass over it opens nothing. */
396
- const opened = useRef<string | null>(null);
397
-
398
- // `transactionId` stands in for the handoff, the way `priceQueryKey` stands in for a query: the object
399
- // is rebuilt by `useCheckout` on every attempt and identity would be a fine dependency today, but a
400
- // screen that builds one inline would then reopen the checkout on every render.
401
- useEffect(() => {
402
- const current = latestHandoff.current;
403
- if (transactionId === undefined || current === null) return;
404
- // StrictMode's second pass, or any remount holding the same handoff. One click bought one checkout.
405
- if (opened.current === transactionId) return;
406
- opened.current = transactionId;
407
- setOpening(true);
408
- setFailure(null);
409
- void openPaddleCheckout(current, latest.current).then((refused) => {
410
- if (!live.current) return;
411
- setOpening(false);
412
- setFailure(refused);
413
- });
414
- }, [transactionId, latest, latestHandoff, live]);
415
-
416
- return { inline: handoff?.displayMode === "inline", opening, failure };
362
+ const opened = useRead(
363
+ `paddle-open:${transactionId ?? ""}`,
364
+ async () => {
365
+ const current = latestHandoff.current;
366
+ return current === null ? null : openPaddleCheckout(current, latest.current);
367
+ },
368
+ { skip: transactionId === undefined, once: true },
369
+ );
370
+
371
+ return {
372
+ inline: handoff?.displayMode === "inline",
373
+ opening: opened.loading,
374
+ failure: transactionId === undefined || opened.loading ? null : (opened.value ?? refusalOf(opened.failure)),
375
+ };
417
376
  }
418
377
 
419
378
  /** What {@link usePaddleLink} gives the screen a Paddle payment link lands on. */
@@ -423,7 +382,7 @@ export interface UsePaddleLink {
423
382
  *
424
383
  * Null covers three different facts and deliberately reads as one: there was no `_ptxn` in the URL, there
425
384
  * was one and it was not a transaction id, or the server has not answered yet. A screen renders its
426
- * ordinary state for all three, which is what it was already rendering before this hook existed.
385
+ * ordinary state for all three.
427
386
  */
428
387
  handoff: PaddleCheckoutHandoff | null;
429
388
  /** Whether the resume read is in flight. A screen with nothing to show need not read it. */
@@ -432,6 +391,15 @@ export interface UsePaddleLink {
432
391
  failure: PaymentsFailure | null;
433
392
  }
434
393
 
394
+ /** The transaction a Paddle payment link put in this page's URL, or null — and null with no browser at all. */
395
+ function arrivedTransaction(): string | null {
396
+ // Narrowly cast rather than read off a typed global, which is `checkout.ts`'s `documentOf` pattern and is
397
+ // forced by the same thing: the build's tsconfig gives `globalThis` no DOM index signature, so
398
+ // `globalThis.location` compiles under `typecheck` and fails the published build with TS7017.
399
+ const search = (globalThis as { location?: { search?: string } }).location?.search;
400
+ return search === undefined ? null : readPaddleLinkTransaction(search);
401
+ }
402
+
435
403
  /**
436
404
  * Resume the checkout a Paddle payment link arrived for.
437
405
  *
@@ -442,62 +410,38 @@ export interface UsePaddleLink {
442
410
  * one already exists.
443
411
  *
444
412
  * **Pass the result to {@link usePaddleCheckout}, which opens it.** Nothing about opening is reimplemented
445
- * here, and that is the point: the one-open-per-transaction guard, the `StrictMode` second pass, and the
446
- * `PADDLE_NO_CONTAINER` refusal when an inline container is missing are all inherited by going through the
447
- * same hook the minted path goes through.
413
+ * here, and that is the point: the one-open-per-transaction rule and the `PADDLE_NO_CONTAINER` refusal when
414
+ * an inline container is missing are inherited by going through the same hook the minted path goes through.
448
415
  *
449
416
  * **In inline mode the page must already render the container.** Paddle finds it by class name when `open`
450
417
  * is called, so a Default payment link pointing at a page that does not render one produces a refusal
451
418
  * rather than a checkout — which makes the choice of landing page part of configuring this, not a detail.
452
419
  * `docs/paddle.md` says so where an adopter sets the link.
453
420
  *
454
- * Reads `location.search` once, on mount. A link is a navigation, so there is no later arrival to watch for.
455
- *
456
- * **One read per transaction, remembered rather than assumed.** The same rule {@link usePaddleCheckout}
457
- * states and for the same reason: `StrictMode` runs every effect, cleans it up and runs it again, and that
458
- * is the mode `pithy ui add` scaffolds. Without the ref this asked the server twice on every mount — not
459
- * harmful, since the route only echoes config, and still two requests where the file beside it had already
460
- * solved the problem.
421
+ * Reads `location.search` once, on mount, and asks the server once per transaction, `StrictMode` included. A
422
+ * link is a navigation, so there is no later arrival to watch for.
461
423
  */
462
424
  export function usePaddleLink(options?: PaymentsClientOptions): UsePaddleLink {
463
- const [handoff, setHandoff] = useState<PaddleCheckoutHandoff | null>(null);
464
- const [loading, setLoading] = useState(false);
465
- const [failure, setFailure] = useState<PaymentsFailure | null>(null);
466
425
  const latest = useLatest(options);
467
- const live = useLive();
468
- /** The transaction this hook has already asked about, so a second effect pass asks nothing. */
469
- const asked = useRef<string | null>(null);
470
-
471
- useEffect(() => {
472
- // Narrowly cast rather than read off a typed global, which is `checkout.ts`'s `documentOf` pattern and
473
- // is forced by the same thing: the build's tsconfig gives `globalThis` no DOM index signature, so
474
- // `globalThis.location` compiles under `typecheck` and fails the published build with TS7017.
475
- const search = (globalThis as { location?: { search?: string } }).location?.search;
476
- // No browser, or nothing in the URL. Both are "this page was not reached from a payment link", and a
477
- // server render is the first of those rather than a failure worth reporting.
478
- const transactionId = search === undefined ? null : readPaddleLinkTransaction(search);
479
- if (transactionId === null) return;
480
- // StrictMode's second pass, or any remount holding the same URL. One arrival is one read.
481
- if (asked.current === transactionId) return;
482
- asked.current = transactionId;
483
- setLoading(true);
484
- void resumeCheckout(transactionId, latest.current).then((outcome) => {
485
- if (!live.current) return;
486
- setLoading(false);
487
- if (outcome.ok) setHandoff(outcome.value);
488
- else setFailure(outcome.failure);
489
- });
490
- }, [latest, live]);
491
-
492
- return { handoff, loading, failure };
426
+ const [transactionId] = useState(arrivedTransaction);
427
+ const resumed = useRead(
428
+ `paddle-link:${transactionId ?? ""}`,
429
+ async () => (transactionId === null ? null : unwrap(await resumeCheckout(transactionId, latest.current))),
430
+ { skip: transactionId === null, once: true },
431
+ );
432
+
433
+ return { handoff: resumed.value ?? null, loading: resumed.loading, failure: refusalOf(resumed.failure) };
493
434
  }
494
435
 
495
436
  /** What {@link usePurchase} gives the screen that submits receipts. */
496
437
  export interface UsePurchase {
497
- /** Submit one receipt for verification. */
498
- submit: (rail: PaymentsClientRail, receipt: string) => Promise<void>;
499
- /** Submit a store account's whole history on one rail — Restore Purchases. */
500
- restore: (rail: PaymentsClientRail, receipts: readonly string[]) => Promise<void>;
438
+ /**
439
+ * Submit one receipt for verification. Resolves `true` when the Worker accepted it: a native app finishes the
440
+ * store's transaction only then, so a refused one stays with the store to be submitted again.
441
+ */
442
+ submit: (rail: PaymentsClientRail, receipt: string) => Promise<boolean>;
443
+ /** Submit a store account's whole history on one rail — Restore Purchases. Resolves `true` when accepted. */
444
+ restore: (rail: PaymentsClientRail, receipts: readonly string[]) => Promise<boolean>;
501
445
  /** The purchase the last successful submission projected, or null. */
502
446
  purchase: PurchaseView | null;
503
447
  /** The caller's entitlements as of the last successful write. */
@@ -521,48 +465,46 @@ export interface UsePurchase {
521
465
  * paywall back over a feature the user already owns, on nothing more than a failed second submission.
522
466
  */
523
467
  export function usePurchase(options?: PaymentsClientOptions): UsePurchase {
524
- const [purchase, setPurchase] = useState<PurchaseView | null>(null);
525
- const [entitlements, setEntitlements] = useState<readonly EntitlementView[]>([]);
526
- const [busy, setBusy] = useState(false);
527
- const [failure, setFailure] = useState<PaymentsFailure | null>(null);
528
468
  const latest = useLatest(options);
529
- const live = useLive();
530
-
531
- const submit = useCallback(
532
- async (rail: PaymentsClientRail, receipt: string) => {
533
- setBusy(true);
534
- setFailure(null);
535
- const result = await submitPurchase({ rail, receipt }, latest.current);
536
- if (!live.current) return;
537
- setBusy(false);
538
- if (!result.ok) {
539
- setFailure(result.failure);
540
- return;
469
+ // One action for both calls, so the last success of either is what the screen shows.
470
+ const write = useAction(
471
+ async (
472
+ _signal,
473
+ call:
474
+ | { kind: "submit"; rail: PaymentsClientRail; receipt: string }
475
+ | {
476
+ kind: "restore";
477
+ rail: PaymentsClientRail;
478
+ receipts: readonly string[];
479
+ },
480
+ ): Promise<{ purchase: PurchaseView | null; entitlements: readonly EntitlementView[] }> => {
481
+ if (call.kind === "submit") {
482
+ const written = unwrap(await submitPurchase({ rail: call.rail, receipt: call.receipt }, latest.current));
483
+ return { purchase: written.purchase, entitlements: written.entitlements };
541
484
  }
542
- setPurchase(result.value.purchase);
543
- setEntitlements(result.value.entitlements);
485
+ const restored = unwrap(await restorePurchases({ rail: call.rail, receipts: call.receipts }, latest.current));
486
+ return { purchase: restored.purchases[0] ?? null, entitlements: restored.entitlements };
544
487
  },
545
- [latest, live],
546
488
  );
547
-
489
+ const run = write.run;
490
+ const submit = useCallback(
491
+ async (rail: PaymentsClientRail, receipt: string) => (await run({ kind: "submit", rail, receipt })) !== undefined,
492
+ [run],
493
+ );
548
494
  const restore = useCallback(
549
- async (rail: PaymentsClientRail, receipts: readonly string[]) => {
550
- setBusy(true);
551
- setFailure(null);
552
- const result = await restorePurchases({ rail, receipts }, latest.current);
553
- if (!live.current) return;
554
- setBusy(false);
555
- if (!result.ok) {
556
- setFailure(result.failure);
557
- return;
558
- }
559
- setPurchase(result.value.purchases[0] ?? null);
560
- setEntitlements(result.value.entitlements);
561
- },
562
- [latest, live],
495
+ async (rail: PaymentsClientRail, receipts: readonly string[]) =>
496
+ (await run({ kind: "restore", rail, receipts })) !== undefined,
497
+ [run],
563
498
  );
564
499
 
565
- return { submit, restore, purchase, entitlements, busy, failure };
500
+ return {
501
+ submit,
502
+ restore,
503
+ purchase: write.value?.purchase ?? null,
504
+ entitlements: write.value?.entitlements ?? NO_ENTITLEMENTS,
505
+ busy: write.pending,
506
+ failure: refusalOf(write.failure),
507
+ };
566
508
  }
567
509
 
568
510
  /** What {@link usePaddle} gives a screen that has to talk to Paddle.js directly. */
@@ -588,31 +530,25 @@ export interface UsePaddle {
588
530
  * React-shaped view of it: a state a screen can render.
589
531
  */
590
532
  export function usePaddle(setup: PaddleSetup | null, options?: PaddleOptions): UsePaddle {
591
- const [paddle, setPaddle] = useState<PaddleJs | null>(null);
592
- const [loading, setLoading] = useState(setup !== null);
593
- const [failure, setFailure] = useState<PaymentsFailure | null>(null);
594
533
  const latest = useLatest(options);
595
- const live = useLive();
596
- // The two fields, not the object: a screen writing `usePaddle(paymentsConfig.paddle)` passes a stable
597
- // reference today, and one writing an object literal must not restart the load every render.
534
+ // The two fields, not the object: a screen writing an object literal must not restart the load every render.
598
535
  const clientToken = setup?.clientToken;
599
536
  const environment = setup?.environment;
537
+ const loaded = useRead(
538
+ `paddle:${environment ?? ""}:${clientToken ?? ""}`,
539
+ () =>
540
+ clientToken === undefined || environment === undefined
541
+ ? Promise.resolve(null)
542
+ : loadPaddle({ clientToken, environment }, latest.current),
543
+ { skip: clientToken === undefined || environment === undefined },
544
+ );
545
+ const result = loaded.value;
600
546
 
601
- useEffect(() => {
602
- if (clientToken === undefined || environment === undefined) {
603
- setLoading(false);
604
- return;
605
- }
606
- setLoading(true);
607
- void loadPaddle({ clientToken, environment }, latest.current).then((result) => {
608
- if (!live.current) return;
609
- setPaddle(result.ok ? result.value : null);
610
- setFailure(result.ok ? null : result.failure);
611
- setLoading(false);
612
- });
613
- }, [clientToken, environment, latest, live]);
614
-
615
- return { paddle, loading, failure };
547
+ return {
548
+ paddle: result?.ok === true ? result.value : null,
549
+ loading: loaded.loading,
550
+ failure: result?.ok === false ? result.failure : refusalOf(loaded.failure),
551
+ };
616
552
  }
617
553
 
618
554
  /** What {@link usePricePreview} gives a pricing screen. */
@@ -643,70 +579,39 @@ export interface UsePricePreview {
643
579
  * $5.44 in New York, $5.75 in Chicago, $5.00 in Berlin including €0.80 of VAT, and ¥725 in Tokyo without
644
580
  * a table of tax rates aging in somebody's repository.
645
581
  *
646
- * `query` may be written inline. The effect depends on {@link priceQueryKey} rather than on the object,
647
- * so an object literal re-created on every render re-quotes when the request changed and not before.
582
+ * `query` may be written inline. The read is keyed on {@link priceQueryKey} rather than on the object, so an
583
+ * object literal re-created on every render re-quotes when the request changed and not before.
648
584
  *
649
- * A failure clears the previous quote rather than leaving it. The other hooks here keep their last good
650
- * value on a refusal, and this one deliberately does not: a re-quote happens because the *request*
585
+ * A failure clears the previous quote rather than leaving it, because a re-quote happens when the *request*
651
586
  * changed, so the value it would be keeping is a price for something else.
652
587
  *
653
- * **Only the latest quote is rendered, whichever answers first.** Two previews can be in flight at once —
654
- * an anonymous visitor's location resolves under the query, or a country picker moves — and the slower
655
- * one landing last would otherwise win, putting a price for an address the visitor has left on the one
656
- * screen whose entire job is showing a correct one. Superseded answers are *ignored*, not canceled:
657
- * Paddle.js's `PricePreview` takes no `AbortSignal` and hands back a bare promise, so there is nothing to
658
- * cancel and ignoring it is the whole of the fix. A superseded refusal is ignored the same way, which is
659
- * what stops a dead request blanking a price the visitor is already reading.
588
+ * **Only the latest quote is rendered, whichever answers first.** A slower quote for an address the visitor
589
+ * has left — an anonymous visitor's location resolving under the query, or a country picker moving — is
590
+ * discarded rather than rendered, and so is a superseded refusal.
660
591
  */
661
592
  export function usePricePreview(
662
593
  setup: PaddleSetup | null,
663
594
  query: PaddlePriceQuery,
664
595
  options?: PaddleOptions,
665
596
  ): UsePricePreview {
666
- const [preview, setPreview] = useState<PricePreview | null>(null);
667
- const [loading, setLoading] = useState(setup !== null);
668
- const [failure, setFailure] = useState<PaymentsFailure | null>(null);
669
597
  const latest = useLatest(options);
670
598
  const latestQuery = useLatest(query);
671
- const live = useLive();
672
599
  const clientToken = setup?.clientToken;
673
600
  const environment = setup?.environment;
674
- const queryKey = priceQueryKey(query);
675
- /**
676
- * Which quote is the current one.
677
- *
678
- * A counter rather than a comparison against `queryKey`, because two quotes for the *same* query race
679
- * too — a screen calling `refresh` twice is the ordinary way to get there — and a key would read those
680
- * two as one and let either win. Every ask takes the next number; only the holder of the last one
681
- * issued may write state.
682
- */
683
- const issued = useRef(0);
684
-
685
- // `queryKey` is a dependency the body never reads, and that is the design. It is what makes "the request
686
- // changed" a value React can compare — the query itself is an object literal rebuilt every render, and
687
- // depending on that would quote forever. Reading the key back inside would mean parsing it, which is how
688
- // a serialization becomes a second source of truth for the thing it serializes.
689
- // biome-ignore lint/correctness/useExhaustiveDependencies: queryKey stands in for the query, deliberately.
690
- const refresh = useCallback(() => {
691
- if (clientToken === undefined || environment === undefined) {
692
- setLoading(false);
693
- return;
694
- }
695
- const ticket = ++issued.current;
696
- setLoading(true);
697
- void previewPrices({ clientToken, environment }, latestQuery.current, latest.current).then((result) => {
698
- if (!live.current) return;
699
- // A superseded answer is not a late answer to render, it is an answer to a question nobody is
700
- // asking any more. It writes nothing at all — not the price, not the failure, and not `loading`,
701
- // which still belongs to the quote that is out.
702
- if (ticket !== issued.current) return;
703
- setPreview(result.ok ? result.value : null);
704
- setFailure(result.ok ? null : result.failure);
705
- setLoading(false);
706
- });
707
- }, [clientToken, environment, queryKey, latest, latestQuery, live]);
708
-
709
- useEffect(refresh, [refresh]);
710
-
711
- return { preview, loading, failure, refresh };
601
+ const quoted = useRead(
602
+ `price:${environment ?? ""}:${clientToken ?? ""}:${priceQueryKey(query)}`,
603
+ () =>
604
+ clientToken === undefined || environment === undefined
605
+ ? Promise.resolve(null)
606
+ : previewPrices({ clientToken, environment }, latestQuery.current, latest.current),
607
+ { skip: clientToken === undefined || environment === undefined },
608
+ );
609
+ const result = quoted.value;
610
+
611
+ return {
612
+ preview: result?.ok === true ? result.value : null,
613
+ loading: quoted.loading,
614
+ failure: result?.ok === false ? result.failure : refusalOf(quoted.failure),
615
+ refresh: quoted.refresh,
616
+ };
712
617
  }