@stewardhq/cli 0.3.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 +768 -651
  3. package/package.json +3 -3
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,167 +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
- /** Local mail catcher for billing emails (SMTP inside the compose network, web UI on the host). */
441
- const MAILPIT_IMAGE = "axllent/mailpit:v1.31.1";
442
- const MAILPIT_SERVICE = "mailpit";
443
- const MAILPIT_UI_PORT = 8025;
444
- const STATE_DIR = ".steward";
445
- const COMPOSE_FILE = `${STATE_DIR}/compose.yml`;
446
- const CREDENTIALS_FILE = `${STATE_DIR}/credentials.json`;
447
- /** Servisin ürettiği dev şifreleme anahtarı (kimlik dosyasının yanında). */
448
- const ENCRYPTION_KEY_FILE = `${STATE_DIR}/encryption-key`;
449
- const CONTAINER_STATE_DIR = "/steward-dev";
450
- const CONTAINER_PORT = 3002;
451
- const STEWARD_SERVICE = "steward";
452
- const PLACEHOLDER_TAG = "dev-unreleased";
453
- /** İmaj referansı: etiket ya da digest zorunlu, `latest` ve yer tutucu reddedilir. */
454
- function checkImage(image) {
455
- const value = image.trim();
456
- if (value === "" || /\s/.test(value)) throw new UsageError("--image: geçerli bir imaj referansı değil");
457
- if (value.includes("@sha256:")) return value;
458
- const lastSlash = value.lastIndexOf("/");
459
- const colon = value.lastIndexOf(":");
460
- const tag = colon > lastSlash ? value.slice(colon + 1) : "";
461
- 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)");
462
- if (tag === "") throw new UsageError(`--image: etiket ya da digest gerekli (latest kullanılmaz): ${value}`);
463
- if (/(^|-)latest$/.test(tag)) throw new UsageError(`--image: ${tag} kayan etiket; sabit bir etiket verin (AGENTS.md kural 4)`);
464
- return value;
465
- }
466
- function composeProjectName(projectDir, product) {
467
- const digest = createHash("sha256").update(projectDir).digest("hex").slice(0, 8);
468
- return `steward-dev-${product.replace(/_/g, "-")}-${digest}`;
469
- }
470
- /** Tırnaklı YAML skaleri; compose `$` yerleştirmesi kaçışlı. */
471
- const q = (value) => JSON.stringify(String(value).replace(/\$/g, "$$$$"));
472
- function localBaseUrl(port) {
473
- return `http://localhost:${port}`;
474
- }
475
- function composeFile(options) {
476
- const env = [
477
- ["STEWARD_DATABASE_URL", "postgres://steward:steward@db:5432/steward"],
478
- ["STEWARD_PUBLIC_URL", localBaseUrl(options.port)],
479
- ["STEWARD_DEV_PRODUCT", options.product],
480
- ["STEWARD_DEV_CREDENTIALS_FILE", `${CONTAINER_STATE_DIR}/credentials.json`],
481
- ["STEWARD_DEV_APP_URL", options.appUrl],
482
- ...options.webhookUrl !== void 0 ? [["STEWARD_DEV_WEBHOOK_URL", options.webhookUrl]] : [],
483
- ["STEWARD_SMTP_URL", `smtp://${MAILPIT_SERVICE}:1025`],
484
- ["STEWARD_EMAIL_FROM", "billing@steward.localhost"]
485
- ];
486
- return `${[
487
- "# steward dev tarafından üretildi — elle düzenlemeyin, her `steward dev` yeniden yazar.",
488
- "# Durdur: docker compose -f .steward/compose.yml down · Sıfırla: steward dev reset --yes",
489
- `name: ${q(composeProjectName(options.projectDir, options.product))}`,
490
- "services:",
491
- " db:",
492
- ` image: ${q(POSTGRES_IMAGE)}`,
493
- " environment:",
494
- ` POSTGRES_USER: ${q("steward")}`,
495
- ` POSTGRES_PASSWORD: ${q("steward")}`,
496
- ` POSTGRES_DB: ${q("steward")}`,
497
- " volumes:",
498
- ` - ${q("db:/var/lib/postgresql/data")}`,
499
- " healthcheck:",
500
- ` test: [${[
501
- "CMD",
502
- "pg_isready",
503
- "-h",
504
- "127.0.0.1",
505
- "-U",
506
- "steward",
507
- "-d",
508
- "steward"
509
- ].map(q).join(", ")}]`,
510
- ` interval: ${q("2s")}`,
511
- ` timeout: ${q("5s")}`,
512
- " retries: 30",
513
- ` ${STEWARD_SERVICE}:`,
514
- ` image: ${q(options.image)}`,
515
- ...options.user ? [` user: ${q(`${options.user.uid}:${options.user.gid}`)}`] : [],
516
- " depends_on:",
517
- " db:",
518
- " condition: service_healthy",
519
- ` ${MAILPIT_SERVICE}:`,
520
- " condition: service_started",
521
- " ports:",
522
- ` - ${q(`127.0.0.1:${options.port}:${CONTAINER_PORT}`)}`,
523
- " environment:",
524
- ...env.map(([key, value]) => ` ${key}: ${q(value)}`),
525
- " extra_hosts:",
526
- ` - ${q("host.docker.internal:host-gateway")}`,
527
- " volumes:",
528
- ` - ${q(`.:${CONTAINER_STATE_DIR}`)}`,
529
- ` ${MAILPIT_SERVICE}:`,
530
- ` image: ${q(MAILPIT_IMAGE)}`,
531
- " ports:",
532
- ` - ${q(`127.0.0.1:${options.mailPort ?? 8025}:${MAILPIT_UI_PORT}`)}`,
533
- "volumes:",
534
- " db: {}"
535
- ].join("\n")}\n`;
536
- }
537
- //#endregion
538
- //#region src/dev/credentials.ts
539
- const isString = (value) => typeof value === "string" && value !== "";
540
- const nullableString = (value) => value === null || isString(value);
541
- async function readCredentials(path) {
542
- let text;
543
- try {
544
- text = await readFile(path, "utf8");
545
- } catch (error) {
546
- return {
547
- ok: false,
548
- reason: errnoCode(error) === "ENOENT" ? "missing" : "unreadable"
549
- };
550
- }
551
- let data;
552
- try {
553
- data = JSON.parse(text);
554
- } catch {
555
- return {
556
- ok: false,
557
- reason: "invalid"
558
- };
559
- }
560
- if (typeof data !== "object" || data === null) return {
561
- ok: false,
562
- reason: "invalid"
563
- };
564
- const record = data;
565
- if (typeof record.version === "number" && record.version !== 1) return {
566
- ok: false,
567
- reason: "unsupported_version"
568
- };
569
- 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 {
570
- ok: false,
571
- reason: "invalid"
572
- };
573
- const safe = (value) => value === null || /^[A-Za-z0-9_\-+/=.]+$/.test(value);
574
- if (!safe(record.apiKey) || !safe(record.adminApiKey) || !safe(record.webhookSecret)) return {
575
- ok: false,
576
- reason: "invalid"
577
- };
578
- return {
579
- ok: true,
580
- credentials: record
581
- };
582
- }
583
- /** Başkalarınca okunabiliyorsa 0600'e indirir (en iyi çaba; dosya başkasınınsa sessizce geçer). */
584
- async function tightenMode(path) {
585
- if (process.platform === "win32") return;
586
- try {
587
- if (((await stat(path)).mode & 63) !== 0) await chmod(path, 384);
588
- } catch {}
589
- }
590
- const CREDENTIALS_PROBLEM = {
591
- missing: "kimlik dosyası henüz yok",
592
- unreadable: "kimlik dosyası okunamıyor (izin?)",
593
- invalid: "kimlik dosyası beklenen biçimde değil",
594
- unsupported_version: "kimlik dosyası sürümü bu CLI'da desteklenmiyor (CLI'ı güncelleyin)"
595
- };
596
700
  //#endregion
