@stewardhq/sdk 0.2.0 → 0.5.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 (39) hide show
  1. package/README.md +123 -88
  2. package/dist/_chunks/errors.js +1 -1
  3. package/dist/_chunks/events.d.ts +315 -4
  4. package/dist/_chunks/events.js +1155 -9
  5. package/dist/_chunks/index.d.ts +3473 -90
  6. package/dist/_chunks/locale.d.ts +269 -1
  7. package/dist/_chunks/src.js +842 -24
  8. package/dist/_chunks/validators.d.ts +45 -1
  9. package/dist/_chunks/validators.js +128 -27
  10. package/dist/contract.d.ts +4 -4
  11. package/dist/contract.js +4 -4
  12. package/dist/index.d.ts +436 -22
  13. package/dist/index.js +1659 -26
  14. package/dist/server.d.ts +44 -6
  15. package/dist/server.js +29 -2
  16. package/package.json +4 -10
  17. package/dist/_chunks/steward.d.ts +0 -189
  18. package/dist/_chunks/steward.js +0 -560
  19. package/dist/testing/fixtures/events/LOCK.json +0 -27
  20. package/dist/testing/fixtures/events/account.deleted.json +0 -36
  21. package/dist/testing/fixtures/events/account.state_changed.json +0 -53
  22. package/dist/testing/fixtures/events/account.updated.json +0 -37
  23. package/dist/testing/fixtures/events/checkout.completed.json +0 -36
  24. package/dist/testing/fixtures/events/checkout.expired.json +0 -26
  25. package/dist/testing/fixtures/events/checkout.failed.json +0 -27
  26. package/dist/testing/fixtures/events/invoice.created.json +0 -37
  27. package/dist/testing/fixtures/events/invoice.issued.json +0 -38
  28. package/dist/testing/fixtures/events/invoice.voided.json +0 -39
  29. package/dist/testing/fixtures/events/subscription.activated.json +0 -40
  30. package/dist/testing/fixtures/events/subscription.cancel_scheduled.json +0 -38
  31. package/dist/testing/fixtures/events/subscription.canceled.json +0 -29
  32. package/dist/testing/fixtures/events/subscription.expired.json +0 -27
  33. package/dist/testing/fixtures/events/subscription.payment_failed.json +0 -38
  34. package/dist/testing/fixtures/events/subscription.reactivated.json +0 -36
  35. package/dist/testing/fixtures/events/subscription.renewed.json +0 -39
  36. package/dist/testing/fixtures/events/subscription.suspended.json +0 -36
  37. package/dist/testing/fixtures/events/subscription.terminated.json +0 -28
  38. package/dist/testing.d.ts +0 -626
  39. package/dist/testing.js +0 -3638
