@baukit/purchases-core 0.13.0 → 0.14.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 (46) hide show
  1. package/README.md +5 -6
  2. package/dist/access.d.ts +22 -0
  3. package/dist/access.d.ts.map +1 -0
  4. package/dist/access.js +24 -0
  5. package/dist/access.js.map +1 -0
  6. package/dist/account-plan.d.ts +22 -0
  7. package/dist/account-plan.d.ts.map +1 -0
  8. package/dist/account-plan.js +96 -0
  9. package/dist/account-plan.js.map +1 -0
  10. package/dist/entitlement.d.ts +27 -4
  11. package/dist/entitlement.d.ts.map +1 -1
  12. package/dist/entitlement.js +4 -1
  13. package/dist/entitlement.js.map +1 -1
  14. package/dist/flow.d.ts +7 -0
  15. package/dist/flow.d.ts.map +1 -1
  16. package/dist/flow.js +21 -3
  17. package/dist/flow.js.map +1 -1
  18. package/dist/index.d.ts +4 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/paywall.d.ts +28 -0
  23. package/dist/paywall.d.ts.map +1 -0
  24. package/dist/paywall.js +41 -0
  25. package/dist/paywall.js.map +1 -0
  26. package/dist/plans-link.d.ts +9 -0
  27. package/dist/plans-link.d.ts.map +1 -0
  28. package/dist/plans-link.js +17 -0
  29. package/dist/plans-link.js.map +1 -0
  30. package/dist/react.d.ts +19 -4
  31. package/dist/react.d.ts.map +1 -1
  32. package/dist/react.js +28 -10
  33. package/dist/react.js.map +1 -1
  34. package/package.json +1 -1
  35. package/src/access.ts +45 -0
  36. package/src/account-plan.test.ts +96 -0
  37. package/src/account-plan.ts +124 -0
  38. package/src/entitlement.ts +31 -4
  39. package/src/flow.test.ts +84 -13
  40. package/src/flow.ts +28 -3
  41. package/src/index.ts +4 -0
  42. package/src/paywall.test.ts +82 -0
  43. package/src/paywall.ts +60 -0
  44. package/src/plans-link.ts +21 -0
  45. package/src/react.test.ts +113 -12
  46. package/src/react.ts +54 -11
package/dist/react.js CHANGED
@@ -1,14 +1,17 @@
1
- import { createContext, createElement, useContext, useSyncExternalStore } from 'react';
2
- import { hasFeature } from './entitlement.js';
1
+ import { createContext, createElement, Fragment, useContext, useSyncExternalStore } from 'react';
2
+ import { featureAccess } from './access.js';
3
3
  const PurchaseFlowContext = createContext(null);