597
701
  //#region src/commands/doctor.ts
598
702
  const DOCTOR_USAGE = `Kullanım: steward doctor [--json]
@@ -609,7 +713,15 @@ yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
609
713
  Çıkış kodu: 0 hazır; 1 rapor ok değil (error önemde uyarı) ya da APP_URL
610
714
  steward'da izinli değil.
611
715
 
612
- --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)`;
613
725
  /** `APP_URL` (ürünün kendi adresi; checkout `successUrl`'i bundan kurulur) ↔ steward ayarları. */
614
726
  function appUrlWarnings(appUrl, report) {
615
727
  if (appUrl === void 0) return [];
@@ -635,6 +747,62 @@ function appUrlWarnings(appUrl, report) {
635
747
  }];
636
748
  return [];
637
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
+ }
638
806
  const MARK = {
639
807
  error: "✗",
640
808
  warning: "!",
@@ -658,7 +826,7 @@ function countBySeverity(warnings) {
658
826
  };
659
827
  }
660
828
  /** Tam insan okunur rapor. */
661
- function formatDoctorReport(report, cliWarnings) {
829
+ function formatDoctorReport(report, cliWarnings, metering = null) {
662
830
  const all = [...report.warnings, ...cliWarnings];
663
831
  const { errors, warnings } = countBySeverity(all);
664
832
  const ready = errors === 0;
@@ -691,6 +859,7 @@ function formatDoctorReport(report, cliWarnings) {
691
859
  const disabled = emails.disabledTemplates.length > 0 ? ` · disabled: ${emails.disabledTemplates.join(", ")}` : "";
692
860
  lines.push(`emails ${emails.ready ? "ready ✓" : `not sending ✗${problems.length > 0 ? ` (${problems.join(", ")})` : ""}`}${disabled}`);
693
861
  }
862
+ lines.push(...formatMetering(report, metering));
694
863
  for (const severity of SEVERITY_ORDER) {
695
864
  const items = all.filter((w) => w.severity === severity);
696
865
  if (items.length === 0) continue;
@@ -703,13 +872,6 @@ function formatDoctorReport(report, cliWarnings) {
703
872
  }
704
873
  return lines;
705
874
  }
706
- /** `steward dev` sonundaki kısa özet. */
707
- function formatDoctorSummary(report) {
708
- const { errors, warnings } = countBySeverity(report.warnings);
709
- const lines = [report.ok ? `doctor: hazır ✓ (${warnings} uyarı)` : `doctor: ${errors} hata, ${warnings} uyarı`];
710
- 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}`);
711
- return lines;
712
- }
713
875
  async function doctorCommand(ctx, out, args) {
714
876
  const { values, positionals } = parse(args, {
715
877
  ...HELP_OPTION,
@@ -725,356 +887,20 @@ async function doctorCommand(ctx, out, args) {
725
887
  const appUrl = env.get("APP_URL");
726
888
  out.err(connectionLine(target));
727
889
  if (appUrl === void 0) out.err(`APP_URL tanımlı değil (${env.source}): steward appUrl karşılaştırması atlandı`);
728
- const report = await callSteward(target, () => clientFor(ctx, target).doctor());
890
+ const steward = clientFor(ctx, target);
891
+ const report = await callSteward(target, () => steward.doctor());
729
892
  const cliWarnings = appUrlWarnings(appUrl, report);
730
893
  const failed = !report.ok || cliWarnings.some((w) => w.severity === "error");
894
+ const metering = await meteringSummary(steward);
731
895
  if (values.json) out.out(JSON.stringify({
732
896
  ...report,
733
- cliWarnings
897
+ cliWarnings,
898
+ ...metering !== null ? { cliMetering: metering } : {}
734
899
  }, null, 2));
735
- else for (const line of formatDoctorReport(report, cliWarnings)) out.out(line);
900
+ else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
736
901
  return failed ? 1 : 0;
737
902
  }
738
903
  //#endregion
739
- //#region src/commands/dev.ts
740
- const DEV_USAGE = `Kullanım:
741
- steward dev [--product <kod>] [--catalog <dosya>] [--port 3002] [--app-url <url>]
742
- [--webhook-url <url>] [--mail-port 8025] [--image <imaj>] [--timeout <sn>]
743
- steward dev reset --yes
744
-
745
- Yerel steward: dev imajı + Postgres (Docker compose, yalnızca 127.0.0.1), sahte
746
- ödeme sağlayıcısı; hosted checkout ve portal http://localhost:<port>/public altında.
747
- Billing emails are caught by Mailpit: http://localhost:<mail-port>.
748
-
749
- 1. .steward/compose.yml yazılır, .steward/ .gitignore'a eklenir (yoksa)
750
- 2. docker compose -f .steward/compose.yml up -d, /health beklenir
751
- 3. servis ürünü ve anahtarları oluşturur; .steward/credentials.json okunur
752
- 4. .env.local'e STEWARD_URL, STEWARD_ADMIN_URL, STEWARD_API_KEY,
753
- STEWARD_ADMIN_API_KEY (+ STEWARD_WEBHOOK_SECRET) yazılır — değerler
754
- terminale yazılmaz, diğer satırlar korunur; --webhook-url verilmezse
755
- önceki koşunun STEWARD_WEBHOOK_SECRET satırı silinir
756
- 5. --catalog verilmişse katalog senkronlanır; doctor özeti
757
-
758
- --product <kod> ürün kodu (varsayılan: package.json adından)
759
- --catalog <dosya> katalog (.ts/.mjs/.js/.json; bkz. steward catalog push)
760
- --port <n> host portu (varsayılan 3002)
761
- --app-url <url> ürünün yerel adresi (varsayılan http://localhost:3000)
762
- --webhook-url <url> webhook alıcısı, ör. http://host.docker.internal:3000/api/billing/events
763
- --mail-port <n> host port of the Mailpit web UI (default 8025)
764
- --image <imaj> dev imajı. İlk dev imajı yayınına kadar ZORUNLU (varsayılan
765
- etiket yer tutucu): ghcr.io/z9cloud/steward:dev-<etiket> ya da
766
- steward reposunda docker build --target dev -t steward-dev:local .
767
- → --image steward-dev:local
768
- --timeout <sn> hazır olma beklemesi (varsayılan 180)
769
-
770
- dev reset --yes: compose'u durdurur, veritabanı volume'ünü (docker compose down -v),
771
- kimlik dosyasını ve servisin dev şifreleme anahtarını (.steward/encryption-key) siler.
772
- .env.local'deki anahtarlar geçersiz kalır; sonraki steward dev yenilerini yazar.`;
773
- const DEV_OPTIONS = {
774
- ...HELP_OPTION,
775
- product: { type: "string" },
776
- catalog: { type: "string" },
777
- port: { type: "string" },
778
- "app-url": { type: "string" },
779
- "webhook-url": { type: "string" },
780
- "mail-port": { type: "string" },
781
- image: { type: "string" },
782
- timeout: { type: "string" }
783
- };
784
- const PRODUCT_CODE = /^[a-z][a-z0-9_]{0,62}$/;
785
- const WEBHOOK_SECRET_KEY = "STEWARD_WEBHOOK_SECRET";
786
- const GITIGNORE_ENTRIES = /* @__PURE__ */ new Set([
787
- ".steward",
788
- ".steward/",
789
- "/.steward",
790
- "/.steward/",
791
- ".steward/*",
792
- "/.steward/*"
793
- ]);
794
- /**
795
- Servis kimlik dosyasını `serve`'den önce yazar: /health yanıt verdiğinde dosya hazırdır. Yine de
796
- (yeniden başlatma, yavaş dosya sistemi) kısa bir süre tekrar okunur; sonra açık hata.
797
- */
798
- const CREDENTIALS_GRACE_MS = 15e3;
799
- /** Paket adı ya da klasör adından ürün kodu (`@acme/Web-App` → `web_app`). */
800
- function toProductCode(value) {
801
- if (value === void 0) return null;
802
- const code = value.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^[^a-z]+/, "").replace(/_+$/, "").slice(0, 63);
803
- return PRODUCT_CODE.test(code) ? code : null;
804
- }
805
- async function inferProductCode(cwd) {
806
- try {
807
- const pkg = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
808
- const code = toProductCode(typeof pkg.name === "string" ? pkg.name : void 0);
809
- if (code !== null) return {
810
- code,
811
- from: "package.json adı"
812
- };
813
- } catch {}
814
- const code = toProductCode(basename(cwd));
815
- return code !== null ? {
816
- code,
817
- from: "klasör adı"
818
- } : {
819
- code: "dev",
820
- from: "varsayılan"
821
- };
822
- }
823
- async function exists(path) {
824
- try {
825
- await stat(path);
826
- return true;
827
- } catch (error) {
828
- if (errnoCode(error) === "ENOENT") return false;
829
- throw error;
830
- }
831
- }
832
- async function ensureDockerCompose(ctx) {
833
- if ((await ctx.run("docker", ["compose", "version"], {
834
- cwd: ctx.cwd,
835
- capture: true
836
- })).code !== 0) throw new CliError("docker compose bulunamadı ya da Docker çalışmıyor (Docker Desktop / OrbStack açık mı?)");
837
- }
838
- /** `.steward/` .gitignore'da değilse ekler (dosya yoksa oluşturur). Eklendiyse true. */
839
- async function ensureGitignored(cwd) {
840
- const path = join(cwd, ".gitignore");
841
- let text = "";
842
- try {
843
- text = await readFile(path, "utf8");
844
- } catch (error) {
845
- if (errnoCode(error) !== "ENOENT") throw error;
846
- }
847
- if (text.split(/\r?\n/).some((line) => GITIGNORE_ENTRIES.has(line.trim()))) return false;
848
- const eol = text.includes("\r\n") ? "\r\n" : "\n";
849
- const prefix = text === "" ? "" : text.endsWith("\n") ? eol : `${eol}${eol}`;
850
- await writeFile(path, `${text}${prefix}# steward dev (yerel veritabanı ve kimlik bilgileri)${eol}${STATE_DIR}/${eol}`);
851
- return true;
852
- }
853
- async function waitForHealth(ctx, baseUrl, deadline, timeoutSeconds) {
854
- let last = "bağlantı yok";
855
- for (let attempt = 1;; attempt++) {
856
- try {
857
- const res = await ctx.fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(2e3) });
858
- if (res.ok) {
859
- const body = await res.json().catch(() => null);
860
- return { env: typeof body?.env === "string" ? body.env : null };
861
- }
862
- last = `HTTP ${res.status}`;
863
- } catch {
864
- last = "bağlantı yok";
865
- }
866
- 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}`);
867
- if (attempt % 5 === 0) {
868
- const ps = await ctx.run("docker", [
869
- "compose",
870
- "-f",
871
- COMPOSE_FILE,
872
- "ps",
873
- "--status",
874
- "running",
875
- "--services"
876
- ], {
877
- cwd: ctx.cwd,
878
- capture: true
879
- });
880
- 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}`);
881
- }
882
- await ctx.sleep(1e3);
883
- }
884
- }
885
- /** Anahtarlar bu steward'da geçerli ve beklenen ürün/kapsamda mı; sorun varsa açıklaması. */
886
- async function verifyKeys(ctx, baseUrl, credentials) {
887
- const keys = [{
888
- apiKey: credentials.apiKey,
889
- scope: "product",
890
- label: "ürün anahtarı"
891
- }, {
892
- apiKey: credentials.adminApiKey,
893
- scope: "admin",
894
- label: "admin anahtarı"
895
- }];
896
- for (const key of keys) try {
897
- const me = await clientFor(ctx, {
898
- url: baseUrl,
899
- apiKey: key.apiKey
900
- }, { retries: false }).me();
901
- if (me.product !== credentials.product) return `kimlik dosyasındaki ${key.label} başka bir ürünün (${me.product})`;
902
- if (me.scope !== key.scope) return `kimlik dosyasındaki ${key.label} kapsamı beklenen değil (${me.scope})`;
903
- } catch (error) {
904
- 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)`;
905
- if (error instanceof StewardError) return describeStewardError(error, { url: baseUrl });
906
- throw error;
907
- }
908
- return null;
909
- }
910
- async function waitForCredentials(ctx, options) {
911
- const giveUpAt = Math.min(options.deadline, ctx.now() + CREDENTIALS_GRACE_MS);
912
- for (;;) {
913
- const read = await readCredentials(options.path);
914
- let problem;
915
- if (read.ok) {
916
- const { credentials } = read;
917
- 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);
918
- if (invalid === null) {
919
- await tightenMode(options.path);
920
- return credentials;
921
- }
922
- problem = invalid;
923
- } else {
924
- if (read.reason === "unsupported_version") throw new CliError(CREDENTIALS_PROBLEM.unsupported_version);
925
- problem = read.reason === "missing" ? `${CREDENTIALS_PROBLEM.missing} (imaj dev sağlamayı destekliyor mu? ghcr.io/z9cloud/steward:dev-<etiket>)` : CREDENTIALS_PROBLEM[read.reason];
926
- }
927
- if (ctx.now() >= giveUpAt) throw new CliError(`steward kimlik bilgileri alınamadı: ${problem}. Loglar: docker compose -f ${COMPOSE_FILE} logs ${STEWARD_SERVICE}`);
928
- await ctx.sleep(1e3);
929
- }
930
- }
931
- /** `.env.local` gitignore'da değilse uyarır (git yoksa ya da repo değilse sessiz). */
932
- async function warnIfEnvLocalTracked(ctx, out) {
933
- if ((await ctx.run("git", [
934
- "check-ignore",
935
- "-q",
936
- ".env.local"
937
- ], {
938
- cwd: ctx.cwd,
939
- capture: true
940
- })).code === 1) out.err(`! ${ENV_LOCAL} .gitignore'da değil: anahtarlar içerir, commit'lenmemeli (ör. .gitignore'a \`.env*.local\` ekleyin)`);
941
- }
942
- async function devCommand(ctx, out, args) {
943
- if (args[0] === "reset") return devReset(ctx, out, args.slice(1));
944
- const { values, positionals } = parse(args, DEV_OPTIONS, "dev");
945
- if (values.help) {
946
- out.out(DEV_USAGE);
947
- return 0;
948
- }
949
- if (positionals.length > 0) throw new UsageError(`bilinmeyen alt komut: dev ${positionals[0]} (ayrıntı: steward dev --help)`);
950
- let product;
951
- if (values.product !== void 0) {
952
- product = values.product.trim();
953
- if (!PRODUCT_CODE.test(product)) throw new UsageError("--product: küçük harf, rakam ve _ (harfle başlar, en çok 63)");
954
- } else {
955
- const inferred = await inferProductCode(ctx.cwd);
956
- product = inferred.code;
957
- out.err(`ürün kodu: ${product} (${inferred.from}; değiştirmek için --product)`);
958
- }
959
- const port = parsePositiveInt(values.port ?? "3002", "--port", { max: 65535 });
960
- const mailPort = parsePositiveInt(values["mail-port"] ?? String(8025), "--mail-port", { max: 65535 });
961
- const appUrl = parseHttpUrl(values["app-url"] ?? "http://localhost:3000", "--app-url");
962
- const webhookUrl = values["webhook-url"] !== void 0 ? parseHttpUrl(values["webhook-url"], "--webhook-url") : void 0;
963
- const image = checkImage(values.image ?? "ghcr.io/z9cloud/steward:dev-unreleased");
964
- const timeoutSeconds = parsePositiveInt(values.timeout ?? "180", "--timeout", { max: 3600 });
965
- let catalog = null;
966
- if (values.catalog !== void 0) catalog = await loadCatalogFile(ctx, values.catalog);
967
- const baseUrl = localBaseUrl(port);
968
- await ensureDockerCompose(ctx);
969
- const stateDir = join(ctx.cwd, STATE_DIR);
970
- await mkdir(stateDir, {
971
- recursive: true,
972
- mode: 448
973
- });
974
- await writeFile(join(ctx.cwd, COMPOSE_FILE), composeFile({
975
- projectDir: resolve(ctx.cwd),
976
- product,
977
- port,
978
- mailPort,
979
- appUrl,
980
- ...webhookUrl !== void 0 ? { webhookUrl } : {},
981
- image,
982
- user: ctx.platform === "linux" ? ctx.hostUser() : null
983
- }));
984
- if (await ensureGitignored(ctx.cwd)) out.err(`.gitignore'a ${STATE_DIR}/ eklendi (yerel veritabanı ve kimlik bilgileri)`);
985
- await warnIfEnvLocalTracked(ctx, out);
986
- out.err(`steward başlatılıyor (${image}) → ${baseUrl}`);
987
- const up = await ctx.run("docker", [
988
- "compose",
989
- "-f",
990
- COMPOSE_FILE,
991
- "up",
992
- "-d"
993
- ], { cwd: ctx.cwd });
994
- if (up.code !== 0) throw new CliError(`docker compose up failed (exit ${up.code}); port ${port} or ${mailPort} may be in use (--port, --mail-port)`);
995
- const deadline = ctx.now() + timeoutSeconds * 1e3;
996
- const health = await waitForHealth(ctx, baseUrl, deadline, timeoutSeconds);
997
- if (health.env === "production") throw new CliError(`${image} üretim imajı (env: production): dev imajı verin (ghcr.io/z9cloud/steward:dev-<etiket>)`);
998
- const credentials = await waitForCredentials(ctx, {
999
- path: join(ctx.cwd, CREDENTIALS_FILE),
1000
- product,
1001
- baseUrl,
1002
- deadline
1003
- });
1004
- const entries = [
1005
- ["STEWARD_URL", baseUrl],
1006
- ["STEWARD_ADMIN_URL", baseUrl],
1007
- ["STEWARD_API_KEY", credentials.apiKey],
1008
- ["STEWARD_ADMIN_API_KEY", credentials.adminApiKey],
1009
- ...credentials.webhookSecret !== null ? [[WEBHOOK_SECRET_KEY, credentials.webhookSecret]] : []
1010
- ];
1011
- const remove = credentials.webhookSecret === null ? [WEBHOOK_SECRET_KEY] : [];
1012
- const env = await upsertDotenvFile(join(ctx.cwd, ENV_LOCAL), entries, remove);
1013
- const written = entries.map(([key]) => key).filter((key) => env.added.includes(key) || env.updated.includes(key));
1014
- const removed = env.removed.length > 0 ? `; kaldırıldı: ${env.removed.join(", ")} (webhook endpoint'i yok)` : "";
1015
- if (env.created) out.err(`${ENV_LOCAL} oluşturuldu (0600): ${written.join(", ")} (değerler yazdırılmaz)`);
1016
- else if (written.length > 0 || removed !== "") {
1017
- const changed = written.length > 0 ? written.join(", ") : "değer değişmedi";
1018
- out.err(`${ENV_LOCAL} güncellendi: ${changed}${removed} (değerler yazdırılmaz; diğer satırlar korundu)`);
1019
- } else out.err(`${ENV_LOCAL} güncel: ${env.unchanged.join(", ")}`);
1020
- if (env.looseMode) out.err(`! ${ENV_LOCAL} başka kullanıcılarca okunabilir: chmod 600 ${ENV_LOCAL}`);
1021
- if (credentials.webhookSecret === null) out.err("webhook endpoint'i yok (laptop'a webhook gelmez); gerekirse --webhook-url http://host.docker.internal:<port>/<yol>");
1022
- let exitCode = 0;
1023
- if (catalog !== null) {
1024
- const pushed = await pushCatalog(ctx, {
1025
- url: baseUrl,
1026
- apiKey: credentials.adminApiKey
1027
- }, catalog);
1028
- for (const line of pushed.lines) out.err(line);
1029
- if (pushed.providerErrors > 0) exitCode = 1;
1030
- }
1031
- const target = {
1032
- url: baseUrl,
1033
- apiKey: credentials.apiKey
1034
- };
1035
- const report = await callSteward(target, () => clientFor(ctx, target).doctor());
1036
- for (const line of formatDoctorSummary(report)) out.err(line);
1037
- out.out(`steward dev hazır: ${baseUrl} (ürün ${product}${health.env !== null ? `, env ${health.env}` : ""})`);
1038
- out.out(` hosted checkout/portal: ${baseUrl}/public/… · uygulamanızı başlatın (ör. pnpm dev)`);
1039
- out.out(` billing emails (Mailpit): http://localhost:${mailPort}`);
1040
- out.out(` durdur: docker compose -f ${COMPOSE_FILE} down · sıfırla: steward dev reset --yes`);
1041
- return exitCode;
1042
- }
1043
- async function devReset(ctx, out, args) {
1044
- const { values, positionals } = parse(args, {
1045
- ...HELP_OPTION,
1046
- yes: { type: "boolean" }
1047
- }, "dev");
1048
- if (values.help) {
1049
- out.out(DEV_USAGE);
1050
- return 0;
1051
- }
1052
- expectPositionals(positionals, 0, 0, "dev");
1053
- 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`);
1054
- const files = [CREDENTIALS_FILE, ENCRYPTION_KEY_FILE];
1055
- if (await exists(join(ctx.cwd, COMPOSE_FILE))) {
1056
- await ensureDockerCompose(ctx);
1057
- const down = await ctx.run("docker", [
1058
- "compose",
1059
- "-f",
1060
- COMPOSE_FILE,
1061
- "down",
1062
- "-v",
1063
- "--remove-orphans"
1064
- ], { cwd: ctx.cwd });
1065
- if (down.code !== 0) throw new CliError(`docker compose down başarısız (çıkış ${down.code}); dosyalar silinmedi`);
1066
- } else {
1067
- const leftovers = [];
1068
- for (const file of files) if (await exists(join(ctx.cwd, file))) leftovers.push(file);
1069
- 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.`);
1070
- out.out("sıfırlanacak yerel steward yok");
1071
- return 0;
1072
- }
1073
- for (const file of files) await rm(join(ctx.cwd, file), { force: true });
1074
- 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.`);
1075
- return 0;
1076
- }
1077
- //#endregion
1078
904
  //#region src/secret-file.ts
1079
905
  async function withSecretFile(cwd, out, secret, options, action) {
1080
906
  const target = resolve(cwd, out);
@@ -1270,6 +1096,276 @@ function secretNotice(out, path, fallback, next) {
1270
1096
  out.err(next);
1271
1097
  }
1272
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
1273
1369
  //#region src/commands/settings.ts
1274
1370
  const SETTINGS_USAGE = `Kullanım:
