@stewardhq/cli 0.12.0 → 0.14.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 (3) hide show
  1. package/README.md +22 -6
  2. package/dist/bin.js +967 -400
  3. package/package.json +5 -5
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 { ACCOUNT_INCLUDES, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CodeSchema, CreditAdjustmentInputSchema, DateTimeSchema, DunningPolicySchema, EmailSmtpVerifyInputSchema, EventsIngestInputSchema, FxRateSchema, GRANT_LIST_DEFAULT_LIMIT, GRANT_LIST_MAX_LIMIT, GrantListSubscriptionFilterSchema, INVOICE_LINE_TEXTS, IdSchema, InvoiceIssueInputSchema, InvoicePaymentStatusSchema, InvoiceStatusSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, SALES_REPORT_MAX_MONTHS, SmtpUrlSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, TAX_PROVIDERS, TAX_THRESHOLD_PERIODS, TAX_THRESHOLD_SCOPES, TaxThresholdInputSchema, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf, taxIdTypeOf } from "@stewardhq/sdk";
5
+ import { ACCOUNT_INCLUDES, ACCOUNT_LIST_QUERY_MAX, ADMIN_LIST_DEFAULT_LIMIT, ADMIN_LIST_MAX_LIMIT, AUDIT_LIST_FILTER_MAX, AccountListDeletedFilterSchema, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, ApiKeyPrefixSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CodeSchema, CreditAdjustmentInputSchema, DateTimeSchema, DiscountCreateInputSchema, DiscountUpdateInputSchema, DunningPolicySchema, EmailMessageStatusSchema, EmailSmtpVerifyInputSchema, EmailTemplateSchema, EventIdSchema, EventsIngestInputSchema, ExternalRefSchema, FxRateSchema, GRANT_LIST_DEFAULT_LIMIT, GRANT_LIST_MAX_LIMIT, GrantListSubscriptionFilterSchema, INVOICE_LINE_TEXTS, IdSchema, InvoiceIssueInputSchema, InvoicePaymentStatusSchema, InvoiceStatusSchema, METER_CHARGE_MODES, PaymentListDisputedFilterSchema, PaymentMethodSchema, ProductSettingsPatchSchema, RepriceInputSchema, SALES_REPORT_MAX_MONTHS, SmtpUrlSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, SubscriptionStatusSchema, TAX_PROVIDERS, TAX_THRESHOLD_PERIODS, TAX_THRESHOLD_SCOPES, TaxThresholdInputSchema, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, WebhookEventDeliveryFilterSchema, catalogPriceChangeCount as priceChangeCount, createSteward, diffCatalogSync, generateApiKeyToken, generateWebhookSecret, meteredRateText, plainDecimalOf, taxIdTypeOf } from "@stewardhq/sdk";
6
6
  import { parseArgs } from "node:util";
7
7
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
8
8
  import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
