@stewardhq/cli 0.2.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +54 -34
  2. package/dist/bin.js +793 -634
  3. package/package.json +5 -6
package/dist/bin.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import { spawn } from "node:child_process";
3
2
  import { userInfo } from "node:os";
3
+ import { createInterface } from "node:readline/promises";
4
4
  import { setTimeout } from "node:timers/promises";
5
- import { CatalogSyncInputSchema, ProductSettingsPatchSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateWebhookSecret } from "@stewardhq/sdk";
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";
6
6
  import { parseArgs } from "node:util";
7
- import { chmod, link, lstat, mkdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
7
+ import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
8
8
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
9
9
  import { pathToFileURL } from "node:url";
10
- import { createHash, randomUUID } from "node:crypto";
10
+ import { randomUUID } from "node:crypto";
11
11
  //#region src/io.ts
12
12
  const SECRET_PATTERN = /\b(whsec_|stw_)[A-Za-z0-9_\-+/=]+/g;
13
13
  /** Sır biçimindeki değerleri maskeler (`whsec_***`). */
@@ -81,17 +81,29 @@ function parsePositiveInt(value, flag, { max = Number.MAX_SAFE_INTEGER } = {}) {
81
81
  if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new UsageError(`${flag}: 1–${max} arası tam sayı olmalı`);
82
82
  return n;
83
83
  }
84
- /** http(s) adresi; kullanıcı bilgisi taşıyamaz. */
85
- function parseHttpUrl(value, flag) {
86
- let url;
87
- try {
88
- url = new URL(value);
89
- } catch {
90
- throw new UsageError(`${flag}: geçerli bir adres değil`);
91
- }
92
- if (url.protocol !== "http:" && url.protocol !== "https:") throw new UsageError(`${flag}: http(s) adresi olmalı`);
93
- if (url.username !== "" || url.password !== "") throw new UsageError(`${flag}: adreste kullanıcı bilgisi olamaz`);
94
- return value;
84
+ /** Non-negative integer (digits only), e.g. an amount in minor units. */
85
+ function parseNonNegativeInt(value, flag) {
86
+ const trimmed = value.trim();
87
+ const n = /^\d+$/.test(trimmed) ? Number(trimmed) : NaN;
88
+ if (!Number.isSafeInteger(n)) throw new UsageError(`${flag}: must be a non-negative integer`);
89
+ return n;
90
+ }
91
+ /** `true` / `false` (also `yes` / `no`, `on` / `off`, `1` / `0`). */
92
+ function parseBoolean(value, flag) {
93
+ const text = value.trim().toLowerCase();
94
+ if ([
95
+ "true",
96
+ "yes",
97
+ "on",
98
+ "1"
99
+ ].includes(text)) return true;
100
+ if ([
101
+ "false",
102
+ "no",
103
+ "off",
104
+ "0"
105
+ ].includes(text)) return false;
106
+ throw new UsageError(`${flag}: must be true or false`);
95
107
  }
96
108
  //#endregion
97
109
  //#region src/catalog-file.ts
@@ -155,6 +167,249 @@ async function loadCatalogFile(ctx, file) {
155
167
  return input;
156
168
  }
157
169
  //#endregion
170
+ //#region src/catalog-diff.ts
171
+ /** A catalog that defines benefits needs a steward with the `benefits` capability (M27). */
172
+ function definesBenefits(input) {
173
+ return Object.keys(input.benefits ?? {}).length > 0;
174
+ }
175
+ /** A catalog that defines meters or metered prices needs a steward with the `meters` capability (M27). */
176
+ function definesMeters(input) {
177
+ return Object.keys(input.meters ?? {}).length > 0 || (input.meteredPrices ?? []).length > 0;
178
+ }
179
+ const isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
180
+ /** JSON with sorted object keys: key order does not count as a change. */
181
+ 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);
182
+ const priceKey = (p) => `${p.planCode}/${p.interval}/${p.intervalCount}/${p.currency}`;
183
+ const priceLabel = (p) => `${p.planCode} ${p.intervalCount > 1 ? `${p.intervalCount}×` : ""}${p.interval}`;
184
+ /** `TRY 1,250.00`; minor units with the currency's own fraction digits (unknown currency: minor units). */
185
+ function formatMinor(amountMinor, currency) {
186
+ try {
187
+ const format = new Intl.NumberFormat("en", {
188
+ style: "currency",
189
+ currency,
190
+ currencyDisplay: "code"
191
+ });
192
+ const digits = format.resolvedOptions().maximumFractionDigits ?? 2;
193
+ return format.format(amountMinor / 10 ** digits).replace(/\u00a0/g, " ");
194
+ } catch {
195
+ return `${amountMinor} ${currency} (minor units)`;
196
+ }
197
+ }
198
+ const percent = (bps) => `${bps / 100}%`;
199
+ /** Units as exact text with grouping (`2,000,000`, `0.25`). */
200
+ const unitsText = (value) => new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
201
+ const meteredKey = (p) => `${p.planCode}/${p.meter}/${p.currency}`;
202
+ const meteredLabel = (p) => `${p.planCode} ${p.meter}`;
203
+ /** `TRY 12.50 per 1,000 units` (+ `, cap TRY 500.00`). */
204
+ function meteredRate(p) {
205
+ const cap = p.capMinor === void 0 || p.capMinor === null ? "" : `, cap ${formatMinor(p.capMinor, p.currency)}`;
206
+ return `${formatMinor(p.amountMinor, p.currency)} per ${unitsText(p.perUnits)} unit${p.perUnits === 1 ? "" : "s"}${cap}`;
207
+ }
208
+ function creditTerms(properties) {
209
+ const parsed = MeterCreditPropertiesSchema.safeParse(properties);
210
+ return parsed.success ? {
211
+ meter: parsed.data.meter,
212
+ units: parsed.data.units,
213
+ rolloverCapUnits: parsed.data.rolloverCapUnits ?? null
214
+ } : null;
215
+ }
216
+ function diffMeters(current, input) {
217
+ const before = current?.meters ?? {};
218
+ const meters = {
219
+ added: [],
220
+ changed: [],
221
+ ruleChanged: [],
222
+ archived: []
223
+ };
224
+ for (const [code, next] of Object.entries(input.meters)) {
225
+ const old = Object.hasOwn(before, code) ? before[code] : void 0;
226
+ if (old === void 0) {
227
+ meters.added.push(code);
228
+ continue;
229
+ }
230
+ if (canonical(old.filter) !== canonical(next.filter) || canonical(old.aggregation) !== canonical(next.aggregation)) meters.ruleChanged.push(code);
231
+ 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);
232
+ }
233
+ meters.archived = Object.keys(before).filter((code) => !Object.hasOwn(input.meters, code));
234
+ return meters;
235
+ }
236
+ function meteredTerms(p) {
237
+ return {
238
+ amountMinor: p.amountMinor,
239
+ perUnits: p.perUnits,
240
+ taxInclusive: p.taxInclusive,
241
+ taxRateBps: p.taxRateBps,
242
+ capMinor: p.capMinor ?? null
243
+ };
244
+ }
245
+ function diffMeteredPrices(current, input) {
246
+ const before = new Map((current?.meteredPrices ?? []).map((p) => [meteredKey(p), p]));
247
+ const inputKeys = new Set(input.meteredPrices.map(meteredKey));
248
+ const out = {
249
+ added: [],
250
+ deactivated: [],
251
+ changed: []
252
+ };
253
+ for (const price of input.meteredPrices) {
254
+ const old = before.get(meteredKey(price));
255
+ if (old === void 0) out.added.push(`${meteredLabel(price)} ${meteredRate(price)}`);
256
+ else if (canonical(meteredTerms(old)) !== canonical(meteredTerms(price))) out.changed.push({
257
+ label: meteredLabel(price),
258
+ id: old.id,
259
+ currency: price.currency,
260
+ from: meteredTerms(old),
261
+ to: meteredTerms(price)
262
+ });
263
+ }
264
+ for (const [key, price] of before) if (!inputKeys.has(key)) out.deactivated.push(`${meteredLabel(price)} ${meteredRate(price)}`);
265
+ return out;
266
+ }
267
+ function diffCatalog(current, file) {
268
+ const input = CatalogSyncInputSchema.parse(file);
269
+ const currentBenefits = current?.benefits ?? {};
270
+ const benefits = {
271
+ added: Object.keys(input.benefits).filter((code) => !Object.hasOwn(currentBenefits, code)),
272
+ changed: Object.entries(input.benefits).filter(([code]) => Object.hasOwn(currentBenefits, code)).filter(([code, next]) => {
273
+ const before = currentBenefits[code];
274
+ return before.type !== next.type || canonical(before.properties) !== canonical(next.properties) || canonical(before.description) !== canonical(next.description);
275
+ }).map(([code]) => code),
276
+ archived: Object.keys(currentBenefits).filter((code) => !Object.hasOwn(input.benefits, code))
277
+ };
278
+ const currentPlans = new Map((current?.plans ?? []).map((plan) => [plan.code, plan.benefits ?? []]));
279
+ const planBenefits = [];
280
+ for (const plan of input.plans) {
281
+ const before = currentPlans.get(plan.code) ?? [];
282
+ const added = plan.benefits.filter((code) => !before.includes(code));
283
+ const removed = before.filter((code) => !plan.benefits.includes(code));
284
+ if (added.length > 0 || removed.length > 0) planBenefits.push({
285
+ plan: plan.code,
286
+ added,
287
+ removed
288
+ });
289
+ }
290
+ const currentPrices = new Map((current?.prices ?? []).map((price) => [priceKey(price), price]));
291
+ const inputKeys = new Set(input.prices.map(priceKey));
292
+ const prices = {
293
+ added: [],
294
+ deactivated: [],
295
+ changed: []
296
+ };
297
+ for (const price of input.prices) {
298
+ const before = currentPrices.get(priceKey(price));
299
+ if (before === void 0) prices.added.push(`${priceLabel(price)} ${formatMinor(price.amountMinor, price.currency)}`);
300
+ else if (before.amountMinor !== price.amountMinor || before.taxInclusive !== price.taxInclusive || before.taxRateBps !== price.taxRateBps) {
301
+ const terms = ({ amountMinor, taxInclusive, taxRateBps }) => ({
302
+ amountMinor,
303
+ taxInclusive,
304
+ taxRateBps
305
+ });
306
+ prices.changed.push({
307
+ label: priceLabel(price),
308
+ id: before.id,
309
+ currency: price.currency,
310
+ from: terms(before),
311
+ to: terms(price)
312
+ });
313
+ }
314
+ }
315
+ for (const [key, price] of currentPrices) if (!inputKeys.has(key)) prices.deactivated.push(`${priceLabel(price)} ${formatMinor(price.amountMinor, price.currency)}`);
316
+ const credits = [];
317
+ for (const [code, next] of Object.entries(input.benefits)) {
318
+ const old = Object.hasOwn(currentBenefits, code) ? currentBenefits[code] : void 0;
319
+ if (old === void 0 || old.type !== "meter_credit" || next.type !== "meter_credit") continue;
320
+ const from = creditTerms(old.properties);
321
+ const to = creditTerms(next.properties);
322
+ if (from !== null && to !== null && canonical(from) !== canonical(to)) credits.push({
323
+ code,
324
+ from,
325
+ to
326
+ });
327
+ }
328
+ return {
329
+ benefits,
330
+ planBenefits,
331
+ prices,
332
+ meters: diffMeters(current, input),
333
+ credits,
334
+ meteredPrices: diffMeteredPrices(current, input)
335
+ };
336
+ }
337
+ function describePriceChange({ label, currency, from, to }) {
338
+ const parts = [];
339
+ if (from.amountMinor !== to.amountMinor) parts.push(`${formatMinor(from.amountMinor, currency)} → ${formatMinor(to.amountMinor, currency)}`);
340
+ if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent(from.taxRateBps)} → ${percent(to.taxRateBps)}`);
341
+ if (from.taxInclusive !== to.taxInclusive) parts.push(`tax ${from.taxInclusive ? "inclusive" : "exclusive"} → ${to.taxInclusive ? "inclusive" : "exclusive"}`);
342
+ return `${from.amountMinor === to.amountMinor ? `${label} ${formatMinor(to.amountMinor, currency)}` : label}: ${parts.join(", ")}`;
343
+ }
344
+ function describeMeteredPriceChange({ label, currency, from, to }) {
345
+ const parts = [];
346
+ if (from.amountMinor !== to.amountMinor || from.perUnits !== to.perUnits) parts.push(`${meteredRate({
347
+ currency,
348
+ amountMinor: from.amountMinor,
349
+ perUnits: from.perUnits
350
+ })} → ${meteredRate({
351
+ currency,
352
+ amountMinor: to.amountMinor,
353
+ perUnits: to.perUnits
354
+ })}`);
355
+ if (from.capMinor !== to.capMinor) {
356
+ const cap = (minor) => minor === null ? "none" : formatMinor(minor, currency);
357
+ parts.push(`cap ${cap(from.capMinor)} → ${cap(to.capMinor)}`);
358
+ }
359
+ if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent(from.taxRateBps)} → ${percent(to.taxRateBps)}`);
360
+ if (from.taxInclusive !== to.taxInclusive) parts.push(`tax ${from.taxInclusive ? "inclusive" : "exclusive"} → ${to.taxInclusive ? "inclusive" : "exclusive"}`);
361
+ return `${label}: ${parts.join(", ")}`;
362
+ }
363
+ function describeCreditChange({ code, from, to }) {
364
+ const parts = [];
365
+ if (from.meter !== to.meter) parts.push(`meter ${from.meter} → ${to.meter}`);
366
+ if (from.units !== to.units) parts.push(`${unitsText(from.units)} → ${unitsText(to.units)} units per period`);
367
+ if (from.rolloverCapUnits !== to.rolloverCapUnits) {
368
+ const cap = (units) => units === null ? "no rollover" : `rollover cap ${unitsText(units)}`;
369
+ parts.push(`${cap(from.rolloverCapUnits)} → ${cap(to.rolloverCapUnits)}`);
370
+ }
371
+ return `${code} (${to.meter}): ${parts.join(", ")}`;
372
+ }
373
+ const list$1 = (items) => items.join(", ");
374
+ /** Lines for the terminal; empty when nothing the operator must see changes. */
375
+ function describeDiff(diff) {
376
+ const lines = [];
377
+ const row = (label, text) => lines.push(` ${label.length >= 19 ? `${label} ` : label.padEnd(19)}${text}`);
378
+ if (diff.benefits.added.length > 0) row("new benefits", list$1(diff.benefits.added));
379
+ if (diff.benefits.changed.length > 0) row("changed benefits", list$1(diff.benefits.changed));
380
+ if (diff.benefits.archived.length > 0) row("archived benefits", `${list$1(diff.benefits.archived)} (accounts that have them lose them)`);
381
+ for (const { plan, added, removed } of diff.planBenefits) row("plan benefits", `${plan}: ${[...added.map((code) => `+${code}`), ...removed.map((code) => `-${code}`)].join(" ")}`);
382
+ for (const price of diff.prices.added) row("new price", price);
383
+ for (const price of diff.prices.deactivated) row("deactivated price", price);
384
+ for (const change of diff.prices.changed) row("price change", describePriceChange(change));
385
+ if (diff.prices.changed.length > 0) {
386
+ lines.push(" note: a changed price keeps its id; existing subscriptions keep the amount they locked and new");
387
+ lines.push(" subscriptions pay the new amount; a tax change applies to every invoice written from now on");
388
+ }
389
+ const { meters, credits, meteredPrices } = diff;
390
+ if (meters.added.length > 0) row("new meters", `${list$1(meters.added)} (the current period is filled from stored events)`);
391
+ if (meters.changed.length > 0) row("changed meters", `${list$1(meters.changed)} (labels, display or lowAt)`);
392
+ if (meters.ruleChanged.length > 0) {
393
+ row("meter rule change", `${list$1(meters.ruleChanged)} (filter or aggregation)`);
394
+ lines.push(" note: a meter's filter and aggregation are fixed once it has counted a period: steward then refuses");
395
+ lines.push(" the push (422 meter_locked); give the new rule a new meter code");
396
+ }
397
+ if (meters.archived.length > 0) row("archived meters", `${list$1(meters.archived)} (no longer counted; their periods stay)`);
398
+ for (const credit of credits) row("credit change", describeCreditChange(credit));
399
+ for (const price of meteredPrices.added) row("new metered price", price);
400
+ for (const price of meteredPrices.deactivated) row("deactivated metered price", price);
401
+ for (const change of meteredPrices.changed) row("metered price change", describeMeteredPriceChange(change));
402
+ if (meteredPrices.changed.length > 0) {
403
+ lines.push(" note: a changed metered price keeps its id; existing subscriptions keep the rate they locked and new");
404
+ lines.push(" subscriptions get the new rate");
405
+ }
406
+ return lines.length > 0 ? ["changes against the current catalog:", ...lines] : [];
407
+ }
408
+ /** Price changes the operator confirms before the push: base prices and metered prices changed in place. */
409
+ function priceChangeCount(diff) {
410
+ return diff.prices.changed.length + diff.meteredPrices.changed.length;
411
+ }
412
+ //#endregion
158
413
  //#region src/dotenv.ts