1275
1371
  steward settings get
@@ -1277,6 +1373,10 @@ const SETTINGS_USAGE = `Kullanım:
1277
1373
  [--branding <json>] [--default-locale tr|en]
1278
1374
  [--checkout-ttl <dakika>] [--portal-ttl <dakika>]
1279
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>]
1280
1380
 
1281
1381
  Ürün ayarları (GET/PATCH /v1/admin/settings). Verilmeyen alan değişmez; boş değer
1282
1382
  (--privacy-url "") alanı temizler, --branding null markayı temizler, --branding
@@ -1285,6 +1385,18 @@ temizleyin). --extra-return-origins "" listeyi boşaltır.
1285
1385
  --emails '{"billingPath":"/{LOCALE}/billing","templates":{"invoice_issued":{"enabled":false}}}'
1286
1386
  sets billing emails (sender: from.name, from.address; templates merge per
1287
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.
1288
1400
 
1289
1401
  Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
1290
1402
  const SET_OPTIONS = {
@@ -1297,7 +1409,13 @@ const SET_OPTIONS = {
1297
1409
  "checkout-ttl": { type: "string" },
1298
1410
  "portal-ttl": { type: "string" },
1299
1411
  "extra-return-origins": { type: "string" },
1300
- emails: { 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" }
1301
1419
  };
1302
1420
  const orNull = (value) => value.trim() === "" ? null : value.trim();
1303
1421
  /** Bayraklardan yama; sözleşme şemasıyla doğrulanır (geçersizse istek gönderilmez). */
@@ -1338,6 +1456,26 @@ function buildSettingsPatch(values) {
1338
1456
  if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
1339
1457
  if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
1340
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 }) };
1341
1479
  if (Object.keys(patch).length === 0) throw new UsageError(`en az bir ayar bayrağı gerekli (ayrıntı: steward settings --help)`);
1342
1480
  const parsed = ProductSettingsPatchSchema.safeParse(patch);
1343
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")}`);
@@ -1375,6 +1513,7 @@ async function settingsCommand(ctx, out, args) {
1375
1513
  out.err(connectionLine(target));
1376
1514
  const settings = await callSteward(target, () => clientFor(ctx, target).admin.settings.update(patch));
1377
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");
1378
1517
  out.out(JSON.stringify(settings, null, 2));
1379
1518
  return 0;
1380
1519
  }