@@ -117,11 +117,6 @@ function definesMeters(input) {
117
117
  function definesUnlistedPlans(input) {
118
118
  return input.plans.some((plan) => plan.listed === false);
119
119
  }
120
- const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
121
- /** JSON with sorted object keys: key order does not count as a change. */
122
- const canonical = (value) => JSON.stringify(value ?? null, (_key, v) => isPlainObject(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : v);
123
- const priceKey = (p) => `${p.planCode}/${p.interval}/${p.intervalCount}/${p.currency}`;
124
- const priceLabel = (p) => `${p.planCode} ${p.intervalCount > 1 ? `${p.intervalCount}×` : ""}${p.interval}`;
125
120
  /** `TRY 1,250.00`; minor units with the currency's own fraction digits (unknown currency: minor units). */
126
121
  function formatMinor(amountMinor, currency) {
127
122
  try {
@@ -139,147 +134,12 @@ function formatMinor(amountMinor, currency) {
139
134
  const percent$1 = (bps) => `${bps / 100}%`;
140
135
  /** Units as exact text with grouping (`2,000,000`, `0.25`). */
141
136
  const unitsText = (value) => new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
142
- const meteredKey = (p) => `${p.planCode}/${p.meter}/${p.currency}`;
143
- const meteredLabel = (p) => `${p.planCode} ${p.meter}`;
144
- /** `TRY 12.50 per 1,000 units` (+ `, cap TRY 500.00`). */
145
- function meteredRate(p) {
146
- const cap = p.capMinor === void 0 || p.capMinor === null ? "" : `, cap ${formatMinor(p.capMinor, p.currency)}`;
147
- return `${formatMinor(p.amountMinor, p.currency)} per ${unitsText(p.perUnits)} unit${p.perUnits === 1 ? "" : "s"}${cap}`;
148
- }
149
- function creditTerms(properties) {
150
- const parsed = MeterCreditPropertiesSchema.safeParse(properties);
151
- return parsed.success ? {
152
- meter: parsed.data.meter,
153
- units: parsed.data.units,
154
- rolloverCapUnits: parsed.data.rolloverCapUnits ?? null
155
- } : null;
156
- }
157
- function diffMeters(current, input) {
158
- const before = current?.meters ?? {};
159
- const meters = {
160
- added: [],
161
- changed: [],
162
- ruleChanged: [],
163
- archived: []
164
- };
165
- for (const [code, next] of Object.entries(input.meters)) {
166
- const old = Object.hasOwn(before, code) ? before[code] : void 0;
167
- if (old === void 0) {
168
- meters.added.push(code);
169
- continue;
170
- }
171
- if (canonical(old.filter) !== canonical(next.filter) || canonical(old.aggregation) !== canonical(next.aggregation)) meters.ruleChanged.push(code);
172
- if (canonical(old.label) !== canonical(next.label) || canonical(old.unitLabel) !== canonical(next.unitLabel) || (old.displayPer ?? null) !== (next.displayPer ?? null) || old.lowAt !== next.lowAt) meters.changed.push(code);
173
- }
174
- meters.archived = Object.keys(before).filter((code) => !Object.hasOwn(input.meters, code));
175
- return meters;
176
- }
177
- function meteredTerms(p) {
178
- return {
179
- amountMinor: p.amountMinor,
180
- perUnits: p.perUnits,
181
- taxInclusive: p.taxInclusive,
182
- taxRateBps: p.taxRateBps,
183
- capMinor: p.capMinor ?? null
184
- };
185
- }
186
- function diffMeteredPrices(current, input) {
187
- const before = new Map((current?.meteredPrices ?? []).map((p) => [meteredKey(p), p]));
188
- const inputKeys = new Set(input.meteredPrices.map(meteredKey));
189
- const out = {
190
- added: [],
191
- deactivated: [],
192
- changed: []
193
- };
194
- for (const price of input.meteredPrices) {
195
- const old = before.get(meteredKey(price));
196
- if (old === void 0) out.added.push(`${meteredLabel(price)} ${meteredRate(price)}`);
197
- else if (canonical(meteredTerms(old)) !== canonical(meteredTerms(price))) out.changed.push({
198
- label: meteredLabel(price),
199
- id: old.id,
200
- currency: price.currency,
201
- from: meteredTerms(old),
202
- to: meteredTerms(price)
203
- });
204
- }
205
- for (const [key, price] of before) if (!inputKeys.has(key)) out.deactivated.push(`${meteredLabel(price)} ${meteredRate(price)}`);
206
- return out;
207
- }
137
+ const FORMAT = {
138
+ money: formatMinor,
139
+ units: unitsText
140
+ };
208
141
  function diffCatalog(current, file) {
209
- const input = CatalogSyncInputSchema.parse(file);
210
- const currentBenefits = current?.benefits ?? {};
211
- const benefits = {
212
- added: Object.keys(input.benefits).filter((code) => !Object.hasOwn(currentBenefits, code)),
213
- changed: Object.entries(input.benefits).filter(([code]) => Object.hasOwn(currentBenefits, code)).filter(([code, next]) => {
214
- const before = currentBenefits[code];
215
- return before.type !== next.type || canonical(before.properties) !== canonical(next.properties) || canonical(before.description) !== canonical(next.description);
216
- }).map(([code]) => code),
217
- archived: Object.keys(currentBenefits).filter((code) => !Object.hasOwn(input.benefits, code))
218
- };
219
- const currentPlans = new Map((current?.plans ?? []).map((plan) => [plan.code, plan.benefits ?? []]));
220
- const planBenefits = [];
221
- for (const plan of input.plans) {
222
- const before = currentPlans.get(plan.code) ?? [];
223
- const added = plan.benefits.filter((code) => !before.includes(code));
224
- const removed = before.filter((code) => !plan.benefits.includes(code));
225
- if (added.length > 0 || removed.length > 0) planBenefits.push({
226
- plan: plan.code,
227
- added,
228
- removed
229
- });
230
- }
231
- const currentListing = new Map((current?.plans ?? []).map((plan) => [plan.code, plan.listed ?? true]));
232
- const planListing = input.plans.filter((plan) => (currentListing.get(plan.code) ?? true) !== plan.listed).map((plan) => ({
233
- plan: plan.code,
234
- listed: plan.listed
235
- }));
236
- const currentPrices = new Map((current?.prices ?? []).map((price) => [priceKey(price), price]));
237
- const inputKeys = new Set(input.prices.map(priceKey));
238
- const prices = {
239
- added: [],
240
- deactivated: [],
241
- changed: []
242
- };
243
- for (const price of input.prices) {
244
- const before = currentPrices.get(priceKey(price));
245
- if (before === void 0) prices.added.push(`${priceLabel(price)} ${formatMinor(price.amountMinor, price.currency)}`);
246
- else if (before.amountMinor !== price.amountMinor || before.taxInclusive !== price.taxInclusive || before.taxRateBps !== price.taxRateBps) {
247
- const terms = ({ amountMinor, taxInclusive, taxRateBps }) => ({
248
- amountMinor,
249
- taxInclusive,
250
- taxRateBps
251
- });
252
- prices.changed.push({
253
- label: priceLabel(price),
254
- id: before.id,
255
- currency: price.currency,
256
- from: terms(before),
257
- to: terms(price)
258
- });
259
- }
260
- }
261
- for (const [key, price] of currentPrices) if (!inputKeys.has(key)) prices.deactivated.push(`${priceLabel(price)} ${formatMinor(price.amountMinor, price.currency)}`);
262
- const credits = [];
263
- for (const [code, next] of Object.entries(input.benefits)) {
264
- const old = Object.hasOwn(currentBenefits, code) ? currentBenefits[code] : void 0;
265
- if (old === void 0 || old.type !== "meter_credit" || next.type !== "meter_credit") continue;
266
- const from = creditTerms(old.properties);
267
- const to = creditTerms(next.properties);
268
- if (from !== null && to !== null && canonical(from) !== canonical(to)) credits.push({
269
- code,
270
- from,
271
- to
272
- });
273
- }
274
- return {
275
- benefits,
276
- planBenefits,
277
- planListing,
278
- prices,
279
- meters: diffMeters(current, input),
280
- credits,
281
- meteredPrices: diffMeteredPrices(current, input)
282
- };
142
+ return diffCatalogSync(current, CatalogSyncInputSchema.parse(file), FORMAT);
283
143
  }
284
144
  function describePriceChange({ label, currency, from, to }) {
285
145
  const parts = [];
@@ -290,15 +150,15 @@ function describePriceChange({ label, currency, from, to }) {
290
150
  }
291
151
  function describeMeteredPriceChange({ label, currency, from, to }) {
292
152
  const parts = [];
293
- if (from.amountMinor !== to.amountMinor || from.perUnits !== to.perUnits) parts.push(`${meteredRate({
153
+ if (from.amountMinor !== to.amountMinor || from.perUnits !== to.perUnits) parts.push(`${meteredRateText({
294
154
  currency,
295
155
  amountMinor: from.amountMinor,
296
156
  perUnits: from.perUnits
297
- })} → ${meteredRate({
157
+ }, FORMAT)} → ${meteredRateText({
298
158
  currency,
299
159
  amountMinor: to.amountMinor,
300
160
  perUnits: to.perUnits
301
- })}`);
161
+ }, FORMAT)}`);
302
162
  if (from.capMinor !== to.capMinor) {
303
163
  const cap = (minor) => minor === null ? "none" : formatMinor(minor, currency);
304
164
  parts.push(`cap ${cap(from.capMinor)} → ${cap(to.capMinor)}`);
@@ -353,10 +213,6 @@ function describeDiff(diff) {
353
213
  }
354
214
  return lines.length > 0 ? ["changes against the current catalog:", ...lines] : [];
355
215
  }
356
- /** Price changes the operator confirms before the push: base prices and metered prices changed in place. */
357
- function priceChangeCount(diff) {
358
- return diff.prices.changed.length + diff.meteredPrices.changed.length;
359
- }
360
216
  // src/dotenv.ts
361
217
  const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
362
218
  function unquote(rest) {
@@ -522,193 +378,6 @@ function describeStewardError(error, target) {
522
378
  }
523
379
  return `steward response does not match the contract${where}: ${error.code} (HTTP ${error.httpStatus}) — the CLI and steward versions may be incompatible${request}`;
524
380
  }
525
- // src/commands/accounts.ts
526
- const ACCOUNTS_USAGE = `Usage:
527
- steward accounts get <ref> [--include <a,b>] [--json]
528
- steward accounts metadata set <ref> <key>=<value>… [--reason <text>] [--json]
529
- steward accounts metadata unset <ref> <key>… [--reason <text>] [--json]
530
-
531
- get reads an account (GET /v1/accounts/:ref): name, plan, the primary subscription and the
532
- metadata. Nothing is written.
533
-
534
- --include <a,b> also read profile, subscriptions, checkouts, payments, invoices, grants
535
- (comma separated). Subscriptions are listed, the others are counted; --json
536
- prints the whole response.
537
- --json print the response as JSON
538
-
539
- metadata set / unset change single metadata keys (PATCH /v1/accounts/:ref/metadata) and leave
540
- every other key as it is. Steward merges them in one atomic write, so the change cannot
541
- overwrite a key another writer (the product, another operator) changes at the same time. The
542
- command reads the account first, prints each key's value before and after, then sends the
543
- change. Steward records it in the audit trail with the key names, --reason and the operator;
544
- the account state does not change and no event is emitted. Running it again is harmless.
545
-
546
- <key>=<value> split at the first "="; key at most 64 characters, value at most 500. An
547
- empty value (key=) is stored as empty text; unset removes the key.
548
- --reason <text> why (3–500 characters); kept in the audit trail only
549
- --json print the updated account as JSON (the before → after lines go to stderr)
550
-
551
- The account must exist: these commands never create one (404 account_not_found). Metadata
552
- must not carry personal data (names, e-mail addresses, phone numbers): use opaque ids and
553
- flags. set and unset need a steward whose GET /v1/me lists the "account_metadata" capability.
554
-
555
- Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
556
- STEWARD_ADMIN_API_KEY). Environment, otherwise ./.env.local. Changes are sent with
557
- X-Actor-Ref operator:<user>.
558
- Exit code 1: steward refused (unknown or deleted account, no capability); 2: wrong usage,
559
- nothing was sent.`;
560
- const GET_OPTIONS$1 = {
561
- ...HELP_OPTION,
562
- include: { type: "string" },
563
- json: { type: "boolean" }
564
- };
565
- const METADATA_OPTIONS = {
566
- ...HELP_OPTION,
567
- reason: { type: "string" },
568
- json: { type: "boolean" }
569
- };
570
- /** A metadata value on one terminal line: as is, or JSON-quoted when empty, padded or with control characters. */
571
- function show(value) {
572
- return value === "" || value !== value.trim() || /\p{Cc}/u.test(value) ? JSON.stringify(value) : value;
573
- }
574
- /** Human-readable account read: name, plan, primary subscription, metadata, and the included parts. */
575
- function formatAccount(account) {
576
- const { snapshot } = account;
577
- const lines = [
578
- `account ${account.ref} · ${account.displayName}`,
579
- ` created ${account.createdAt}`,
580
- ` plan ${snapshot.planCode} · access ${snapshot.accessState}`
581
- ];
582
- const sub = snapshot.subscription;
583
- if (sub === null) lines.push(" subscription none");
584
- else {
585
- const ends = sub.cancelAt !== null ? `cancels at ${sub.cancelAt}` : `period ends ${sub.currentPeriodEnd ?? "-"}`;
586
- lines.push(` subscription ${sub.status} · ${sub.planCode} ${sub.interval} · ${formatMinor(sub.amountMinor, sub.currency)} · ${ends}`);
587
- }
588
- const keys = Object.keys(account.metadata);
589
- if (keys.length === 0) lines.push(" metadata none");
590
- else {
591
- lines.push(" metadata");
592
- const width = Math.max(...keys.map((key) => key.length));
593
- for (const key of keys) lines.push(` ${key.padEnd(width)} ${show(account.metadata[key])}`);
594
- }
595
- if (account.profile !== void 0) lines.push(` profile ${account.profile === null ? "none" : account.profile.kind}`);
596
- if (account.subscriptions !== void 0) {
597
- lines.push(` subscriptions ${account.subscriptions.length}`);
598
- for (const s of account.subscriptions) lines.push(` ${s.id} ${s.status} · ${s.planCode} ${s.interval} · ${formatMinor(s.amountMinor, s.currency)} · period ends ${s.currentPeriodEnd ?? "-"}`);
599
- }
600
- for (const part of [
601
- "checkouts",
602
- "payments",
603
- "invoices",
604
- "grants"
605
- ]) {
606
- const items = account[part];
607
- if (items !== void 0) lines.push(` ${part.padEnd(13)} ${items.length}${items.length > 0 ? " (--json for the details)" : ""}`);
608
- }
609
- return lines;
610
- }
611
- async function getCommand(ctx, out, args) {
612
- const { values, positionals } = parse(args, GET_OPTIONS$1, "accounts");
613
- if (values.help) {
614
- out.out(ACCOUNTS_USAGE);
615
- return 0;
616
- }
617
- expectPositionals(positionals, 1, 1, "accounts");
618
- const ref = positionals[0];
619
- const include = values.include === void 0 ? [] : parseList(values.include);
620
- const unknown = include.filter((item) => !ACCOUNT_INCLUDES.includes(item));
621
- if (unknown.length > 0) throw new UsageError(`--include: unknown ${unknown.join(", ")} (one of: ${ACCOUNT_INCLUDES.join(", ")})`);
622
- const target = requireReadTarget(await resolveEnv(ctx));
623
- out.err(connectionLine(target));
624
- const account = await callSteward(target, () => clientFor(ctx, target).accounts.get(ref, { include }));
625
- if (values.json) out.out(JSON.stringify(account, null, 2));
626
- else for (const line of formatAccount(account)) out.out(line);
627
- return 0;
628
- }
629
- /** `key=value` arguments (split at the first `=`) or bare keys → the patch: a value sets, `null` removes. */
630
- function parseMetadataChange(action, items) {
631
- const change = /* @__PURE__ */ new Map();
632
- for (const item of items) {
633
- const at = action === "set" ? item.indexOf("=") : item.length;
634
- if (at <= 0) throw new UsageError(action === "set" ? `expected key=value, got "${item}"` : "a key cannot be empty");
635
- const key = item.slice(0, at);
636
- if (key === "__proto__") throw new UsageError("key \"__proto__\" is not accepted");
637
- if (change.has(key)) throw new UsageError(`key "${key}" given twice`);
638
- change.set(key, action === "set" ? item.slice(at + 1) : null);
639
- }
640
- return Object.fromEntries(change);
641
- }
642
- /** One line per key of the patch: its value now and after the patch. */
643
- function changeLines(current, change) {
644
- return Object.entries(change).map(([key, value]) => {
645
- const before = Object.hasOwn(current, key) ? current[key] : null;
646
- const from = before === null ? "(none)" : show(before);
647
- if (value === null) return ` ${key}: ${from} → ${before === null ? "(none) (unchanged)" : "(removed)"}`;
648
- return ` ${key}: ${from} → ${show(value)}${before === value ? " (unchanged)" : ""}`;
649
- });
650
- }
651
- /** An older steward has no metadata patch endpoint: its 404 would read like a missing account. */
652
- async function requireMetadataCapability(steward, target) {
653
- if (((await callSteward(target, () => steward.me())).capabilities ?? []).includes("account_metadata")) return;
654
- throw new CliError(`steward at ${originOf(target.url)} does not support changing single metadata keys (GET /v1/me capabilities has no "account_metadata"). Update steward first; nothing was sent.`);
655
- }
656
- async function metadataCommand(ctx, out, args) {
657
- const [action, ...rest] = args;
658
- if (action === void 0 || action === "--help" || action === "-h" || action === "help") {
659
- out.out(ACCOUNTS_USAGE);
660
- return action === void 0 ? 2 : 0;
661
- }
662
- if (action !== "set" && action !== "unset") throw new UsageError(`unknown subcommand: accounts metadata ${action} (see: steward accounts --help)`);
663
- const { values, positionals } = parse(rest, METADATA_OPTIONS, "accounts");
664
- if (values.help) {
665
- out.out(ACCOUNTS_USAGE);
666
- return 0;
667
- }
668
- expectPositionals(positionals, 2, 101, "accounts");
669
- const [ref, ...items] = positionals;
670
- const input = AccountMetadataPatchInputSchema.safeParse({
671
- metadata: parseMetadataChange(action, items),
672
- ...values.reason !== void 0 ? { reason: values.reason } : {}
673
- });
674
- if (!input.success) throw new UsageError(`invalid metadata change (nothing was sent)\n${input.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
675
- const target = requireReadTarget(await resolveEnv(ctx));
676
- out.err(connectionLine(target));
677
- const steward = clientFor(ctx, target);
678
- await requireMetadataCapability(steward, target);
679
- const current = await callSteward(target, () => steward.accounts.get(ref));
680
- const say = values.json ? out.err : out.out;
681
- say(`metadata of ${ref}:`);
682
- for (const line of changeLines(current.metadata, input.data.metadata)) say(line);
683
- const updated = await callSteward(target, () => steward.accounts.updateMetadata(ref, input.data));
684
- if (values.json) out.out(JSON.stringify(updated, null, 2));
685
- else {
686
- const count = Object.keys(updated.metadata).length;
687
- out.out(`written → ${originOf(target.url)}: ${ref} now has ${count} metadata key${count === 1 ? "" : "s"}`);
688
- }
689
- return 0;
690
- }
691
- async function accountsCommand(ctx, out, args) {
692
- const [sub, ...rest] = args;
693
- if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
694
- out.out(ACCOUNTS_USAGE);
695
- return sub === void 0 ? 2 : 0;
696
- }
697
- if (sub === "get") return getCommand(ctx, out, rest);
698
- if (sub === "metadata") return metadataCommand(ctx, out, rest);
699
- throw new UsageError(`unknown subcommand: accounts ${sub} (see: steward accounts --help)`);
700
- }
701
- // src/confirm.ts
702
- /**
703
- * Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
704
- * terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
705
- */
706
- async function confirm(ctx, question, options) {
707
- if (options.yes) return true;
708
- const answer = await ctx.prompt(`${question} [y/N] `);
709
- if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
710
- return /^y(es)?$/i.test(answer.trim());
711
- }
712
381
  // src/secret-file.ts
713
382
  async function withSecretFile(cwd, out, secret, options, action) {
714
383
  const target = resolve(cwd, out);
@@ -798,7 +467,7 @@ async function endpointsCommand(ctx, out, args) {
798
467
  ...HELP_OPTION,
799
468
  json: { type: "boolean" }
800
469
  }, "endpoints");
801
- if (values.help) return help$6(out);
470
+ if (values.help) return help$7(out);
802
471
  expectPositionals(positionals, 0, 0, "endpoints");
803
472
  const target = requireAdminTarget(await resolveEnv(ctx));
804
473
  out.err(connectionLine(target));
@@ -833,7 +502,7 @@ async function endpointsCommand(ctx, out, args) {
833
502
  description: { type: "string" },
834
503
  force: { type: "boolean" }
835
504
  }, ENDPOINTS_USAGE);
836
- if (values.help) return help$6(out);
505
+ if (values.help) return help$7(out);
837
506
  expectPositionals(positionals, 0, 0, "endpoints");
838
507
  const url = requireOption(values.url, "--url", "endpoints");
839
508
  const file = requireOption(values.out, "--out", "endpoints");
@@ -858,50 +527,442 @@ async function endpointsCommand(ctx, out, args) {
858
527
  secretNotice(out, result.path, result.fallback, "Move the secret into the product's Secret (STEWARD_WEBHOOK_SECRET), then delete the file.");
859
528
  return 0;
860
529
  }
861
- if (sub === "rotate") {
862
- const { values, positionals } = parse(rest, {
863
- ...HELP_OPTION,
864
- out: { type: "string" },
865
- force: { type: "boolean" }
866
- }, "endpoints");
867
- if (values.help) return help$6(out);
868
- expectPositionals(positionals, 1, 1, "endpoints");
869
- const id = positionals[0];
870
- const file = requireOption(values.out, "--out", "endpoints");
871
- const secret = generateWebhookSecret();
872
- const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
873
- if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems$1(parsed.error.issues)}`);
874
- const target = requireAdminTarget(await resolveEnv(ctx));
875
- out.err(connectionLine(target));
876
- const steward = clientFor(ctx, target);
877
- const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
878
- out.out(`secret rotated → ${originOf(target.url)}`);
879
- out.out(` id ${result.value.id}`);
880
- out.out(` url ${result.value.url}`);
881
- secretNotice(out, result.path, result.fallback, "Set STEWARD_WEBHOOK_SECRET in the product's Secret to \"new,old\" and roll out; the old secret stays in steward as a second signature for the transition. Then delete the file.");
530
+ if (sub === "rotate") {
531
+ const { values, positionals } = parse(rest, {
532
+ ...HELP_OPTION,
533
+ out: { type: "string" },
534
+ force: { type: "boolean" }
535
+ }, "endpoints");
536
+ if (values.help) return help$7(out);
537
+ expectPositionals(positionals, 1, 1, "endpoints");
538
+ const id = positionals[0];
539
+ const file = requireOption(values.out, "--out", "endpoints");
540
+ const secret = generateWebhookSecret();
541
+ const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
542
+ if (!parsed.success) throw new UsageError(`invalid secret\n${schemaProblems$1(parsed.error.issues)}`);
543
+ const target = requireAdminTarget(await resolveEnv(ctx));
544
+ out.err(connectionLine(target));
545
+ const steward = clientFor(ctx, target);
546
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
547
+ out.out(`secret rotated → ${originOf(target.url)}`);
548
+ out.out(` id ${result.value.id}`);
549
+ out.out(` url ${result.value.url}`);
550
+ secretNotice(out, result.path, result.fallback, "Set STEWARD_WEBHOOK_SECRET in the product's Secret to \"new,old\" and roll out; the old secret stays in steward as a second signature for the transition. Then delete the file.");
551
+ return 0;
552
+ }
553
+ if (sub === "deactivate") {
554
+ const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
555
+ if (values.help) return help$7(out);
556
+ expectPositionals(positionals, 1, 1, "endpoints");
557
+ const target = requireAdminTarget(await resolveEnv(ctx));
558
+ out.err(connectionLine(target));
559
+ const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
560
+ out.out(`endpoint deactivated → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, status ${endpoint.status})`);
561
+ return 0;
562
+ }
563
+ throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
564
+ }
565
+ function help$7(out) {
566
+ out.out(ENDPOINTS_USAGE);
567
+ return 0;
568
+ }
569
+ /** Where a generated secret went (`withSecretFile`); shared by `endpoints` and `keys`. */
570
+ function secretNotice(out, path, fallback, next) {
571
+ if (fallback) out.err(`! the secret could not be moved to the target file (it may have been created meanwhile); it is in ${path} (0600)`);
572
+ out.out(` secret ${path} (0600; not written to the terminal)`);
573
+ out.err(next);
574
+ }
575
+ // src/commands/list-options.ts
576
+ /** An optional flag's value checked against a contract schema; `message` (it names the flag) when it does not match. */
577
+ function checkedOption(value, schema, message) {
578
+ if (value === void 0) return void 0;
579
+ const parsed = schema.safeParse(value);
580
+ if (!parsed.success) throw new UsageError(message);
581
+ return parsed.data;
582
+ }
583
+ /** `--account <ref>`: the product's external ref of an account. */
584
+ const accountOption = (value) => checkedOption(value, ExternalRefSchema, "--account: an account ref (letters, digits and _ . : -)");
585
+ /**
586
+ * `--from` (inclusive) / `--to` (exclusive): ISO-8601 with an offset (a bare local time would depend on
587
+ * this machine's time zone). The flag names stay inside the messages: the package check
588
+ * (`scripts/check-pack.mjs`) reads a quoted flag name that ends with the word from as an import.
589
+ */
590
+ function periodOptions(values) {
591
+ return {
592
+ from: checkedOption(values.from, DateTimeSchema, "--from: ISO-8601 with an offset, e.g. 2026-10-01T00:00:00Z"),
593
+ to: checkedOption(values.to, DateTimeSchema, "--to: ISO-8601 with an offset, e.g. 2026-10-01T00:00:00Z")
594
+ };
595
+ }
596
+ /** Free text of 1–`max` characters (`--search`, `--type`, `--action`, `--source`). */
597
+ function textOption(value, flag, max) {
598
+ if (value !== void 0 && (value.length === 0 || value.length > max)) throw new UsageError(`${flag}: 1–${max} characters`);
599
+ return value;
600
+ }
601
+ const limitOption = (value) => value === void 0 ? void 0 : parsePositiveInt(value, "--limit", { max: ADMIN_LIST_MAX_LIMIT });
602
+ /** The filter without its unset options: the contract's filter types take no explicit `undefined`. */
603
+ function definedOnly(filter) {
604
+ return Object.fromEntries(Object.entries(filter).filter(([, value]) => value !== void 0));
605
+ }
606
+ /** The stderr line of a cut list: how many were listed and the `--after` value of the next page. */
607
+ function nextPageLine(noun, limit, cursor) {
608
+ return `more ${noun} than the ${limit ?? ADMIN_LIST_DEFAULT_LIMIT} listed; next page: --after ${cursor}`;
609
+ }
610
+ // src/commands/accounts.ts
611
+ const ACCOUNTS_USAGE = `Usage:
612
+ steward accounts get <ref> [--include <a,b>] [--json]
613
+ steward accounts list [--search <text>] [--status <status>] [--plan <code>]
614
+ [--deleted exclude|include|only] [--limit <n>] [--after <ref>] [--json]
615
+ steward accounts metadata set <ref> <key>=<value>… [--reason <text>] [--json]
616
+ steward accounts metadata unset <ref> <key>… [--reason <text>] [--json]
617
+
618
+ get reads an account (GET /v1/accounts/:ref): name, plan, the primary subscription and the
619
+ metadata. Nothing is written.
620
+
621
+ --include <a,b> also read profile, subscriptions, checkouts, payments, invoices, grants
622
+ (comma separated). Subscriptions are listed, the others are counted; --json
623
+ prints the whole response.
624
+ --json print the response as JSON
625
+
626
+ list (admin) finds accounts without their exact ref: the product's accounts in ref order, one
627
+ line per account with its billing currency and live subscriptions (GET /v1/admin/accounts).
628
+ Nothing personal is listed (no billing profile, no notification address): get <ref> --include
629
+ profile reads one account's profile.
630
+
631
+ --search <text> the ref starts with it, or the display name contains it (case-insensitive,
632
+ 1–${ACCOUNT_LIST_QUERY_MAX} characters)
633
+ --status <status> accounts with a subscription in that status: active, past_due, suspended,
634
+ canceled or expired
635
+ --plan <code> accounts with a live subscription (active, past_due, suspended) of that plan;
636
+ with --status, a subscription of that plan in that status. A code the product
637
+ never had is refused (plan_not_found).
638
+ --deleted exclude (default): accounts that are not deleted; only: deleted (anonymized)
639
+ ones, shown as "(deleted <time>)"; include: both
640
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
641
+ (the last REF) of the next page
642
+ --json print the items as JSON
643
+
644
+ metadata set / unset change single metadata keys (PATCH /v1/accounts/:ref/metadata) and leave
645
+ every other key as it is. Steward merges them in one atomic write, so the change cannot
646
+ overwrite a key another writer (the product, another operator) changes at the same time. The
647
+ command reads the account first, prints each key's value before and after, then sends the
648
+ change. Steward records it in the audit trail with the key names, --reason and the operator;
649
+ the account state does not change and no event is emitted. Running it again is harmless.
650
+
651
+ <key>=<value> split at the first "="; key at most 64 characters, value at most 500. An
652
+ empty value (key=) is stored as empty text; unset removes the key.
653
+ --reason <text> why (3–500 characters); kept in the audit trail only
654
+ --json print the updated account as JSON (the before → after lines go to stderr)
655
+
656
+ The account must exist: these commands never create one (404 account_not_found). Metadata
657
+ must not carry personal data (names, e-mail addresses, phone numbers): use opaque ids and
658
+ flags. set and unset need a steward whose GET /v1/me lists the "account_metadata" capability.
659
+
660
+ Connection: get and metadata use STEWARD_URL + STEWARD_API_KEY (or, when neither is set,
661
+ STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY); list uses STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY.
662
+ Environment, otherwise ./.env.local. Changes are sent with X-Actor-Ref operator:<user>.
663
+ Exit code 1: steward refused (unknown or deleted account, unknown plan, no capability); 2: wrong
664
+ usage, nothing was sent.`;
665
+ const GET_OPTIONS$1 = {
666
+ ...HELP_OPTION,
667
+ include: { type: "string" },
668
+ json: { type: "boolean" }
669
+ };
670
+ const LIST_OPTIONS$4 = {
671
+ ...HELP_OPTION,
672
+ search: { type: "string" },
673
+ status: { type: "string" },
674
+ plan: { type: "string" },
675
+ deleted: { type: "string" },
676
+ limit: { type: "string" },
677
+ after: { type: "string" },
678
+ json: { type: "boolean" }
679
+ };
680
+ const METADATA_OPTIONS = {
681
+ ...HELP_OPTION,
682
+ reason: { type: "string" },
683
+ json: { type: "boolean" }
684
+ };
685
+ /** A metadata value on one terminal line: as is, or JSON-quoted when empty, padded or with control characters. */
686
+ function show(value) {
687
+ return value === "" || value !== value.trim() || /\p{Cc}/u.test(value) ? JSON.stringify(value) : value;
688
+ }
689
+ /** Human-readable account read: name, plan, primary subscription, metadata, and the included parts. */
690
+ function formatAccount(account) {
691
+ const { snapshot } = account;
692
+ const lines = [
693
+ `account ${account.ref} · ${account.displayName}`,
694
+ ` created ${account.createdAt}`,
695
+ ` plan ${snapshot.planCode} · access ${snapshot.accessState}`
696
+ ];
697
+ const sub = snapshot.subscription;
698
+ if (sub === null) lines.push(" subscription none");
699
+ else {
700
+ const ends = sub.cancelAt !== null ? `cancels at ${sub.cancelAt}` : `period ends ${sub.currentPeriodEnd ?? "-"}`;
701
+ lines.push(` subscription ${sub.status} · ${sub.planCode} ${sub.interval} · ${formatMinor(sub.amountMinor, sub.currency)} · ${ends}`);
702
+ }
703
+ const keys = Object.keys(account.metadata);
704
+ if (keys.length === 0) lines.push(" metadata none");
705
+ else {
706
+ lines.push(" metadata");
707
+ const width = Math.max(...keys.map((key) => key.length));
708
+ for (const key of keys) lines.push(` ${key.padEnd(width)} ${show(account.metadata[key])}`);
709
+ }
710
+ if (account.profile !== void 0) lines.push(` profile ${account.profile === null ? "none" : account.profile.kind}`);
711
+ if (account.subscriptions !== void 0) {
712
+ lines.push(` subscriptions ${account.subscriptions.length}`);
713
+ for (const s of account.subscriptions) lines.push(` ${s.id} ${s.status} · ${s.planCode} ${s.interval} · ${formatMinor(s.amountMinor, s.currency)} · period ends ${s.currentPeriodEnd ?? "-"}`);
714
+ }
715
+ for (const part of [
716
+ "checkouts",
717
+ "payments",
718
+ "invoices",
719
+ "grants"
720
+ ]) {
721
+ const items = account[part];
722
+ if (items !== void 0) lines.push(` ${part.padEnd(13)} ${items.length}${items.length > 0 ? " (--json for the details)" : ""}`);
723
+ }
724
+ return lines;
725
+ }
726
+ async function getCommand(ctx, out, args) {
727
+ const { values, positionals } = parse(args, GET_OPTIONS$1, "accounts");
728
+ if (values.help) {
729
+ out.out(ACCOUNTS_USAGE);
730
+ return 0;
731
+ }
732
+ expectPositionals(positionals, 1, 1, "accounts");
733
+ const ref = positionals[0];
734
+ const include = values.include === void 0 ? [] : parseList(values.include);
735
+ const unknown = include.filter((item) => !ACCOUNT_INCLUDES.includes(item));
736
+ if (unknown.length > 0) throw new UsageError(`--include: unknown ${unknown.join(", ")} (one of: ${ACCOUNT_INCLUDES.join(", ")})`);
737
+ const target = requireReadTarget(await resolveEnv(ctx));
738
+ out.err(connectionLine(target));
739
+ const account = await callSteward(target, () => clientFor(ctx, target).accounts.get(ref, { include }));
740
+ if (values.json) out.out(JSON.stringify(account, null, 2));
741
+ else for (const line of formatAccount(account)) out.out(line);
742
+ return 0;
743
+ }
744
+ async function listCommand$1(ctx, out, args) {
745
+ const { values, positionals } = parse(args, LIST_OPTIONS$4, "accounts");
746
+ if (values.help) {
747
+ out.out(ACCOUNTS_USAGE);
748
+ return 0;
749
+ }
750
+ expectPositionals(positionals, 0, 0, "accounts");
751
+ const limit = limitOption(values.limit);
752
+ const filter = definedOnly({
753
+ q: textOption(values.search, "--search", ACCOUNT_LIST_QUERY_MAX),
754
+ status: checkedOption(values.status, SubscriptionStatusSchema, `--status: one of ${SubscriptionStatusSchema.options.join(", ")}`),
755
+ plan: checkedOption(values.plan, CodeSchema, "--plan: a plan code"),
756
+ deleted: checkedOption(values.deleted, AccountListDeletedFilterSchema, "--deleted: exclude, include or only"),
757
+ limit,
758
+ after: checkedOption(values.after, ExternalRefSchema, "--after: an account ref (the last REF of the previous page)")
759
+ });
760
+ const target = requireAdminTarget(await resolveEnv(ctx));
761
+ out.err(connectionLine(target));
762
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.accounts.list(filter));
763
+ if (values.json) out.out(JSON.stringify(items, null, 2));
764
+ else if (items.length === 0) out.out("no accounts");
765
+ else {
766
+ const rows = [[
767
+ "REF",
768
+ "NAME",
769
+ "CREATED",
770
+ "CURRENCY",
771
+ "SUBSCRIPTIONS"
772
+ ]];
773
+ for (const a of items) rows.push([
774
+ a.ref,
775
+ a.deletedAt !== null ? `(deleted ${a.deletedAt})` : a.displayName || "-",
776
+ a.createdAt,
777
+ a.billingCurrency ?? "-",
778
+ a.liveSubscriptions.map((s) => `${s.planCode}/${s.interval} ${s.status}`).join(", ") || "-"
779
+ ]);
780
+ for (const line of table(rows)) out.out(line);
781
+ }
782
+ const last = items.at(-1);
783
+ if (hasMore && last !== void 0) out.err(nextPageLine("accounts", limit, last.ref));
784
+ return 0;
785
+ }
786
+ /** `key=value` arguments (split at the first `=`) or bare keys → the patch: a value sets, `null` removes. */
787
+ function parseMetadataChange(action, items) {
788
+ const change = /* @__PURE__ */ new Map();
789
+ for (const item of items) {
790
+ const at = action === "set" ? item.indexOf("=") : item.length;
791
+ if (at <= 0) throw new UsageError(action === "set" ? `expected key=value, got "${item}"` : "a key cannot be empty");
792
+ const key = item.slice(0, at);
793
+ if (key === "__proto__") throw new UsageError("key \"__proto__\" is not accepted");
794
+ if (change.has(key)) throw new UsageError(`key "${key}" given twice`);
795
+ change.set(key, action === "set" ? item.slice(at + 1) : null);
796
+ }
797
+ return Object.fromEntries(change);
798
+ }
799
+ /** One line per key of the patch: its value now and after the patch. */
800
+ function changeLines(current, change) {
801
+ return Object.entries(change).map(([key, value]) => {
802
+ const before = Object.hasOwn(current, key) ? current[key] : null;
803
+ const from = before === null ? "(none)" : show(before);
804
+ if (value === null) return ` ${key}: ${from} → ${before === null ? "(none) (unchanged)" : "(removed)"}`;
805
+ return ` ${key}: ${from} → ${show(value)}${before === value ? " (unchanged)" : ""}`;
806
+ });
807
+ }
808
+ /** An older steward has no metadata patch endpoint: its 404 would read like a missing account. */
809
+ async function requireMetadataCapability(steward, target) {
810
+ if (((await callSteward(target, () => steward.me())).capabilities ?? []).includes("account_metadata")) return;
811
+ throw new CliError(`steward at ${originOf(target.url)} does not support changing single metadata keys (GET /v1/me capabilities has no "account_metadata"). Update steward first; nothing was sent.`);
812
+ }
813
+ async function metadataCommand(ctx, out, args) {
814
+ const [action, ...rest] = args;
815
+ if (action === void 0 || action === "--help" || action === "-h" || action === "help") {
816
+ out.out(ACCOUNTS_USAGE);
817
+ return action === void 0 ? 2 : 0;
818
+ }
819
+ if (action !== "set" && action !== "unset") throw new UsageError(`unknown subcommand: accounts metadata ${action} (see: steward accounts --help)`);
820
+ const { values, positionals } = parse(rest, METADATA_OPTIONS, "accounts");
821
+ if (values.help) {
822
+ out.out(ACCOUNTS_USAGE);
882
823
  return 0;
883
824
  }
884
- if (sub === "deactivate") {
885
- const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
886
- if (values.help) return help$6(out);
887
- expectPositionals(positionals, 1, 1, "endpoints");
888
- const target = requireAdminTarget(await resolveEnv(ctx));
889
- out.err(connectionLine(target));
890
- const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
891
- out.out(`endpoint deactivated → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, status ${endpoint.status})`);
892
- return 0;
825
+ expectPositionals(positionals, 2, 101, "accounts");
826
+ const [ref, ...items] = positionals;
827
+ const input = AccountMetadataPatchInputSchema.safeParse({
828
+ metadata: parseMetadataChange(action, items),
829
+ ...values.reason !== void 0 ? { reason: values.reason } : {}
830
+ });
831
+ if (!input.success) throw new UsageError(`invalid metadata change (nothing was sent)\n${input.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
832
+ const target = requireReadTarget(await resolveEnv(ctx));
833
+ out.err(connectionLine(target));
834
+ const steward = clientFor(ctx, target);
835
+ await requireMetadataCapability(steward, target);
836
+ const current = await callSteward(target, () => steward.accounts.get(ref));
837
+ const say = values.json ? out.err : out.out;
838
+ say(`metadata of ${ref}:`);
839
+ for (const line of changeLines(current.metadata, input.data.metadata)) say(line);
840
+ const updated = await callSteward(target, () => steward.accounts.updateMetadata(ref, input.data));
841
+ if (values.json) out.out(JSON.stringify(updated, null, 2));
842
+ else {
843
+ const count = Object.keys(updated.metadata).length;
844
+ out.out(`written → ${originOf(target.url)}: ${ref} now has ${count} metadata key${count === 1 ? "" : "s"}`);
893
845
  }
894
- throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
846
+ return 0;
895
847
  }
896
- function help$6(out) {
897
- out.out(ENDPOINTS_USAGE);
848
+ async function accountsCommand(ctx, out, args) {
849
+ const [sub, ...rest] = args;
850
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
851
+ out.out(ACCOUNTS_USAGE);
852
+ return sub === void 0 ? 2 : 0;
853
+ }
854
+ if (sub === "get") return getCommand(ctx, out, rest);
855
+ if (sub === "list") return listCommand$1(ctx, out, rest);
856
+ if (sub === "metadata") return metadataCommand(ctx, out, rest);
857
+ throw new UsageError(`unknown subcommand: accounts ${sub} (see: steward accounts --help)`);
858
+ }
859
+ // src/commands/audit.ts
860
+ const AUDIT_USAGE = `Usage:
861
+ steward audit list [--account <ref>] [--action <action>] [--api-key <prefix>] [--console-user <id>]
862
+ [--source <source>] [--from <iso>] [--to <iso>] [--limit <n>] [--after <id>] [--json]
863
+
864
+ The product's audit trail, newest first, one line per row (GET /v1/admin/audit): when, the
865
+ action (e.g. subscription.canceled, api_key.created), the account, who wrote it and the actor.
866
+ WHO is the API key's prefix for a /v1 request (key a1b2c3d4e5f6), the console user's id for an
867
+ operator console request (console <id>), otherwise the source: job:<name>, cli (the pod CLI),
868
+ hosted or provider_webhook. ACTOR is what the caller reported about itself (X-Actor-Ref, e.g.
869
+ operator:ada), not proof of identity. Reads are not audited.
870
+
871
+ --account <ref> one account's rows (an unknown ref is account_not_found)
872
+ --action <action> one action, exact
873
+ --api-key <prefix> rows written with one API key: the 12 hex characters after stw_ (keys list)
874
+ --console-user <id> rows written by one console user, by id (as WHO shows it)
875
+ --source <source> rows of one source, exact (e.g. job:dunning, hosted)
876
+ --from <iso> written at or after (inclusive); ISO-8601 with an offset
877
+ --to <iso> written before (exclusive); ISO-8601 with an offset
878
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
879
+ (the last row's id) of the next page
880
+ --json print the items as JSON, with each row's writer, request id and detail (its
881
+ own record of what changed; an admin.request row carries the client IP)
882
+
883
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
884
+ const LIST_OPTIONS$3 = {
885
+ ...HELP_OPTION,
886
+ account: { type: "string" },
887
+ action: { type: "string" },
888
+ "api-key": { type: "string" },
889
+ "console-user": { type: "string" },
890
+ source: { type: "string" },
891
+ from: { type: "string" },
892
+ to: { type: "string" },
893
+ limit: { type: "string" },
894
+ after: { type: "string" },
895
+ json: { type: "boolean" }
896
+ };
897
+ /** Who wrote the row: the API key of a /v1 request, the console user of a console request, otherwise its source. */
898
+ function writerOf(writer) {
899
+ if (writer === null) return "-";
900
+ switch (writer.kind) {
901
+ case "api_key": return `key ${writer.prefix}`;
902
+ case "console_user": return `console ${writer.id}`;
903
+ case "source": return writer.source;
904
+ }
905
+ }
906
+ async function auditCommand(ctx, out, args) {
907
+ const [sub, ...rest] = args;
908
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
909
+ out.out(AUDIT_USAGE);
910
+ return sub === void 0 ? 2 : 0;
911
+ }
912
+ if (sub !== "list") throw new UsageError(`unknown subcommand: audit ${sub} (see: steward audit --help)`);
913
+ const { values, positionals } = parse(rest, LIST_OPTIONS$3, "audit");
914
+ if (values.help) {
915
+ out.out(AUDIT_USAGE);
916
+ return 0;
917
+ }
918
+ expectPositionals(positionals, 0, 0, "audit");
919
+ const limit = limitOption(values.limit);
920
+ const filter = definedOnly({
921
+ account: accountOption(values.account),
922
+ action: textOption(values.action, "--action", AUDIT_LIST_FILTER_MAX),
923
+ apiKey: checkedOption(values["api-key"], ApiKeyPrefixSchema, "--api-key: a key prefix, the 12 hex characters after stw_"),
924
+ consoleUser: checkedOption(values["console-user"], IdSchema, "--console-user: a console user id"),
925
+ source: textOption(values.source, "--source", AUDIT_LIST_FILTER_MAX),
926
+ ...periodOptions(values),
927
+ limit,
928
+ after: checkedOption(values.after, IdSchema, "--after: an audit row id")
929
+ });
930
+ const target = requireAdminTarget(await resolveEnv(ctx));
931
+ out.err(connectionLine(target));
932
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.audit.list(filter));
933
+ if (values.json) out.out(JSON.stringify(items, null, 2));
934
+ else if (items.length === 0) out.out("no audit rows");
935
+ else {
936
+ const rows = [[
937
+ "TIME",
938
+ "ACTION",
939
+ "ACCOUNT",
940
+ "WHO",
941
+ "ACTOR"
942
+ ]];
943
+ for (const row of items) rows.push([
944
+ row.createdAt,
945
+ row.action,
946
+ row.accountRef ?? "-",
947
+ writerOf(row.writer),
948
+ row.actorRef ?? "-"
949
+ ]);
950
+ for (const line of table(rows)) out.out(line);
951
+ }
952
+ const last = items.at(-1);
953
+ if (hasMore && last !== void 0) out.err(nextPageLine("audit rows", limit, last.id));
898
954
  return 0;
899
955
  }
900
- /** Where a generated secret went (`withSecretFile`); shared by `endpoints` and `keys`. */
901
- function secretNotice(out, path, fallback, next) {
902
- if (fallback) out.err(`! the secret could not be moved to the target file (it may have been created meanwhile); it is in ${path} (0600)`);
903
- out.out(` secret ${path} (0600; not written to the terminal)`);
904
- out.err(next);
956
+ // src/confirm.ts
957
+ /**
958
+ * Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
959
+ * terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
960
+ */
961
+ async function confirm(ctx, question, options) {
962
+ if (options.yes) return true;
963
+ const answer = await ctx.prompt(`${question} [y/N] `);
964
+ if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
965
+ return /^y(es)?$/i.test(answer.trim());
905
966
  }
906
967
  // src/commands/bank-transfers.ts
907
968
  const BANK_TRANSFERS_USAGE = `Usage:
@@ -965,7 +1026,7 @@ async function bankTransfersCommand(ctx, out, args) {
965
1026
  currency: { type: "string" },
966
1027
  json: { type: "boolean" }
967
1028
  }, "bank-transfers");
968
- if (values.help) return help$5(out);
1029
+ if (values.help) return help$6(out);
969
1030
  expectPositionals(positionals, 0, 0, "bank-transfers");
970
1031
  const status = values.status ?? "pending";
971
1032
  if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
@@ -1027,7 +1088,7 @@ async function bankTransfersCommand(ctx, out, args) {
1027
1088
  },
1028
1089
  json: { type: "boolean" }
1029
1090
  }, "bank-transfers");
1030
- if (values.help) return help$5(out);
1091
+ if (values.help) return help$6(out);
1031
1092
  expectPositionals(positionals, 1, 1, "bank-transfers");
1032
1093
  const receivedAt = requireOption(values["received-at"], "--received-at", "bank-transfers");
1033
1094
  if (!WITH_OFFSET$1.test(receivedAt)) throw new UsageError("--received-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
@@ -1071,7 +1132,7 @@ async function bankTransfersCommand(ctx, out, args) {
1071
1132
  json: { type: "boolean" },
1072
1133
  csv: { type: "boolean" }
1073
1134
  }, "bank-transfers");
1074
- if (values.help) return help$5(out);
1135
+ if (values.help) return help$6(out);
1075
1136
  expectPositionals(positionals, 0, 0, "bank-transfers");
1076
1137
  if (values.json && values.csv) throw new UsageError("--json or --csv, not both");
1077
1138
  if (values.from !== void 0 && !WITH_OFFSET$1.test(values.from)) throw new UsageError("--from: ISO-8601 with an offset (2026-09-01T00:00:00+03:00)");
@@ -1136,7 +1197,7 @@ function csvField(value) {
1136
1197
  const text = typeof value === "string" && /^[=+\-@]/.test(value) ? `'${value}` : String(value);
1137
1198
  return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
1138
1199
  }
1139
- function help$5(out) {
1200
+ function help$6(out) {
1140
1201
  out.out(BANK_TRANSFERS_USAGE);
1141
1202
  return 0;
1142
1203
  }
@@ -1758,7 +1819,7 @@ async function dunningCommand(ctx, out, args) {
1758
1819
  ...HELP_OPTION,
1759
1820
  json: { type: "boolean" }
1760
1821
  }, "dunning");
1761
- if (values.help) return help$4(out);
1822
+ if (values.help) return help$5(out);
1762
1823
  expectPositionals(positionals, 0, 0, "dunning");
1763
1824
  const target = requireAdminTarget(await resolveEnv(ctx));
1764
1825
  out.err(connectionLine(target));
@@ -1775,7 +1836,7 @@ async function dunningCommand(ctx, out, args) {
1775
1836
  short: "y"
1776
1837
  }
1777
1838
  }, "dunning");
1778
- if (values.help) return help$4(out);
1839
+ if (values.help) return help$5(out);
1779
1840
  expectPositionals(positionals, 1, 1, "dunning");
1780
1841
  const file = positionals[0];
1781
1842
  let json;
@@ -1808,10 +1869,236 @@ async function dunningCommand(ctx, out, args) {
1808
1869
  }
1809
1870
  throw new UsageError(`unknown subcommand: dunning ${sub} (see: steward dunning --help)`);
1810
1871
  }
1811
- function help$4(out) {
1872
+ function help$5(out) {
1812
1873
  out.out(DUNNING_USAGE);
1813
1874
  return 0;
1814
1875
  }
1876
+ // src/commands/discounts.ts
1877
+ const DISCOUNTS_USAGE = `Usage:
1878
+ steward discounts list [--archived] [--json]
1879
+ steward discounts create --name <text> (--percent <n> | --amount <CUR:minor>...) --duration once|repeating|forever
1880
+ [--months <n>] [--code <code>] [--plans <a,b>] [--starts <iso>] [--ends <iso>]
1881
+ [--max <n>] [--per-customer <n>|unlimited] [--json]
1882
+ steward discounts update <id> [--name …] [--code <code>|none] [--plans <a,b>|none] [--starts <iso>|none]
1883
+ [--ends <iso>|none] [--max <n>|none] [--per-customer <n>|unlimited]
1884
+ [--percent … | --amount …] [--duration … --months …] [--json]
1885
+ steward discounts archive <id> [--yes]
1886
+
1887
+ The product's discounts (/v1/admin/discounts): a share (--percent 20, up to 99.99) or an amount per
1888
+ currency in minor units (--amount USD:500 --amount EUR:450) off a plan's base price, for the first
1889
+ invoice (once), --months calendar months (repeating) or every invoice (forever). A discount with
1890
+ --code is entered by the customer on the hosted checkout; one without is applied by the product
1891
+ (checkout.create({ discountId })). Codes are case-insensitive. --plans restricts it (default:
1892
+ every listed plan). --per-customer defaults to 1. Once redeemed, its value and duration no
1893
+ longer change; archive it and create another instead.
1894
+
1895
+ create warns when the discount would bring a sellable price of the catalog to zero or under the
1896
+ payment provider's minimum charge (such a price refuses the code at checkout).
1897
+
1898
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
1899
+ /** The provider minimums the warning knows (Stripe's; the service refuses below them at checkout). */
1900
+ const PROVIDER_MINIMUMS = { stripe: {
1901
+ EUR: 50,
1902
+ GBP: 30,
1903
+ USD: 50
1904
+ } };
1905
+ const OPTIONS$1 = {
1906
+ ...HELP_OPTION,
1907
+ name: { type: "string" },
1908
+ percent: { type: "string" },
1909
+ amount: {
1910
+ type: "string",
1911
+ multiple: true
1912
+ },
1913
+ duration: { type: "string" },
1914
+ months: { type: "string" },
1915
+ code: { type: "string" },
1916
+ plans: { type: "string" },
1917
+ starts: { type: "string" },
1918
+ ends: { type: "string" },
1919
+ max: { type: "string" },
1920
+ "per-customer": { type: "string" },
1921
+ json: { type: "boolean" }
1922
+ };
1923
+ const NONE = "none";
1924
+ /** `20` / `12.5` → basis points (2000 / 1250). */
1925
+ function parsePercent(value) {
1926
+ const trimmed = value.trim().replace(/%$/, "");
1927
+ if (!/^\d{1,2}(\.\d{1,2})?$/.test(trimmed)) throw new UsageError("--percent: a number between 0.01 and 99.99");
1928
+ const bps = Math.round(Number(trimmed) * 100);
1929
+ if (bps < 1 || bps > 9999) throw new UsageError("--percent: a number between 0.01 and 99.99");
1930
+ return bps;
1931
+ }
1932
+ /** `USD:500` (repeatable) → `{ USD: 500 }`. */
1933
+ function parseAmounts(values) {
1934
+ const out = {};
1935
+ for (const value of values) {
1936
+ const match = /^([A-Za-z]{3}):(\d+)$/.exec(value.trim());
1937
+ if (!match) throw new UsageError(`--amount: <CUR:minor>, e.g. USD:500 (got ${JSON.stringify(value)})`);
1938
+ out[match[1].toUpperCase()] = Number(match[2]);
1939
+ }
1940
+ return out;
1941
+ }
1942
+ /** The fields shared by create and update (update: `none` clears an optional one). */
1943
+ function fieldsOf(values, update) {
1944
+ const clearable = (value, read) => value === void 0 ? void 0 : update && value.trim() === NONE ? null : read(value);
1945
+ const fields = {
1946
+ name: values.name,
1947
+ code: clearable(values.code, (v) => v.trim()),
1948
+ duration: values.duration,
1949
+ durationInMonths: values.months !== void 0 ? parsePositiveInt(values.months, "--months", { max: 120 }) : void 0,
1950
+ planCodes: values.plans !== void 0 ? values.plans.trim() === NONE ? [] : parseList(values.plans) : void 0,
1951
+ startsAt: clearable(values.starts, (v) => v.trim()),
1952
+ endsAt: clearable(values.ends, (v) => v.trim()),
1953
+ maxRedemptions: clearable(values.max, (v) => parsePositiveInt(v, "--max")),
1954
+ maxRedemptionsPerCustomer: values["per-customer"] === void 0 ? void 0 : values["per-customer"].trim() === "unlimited" ? null : parsePositiveInt(values["per-customer"], "--per-customer")
1955
+ };
1956
+ if (values.percent !== void 0 && values.amount !== void 0) throw new UsageError("give --percent or --amount, not both");
1957
+ if (values.percent !== void 0) Object.assign(fields, {
1958
+ type: "percentage",
1959
+ basisPoints: parsePercent(values.percent)
1960
+ });
1961
+ if (values.amount !== void 0) Object.assign(fields, {
1962
+ type: "fixed",
1963
+ amounts: parseAmounts(values.amount)
1964
+ });
1965
+ return Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== void 0));
1966
+ }
1967
+ function problems(issues) {
1968
+ return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "input"}: ${issue.message}`).join("\n");
1969
+ }
1970
+ function buildCreateInput(values) {
1971
+ const parsed = DiscountCreateInputSchema.safeParse(fieldsOf(values, false));
1972
+ if (!parsed.success) throw new UsageError(`invalid discount (no request was sent)\n${problems(parsed.error.issues)}`);
1973
+ return parsed.data;
1974
+ }
1975
+ function buildUpdateInput(values) {
1976
+ const fields = fieldsOf(values, true);
1977
+ if (Object.keys(fields).length === 0) throw new UsageError("nothing to change (details: steward discounts --help)");
1978
+ const parsed = DiscountUpdateInputSchema.safeParse(fields);
1979
+ if (!parsed.success) throw new UsageError(`invalid change (no request was sent)\n${problems(parsed.error.issues)}`);
1980
+ return parsed.data;
1981
+ }
1982
+ const money = (minor, currency) => `${(minor / 100).toFixed(2)} ${currency}`;
1983
+ /**
1984
+ * The catalog's sellable prices the discount would bring to zero or under the provider's minimum
1985
+ * (the hosted checkout refuses the code there: `discount_below_minimum`). The total is the price
1986
+ * minus the discount, with tax added for a tax-exclusive price; an approximation of the service's
1987
+ * rule, good enough to warn.
1988
+ */
1989
+ function belowMinimumWarnings(catalog, discount, provider) {
1990
+ const minimums = provider && PROVIDER_MINIMUMS[provider] || {};
1991
+ const plans = new Map(catalog.plans.map((p) => [p.code, p]));
1992
+ const warnings = [];
1993
+ for (const price of catalog.prices) {
1994
+ const plan = plans.get(price.planCode);
1995
+ if (!plan?.sellable) continue;
1996
+ const listed = plan.listed !== false;
1997
+ if (discount.planCodes.length > 0 ? !discount.planCodes.includes(price.planCode) : !listed) continue;
1998
+ const off = discount.type === "percentage" ? Math.round(price.amountMinor * (discount.basisPoints ?? 0) / 1e4) : discount.amounts?.[price.currency];
1999
+ if (off === void 0) continue;
2000
+ const net = Math.max(0, price.amountMinor - off);
2001
+ const total = price.taxInclusive ? net : net + Math.round(net * price.taxRateBps / 1e4);
2002
+ const minimum = minimums[price.currency] ?? 0;
2003
+ if (total <= 0 || total < minimum) warnings.push(`${price.planCode}/${price.interval} ${money(price.amountMinor, price.currency)} → ${money(total, price.currency)}` + (minimum > 0 ? ` (under ${provider}'s minimum ${money(minimum, price.currency)})` : " (nothing left to charge)"));
2004
+ }
2005
+ return warnings;
2006
+ }
2007
+ function describe$1(d) {
2008
+ const value = d.type === "percentage" ? `${(d.basisPoints ?? 0) / 100}%` : Object.entries(d.amounts ?? {}).map(([c, m]) => money(m, c)).join(", ");
2009
+ const term = d.duration === "repeating" ? `${d.durationInMonths} months` : d.duration;
2010
+ const limits = [
2011
+ d.maxRedemptions !== null ? `max ${d.maxRedemptions}` : null,
2012
+ `per customer ${d.maxRedemptionsPerCustomer ?? "unlimited"}`,
2013
+ d.planCodes.length > 0 ? `plans ${d.planCodes.join(",")}` : null,
2014
+ d.startsAt ? `from ${d.startsAt}` : null,
2015
+ d.endsAt ? `until ${d.endsAt}` : null
2016
+ ].filter(Boolean);
2017
+ return `${d.id} ${d.code ?? "(no code)"} ${d.name} ${value} ${term} redeemed ${d.redemptions.redeemed}, reserved ${d.redemptions.reserved} ${limits.join(" · ")}${d.archivedAt ? ` archived ${d.archivedAt}` : ""}`;
2018
+ }
2019
+ async function discountsCommand(ctx, out, args) {
2020
+ const [sub, ...rest] = args;
2021
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
2022
+ out.out(DISCOUNTS_USAGE);
2023
+ return sub === void 0 ? 2 : 0;
2024
+ }
2025
+ if (sub === "list") {
2026
+ const { values, positionals } = parse(rest, {
2027
+ ...HELP_OPTION,
2028
+ archived: { type: "boolean" },
2029
+ json: { type: "boolean" }
2030
+ }, "discounts");
2031
+ if (values.help) return help$4(out);
2032
+ expectPositionals(positionals, 0, 0, "discounts");
2033
+ const target = requireAdminTarget(await resolveEnv(ctx));
2034
+ out.err(connectionLine(target));
2035
+ const list = await callSteward(target, () => clientFor(ctx, target).admin.discounts.list({ archived: values.archived === true }));
2036
+ if (values.json) out.out(JSON.stringify(list, null, 2));
2037
+ else if (list.discounts.length === 0) out.out("no discounts");
2038
+ else for (const d of list.discounts) out.out(describe$1(d));
2039
+ return 0;
2040
+ }
2041
+ if (sub === "create") {
2042
+ const { values, positionals } = parse(rest, OPTIONS$1, "discounts");
2043
+ if (values.help) return help$4(out);
2044
+ expectPositionals(positionals, 0, 0, "discounts");
2045
+ const input = buildCreateInput(values);
2046
+ const target = requireAdminTarget(await resolveEnv(ctx));
2047
+ out.err(connectionLine(target));
2048
+ const client = clientFor(ctx, target);
2049
+ const created = await callSteward(target, () => client.admin.discounts.create(input));
2050
+ if (values.json) out.out(JSON.stringify(created, null, 2));
2051
+ else out.out(`discount created → ${originOf(target.url)}\n ${describe$1(created)}`);
2052
+ try {
2053
+ const [catalog, settings] = await Promise.all([client.catalog.get(), client.admin.settings.get()]);
2054
+ for (const warning of belowMinimumWarnings(catalog, created, settings.provider)) out.err(`warning: ${warning}; the code is refused for this price at checkout`);
2055
+ } catch {}
2056
+ return 0;
2057
+ }
2058
+ if (sub === "update") {
2059
+ const { values, positionals } = parse(rest, OPTIONS$1, "discounts");
2060
+ if (values.help) return help$4(out);
2061
+ expectPositionals(positionals, 1, 1, "discounts");
2062
+ const id = discountId(positionals[0]);
2063
+ const input = buildUpdateInput(values);
2064
+ const target = requireAdminTarget(await resolveEnv(ctx));
2065
+ out.err(connectionLine(target));
2066
+ const updated = await callSteward(target, () => clientFor(ctx, target).admin.discounts.update(id, input));
2067
+ if (values.json) out.out(JSON.stringify(updated, null, 2));
2068
+ else out.out(`discount updated → ${originOf(target.url)}\n ${describe$1(updated)}`);
2069
+ return 0;
2070
+ }
2071
+ if (sub === "archive") {
2072
+ const { values, positionals } = parse(rest, {
2073
+ ...HELP_OPTION,
2074
+ yes: { type: "boolean" }
2075
+ }, "discounts");
2076
+ if (values.help) return help$4(out);
2077
+ expectPositionals(positionals, 1, 1, "discounts");
2078
+ const id = discountId(positionals[0]);
2079
+ const target = requireAdminTarget(await resolveEnv(ctx));
2080
+ out.err(connectionLine(target));
2081
+ if (!await confirm(ctx, `Archive discount ${id} at ${originOf(target.url)}? It can no longer be redeemed; running subscriptions keep it.`, {
2082
+ yes: values.yes === true,
2083
+ notConfirmed: "the discount was not archived"
2084
+ })) {
2085
+ out.err("not archived");
2086
+ return 1;
2087
+ }
2088
+ const archived = await callSteward(target, () => clientFor(ctx, target).admin.discounts.archive(id));
2089
+ out.out(`discount archived → ${originOf(target.url)}\n ${describe$1(archived)}`);
2090
+ return 0;
2091
+ }
2092
+ throw new UsageError(`unknown subcommand: discounts ${sub} (details: steward discounts --help)`);
2093
+ }
2094
+ function discountId(value) {
2095
+ if (!IdSchema.safeParse(value).success) throw new UsageError(`not a discount id: ${JSON.stringify(value)}`);
2096
+ return value;
2097
+ }
2098
+ function help$4(out) {
2099
+ out.out(DISCOUNTS_USAGE);
2100
+ return 0;
2101
+ }
1815
2102
  // src/commands/email-smtp.ts
1816
2103
  const EMAIL_SMTP_USAGE = `Usage:
1817
2104
  steward email-smtp get [--json]
@@ -1946,10 +2233,99 @@ function help$3(out) {
1946
2233
  out.out(EMAIL_SMTP_USAGE);
1947
2234
  return 0;
1948
2235
  }
2236
+ // src/commands/emails.ts
2237
+ /** Longest email id: an event id, or the source key of an email without one. */
2238
+ const EMAIL_ID_MAX = 200;
2239
+ const EMAILS_USAGE = `Usage:
2240
+ steward emails list [--account <ref>] [--status pending|sent|skipped|dead] [--template <name>]
2241
+ [--limit <n>] [--after <id>] [--json]
2242
+
2243
+ The billing emails steward queued for the product's accounts, newest first, one line per email
2244
+ (GET /v1/admin/emails): the template, the status, the account, the attempts and the last error.
2245
+ pending: waiting or being retried; sent; skipped: not sent, ERROR says why (e.g. no_recipient,
2246
+ template_disabled); dead: the retries ran out, ERROR is the last error code. The ID is the
2247
+ email's webhook event (evt_…) or, for an email without one (e.g. the invoice payment reminder),
2248
+ its source key. Recipient addresses are never stored, so they are not listed (--json has their
2249
+ count).
2250
+
2251
+ --account <ref> one account's emails (an unknown ref is account_not_found)
2252
+ --status <status> pending, sent, skipped or dead
2253
+ --template <name> one template, e.g. payment_receipt, payment_failed, invoice_payment_due (an
2254
+ unknown name is refused with the list)
2255
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
2256
+ (the last ID) of the next page
2257
+ --json print the items as JSON
2258
+
2259
+ Failing emails: steward doctor shows which SMTP account the emails go through and its recent
2260
+ failures; steward email-smtp verify checks the product's own account.
2261
+
2262
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
2263
+ const LIST_OPTIONS$2 = {
2264
+ ...HELP_OPTION,
2265
+ account: { type: "string" },
2266
+ status: { type: "string" },
2267
+ template: { type: "string" },
2268
+ limit: { type: "string" },
2269
+ after: { type: "string" },
2270
+ json: { type: "boolean" }
2271
+ };
2272
+ async function emailsCommand(ctx, out, args) {
2273
+ const [sub, ...rest] = args;
2274
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
2275
+ out.out(EMAILS_USAGE);
2276
+ return sub === void 0 ? 2 : 0;
2277
+ }
2278
+ if (sub !== "list") throw new UsageError(`unknown subcommand: emails ${sub} (see: steward emails --help)`);
2279
+ const { values, positionals } = parse(rest, LIST_OPTIONS$2, "emails");
2280
+ if (values.help) {
2281
+ out.out(EMAILS_USAGE);
2282
+ return 0;
2283
+ }
2284
+ expectPositionals(positionals, 0, 0, "emails");
2285
+ const limit = limitOption(values.limit);
2286
+ const filter = definedOnly({
2287
+ account: accountOption(values.account),
2288
+ status: checkedOption(values.status, EmailMessageStatusSchema, "--status: pending, sent, skipped or dead"),
2289
+ template: checkedOption(values.template, EmailTemplateSchema, `--template: one of ${EmailTemplateSchema.options.join(", ")}`),
2290
+ limit,
2291
+ after: textOption(values.after, "--after", EMAIL_ID_MAX)
2292
+ });
2293
+ const target = requireAdminTarget(await resolveEnv(ctx));
2294
+ out.err(connectionLine(target));
2295
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.emails.list(filter));
2296
+ if (values.json) out.out(JSON.stringify(items, null, 2));
2297
+ else if (items.length === 0) out.out("no emails");
2298
+ else {
2299
+ const rows = [[
2300
+ "CREATED",
2301
+ "TEMPLATE",
2302
+ "STATUS",
2303
+ "ACCOUNT",
2304
+ "ATTEMPTS",
2305
+ "ERROR",
2306
+ "ID"
2307
+ ]];
2308
+ for (const e of items) rows.push([
2309
+ e.createdAt,
2310
+ e.template,
2311
+ e.status,
2312
+ e.accountRef,
2313
+ String(e.attempts),
2314
+ e.lastError ?? "-",
2315
+ e.id
2316
+ ]);
2317
+ for (const line of table(rows)) out.out(line);
2318
+ }
2319
+ const last = items.at(-1);
2320
+ if (hasMore && last !== void 0) out.err(nextPageLine("emails", limit, last.id));
2321
+ return 0;
2322
+ }
1949
2323
  // src/commands/events.ts