159
414
  const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
160
415
  function unquote(rest) {
@@ -178,51 +433,6 @@ function parseDotenv(text) {
178
433
  }
179
434
  return values;
180
435
  }
181
- const DOTENV_HEADER = "# steward dev (yerel steward kimlik bilgileri; steward dev günceller)";
182
- function upsertDotenv(text, entries, remove = []) {
183
- for (const [key, value] of entries) if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || !/^[^\s"'`#\\]+$/.test(value)) throw new Error(`upsertDotenv: ${key} tırnaksız yazılamaz`);
184
- const eol = text.includes("\r\n") ? "\r\n" : "\n";
185
- const lines = text === "" ? [] : text.split(/\r?\n/);
186
- if (lines.at(-1) === "") lines.pop();
187
- const wanted = new Map(entries);
188
- if (remove.some((key) => wanted.has(key))) throw new Error("upsertDotenv: aynı anahtar hem yazılıp hem silinemez");
189
- const dropped = /* @__PURE__ */ new Set();
190
- for (let index = lines.length - 1; index >= 0; index--) {
191
- const key = LINE.exec(lines[index])?.[3];
192
- if (key !== void 0 && remove.includes(key)) {
193
- lines.splice(index, 1);
194
- dropped.add(key);
195
- }
196
- }
197
- const seen = /* @__PURE__ */ new Set();
198
- const updated = /* @__PURE__ */ new Set();
199
- for (const [index, line] of lines.entries()) {
200
- const match = LINE.exec(line);
201
- const key = match?.[3];
202
- if (!match || key === void 0 || !wanted.has(key)) continue;
203
- seen.add(key);
204
- const value = wanted.get(key);
205
- if (unquote(match[4]) !== value) {
206
- lines[index] = `${match[1]}${match[2] ?? ""}${key}=${value}`;
207
- updated.add(key);
208
- }
209
- }
210
- const added = [...wanted.keys()].filter((key) => !seen.has(key));
211
- if (added.length > 0) {
212
- if (!lines.includes("# steward dev (yerel steward kimlik bilgileri; steward dev günceller)")) {
213
- if (lines.length > 0 && lines.at(-1).trim() !== "") lines.push("");
214
- lines.push(DOTENV_HEADER);
215
- }
216
- for (const key of added) lines.push(`${key}=${wanted.get(key)}`);
217
- }
218
- return {
219
- text: lines.length === 0 ? "" : `${lines.join(eol)}${eol}`,
220
- added,
221
- updated: [...updated],
222
- unchanged: [...seen].filter((key) => !updated.has(key)),
223
- removed: remove.filter((key) => dropped.has(key))
224
- };
225
- }
226
436
  async function readDotenvFile(path) {
227
437
  try {
228
438
  return parseDotenv(await readFile(path, "utf8"));
@@ -231,33 +441,6 @@ async function readDotenvFile(path) {
231
441
  throw error;
232
442
  }
233
443
  }
234
- async function upsertDotenvFile(path, entries, remove = []) {
235
- let current = null;
236
- try {
237
- current = await readFile(path, "utf8");
238
- } catch (error) {
239
- if (errnoCode(error) !== "ENOENT") throw error;
240
- }
241
- const result = upsertDotenv(current ?? "", entries, remove);
242
- if (current === null) {
243
- await writeFile(path, result.text, {
244
- mode: 384,
245
- flag: "wx"
246
- });
247
- return {
248
- ...result,
249
- created: true,
250
- looseMode: false
251
- };
252
- }
253
- if (result.text !== current) await writeFile(path, result.text);
254
- const looseMode = process.platform !== "win32" && ((await stat(path)).mode & 63) !== 0;
255
- return {
256
- ...result,
257
- created: false,
258
- looseMode
259
- };
260
- }
261
444
  //#endregion
262
445
  //#region src/env.ts
263
446
  const ENV_LOCAL = ".env.local";
@@ -313,7 +496,7 @@ function whereMissing(env) {
313
496
  case "missing": return `tanımlı değil (ortam değişkeni ya da ./${ENV_LOCAL}; dosya yok)`;
314
497
  }
315
498
  }
316
- const ADMIN_HINT = "Yerelde `steward dev` bunları .env.local'e yazar. Cluster'da: admin ucunu port-forward edin (STEWARD_ADMIN_URL=http://localhost:13002) ve admin anahtarını operatör Secret'ından ortam değişkeni olarak verin.";
499
+ const ADMIN_HINT = "Bunları ortam değişkeni ya da ./.env.local olarak verin. Cluster'da: admin ucunu port-forward edin (STEWARD_ADMIN_URL=http://localhost:13002) ve admin anahtarını operatör Secret'ından ortam değişkeni olarak verin.";
317
500
  function pairError(names, missing, env) {
318
501
  return new CliError(`${names.url} + ${names.key} gerekli: ${missing.join(" ve ")} ${whereMissing(env)}.\n${ADMIN_HINT}`);
319
502
  }
@@ -375,14 +558,19 @@ async function callSteward(target, fn) {
375
558
  throw error;
376
559
  }
377
560
  }
561
+ /** What to do about an error code the operator can fix (metering catalog codes). */
562
+ const CODE_HINTS = {
563
+ meter_locked: " — a meter's filter and aggregation are fixed once it has counted a period: give the new rule a new meter code",
564
+ metered_price_tax_mismatch: " — a metered price needs the tax terms (taxInclusive, taxRateBps) of its plan's base price in that currency"
565
+ };
378
566
  /** SDK hatasını tek satırlık kullanıcı mesajına çevirir (değer/anahtar içermez). */