4
- export function PurchasesProvider({ flow, children }) {
5
- return createElement(PurchaseFlowContext.Provider, { value: flow }, children);
4
+ export function PurchasesProvider({ flow, productId, children, }) {
5
+ return createElement(PurchaseFlowContext.Provider, { value: { flow, productId } }, children);
6
6
  }
7
- export function usePurchaseFlow() {
8
- const flow = useContext(PurchaseFlowContext);
9
- if (flow === null)
7
+ function usePurchasesContext() {
8
+ const context = useContext(PurchaseFlowContext);
9
+ if (context === null)
10
10
  throw new Error('usePurchaseFlow requires a PurchasesProvider');
11
- return flow;
11
+ return context;
12
+ }
13
+ export function usePurchaseFlow() {
14
+ return usePurchasesContext().flow;
12
15
  }
13
16
  export function usePurchaseState() {
14
17
  const flow = usePurchaseFlow();
@@ -17,8 +20,23 @@ export function usePurchaseState() {
17
20
  export function useEntitlement() {
18
21
  return usePurchaseState().entitlement;
19
22
  }
20
- /** True only when the backend-verified entitlement grants the feature key. */
23
+ /** Access to a feature key from the backend-verified entitlement. See `featureAccess`. */
21
24
  export function useFeature(key) {
22
- return hasFeature(useEntitlement(), key);
25
+ const { productId } = usePurchasesContext();
26
+ return featureAccess(usePurchaseState(), key, { productId });
27
+ }
28
+ /** Renders `children` only while the verified entitlement grants `feature`. */
29
+ export function LockedFeature(props) {
30
+ const access = useFeature(props.feature);
31
+ switch (access.status) {
32
+ case 'granted':
33
+ return createElement(Fragment, null, props.children);
34
+ case 'locked':
35
+ return props.locked(access.paywall);
36
+ case 'loading':
37
+ return props.loading ?? null;
38
+ case 'unavailable':
39
+ return props.unavailable ?? null;
40
+ }
23
41
  }
24
42
  //# sourceMappingURL=react.js.map
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","sourceRoot":"","sources":["../src/react.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAGvF,OAAO,EAAE,UAAU,EAA4B,MAAM,kBAAkB,CAAC;AAGxE,MAAM,mBAAmB,GAAG,aAAa,CAAsB,IAAI,CAAC,CAAC;AAOrE,MAAM,UAAU,iBAAiB,CAAC,EAAE,IAAI,EAAE,QAAQ,EAA0B;IAC1E,OAAO,aAAa,CAAC,mBAAmB,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,QAAQ,CAAC,CAAC;AAChF,CAAC;AAED,MAAM,UAAU,eAAe;IAC7B,MAAM,IAAI,GAAG,UAAU,CAAC,mBAAmB,CAAC,CAAC;IAC7C,IAAI,IAAI,KAAK,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IACnF,OAAO,IAAI,CAAC;AACd,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,MAAM,IAAI,GAAG,eAAe,EAAE,CAAC;IAC/B,OAAO,oBAAoB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC5E,CAAC;AAED,MAAM,UAAU,cAAc;IAC5B,OAAO,gBAAgB,EAAE,CAAC,WAAW,CAAC;AACxC,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,OAAO,UAAU,CAAC,cAAc,EAAE,EAAE,GAAG,CAAC,CAAC;AAC3C,CAAC"}
1
+ {"version":3,"file":"react.js","sourceRoot":"","sources":["../src/react.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,oBAAoB,EAAE,MAAM,OAAO,CAAC;AAGjG,OAAO,EAAE,aAAa,EAAsB,MAAM,aAAa,CAAC;AAUhE,MAAM,mBAAmB,GAAG,aAAa,CAA0B,IAAI,CAAC,CAAC;AASzE,MAAM,UAAU,iBAAiB,CAAC,EAChC,IAAI,EACJ,SAAS,EACT,QAAQ,GACe;IACvB,OAAO,aAAa,CAAC,mBAAmB,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,QAAQ,CAAC,CAAC;AAC/F,CAAC;AAED,SAAS,mBAAmB;IAC1B,MAAM,OAAO,GAAG,UAAU,CAAC,mBAAmB,CAAC,CAAC;IAChD,IAAI,OAAO,KAAK,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IACtF,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,eAAe;IAC7B,OAAO,mBAAmB,EAAE,CAAC,IAAI,CAAC;AACpC,CAAC;AAED,MAAM,UAAU,gBAAgB;IAC9B,MAAM,IAAI,GAAG,eAAe,EAAE,CAAC;IAC/B,OAAO,oBAAoB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;AAC5E,CAAC;AAED,MAAM,UAAU,cAAc;IAC5B,OAAO,gBAAgB,EAAE,CAAC,WAAW,CAAC;AACxC,CAAC;AAED,0FAA0F;AAC1F,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,MAAM,EAAE,SAAS,EAAE,GAAG,mBAAmB,EAAE,CAAC;IAC5C,OAAO,aAAa,CAAC,gBAAgB,EAAE,EAAE,GAAG,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;AAC/D,CAAC;AAYD,+EAA+E;AAC/E,MAAM,UAAU,aAAa,CAAC,KAAyB;IACrD,MAAM,MAAM,GAAG,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACzC,QAAQ,MAAM,CAAC,MAAM,EAAE,CAAC;QACtB,KAAK,SAAS;YACZ,OAAO,aAAa,CAAC,QAAQ,EAAE,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;QACvD,KAAK,QAAQ;YACX,OAAO,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACtC,KAAK,SAAS;YACZ,OAAO,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC;QAC/B,KAAK,aAAa;YAChB,OAAO,KAAK,CAAC,WAAW,IAAI,IAAI,CAAC;IACrC,CAAC;AACH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@baukit/purchases-core",
3
- "version": "0.13.0",
3
+ "version": "0.14.1",
4
4
  "description": "Store-neutral mobile purchases: a purchases port, a no-op client, a purchase flow that waits for suite identity and the refreshed entitlement, and feature-key gating hooks.",
5
5
  "license": "MIT",
6
6
  "author": "Patrick Koss",
package/src/access.ts ADDED
@@ -0,0 +1,45 @@
1
+ import type { VerifiedEntitlement } from './entitlement.js';
2
+ import type { PurchaseState } from './flow.js';
3
+ import { paywallFor, type Paywall, type PaywallContext } from './paywall.js';
4
+
5
+ /**
6
+ * Gating is closed until a verified entitlement grants the key. `loading` and
7
+ * `unavailable` show neither the feature nor a paywall, so a slow or failing
8
+ * backend never unlocks a feature and never sells a plan.
9
+ */
10
+ export type FeatureAccess =
11
+ | { readonly status: 'loading' }
12
+ | { readonly status: 'unavailable' }
13
+ | { readonly status: 'granted'; readonly entitlement: VerifiedEntitlement }
14
+ | {
15
+ readonly status: 'locked';
16
+ readonly entitlement: VerifiedEntitlement | null;
17
+ readonly paywall: Paywall;
18
+ };
19
+
20
+ export function featureAccess(
21
+ state: PurchaseState,
22
+ feature: string,
23
+ context: Omit<PaywallContext, 'feature'>,
24
+ ): FeatureAccess {
25
+ const { entitlement, entitlementStatus } = state;
26
+ if (entitlement?.features.includes(feature)) {
27
+ return { status: 'granted', entitlement };
28
+ }
29
+ if (entitlement !== null) {
30
+ return {
31
+ status: 'locked',
32
+ entitlement,
33
+ paywall: paywallFor(entitlement, { ...context, feature }),
34
+ };
35
+ }
36
+ switch (entitlementStatus) {
37
+ case 'loading':
38
+ return { status: 'loading' };
39
+ case 'unavailable':
40
+ return { status: 'unavailable' };
41
+ case 'signed_out':
42
+ case 'ready':
43
+ return { status: 'locked', entitlement: null, paywall: { kind: 'none' } };
44
+ }
45
+ }
@@ -0,0 +1,96 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { AccountPlanError, createAccountPlanBackend } from './index.js';
4
+
5
+ const entitlement = {
6
+ mode: 'hub',
7
+ suiteSubject: 'suite|a',
8
+ tier: 'premium',
9
+ features: ['hebkit.export'],
10
+ revision: 3,
11
+ plansUrl: 'https://accounts.example.test/plans',
12
+ billing: { channel: 'app_store', soldBy: 'hebkit' },
13
+ };
14
+ const balance = {
15
+ suiteSubject: 'suite|a',
16
+ wallet: 'hebkit',
17
+ revision: 0,
18
+ total: 10,
19
+ grant: { available: 0, expiresAt: null },
20
+ packs: [{ available: 10, expiresAt: 1795392000 }],
21
+ };
22
+
23
+ function json(status: number, body: unknown, headers: Record<string, string> = {}): Response {
24
+ return new Response(JSON.stringify(body), {
25
+ status,
26
+ headers: { 'content-type': 'application/json', ...headers },
27
+ });
28
+ }
29
+ function error(status: number, code: string, headers: Record<string, string> = {}): Response {
30
+ return json(status, { error: { code, message: code, details: {} } }, headers);
31
+ }
32
+
33
+ describe('createAccountPlanBackend', () => {
34
+ it('reads both routes under the API prefix with per-request headers', async () => {
35
+ const fetch = vi.fn((url: string) =>
36
+ Promise.resolve(json(200, url.endsWith('/me/credits') ? balance : entitlement)),
37
+ );
38
+ const backend = createAccountPlanBackend({
39
+ baseUrl: 'https://api.example.test/api/v1/',
40
+ fetch,
41
+ headers: () => ({ authorization: 'Bearer t' }),
42
+ });
43
+
44
+ await expect(backend.refreshEntitlement()).resolves.toEqual(entitlement);
45
+ await expect(backend.creditBalance?.()).resolves.toEqual(balance);
46
+ expect(fetch).toHaveBeenCalledWith('https://api.example.test/api/v1/me/entitlement', {
47
+ headers: { accept: 'application/json', authorization: 'Bearer t' },
48
+ });
49
+ expect(fetch.mock.calls[1]?.[0]).toBe('https://api.example.test/api/v1/me/credits');
50
+ });
51
+
52
+ it('treats a session without suite identity as no entitlement', async () => {
53
+ const backend = createAccountPlanBackend({
54
+ baseUrl: 'https://api.example.test',
55
+ fetch: () => Promise.resolve(error(403, 'suite_identity_missing')),
56
+ });
57
+ await expect(backend.refreshEntitlement()).resolves.toBeNull();
58
+ });
59
+
60
+ it('raises the plan error code with Retry-After', async () => {
61
+ const backend = createAccountPlanBackend({
62
+ baseUrl: 'https://api.example.test',
63
+ fetch: () => Promise.resolve(error(503, 'entitlements_unavailable', { 'retry-after': '5' })),
64
+ });
65
+ await expect(backend.refreshEntitlement()).rejects.toEqual(
66
+ new AccountPlanError(503, 'entitlements_unavailable', 5),
67
+ );
68
+ const broken = createAccountPlanBackend({
69
+ baseUrl: 'https://api.example.test',
70
+ fetch: () => Promise.resolve(new Response('oops', { status: 502 })),
71
+ });
72
+ await expect(broken.creditBalance?.()).rejects.toMatchObject({
73
+ status: 502,
74
+ code: 'internal_error',
75
+ retryAfterSeconds: null,
76
+ });
77
+ });
78
+
79
+ it('rejects bodies that do not match the route shapes', async () => {
80
+ for (const [path, body] of [
81
+ ['entitlement', { ...entitlement, mode: 'local' }],
82
+ ['entitlement', { ...entitlement, revision: -1 }],
83
+ ['entitlement', { ...entitlement, billing: 'web' }],
84
+ ['credits', { ...balance, available: 10, total: undefined }],
85
+ ['credits', { ...balance, packs: [{ remaining: 1 }] }],
86
+ ] as const) {
87
+ const backend = createAccountPlanBackend({
88
+ baseUrl: 'https://api.example.test',
89
+ fetch: () => Promise.resolve(json(200, body)),
90
+ });
91
+ const read =
92
+ path === 'entitlement' ? backend.refreshEntitlement() : backend.creditBalance?.();
93
+ await expect(read).rejects.toThrow(TypeError);
94
+ }
95
+ });
96
+ });
@@ -0,0 +1,124 @@
1
+ import type {
2
+ CreditBalanceSnapshot,
3
+ EntitlementBackend,
4
+ VerifiedEntitlement,
5
+ } from './entitlement.js';
6
+
7
+ /** Error codes of Baukit's account plan routes. */
8
+ export const ACCOUNT_PLAN_ERROR_CODES = [
9
+ 'suite_identity_missing',
10
+ 'entitlements_unavailable',
11
+ 'credits_unavailable',
12
+ 'feature_not_entitled',
13
+ ] as const;
14
+ export type AccountPlanErrorCode = (typeof ACCOUNT_PLAN_ERROR_CODES)[number];
15
+
16
+ export class AccountPlanError extends Error {
17
+ constructor(
18
+ readonly status: number,
19
+ readonly code: string,
20
+ readonly retryAfterSeconds: number | null = null,
21
+ ) {
22
+ super(code);
23
+ this.name = 'AccountPlanError';
24
+ }
25
+ }
26
+
27
+ export interface AccountPlanBackendOptions {
28
+ /** The product API prefix that nests the plan router, for example `https://api.example/api/v1`. */
29
+ readonly baseUrl: string;
30
+ readonly fetch: (
31
+ input: string,
32
+ init: { readonly headers: Record<string, string> },
33
+ ) => Promise<Response>;
34
+ /** Called per request, for example to add the bearer token. */
35
+ readonly headers?: () => Promise<Record<string, string>> | Record<string, string>;
36
+ }
37
+
38
+ type Json = Record<string, unknown>;
39
+
40
+ function record(value: unknown): value is Json {
41
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
42
+ }
43
+ function count(value: unknown): value is number {
44
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
45
+ }
46
+ function nullable(value: unknown, check: (value: unknown) => boolean): boolean {
47
+ return value === null || check(value);
48
+ }
49
+ function text(value: unknown): value is string {
50
+ return typeof value === 'string';
51
+ }
52
+
53
+ function parseEntitlement(value: unknown): VerifiedEntitlement {
54
+ if (
55
+ !record(value) ||
56
+ (value['mode'] !== 'hub' && value['mode'] !== 'standalone') ||
57
+ !text(value['suiteSubject']) ||
58
+ !text(value['tier']) ||
59
+ !Array.isArray(value['features']) ||
60
+ !value['features'].every(text) ||
61
+ !count(value['revision']) ||
62
+ !nullable(value['plansUrl'], text) ||
63
+ !nullable(value['billing'], record)
64
+ ) {
65
+ throw new TypeError('The API returned an invalid entitlement.');
66
+ }
67
+ return value as unknown as VerifiedEntitlement;
68
+ }
69
+
70
+ function parseBalance(value: unknown): CreditBalanceSnapshot {
71
+ const grant = record(value) ? value['grant'] : undefined;
72
+ const packs = record(value) ? value['packs'] : undefined;
73
+ if (
74
+ !record(value) ||
75
+ !text(value['suiteSubject']) ||
76
+ !text(value['wallet']) ||
77
+ !count(value['revision']) ||
78
+ !count(value['total']) ||
79
+ !record(grant) ||
80
+ !count(grant['available']) ||
81
+ !nullable(grant['expiresAt'], count) ||
82
+ !Array.isArray(packs) ||
83
+ !packs.every((pack) => record(pack) && count(pack['available']) && count(pack['expiresAt']))
84
+ ) {
85
+ throw new TypeError('The API returned an invalid credit balance.');
86
+ }
87
+ return value as unknown as CreditBalanceSnapshot;
88
+ }
89
+
90
+ async function failure(response: Response): Promise<AccountPlanError> {
91
+ const retry = Number(response.headers.get('retry-after'));
92
+ let code = 'internal_error';
93
+ try {
94
+ const body: unknown = await response.json();
95
+ const error = record(body) ? body['error'] : undefined;
96
+ if (record(error) && text(error['code'])) code = error['code'];
97
+ } catch {
98
+ code = 'internal_error';
99
+ }
100
+ return new AccountPlanError(
101
+ response.status,
102
+ code,
103
+ Number.isSafeInteger(retry) && retry > 0 ? retry : null,
104
+ );
105
+ }
106
+
107
+ /** Reads Baukit's `GET /me/entitlement` and `GET /me/credits`. `suite_identity_missing` resolves to `null`. */
108
+ export function createAccountPlanBackend(options: AccountPlanBackendOptions): EntitlementBackend {
109
+ const base = options.baseUrl.replace(/\/+$/u, '');
110
+ async function read<T>(path: string, parse: (value: unknown) => T): Promise<T | null> {
111
+ const headers = { accept: 'application/json', ...(await options.headers?.()) };
112
+ const response = await options.fetch(`${base}${path}`, { headers });
113
+ if (!response.ok) {
114
+ const error = await failure(response);
115
+ if (error.code === 'suite_identity_missing') return null;
116
+ throw error;
117
+ }
118
+ return parse(await response.json());
119
+ }
120
+ return {
121
+ refreshEntitlement: () => read('/me/entitlement', parseEntitlement),
122
+ creditBalance: () => read('/me/credits', parseBalance),
123
+ };
124
+ }
@@ -1,18 +1,38 @@
1
- /** Entitlement the product backend verified from the hub ticket. */
1
+ export type PlanMode = 'hub' | 'standalone';
2
+
3
+ export type BillingChannel =
4
+ 'web' | 'app_store' | 'play_store' | 'family' | 'organization' | 'promo';
5
+
6
+ /** The hub ticket's optional `billing` claim, passed through by the product backend. */
7
+ export interface BillingClaim {
8
+ readonly channel: BillingChannel;
9
+ readonly soldBy?: string;
10
+ readonly manageUrl?: string;
11
+ }
12
+
13
+ /** The body of the product backend's `GET /me/entitlement`. */
2
14
  export interface VerifiedEntitlement {
15
+ readonly mode: PlanMode;
3
16
  readonly suiteSubject: string;
4
17
  readonly tier: string;
5
18
  readonly features: readonly string[];
6
19
  readonly revision: number;
20
+ /** The hub `/plans` page in hub mode, null in standalone mode. */
21
+ readonly plansUrl: string | null;
22
+ readonly billing: BillingClaim | null;
7
23
  }
8
24
 
25
+ /** The body of the product backend's `GET /me/credits`. */
9
26
  export interface CreditBalanceSnapshot {
10
27
  readonly suiteSubject: string;
11
- readonly available: number;
28
+ readonly wallet: string;
12
29
  readonly revision: number;
30
+ readonly total: number;
31
+ readonly grant: { readonly available: number; readonly expiresAt: number | null };
32
+ readonly packs: readonly { readonly available: number; readonly expiresAt: number }[];
13
33
  }
14
34
 
15
- /** Product backend calls. The backend refreshes the hub ticket with its service credentials. */
35
+ /** Product backend calls. `null` means the session has no suite identity. */
16
36
  export interface EntitlementBackend {
17
37
  refreshEntitlement(): Promise<VerifiedEntitlement | null>;
18
38
  creditBalance?(): Promise<CreditBalanceSnapshot | null>;
@@ -23,14 +43,21 @@ export interface TicketClaimsLike {
23
43
  readonly tier: string;
24
44
  readonly features: readonly string[];
25
45
  readonly rev: number;
46
+ readonly billing?: BillingClaim;
26
47
  }
27
48
 
28
- export function entitlementFromTicket(claims: TicketClaimsLike): VerifiedEntitlement {
49
+ export function entitlementFromTicket(
50
+ claims: TicketClaimsLike,
51
+ plansUrl: string | null = null,
52
+ ): VerifiedEntitlement {
29
53
  return {
54
+ mode: 'hub',
30
55
  suiteSubject: claims.sub,
31
56
  tier: claims.tier,
32
57
  features: claims.features,
33
58
  revision: claims.rev,
59
+ plansUrl,
60
+ billing: claims.billing ?? null,
34
61
  };
35
62
  }
36
63
 
package/src/flow.test.ts CHANGED
@@ -82,7 +82,7 @@ class FakePort implements PurchasesPort {
82
82
 
83
83
  class FakeBackend implements EntitlementBackend {
84
84
  entitlement: VerifiedEntitlement | null = entitlement(1, []);
85
- balance: CreditBalanceSnapshot | null = { suiteSubject: SUBJECT, available: 0, revision: 0 };
85
+ balance: CreditBalanceSnapshot | null = balance(0, 0);
86
86
  refreshes = 0;
87
87
  failNext = false;
88
88
 
@@ -104,7 +104,26 @@ function entitlement(
104
104
  features: string[],
105
105
  suiteSubject = SUBJECT,
106
106
  ): VerifiedEntitlement {
107
- return { suiteSubject, tier: features.length ? 'premium' : 'free', features, revision };
107
+ return {
108
+ mode: 'hub',
109
+ suiteSubject,
110
+ tier: features.length ? 'premium' : 'free',
111
+ features,
112
+ revision,
113
+ plansUrl: 'https://accounts.example.test/plans',
114
+ billing: null,
115
+ };
116
+ }
117
+
118
+ function balance(total: number, revision: number): CreditBalanceSnapshot {
119
+ return {
120
+ suiteSubject: SUBJECT,
121
+ wallet: 'hebkit',
122
+ revision,
123
+ total,
124
+ grant: { available: total, expiresAt: null },
125
+ packs: [],
126
+ };
108
127
  }
109
128
 
110
129
  function setup(attempts = 3) {
@@ -175,7 +194,12 @@ describe('PurchaseFlow identity', () => {
175
194
  await flow.signOut();
176
195
 
177
196
  expect(port.calls).toEqual([`identify:${SUBJECT}`, 'reset']);
178
- expect(flow.getState()).toEqual({ suiteSubject: null, entitlement: null, creditBalance: null });
197
+ expect(flow.getState()).toEqual({
198
+ suiteSubject: null,
199
+ entitlement: null,
200
+ creditBalance: null,
201
+ entitlementStatus: 'signed_out',
202
+ });
179
203
  await expect(flow.purchase(monthly)).rejects.toMatchObject({ code: 'not_identified' });
180
204
  });
181
205
 
@@ -390,7 +414,7 @@ describe('PurchaseFlow credit packs', () => {
390
414
  const { port, backend, flow } = setup();
391
415
  await flow.identify(SUBJECT);
392
416
  port.onPurchase = () => {
393
- backend.balance = { suiteSubject: SUBJECT, available: 1_000, revision: 1 };
417
+ backend.balance = balance(1_000, 1);
394
418
  };
395
419
 
396
420
  const outcome = await flow.purchaseCreditPack(pack);
@@ -398,9 +422,9 @@ describe('PurchaseFlow credit packs', () => {
398
422
  expect(port.calls).toEqual([`identify:${SUBJECT}`, 'purchase:pack_small']);
399
423
  expect(outcome).toEqual({
400
424
  status: 'credited',
401
- balance: { suiteSubject: SUBJECT, available: 1_000, revision: 1 },
425
+ balance: balance(1_000, 1),
402
426
  });
403
- expect(flow.getState().creditBalance?.available).toBe(1_000);
427
+ expect(flow.getState().creditBalance?.total).toBe(1_000);
404
428
  });
405
429
 
406
430
  it('reports a pack as pending until the balance revision moves', async () => {
@@ -409,7 +433,7 @@ describe('PurchaseFlow credit packs', () => {
409
433
 
410
434
  await expect(flow.purchaseCreditPack(pack)).resolves.toEqual({
411
435
  status: 'pending',
412
- balance: { suiteSubject: SUBJECT, available: 0, revision: 0 },
436
+ balance: balance(0, 0),
413
437
  });
414
438
  });
415
439
 
@@ -417,14 +441,14 @@ describe('PurchaseFlow credit packs', () => {
417
441
  const { port, backend, flow } = setup(3);
418
442
  await flow.identify(SUBJECT);
419
443
  await flow.refreshCreditBalance();
420
- backend.balance = { suiteSubject: SUBJECT, available: 500, revision: 1 };
444
+ backend.balance = balance(500, 1);
421
445
  port.onPurchase = () => {
422
- backend.balance = { suiteSubject: SUBJECT, available: 1_500, revision: 2 };
446
+ backend.balance = balance(1_500, 2);
423
447
  };
424
448
 
425
449
  await expect(flow.purchaseCreditPack(pack)).resolves.toEqual({
426
450
  status: 'credited',
427
- balance: { suiteSubject: SUBJECT, available: 1_500, revision: 2 },
451
+ balance: balance(1_500, 2),
428
452
  });
429
453
  });
430
454
 
@@ -432,11 +456,11 @@ describe('PurchaseFlow credit packs', () => {
432
456
  const { backend, flow } = setup(3);
433
457
  await flow.identify(SUBJECT);
434
458
  await flow.refreshCreditBalance();
435
- backend.balance = { suiteSubject: SUBJECT, available: 500, revision: 1 };
459
+ backend.balance = balance(500, 1);
436
460
 
437
461
  await expect(flow.purchaseCreditPack(pack)).resolves.toEqual({
438
462
  status: 'pending',
439
- balance: { suiteSubject: SUBJECT, available: 500, revision: 1 },
463
+ balance: balance(500, 1),
440
464
  });
441
465
  });
442
466
 
@@ -454,7 +478,7 @@ describe('PurchaseFlow credit packs', () => {
454
478
  await flow.identify(SUBJECT);
455
479
  backend.balance = null;
456
480
  port.onPurchase = () => {
457
- backend.balance = { suiteSubject: SUBJECT, available: 3_000, revision: 0 };
481
+ backend.balance = balance(3_000, 0);
458
482
  };
459
483
 
460
484
  await expect(flow.purchaseCreditPack(pack)).resolves.toMatchObject({ status: 'credited' });
@@ -477,6 +501,41 @@ describe('PurchaseFlow credit packs', () => {
477
501
  });
478
502
  });
479
503
 
504
+ describe('PurchaseFlow entitlement status', () => {
505
+ it('loads, then turns ready or unavailable, and keeps a verified entitlement on failure', async () => {
506
+ const { backend, flow } = setup();
507
+ expect(flow.getState().entitlementStatus).toBe('signed_out');
508
+ await flow.identify(SUBJECT);
509
+ expect(flow.getState().entitlementStatus).toBe('loading');
510
+
511
+ backend.failNext = true;
512
+ await expect(flow.refreshEntitlement()).rejects.toThrow('backend offline');
513
+ expect(flow.getState().entitlementStatus).toBe('unavailable');
514
+
515
+ backend.entitlement = entitlement(2, ['export']);
516
+ await flow.refreshEntitlement();
517
+ expect(flow.getState().entitlementStatus).toBe('ready');
518
+
519
+ backend.failNext = true;
520
+ await expect(flow.refreshEntitlement()).rejects.toThrow('backend offline');
521
+ expect(flow.getState()).toMatchObject({
522
+ entitlementStatus: 'ready',
523
+ entitlement: { revision: 2 },
524
+ });
525
+
526
+ await flow.signOut();
527
+ expect(flow.getState().entitlementStatus).toBe('signed_out');
528
+ });
529
+
530
+ it('is ready without an entitlement when the session has no suite identity', async () => {
531
+ const { backend, flow } = setup();
532
+ backend.entitlement = null;
533
+ await flow.identify(SUBJECT);
534
+ await flow.refreshEntitlement();
535
+ expect(flow.getState()).toMatchObject({ entitlementStatus: 'ready', entitlement: null });
536
+ });
537
+ });
538
+
480
539
  describe('no-op purchases', () => {
481
540
  it('identifies, sells nothing and keeps gating on the backend entitlement', async () => {
482
541
  const backend = new FakeBackend();
@@ -512,10 +571,22 @@ describe('helpers', () => {
512
571
  });
513
572
 
514
573
  expect(verified).toEqual({
574
+ mode: 'hub',
515
575
  suiteSubject: SUBJECT,
516
576
  tier: 'premium',
517
577
  features: ['export'],
518
578
  revision: 7,
579
+ plansUrl: null,
580
+ billing: null,
581
+ });
582
+ expect(
583
+ entitlementFromTicket(
584
+ { sub: SUBJECT, tier: 'free', features: [], rev: 1, billing: { channel: 'family' } },
585
+ 'https://accounts.example.test/plans',
586
+ ),
587
+ ).toMatchObject({
588
+ billing: { channel: 'family' },
589
+ plansUrl: 'https://accounts.example.test/plans',
519
590
  });
520
591
  expect(hasFeature(verified, 'export')).toBe(true);
521
592
  expect(hasFeature(verified, 'sync')).toBe(false);
package/src/flow.ts CHANGED
@@ -10,8 +10,16 @@ export const DEFAULT_REFRESH_ATTEMPTS = 5;
10
10
  export const DEFAULT_REFRESH_INTERVAL_MS = 2_000;
11
11
  const NO_REVISION = -1;
12
12
 
13
+ /**
14
+ * `loading` until the first read for this identity, `ready` after a verified answer,
15
+ * `unavailable` when a read failed before any verified entitlement arrived. A failed
16
+ * refresh keeps an earlier verified entitlement, like the backend's ticket cache.
17
+ */
18
+ export type EntitlementStatus = 'signed_out' | 'loading' | 'ready' | 'unavailable';
19
+
13
20
  export interface PurchaseState {
14
21
  readonly suiteSubject: string | null;
22
+ readonly entitlementStatus: EntitlementStatus;
15
23
  readonly entitlement: VerifiedEntitlement | null;
16
24
  readonly creditBalance: CreditBalanceSnapshot | null;
17
25
  }
@@ -46,7 +54,12 @@ interface Revisioned {
46
54
  readonly revision: number;
47
55
  }
48
56
 
49
- const SIGNED_OUT: PurchaseState = { suiteSubject: null, entitlement: null, creditBalance: null };
57
+ const SIGNED_OUT: PurchaseState = {
58
+ suiteSubject: null,
59
+ entitlementStatus: 'signed_out',
60
+ entitlement: null,
61
+ creditBalance: null,
62
+ };
50
63
 
51
64
  function wait(milliseconds: number): Promise<void> {
52
65
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
@@ -94,7 +107,7 @@ export class PurchaseFlow {
94
107
  const generation = this.#restart();
95
108
  await this.#port.identify(suiteSubject);
96
109
  this.#assertGeneration(generation);
97
- this.#setState({ ...SIGNED_OUT, suiteSubject });
110
+ this.#setState({ ...SIGNED_OUT, suiteSubject, entitlementStatus: 'loading' });
98
111
  }
99
112
 
100
113
  async signOut(): Promise<void> {
@@ -108,8 +121,20 @@ export class PurchaseFlow {
108
121
 
109
122
  async refreshEntitlement(): Promise<VerifiedEntitlement | null> {
110
123
  const identity = this.#identity();
111
- const entitlement = await this.#backend.refreshEntitlement();
124
+ let entitlement: VerifiedEntitlement | null;
125
+ try {
126
+ entitlement = await this.#backend.refreshEntitlement();
127
+ } catch (error) {
128
+ this.#assertGeneration(identity.generation);
129
+ if (this.#state.entitlement === null) {
130
+ this.#setState({ ...this.#state, entitlementStatus: 'unavailable' });
131
+ }
132
+ throw error;
133
+ }
112
134
  this.#accept(identity, entitlement, 'entitlement');
135
+ if (this.#state.entitlementStatus !== 'ready') {
136
+ this.#setState({ ...this.#state, entitlementStatus: 'ready' });
137
+ }
113
138
  return this.#state.entitlement;
114
139
  }
115
140
 
package/src/index.ts CHANGED
@@ -1,5 +1,9 @@
1
+ export * from './access.js';
2
+ export * from './account-plan.js';
1
3
  export * from './entitlement.js';
2
4
  export * from './errors.js';
3
5
  export * from './flow.js';
4
6
  export * from './noop.js';
7
+ export * from './paywall.js';
8
+ export * from './plans-link.js';
5
9
  export * from './port.js';