1950
2324
  const EVENTS_USAGE = `Usage:
1951
2325
  steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
1952
2326
  [--timestamp <iso>] [--json]
2327
+ steward events list [--account <ref>] [--type <type>] [--delivery pending|delivered|dead|failed]
2328
+ [--limit <n>] [--after <event id>] [--json]
1953
2329
  steward events redeliver <eventId> [<eventId>…]
1954
2330
 
1955
2331
  Sends one event for account <ref> (POST /v1/events/ingest), e.g. to try a meter locally.
@@ -1975,7 +2351,35 @@ Exit code 1: the event was rejected (unknown or deleted account, timestamp out o
1975
2351
  redeliver (admin; STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY): requeues every delivery of a
1976
2352
  webhook event (evt_…; dead ones included) with attempts reset, after the receiver's problem is
1977
2353
  fixed. The dispatcher sends it on its next tick; an account's older events go first. When only
1978
- the current state matters, the product calls POST /v1/accounts/:ref/resync instead.`;
2354
+ the current state matters, the product calls POST /v1/accounts/:ref/resync instead.
2355
+
2356
+ list (admin; STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY): the webhook events steward wrote for
2357
+ the product, newest first, one line per event (GET /v1/admin/events). DELIVERIES has one entry
2358
+ per endpoint, in endpoint order: the status, the attempts so far and the last error code
2359
+ (http_<status>, timeout, network_error, endpoint_inactive, url_not_allowed), e.g.
2360
+ "dead 8× http_500"; "-" when the product had no active endpoint. --json adds each endpoint's
2361
+ address, the last HTTP status and the next attempt time. The payload is not listed: read the
2362
+ account's state with steward accounts get <ref>.
2363
+
2364
+ --account <ref> one account's events (an unknown ref is account_not_found)
2365
+ --type <type> one event type, e.g. account.state_changed
2366
+ --delivery <d> events with a delivery that is pending, delivered or dead; failed: dead, or
2367
+ pending after a failed attempt (being retried)
2368
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
2369
+ (the last ID) of the next page
2370
+ --json print the items as JSON
2371
+
2372
+ A failed event (list --delivery failed) is sent again with steward events redeliver <id> once
2373
+ the receiver's problem is fixed.`;
2374
+ const LIST_OPTIONS$1 = {
2375
+ ...HELP_OPTION,
2376
+ account: { type: "string" },
2377
+ type: { type: "string" },
2378
+ delivery: { type: "string" },
2379
+ limit: { type: "string" },
2380
+ after: { type: "string" },
2381
+ json: { type: "boolean" }
2382
+ };
1979
2383
  const SEND_OPTIONS = {
1980
2384
  ...HELP_OPTION,
1981
2385
  meta: {
@@ -2019,6 +2423,7 @@ async function eventsCommand(ctx, out, args) {
2019
2423
  return sub === void 0 ? 2 : 0;
2020
2424
  }
2021
2425
  if (sub === "redeliver") return redeliverCommand(ctx, out, rest);
2426
+ if (sub === "list") return listCommand(ctx, out, rest);
2022
2427
  if (sub !== "send") throw new UsageError(`unknown subcommand: events ${sub} (see: steward events --help)`);
2023
2428
  const { values, positionals } = parse(rest, SEND_OPTIONS, "events");
2024
2429
  if (values.help) {
@@ -2072,6 +2477,51 @@ async function redeliverCommand(ctx, out, args) {
2072
2477
  }
2073
2478
  return 0;
2074
2479
  }
2480
+ /** One delivery in a table cell: `delivered 1×`, `dead 8× http_500`. */
2481
+ function deliveryText(delivery) {
2482
+ return `${delivery.status} ${delivery.attempts}×${delivery.lastError !== null ? ` ${delivery.lastError}` : ""}`;
2483
+ }
2484
+ async function listCommand(ctx, out, args) {
2485
+ const { values, positionals } = parse(args, LIST_OPTIONS$1, "events");
2486
+ if (values.help) {
2487
+ out.out(EVENTS_USAGE);
2488
+ return 0;
2489
+ }
2490
+ expectPositionals(positionals, 0, 0, "events");
2491
+ const limit = limitOption(values.limit);
2492
+ const filter = definedOnly({
2493
+ account: accountOption(values.account),
2494
+ type: textOption(values.type, "--type", AUDIT_LIST_FILTER_MAX),
2495
+ delivery: checkedOption(values.delivery, WebhookEventDeliveryFilterSchema, "--delivery: pending, delivered, dead or failed"),
2496
+ limit,
2497
+ after: checkedOption(values.after, EventIdSchema, "--after: an event id (evt_…)")
2498
+ });
2499
+ const target = requireAdminTarget(await resolveEnv(ctx));
2500
+ out.err(connectionLine(target));
2501
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.events.list(filter));
2502
+ if (values.json) out.out(JSON.stringify(items, null, 2));
2503
+ else if (items.length === 0) out.out("no events");
2504
+ else {
2505
+ const rows = [[
2506
+ "CREATED",
2507
+ "TYPE",
2508
+ "ACCOUNT",
2509
+ "DELIVERIES",
2510
+ "ID"
2511
+ ]];
2512
+ for (const e of items) rows.push([
2513
+ e.createdAt,
2514
+ e.type,
2515
+ e.accountRef ?? "-",
2516
+ e.deliveries.map(deliveryText).join(", ") || "-",
2517
+ e.id
2518
+ ]);
2519
+ for (const line of table(rows)) out.out(line);
2520
+ }
2521
+ const last = items.at(-1);
2522
+ if (hasMore && last !== void 0) out.err(nextPageLine("events", limit, last.id));
2523
+ return 0;
2524
+ }
2075
2525
  // src/commands/grants.ts
2076
2526
  const GRANTS_USAGE = `Usage:
2077
2527
  steward grants list [--plan <code>] [--subscription none|live|any] [--limit <n>]
@@ -2154,7 +2604,8 @@ async function grantsCommand(ctx, out, args) {
2154
2604
  // src/commands/invoices.ts
2155
2605
  const INVOICES_USAGE = `Usage:
2156
2606
  steward invoices list [--status draft|issued|void|all] [--payment-status <status>]
2157
- [--from <iso>] [--to <iso>] [--limit <n>] [--json | --csv]
2607
+ [--from <iso>] [--to <iso>] [--limit <n>] [--after <invoice id>]
2608
+ [--json | --csv]
2158
2609
  steward invoices issue <id> --number <number> [--external-ref <ref>] [--issued-at <iso>]
2159
2610
  [--document <file.pdf>] [--yes] [--json]
2160
2611
 
@@ -2164,7 +2615,8 @@ list: the product's invoices, oldest first (GET /v1/admin/invoices). draft (defa
2164
2615
  not issued yet, i.e. with no number of the external system; issued: the ones that have it; all:
2165
2616
  every status. --payment-status narrows it (unpaid, paid, …). --from (inclusive) and --to
2166
2617
  (exclusive), ISO-8601 with an offset, keep the invoices written in that window. --limit: 1–500,
2167
- default 100; a cut list says so on stderr.
2618
+ default 100; a cut list says so on stderr with the --after value (the last invoice id) of the
2619
+ next page.
2168
2620
 
2169
2621
  --csv is the export for an accounting system that issues the invoices (one row per invoice, a
2170
2622
  header row first): the invoice, its amounts in minor units, the tax decision (treatment, reason,
@@ -2196,6 +2648,7 @@ async function invoicesCommand(ctx, out, args) {
2196
2648
  from: { type: "string" },
2197
2649
  to: { type: "string" },
2198
2650
  limit: { type: "string" },
2651
+ after: { type: "string" },
2199
2652
  json: { type: "boolean" },
2200
2653
  csv: { type: "boolean" }
2201
2654
  }, "invoices");
@@ -2210,12 +2663,14 @@ async function invoicesCommand(ctx, out, args) {
2210
2663
  const paymentStatus = InvoicePaymentStatusSchema.optional().safeParse(values["payment-status"]);
2211
2664
  if (!paymentStatus.success) throw new UsageError(`--payment-status: one of ${InvoicePaymentStatusSchema.options.join(", ")}`);
2212
2665
  const limit = values.limit !== void 0 ? parsePositiveInt(values.limit, "--limit", { max: 500 }) : void 0;
2666
+ if (values.after !== void 0 && !IdSchema.safeParse(values.after).success) throw new UsageError("--after: an invoice id");
2213
2667
  const filter = {
2214
2668
  ...status !== void 0 ? { status } : {},
2215
2669
  ...paymentStatus.data !== void 0 ? { paymentStatus: paymentStatus.data } : {},
2216
2670
  ...values.from !== void 0 ? { from: values.from } : {},
2217
2671
  ...values.to !== void 0 ? { to: values.to } : {},
2218
- ...limit !== void 0 ? { limit } : {}
2672
+ ...limit !== void 0 ? { limit } : {},
2673
+ ...values.after !== void 0 ? { after: values.after } : {}
2219
2674
  };
2220
2675
  const target = requireAdminTarget(await resolveEnv(ctx));
2221
2676
  out.err(connectionLine(target));
@@ -2246,7 +2701,8 @@ async function invoicesCommand(ctx, out, args) {
2246
2701
  ]);
2247
2702
  for (const line of table(rows)) out.out(line);
2248
2703
  }