@@ -1,3 +1,271 @@
1
+ import { Ai as MeResponse, Bn as ResyncResult, Cr as EventsIngestInput, Ei as InvoiceWaiveResponse, Fn as PlanSetResponse, G as WebhookEndpoint, Go as AccountMeters, Hi as InvoicePaymentSessionCreateInput, J as WebhookEndpointList, K as WebhookEndpointCreateInput, La as CheckoutSessionCreated, Li as InvoiceIssueInput, Mt as ProductSettingsPatch, Oi as ManualInvoiceResponse, Pa as CheckoutSessionCreateInput, Pi as UncancelSubscriptionResponse, Qi as ManualInvoiceInput, Si as InvoiceIssueResponse, T as DoctorReport, Tr as EventsIngestResult, Vi as InvoicePaymentSession, Vs as MeterPeriodList, X as WebhookEndpointRotateInput, Ya as AccountsRefreshResult, Yi as InvoiceWaiveInput, Yo as CreditGrantInput, Za as Catalog, ai as AccountUpsertResponse, ba as PortalSession, di as CheckoutSessionResponse, ga as SubscriptionChangeInput, hi as GrantCreateResponse, hs as MeterChargeList, ia as CancelSubscriptionInput, jn as PlanSetInput, jt as ProductSettings, li as ChangeSubscriptionResponse, pa as Stats, pi as CreditGrantResponse, qi as InvoiceVoidInput, ri as AccountDetail, ro as CatalogSyncResult, sa as GrantCreateInput, si as CancelSubscriptionResponse, to as CatalogSyncInput, wi as InvoiceVoidResponse, xa as PortalSessionCreateInput } from "./index.js";
2
+ import { O as AccountInclude, U as AccountState, q as AccountUpsertInput, w as AccountDeleteResponse } from "./events.js";
3
+ //#region ../contract/src/client.d.ts
4
+ type CallOptions = {
5
+ idempotencyKey?: string;
6
+ actorRef?: string;
7
+ };
8
+ /** `getAccountState` sonucu: 304'te gövde yok, elindeki durum güncel. */
9
+ type AccountStateRead = {
10
+ notModified: false;
11
+ etag: string | null;
12
+ state: AccountState;
13
+ } | {
14
+ notModified: true;
15
+ etag: string;
16
+ };
17
+ /** `getAccountMeters` result: on 304 there is no body and the meters you hold are current. */
18
+ type AccountMetersRead = {
19
+ notModified: false;
20
+ etag: string | null;
21
+ meters: AccountMeters;
22
+ } | {
23
+ notModified: true;
24
+ etag: string;
25
+ };
26
+ //#endregion
27
+ //#region src/retry.d.ts
28
+ type RetryClass = "network" | "5xx" | "429";
29
+ type RetryOptions = {
30
+ /** İlk istekten sonraki en çok tekrar sayısı; 0 kapatır. Varsayılan 2. */
31
+ attempts?: number;
32
+ /** Tekrar denenen hata sınıfları. Varsayılan hepsi. */
33
+ on?: readonly RetryClass[];
34
+ /** Tek bir beklemenin üst sınırı (Retry-After dahil), ms. Varsayılan 5000. */
35
+ maxDelayMs?: number;
36
+ /** Test için: bekleme. Varsayılan `setTimeout`. */
37
+ sleep?: (ms: number) => Promise<void>;
38
+ /** Test için: jitter kaynağı, [0, 1). Varsayılan `Math.random`. */
39
+ random?: () => number;
40
+ };
41
+ //#endregion
42
+ //#region src/steward.d.ts
43
+ type StewardEnv = Readonly<Record<string, string | undefined>>;
44
+ type StewardOptions = {
45
+ /** Varsayılan `STEWARD_URL`. Ürün adresi ve anahtarı ikisi de yoksa ve admin ayarları tamsa istemci yalnızca `admin.*` içindir. */
46
+ baseUrl?: string;
47
+ /** Varsayılan `STEWARD_API_KEY`. */
48
+ apiKey?: string;
49
+ /** Ayarların okunduğu ortam; varsayılan `process.env` (varsa). */
50
+ env?: StewardEnv;
51
+ fetch?: typeof fetch;
52
+ /** Deneme başına zaman aşımı, ms. Varsayılan 10 sn. */
53
+ timeoutMs?: number;
54
+ /**
55
+ * Mutasyonlarda varsayılan `X-Actor-Ref` (ör. `system`); çağrıdaki `actorRef` ezer. İkisi de
56
+ * yoksa mutasyon istek göndermeden `StewardConfigError` (`actor_ref_required`) fırlatır.
57
+ */
58
+ actorRef?: string;
59
+ /** Varsayılan `STEWARD_ADMIN_URL`; yalnızca `admin.*` için. */
60
+ adminBaseUrl?: string;
61
+ /** Varsayılan `STEWARD_ADMIN_API_KEY`; yalnızca `admin.*` için. */
62
+ adminApiKey?: string;
63
+ retries?: RetryOptions;
64
+ };
65
+ /** Mutasyon çağrısı seçenekleri: `Idempotency-Key` ve `X-Actor-Ref`. */
66
+ type MutationOptions = CallOptions;
67
+ /** Koşullu katalog okuması: 304'te gövde yok, elindeki katalog güncel. */
68
+ type CatalogRead = {
69
+ notModified: false;
70
+ etag: string | null;
71
+ catalog: Catalog;
72
+ } | {
73
+ notModified: true;
74
+ etag: string;
75
+ };
76
+ type InvoiceDocument = {
77
+ contentType: string;
78
+ bytes: Uint8Array;
79
+ };
80
+ /**
81
+ * `GET /v1/me`: anahtarın ürünü ve kapsamı (kurulum doğrulaması), and since billing core the
82
+ * steward's `capabilities` (`STEWARD_CAPABILITIES`; absent from an older steward). The contract's
83
+ * `MeResponse`.
84
+ */
85
+ type StewardMe = MeResponse;
86
+ type Steward = {
87
+ accounts: {
88
+ /** `PUT /v1/accounts/{ref}` — hesabı oluşturur ya da günceller. */
89
+ upsert(ref: string, input: AccountUpsertInput, options?: MutationOptions): Promise<AccountUpsertResponse>;
90
+ get(ref: string, options?: {
91
+ include?: readonly AccountInclude[];
92
+ }): Promise<AccountDetail>;
93
+ /** `GET /v1/accounts/{ref}/state`. */
94
+ state(ref: string): Promise<AccountState>;
95
+ /** Koşullu durum okuması (önbellekler için): `etag` verilir ve durum değişmediyse `{notModified: true}`. */
96
+ readState(ref: string, options?: {
97
+ etag?: string;
98
+ }): Promise<AccountStateRead>;
99
+ /**
100
+ * `PUT /v1/accounts/{ref}/plan` — atomic plan (K6): active plan grants are replaced by one plan
101
+ * grant, `planCode: null` removes it. Entitlements are the layered merge of everything granted
102
+ * (M35, no rank): `mode` is accepted and ignored, `warnings` is always empty. The response's
103
+ * `account` can be `prime`d into a cache.
104
+ */
105
+ setPlan(ref: string, input: PlanSetInput, options?: MutationOptions): Promise<PlanSetResponse>;
106
+ /** `POST /v1/accounts/{ref}/resync` — saklı durumu `account.state_changed` (`cause: "resync"`) olarak yeniden yayınlar; version değişmez. */
107
+ resync(ref: string, options?: MutationOptions): Promise<ResyncResult>;
108
+ /**
109
+ * `DELETE /v1/accounts/{ref}` — KVKK anonimleştirme (F4e): profil ve kişisel veri silinir,
110
+ * faturalar kalır → `{ref, deletedAt}`. Sonra hesabın her ucu `account_deleted` (410; aynı
111
+ * ref'le `upsert` dahil). Canlı abonelikte `subscription_active` (409; önce `immediate`
112
+ * iptal), formu açık checkout'ta `checkout_in_progress` (409; süresi dolunca tekrar);
113
+ * zaten silinmişse `account_deleted` — iş tekrarında başarı sayılabilir.
114
+ */
115
+ delete(ref: string, options?: MutationOptions): Promise<AccountDeleteResponse>;
116
+ };
117
+ checkoutSessions: {
118
+ create(ref: string, input: CheckoutSessionCreateInput, options?: MutationOptions): Promise<CheckoutSessionCreated>;
119
+ get(id: string): Promise<CheckoutSessionResponse>;
120
+ };
121
+ /**
122
+ * Hosted customer portal (F3a): `POST /v1/accounts/{ref}/portal-sessions` → `{id, url, expiresAt}`.
123
+ * Redirect the browser to `url` (cancel and undo cancellation, change plan, "Pay invoice",
124
+ * invoices and the billing profile live in steward). Authorization is the product's; `actorRef` is
125
+ * the user opening the portal. Opening changes no state and emits no event.
126
+ */
127
+ portalSessions: {
128
+ create(ref: string, input?: PortalSessionCreateInput, options?: MutationOptions): Promise<PortalSession>;
129
+ };
130
+ subscriptions: {
131
+ cancel(id: string, input: CancelSubscriptionInput, options?: MutationOptions): Promise<CancelSubscriptionResponse>;
132
+ /**
133
+ * `POST /v1/subscriptions/{id}/change` (billing core, MF9): schedules a plan, interval or price
134
+ * change (`price: "current"` re-locks the price's current amount and the plan's current metered
135
+ * rates, M20/M36) for the next period (`when: "next_period"`);
136
+ * `account.subscription.scheduledChange` shows it and the next renewal invoice is written from
137
+ * the new terms. The current plan and interval take a pending change back. 409
138
+ * `already_subscribed` (another live subscription holds or is moving to the plan),
139
+ * `meter_already_billed` (the target prices a meter another live subscription bills); 422
140
+ * `plan_not_found`, `plan_not_sellable`, `subscription_change_invalid` when not possible.
141
+ */
142
+ change(id: string, input: SubscriptionChangeInput, options?: MutationOptions): Promise<ChangeSubscriptionResponse>;
143
+ /**
144
+ * `POST /v1/subscriptions/{id}/uncancel` (billing core, MF9): takes back a cancellation scheduled
145
+ * for the period end. 409 `cancel_not_scheduled` (none scheduled), `already_canceled` (ended).
146
+ */
147
+ uncancel(id: string, options?: MutationOptions): Promise<UncancelSubscriptionResponse>;
148
+ };
149
+ grants: {
150
+ create(ref: string, input: GrantCreateInput, options?: MutationOptions): Promise<GrantCreateResponse>;
151
+ revoke(id: string, options?: MutationOptions): Promise<void>;
152
+ };
153
+ invoices: {
154
+ issue(id: string, input: InvoiceIssueInput, options?: MutationOptions): Promise<InvoiceIssueResponse>;
155
+ document(id: string): Promise<InvoiceDocument>;
156
+ /**
157
+ * `POST /v1/accounts/{ref}/invoices` (F4f) — manuel taslak fatura (Enterprise satışı); `issue` ile kesilir.
158
+ * Hesabın fatura profili gerekir (422 `billing_profile_required`). `invoice.created` yayınlanır, durum değişmez.
159
+ */
160
+ createManual(ref: string, input: ManualInvoiceInput, options?: MutationOptions): Promise<ManualInvoiceResponse>;
161
+ /**
162
+ * `POST /v1/invoices/{id}/void` (F4f) — yalnızca manuel fatura (taslak ya da kesilmiş; numara ve belge kalır).
163
+ * Ödemeli fatura 409 `invoice_has_payment`, zaten void 409 `invoice_not_voidable`. `invoice.voided` yayınlanır.
164
+ */
165
+ void(id: string, input: InvoiceVoidInput, options?: MutationOptions): Promise<InvoiceVoidResponse>;
166
+ /**
167
+ * `POST /v1/invoices/{id}/payment-sessions` (billing core): opens steward's hosted pay page for an
168
+ * unpaid invoice → `{id, url, expiresAt}`; redirect the customer to `url` (the product's own "Pay
169
+ * invoice" button; e-mails and the portal link to the same page). `url` carries the page key: do
170
+ * not log it. 409 `invoice_not_payable` when the invoice is not unpaid. Opening changes no state.
171
+ */
172
+ createPaymentSession(id: string, input?: InvoicePaymentSessionCreateInput, options?: MutationOptions): Promise<InvoicePaymentSession>;
173
+ /**
174
+ * `POST /v1/invoices/{id}/waive` (billing core): forgives an unpaid invoice (`paymentStatus:
175
+ * "waived"`, e.g. before deleting the account; it leaves `account.openInvoices`). 409
176
+ * `invoice_not_waivable` otherwise.
177
+ */
178
+ waive(id: string, input: InvoiceWaiveInput, options?: MutationOptions): Promise<InvoiceWaiveResponse>;
179
+ };
180
+ catalog: {
181
+ get(): Promise<Catalog>;
182
+ /** Conditional read (`If-None-Match`); used by `steward catalog push` to report the current version. */
183
+ read(options?: {
184
+ etag?: string;
185
+ }): Promise<CatalogRead>;
186
+ };
187
+ /**
188
+ * Metering (phase 2): the product's events (`POST /v1/events/ingest`). For tracking from request
189
+ * handlers use `Events()` (queued, batched, retried in the background).
190
+ */
191
+ events: {
192
+ /**
193
+ * `POST /v1/events/ingest`: 1–1 000 events → `{inserted, duplicates, rejected[]}`. Every event
194
+ * needs an `externalId` (unique within the product; the lasting dedup key, M10). One
195
+ * `Idempotency-Key` per call, reused by every retry of it; `503 events_backlog` is retried after
196
+ * `Retry-After`. `rejected` lists per-event rejections (`account_not_found`, `account_deleted`,
197
+ * `timestamp_out_of_range`); a structurally invalid batch is `422` as a whole.
198
+ */
199
+ ingest(input: EventsIngestInput, options?: MutationOptions): Promise<EventsIngestResult>;
200
+ };
201
+ /** Metering (phase 2): meter reads (M13). For gates and the product's meter card use `Meters()` (cached, with pending units). */
202
+ meters: {
203
+ /** `GET /v1/accounts/{ref}/meters`: the open period of every meter. */
204
+ get(ref: string): Promise<AccountMeters>;
205
+ /** Conditional read (`If-None-Match`; ETag = the account's meter sequence): unchanged → `{notModified: true}`. */
206
+ read(ref: string, options?: {
207
+ etag?: string;
208
+ }): Promise<AccountMetersRead>;
209
+ /** `GET /v1/accounts/{ref}/meters/periods`: closed meter periods, newest first. */
210
+ periods(ref: string, options?: {
211
+ limit?: number;
212
+ }): Promise<MeterPeriodList>;
213
+ };
214
+ /** Metering (phase 2): one-off credits (ops; goodwill, campaigns). */
215
+ credits: {
216
+ /**
217
+ * `POST /v1/accounts/{ref}/credits` `{meter, units, reason}`: credit for the meter's open period,
218
+ * written to the append-only credit ledger with the actor → `{entry, meters, account?}`. 422
219
+ * `meter_not_found` for a code that is not an active catalog meter.
220
+ */
221
+ grant(ref: string, input: CreditGrantInput, options?: MutationOptions): Promise<CreditGrantResponse>;
222
+ };
223
+ /** Metering (phase 2, MF5): overage pricing records. */
224
+ meterCharges: {
225
+ /** `GET /v1/accounts/{ref}/meter-charges`: newest first, `dry_run` ones included. */
226
+ list(ref: string): Promise<MeterChargeList>;
227
+ };
228
+ stats(): Promise<Stats>;
229
+ me(): Promise<StewardMe>;
230
+ /**
231
+ * `GET /v1/doctor` — kurulum teşhisi (K11): katalog senkronu, sağlayıcı, ayarlar, hosted
232
+ * sayfa hazırlığı, endpoint teslimat teşhisi (`wrong_secret` = son teslimat 401),
233
+ * dunning ve `warnings[{code, severity, message}]`; `ok` = `error` önemde uyarı yok.
234
+ * Ürün anahtarıyla çalışır (yalnızca admin ayarlı istemcide admin anahtarıyla). Sağlayıcı
235
+ * sağlığı yanıtı veren pod'un gözlemidir.
236
+ */
237
+ doctor(): Promise<DoctorReport>;
238
+ /** Admin kapsamlı uçlar: `adminBaseUrl`/`adminApiKey` (ya da `STEWARD_ADMIN_*`) gerekir. */
239
+ admin: {
240
+ catalog: {
241
+ sync(input: CatalogSyncInput, options?: MutationOptions): Promise<CatalogSyncResult>;
242
+ };
243
+ accounts: {
244
+ refresh(options?: MutationOptions): Promise<AccountsRefreshResult>;
245
+ };
246
+ settings: {
247
+ /** `GET /v1/admin/settings`. */
248
+ get(): Promise<ProductSettings>;
249
+ /** `PATCH /v1/admin/settings`: verilmeyen alan değişmez, `null` temizler, `branding` sığ birleşir. */
250
+ update(patch: ProductSettingsPatch, options?: MutationOptions): Promise<ProductSettings>;
251
+ };
252
+ /**
253
+ * Webhook endpoint'leri. Sırrı çağıran üretir (`generateWebhookSecret()`) ve
254
+ * saklar; steward hiçbir yanıtta geri vermez.
255
+ */
256
+ endpoints: {
257
+ list(): Promise<WebhookEndpointList>;
258
+ /** `eventTypes` verilmezse yalnızca `account.state_changed`. */
259
+ create(input: WebhookEndpointCreateInput, options?: MutationOptions): Promise<WebhookEndpoint>;
260
+ /** Yeni sır; eskisi ürün geçişi bitene kadar ikinci imza olarak kalır. */
261
+ rotate(id: string, input: WebhookEndpointRotateInput, options?: MutationOptions): Promise<WebhookEndpoint>;
262
+ /** `status: inactive`; geri alınmaz (yeni endpoint açılır). */
263
+ deactivate(id: string, options?: MutationOptions): Promise<WebhookEndpoint>;
264
+ };
265
+ };
266
+ };
267
+ declare function createSteward(options?: StewardOptions): Steward;
268
+ //#endregion
1
269
  //#region src/http-status.d.ts
2
270
  type StewardLogger = {
3
271
  warn(message: string, context: Record<string, unknown>): void;
@@ -14,4 +282,4 @@ declare function httpStatusFor(err: unknown, options?: {
14
282
  //#region src/locale.d.ts
15
283
  type StewardLocale = "tr" | "en";
16
284
  //#endregion
17
- export { httpStatusFor as i, HttpStatusResult as n, StewardLogger as r, StewardLocale as t };
285
+ export { CatalogRead as a, Steward as c, StewardOptions as d, createSteward as f, AccountStateRead as g, AccountMetersRead as h, httpStatusFor as i, StewardEnv as l, RetryOptions as m, HttpStatusResult as n, InvoiceDocument as o, RetryClass as p, StewardLogger as r, MutationOptions as s, StewardLocale as t, StewardMe as u };