@neetru/sdk 1.2.0 → 2.1.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 (77) hide show
  1. package/CHANGELOG.md +284 -244
  2. package/README.md +194 -194
  3. package/dist/auth.cjs +3740 -345
  4. package/dist/auth.cjs.map +1 -1
  5. package/dist/auth.d.cts +5 -1
  6. package/dist/auth.d.ts +5 -1
  7. package/dist/auth.mjs +3740 -345
  8. package/dist/auth.mjs.map +1 -1
  9. package/dist/catalog.cjs.map +1 -1
  10. package/dist/catalog.d.cts +5 -1
  11. package/dist/catalog.d.ts +5 -1
  12. package/dist/catalog.mjs.map +1 -1
  13. package/dist/checkout.cjs.map +1 -1
  14. package/dist/checkout.d.cts +5 -1
  15. package/dist/checkout.d.ts +5 -1
  16. package/dist/checkout.mjs.map +1 -1
  17. package/dist/collection-ref-BBvTTXoG.d.cts +423 -0
  18. package/dist/collection-ref-BBvTTXoG.d.ts +423 -0
  19. package/dist/db-react.cjs +136 -0
  20. package/dist/db-react.cjs.map +1 -0
  21. package/dist/db-react.d.cts +99 -0
  22. package/dist/db-react.d.ts +99 -0
  23. package/dist/db-react.mjs +112 -0
  24. package/dist/db-react.mjs.map +1 -0
  25. package/dist/db.cjs +3599 -131
  26. package/dist/db.cjs.map +1 -1
  27. package/dist/db.d.cts +5 -8
  28. package/dist/db.d.ts +5 -8
  29. package/dist/db.mjs +3596 -131
  30. package/dist/db.mjs.map +1 -1
  31. package/dist/entitlements.cjs.map +1 -1
  32. package/dist/entitlements.d.cts +5 -1
  33. package/dist/entitlements.d.ts +5 -1
  34. package/dist/entitlements.mjs.map +1 -1
  35. package/dist/errors.cjs.map +1 -1
  36. package/dist/errors.mjs.map +1 -1
  37. package/dist/index.cjs +3957 -342
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +13 -6
  40. package/dist/index.d.ts +13 -6
  41. package/dist/index.mjs +3877 -263
  42. package/dist/index.mjs.map +1 -1
  43. package/dist/mocks.cjs +183 -7
  44. package/dist/mocks.cjs.map +1 -1
  45. package/dist/mocks.d.cts +18 -5
  46. package/dist/mocks.d.ts +18 -5
  47. package/dist/mocks.mjs +183 -7
  48. package/dist/mocks.mjs.map +1 -1
  49. package/dist/notifications.cjs.map +1 -1
  50. package/dist/notifications.d.cts +5 -1
  51. package/dist/notifications.d.ts +5 -1
  52. package/dist/notifications.mjs.map +1 -1
  53. package/dist/react.cjs.map +1 -1
  54. package/dist/react.d.cts +5 -1
  55. package/dist/react.d.ts +5 -1
  56. package/dist/react.mjs.map +1 -1
  57. package/dist/support.cjs.map +1 -1
  58. package/dist/support.d.cts +5 -1
  59. package/dist/support.d.ts +5 -1
  60. package/dist/support.mjs.map +1 -1
  61. package/dist/telemetry.cjs.map +1 -1
  62. package/dist/telemetry.d.cts +5 -1
  63. package/dist/telemetry.d.ts +5 -1
  64. package/dist/telemetry.mjs.map +1 -1
  65. package/dist/types-B1jylbMC.d.ts +1364 -0
  66. package/dist/types-Kmt4y1FQ.d.cts +1364 -0
  67. package/dist/usage.cjs.map +1 -1
  68. package/dist/usage.d.cts +5 -1
  69. package/dist/usage.d.ts +5 -1
  70. package/dist/usage.mjs.map +1 -1
  71. package/dist/webhooks.cjs.map +1 -1
  72. package/dist/webhooks.d.cts +5 -1
  73. package/dist/webhooks.d.ts +5 -1
  74. package/dist/webhooks.mjs.map +1 -1
  75. package/package.json +133 -111
  76. package/dist/types-CQAfwqUS.d.cts +0 -654
  77. package/dist/types-CQAfwqUS.d.ts +0 -654