379
567
  function describeStewardError(error, target) {
380
568
  const where = target ? ` (${originOf(target.url)})` : "";
381
569
  const request = error.requestId !== void 0 ? ` [istek ${error.requestId}]` : "";
382
- if (error instanceof StewardNetworkError) return `steward'a ulaşılamadı${where}: ${error.code === "timeout" ? "zaman aşımı" : "bağlantı kurulamadı"}. Adres doğru mu, port-forward ya da \`steward dev\` açık mı?`;
570
+ if (error instanceof StewardNetworkError) return `steward'a ulaşılamadı${where}: ${error.code === "timeout" ? "zaman aşımı" : "bağlantı kurulamadı"}. Adres doğru mu, port-forward açık mı?`;
383
571
  if (error instanceof StewardConfigError) return `yapılandırma hatası: ${error.message}`;
384
572
  if (error instanceof StewardApiError) {
385
- const hint = error.httpStatus === 401 ? " — anahtar geçersiz ya da iptal edilmiş" : error.httpStatus === 403 ? " — bu işlem admin kapsamlı anahtar ister" : "";
573
+ const hint = error.httpStatus === 401 ? " — anahtar geçersiz ya da iptal edilmiş" : error.httpStatus === 403 ? " — bu işlem admin kapsamlı anahtar ister" : Object.hasOwn(CODE_HINTS, error.code) ? CODE_HINTS[error.code] : "";
386
574
  const message = error.message !== error.code ? `: ${error.message}` : "";
387
575
  return `steward hatası${where}: ${error.code} (HTTP ${error.httpStatus})${message}${hint}${request}`;
388
576
  }
@@ -390,32 +578,91 @@ function describeStewardError(error, target) {
390
578
  }
391
579
  //#endregion
392
580
  //#region src/commands/catalog.ts
393
- const CATALOG_USAGE = `Kullanım: steward catalog push <dosya>
581
+ const CATALOG_USAGE = `Kullanım: steward catalog push <dosya> [--yes]
394
582
 
395
583
  Katalog tanımını steward'a senkronlar (PUT /v1/admin/catalog), sonra sürümü ve
396
584
  sayıları yazar. Dosya: .ts/.mts (Node tip ayıklaması, Node ≥ 22.18), .js/.mjs/.cjs
397
585
  (\`export const catalog = defineCatalog(…)\` ya da default export) veya .json
398
586
  (senkron gövdesi). Geçersiz katalogda istek gönderilmez.
399
587
 
588
+ Before pushing, prints what changes against steward's current catalog: benefits
589
+ (new, changed, archived, plan benefit lists) and prices (new, deactivated, amount or
590
+ tax terms changed). A changed price is updated in place: existing subscriptions keep
591
+ the amount they locked, new subscriptions pay the new amount, a tax change applies to
592
+ every invoice written from now on. Price changes need confirmation: a prompt on a
593
+ terminal, otherwise --yes (-y). A catalog with benefits is pushed only to a steward
594
+ whose GET /v1/me lists the "benefits" capability (an older steward would drop them).
595
+
596
+ Metering: the diff also lists meters (new, changed, rule changed, archived), changed
597
+ credits (meter_credit benefits) and metered prices (new, deactivated, changed; a
598
+ changed metered price needs the same confirmation). A meter's filter and aggregation
599
+ are fixed once it has counted a period (422 meter_locked: use a new meter code). A
600
+ catalog with meters or metered prices is pushed only to a steward whose GET /v1/me
601
+ lists the "meters" capability.
602
+
400
603
  Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).
401
- Çıkış kodu 1: sağlayıcıda karşılığı açılamayan fiyat var (senkronu yeniden koşun).`;
604
+ Çıkış kodu 1: sağlayıcıda karşılığı açılamayan fiyat var (senkronu yeniden koşun);
605
+ the push was refused or not confirmed.`;
606
+ const PUSH_OPTIONS = {
607
+ ...HELP_OPTION,
608
+ yes: {
609
+ type: "boolean",
610
+ short: "y"
611
+ }
612
+ };
402
613
  const list = (items) => items.length > 0 ? items.join(", ") : "-";
403
614
  /** Senkron + sürüm okuması; özet satırları ve sağlayıcı hatası olup olmadığı. */
404
- async function pushCatalog(ctx, target, input) {
405
- const steward = clientFor(ctx, target);
615
+ async function pushCatalog(steward, target, input) {
406
616
  const result = await callSteward(target, () => steward.admin.catalog.sync(input));
407
617
  const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "bilinmiyor";
618
+ const benefitCount = Object.keys(input.benefits ?? {}).length;
619
+ const meterCount = Object.keys(input.meters ?? {}).length;
620
+ const meteredCount = (input.meteredPrices ?? []).length;
621
+ const metering = `${meterCount > 0 ? ` · ${meterCount} meter${meterCount === 1 ? "" : "s"}` : ""}${meteredCount > 0 ? ` · ${meteredCount} metered price${meteredCount === 1 ? "" : "s"}` : ""}`;
408
622
  const lines = [`katalog senkronlandı → ${originOf(target.url)}`];
409
623
  lines.push(` sürüm ${version}`);
410
- lines.push(` tanım ${input.plans.length} plan · ${input.features.length} feature · ${input.prices.length} fiyat · varsayılan plan ${input.defaultPlanCode}`);
624
+ lines.push(` tanım ${input.plans.length} plan · ${input.features.length} feature · ${input.prices.length} fiyat${benefitCount > 0 ? ` · ${benefitCount} benefit` : ""}${metering} · varsayılan plan ${input.defaultPlanCode}`);
411
625
  if (result.unchanged) lines.push(" değişiklik yok");
412
- else lines.push(` değişiklik yeni fiyat ${result.createdPrices.length} · pasif fiyat ${result.deactivatedPrices.length} · değişen plan: ${list(result.changedPlans)} · emekli plan: ${list(result.retiredPlans)} · kaldırılan feature: ${list(result.removedFeatures)}${result.defaultPlanChanged ? " · varsayılan plan değişti" : ""}`);
626
+ else {
627
+ lines.push(` değişiklik yeni fiyat ${result.createdPrices.length} · pasif fiyat ${result.deactivatedPrices.length} · değişen plan: ${list(result.changedPlans)} · emekli plan: ${list(result.retiredPlans)} · kaldırılan feature: ${list(result.removedFeatures)}${result.defaultPlanChanged ? " · varsayılan plan değişti" : ""}`);
628
+ const changedBenefits = result.changedBenefits ?? [];
629
+ const archivedBenefits = result.archivedBenefits ?? [];
630
+ if (changedBenefits.length > 0 || archivedBenefits.length > 0) lines.push(` benefits changed: ${list(changedBenefits)} · archived: ${list(archivedBenefits)}`);
631
+ if ((result.updatedPrices ?? []).length > 0) lines.push(` prices updated in place: ${result.updatedPrices.length}`);
632
+ const changedMeters = result.changedMeters ?? [];
633
+ const archivedMeters = result.archivedMeters ?? [];
634
+ if (changedMeters.length > 0 || archivedMeters.length > 0) lines.push(` meters changed: ${list(changedMeters)} · archived: ${list(archivedMeters)}`);
635
+ const [created, updated, deactivated] = [
636
+ result.createdMeteredPrices ?? [],
637
+ result.updatedMeteredPrices ?? [],
638
+ result.deactivatedMeteredPrices ?? []
639
+ ];
640
+ if (created.length + updated.length + deactivated.length > 0) lines.push(` metered new ${created.length} · updated in place ${updated.length} · deactivated ${deactivated.length}`);
641
+ }
413
642
  for (const error of result.providerErrors) lines.push(` ✗ sağlayıcı hatası: fiyat ${error.priceId} (${error.provider}: ${error.code}) — senkronu yeniden koşun`);
414
643
  return {
415
644
  lines,
416
645
  providerErrors: result.providerErrors.length
417
646
  };
418
647
  }
648
+ /** The steward's current catalog; null before the first push (`404 catalog_not_configured`). */
649
+ function currentCatalog(steward, target) {
650
+ return callSteward(target, () => steward.catalog.get().catch((error) => {
651
+ if (error instanceof StewardApiError && error.httpStatus === 404 && error.code === "catalog_not_configured") return null;
652
+ throw error;
653
+ }));
654
+ }
655
+ /**
656
+ * Refuses a catalog whose benefits or meters steward does not understand (M27): an older steward
657
+ * drops the keys silently. `needed`: the capabilities the catalog needs (`benefits`, `meters`).
658
+ */
659
+ async function requireCapabilities(steward, target, needed) {
660
+ if (needed.length === 0) return;
661
+ const me = await callSteward(target, () => steward.me());
662
+ const missing = needed.filter((capability) => !(me.capabilities ?? []).includes(capability));
663
+ if (missing.length === 0) return;
664
+ throw new CliError(`the catalog defines ${missing.join(" and ")} but steward at ${originOf(target.url)} does not support them (GET /v1/me capabilities has no ${missing.map((c) => `"${c}"`).join(", ")}; it would drop them silently). Update steward first; nothing was pushed.`);
665
+ }
419
666
  async function catalogCommand(ctx, out, args) {
420
667
  const [sub, ...rest] = args;
421
668
  if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
@@ -423,7 +670,7 @@ async function catalogCommand(ctx, out, args) {
423
670
  return sub === void 0 ? 2 : 0;
424
671
  }
425
672
  if (sub !== "push") throw new UsageError(`bilinmeyen alt komut: catalog ${sub} (ayrıntı: steward catalog --help)`);
426
- const { values, positionals } = parse(rest, { ...HELP_OPTION }, "catalog push");
673
+ const { values, positionals } = parse(rest, PUSH_OPTIONS, "catalog push");
427
674
  if (values.help) {
428
675
  out.out(CATALOG_USAGE);
429
676
  return 0;
@@ -432,155 +679,24 @@ async function catalogCommand(ctx, out, args) {
432
679
  const input = await loadCatalogFile(ctx, positionals[0]);
433
680
  const target = requireAdminTarget(await resolveEnv(ctx));
434
681
  out.err(connectionLine(target));
435
- const { lines, providerErrors } = await pushCatalog(ctx, target, input);
682
+ const steward = clientFor(ctx, target);
683
+ await requireCapabilities(steward, target, [...definesBenefits(input) ? ["benefits"] : [], ...definesMeters(input) ? ["meters"] : []]);
684
+ const diff = diffCatalog(await currentCatalog(steward, target), input);
685
+ for (const line of describeDiff(diff)) out.out(line);
686
+ const priceChanges = priceChangeCount(diff);
687
+ if (priceChanges > 0 && !values.yes) {
688
+ const question = `Apply ${priceChanges} price change${priceChanges === 1 ? "" : "s"}? [y/N] `;
689
+ const answer = await ctx.prompt(question);
690
+ if (answer === null) throw new CliError(`${priceChanges} price change${priceChanges === 1 ? "" : "s"} need${priceChanges === 1 ? "s" : ""} confirmation: run again with --yes (nothing was pushed)`);
691
+ if (!/^y(es)?$/i.test(answer.trim())) {
692
+ out.err("not confirmed; nothing was pushed");
693
+ return 1;
694
+ }
695
+ }
696
+ const { lines, providerErrors } = await pushCatalog(steward, target, input);
436
697
  for (const line of lines) out.out(line);
437
698
  return providerErrors > 0 ? 1 : 0;
438
699
  }
439
- const POSTGRES_IMAGE = "postgres:17.6-alpine";
440
- const STATE_DIR = ".steward";
441
- const COMPOSE_FILE = `${STATE_DIR}/compose.yml`;
442
- const CREDENTIALS_FILE = `${STATE_DIR}/credentials.json`;
443
- /** Servisin ürettiği dev şifreleme anahtarı (kimlik dosyasının yanında). */
444
- const ENCRYPTION_KEY_FILE = `${STATE_DIR}/encryption-key`;
445
- const CONTAINER_STATE_DIR = "/steward-dev";
446
- const CONTAINER_PORT = 3002;
447
- const STEWARD_SERVICE = "steward";
448
- const PLACEHOLDER_TAG = "dev-unreleased";
449
- /** İmaj referansı: etiket ya da digest zorunlu, `latest` ve yer tutucu reddedilir. */
450
- function checkImage(image) {
451
- const value = image.trim();
452
- if (value === "" || /\s/.test(value)) throw new UsageError("--image: geçerli bir imaj referansı değil");
453
- if (value.includes("@sha256:")) return value;
454
- const lastSlash = value.lastIndexOf("/");
455
- const colon = value.lastIndexOf(":");
456
- const tag = colon > lastSlash ? value.slice(colon + 1) : "";
457
- if (tag === PLACEHOLDER_TAG) throw new UsageError("bu CLI sürümü henüz bir dev imajı sabitlemiyor: --image ghcr.io/z9cloud/steward:dev-<etiket> verin (etiketler image-publish'te; latest yok)");
458
- if (tag === "") throw new UsageError(`--image: etiket ya da digest gerekli (latest kullanılmaz): ${value}`);
459
- if (/(^|-)latest$/.test(tag)) throw new UsageError(`--image: ${tag} kayan etiket; sabit bir etiket verin (AGENTS.md kural 4)`);
460
- return value;
461
- }
462
- function composeProjectName(projectDir, product) {
463
- const digest = createHash("sha256").update(projectDir).digest("hex").slice(0, 8);
464
- return `steward-dev-${product.replace(/_/g, "-")}-${digest}`;
465
- }
466
- /** Tırnaklı YAML skaleri; compose `$` yerleştirmesi kaçışlı. */
467
- const q = (value) => JSON.stringify(String(value).replace(/\$/g, "$$$$"));
468
- function localBaseUrl(port) {
469
- return `http://localhost:${port}`;
470
- }
471
- function composeFile(options) {
472
- const env = [
473
- ["STEWARD_DATABASE_URL", "postgres://steward:steward@db:5432/steward"],
474
- ["STEWARD_PUBLIC_URL", localBaseUrl(options.port)],
475
- ["STEWARD_DEV_PRODUCT", options.product],
476
- ["STEWARD_DEV_CREDENTIALS_FILE", `${CONTAINER_STATE_DIR}/credentials.json`],
477
- ["STEWARD_DEV_APP_URL", options.appUrl],
478
- ...options.webhookUrl !== void 0 ? [["STEWARD_DEV_WEBHOOK_URL", options.webhookUrl]] : []
479
- ];
480
- return `${[
481
- "# steward dev tarafından üretildi — elle düzenlemeyin, her `steward dev` yeniden yazar.",
482
- "# Durdur: docker compose -f .steward/compose.yml down · Sıfırla: steward dev reset --yes",
483
- `name: ${q(composeProjectName(options.projectDir, options.product))}`,
484
- "services:",
485
- " db:",
486
- ` image: ${q(POSTGRES_IMAGE)}`,
487
- " environment:",
488
- ` POSTGRES_USER: ${q("steward")}`,
489
- ` POSTGRES_PASSWORD: ${q("steward")}`,
490
- ` POSTGRES_DB: ${q("steward")}`,
491
- " volumes:",
492
- ` - ${q("db:/var/lib/postgresql/data")}`,
493
- " healthcheck:",
494
- ` test: [${[
495
- "CMD",
496
- "pg_isready",
497
- "-h",
498
- "127.0.0.1",
499
- "-U",
500
- "steward",
501
- "-d",
502
- "steward"
503
- ].map(q).join(", ")}]`,
504
- ` interval: ${q("2s")}`,
505
- ` timeout: ${q("5s")}`,
506
- " retries: 30",
507
- ` ${STEWARD_SERVICE}:`,
508
- ` image: ${q(options.image)}`,
509
- ...options.user ? [` user: ${q(`${options.user.uid}:${options.user.gid}`)}`] : [],
510
- " depends_on:",
511
- " db:",
512
- " condition: service_healthy",
513
- " ports:",
514
- ` - ${q(`127.0.0.1:${options.port}:${CONTAINER_PORT}`)}`,
515
- " environment:",
516
- ...env.map(([key, value]) => ` ${key}: ${q(value)}`),
517
- " extra_hosts:",
518
- ` - ${q("host.docker.internal:host-gateway")}`,
519
- " volumes:",
520
- ` - ${q(`.:${CONTAINER_STATE_DIR}`)}`,
521
- "volumes:",
522
- " db: {}"
523
- ].join("\n")}\n`;
524
- }
525
- //#endregion
526
- //#region src/dev/credentials.ts
527
- const isString = (value) => typeof value === "string" && value !== "";
528
- const nullableString = (value) => value === null || isString(value);
529
- async function readCredentials(path) {
530
- let text;
531
- try {
532
- text = await readFile(path, "utf8");
533
- } catch (error) {
534
- return {
535
- ok: false,
536
- reason: errnoCode(error) === "ENOENT" ? "missing" : "unreadable"
537
- };
538
- }
539
- let data;
540
- try {
541
- data = JSON.parse(text);
542
- } catch {
543
- return {
544
- ok: false,
545
- reason: "invalid"
546
- };
547
- }
548
- if (typeof data !== "object" || data === null) return {
549
- ok: false,
550
- reason: "invalid"
551
- };
552
- const record = data;
553
- if (typeof record.version === "number" && record.version !== 1) return {
554
- ok: false,
555
- reason: "unsupported_version"
556
- };
557
- if (!(record.version === 1 && isString(record.product) && isString(record.apiKey) && record.apiKey.startsWith("stw_") && isString(record.adminApiKey) && record.adminApiKey.startsWith("stw_") && nullableString(record.webhookSecret) && (record.webhookSecret === null || record.webhookSecret.startsWith("whsec_")) && nullableString(record.endpointId) && isString(record.createdAt))) return {
558
- ok: false,
559
- reason: "invalid"
560
- };
561
- const safe = (value) => value === null || /^[A-Za-z0-9_\-+/=.]+$/.test(value);
562
- if (!safe(record.apiKey) || !safe(record.adminApiKey) || !safe(record.webhookSecret)) return {
563
- ok: false,
564
- reason: "invalid"
565
- };
566
- return {
567
- ok: true,
568
- credentials: record
569
- };
570
- }
571
- /** Başkalarınca okunabiliyorsa 0600'e indirir (en iyi çaba; dosya başkasınınsa sessizce geçer). */
572
- async function tightenMode(path) {
573
- if (process.platform === "win32") return;
574
- try {
575
- if (((await stat(path)).mode & 63) !== 0) await chmod(path, 384);
576
- } catch {}
577
- }
578
- const CREDENTIALS_PROBLEM = {
579
- missing: "kimlik dosyası henüz yok",
580
- unreadable: "kimlik dosyası okunamıyor (izin?)",
581
- invalid: "kimlik dosyası beklenen biçimde değil",
582
- unsupported_version: "kimlik dosyası sürümü bu CLI'da desteklenmiyor (CLI'ı güncelleyin)"
583
- };
584
700
  //#endregion
585
701
  //#region src/commands/doctor.ts
586
702
  const DOCTOR_USAGE = `Kullanım: steward doctor [--json]
@@ -597,7 +713,15 @@ yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
597
713
  Çıkış kodu: 0 hazır; 1 rapor ok değil (error önemde uyarı) ya da APP_URL
598
714
  steward'da izinli değil.
599
715
 
600
- --json raporu JSON yazar (+ cliWarnings: yerel APP_URL karşılaştırması)`;
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.
722
+
723
+ --json raporu JSON yazar (+ cliWarnings: yerel APP_URL karşılaştırması;
724
+ cliMetering: the metering line's catalog and capability facts)`;
601
725
  /** `APP_URL` (ürünün kendi adresi; checkout `successUrl`'i bundan kurulur) ↔ steward ayarları. */
602
726
  function appUrlWarnings(appUrl, report) {
603
727
  if (appUrl === void 0) return [];
@@ -623,6 +747,62 @@ function appUrlWarnings(appUrl, report) {
623
747
  }];
624
748
  return [];
625
749
  }
750
+ /** The capabilities the metering section shows (M27). */
751
+ const METERING_CAPABILITIES = [
752
+ "events",
753
+ "meters",
754
+ "overage"
755
+ ];
756
+ /**
757
+ * The metering section's facts: the catalog's meters and metered prices and steward's capabilities.
758
+ * Null when the catalog carries no meters (a product that never defined one, an older steward, no
759
+ * catalog yet) or cannot be read: the section is informational and never fails the doctor.
760
+ */
761
+ async function meteringSummary(steward) {
762
+ try {
763
+ const catalog = await steward.catalog.get();
764
+ if (catalog.meters === void 0) return null;
765
+ const me = await steward.me().catch(() => null);
766
+ return {
767
+ meters: Object.keys(catalog.meters),
768
+ meteredPrices: (catalog.meteredPrices ?? []).length,
769
+ capabilities: me?.capabilities ?? null
770
+ };
771
+ } catch {
772
+ return null;
773
+ }
774
+ }
775
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
776
+ /** `name (count), …` of a sample list. */
777
+ const counted = (items, key) => items.map((item) => `${item[key]} (${item.events})`).join(", ");
778
+ /**
779
+ * Lines of the metering sections: the CLI's catalog and capability facts (`metering`), then the
780
+ * report's own `events` and `overage` sections when steward sends them (a product with meters or
781
+ * metered prices; older steward sends neither).
782
+ */
783
+ function formatMetering(report, summary) {
784
+ const lines = [];
785
+ if (summary !== null) {
786
+ const meters = summary.meters.length === 0 ? "no active meters" : `${plural(summary.meters.length, "meter")} (${summary.meters.join(", ")})`;
787
+ const capabilities = summary.capabilities === null ? "capabilities unknown" : METERING_CAPABILITIES.map((c) => `${c} ${yesNo(summary.capabilities.includes(c))}`).join(" ");
788
+ lines.push(`metering ${meters} · ${plural(summary.meteredPrices, "metered price")} · steward: ${capabilities}`);
789
+ }
790
+ const { events, overage } = report;
791
+ if (events) {
792
+ const parts = [
793
+ plural(events.meters, "meter"),
794
+ ...events.backfillingMeters.length > 0 ? [`backfilling: ${events.backfillingMeters.join(", ")}`] : [],
795
+ `backlog ${events.backlogRows} (rollup lag ${events.rollupLagSeconds} s)${events.backlogged ? " — ingest answers 503 events_backlog" : ""}`,
796
+ `${plural(events.sampledEvents, "event")} sampled (7 days)`,
797
+ ...events.unmatchedEventNames.length > 0 ? [`unmatched: ${counted(events.unmatchedEventNames, "name")}`] : [],
798
+ ...events.invalidValues.length > 0 ? [`invalid values: ${counted(events.invalidValues, "meter")}`] : [],
799
+ ...events.metersWithoutEvents.length > 0 ? [`no events: ${events.metersWithoutEvents.join(", ")}`] : []
800
+ ];
801
+ lines.push(`events ${parts.join(" · ")}`);
802
+ }
803
+ if (overage) lines.push(`overage charge mode ${overage.chargeMode} · ${plural(overage.meteredPrices, "metered price")} · ${plural(overage.unratedSubscriptions, "subscription")} without a locked rate · ${plural(overage.carriedCharges, "carried charge")}`);
804
+ return lines;
805
+ }
626
806
  const MARK = {
627
807
  error: "✗",
628
808
  warning: "!",
@@ -646,7 +826,7 @@ function countBySeverity(warnings) {
646
826
  };
647
827
  }
648
828
  /** Tam insan okunur rapor. */
649
- function formatDoctorReport(report, cliWarnings) {
829
+ function formatDoctorReport(report, cliWarnings, metering = null) {
650
830
  const all = [...report.warnings, ...cliWarnings];
651
831
  const { errors, warnings } = countBySeverity(all);
652
832
  const ready = errors === 0;
@@ -673,6 +853,13 @@ function formatDoctorReport(report, cliWarnings) {
673
853
  }
674
854
  }
675
855
  lines.push(`dunning ${report.dunning.dryRun ? "dry-run (askı/sonlandırma uygulanmaz)" : "etkin"}`);
856
+ if (report.emails) {
857
+ const { emails } = report;
858
+ const problems = [...emails.transportConfigured ? [] : ["no transport"], ...emails.senderConfigured ? [] : ["no sender"]];
859
+ const disabled = emails.disabledTemplates.length > 0 ? ` · disabled: ${emails.disabledTemplates.join(", ")}` : "";
860
+ lines.push(`emails ${emails.ready ? "ready ✓" : `not sending ✗${problems.length > 0 ? ` (${problems.join(", ")})` : ""}`}${disabled}`);
861
+ }
862
+ lines.push(...formatMetering(report, metering));
676
863
  for (const severity of SEVERITY_ORDER) {
677
864
  const items = all.filter((w) => w.severity === severity);
678
865
  if (items.length === 0) continue;
@@ -685,13 +872,6 @@ function formatDoctorReport(report, cliWarnings) {
685
872
  }
686
873
  return lines;
687
874
  }
688
- /** `steward dev` sonundaki kısa özet. */
689
- function formatDoctorSummary(report) {
690
- const { errors, warnings } = countBySeverity(report.warnings);
691
- const lines = [report.ok ? `doctor: hazır ✓ (${warnings} uyarı)` : `doctor: ${errors} hata, ${warnings} uyarı`];
692
- for (const severity of SEVERITY_ORDER) for (const item of report.warnings.filter((w) => w.severity === severity)) lines.push(` ${MARK[severity]} ${item.code}: ${item.message}`);
693
- return lines;
694
- }
695
875
  async function doctorCommand(ctx, out, args) {
696
876
  const { values, positionals } = parse(args, {
697
877
  ...HELP_OPTION,
@@ -707,350 +887,20 @@ async function doctorCommand(ctx, out, args) {
707
887
  const appUrl = env.get("APP_URL");
708
888
  out.err(connectionLine(target));
709
889
  if (appUrl === void 0) out.err(`APP_URL tanımlı değil (${env.source}): steward appUrl karşılaştırması atlandı`);
710
- const report = await callSteward(target, () => clientFor(ctx, target).doctor());
890
+ const steward = clientFor(ctx, target);
891
+ const report = await callSteward(target, () => steward.doctor());
711
892
  const cliWarnings = appUrlWarnings(appUrl, report);
712
893
  const failed = !report.ok || cliWarnings.some((w) => w.severity === "error");
894
+ const metering = await meteringSummary(steward);
713
895
  if (values.json) out.out(JSON.stringify({
714
896
  ...report,
715
- cliWarnings
897
+ cliWarnings,
898
+ ...metering !== null ? { cliMetering: metering } : {}
716
899
  }, null, 2));
717
- else for (const line of formatDoctorReport(report, cliWarnings)) out.out(line);
900
+ else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
718
901
  return failed ? 1 : 0;
719
902
  }
720
903
  //#endregion
721
- //#region src/commands/dev.ts
722
- const DEV_USAGE = `Kullanım:
723
- steward dev [--product <kod>] [--catalog <dosya>] [--port 3002] [--app-url <url>]
724
- [--webhook-url <url>] [--image <imaj>] [--timeout <sn>]
725
- steward dev reset --yes
726
-
727
- Yerel steward: dev imajı + Postgres (Docker compose, yalnızca 127.0.0.1), sahte
728
- ödeme sağlayıcısı; hosted checkout ve portal http://localhost:<port>/public altında.
729
-
730
- 1. .steward/compose.yml yazılır, .steward/ .gitignore'a eklenir (yoksa)
731
- 2. docker compose -f .steward/compose.yml up -d, /health beklenir
732
- 3. servis ürünü ve anahtarları oluşturur; .steward/credentials.json okunur
733
- 4. .env.local'e STEWARD_URL, STEWARD_ADMIN_URL, STEWARD_API_KEY,
734
- STEWARD_ADMIN_API_KEY (+ STEWARD_WEBHOOK_SECRET) yazılır — değerler
735
- terminale yazılmaz, diğer satırlar korunur; --webhook-url verilmezse
736
- önceki koşunun STEWARD_WEBHOOK_SECRET satırı silinir
737
- 5. --catalog verilmişse katalog senkronlanır; doctor özeti
738
-
739
- --product <kod> ürün kodu (varsayılan: package.json adından)
740
- --catalog <dosya> katalog (.ts/.mjs/.js/.json; bkz. steward catalog push)
741
- --port <n> host portu (varsayılan 3002)
742
- --app-url <url> ürünün yerel adresi (varsayılan http://localhost:3000)
743
- --webhook-url <url> webhook alıcısı, ör. http://host.docker.internal:3000/api/billing/events
744
- --image <imaj> dev imajı. İlk dev imajı yayınına kadar ZORUNLU (varsayılan
745
- etiket yer tutucu): ghcr.io/z9cloud/steward:dev-<etiket> ya da
746
- steward reposunda docker build --target dev -t steward-dev:local .
747
- → --image steward-dev:local
748
- --timeout <sn> hazır olma beklemesi (varsayılan 180)
749
-
750
- dev reset --yes: compose'u durdurur, veritabanı volume'ünü (docker compose down -v),
751
- kimlik dosyasını ve servisin dev şifreleme anahtarını (.steward/encryption-key) siler.
752
- .env.local'deki anahtarlar geçersiz kalır; sonraki steward dev yenilerini yazar.`;
753
- const DEV_OPTIONS = {
754
- ...HELP_OPTION,
755
- product: { type: "string" },
756
- catalog: { type: "string" },
757
- port: { type: "string" },
758
- "app-url": { type: "string" },
759
- "webhook-url": { type: "string" },
760
- image: { type: "string" },
761
- timeout: { type: "string" }
762
- };
763
- const PRODUCT_CODE = /^[a-z][a-z0-9_]{0,62}$/;
764
- const WEBHOOK_SECRET_KEY = "STEWARD_WEBHOOK_SECRET";
765
- const GITIGNORE_ENTRIES = /* @__PURE__ */ new Set([
766
- ".steward",
767
- ".steward/",
768
- "/.steward",
769
- "/.steward/",
770
- ".steward/*",
771
- "/.steward/*"
772
- ]);
773
- /**
774
- Servis kimlik dosyasını `serve`'den önce yazar: /health yanıt verdiğinde dosya hazırdır. Yine de
775
- (yeniden başlatma, yavaş dosya sistemi) kısa bir süre tekrar okunur; sonra açık hata.
776
- */
777
- const CREDENTIALS_GRACE_MS = 15e3;
778
- /** Paket adı ya da klasör adından ürün kodu (`@acme/Web-App` → `web_app`). */
779
- function toProductCode(value) {
780
- if (value === void 0) return null;
781
- const code = value.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^[^a-z]+/, "").replace(/_+$/, "").slice(0, 63);
782
- return PRODUCT_CODE.test(code) ? code : null;
783
- }
784
- async function inferProductCode(cwd) {
785
- try {
786
- const pkg = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
787
- const code = toProductCode(typeof pkg.name === "string" ? pkg.name : void 0);
788
- if (code !== null) return {
789
- code,
790
- from: "package.json adı"
791
- };
792
- } catch {}
793
- const code = toProductCode(basename(cwd));
794
- return code !== null ? {
795
- code,
796
- from: "klasör adı"
797
- } : {
798
- code: "dev",
799
- from: "varsayılan"
800
- };
801
- }
802
- async function exists(path) {
803
- try {
804
- await stat(path);
805
- return true;
806
- } catch (error) {
807
- if (errnoCode(error) === "ENOENT") return false;
808
- throw error;
809
- }
810
- }
811
- async function ensureDockerCompose(ctx) {
812
- if ((await ctx.run("docker", ["compose", "version"], {
813
- cwd: ctx.cwd,
814
- capture: true
815
- })).code !== 0) throw new CliError("docker compose bulunamadı ya da Docker çalışmıyor (Docker Desktop / OrbStack açık mı?)");
816
- }
817
- /** `.steward/` .gitignore'da değilse ekler (dosya yoksa oluşturur). Eklendiyse true. */
818
- async function ensureGitignored(cwd) {
819
- const path = join(cwd, ".gitignore");
820
- let text = "";
821
- try {
822
- text = await readFile(path, "utf8");
823
- } catch (error) {
824
- if (errnoCode(error) !== "ENOENT") throw error;
825
- }
826
- if (text.split(/\r?\n/).some((line) => GITIGNORE_ENTRIES.has(line.trim()))) return false;
827
- const eol = text.includes("\r\n") ? "\r\n" : "\n";
828
- const prefix = text === "" ? "" : text.endsWith("\n") ? eol : `${eol}${eol}`;
829
- await writeFile(path, `${text}${prefix}# steward dev (yerel veritabanı ve kimlik bilgileri)${eol}${STATE_DIR}/${eol}`);
830
- return true;
831
- }
832
- async function waitForHealth(ctx, baseUrl, deadline, timeoutSeconds) {
833
- let last = "bağlantı yok";
834
- for (let attempt = 1;; attempt++) {
835
- try {
836
- const res = await ctx.fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(2e3) });
837
- if (res.ok) {
838
- const body = await res.json().catch(() => null);
839
- return { env: typeof body?.env === "string" ? body.env : null };
840
- }
841
- last = `HTTP ${res.status}`;
842
- } catch {
843
- last = "bağlantı yok";
844
- }
845
- if (ctx.now() >= deadline) throw new CliError(`steward ${timeoutSeconds} sn içinde hazır olmadı (/health: ${last}). Loglar: docker compose -f ${COMPOSE_FILE} logs ${STEWARD_SERVICE}`);
846
- if (attempt % 5 === 0) {
847
- const ps = await ctx.run("docker", [
848
- "compose",
849
- "-f",
850
- COMPOSE_FILE,
851
- "ps",
852
- "--status",
853
- "running",
854
- "--services"
855
- ], {
856
- cwd: ctx.cwd,
857
- capture: true
858
- });
859
- if (ps.code === 0 && !ps.stdout.split(/\r?\n/).includes("steward")) throw new CliError(`steward konteyneri çalışmıyor. Loglar: docker compose -f ${COMPOSE_FILE} logs ${STEWARD_SERVICE}`);
860
- }
861
- await ctx.sleep(1e3);
862
- }
863
- }
864
- /** Anahtarlar bu steward'da geçerli ve beklenen ürün/kapsamda mı; sorun varsa açıklaması. */
865
- async function verifyKeys(ctx, baseUrl, credentials) {
866
- const keys = [{
867
- apiKey: credentials.apiKey,
868
- scope: "product",
869
- label: "ürün anahtarı"
870
- }, {
871
- apiKey: credentials.adminApiKey,
872
- scope: "admin",
873
- label: "admin anahtarı"
874
- }];
875
- for (const key of keys) try {
876
- const me = await clientFor(ctx, {
877
- url: baseUrl,
878
- apiKey: key.apiKey
879
- }, { retries: false }).me();
880
- if (me.product !== credentials.product) return `kimlik dosyasındaki ${key.label} başka bir ürünün (${me.product})`;
881
- if (me.scope !== key.scope) return `kimlik dosyasındaki ${key.label} kapsamı beklenen değil (${me.scope})`;
882
- } catch (error) {
883
- if (error instanceof StewardApiError && error.httpStatus === 401) return `kimlik dosyasındaki ${key.label} bu veritabanında geçersiz (veritabanı elle silindiyse: steward dev reset --yes)`;
884
- if (error instanceof StewardError) return describeStewardError(error, { url: baseUrl });
885
- throw error;
886
- }
887
- return null;
888
- }
889
- async function waitForCredentials(ctx, options) {
890
- const giveUpAt = Math.min(options.deadline, ctx.now() + CREDENTIALS_GRACE_MS);
891
- for (;;) {
892
- const read = await readCredentials(options.path);
893
- let problem;
894
- if (read.ok) {
895
- const { credentials } = read;
896
- const invalid = (credentials.product !== options.product ? `kimlik dosyası başka bir ürünün (${credentials.product}); servis yeniden başlatılınca yeniden yazar` : null) ?? await verifyKeys(ctx, options.baseUrl, credentials);
897
- if (invalid === null) {
898
- await tightenMode(options.path);
899
- return credentials;
900
- }
901
- problem = invalid;
902
- } else {
903
- if (read.reason === "unsupported_version") throw new CliError(CREDENTIALS_PROBLEM.unsupported_version);
904
- problem = read.reason === "missing" ? `${CREDENTIALS_PROBLEM.missing} (imaj dev sağlamayı destekliyor mu? ghcr.io/z9cloud/steward:dev-<etiket>)` : CREDENTIALS_PROBLEM[read.reason];
905
- }
906
- if (ctx.now() >= giveUpAt) throw new CliError(`steward kimlik bilgileri alınamadı: ${problem}. Loglar: docker compose -f ${COMPOSE_FILE} logs ${STEWARD_SERVICE}`);
907
- await ctx.sleep(1e3);
908
- }
909
- }
910
- /** `.env.local` gitignore'da değilse uyarır (git yoksa ya da repo değilse sessiz). */
911
- async function warnIfEnvLocalTracked(ctx, out) {
912
- if ((await ctx.run("git", [
913
- "check-ignore",
914
- "-q",
915
- ".env.local"
916
- ], {
917
- cwd: ctx.cwd,
918
- capture: true
919
- })).code === 1) out.err(`! ${ENV_LOCAL} .gitignore'da değil: anahtarlar içerir, commit'lenmemeli (ör. .gitignore'a \`.env*.local\` ekleyin)`);
920
- }
921
- async function devCommand(ctx, out, args) {
922
- if (args[0] === "reset") return devReset(ctx, out, args.slice(1));
923
- const { values, positionals } = parse(args, DEV_OPTIONS, "dev");
924
- if (values.help) {
925
- out.out(DEV_USAGE);
926
- return 0;
927
- }
928
- if (positionals.length > 0) throw new UsageError(`bilinmeyen alt komut: dev ${positionals[0]} (ayrıntı: steward dev --help)`);
929
- let product;
930
- if (values.product !== void 0) {
931
- product = values.product.trim();
932
- if (!PRODUCT_CODE.test(product)) throw new UsageError("--product: küçük harf, rakam ve _ (harfle başlar, en çok 63)");
933
- } else {
934
- const inferred = await inferProductCode(ctx.cwd);
935
- product = inferred.code;
936
- out.err(`ürün kodu: ${product} (${inferred.from}; değiştirmek için --product)`);
937
- }
938
- const port = parsePositiveInt(values.port ?? "3002", "--port", { max: 65535 });
939
- const appUrl = parseHttpUrl(values["app-url"] ?? "http://localhost:3000", "--app-url");
940
- const webhookUrl = values["webhook-url"] !== void 0 ? parseHttpUrl(values["webhook-url"], "--webhook-url") : void 0;
941
- const image = checkImage(values.image ?? "ghcr.io/z9cloud/steward:dev-unreleased");
942
- const timeoutSeconds = parsePositiveInt(values.timeout ?? "180", "--timeout", { max: 3600 });
943
- let catalog = null;
944
- if (values.catalog !== void 0) catalog = await loadCatalogFile(ctx, values.catalog);
945
- const baseUrl = localBaseUrl(port);
946
- await ensureDockerCompose(ctx);
947
- const stateDir = join(ctx.cwd, STATE_DIR);
948
- await mkdir(stateDir, {
949
- recursive: true,
950
- mode: 448
951
- });
952
- await writeFile(join(ctx.cwd, COMPOSE_FILE), composeFile({
953
- projectDir: resolve(ctx.cwd),
954
- product,
955
- port,
956
- appUrl,
957
- ...webhookUrl !== void 0 ? { webhookUrl } : {},
958
- image,
959
- user: ctx.platform === "linux" ? ctx.hostUser() : null
960
- }));
961
- if (await ensureGitignored(ctx.cwd)) out.err(`.gitignore'a ${STATE_DIR}/ eklendi (yerel veritabanı ve kimlik bilgileri)`);
962
- await warnIfEnvLocalTracked(ctx, out);
963
- out.err(`steward başlatılıyor (${image}) → ${baseUrl}`);
964
- const up = await ctx.run("docker", [
965
- "compose",
966
- "-f",
967
- COMPOSE_FILE,
968
- "up",
969
- "-d"
970
- ], { cwd: ctx.cwd });
971
- if (up.code !== 0) throw new CliError(`docker compose up başarısız (çıkış ${up.code}); port ${port} kullanımda olabilir (--port)`);
972
- const deadline = ctx.now() + timeoutSeconds * 1e3;
973
- const health = await waitForHealth(ctx, baseUrl, deadline, timeoutSeconds);
974
- if (health.env === "production") throw new CliError(`${image} üretim imajı (env: production): dev imajı verin (ghcr.io/z9cloud/steward:dev-<etiket>)`);
975
- const credentials = await waitForCredentials(ctx, {
976
- path: join(ctx.cwd, CREDENTIALS_FILE),
977
- product,
978
- baseUrl,
979
- deadline
980
- });
981
- const entries = [
982
- ["STEWARD_URL", baseUrl],
983
- ["STEWARD_ADMIN_URL", baseUrl],
984
- ["STEWARD_API_KEY", credentials.apiKey],
985
- ["STEWARD_ADMIN_API_KEY", credentials.adminApiKey],
986
- ...credentials.webhookSecret !== null ? [[WEBHOOK_SECRET_KEY, credentials.webhookSecret]] : []
987
- ];
988
- const remove = credentials.webhookSecret === null ? [WEBHOOK_SECRET_KEY] : [];
989
- const env = await upsertDotenvFile(join(ctx.cwd, ENV_LOCAL), entries, remove);
990
- const written = entries.map(([key]) => key).filter((key) => env.added.includes(key) || env.updated.includes(key));
991
- const removed = env.removed.length > 0 ? `; kaldırıldı: ${env.removed.join(", ")} (webhook endpoint'i yok)` : "";
992
- if (env.created) out.err(`${ENV_LOCAL} oluşturuldu (0600): ${written.join(", ")} (değerler yazdırılmaz)`);
993
- else if (written.length > 0 || removed !== "") {
994
- const changed = written.length > 0 ? written.join(", ") : "değer değişmedi";
995
- out.err(`${ENV_LOCAL} güncellendi: ${changed}${removed} (değerler yazdırılmaz; diğer satırlar korundu)`);
996
- } else out.err(`${ENV_LOCAL} güncel: ${env.unchanged.join(", ")}`);
997
- if (env.looseMode) out.err(`! ${ENV_LOCAL} başka kullanıcılarca okunabilir: chmod 600 ${ENV_LOCAL}`);
998
- if (credentials.webhookSecret === null) out.err("webhook endpoint'i yok (laptop'a webhook gelmez); gerekirse --webhook-url http://host.docker.internal:<port>/<yol>");
999
- let exitCode = 0;
1000
- if (catalog !== null) {
1001
- const pushed = await pushCatalog(ctx, {
1002
- url: baseUrl,
1003
- apiKey: credentials.adminApiKey
1004
- }, catalog);
1005
- for (const line of pushed.lines) out.err(line);
1006
- if (pushed.providerErrors > 0) exitCode = 1;
1007
- }
1008
- const target = {
1009
- url: baseUrl,
1010
- apiKey: credentials.apiKey
1011
- };
1012
- const report = await callSteward(target, () => clientFor(ctx, target).doctor());
1013
- for (const line of formatDoctorSummary(report)) out.err(line);
1014
- out.out(`steward dev hazır: ${baseUrl} (ürün ${product}${health.env !== null ? `, env ${health.env}` : ""})`);
1015
- out.out(` hosted checkout/portal: ${baseUrl}/public/… · uygulamanızı başlatın (ör. pnpm dev)`);
1016
- out.out(` durdur: docker compose -f ${COMPOSE_FILE} down · sıfırla: steward dev reset --yes`);
1017
- return exitCode;
1018
- }
1019
- async function devReset(ctx, out, args) {
1020
- const { values, positionals } = parse(args, {
1021
- ...HELP_OPTION,
1022
- yes: { type: "boolean" }
1023
- }, "dev");
1024
- if (values.help) {
1025
- out.out(DEV_USAGE);
1026
- return 0;
1027
- }
1028
- expectPositionals(positionals, 0, 0, "dev");
1029
- if (!values.yes) throw new UsageError(`dev reset yerel steward veritabanını (Docker volume), ${CREDENTIALS_FILE} ve ${ENCRYPTION_KEY_FILE} dosyalarını siler; onaylamak için --yes`);
1030
- const files = [CREDENTIALS_FILE, ENCRYPTION_KEY_FILE];
1031
- if (await exists(join(ctx.cwd, COMPOSE_FILE))) {
1032
- await ensureDockerCompose(ctx);
1033
- const down = await ctx.run("docker", [
1034
- "compose",
1035
- "-f",
1036
- COMPOSE_FILE,
1037
- "down",
1038
- "-v",
1039
- "--remove-orphans"
1040
- ], { cwd: ctx.cwd });
1041
- if (down.code !== 0) throw new CliError(`docker compose down başarısız (çıkış ${down.code}); dosyalar silinmedi`);
1042
- } else {
1043
- const leftovers = [];
1044
- for (const file of files) if (await exists(join(ctx.cwd, file))) leftovers.push(file);
1045
- if (leftovers.length > 0) throw new CliError(`${COMPOSE_FILE} yok, veritabanı volume'ü silinemiyor; ${leftovers.join(" ve ")} korunuyor. Önce steward dev (aynı --product) ile compose'u yeniden yazın.`);
1046
- out.out("sıfırlanacak yerel steward yok");
1047
- return 0;
1048
- }
1049
- for (const file of files) await rm(join(ctx.cwd, file), { force: true });
1050
- out.out(`yerel steward sıfırlandı: veritabanı volume'ü, ${CREDENTIALS_FILE} ve ${ENCRYPTION_KEY_FILE} silindi. ${ENV_LOCAL}'deki anahtarlar geçersiz; steward dev yenilerini yazar.`);
1051
- return 0;
1052
- }
1053
- //#endregion
1054
904
  //#region src/secret-file.ts
1055
905
  async function withSecretFile(cwd, out, secret, options, action) {
1056
906
  const target = resolve(cwd, out);
@@ -1246,18 +1096,307 @@ function secretNotice(out, path, fallback, next) {
1246
1096
  out.err(next);
1247
1097
  }
1248
1098
  //#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
+ //#region src/commands/events.ts
1176
+ const EVENTS_USAGE = `Usage: steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
1177
+ [--timestamp <iso>] [--json]
1178
+
1179
+ Sends one event for account <ref> (POST /v1/events/ingest), e.g. to try a meter locally.
1180
+ The event itself has no billing meaning: it counts as usage for the meters whose filter
1181
+ matches it, once steward has rolled it up (seconds; see steward meters get <ref>).
1182
+
1183
+ --meta key=value metadata pair, repeatable. A plain number (12, 0.25) or true/false is
1184
+ sent as such, anything else as text; double quotes force text
1185
+ (--meta 'code="007"').
1186
+ --external-id <id> the event's dedup key (8–200 characters: A–Z a–z 0–9 _ . : -). Default:
1187
+ a new cli:<uuid>, printed so the same event can be sent again (it is then
1188
+ a duplicate and counts once).
1189
+ --timestamp <iso> when it happened (default: when steward receives it); at most 35 days
1190
+ back and 5 minutes ahead.
1191
+ --json print the ingest result as JSON
1192
+
1193
+ Metadata must not carry personal data (names, e-mail addresses, phone numbers): use opaque ids.
1194
+
1195
+ Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
1196
+ STEWARD_ADMIN_API_KEY). Sent with X-Actor-Ref operator:<user>.
1197
+ Exit code 1: the event was rejected (unknown or deleted account, timestamp out of range).`;
1198
+ const SEND_OPTIONS = {
1199
+ ...HELP_OPTION,
1200
+ meta: {
1201
+ type: "string",
1202
+ multiple: true
1203
+ },
1204
+ "external-id": { type: "string" },
1205
+ timestamp: { type: "string" },
1206
+ json: { type: "boolean" }
1207
+ };
1208
+ const PLAIN_NUMBER = /^-?\d+(\.\d+)?$/;
1209
+ /** `--meta` value: a plain number in canonical form or true/false keeps its type; `"…"` forces text; otherwise text. */
1210
+ function parseMetaValue(text) {
1211
+ if (text.length >= 2 && text.startsWith("\"") && text.endsWith("\"")) return text.slice(1, -1);
1212
+ if (text === "true") return true;
1213
+ if (text === "false") return false;
1214
+ if (PLAIN_NUMBER.test(text) && String(Number(text)) === text) return Number(text);
1215
+ return text;
1216
+ }
1217
+ /** `--meta k=v` pairs → metadata; a pair without `=` or a repeated key is a usage error. */
1218
+ function parseMetadata(pairs) {
1219
+ const metadata = {};
1220
+ for (const pair of pairs) {
1221
+ const at = pair.indexOf("=");
1222
+ if (at <= 0) throw new UsageError(`--meta: expected key=value, got "${pair}"`);
1223
+ const key = pair.slice(0, at);
1224
+ if (Object.hasOwn(metadata, key)) throw new UsageError(`--meta: key "${key}" given twice`);
1225
+ metadata[key] = parseMetaValue(pair.slice(at + 1));
1226
+ }
1227
+ return metadata;
1228
+ }
1229
+ const REJECT_HINTS = {
1230
+ account_not_found: "steward has no such account (it is created by the first checkout or accounts.upsert)",
1231
+ account_deleted: "the account was deleted",
1232
+ timestamp_out_of_range: "--timestamp must lie within the last 35 days and at most 5 minutes ahead"
1233
+ };
1234
+ async function eventsCommand(ctx, out, args) {
1235
+ const [sub, ...rest] = args;
1236
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1237
+ out.out(EVENTS_USAGE);
1238
+ return sub === void 0 ? 2 : 0;
1239
+ }
1240
+ if (sub !== "send") throw new UsageError(`unknown subcommand: events ${sub} (see: steward events --help)`);
1241
+ const { values, positionals } = parse(rest, SEND_OPTIONS, "events");
1242
+ if (values.help) {
1243
+ out.out(EVENTS_USAGE);
1244
+ return 0;
1245
+ }
1246
+ expectPositionals(positionals, 2, 2, "events");
1247
+ const [ref, name] = positionals;
1248
+ const metadata = parseMetadata(values.meta ?? []);
1249
+ const externalId = values["external-id"] ?? `cli:${globalThis.crypto.randomUUID()}`;
1250
+ const event = {
1251
+ accountRef: ref,
1252
+ name,
1253
+ externalId,
1254
+ ...values.timestamp !== void 0 ? { timestamp: values.timestamp } : {},
1255
+ ...Object.keys(metadata).length > 0 ? { metadata } : {}
1256
+ };
1257
+ const input = EventsIngestInputSchema.safeParse({ events: [event] });
1258
+ 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
+ const target = requireReadTarget(await resolveEnv(ctx));
1260
+ 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
+ }));
1267
+ if (values.json) out.out(JSON.stringify({
1268
+ externalId,
1269
+ ...result
1270
+ }, null, 2));
1271
+ else if (result.inserted > 0) {
1272
+ out.out(`event stored → ${originOf(target.url)}: ${name} for ${ref} (externalId ${externalId})`);
1273
+ out.out(`it counts for the meters whose filter matches it once rolled up: steward meters get ${ref}`);
1274
+ } else if (result.duplicates > 0) out.out(`duplicate: an event with externalId ${externalId} is already stored; nothing new was written (it counts once)`);
1275
+ const rejected = result.rejected[0];
1276
+ if (rejected !== void 0) {
1277
+ const hint = Object.hasOwn(REJECT_HINTS, rejected.code) ? ` — ${REJECT_HINTS[rejected.code]}` : "";
1278
+ throw new CliError(`event rejected: ${rejected.code}${hint}`);
1279
+ }
1280
+ return 0;
1281
+ }
1282
+ //#endregion
1283
+ //#region src/commands/meters.ts
1284
+ const METERS_USAGE = `Usage: steward meters get <ref> [--periods <n>] [--json]
1285
+
1286
+ Reads an account's meters (GET /v1/accounts/:ref/meters): per meter the current usage
1287
+ period, units used, the period's credit, the balance, the standing (ok | low | exhausted)
1288
+ and, for a billable meter, the estimated overage so far. Nothing is written.
1289
+
1290
+ --periods <n> also list the last n closed periods (1–100; GET …/meters/periods)
1291
+ --json print the response as JSON
1292
+
1293
+ Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
1294
+ STEWARD_ADMIN_API_KEY); environment, otherwise ./.env.local.`;
1295
+ const GET_OPTIONS = {
1296
+ ...HELP_OPTION,
1297
+ periods: { type: "string" },
1298
+ json: { type: "boolean" }
1299
+ };
1300
+ /** Units of a meter read (a JSON number with at most 6 decimals) as exact text with grouping: `1,700,000.5`. */
1301
+ function formatUnitsText(value) {
1302
+ return new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
1303
+ }
1304
+ function meterLines(code, meter, width) {
1305
+ const lines = [` ${code.padEnd(width)} ${meter.periodStart} → ${meter.periodEnd}`];
1306
+ const indent = " ".repeat(width + 4);
1307
+ lines.push(`${indent}used ${formatUnitsText(meter.consumedUnits)} · credit ${formatUnitsText(meter.creditedUnits)} · balance ${formatUnitsText(meter.balance)} · standing ${meter.standing}`);
1308
+ const included = meter.includedUnits === null ? "no credit included" : `included ${formatUnitsText(meter.includedUnits)} per period`;
1309
+ const billing = meter.billable && meter.amountDueMinor !== null && meter.currency !== null ? `billable: ${formatUnitsText(meter.overageUnits)} over the credit, estimated overage ${formatMinor(meter.amountDueMinor, meter.currency)}` : "not billable (no metered price)";
1310
+ lines.push(`${indent}${included} · ${billing}`);
1311
+ return lines;
1312
+ }
1313
+ /** Human-readable meter read (+ closed periods, newest first). */
1314
+ function formatMeters(meters, periods) {
1315
+ const lines = [`meters of ${meters.ref} · as of ${meters.asOf} · events received before ${meters.rolledUpThrough} are counted`];
1316
+ const codes = Object.keys(meters.meters);
1317
+ if (codes.length === 0) lines.push(" no meters (the product's catalog defines none)");
1318
+ else {
1319
+ const width = Math.max(...codes.map((code) => code.length));
1320
+ for (const code of codes) lines.push(...meterLines(code, meters.meters[code], width));
1321
+ }
1322
+ if (periods !== null) {
1323
+ lines.push("");
1324
+ if (periods.length === 0) lines.push("closed periods: none");
1325
+ else {
1326
+ lines.push("closed periods (newest first):");
1327
+ const width = Math.max(...periods.map((p) => p.meter.length));
1328
+ for (const period of periods) lines.push(` ${period.meter.padEnd(width)} ${period.periodStart} → ${period.periodEnd} used ${formatUnitsText(period.consumedUnits)} · credit ${formatUnitsText(period.creditedUnits)} · over ${formatUnitsText(period.overageUnits)}`);
1329
+ }
1330
+ }
1331
+ return lines;
1332
+ }
1333
+ async function metersCommand(ctx, out, args) {
1334
+ const [sub, ...rest] = args;
1335
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1336
+ out.out(METERS_USAGE);
1337
+ return sub === void 0 ? 2 : 0;
1338
+ }
1339
+ if (sub !== "get") throw new UsageError(`unknown subcommand: meters ${sub} (see: steward meters --help)`);
1340
+ const { values, positionals } = parse(rest, GET_OPTIONS, "meters");
1341
+ if (values.help) {
1342
+ out.out(METERS_USAGE);
1343
+ return 0;
1344
+ }
1345
+ expectPositionals(positionals, 1, 1, "meters");
1346
+ const ref = positionals[0];
1347
+ const limit = values.periods === void 0 ? null : parsePositiveInt(values.periods, "--periods", { max: 100 });
1348
+ const target = requireReadTarget(await resolveEnv(ctx));
1349
+ 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,
1363
+ closedPeriods: periods
1364
+ }, null, 2));
1365
+ else for (const line of formatMeters(read.data, periods)) out.out(line);
1366
+ return 0;
1367
+ }
1368
+ //#endregion
1249
1369
  //#region src/commands/settings.ts
