@monetize.software/sdk 3.0.0-alpha.0 → 3.0.0-alpha.2

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.
package/README.md CHANGED
@@ -1,24 +1,24 @@
1
1
  # @monetize.software/sdk
2
2
 
3
- SDK 3.0 — bundled billing client и render engine пейвола. Встраивается в расширения Chrome
4
- и веб-сайты через npm / CDN, без iframe и без remote code.
3
+ SDK 3.0 — bundled billing client and paywall render engine. Embeds into Chrome
4
+ extensions and websites via npm / CDN, with no iframe and no remote code.
5
5
 
6
- Статус: **alpha, WIP**. См. [TODO.md](../TODO.md).
6
+ Status: **alpha, WIP**. See [TODO.md](../TODO.md).
7
7
 
8
- ## Три entrypoint'а
8
+ ## Three entrypoints
9
9
 
10
10
  ```ts
11
- // server / headless billing — только API, без UI
11
+ // server / headless billing — API only, no UI
12
12
  import { BillingClient } from '@monetize.software/sdk/core';
13
13
 
14
- // host сам показывает UI, но нужна наша модалка
14
+ // host renders its own UI but needs our modal
15
15
  import { PaywallUI } from '@monetize.software/sdk/ui';
16
16
 
17
- // все в одном — auth-слой подгружается лениво
17
+ // all in one — auth layer is loaded lazily
18
18
  import { PaywallUI } from '@monetize.software/sdk';
19
19
  ```
20
20
 
21
- ## Быстрый старт
21
+ ## Quick start
22
22
 
23
23
  ```ts
24
24
  import { PaywallUI } from '@monetize.software/sdk';
@@ -35,32 +35,32 @@ paywall.on('checkout_started', ({ url }) => {
35
35
  document.getElementById('upgrade').onclick = () => paywall.open();
36
36
  ```
37
37
 
38
- ## Скрипты
38
+ ## Scripts
39
39
 
40
40
  ```bash
41
41
  pnpm install
42
- pnpm dev # локальная демка на http://localhost:5060/demo/
43
- pnpm build # ESM + CJS + .d.ts в dist/
42
+ pnpm dev # local demo at http://localhost:5060/demo/
43
+ pnpm build # ESM + CJS + .d.ts into dist/
44
44
  pnpm typecheck
45
45
  pnpm size # bundle-size gate
46
46
  pnpm test
47
47
  ```
48
48
 
49
- ## Архитектура (коротко)
49
+ ## Architecture (in brief)
50
50
 
51
- - **Preact** (не React) — 3KB вместо 45KB. Critical для bundle-бюджета.
52
- - **Shadow DOM** (`{ mode: 'closed' }`) — изоляция стилей.
53
- - **Tailwind v4**, скомпилированный в CSS-строку и инжектированный в shadow root.
54
- - **Server-driven layout** — JSON-схема блоков (`heading`, `price_grid`, `cta_button`, ...).
55
- SDK умеет рендерить блоки; server управляет порядком, текстами, visibility.
56
- - **Server-driven checkout** — SDK не знает провайдеров (Stripe/Paddle/Chargebee),
57
- просто открывает `checkout_url`, который вернул сервер.
51
+ - **Preact** (not React) — 3KB instead of 45KB. Critical for the bundle budget.
52
+ - **Shadow DOM** (`{ mode: 'closed' }`) — style isolation.
53
+ - **Tailwind v4**, compiled into a CSS string and injected into the shadow root.
54
+ - **Server-driven layout** — JSON schema of blocks (`heading`, `price_grid`, `cta_button`, ...).
55
+ SDK knows how to render blocks; the server controls order, copy, and visibility.
56
+ - **Server-driven checkout** — SDK is provider-agnostic (Stripe/Paddle/Chargebee),
57
+ it just opens the `checkout_url` returned by the server.
58
58
 
59
- ## Метированный AI-прокси (`ApiGatewayClient`)
59
+ ## Metered AI proxy (`ApiGatewayClient`)
60
60
 
61
- Платформа поддерживает прокси-вызовы к OpenAI/Anthropic/любому HTTP-API с
62
- посчётом токенов из `paywall_balances`. SDK даёт тонкий клиент к этому прокси
63
- и хранит локальное состояние балансов.
61
+ The platform supports proxying calls to OpenAI/Anthropic/any HTTP API with
62
+ token accounting against `paywall_balances`. The SDK ships a thin client to
63
+ this proxy and maintains local balance state.
64
64
 