package/CHANGELOG.md CHANGED
@@ -1,244 +1,284 @@
1
- # Changelog
2
-
3
- All notable changes to `@neetru/sdk` will be documented in this file.
4
-
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
-
8
- ## [Unreleased]
9
-
10
- ### Planned (post-1.2)
11
- - size-limit budget no CI (<12KB gz core com db namespace).
12
- - CDN distribution (`cdn.neetru.com/sdk/v1/`).
13
- - Endpoint batch `/api/v1/sdk/telemetry/batch` (substitui drenagem N×1 do `track()` por 1 request).
14
-
15
- ## [1.2.0] - 2026-05-19 — **Webhooks + Notifications + DX (cache, retry, batch)**
16
-
17
- Release de qualidade fechando 3 CRITICAL + 6 IMPORTANT do code review interno + 4 melhorias de DX. Adiciona `webhooks` + `notifications` no `NeetruClient`.
18
-
19
- ### Added
20
- - **`client.webhooks`** — `register`/`list`/`unregister`/`test` pra endpoints HTTP do produto receberem eventos do Core (subscription.activated, usage.quota_exceeded, etc).
21
- - **`verifyWebhookSignature(payload, signature, secret)`** util pura (HMAC SHA-256 constant-time compare via `node:crypto`) pra consumidor validar payloads recebidos.
22
- - **`client.notifications`** `send`/`list`/`markRead`/`dismiss` pra produto integrar com a bandeja in-app do Neetru.
23
- - **`client.telemetry.track(input)`** + `client.telemetry.flush()` fire-and-forget batch (500ms debounce). Ideal pra alta frequência (page-views, cliques). `event()` segue como single-shot com `eventId` ack.
24
- - **`client.entitlements.check(..., { cacheBust })`** cache LRU em memória (60s TTL, 100 entries). Corta 90%+ requests em renders repetidos do `<EntitlementGate>`. `cacheBust: true` força ida ao servidor.
25
- - **httpRequest retry/backoff** 2 retries default em `rate_limited` (429), `server_error` (5xx), `network_error`. Honra `Retry-After` header. Caller opt-out com `opts.retries: 0`.
26
- - **Subpaths novos**: `@neetru/sdk/webhooks`, `@neetru/sdk/notifications`.
27
-
28
- ### Changed
29
- - **`client.catalog.list()` / `get()`** agora consomem `/api/sdk/v1/catalog` (público, sem Bearer) em vez de `/api/v1/cli/catalog` (staff). Consumidor não precisa mais de chave staff só pra ler catálogo. `includeDrafts` é ignorado — rascunhos só via CLI.
30
- - **`auth.signOut()`** revoga token em `auth.neetru.com/api/v1/oauth/revoke` (canônico), não mais `api.neetru.com/oauth/revoke` (404 em prod).
31
- - **`<EntitlementGate>`** passa `tenantId` (do `client.config.tenantId`) pra `usage.check`. Sem tenantId, cai pra `entitlements.check` em vez de chamar `usage.check` e travar em `validation_failed` silencioso.
32
- - **`engines.node`** subiu pra `>=20` (alinha com `target: node20` do tsup; Node 18 EOL).
33
-
34
- ### Fixed
35
- - **CRITICAL** `webhooks` e `notifications` lançavam `'invalid_input'`, código ausente da union `NeetruErrorCode`. Todas as 17 ocorrências viraram `'validation_failed'`.
36
- - **CRITICAL** `telemetry.log()` chamava `/sdk/v1/telemetry/log` (404). Corrigido pra `/api/sdk/v1/telemetry/log`.
37
- - **CRITICAL**`db` namespace tinha o mesmo bug em 6 paths (`/sdk/v1/datastore/...`). Corrigido em massa pra `/api/sdk/v1/datastore/...`.
38
- - **CRITICAL**8 `httpRequest` calls em `webhooks` e `notifications` não passavam `requireAuth: true` — todos hits em prod retornavam 401. Corrigido.
39
- - **`MockSupport.mockTicketSeq`** virou instance field (era module-level, poluía tests entre suites).
40
- - **`db.list()`** removeu variável `query` dead code (refactor incompleto de pre-1.1).
41
-
42
- ### Internal
43
- - 51 testes novos (webhooks: 22, notifications: 20, react: 9). Total: 215 testes (16 files), 100% passing. tsc clean.
44
- - `api-surface-stability.test.ts` agora lock `webhooks` + `notifications` no `NeetruClient`.
45
-
46
- ## [1.1.0] - 2026-05-08 **Checkout namespace + React helpers**
47
-
48
- Adiciona o namespace `client.checkout` (start/get/cancel intent) com auto-redirect
49
- em browser. Suporte ao fluxo Sprint 13 onde produtos SaaS delegam checkout pro
50
- portal `minhaconta.neetru.com` via `POST /api/v1/checkout/intents`.
51
-
52
- ### Added
53
- - **`client.checkout.start({productId, planId, callbackUrl, tenantType?, tenantId?})`** — cria
54
- `checkout_intents/{intentId}` no Core e (em browser) redireciona automaticamente
55
- pra `minhaconta.neetru.com/portal/checkout/{intentId}`. Em Node/SSR retorna
56
- `{intentId, redirectUrl}` sem efeito colateral.
57
- - **`client.checkout.get(intentId)`** estado atual do intent.
58
- - **`client.checkout.cancel(intentId)`** — marca intent como `cancelled`.
59
- - **Subpath `@neetru/sdk/react`** — componente `<CheckoutLink>` (wrapper de `<a>`
60
- que dispara `start()` no click) + `<EntitlementGate mode="block|readonly">`
61
- + hook `useEntitlementContext()` pra desabilitar escritas quando free tier
62
- estoura limite (decisão CEO §5 read-only sempre, não hard-block).
63
- - **`MockCheckout`** — implementação dev (`NEETRU_ENV=dev`) sem network. Retorna
64
- URL fake `https://localhost:9003/portal/checkout/{intentId}` pra dev externo
65
- testar UI sem provisionar conta Neetru.
66
- - **Peer dep `react ^18 || ^19`** marcado opcional (só carregado se import `/react`).
67
-
68
- ### Changed
69
- - `VERSION` const bump `1.0.0 1.1.0`.
70
- - `NeetruClient.checkout` adicionado backward-compatible (caller que não usa
71
- o namespace não é afetado).
72
-
73
- ### Notes
74
- - API stability test (`api-surface-stability.test.ts`) atualizado pra incluir
75
- `checkout` no inventário canônico.
76
-
77
- ## [1.0.0] - 2026-05-06**GA (General Availability)**
78
-
79
- Marco de estabilidade. A partir desta versão, **a superfície pública do SDK
80
- está congelada** breaking changes em majors (semver estrito).
81
-
82
- ### Added
83
- - **API stability lock** todos os contratos (`createNeetruClient`,
84
- `NeetruClient`, namespaces `auth`/`catalog`/`entitlements`/`telemetry`/
85
- `usage`/`support`/`db`, `NeetruError`) ficam estáveis em v1.x. Coberto
86
- por `api-surface-stability.test.ts` que falha o build se algum método
87
- muda forma.
88
- - **JSDoc completo** em toda função/método público base pra `npm run docs:gen`
89
- (typedoc `sdk/docs-html/`).
90
- - **`docs:gen` script** + `scripts/typedoc.config.json` gera HTML
91
- navigable das APIs.
92
- - **`engines.node`** relaxado de `>=20` → `>=18` (suporta runtimes Node 18 LTS
93
- ainda em uso por consumers).
94
-
95
- ### Changed
96
- - `VERSION` bump `0.3.0` → `1.0.0`.
97
- - README atualizado com seção de migração v0.3 → v1.0 (no breaking changes —
98
- upgrade transparente).
99
-
100
- ### Migration v0.3 v1.0
101
- - **Sem breaking changes.** Upgrade direto via `npm install @neetru/sdk@1.0.0`.
102
- - `initNeetru` continua deprecated mas funcional. **Será removido em v2.0.0.**
103
- - `NeetruConfig` continua deprecated. Use `NeetruClientConfig`.
104
-
105
- ### Stability promise (v1.x)
106
- A partir de v1.0:
107
- - Métodos novos podem ser adicionados a namespaces existentes (minor bump).
108
- - Métodos podem ser marcados `@deprecated` em qualquer minor — só removidos
109
- em major.
110
- - Tipos nunca ganham campos required em minor ( optional ou via union).
111
- - `NeetruErrorCode` é union fechado em v1.0 — qualquer novo código bumpa minor.
112
-
113
- ### Notes
114
- - Pacote ainda **privado** (`private: true`). Publicação no npm é
115
- responsabilidade do owner — gate no CHANGELOG continua trancado até decisão.
116
-
117
- ## [0.3.0] - 2026-05-06
118
-
119
- ### Added
120
- - Namespace `client.db` (v0.3) wrapper minimalista pra coleções tenant-scoped:
121
- - `client.db.collection(name).list({ limit? })`
122
- - `client.db.collection(name).get(id)` (retorna null em not_found)
123
- - `client.db.collection(name).set(id, data)` upsert
124
- - `client.db.collection(name).remove(id)` delete
125
- - Endpoints: `/sdk/v1/datastore/{collection}/{id?}` (placeholder REST Sprint 9
126
- finaliza; SDK expõe interface estável).
127
- - `MockDb` (in-memory) ativo em `NEETRU_ENV=dev`.
128
- - Namespace `client.usage` ganhou `report()` e `check()`:
129
- - `usage.report(resource, qty?)` → `POST /sdk/v1/usage/record` canônico
130
- (Sprint 7) incrementa atomicamente `usage_counters/{tid}_{pid}_{r}_{yyyymm}`.
131
- - `usage.check(resource)` → `GET /sdk/v1/entitlements?productId&tenantId&feature` —
132
- retorna `{allowed, reason, remaining, limit, planId, planFeatures}`.
133
- - `NeetruClientConfig.productId` / `.tenantId` — defaults pra `usage.report` /
134
- `usage.check` / `db.collection` quando não passado em options.
135
- - Mock helpers: `MockDb`, `MockUsage.report()`, `MockUsage.check()`.
136
-
137
- ### Changed
138
- - `VERSION` bump `0.2.0` → `0.3.0`.
139
- - `NeetruClient` agora expõe `.db` além dos antigos.
140
- - `ResolvedConfig` ganhou `productId` + `tenantId` opcionais.
141
-
142
- ### Backend (acompanha esta release)
143
- - Novos endpoints (Sprint 7):
144
- - `POST /sdk/v1/usage/record` — atomic increment + 80%/100% notifications + audit.
145
- - `GET /sdk/v1/entitlements` lookup canônico subscription→plan→counter.
146
- - `POST /sdk/v1/telemetry/log` — batch logger pra `logs/{productId}/{yyyymmdd}/`.
147
-
148
- ## [0.2.0] - 2026-05-06
149
-
150
- ### Added
151
- - Namespace `client.auth` (v0.2OIDC + dev mocks):
152
- - `signIn(options?)` — redireciona pra auth.neetru.com authorize endpoint
153
- (browser) ou retorna mock user em dev (`NEETRU_ENV=dev`).
154
- - `signOut()` limpa `localStorage.neetru_id_token` + revoga refresh
155
- server-side (best-effort).
156
- - `getUser()` — decodifica id_token cached e retorna `NeetruUser` ou null.
157
- - `onAuthStateChanged(listener)` sub a mudanças, dispatcha sync no subscribe.
158
- - Namespace `client.usage` (v0.2 — meter):
159
- - `track(event, props?)` → `POST /sdk/v1/usage/record` com Bearer.
160
- - `getQuota(metric)` `GET /sdk/v1/usage/quota?metric=` returns
161
- `{ metric, used, limit, plan, resetsAt? }`.
162
- - Namespace `client.support` (v0.2 tickets):
163
- - `createTicket({subject, message, severity?, productSlug?})`
164
- `POST /api/v1/products/{slug}/tickets` (default `_default`).
165
- - `listMyTickets()` `GET ...` retorna array (aceita envelope `{tickets:[]}`).
166
- - `mocks` module (`@neetru/sdk/mocks`):
167
- - `MockAuth`, `MockUsage`, `MockSupport`, `MockEntitlements` overridáveis
168
- via `createNeetruClient({ mocks: { auth: MockAuth(...), ... } })`.
169
- - `DEV_FIXTURE_USER` constante exportada.
170
- - `NEETRU_ENV` resolution chain: config arg > `process.env.NEETRU_ENV` >
171
- `globalThis.NEETRU_ENV` > default `prod`. `dev` ativa mocks automáticos.
172
- - Subpath exports adicionais: `@neetru/sdk/{auth,usage,support,mocks}`.
173
- - Tipos novos: `NeetruUser`, `AuthNamespace`, `UsageNamespace`,
174
- `SupportNamespace`, `SignInOptions`, `SupportTicket`, `UsageQuota`,
175
- `NeetruEnv`, `CreateTicketInput`.
176
-
177
- ### Changed
178
- - `VERSION` bump `0.1.0` → `0.2.0`.
179
- - `NeetruClientConfig` ganhou campos `env` + `mocks`.
180
- - `ResolvedConfig` ganhou `env` resolved.
181
- - `NeetruClient` agora expõe `.auth`, `.usage`, `.support` além dos antigos.
182
-
183
- ### Backend (acompanha esta release — endpoints documentados em `docs/SDK_OPENAPI.md`)
184
- - `POST /sdk/v1/usage/record` — record event meterado.
185
- - `GET /sdk/v1/usage/quota?metric=`ler quota atual.
186
- - `POST /api/v1/products/{slug}/tickets` — criar ticket.
187
- - `GET /api/v1/products/{slug}/tickets` — listar meus tickets.
188
- - (auth) `auth.neetru.com/oauth/authorize` já live (Sprint 1 OIDC).
189
- - (auth) `auth.neetru.com/oauth/revoke` — revoga refresh token.
190
-
191
- ### Notes
192
- - Pacote ainda **privado** (`private: true`) não publicado no npm.
193
- - Carry-over: integração OIDC live aguarda owner habilitar redirect_uri pro
194
- domain do consumer (configurar em `oidc_clients/{client_id}.redirect_uris`).
195
- - TODO: `support.listMyTickets` precisa parametrizar productSlug (fixed
196
- `_default` na v0.2).
197
-
198
- ## [0.1.0] - 2026-05-05
199
-
200
- ### Added
201
- - `createNeetruClient(config)` factory entry point principal.
202
- - Resolve `apiKey` (arg explícito > `NEETRU_API_KEY` env em Node).
203
- - Resolve `baseUrl` (default `https://api.neetru.com`).
204
- - Resolve `fetch` (arg > `globalThis.fetch`).
205
- - Namespace `client.catalog`:
206
- - `list(opts?)` `GET /api/v1/cli/catalog`. Aceita `includeDrafts`.
207
- - `get(slug)` `GET /api/v1/cli/catalog/{slug}`.
208
- - Namespace `client.entitlements`:
209
- - `check(slug, feature)` boolean.
210
- - `checkDetailed(slug, feature)` `EntitlementCheck` com `reason`.
211
- - Backed por `GET /api/v1/sdk/entitlements/check`.
212
- - Namespace `client.telemetry`:
213
- - `event({ name, properties?, timestamp? })` `POST /api/v1/sdk/telemetry/event`.
214
- - Subpath exports map: `@neetru/sdk/{catalog,entitlements,telemetry,errors}`.
215
- - HTTP transport com mapeamento status → `NeetruError.code` estável.
216
- - Tipos exportados: `NeetruClient`, `NeetruClientConfig`, `Product`, `ProductPlan`,
217
- `EntitlementCheck`, `TelemetryEventInput`, `TelemetryEventAck`, `NeetruErrorCode`.
218
- - Compat alias `initNeetru` (deprecated, será removido em v1.0).
219
-
220
- ### Changed
221
- - `VERSION` bump `0.0.1` `0.1.0`.
222
- - tsup config multi-entry pra subpath imports.
223
-
224
- ### Backend (acompanha esta release)
225
- - `GET /api/v1/cli/catalog/{slug}`produto único.
226
- - `GET /api/v1/sdk/entitlements/check?slug=&feature=`verificação por user.
227
- - `POST /api/v1/sdk/telemetry/event` — persiste em `usage_events`.
228
-
229
- ### Notes
230
- - Pacote ainda **privado** (`private: true`). Publicação no npm é
231
- responsabilidade do owner em Sprint 6.
232
- - API instável; pré-1.0 segue regra "breaking allowed em qualquer minor".
233
-
234
- ## [0.0.1] - 2026-05-04
235
-
236
- ### Added
237
- - Scaffold inicial do pacote `@neetru/sdk` (private, não publicado no npm ainda).
238
- - `initNeetru(config)` com validação de `apiUrl` e injeção opcional de `fetch`.
239
- - `NeetruError` com `code`, `status` e `requestId` opcionais.
240
- - `NeetruConfig` e `NeetruClient` types públicos.
241
- - `VERSION` const exportada.
242
- - Build pipeline com tsup (dual ESM + CJS + `.d.ts`).
243
- - README + CHANGELOG.
244
- - `tsconfig.json` strict ES2022 ESNext.
1
+ # Changelog
2
+
3
+ All notable changes to `@neetru/sdk` will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Planned (post-2.0)
11
+ - size-limit budget no CI (<12KB gz core com db namespace).
12
+ - CDN distribution (`cdn.neetru.com/sdk/v2/`).
13
+ - Endpoint batch `/api/v1/sdk/telemetry/batch` (substitui drenagem N×1 do `track()` por 1 request).
14
+
15
+ ## [2.0.0] - 2026-05-22 — **client.db NeetruDb (Documentos engine-aware + SQL) [M2]**
16
+
17
+ Major bump breaking changes no namespace `db`. Liga todos os building blocks M2 na superfície pública.
18
+
19
+ ### Breaking Changes
20
+
21
+ - **`client.db`** troca de `DbNamespace` (v0.3 REST simples) para `NeetruDb` (v2.0 offline-first engine-aware).
22
+ - `collection().list()` agora retorna `DbListResult<T>` (com `docs`, `nextCursor`, `fromCache`, `stale`, `hasPendingWrites`, `changes`) em vez de `T[]`.
23
+ - `collection().get(id)` retorna `DbGetResult<T> | null` em vez de `T | null`.
24
+ - `db_unavailable` não significa mais "sem rede" ciclo de vida do banco. Offline é transparente.
25
+ - Novos métodos obrigatórios na superfície: `sql()`, `syncState`, `flush()`, `clearCache()`, `getConflicts()`, `onSyncStateChanged()`, `batch()`, `onDoc()`, `onSnapshot()`, `doc()`.
26
+ - **`db.sql(schema)` lança `NeetruDbError('db_unavailable')` em `NEETRU_ENV=dev`** — sem Postgres local, sem acesso SQL. Use `neetru dev` para subir o container.
27
+ - **`initNeetru`** — mantido como stub funcional mas não mapeia mais `apiUrl → baseUrl`. Remover em v3.0.
28
+ - **`MockDb`** foi atualizado para implementar `NeetruDb` (v2.0) em vez de `DbNamespace` (v0.3).
29
+
30
+ ### Added
31
+
32
+ - **`client.db.collection<T>(name)`** retorna `DbCollectionRef<T>` offline-first, engine-aware. Funciona sem rede. Sync automático quando conectado.
33
+ - CRUD: `add`, `set`, `update`, `remove`, `get`, `list` (com query, cursor, orderBy, where, limit).
34
+ - Batch: `batch(ops)` — operações atômicas (client-side).
35
+ - Realtime: `onSnapshot(query, cb)`, `onDoc(id, cb)` subscriptions permanentes, delivery imediato do cache.
36
+ - Doc ref: `doc(id).get()`, `.set()`, `.update()`, `.remove()`, `.onSnapshot()`.
37
+ - **`client.db.sql<TSchema>(schema)`**lease SQL. Retorna `NeetruSqlClient<TSchema>` com `orm` (Drizzle `NodePgDatabase`) + `transaction()` + `close()`.
38
+ - **`client.db.syncState`**estado de sincronização observável (`status`, `pendingWrites`, `lastSyncedAt`, `isLeaderTab`).
39
+ - **`client.db.onSyncStateChanged(cb)`** subscrição de mudanças de sync state.
40
+ - **`client.db.flush()`** força ciclo de sync imediato.
41
+ - **`client.db.clearCache(collections?)`** — limpa o cache local (IndexedDB).
42
+ - **`client.db.getConflicts(collection?)`** — lista conflitos LWW pendentes.
43
+ - **Engine detection** via `NeetruDbOptions.engine`: `'firestore'` | `'nosql-vm'` | `'rest'` (default MVP).
44
+ - **Subpath `@neetru/sdk/db/react`** hooks React: `useCollection`, `useDoc` (exporta via `dist/db-react.{mjs,cjs}`).
45
+ - **Novos tipos públicos exportados**: `NeetruDb`, `NeetruDbEngine`, `NeetruDbOptions`, `NeetruSqlClient`, `DbSqlLease`, `DbCollectionRef`, `DbDocRef`, `DbQuery`, `DbDoc`, `DbListResult`, `DbGetResult`, `DbBatchOp`, `DbChangeType`, `NeetruDbError`, `NeetruDbErrorCode`.
46
+ - **`createNeetruDb(config, opts)`**factory async (para uso fora do `createNeetruClient`).
47
+ - **`createNeetruDbSync(config, opts)`** — factory sync com lazy init IndexedDB (usada internamente em `createNeetruClient`).
48
+
49
+ ### Changed
50
+
51
+ - **`NeetruClientConfig.db`** — aceita `NeetruDbOptions` (engine, dbId, collections, dbName, etc.).
52
+ - **`client.config.mocks.db`** — agora é `NeetruDb` em vez de `DbNamespace`.
53
+ - **`VERSION`** bumped para `'2.0.0'`.
54
+
55
+ ## [1.2.0] - 2026-05-19 — **Webhooks + Notifications + DX (cache, retry, batch)**
56
+
57
+ Release de qualidade fechando 3 CRITICAL + 6 IMPORTANT do code review interno + 4 melhorias de DX. Adiciona `webhooks` + `notifications` no `NeetruClient`.
58
+
59
+ ### Added
60
+ - **`client.webhooks`** `register`/`list`/`unregister`/`test` pra endpoints HTTP do produto receberem eventos do Core (subscription.activated, usage.quota_exceeded, etc).
61
+ - **`verifyWebhookSignature(payload, signature, secret)`** — util pura (HMAC SHA-256 constant-time compare via `node:crypto`) pra consumidor validar payloads recebidos.
62
+ - **`client.notifications`** `send`/`list`/`markRead`/`dismiss` pra produto integrar com a bandeja in-app do Neetru.
63
+ - **`client.telemetry.track(input)`** + `client.telemetry.flush()` fire-and-forget batch (500ms debounce). Ideal pra alta frequência (page-views, cliques). `event()` segue como single-shot com `eventId` ack.
64
+ - **`client.entitlements.check(..., { cacheBust })`** — cache LRU em memória (60s TTL, 100 entries). Corta 90%+ requests em renders repetidos do `<EntitlementGate>`. `cacheBust: true` força ida ao servidor.
65
+ - **httpRequest retry/backoff** 2 retries default em `rate_limited` (429), `server_error` (5xx), `network_error`. Honra `Retry-After` header. Caller opt-out com `opts.retries: 0`.
66
+ - **Subpaths novos**: `@neetru/sdk/webhooks`, `@neetru/sdk/notifications`.
67
+
68
+ ### Changed
69
+ - **`client.catalog.list()` / `get()`** agora consomem `/api/sdk/v1/catalog` (público, sem Bearer) em vez de `/api/v1/cli/catalog` (staff). Consumidor não precisa mais de chave staff só pra ler catálogo. `includeDrafts` é ignorado — rascunhos só via CLI.
70
+ - **`auth.signOut()`** revoga token em `auth.neetru.com/api/v1/oauth/revoke` (canônico), não mais `api.neetru.com/oauth/revoke` (404 em prod).
71
+ - **`<EntitlementGate>`** passa `tenantId` (do `client.config.tenantId`) pra `usage.check`. Sem tenantId, cai pra `entitlements.check` em vez de chamar `usage.check` e travar em `validation_failed` silencioso.
72
+ - **`engines.node`** subiu pra `>=20` (alinha com `target: node20` do tsup; Node 18 EOL).
73
+
74
+ ### Fixed
75
+ - **CRITICAL** — `webhooks` e `notifications` lançavam `'invalid_input'`, código ausente da union `NeetruErrorCode`. Todas as 17 ocorrências viraram `'validation_failed'`.
76
+ - **CRITICAL** — `telemetry.log()` chamava `/sdk/v1/telemetry/log` (404). Corrigido pra `/api/sdk/v1/telemetry/log`.
77
+ - **CRITICAL**`db` namespace tinha o mesmo bug em 6 paths (`/sdk/v1/datastore/...`). Corrigido em massa pra `/api/sdk/v1/datastore/...`.
78
+ - **CRITICAL** — 8 `httpRequest` calls em `webhooks` e `notifications` não passavam `requireAuth: true` — todos hits em prod retornavam 401. Corrigido.
79
+ - **`MockSupport.mockTicketSeq`** virou instance field (era module-level, poluía tests entre suites).
80
+ - **`db.list()`** removeu variável `query` dead code (refactor incompleto de pre-1.1).
81
+
82
+ ### Internal
83
+ - 51 testes novos (webhooks: 22, notifications: 20, react: 9). Total: 215 testes (16 files), 100% passing. tsc clean.
84
+ - `api-surface-stability.test.ts` agora lock `webhooks` + `notifications` no `NeetruClient`.
85
+
86
+ ## [1.1.0] - 2026-05-08 **Checkout namespace + React helpers**
87
+
88
+ Adiciona o namespace `client.checkout` (start/get/cancel intent) com auto-redirect
89
+ em browser. Suporte ao fluxo Sprint 13 onde produtos SaaS delegam checkout pro
90
+ portal `minhaconta.neetru.com` via `POST /api/v1/checkout/intents`.
91
+
92
+ ### Added
93
+ - **`client.checkout.start({productId, planId, callbackUrl, tenantType?, tenantId?})`** — cria
94
+ `checkout_intents/{intentId}` no Core e (em browser) redireciona automaticamente
95
+ pra `minhaconta.neetru.com/portal/checkout/{intentId}`. Em Node/SSR retorna
96
+ `{intentId, redirectUrl}` sem efeito colateral.
97
+ - **`client.checkout.get(intentId)`** estado atual do intent.
98
+ - **`client.checkout.cancel(intentId)`** — marca intent como `cancelled`.
99
+ - **Subpath `@neetru/sdk/react`** — componente `<CheckoutLink>` (wrapper de `<a>`
100
+ que dispara `start()` no click) + `<EntitlementGate mode="block|readonly">`
101
+ + hook `useEntitlementContext()` pra desabilitar escritas quando free tier
102
+ estoura limite (decisão CEO §5 read-only sempre, não hard-block).
103
+ - **`MockCheckout`** — implementação dev (`NEETRU_ENV=dev`) sem network. Retorna
104
+ URL fake `https://localhost:9003/portal/checkout/{intentId}` pra dev externo
105
+ testar UI sem provisionar conta Neetru.
106
+ - **Peer dep `react ^18 || ^19`** marcado opcional (só carregado se import `/react`).
107
+
108
+ ### Changed
109
+ - `VERSION` const bump `1.0.0 → 1.1.0`.
110
+ - `NeetruClient.checkout` adicionado backward-compatible (caller que não usa
111
+ o namespace não é afetado).
112
+
113
+ ### Notes
114
+ - API stability test (`api-surface-stability.test.ts`) atualizado pra incluir
115
+ `checkout` no inventário canônico.
116
+
117
+ ## [1.0.0] - 2026-05-06 — **GA (General Availability)**
118
+
119
+ Marco de estabilidade. A partir desta versão, **a superfície pública do SDK
120
+ está congelada** breaking changes em majors (semver estrito).
121
+
122
+ ### Added
123
+ - **API stability lock** — todos os contratos (`createNeetruClient`,
124
+ `NeetruClient`, namespaces `auth`/`catalog`/`entitlements`/`telemetry`/
125
+ `usage`/`support`/`db`, `NeetruError`) ficam estáveis em v1.x. Coberto
126
+ por `api-surface-stability.test.ts` que falha o build se algum método
127
+ muda forma.
128
+ - **JSDoc completo** em toda função/método público — base pra `npm run docs:gen`
129
+ (typedoc → `sdk/docs-html/`).
130
+ - **`docs:gen` script** + `scripts/typedoc.config.json` — gera HTML
131
+ navigable das APIs.
132
+ - **`engines.node`** relaxado de `>=20` `>=18` (suporta runtimes Node 18 LTS
133
+ ainda em uso por consumers).
134
+
135
+ ### Changed
136
+ - `VERSION` bump `0.3.0` → `1.0.0`.
137
+ - README atualizado com seção de migração v0.3 → v1.0 (no breaking changes —
138
+ upgrade transparente).
139
+
140
+ ### Migration v0.3 v1.0
141
+ - **Sem breaking changes.** Upgrade direto via `npm install @neetru/sdk@1.0.0`.
142
+ - `initNeetru` continua deprecated mas funcional. **Será removido em v2.0.0.**
143
+ - `NeetruConfig` continua deprecated. Use `NeetruClientConfig`.
144
+
145
+ ### Stability promise (v1.x)
146
+ A partir de v1.0:
147
+ - Métodos novos podem ser adicionados a namespaces existentes (minor bump).
148
+ - Métodos podem ser marcados `@deprecated` em qualquer minor — só removidos
149
+ em major.
150
+ - Tipos nunca ganham campos required em minor (só optional ou via union).
151
+ - `NeetruErrorCode` é union fechado em v1.0qualquer novo código bumpa minor.
152
+
153
+ ### Notes
154
+ - Pacote ainda **privado** (`private: true`). Publicação no npm é
155
+ responsabilidade do owner — gate no CHANGELOG continua trancado até decisão.
156
+
157
+ ## [0.3.0] - 2026-05-06
158
+
159
+ ### Added
160
+ - Namespace `client.db` (v0.3) wrapper minimalista pra coleções tenant-scoped:
161
+ - `client.db.collection(name).list({ limit? })`
162
+ - `client.db.collection(name).get(id)` (retorna null em not_found)
163
+ - `client.db.collection(name).set(id, data)` upsert
164
+ - `client.db.collection(name).remove(id)` delete
165
+ - Endpoints: `/sdk/v1/datastore/{collection}/{id?}` (placeholder REST Sprint 9
166
+ finaliza; SDK expõe interface estável).
167
+ - `MockDb` (in-memory) ativo em `NEETRU_ENV=dev`.
168
+ - Namespace `client.usage` ganhou `report()` e `check()`:
169
+ - `usage.report(resource, qty?)` `POST /sdk/v1/usage/record` canônico
170
+ (Sprint 7) incrementa atomicamente `usage_counters/{tid}_{pid}_{r}_{yyyymm}`.
171
+ - `usage.check(resource)` `GET /sdk/v1/entitlements?productId&tenantId&feature`
172
+ retorna `{allowed, reason, remaining, limit, planId, planFeatures}`.
173
+ - `NeetruClientConfig.productId` / `.tenantId` — defaults pra `usage.report` /
174
+ `usage.check` / `db.collection` quando não passado em options.
175
+ - Mock helpers: `MockDb`, `MockUsage.report()`, `MockUsage.check()`.
176
+
177
+ ### Changed
178
+ - `VERSION` bump `0.2.0` → `0.3.0`.
179
+ - `NeetruClient` agora expõe `.db` além dos antigos.
180
+ - `ResolvedConfig` ganhou `productId` + `tenantId` opcionais.
181
+
182
+ ### Backend (acompanha esta release)
183
+ - Novos endpoints (Sprint 7):
184
+ - `POST /sdk/v1/usage/record` — atomic increment + 80%/100% notifications + audit.
185
+ - `GET /sdk/v1/entitlements`lookup canônico subscription→plan→counter.
186
+ - `POST /sdk/v1/telemetry/log` — batch logger pra `logs/{productId}/{yyyymmdd}/`.
187
+
188
+ ## [0.2.0] - 2026-05-06
189
+
190
+ ### Added
191
+ - Namespace `client.auth` (v0.2 — OIDC + dev mocks):
192
+ - `signIn(options?)` — redireciona pra auth.neetru.com authorize endpoint
193
+ (browser) ou retorna mock user em dev (`NEETRU_ENV=dev`).
194
+ - `signOut()` limpa `localStorage.neetru_id_token` + revoga refresh
195
+ server-side (best-effort).
196
+ - `getUser()` decodifica id_token cached e retorna `NeetruUser` ou null.
197
+ - `onAuthStateChanged(listener)` — sub a mudanças, dispatcha sync no subscribe.
198
+ - Namespace `client.usage` (v0.2 meter):
199
+ - `track(event, props?)` → `POST /sdk/v1/usage/record` com Bearer.
200
+ - `getQuota(metric)` → `GET /sdk/v1/usage/quota?metric=` returns
201
+ `{ metric, used, limit, plan, resetsAt? }`.
202
+ - Namespace `client.support` (v0.2 tickets):
203
+ - `createTicket({subject, message, severity?, productSlug?})`
204
+ `POST /api/v1/products/{slug}/tickets` (default `_default`).
205
+ - `listMyTickets()` `GET ...` retorna array (aceita envelope `{tickets:[]}`).
206
+ - `mocks` module (`@neetru/sdk/mocks`):
207
+ - `MockAuth`, `MockUsage`, `MockSupport`, `MockEntitlements` — overridáveis
208
+ via `createNeetruClient({ mocks: { auth: MockAuth(...), ... } })`.
209
+ - `DEV_FIXTURE_USER` constante exportada.
210
+ - `NEETRU_ENV` resolution chain: config arg > `process.env.NEETRU_ENV` >
211
+ `globalThis.NEETRU_ENV` > default `prod`. `dev` ativa mocks automáticos.
212
+ - Subpath exports adicionais: `@neetru/sdk/{auth,usage,support,mocks}`.
213
+ - Tipos novos: `NeetruUser`, `AuthNamespace`, `UsageNamespace`,
214
+ `SupportNamespace`, `SignInOptions`, `SupportTicket`, `UsageQuota`,
215
+ `NeetruEnv`, `CreateTicketInput`.
216
+
217
+ ### Changed
218
+ - `VERSION` bump `0.1.0` `0.2.0`.
219
+ - `NeetruClientConfig` ganhou campos `env` + `mocks`.
220
+ - `ResolvedConfig` ganhou `env` resolved.
221
+ - `NeetruClient` agora expõe `.auth`, `.usage`, `.support` além dos antigos.
222
+
223
+ ### Backend (acompanha esta release — endpoints documentados em `docs/SDK_OPENAPI.md`)
224
+ - `POST /sdk/v1/usage/record` record event meterado.
225
+ - `GET /sdk/v1/usage/quota?metric=`ler quota atual.
226
+ - `POST /api/v1/products/{slug}/tickets`criar ticket.
227
+ - `GET /api/v1/products/{slug}/tickets` — listar meus tickets.
228
+ - (auth) `auth.neetru.com/oauth/authorize` — já live (Sprint 1 OIDC).
229
+ - (auth) `auth.neetru.com/oauth/revoke` — revoga refresh token.
230
+
231
+ ### Notes
232
+ - Pacote ainda **privado** (`private: true`) não publicado no npm.
233
+ - Carry-over: integração OIDC live aguarda owner habilitar redirect_uri pro
234
+ domain do consumer (configurar em `oidc_clients/{client_id}.redirect_uris`).
235
+ - TODO: `support.listMyTickets` precisa parametrizar productSlug (fixed
236
+ `_default` na v0.2).
237
+
238
+ ## [0.1.0] - 2026-05-05
239
+
240
+ ### Added
241
+ - `createNeetruClient(config)` factory — entry point principal.
242
+ - Resolve `apiKey` (arg explícito > `NEETRU_API_KEY` env em Node).
243
+ - Resolve `baseUrl` (default `https://api.neetru.com`).
244
+ - Resolve `fetch` (arg > `globalThis.fetch`).
245
+ - Namespace `client.catalog`:
246
+ - `list(opts?)` → `GET /api/v1/cli/catalog`. Aceita `includeDrafts`.
247
+ - `get(slug)` → `GET /api/v1/cli/catalog/{slug}`.
248
+ - Namespace `client.entitlements`:
249
+ - `check(slug, feature)` → boolean.
250
+ - `checkDetailed(slug, feature)` → `EntitlementCheck` com `reason`.
251
+ - Backed por `GET /api/v1/sdk/entitlements/check`.
252
+ - Namespace `client.telemetry`:
253
+ - `event({ name, properties?, timestamp? })` → `POST /api/v1/sdk/telemetry/event`.
254
+ - Subpath exports map: `@neetru/sdk/{catalog,entitlements,telemetry,errors}`.
255
+ - HTTP transport com mapeamento status → `NeetruError.code` estável.
256
+ - Tipos exportados: `NeetruClient`, `NeetruClientConfig`, `Product`, `ProductPlan`,
257
+ `EntitlementCheck`, `TelemetryEventInput`, `TelemetryEventAck`, `NeetruErrorCode`.
258
+ - Compat alias `initNeetru` (deprecated, será removido em v1.0).
259
+
260
+ ### Changed
261
+ - `VERSION` bump `0.0.1` → `0.1.0`.
262
+ - tsup config multi-entry pra subpath imports.
263
+
264
+ ### Backend (acompanha esta release)
265
+ - `GET /api/v1/cli/catalog/{slug}` — produto único.
266
+ - `GET /api/v1/sdk/entitlements/check?slug=&feature=` — verificação por user.
267
+ - `POST /api/v1/sdk/telemetry/event` — persiste em `usage_events`.
268
+
269
+ ### Notes
270
+ - Pacote ainda **privado** (`private: true`). Publicação no npm é
271
+ responsabilidade do owner em Sprint 6.
272
+ - API instável; pré-1.0 segue regra "breaking allowed em qualquer minor".
273
+
274
+ ## [0.0.1] - 2026-05-04
275
+
276
+ ### Added
277
+ - Scaffold inicial do pacote `@neetru/sdk` (private, não publicado no npm ainda).
278
+ - `initNeetru(config)` com validação de `apiUrl` e injeção opcional de `fetch`.
279
+ - `NeetruError` com `code`, `status` e `requestId` opcionais.
280
+ - `NeetruConfig` e `NeetruClient` types públicos.
281
+ - `VERSION` const exportada.
282
+ - Build pipeline com tsup (dual ESM + CJS + `.d.ts`).
283
+ - README + CHANGELOG.
284
+ - `tsconfig.json` strict ES2022 ESNext.