1250
1370
  const SETTINGS_USAGE = `Kullanım:
1251
1371
  steward settings get
1252
1372
  steward settings set [--app-url <url>] [--privacy-url <url>] [--terms-url <url>]
1253
1373
  [--branding <json>] [--default-locale tr|en]
1254
1374
  [--checkout-ttl <dakika>] [--portal-ttl <dakika>]
1255
- [--extra-return-origins <a,b>]
1375
+ [--extra-return-origins <a,b>] [--emails <json>]
1376
+ [--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>]
1377
+ [--billing-allow-multiple-subscriptions true|false]
1378
+ [--metering-charge-mode off|dry_run|live]
1379
+ [--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]
1256
1380
 
1257
1381
  Ürün ayarları (GET/PATCH /v1/admin/settings). Verilmeyen alan değişmez; boş değer
1258
1382
  (--privacy-url "") alanı temizler, --branding null markayı temizler, --branding
1259
1383
  '{"name":"Acme","supportEmail":"destek@acme.com"}' sığ birleşir (alanı null ile
1260
1384
  temizleyin). --extra-return-origins "" listeyi boşaltır.
1385
+ --emails '{"billingPath":"/{LOCALE}/billing","templates":{"invoice_issued":{"enabled":false}}}'
1386
+ sets billing emails (sender: from.name, from.address; templates merge per
1387
+ template, null resets a field or template; --emails null resets all).
1388
+ Billing (settings.billing): --billing-payment-due-days days from writing a renewal
1389
+ invoice to its due date (default 7), --billing-min-invoice-minor smallest amount
1390
+ steward invoices on its own, in minor units (default 1000), and
1391
+ --billing-allow-multiple-subscriptions (default false: a checkout for an account with
1392
+ a live subscription is 409 already_subscribed; true: only a second subscription to the
1393
+ same plan is). An empty value ("") restores the field's default.
1394
+ Metering (settings.metering, settings.events): --metering-charge-mode prices overage
1395
+ at the end of a usage period: dry_run (default) records the charge without invoicing
1396
+ it, live adds it to the renewal invoice, off prices nothing — run one full cycle in
1397
+ dry_run before live. --metering-late-grace-minutes how long a period waits for late
1398
+ events before it closes (default 60). --events-retention-days how long raw events are
1399
+ kept after receipt, once their period is closed (default 120). "" restores the default.
1261
1400
 
1262
1401
  Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
1263
1402
  const SET_OPTIONS = {
@@ -1269,7 +1408,14 @@ const SET_OPTIONS = {
1269
1408
  "default-locale": { type: "string" },
1270
1409
  "checkout-ttl": { type: "string" },
1271
1410
  "portal-ttl": { type: "string" },
1272
- "extra-return-origins": { type: "string" }
1411
+ "extra-return-origins": { type: "string" },
1412
+ emails: { type: "string" },
1413
+ "billing-payment-due-days": { type: "string" },
1414
+ "billing-min-invoice-minor": { type: "string" },
1415
+ "billing-allow-multiple-subscriptions": { type: "string" },
1416
+ "metering-charge-mode": { type: "string" },
1417
+ "metering-late-grace-minutes": { type: "string" },
1418
+ "events-retention-days": { type: "string" }
1273
1419
  };
1274
1420
  const orNull = (value) => value.trim() === "" ? null : value.trim();
1275
1421
  /** Bayraklardan yama; sözleşme şemasıyla doğrulanır (geçersizse istek gönderilmez). */
@@ -1292,10 +1438,44 @@ function buildSettingsPatch(values) {
1292
1438
  patch.branding = branding;
1293
1439
  }
1294
1440
  }
1441
+ if (values.emails !== void 0) {
1442
+ const text = values.emails.trim();
1443
+ if (text === "" || text === "null") patch.emails = null;
1444
+ else {
1445
+ let emails;
1446
+ try {
1447
+ emails = JSON.parse(text);
1448
+ } catch {
1449
+ throw new UsageError("--emails: must be a JSON object, e.g. '{\"billingPath\":\"/billing\"}'");
1450
+ }
1451
+ if (typeof emails !== "object" || emails === null || Array.isArray(emails)) throw new UsageError("--emails: must be a JSON object");
1452
+ patch.emails = emails;
1453
+ }
1454
+ }
1295
1455
  if (values["default-locale"] !== void 0) patch.defaultLocale = values["default-locale"].trim();
1296
1456
  if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
1297
1457
  if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
1298
1458
  if (values["extra-return-origins"] !== void 0) patch.extraReturnOrigins = parseList(values["extra-return-origins"]);
1459
+ const billing = {};
1460
+ const dueDays = values["billing-payment-due-days"];
1461
+ if (dueDays !== void 0) billing.paymentDueDays = dueDays.trim() === "" ? null : parsePositiveInt(dueDays, "--billing-payment-due-days", { max: 60 });
1462
+ const minInvoice = values["billing-min-invoice-minor"];
1463
+ if (minInvoice !== void 0) billing.minInvoiceMinor = minInvoice.trim() === "" ? null : parseNonNegativeInt(minInvoice, "--billing-min-invoice-minor");
1464
+ const multiple = values["billing-allow-multiple-subscriptions"];
1465
+ if (multiple !== void 0) billing.allowMultipleSubscriptions = multiple.trim() === "" ? null : parseBoolean(multiple, "--billing-allow-multiple-subscriptions");
1466
+ if (Object.keys(billing).length > 0) patch.billing = billing;
1467
+ const metering = {};
1468
+ const chargeMode = values["metering-charge-mode"];
1469
+ if (chargeMode !== void 0) {
1470
+ const mode = chargeMode.trim();
1471
+ if (mode !== "" && !METER_CHARGE_MODES.includes(mode)) throw new UsageError(`--metering-charge-mode: one of ${METER_CHARGE_MODES.join(", ")}`);
1472
+ metering.chargeMode = mode === "" ? null : mode;
1473
+ }
1474
+ const grace = values["metering-late-grace-minutes"];
1475
+ if (grace !== void 0) metering.lateGraceMinutes = grace.trim() === "" ? null : parseNonNegativeInt(grace, "--metering-late-grace-minutes");
1476
+ if (Object.keys(metering).length > 0) patch.metering = metering;
1477
+ const retention = values["events-retention-days"];
1478
+ if (retention !== void 0) patch.events = { retentionDays: retention.trim() === "" ? null : parsePositiveInt(retention, "--events-retention-days", { max: 400 }) };
1299
1479
  if (Object.keys(patch).length === 0) throw new UsageError(`en az bir ayar bayrağı gerekli (ayrıntı: steward settings --help)`);
1300
1480
  const parsed = ProductSettingsPatchSchema.safeParse(patch);
1301
1481
  if (!parsed.success) throw new UsageError(`ayarlar geçersiz (istek gönderilmedi)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n")}`);