2249
- if (hasMore) out.err(`more invoices than the ${limit ?? 100} listed (--limit, at most 500)`);
2704
+ const last = items.at(-1);
2705
+ if (hasMore && last !== void 0) out.err(`more invoices than the ${limit ?? 100} listed (--limit, at most 500); next page: --after ${last.id}`);
2250
2706
  return 0;
2251
2707
  }
2252
2708
  if (sub === "issue") {
@@ -2520,6 +2976,103 @@ function help$1(out) {
2520
2976
  out.out(KEYS_USAGE);
2521
2977
  return 0;
2522
2978
  }
2979
+ // src/commands/payments.ts
2980
+ const PAYMENTS_USAGE = `Usage:
2981
+ steward payments list [--account <ref>] [--method card|bank_transfer] [--disputed any|open|ever]
2982
+ [--from <iso>] [--to <iso>] [--limit <n>] [--after <id>] [--json]
2983
+
2984
+ The product's collected payments, newest collection first, one line per payment
2985
+ (GET /v1/admin/payments): when, the account, the method, the amount, what was refunded at the
2986
+ provider and the dispute (chargeback), if any. Only successful payments are recorded, so a
2987
+ failed charge is not listed (steward invoices list --status all --payment-status unpaid shows
2988
+ what is unpaid). A bank transfer received in another currency also shows what reached the bank;
2989
+ --json adds the rate entered.
2990
+
2991
+ --account <ref> one account's payments (an unknown ref is account_not_found)
2992
+ --method <method> card or bank_transfer
2993
+ --disputed <d> any (default); open: a dispute that is not closed yet; ever: disputed at some
2994
+ point. DISPUTE shows the provider's status and whether it is open or closed.
2995
+ --from <iso> collected at or after (inclusive); ISO-8601 with an offset
2996
+ --to <iso> collected before (exclusive); ISO-8601 with an offset
2997
+ --limit <n> 1–${ADMIN_LIST_MAX_LIMIT}, default ${ADMIN_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after value
2998
+ (the last ID) of the next page
2999
+ --json print the items as JSON
3000
+
3001
+ Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
3002
+ const LIST_OPTIONS = {
3003
+ ...HELP_OPTION,
3004
+ account: { type: "string" },
3005
+ method: { type: "string" },
3006
+ disputed: { type: "string" },
3007
+ from: { type: "string" },
3008
+ to: { type: "string" },
3009
+ limit: { type: "string" },
3010
+ after: { type: "string" },
3011
+ json: { type: "boolean" }
3012
+ };
3013
+ /** The amount, with what reached the bank when a transfer came in another currency. */
3014
+ function paymentAmountText(p) {
3015
+ const amount = formatMinor(p.amountMinor, p.currency);
3016
+ if (p.receivedAmountMinor === void 0 || p.receivedCurrency === void 0) return amount;
3017
+ return `${amount} (received ${formatMinor(p.receivedAmountMinor, p.receivedCurrency)})`;
3018
+ }
3019
+ /** `-` (never disputed), or the provider's dispute status and whether it is still open. */
3020
+ function disputeText(p) {
3021
+ if (p.dispute === null) return "-";
3022
+ return `${p.dispute.status ?? "disputed"} (${p.dispute.closedAt === null ? "open" : "closed"})`;
3023
+ }
3024
+ async function paymentsCommand(ctx, out, args) {
3025
+ const [sub, ...rest] = args;
3026
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
3027
+ out.out(PAYMENTS_USAGE);
3028
+ return sub === void 0 ? 2 : 0;
3029
+ }
3030
+ if (sub !== "list") throw new UsageError(`unknown subcommand: payments ${sub} (see: steward payments --help)`);
3031
+ const { values, positionals } = parse(rest, LIST_OPTIONS, "payments");
3032
+ if (values.help) {
3033
+ out.out(PAYMENTS_USAGE);
3034
+ return 0;
3035
+ }
3036
+ expectPositionals(positionals, 0, 0, "payments");
3037
+ const limit = limitOption(values.limit);
3038
+ const filter = definedOnly({
3039
+ account: accountOption(values.account),
3040
+ method: checkedOption(values.method, PaymentMethodSchema, "--method: card or bank_transfer"),
3041
+ disputed: checkedOption(values.disputed, PaymentListDisputedFilterSchema, "--disputed: any, open or ever"),
3042
+ ...periodOptions(values),
3043
+ limit,
3044
+ after: checkedOption(values.after, IdSchema, "--after: a payment id")
3045
+ });
3046
+ const target = requireAdminTarget(await resolveEnv(ctx));
3047
+ out.err(connectionLine(target));
3048
+ const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.payments.list(filter));
3049
+ if (values.json) out.out(JSON.stringify(items, null, 2));
3050
+ else if (items.length === 0) out.out("no payments");
3051
+ else {
3052
+ const rows = [[
3053
+ "COLLECTED",
3054
+ "ACCOUNT",
3055
+ "METHOD",
3056
+ "AMOUNT",
3057
+ "REFUNDED",
3058
+ "DISPUTE",
3059
+ "ID"
3060
+ ]];
3061
+ for (const p of items) rows.push([
3062
+ p.occurredAt,
3063
+ p.accountRef,
3064
+ p.method,
3065
+ paymentAmountText(p),
3066
+ p.refundedMinor > 0 ? formatMinor(p.refundedMinor, p.currency) : "-",
3067
+ disputeText(p),
3068
+ p.id
3069
+ ]);
3070
+ for (const line of table(rows)) out.out(line);
3071
+ }
3072
+ const last = items.at(-1);
3073
+ if (hasMore && last !== void 0) out.err(nextPageLine("payments", limit, last.id));
3074
+ return 0;
3075
+ }
2523
3076
  // src/commands/reprice.ts
2524
3077
  const REPRICE_USAGE = `Usage: steward reprice --plan <code> --notice-days <n> [--dry-run] [--yes] [--json]
2525
3078
 
@@ -2615,7 +3168,7 @@ const SETTINGS_USAGE = `Usage:
2615
3168
  [--branding <json>] [--default-locale tr|en] [--display-time-zone <iana>]
2616
3169
  [--default-country <XX>]
2617
3170
  [--checkout-ttl <minutes>] [--portal-ttl <minutes>]
2618
- [--extra-return-origins <a,b>] [--emails <json>]
3171
+ [--extra-return-origins <a,b>] [--public-url <url>] [--emails <json>]
2619
3172
  [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>]
2620
3173
  [--billing-allow-multiple-subscriptions true|false]
2621
3174
  [--billing-renewal-notice-intervals <year,month>] [--billing-renewal-notice-days <1-90>]
@@ -2631,6 +3184,9 @@ Product settings (GET/PATCH /v1/admin/settings). A field not given is unchanged;
2631
3184
  empty value (--privacy-url "") clears the field, --branding null clears the branding,
2632
3185
  --branding '{"name":"Acme","supportEmail":"support@acme.com"}' merges shallowly (clear a
2633
3186
  field with null). --extra-return-origins "" empties the list.
3187
+ --public-url puts the product's hosted links (checkout, portal, pay pages, e-mailed pay links)
3188
+ on another address of the same steward, e.g. a second brand's domain; steward accepts only an
3189
+ address its deployment serves (STEWARD_EXTRA_PUBLIC_URLS). "" restores the deployment's address.
2634
3190
  --emails '{"billingPath":"/{LOCALE}/billing","templates":{"invoice_issued":{"enabled":false}}}'
2635
3191
  sets billing emails (sender: from.name, from.address; templates merge per
2636
3192
  template, null resets a field or template; --emails null resets all).
@@ -2688,6 +3244,7 @@ const SET_OPTIONS = {
2688
3244
  "checkout-ttl": { type: "string" },
2689
3245
  "portal-ttl": { type: "string" },
2690
3246
  "extra-return-origins": { type: "string" },
3247
+ "public-url": { type: "string" },
2691
3248
  emails: { type: "string" },
2692
3249
  "billing-payment-due-days": { type: "string" },
2693
3250
  "billing-min-invoice-minor": { type: "string" },
@@ -2762,6 +3319,7 @@ function buildSettingsPatch(values) {
2762
3319
  if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
2763
3320
  if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
2764
3321
  if (values["extra-return-origins"] !== void 0) patch.extraReturnOrigins = parseList(values["extra-return-origins"]);
3322
+ if (values["public-url"] !== void 0) patch.publicUrl = orNull(values["public-url"]);
2765
3323
  const billing = {};
2766
3324
  const dueDays = values["billing-payment-due-days"];
2767
3325
  if (dueDays !== void 0) billing.paymentDueDays = dueDays.trim() === "" ? null : parsePositiveInt(dueDays, "--billing-payment-due-days", { max: 60 });
@@ -3095,7 +3653,7 @@ function help(out) {
3095
3653
  return 0;
3096
3654
  }
3097
3655
  // src/main.ts
3098
- const CLI_VERSION = "0.12.0";
3656
+ const CLI_VERSION = "0.14.0";
3099
3657
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
3100
3658
 
3101
3659
  Usage: steward <command> [options]
@@ -3105,6 +3663,7 @@ Commands:
3105
3663
  catalog push <file> [--yes] catalog sync (PUT /v1/admin/catalog)
3106
3664
  settings get | set [flags] product settings (/v1/admin/settings)
3107
3665
  endpoints list | add | rotate | deactivate webhook endpoints; the secret goes only to the --out file
3666
+ discounts list | create | update | archive discounts and discount codes; archived, never deleted
3108
3667
  email-smtp get | set | clear | verify the product's own SMTP account; the URL only from a file or pipe
3109
3668
  keys list | create | revoke API keys; the key goes only to the --out file
3110
3669
  dunning get | set <policy.json> dunning policy (/v1/admin/dunning-policy)
@@ -3113,17 +3672,21 @@ Commands:
3113
3672
  invoices list | issue invoices not issued yet; write the external invoice number
3114
3673
  grants list active grants; --subscription none: paying for nothing
3115
3674
  credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
3116
- accounts get | metadata set | unset read an account; set or remove metadata keys
3675
+ accounts get | list | metadata set | unset read or list accounts; set or remove metadata keys
3117
3676
  meters get | recompute | close-periods an account's meters; metering repairs (admin)
3118
- events send | redeliver send one event; redeliver webhook events (admin)
3677
+ events send | list | redeliver send one event; list or redeliver webhook events (admin)
3678
+ audit list the product's audit trail: who changed what (admin)
3679
+ emails list billing emails steward queued; never the recipients (admin)
3680
+ payments list collected payments with refunds and disputes (admin)
3119
3681
  tax thresholds list | set | delete tax registration thresholds and their counters
3120
3682
  tax sales [--from] [--to] [--csv] paid sales per month and buyer country (admin)
3121
3683
 
3122
3684
  Connection: admin commands use STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY; doctor,
3123
- accounts, meters and events use STEWARD_URL + STEWARD_API_KEY (or the admin pair). If even
3124
- one of these four variables is in the environment, all of them (and APP_URL) are read from
3125
- the environment and ./.env.local is not read at all; otherwise from ./.env.local. The source
3126
- in use is written to stderr (connection: …). Changes send X-Actor-Ref operator:<user>.
3685
+ accounts get|metadata, meters get and events send use STEWARD_URL + STEWARD_API_KEY (or the
3686
+ admin pair). If even one of these four variables is in the environment, all of them (and
3687
+ APP_URL) are read from the environment and ./.env.local is not read at all; otherwise from
3688
+ ./.env.local. The source in use is written to stderr (connection: …). Changes send
3689
+ X-Actor-Ref operator:<user>.
3127
3690
  The CLI never writes secrets to the terminal and never calls kubectl.
3128
3691
 
3129
3692
  Details: steward <command> --help`;
@@ -3132,10 +3695,14 @@ const COMMANDS = {
3132
3695
  catalog: catalogCommand,
3133
3696
  settings: settingsCommand,
3134
3697
  endpoints: endpointsCommand,
3698
+ discounts: discountsCommand,
3135
3699
  "email-smtp": emailSmtpCommand,
3136
3700
  accounts: accountsCommand,
3137
3701
  meters: metersCommand,
3138
3702
  events: eventsCommand,
3703
+ audit: auditCommand,
3704
+ emails: emailsCommand,
3705
+ payments: paymentsCommand,
3139
3706
  keys: keysCommand,
3140
3707
  dunning: dunningCommand,
3141
3708
  reprice: repriceCommand,