@@ -1382,21 +1521,21 @@ async function settingsCommand(ctx, out, args) {
1382
1521
  }
1383
1522
  //#endregion
1384
1523
  //#region src/main.ts
1385
- const CLI_VERSION = "0.3.0";
1524
+ const CLI_VERSION = "0.5.0";
1386
1525
  const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
1387
1526
 
1388
1527
  Kullanım: steward <komut> [seçenekler]
1389
1528
 
1390
1529
  Komutlar:
1391
- dev [--product <kod>] [--catalog <dosya>] yerel steward (Docker) + .env.local
1392
- dev reset --yes yerel veritabanını ve kimlik dosyasını sıfırla
1393
1530
  doctor [--json] kurulum teşhisi (GET /v1/doctor)
1394
- catalog push <dosya> katalog senkronu (PUT /v1/admin/catalog)
1531
+ catalog push <dosya> [--yes] katalog senkronu (PUT /v1/admin/catalog)
1395
1532
  settings get | set [bayraklar] ürün ayarları (/v1/admin/settings)
1396
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)
1397
1536
 
1398
- Bağlantı: yönetim komutları STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY, doctor
1399
- 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
1400
1539
  biri bile varsa hepsi (ve APP_URL) ortamdan okunur, ./.env.local hiç okunmaz;