@@ -1333,6 +1513,7 @@ async function settingsCommand(ctx, out, args) {
1333
1513
  out.err(connectionLine(target));
1334
1514
  const settings = await callSteward(target, () => clientFor(ctx, target).admin.settings.update(patch));
1335
1515
  out.err(`ayarlar güncellendi → ${originOf(target.url)} (${Object.keys(patch).join(", ")})`);
1516
+ if (patch.metering?.chargeMode === "live") out.err("note: overage is now added to renewal invoices; it should follow one full usage cycle observed in dry_run");
1336
1517
  out.out(JSON.stringify(settings, null, 2));
1337
1518
  return 0;
1338
1519
  }
@@ -1340,21 +1521,21 @@ async function settingsCommand(ctx, out, args) {
1340
1521
  }
1341
1522
  //#endregion
1342
1523
  //#region src/main.ts
1343
- const CLI_VERSION = "0.2.0";
1524
+ const CLI_VERSION = "0.5.0";
1344
1525
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
1345
1526
 
1346
1527
  Kullanım: steward <komut> [seçenekler]
1347
1528
 
1348
1529
  Komutlar:
1349
- dev [--product <kod>] [--catalog <dosya>] yerel steward (Docker) + .env.local
1350
- dev reset --yes yerel veritabanını ve kimlik dosyasını sıfırla
1351
1530
  doctor [--json] kurulum teşhisi (GET /v1/doctor)