65
65
  ```ts
66
66
  import { BillingClient, AuthClient, QuotaExceededError } from '@monetize.software/sdk/core';
@@ -70,11 +70,11 @@ const billing = new BillingClient({ paywallId: 'pw_abc', auth });
70
70
  const gateway = billing.createApiGatewayClient();
71
71
 
72
72
  billing.onBalanceChange((balances) => {
73
- // Рисуем счётчик квот в UI
73
+ // Render quota counter in UI
74
74
  });
75
75
 
76
76
  try {
77
- // SSE-стрим: возвращается голый Response, без своего парсера.
77
+ // SSE stream: returns a raw Response, no built-in parser.
78
78
  const res = await gateway.call({
79
79
  providerId: 'prov_openai',
80
80
  path: '',
@@ -86,21 +86,21 @@ try {
86
86
  }
87
87
  } catch (e) {
88
88
  if (e instanceof QuotaExceededError) {
89
- paywall.open(); // upgrade-prompt
89
+ paywall.open(); // upgrade prompt
90
90
  } else throw e;
91
91
  }
92
92
  ```
93
93
 
94
- - `BillingClient.createApiGatewayClient()` подключает Bearer из `AuthClient`,
95
- оптимистично декрементит `cachedBalances` на success, ре-фетчит `/balances`
96
- на 402.
97
- - `gateway.call()` отдаёт сырой `Response`. Caller сам решает: `.json()`,
98
- `.body.getReader()`, или async-iter — всё работает из коробки `fetch`.
99
- - На 402 бросается `QuotaExceededError` с `balances`/`queryType`/`currentBalance`.
94
+ - `BillingClient.createApiGatewayClient()` wires the Bearer from `AuthClient`,
95
+ optimistically decrements `cachedBalances` on success, and refetches `/balances`
96
+ on 402.
97
+ - `gateway.call()` returns the raw `Response`. Caller decides: `.json()`,
98
+ `.body.getReader()`, or async-iter — anything that works on a `fetch` Response.
99
+ - On 402, `QuotaExceededError` is thrown with `balances` / `queryType` / `currentBalance`.
100
100
 
101
- ## Нет в этой версии (alpha)
101
+ ## Not in this version (alpha)
102
102
 
103
- - Auth-слой (Google/Apple/Email) — будет после hybrid-бета.
104
- - Трейлы с таймером, A/B-варианты, локализация.
103
+ - Auth layer (Google / Apple / Email) — coming after the hybrid beta.
104
+ - Timer-based trials, A/B variants, localization.
105
105
  - Framework adapters (`@monetize/react`).
106
106
  - Tests.
@@ -1197,6 +1197,13 @@ function Zt({
1197
1197
  if (e.auth)
1198
1198
  return e.auth.onAuthChange((h) => m(h));
1199
1199
  }, [e.auth]), M(() => {
1200
+ if (typeof e.onBootstrapChange == "function")
1201
+ return e.onBootstrapChange((h) => {
1202
+ p(
1203
+ (u) => u.status === "ready" ? { status: "ready", data: h } : u
1204
+ );
1205
+ });
1206
+ }, [e]), M(() => {
1200
1207
  if (!t || c.status === "ready" || c.status === "loading") return;
1201
1208
  let h = !1;
1202
1209
  return p({ status: "loading" }), e.bootstrap().then((u) => {
@@ -1727,6 +1734,19 @@ class he {
1727
1734
  onUserChange(t) {
1728
1735
  return this.on("userChange", t);
1729
1736
  }
1737
+ /**
1738
+ * Заменить cachedBootstrap живыми данными — для preview-режима в редакторе
1739
+ * админки. Если модалка открыта, PaywallRoot подписан на onBootstrapChange
1740
+ * и перерендерится мгновенно. До open() — затравка для bootstrap()-effect'а.
1741
+ *
1742
+ * См. {@link BillingClientOptions.preview} — обычно эту опцию ставят на
1743
+ * клиент, чтобы заодно отключить сетевой revalidate. setBootstrap технически
1744
+ * работает и в production-режиме, но конкуренция с revalidate'ом из сети
1745
+ * почти всегда нежелательна.
1746
+ */
1747
+ setBootstrap(t) {
1748
+ this.billing.setBootstrap(t);
1749
+ }
1730
1750
  on(t, i) {
1731
1751
  let n = this.listeners.get(t);
1732
1752
  return n || (n = /* @__PURE__ */ new Set(), this.listeners.set(t, n)), n.add(i), () => n.delete(i);
@@ -2206,4 +2226,4 @@ export {
2206
2226
  he as P,
2207
2227
  $t as b
2208
2228
  };
2209
- //# sourceMappingURL=PaywallUI-BHp9afFC.js.map
2229
+ //# sourceMappingURL=PaywallUI-CRTEPjJm.js.map