@stewardhq/cli 0.5.0 → 0.6.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 (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +94 -77
  3. package/dist/bin.js +22 -108
  4. package/package.json +14 -8
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 The Steward Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,62 +1,69 @@
1
1
  # @stewardhq/cli
2
2
 
3
- Steward CLI: kurulum teşhisi, katalog senkronu, ürün ayarları
4
- ve webhook endpoint yönetimi. Kaynak: [z9cloud/steward](https://github.com/z9cloud/steward/tree/main/cli).
3
+ Steward CLI: setup diagnostics, catalog sync, product settings and webhook endpoint
4
+ management. Source: [z9cloud/steward](https://github.com/z9cloud/steward/tree/main/cli).
5
5
 
6
6
  ```bash
7
- pnpm dlx @stewardhq/cli --help # ya da: pnpm add -D @stewardhq/cli → pnpm steward …
7
+ pnpm dlx @stewardhq/cli --help # or: pnpm add -D @stewardhq/cli → pnpm steward …
8
8
  ```
9
9
 
10
- ESM, Node ≥ 22. Tek çalışma zamanı bağımlılığı `@stewardhq/sdk`.
10
+ ESM, Node ≥ 22. Its only runtime dependency is `@stewardhq/sdk`.
11
11
 
12
- ## Komutlar
12
+ ## Commands
13
13
 
14
- | Komut | Ne yapar |
14
+ | Command | What it does |
15
15
  | --- | --- |
16
- | `steward doctor [--json]` | `GET /v1/doctor`; `APP_URL` ↔ steward `appUrl`/dönüş origin'leri. Hazır değilse çıkış 1. Sayaçlı üründe `metering` satırı (katalogdaki sayaçlar ve ölçümlü fiyatlar, steward yetenekleri `events`, `meters`, `overage`) ve raporun `events` (backlog, toplama gecikmesi, son 7 günün örneğinde eşleşmeyen olay adları, geçersiz değerler, olay almayan sayaçlar) ile `overage` (`chargeMode`, ölçümlü fiyat, kilitli oranı olmayan abonelik, devreden kayıt) bölümleri |
17
- | `steward catalog push <dosya> [--yes]` | `PUT /v1/admin/catalog`; sürüm ve sayılar. Before the push: benefit, price, meter, credit and metered price diff against the current catalog; price and metered price changes need confirmation (prompt, or `--yes`); a catalog with benefits needs the `benefits` capability, one with meters the `meters` capability (`GET /v1/me`) |
18
- | `steward meters get <ref> [--periods <n>] [--json]` | `GET /v1/accounts/:ref/meters`: sayaç başına açık dönem, kullanım, kredi, bakiye, seviye, tahmini aşım; `--periods` son kapalı dönemler |
19
- | `steward events send <ref> <ad> [--meta k=v]… [--external-id <id>] [--timestamp <iso>] [--json]` | `POST /v1/events/ingest` ile tek olay (yerel deneme); `externalId` verilmezse üretilir ve yazılır. Reddedilen olayda çıkış 1 |
16
+ | `steward doctor [--json]` | `GET /v1/doctor`; `APP_URL` ↔ steward `appUrl` / return origins. Exits 1 when not ready. For a product with meters, a `metering` line (the catalog's meters and metered prices, and steward's `events`, `meters`, `overage` capabilities) plus the report's `events` section (backlog, rollup lag, unmatched event names in the last 7 days' sample, invalid values, meters receiving no events) and `overage` section (`chargeMode`, metered price, subscriptions with no locked rate, rolled-over records) |
17
+ | `steward catalog push <file> [--yes]` | `PUT /v1/admin/catalog`; version and counts. Before the push: benefit, price, meter, credit and metered price diff against the current catalog; price and metered price changes need confirmation (prompt, or `--yes`); a catalog with benefits needs the `benefits` capability, one with meters the `meters` capability (`GET /v1/me`) |
18
+ | `steward meters get <ref> [--periods <n>] [--json]` | `GET /v1/accounts/:ref/meters`: per meter the open period, usage, credit, balance, standing and estimated overage; `--periods` adds the most recent closed periods |
19
+ | `steward events send <ref> <name> [--meta k=v]… [--external-id <id>] [--timestamp <iso>] [--json]` | A single event via `POST /v1/events/ingest` (for local trials); when `externalId` is omitted one is generated and printed. Exits 1 on a rejected event |
20
20
  | `steward settings get` | `GET /v1/admin/settings` |
21
- | `steward settings set [--app-url] [--privacy-url] [--terms-url] [--branding <json>] [--default-locale tr\|en] [--checkout-ttl <dk>] [--portal-ttl <dk>] [--extra-return-origins a,b] [--emails <json>] [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>] [--billing-allow-multiple-subscriptions true\|false] [--metering-charge-mode off\|dry_run\|live] [--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]` | `PATCH /v1/admin/settings`; boş değer alanı temizler (billing, metering and events flags: restores the default) |
22
- | `steward endpoints list [--json]` | Endpoint'ler ve son teslimat |
23
- | `steward endpoints add --url <url> --out <dosya> [--event-types a,b] [--description <metin>] [--force]` | Sırrı yerelde üretir, yalnızca `--out`'a yazar |
24
- | `steward endpoints rotate <id> --out <dosya> [--force]` | Yeni sır `--out`'a; ürün `yeni,eski` ile geçer |
25
- | `steward endpoints deactivate <id>` | Geri alınmaz |
26
-
27
- Çıkış kodları: 0 başarı, 1 hata (ya da doctor hazır değil), 2 yanlış kullanım.
28
-
29
- ## Bağlantı ayarları
30
-
31
- - Yönetim komutları (`catalog`, `settings`, `endpoints`): `STEWARD_ADMIN_URL` + `STEWARD_ADMIN_API_KEY`.
32
- Cluster'da admin ucu port-forward ile açılır (ör. `kubectl -n steward port-forward svc/steward 13002:80`
33
- → `http://localhost:13002`); anahtar operatörden.
34
- - `doctor`, `meters`, `events`: `STEWARD_URL` + `STEWARD_API_KEY`; ikisi de yoksa admin çifti. Yarım çift
35
- (yalnızca URL ya da yalnızca anahtar) diğer çifte düşmez, açık hata verir.
36
- - **Kaynak bütün olarak seçilir.** Ortamda `STEWARD_URL`, `STEWARD_API_KEY`, `STEWARD_ADMIN_URL`,
37
- `STEWARD_ADMIN_API_KEY`'den biri bile tanımlıysa bağlantı değerleri ve `APP_URL` yalnızca ortamdan okunur,
38
- çalışılan dizindeki `.env.local` hiç okunmaz. Hiçbiri ortamda yoksa hepsi `.env.local`'den. Böylece
39
- port-forward'lı üretim için ortam verilmişken ürün reposundaki `.env.local` hedefi değiştiremez.
40
- - Komutlar kullanılan kaynağı stderr'e yazar (değer değil, çift adları ve origin):
41
- `bağlantı: ortam · STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY → http://localhost:13002`.
42
- - Değişikliklerde `X-Actor-Ref: operator:<işletim sistemi kullanıcısı>`.
43
-
44
- ## Sırlar
45
-
46
- - CLI API anahtarlarını ve webhook sırlarını terminale **yazmaz**; yalnızca anahtar adlarını yazar
47
- (çıktı ayrıca `whsec_…`/`stw_…` biçimini maskeler).
48
- - `endpoints add/rotate`: sır yalnızca `--out` dosyasına (0600, satır sonu yok). Dosya varsa
49
- `--force` olmadan istek gönderilmez; istek başarısızsa sır dosyası bırakılmaz. Sırrı ürünün
50
- Secret'ına operatör taşır ve dosyayı siler.
51
- - CLI `kubectl` çağırmaz; Secret oluşturma ve rollout operatördedir.
52
-
53
- ## Katalog dosyası
54
-
55
- `export const catalog = defineCatalog(…)` (ya da default export) taşıyan `.ts`/`.mts`,
56
- `.js`/`.mjs`/`.cjs` ya da senkron gövdesi `.json`. `.ts` Node'un yerleşik tip ayıklamasıyla
57
- yüklenir: Node ≥ 22.18 (22.6–22.17'de `NODE_OPTIONS=--experimental-strip-types`); yalnızca
58
- silinebilir TS sözdizimi (enum yok), göreli import'lar uzantılı. Geçersiz katalogda istek
59
- gönderilmez.
21
+ | `steward settings set [--app-url] [--privacy-url] [--terms-url] [--branding <json>] [--default-locale tr\|en] [--checkout-ttl <min>] [--portal-ttl <min>] [--extra-return-origins a,b] [--emails <json>] [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>] [--billing-allow-multiple-subscriptions true\|false] [--metering-charge-mode off\|dry_run\|live] [--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]` | `PATCH /v1/admin/settings`; an empty value clears the field (billing, metering and events flags: restores the default) |
22
+ | `steward endpoints list [--json]` | Endpoints and their last delivery |
23
+ | `steward endpoints add --url <url> --out <file> [--event-types a,b] [--description <text>] [--force]` | Generates the secret locally and writes it only to `--out` |
24
+ | `steward endpoints rotate <id> --out <file> [--force]` | New secret to `--out`; the product transitions with `new,old` |
25
+ | `steward endpoints deactivate <id>` | Not reversible |
26
+
27
+ Exit codes: 0 success, 1 error (or doctor not ready), 2 incorrect usage.
28
+
29
+ ## Connection settings
30
+
31
+ - Admin commands (`catalog`, `settings`, `endpoints`): `STEWARD_ADMIN_URL` +
32
+ `STEWARD_ADMIN_API_KEY`. In a cluster the admin endpoint is reached through a port-forward
33
+ (e.g. `kubectl -n steward port-forward svc/steward 13002:80` → `http://localhost:13002`); the
34
+ key comes from the operator.
35
+ - `doctor`, `meters`, `events`: `STEWARD_URL` + `STEWARD_API_KEY`; if neither is set, the admin
36
+ pair. A half pair (only the URL or only the key) does not fall back to the other pair — it
37
+ fails with a clear error.
38
+ - **The source is chosen as a whole.** If even one of `STEWARD_URL`, `STEWARD_API_KEY`,
39
+ `STEWARD_ADMIN_URL`, `STEWARD_ADMIN_API_KEY` is defined in the environment, the connection
40
+ values and `APP_URL` are read from the environment only, and the `.env.local` in the working
41
+ directory is not read at all. If none of them is in the environment, all of them come from
42
+ `.env.local`. That way, when the environment is set for a port-forwarded production target,
43
+ a product repo's `.env.local` cannot redirect it.
44
+ - Commands print the source they used to stderr (not the values — the pair names and the
45
+ origin). Some CLI output is still in Turkish for historical reasons, so this line currently
46
+ reads: `bağlantı: ortam · STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY → http://localhost:13002`
47
+ (`ortam` = environment, the alternative being `.env.local`).
48
+ - Changes carry `X-Actor-Ref: operator:<operating system user>`.
49
+
50
+ ## Secrets
51
+
52
+ - The CLI **never** prints API keys or webhook secrets to the terminal; it prints only key
53
+ names (and its output additionally masks the `whsec_…` / `stw_…` shapes).
54
+ - `endpoints add/rotate`: the secret goes only to the `--out` file (mode 0600, no trailing
55
+ newline). If the file exists, no request is sent without `--force`; if the request fails, no
56
+ secret file is left behind. The operator moves the secret into the product's Secret and
57
+ deletes the file.
58
+ - The CLI does not call `kubectl`; creating Secrets and rolling out is the operator's job.
59
+
60
+ ## Catalog file
61
+
62
+ A `.ts`/`.mts`, `.js`/`.mjs`/`.cjs` file exporting `export const catalog = defineCatalog(…)`
63
+ (or a default export), or a `.json` file with the sync body. `.ts` is loaded with Node's
64
+ built-in type stripping: Node ≥ 22.18 (on 22.6–22.17 use
65
+ `NODE_OPTIONS=--experimental-strip-types`); only erasable TS syntax (no enums), and relative
66
+ imports need their extension. An invalid catalog is never sent.
60
67
 
61
68
  Before pushing, `catalog push` reads steward's current catalog and prints what changes:
62
69
  benefits (new, changed, archived, plan benefit lists) and prices (new, deactivated, amount or
@@ -75,31 +82,41 @@ counted a period: steward refuses the push with `422 meter_locked`, and the new
75
82
  meter code. A catalog with `meters` or `meteredPrices` is pushed only when `GET /v1/me` lists the
76
83
  `meters` capability.
77
84
 
78
- ## Sayaçlar ve olaylar
79
-
80
- - `steward meters get <ref>` hesabın sayaç okumasını yazar (ürünün `GET /v1/accounts/:ref/meters`'ta
81
- gördüğü sayılar): sayaç başına dönem, kullanılan, kredi, bakiye, seviye (`ok`/`low`/`exhausted`),
82
- dahil kredi ve ölçümlü fiyatlı sayaçta tahmini aşım. `--periods <n>` son kapalı dönemleri de listeler.
83
- - `steward events send <ref> <ad> --meta tokens=1200 --meta model=x` tek olay gönderir (yerel deneme;
84
- ürün kodunda SDK kullanılır). `--meta` değeri düz sayıysa (`12`, `0.25`) ya da `true`/`false` ise o
85
- tipte, değilse metin gider; çift tırnak metni zorlar (`--meta 'kod="007"'`). `--external-id`
86
- verilmezse `cli:<uuid>` üretilir ve yazılır: aynı kimlikle ikinci gönderim `duplicate`dır. Metadata'ya
87
- kişisel veri (ad, e-posta, telefon) yazılmaz. Olay hemen değil, toplama işi onu işleyince (saniyeler)
88
- sayılır.
89
- - Ayrıntı: [sayaçlar ve kullanım rehberi](https://github.com/z9cloud/steward/blob/main/docs/integrate/metering.md).
90
-
91
- ## Sürümler
92
-
93
- Yayın: `cli/package.json` sürümü + `cli-v<sürüm>` etiketi (`.github/workflows/cli-publish.yml`); bağlı
94
- `@stewardhq/sdk` sürümü npm'de önce yayınlanmış olmalı.
95
-
96
- - **0.5.0** (`@stewardhq/sdk` 0.5, ölçümleme Faz 2): `steward meters get`, `steward events send`;
97
- `catalog push` sayaç, kredi ve ölçümlü fiyat farkı (ölçümlü fiyat değişikliği onay ister; sayaçlı katalog
98
- `meters` yeteneği olmadan gönderilmez); `settings set --metering-charge-mode`,
99
- `--metering-late-grace-minutes`, `--events-retention-days`; `doctor`'da `metering` satırı ile raporun
100
- `events` ve `overage` bölümleri.
101
- - **0.4.0** (`@stewardhq/sdk` 0.4, faturalama çekirdeği Faz 1): benefit ve fiyat farkı, fiyat değişikliği
102
- onayı, `benefits` yeteneği kapısı, `settings set --billing-*`; `steward dev` kaldırıldı (kırıcı).
103
-
104
- Paketlenince `@stewardhq/sdk` bağımlılığı `workspace:^`'ten o anki SDK sürümünün aralığına döner (0.5.0 →
105
- `^0.5.0`).
85
+ ## Meters and events
86
+
87
+ - `steward meters get <ref>` prints the account's meter reading (the numbers the product sees
88
+ at `GET /v1/accounts/:ref/meters`): per meter the period, used, credit, balance, standing
89
+ (`ok`/`low`/`exhausted`), included credit, and — for a meter with a metered price — the
90
+ estimated overage. `--periods <n>` also lists the most recent closed periods.
91
+ - `steward events send <ref> <name> --meta tokens=1200 --meta model=x` sends a single event
92
+ (for local trials; product code uses the SDK). A `--meta` value that is a plain number
93
+ (`12`, `0.25`) or `true`/`false` is sent with that type, anything else as text; double
94
+ quotes force text (`--meta 'code="007"'`). When `--external-id` is omitted, `cli:<uuid>` is
95
+ generated and printed: a second send with the same id is a `duplicate`. Do not put personal
96
+ data (name, email, phone) in metadata. An event is not counted immediately — only once the
97
+ rollup job processes it (seconds).
98
+ - Details: [metering guide](https://github.com/z9cloud/steward/blob/main/docs/integrate/metering.md).
99
+
100
+ ## Versions
101
+
102
+ Release: bump the version in `cli/package.json` and push the `cli-v<version>` tag
103
+ (`.github/workflows/cli-publish.yml`); the `@stewardhq/sdk` version it depends on must already
104
+ be published on npm. **The first version on npmjs is 0.5.0** (2026-09-21); 0.4.0 was not
105
+ published.
106
+
107
+ - **0.5.0** (`@stewardhq/sdk` 0.5, metering phase 2): `steward meters get`, `steward events
108
+ send`; meter, credit and metered price diff in `catalog push` (a metered price change asks
109
+ for confirmation; a catalog with meters is not pushed without the `meters` capability);
110
+ `settings set --metering-charge-mode`, `--metering-late-grace-minutes`,
111
+ `--events-retention-days`; the `metering` line in `doctor` plus the report's `events` and
112
+ `overage` sections.
113
+ - **0.4.0** (`@stewardhq/sdk` 0.4, billing core phase 1): benefit and price diff, price change
114
+ confirmation, the `benefits` capability gate, `settings set --billing-*`; `steward dev`
115
+ removed (breaking).
116
+
117
+ When packed, the `@stewardhq/sdk` dependency turns from `workspace:^` into the range of the
118
+ SDK version current at that time (0.5.0 → `^0.5.0`).
119
+
120
+ ## License
121
+
122
+ Apache License 2.0 — see [LICENSE](LICENSE).
package/dist/bin.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { userInfo } from "node:os";
3
3
  import { createInterface } from "node:readline/promises";
4
4
  import { setTimeout } from "node:timers/promises";
5
- import { API_VERSION, AccountMetersSchema, CatalogSyncInputSchema, ErrorResponseSchema, EventsIngestInputSchema, EventsIngestResultSchema, HEADER_ACTOR_REF, HEADER_API_VERSION, HEADER_IDEMPOTENCY_KEY, HEADER_REQUEST_ID, METER_CHARGE_MODES, MeterCreditPropertiesSchema, MeterPeriodListSchema, ProductSettingsPatchSchema, StewardApiError, StewardConfigError, StewardContractError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
5
+ import { CatalogSyncInputSchema, EventsIngestInputSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
6
6
  import { parseArgs } from "node:util";
7
7
  import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
8
8
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
@@ -701,9 +701,11 @@ async function catalogCommand(ctx, out, args) {
701
701
  //#region src/commands/doctor.ts
702
702
  const DOCTOR_USAGE = `Kullanım: steward doctor [--json]
703
703
 
704
- GET /v1/doctor raporu: katalog, sağlayıcı, ayarlar, hosted sayfa hazırlığı,
705
- endpoint teslimat teşhisi ve uyarılar. APP_URL tanımlıysa steward'daki appUrl
706
- ve izinli dönüş origin'leriyle karşılaştırılır.
704
+ GET /v1/doctor raporu. Bölümler sırayla: durum, katalog, sağlayıcı, ayarlar,
705
+ hosted (sayfa hazırlığı), endpoint'ler (teslimat teşhisi), dunning, emails ve
706
+ sayaçlı üründe metering/events/overage; sonda hatalar, uyarılar ve bilgi
707
+ listeleri. APP_URL tanımlıysa steward'daki appUrl ve izinli dönüş
708
+ origin'leriyle karşılaştırılır.
707
709
 
708
710
  Bağlantı: STEWARD_URL + STEWARD_API_KEY (ikisi de yoksa STEWARD_ADMIN_URL +
709
711
  STEWARD_ADMIN_API_KEY). Ortamda steward bağlantı değişkenlerinden biri bile
@@ -713,15 +715,16 @@ yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
713
715
  Çıkış kodu: 0 hazır; 1 rapor ok değil (error önemde uyarı) ya da APP_URL
714
716
  steward'da izinli değil.
715
717
 
716
- Metering: for a product whose catalog defines meters, a "metering" line lists the
717
- meters and metered prices (GET /v1/catalog) and the steward capabilities (GET /v1/me:
718
- events, meters, overage); the report's "events" section (backlog, rollup lag, a sample
719
- of the last 7 days: unmatched event names, invalid values, meters without events) and
720
- "overage" section (charge mode, metered prices, subscriptions without a locked rate,
721
- carried charges) follow. Metering warnings are in the lists as usual.
718
+ Ölçümleme: kataloğunda sayaç tanımlı üründe "metering" satırı sayaçları ve
719
+ ölçümlü fiyatları (GET /v1/catalog) ve steward'ın yeteneklerini (GET /v1/me:
720
+ events, meters, overage) yazar; ardından raporun "events" bölümü (bekleyen olay,
721
+ rollup gecikmesi, son 7 günün örneği: eşleşmeyen olay adları, geçersiz değerler,
722
+ olayı olmayan sayaçlar) ve "overage" bölümü (aşım kipi, ölçümlü fiyatlar, kilitli
723
+ oranı olmayan abonelikler, devreden kayıtlar) gelir. Ölçümleme uyarıları her
724
+ zamanki gibi alttaki listelerdedir.
722
725
 
723
726
  --json raporu JSON yazar (+ cliWarnings: yerel APP_URL karşılaştırması;
724
- cliMetering: the metering line's catalog and capability facts)`;
727
+ cliMetering: metering satırının katalog ve yetenek bilgileri)`;
725
728
  /** `APP_URL` (ürünün kendi adresi; checkout `successUrl`'i bundan kurulur) ↔ steward ayarları. */
726
729
  function appUrlWarnings(appUrl, report) {
727
730
  if (appUrl === void 0) return [];
@@ -1096,82 +1099,6 @@ function secretNotice(out, path, fallback, next) {
1096
1099
  out.err(next);
1097
1100
  }
1098
1101
  //#endregion
1099
- //#region src/api.ts
1100
- const ATTEMPTS = 3;
1101
- const TIMEOUT_MS = 3e4;
1102
- const MAX_WAIT_MS = 1e4;
1103
- function retryAfterMs(value) {
1104
- if (value === null) return void 0;
1105
- const text = value.trim();
1106
- if (/^\d+$/.test(text)) return Number(text) * 1e3;
1107
- const at = /^[A-Za-z]/.test(text) ? Date.parse(text) : NaN;
1108
- return Number.isNaN(at) ? void 0 : Math.max(0, at - Date.now());
1109
- }
1110
- async function apiError(res) {
1111
- const parsed = ErrorResponseSchema.safeParse(await res.json().catch(() => null));
1112
- const requestId = res.headers.get(HEADER_REQUEST_ID) ?? (parsed.success ? parsed.data.requestId : void 0);
1113
- const wait = res.status === 429 || res.status === 503 ? retryAfterMs(res.headers.get("retry-after")) : void 0;
1114
- return new StewardApiError({
1115
- code: parsed.success ? parsed.data.error : `http_${res.status}`,
1116
- httpStatus: res.status,
1117
- ...parsed.success && parsed.data.message !== void 0 ? { message: parsed.data.message } : {},
1118
- ...parsed.success && parsed.data.category !== void 0 ? { category: parsed.data.category } : {},
1119
- ...parsed.success && parsed.data.retryable !== void 0 ? { retryable: parsed.data.retryable } : {},
1120
- ...requestId !== void 0 && requestId !== null ? { requestId } : {},
1121
- ...wait !== void 0 ? { retryAfterMs: wait } : {}
1122
- });
1123
- }
1124
- async function attempt(ctx, target, request, idempotencyKey) {
1125
- const headers = {
1126
- authorization: `Bearer ${target.apiKey}`,
1127
- accept: "application/json",
1128
- [HEADER_API_VERSION]: API_VERSION
1129
- };
1130
- if (request.method !== "GET") {
1131
- headers[HEADER_IDEMPOTENCY_KEY] = idempotencyKey;
1132
- headers[HEADER_ACTOR_REF] = actorRefOf(ctx.username());
1133
- }
1134
- if (request.body !== void 0) headers["content-type"] = "application/json";
1135
- let res;
1136
- try {
1137
- res = await ctx.fetch(`${target.url.replace(/\/$/, "")}${request.path}`, {
1138
- method: request.method,
1139
- headers,
1140
- ...request.body !== void 0 ? { body: JSON.stringify(request.body) } : {},
1141
- signal: AbortSignal.timeout(TIMEOUT_MS)
1142
- });
1143
- } catch (error) {
1144
- const timeout = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
1145
- throw new StewardNetworkError({
1146
- code: timeout ? "timeout" : "network_error",
1147
- cause: error
1148
- });
1149
- }
1150
- if (!res.ok) throw await apiError(res);
1151
- const parsed = request.schema.safeParse(await res.json().catch(() => void 0));
1152
- const requestId = res.headers.get(HEADER_REQUEST_ID);
1153
- if (!parsed.success) throw new StewardContractError({
1154
- httpStatus: res.status,
1155
- ...requestId !== null ? { requestId } : {}
1156
- });
1157
- return {
1158
- status: res.status,
1159
- data: parsed.data,
1160
- etag: res.headers.get("etag")
1161
- };
1162
- }
1163
- /** One steward request (see the header); throws the SDK's `StewardError` subclasses. */
1164
- async function stewardRequest(ctx, target, request) {
1165
- const idempotencyKey = globalThis.crypto.randomUUID();
1166
- for (let n = 1;; n++) try {
1167
- return await attempt(ctx, target, request, idempotencyKey);
1168
- } catch (error) {
1169
- if (!(error instanceof StewardNetworkError || error instanceof StewardApiError && (error.httpStatus === 429 || error.httpStatus >= 500)) || n >= ATTEMPTS) throw error;
1170
- const wait = error instanceof StewardApiError && error.retryAfterMs !== void 0 ? error.retryAfterMs : 250 * 2 ** (n - 1);
1171
- await ctx.sleep(Math.min(wait, MAX_WAIT_MS));
1172
- }
1173
- }
1174
- //#endregion
1175
1102
  //#region src/commands/events.ts
1176
1103
  const EVENTS_USAGE = `Usage: steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
1177
1104
  [--timestamp <iso>] [--json]
@@ -1258,12 +1185,7 @@ async function eventsCommand(ctx, out, args) {
1258
1185
  if (!input.success) throw new UsageError(`invalid event (nothing was sent)\n${input.error.issues.map((issue) => ` - ${issue.path.slice(2).map(String).join(".") || "(event)"}: ${issue.message}`).join("\n")}`);
1259
1186
  const target = requireReadTarget(await resolveEnv(ctx));
1260
1187
  out.err(connectionLine(target));
1261
- const { data: result } = await callSteward(target, () => stewardRequest(ctx, target, {
1262
- method: "POST",
1263
- path: "/v1/events/ingest",
1264
- schema: EventsIngestResultSchema,
1265
- body: input.data
1266
- }));
1188
+ const result = await callSteward(target, () => clientFor(ctx, target).events.ingest(input.data));
1267
1189
  if (values.json) out.out(JSON.stringify({
1268
1190
  externalId,
1269
1191
  ...result
@@ -1347,22 +1269,14 @@ async function metersCommand(ctx, out, args) {
1347
1269
  const limit = values.periods === void 0 ? null : parsePositiveInt(values.periods, "--periods", { max: 100 });
1348
1270
  const target = requireReadTarget(await resolveEnv(ctx));
1349
1271
  out.err(connectionLine(target));
1350
- const path = `/v1/accounts/${encodeURIComponent(ref)}/meters`;
1351
- const read = await callSteward(target, () => stewardRequest(ctx, target, {
1352
- method: "GET",
1353
- path,
1354
- schema: AccountMetersSchema
1355
- }));
1356
- const periods = limit === null ? null : (await callSteward(target, () => stewardRequest(ctx, target, {
1357
- method: "GET",
1358
- path: `${path}/periods?limit=${limit}`,
1359
- schema: MeterPeriodListSchema
1360
- }))).data.periods;
1361
- if (values.json) out.out(JSON.stringify(periods === null ? read.data : {
1362
- ...read.data,
1272
+ const steward = clientFor(ctx, target);
1273
+ const meters = await callSteward(target, () => steward.meters.get(ref));
1274
+ const periods = limit === null ? null : (await callSteward(target, () => steward.meters.periods(ref, { limit }))).periods;
1275
+ if (values.json) out.out(JSON.stringify(periods === null ? meters : {
1276
+ ...meters,
1363
1277
  closedPeriods: periods
1364
1278
  }, null, 2));
1365
- else for (const line of formatMeters(read.data, periods)) out.out(line);
1279
+ else for (const line of formatMeters(meters, periods)) out.out(line);
1366
1280
  return 0;
1367
1281
  }
1368
1282
  //#endregion
@@ -1521,7 +1435,7 @@ async function settingsCommand(ctx, out, args) {
1521
1435
  }
1522
1436
  //#endregion
1523
1437
  //#region src/main.ts
1524
- const CLI_VERSION = "0.5.0";
1438
+ const CLI_VERSION = "0.6.0";
1525
1439
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
1526
1440
 
1527
1441
  Kullanım: steward <komut> [seçenekler]
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "@stewardhq/cli",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Steward CLI: doctor, catalog push, settings and webhook endpoint management.",
5
+ "license": "Apache-2.0",
6
+ "homepage": "https://github.com/z9cloud/steward/tree/main/cli#readme",
7
+ "bugs": {
8
+ "url": "https://github.com/z9cloud/steward/issues"
9
+ },
5
10
  "type": "module",
6
11
  "repository": {
7
12
  "type": "git",
@@ -15,21 +20,22 @@
15
20
  "steward": "./dist/bin.js"
16
21
  },
17
22
  "files": [
18
- "dist"
23
+ "dist",
24
+ "LICENSE"
19
25
  ],
20
26
  "publishConfig": {
21
27
  "access": "public",
22
28
  "registry": "https://registry.npmjs.org"
23
29
  },
24
30
  "dependencies": {
25
- "@stewardhq/sdk": "^0.5.0"
31
+ "@stewardhq/sdk": "^0.6.0"
26
32
  },
27
33
  "devDependencies": {
28
- "@types/node": "^24.13.3",
34
+ "@types/node": "^24.19.0",
29
35
  "tsdown": "^0.23.0",
30
- "tsx": "^4.19.0",
31
- "typescript": "^5.9.0",
32
- "vitest": "^5.0.1"
36
+ "tsx": "^4.23.15",
37
+ "typescript": "^7.0.2",
38
+ "vitest": "^5.0.2"
33
39
  },
34
40
  "scripts": {
35
41
  "build": "tsdown",
@@ -37,6 +43,6 @@
37
43
  "start": "tsx src/bin.ts",
38
44
  "test": "vitest run",
39
45
  "typecheck": "tsc --noEmit",
40
- "lint": "eslint src scripts tsdown.config.ts"
46
+ "lint": "biome check src scripts tsdown.config.ts"
41
47
  }
42
48
  }