1352
- catalog push <dosya> katalog senkronu (PUT /v1/admin/catalog)
1531
+ catalog push <dosya> [--yes] katalog senkronu (PUT /v1/admin/catalog)
1353
1532
  settings get | set [bayraklar] ürün ayarları (/v1/admin/settings)
1354
1533
  endpoints list | add | rotate | deactivate webhook endpoint'leri; sır yalnızca --out dosyasına
1534
+ meters get <ref> [--periods <n>] [--json] an account's meters (GET /v1/accounts/:ref/meters)
1535
+ events send <ref> <name> [--meta k=v]… send one event (POST /v1/events/ingest; local try-out)
1355
1536
 
1356
- Bağlantı: yönetim komutları STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY, doctor
1357
- STEWARD_URL + STEWARD_API_KEY (yoksa admin çifti). Ortamda bu dört değişkenden
1537
+ Bağlantı: yönetim komutları STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY, doctor,
1538
+ meters ve events STEWARD_URL + STEWARD_API_KEY (yoksa admin çifti). Ortamda bu dört değişkenden
1358
1539
  biri bile varsa hepsi (ve APP_URL) ortamdan okunur, ./.env.local hiç okunmaz;
1359
1540
  yoksa ./.env.local'den. Kullanılan kaynak stderr'e yazılır (bağlantı: …).