1401
1540
  yoksa ./.env.local'den. Kullanılan kaynak stderr'e yazılır (bağlantı: …).
1402
1541
  Değişikliklerde X-Actor-Ref operator:<kullanıcı>. CLI sırları terminale yazmaz
@@ -1404,11 +1543,12 @@ ve kubectl çağırmaz.
1404
1543
 
1405
1544
  Ayrıntı: steward <komut> --help`;
1406
1545
  const COMMANDS = {
1407
- dev: devCommand,
1408
1546
  doctor: doctorCommand,
1409
1547
  catalog: catalogCommand,
1410
1548
  settings: settingsCommand,
1411
- endpoints: endpointsCommand
1549
+ endpoints: endpointsCommand,
1550
+ meters: metersCommand,
1551
+ events: eventsCommand
1412
1552
  };
1413
1553
  async function main(argv, ctx) {
1414
1554
  const out = createOutput(ctx.stdout, ctx.stderr);
@@ -1447,43 +1587,13 @@ async function main(argv, ctx) {
1447
1587
  }
1448
1588
  //#endregion
1449
1589
  //#region src/bin.ts
1450
- const run = (command, args, { cwd, capture = false }) => new Promise((resolve) => {
1451
- const child = spawn(command, [...args], {
1452
- cwd,
1453
- stdio: capture ? [
1454
- "ignore",
1455
- "pipe",
1456
- "pipe"
1457
- ] : [
1458
- "ignore",
1459
- 2,
1460
- 2
1461
- ]
1462
- });
1463
- let stdout = "";
1464
- let stderr = "";
1465
- child.stdout?.setEncoding("utf8").on("data", (chunk) => stdout += chunk);
1466
- child.stderr?.setEncoding("utf8").on("data", (chunk) => stderr += chunk);
1467
- child.on("error", (error) => resolve({
1468
- code: 127,
1469
- stdout,
1470
- stderr: error.message
1471
- }));
1472
- child.on("close", (code) => resolve({
1473
- code: code ?? 1,
1474
- stdout,
1475
- stderr
1476
- }));
1477
- });
1478
1590
  const ctx = {
1479
1591
  cwd: process.cwd(),
1480
1592
  env: process.env,
1481
1593
  stdout: process.stdout,
1482
1594
  stderr: process.stderr,
1483
1595
  fetch: globalThis.fetch,
1484
- run,
1485
1596
  sleep: (ms) => setTimeout(ms),
1486
- now: () => Date.now(),
1487
1597
  username: () => {
1488
1598
  try {
1489
1599
  return userInfo().username;
@@ -1491,13 +1601,20 @@ const ctx = {
1491
1601
  return process.env.USER ?? process.env.USERNAME ?? "";
1492
1602
  }
1493
1603
  },
1494
- platform: process.platform,
1495
- hostUser: () => typeof process.getuid === "function" && typeof process.getgid === "function" ? {
1496
- uid: process.getuid(),
1497
- gid: process.getgid()
1498
- } : null,
1499
1604
  typescript: Boolean(process.features.typescript),
1500
- 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
+ }
1501
1618
  };
1502
1619
  process.exitCode = await main(process.argv.slice(2), ctx);
1503
1620
  //#endregion