1360
1541
  Değişikliklerde X-Actor-Ref operator:<kullanıcı>. CLI sırları terminale yazmaz
@@ -1362,11 +1543,12 @@ ve kubectl çağırmaz.
1362
1543
 
1363
1544
  Ayrıntı: steward <komut> --help`;
1364
1545
  const COMMANDS = {
1365
- dev: devCommand,
1366
1546
  doctor: doctorCommand,
1367
1547
  catalog: catalogCommand,
1368
1548
  settings: settingsCommand,
1369
- endpoints: endpointsCommand
1549
+ endpoints: endpointsCommand,
1550
+ meters: metersCommand,
1551
+ events: eventsCommand
1370
1552
  };
1371
1553
  async function main(argv, ctx) {
1372
1554
  const out = createOutput(ctx.stdout, ctx.stderr);
@@ -1405,43 +1587,13 @@ async function main(argv, ctx) {
1405
1587
  }
1406
1588
  //#endregion
1407
1589
  //#region src/bin.ts
1408
- const run = (command, args, { cwd, capture = false }) => new Promise((resolve) => {
1409
- const child = spawn(command, [...args], {
1410
- cwd,
1411
- stdio: capture ? [
1412
- "ignore",
1413
- "pipe",
1414
- "pipe"
1415
- ] : [
1416
- "ignore",
1417
- 2,
1418
- 2
1419
- ]
1420
- });
1421
- let stdout = "";
1422
- let stderr = "";
1423
- child.stdout?.setEncoding("utf8").on("data", (chunk) => stdout += chunk);
1424
- child.stderr?.setEncoding("utf8").on("data", (chunk) => stderr += chunk);
1425
- child.on("error", (error) => resolve({
1426
- code: 127,
1427
- stdout,
1428
- stderr: error.message
1429
- }));
1430
- child.on("close", (code) => resolve({
1431
- code: code ?? 1,
1432
- stdout,
1433
- stderr
1434
- }));
1435
- });
1436
1590
  const ctx = {
1437
1591
  cwd: process.cwd(),
1438
1592
  env: process.env,
1439
1593
  stdout: process.stdout,
1440
1594
  stderr: process.stderr,
1441
1595
  fetch: globalThis.fetch,
1442
- run,
1443
1596
  sleep: (ms) => setTimeout(ms),
1444
- now: () => Date.now(),
1445
1597
  username: () => {
1446
1598
  try {
1447
1599
  return userInfo().username;
@@ -1449,13 +1601,20 @@ const ctx = {
1449
1601
  return process.env.USER ?? process.env.USERNAME ?? "";
1450
1602
  }
1451
1603
  },
1452
- platform: process.platform,
1453
- hostUser: () => typeof process.getuid === "function" && typeof process.getgid === "function" ? {
1454
- uid: process.getuid(),
1455
- gid: process.getgid()
1456
- } : null,
1457
1604
  typescript: Boolean(process.features.typescript),
1458
- importModule: (url) => import(url)
1605
+ importModule: (url) => import(url),
1606
+ prompt: async (question) => {
1607
+ if (!process.stdin.isTTY || !process.stderr.isTTY) return null;
1608
+ const terminal = createInterface({
1609
+ input: process.stdin,
1610
+ output: process.stderr
1611
+ });
1612
+ try {
1613
+ return await terminal.question(question);
1614
+ } finally {
1615
+ terminal.close();
1616
+ }
1617
+ }
1459
1618
  };
1460
1619
  process.exitCode = await main(process.argv.slice(2), ctx);
1461
1620
  //#endregion