@stewardhq/cli 0.6.0 → 0.7.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.
- package/README.md +19 -4
- package/dist/bin.js +1018 -444
- package/package.json +2 -2
package/dist/bin.js
CHANGED
|
@@ -2,12 +2,12 @@
|
|
|
2
2
|
import { userInfo } from "node:os";
|
|
3
3
|
import { createInterface } from "node:readline/promises";
|
|
4
4
|
import { setTimeout } from "node:timers/promises";
|
|
5
|
-
import { CatalogSyncInputSchema, EventsIngestInputSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
|
|
5
|
+
import { ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CreditAdjustmentInputSchema, DunningPolicySchema, EventsIngestInputSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
|
|
6
6
|
import { parseArgs } from "node:util";
|
|
7
|
-
import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
8
7
|
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
9
|
-
import {
|
|
8
|
+
import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
10
9
|
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { pathToFileURL } from "node:url";
|
|
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_***`). */
|
|
@@ -106,67 +106,6 @@ function parseBoolean(value, flag) {
|
|
|
106
106
|
throw new UsageError(`${flag}: must be true or false`);
|
|
107
107
|
}
|
|
108
108
|
//#endregion
|
|
109
|
-
//#region src/catalog-file.ts
|
|
110
|
-
const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
111
|
-
".js",
|
|
112
|
-
".mjs",
|
|
113
|
-
".cjs"
|
|
114
|
-
]);
|
|
115
|
-
const TS_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
116
|
-
".ts",
|
|
117
|
-
".mts",
|
|
118
|
-
".cts"
|
|
119
|
-
]);
|
|
120
|
-
const hasSyncInput = (value) => typeof value === "object" && value !== null && typeof value.toSyncInput === "function";
|
|
121
|
-
function pickExport(mod, file) {
|
|
122
|
-
if (mod.catalog !== void 0) return mod.catalog;
|
|
123
|
-
if (mod.default !== void 0) return mod.default;
|
|
124
|
-
const candidates = Object.values(mod).filter(hasSyncInput);
|
|
125
|
-
if (candidates.length === 1) return candidates[0];
|
|
126
|
-
throw new CliError(`${file}: katalog bulunamadı — \`export const catalog = defineCatalog(…)\` ya da default export bekleniyor`);
|
|
127
|
-
}
|
|
128
|
-
async function loadCatalogFile(ctx, file) {
|
|
129
|
-
const path = resolve(ctx.cwd, file);
|
|
130
|
-
const ext = extname(path).toLowerCase();
|
|
131
|
-
let exported;
|
|
132
|
-
if (ext === ".json") {
|
|
133
|
-
let text;
|
|
134
|
-
try {
|
|
135
|
-
text = await readFile(path, "utf8");
|
|
136
|
-
} catch (error) {
|
|
137
|
-
throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
|
|
138
|
-
}
|
|
139
|
-
try {
|
|
140
|
-
exported = JSON.parse(text);
|
|
141
|
-
} catch {
|
|
142
|
-
throw new CliError(`${file}: geçerli JSON değil`);
|
|
143
|
-
}
|
|
144
|
-
} else if (MODULE_EXTENSIONS.has(ext) || TS_EXTENSIONS.has(ext)) {
|
|
145
|
-
if (TS_EXTENSIONS.has(ext) && !ctx.typescript) throw new CliError(`${file}: bu Node sürümü TypeScript dosyasını doğrudan yükleyemiyor (${process.version}). Node ≥ 22.18 kullanın, \`NODE_OPTIONS=--experimental-strip-types\` verin ya da kataloğu .mjs/.json olarak dışa aktarın.`);
|
|
146
|
-
let mod;
|
|
147
|
-
try {
|
|
148
|
-
await readFile(path);
|
|
149
|
-
} catch (error) {
|
|
150
|
-
throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
|
|
151
|
-
}
|
|
152
|
-
try {
|
|
153
|
-
mod = await ctx.importModule(pathToFileURL(path).href);
|
|
154
|
-
} catch (error) {
|
|
155
|
-
throw new CliError(`${file} yüklenemedi: ${error instanceof Error ? error.message : String(error)}`);
|
|
156
|
-
}
|
|
157
|
-
exported = pickExport(mod, file);
|
|
158
|
-
} else throw new UsageError(`katalog dosyası .ts, .mts, .js, .mjs, .cjs ya da .json olmalı: ${file}`);
|
|
159
|
-
let input;
|
|
160
|
-
try {
|
|
161
|
-
input = hasSyncInput(exported) ? exported.toSyncInput() : exported;
|
|
162
|
-
} catch (error) {
|
|
163
|
-
throw new CliError(`${file}: toSyncInput() hata verdi: ${error instanceof Error ? error.message : String(error)}`);
|
|
164
|
-
}
|
|
165
|
-
const parsed = CatalogSyncInputSchema.safeParse(input);
|
|
166
|
-
if (!parsed.success) throw new CliError(`${file}: katalog geçersiz (istek gönderilmedi)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n")}`);
|
|
167
|
-
return input;
|
|
168
|
-
}
|
|
169
|
-
//#endregion
|
|
170
109
|
//#region src/catalog-diff.ts
|
|
171
110
|
/** A catalog that defines benefits needs a steward with the `benefits` capability (M27). */
|
|
172
111
|
function definesBenefits(input) {
|
|
@@ -410,6 +349,18 @@ function priceChangeCount(diff) {
|
|
|
410
349
|
return diff.prices.changed.length + diff.meteredPrices.changed.length;
|
|
411
350
|
}
|
|
412
351
|
//#endregion
|
|
352
|
+
//#region src/confirm.ts
|
|
353
|
+
/**
|
|
354
|
+
* Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
|
|
355
|
+
* terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
|
|
356
|
+
*/
|
|
357
|
+
async function confirm(ctx, question, options) {
|
|
358
|
+
if (options.yes) return true;
|
|
359
|
+
const answer = await ctx.prompt(`${question} [y/N] `);
|
|
360
|
+
if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
|
|
361
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
362
|
+
}
|
|
363
|
+
//#endregion
|
|
413
364
|
//#region src/dotenv.ts
|
|
414
365
|
const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
|
|
415
366
|
function unquote(rest) {
|
|
@@ -496,7 +447,7 @@ function whereMissing(env) {
|
|
|
496
447
|
case "missing": return `tanımlı değil (ortam değişkeni ya da ./${ENV_LOCAL}; dosya yok)`;
|
|
497
448
|
}
|
|
498
449
|
}
|
|
499
|
-
const ADMIN_HINT = "
|
|
450
|
+
const ADMIN_HINT = "Set them as environment variables or in ./.env.local. Admin: STEWARD_ADMIN_URL=https://billing.zone9.cloud once /v1 is exposed (docs/runbook.md), or a port-forward (http://localhost:13002), which is also the only way to register a cluster-internal (*.svc.cluster.local) webhook endpoint; the admin key comes from the operator Secret as an environment variable.";
|
|
500
451
|
function pairError(names, missing, env) {
|
|
501
452
|
return new CliError(`${names.url} + ${names.key} gerekli: ${missing.join(" ve ")} ${whereMissing(env)}.\n${ADMIN_HINT}`);
|
|
502
453
|
}
|
|
@@ -577,150 +528,708 @@ function describeStewardError(error, target) {
|
|
|
577
528
|
return `steward yanıtı sözleşmeye uymuyor${where}: ${error.code} (HTTP ${error.httpStatus}) — CLI ile steward sürümleri uyumsuz olabilir${request}`;
|
|
578
529
|
}
|
|
579
530
|
//#endregion
|
|
580
|
-
//#region src/
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
(
|
|
586
|
-
(
|
|
587
|
-
|
|
588
|
-
|
|
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
|
-
|
|
603
|
-
Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).
|
|
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"
|
|
531
|
+
//#region src/secret-file.ts
|
|
532
|
+
async function withSecretFile(cwd, out, secret, options, action) {
|
|
533
|
+
const target = resolve(cwd, out);
|
|
534
|
+
try {
|
|
535
|
+
if ((await lstat(target)).isDirectory()) throw new CliError(`--out bir klasör: ${out}`);
|
|
536
|
+
if (!options.force) throw new CliError(`${out} zaten var; üzerine yazmak için --force (istek gönderilmedi)`);
|
|
537
|
+
} catch (error) {
|
|
538
|
+
if (error instanceof CliError) throw error;
|
|
539
|
+
if (errnoCode(error) !== "ENOENT") throw error;
|
|
611
540
|
}
|
|
612
|
-
};
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
const lines = [`katalog senkronlandı → ${originOf(target.url)}`];
|
|
623
|
-
lines.push(` sürüm ${version}`);
|
|
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}`);
|
|
625
|
-
if (result.unchanged) lines.push(" değişiklik yok");
|
|
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}`);
|
|
541
|
+
const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
|
|
542
|
+
try {
|
|
543
|
+
await writeFile(temp, secret, {
|
|
544
|
+
mode: 384,
|
|
545
|
+
flag: "wx"
|
|
546
|
+
});
|
|
547
|
+
} catch (error) {
|
|
548
|
+
const code = errnoCode(error);
|
|
549
|
+
if (code === "ENOENT") throw new CliError(`--out klasörü yok: ${relative(cwd, dirname(target)) || "."}`);
|
|
550
|
+
throw new CliError(`sır dosyası yazılamadı (${code ?? "hata"}): ${out} (istek gönderilmedi)`);
|
|
641
551
|
}
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
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;
|
|
552
|
+
let value;
|
|
553
|
+
try {
|
|
554
|
+
value = await action();
|
|
555
|
+
} catch (error) {
|
|
556
|
+
await unlink(temp).catch(() => {});
|
|
652
557
|
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
|
-
}
|
|
666
|
-
async function catalogCommand(ctx, out, args) {
|
|
667
|
-
const [sub, ...rest] = args;
|
|
668
|
-
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
669
|
-
out.out(CATALOG_USAGE);
|
|
670
|
-
return sub === void 0 ? 2 : 0;
|
|
671
|
-
}
|
|
672
|
-
if (sub !== "push") throw new UsageError(`bilinmeyen alt komut: catalog ${sub} (ayrıntı: steward catalog --help)`);
|
|
673
|
-
const { values, positionals } = parse(rest, PUSH_OPTIONS, "catalog push");
|
|
674
|
-
if (values.help) {
|
|
675
|
-
out.out(CATALOG_USAGE);
|
|
676
|
-
return 0;
|
|
677
558
|
}
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
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;
|
|
559
|
+
try {
|
|
560
|
+
if (options.force) await rename(temp, target);
|
|
561
|
+
else {
|
|
562
|
+
await link(temp, target);
|
|
563
|
+
await unlink(temp).catch(() => {});
|
|
694
564
|
}
|
|
565
|
+
return {
|
|
566
|
+
value,
|
|
567
|
+
path: out,
|
|
568
|
+
fallback: false
|
|
569
|
+
};
|
|
570
|
+
} catch {
|
|
571
|
+
return {
|
|
572
|
+
value,
|
|
573
|
+
path: relative(cwd, temp),
|
|
574
|
+
fallback: true
|
|
575
|
+
};
|
|
695
576
|
}
|
|
696
|
-
const { lines, providerErrors } = await pushCatalog(steward, target, input);
|
|
697
|
-
for (const line of lines) out.out(line);
|
|
698
|
-
return providerErrors > 0 ? 1 : 0;
|
|
699
577
|
}
|
|
700
578
|
//#endregion
|
|
701
|
-
//#region src/commands/
|
|
702
|
-
const
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
listeleri. APP_URL tanımlıysa steward'daki appUrl ve izinli dönüş
|
|
708
|
-
origin'leriyle karşılaştırılır.
|
|
709
|
-
|
|
710
|
-
Bağlantı: STEWARD_URL + STEWARD_API_KEY (ikisi de yoksa STEWARD_ADMIN_URL +
|
|
711
|
-
STEWARD_ADMIN_API_KEY). Ortamda steward bağlantı değişkenlerinden biri bile
|
|
712
|
-
varsa bağlantı ve APP_URL yalnızca ortamdan okunur (./.env.local okunmaz);
|
|
713
|
-
yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
|
|
579
|
+
//#region src/commands/endpoints.ts
|
|
580
|
+
const ENDPOINTS_USAGE = `Kullanım:
|
|
581
|
+
steward endpoints list [--json]
|
|
582
|
+
steward endpoints add --url <url> --out <dosya> [--event-types <a,b>] [--description <metin>] [--force]
|
|
583
|
+
steward endpoints rotate <id> --out <dosya> [--force]
|
|
584
|
+
steward endpoints deactivate <id>
|
|
714
585
|
|
|
715
|
-
|
|
716
|
-
|
|
586
|
+
Webhook endpoint'leri (/v1/admin/webhook-endpoints). İmza sırrı (whsec_…) bu
|
|
587
|
+
makinede üretilir ve YALNIZCA --out dosyasına yazılır (0600, satır sonu yok);
|
|
588
|
+
terminale yazılmaz, steward hiçbir yanıtta geri vermez. Dosya varsa --force
|
|
589
|
+
olmadan istek gönderilmez. Sırrı ürünün Secret'ına operatör taşır (CLI kubectl
|
|
590
|
+
çağırmaz); rotasyonda ürün "yeni,eski" listesiyle geçer. Taşıdıktan sonra dosyayı
|
|
591
|
+
silin. --event-types verilmezse yalnızca account.state_changed. deactivate geri
|
|
592
|
+
alınmaz (yeni endpoint açılır).
|
|
717
593
|
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
594
|
+
Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
|
|
595
|
+
function schemaProblems(issues) {
|
|
596
|
+
return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n");
|
|
597
|
+
}
|
|
598
|
+
const lastDeliveryText = (endpoint) => {
|
|
599
|
+
const last = endpoint.lastDelivery;
|
|
600
|
+
if (last === null) return "-";
|
|
601
|
+
return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
|
|
602
|
+
};
|
|
603
|
+
/** Left-aligned columns; the last column is not padded. */
|
|
604
|
+
function table(rows) {
|
|
605
|
+
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
606
|
+
return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
|
|
607
|
+
}
|
|
608
|
+
const typesText = (endpoint) => endpoint.eventTypes === null ? "(filtre yok: 0.1 tipleri)" : endpoint.eventTypes.join(",");
|
|
609
|
+
async function endpointsCommand(ctx, out, args) {
|
|
610
|
+
const [sub, ...rest] = args;
|
|
611
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
612
|
+
out.out(ENDPOINTS_USAGE);
|
|
613
|
+
return sub === void 0 ? 2 : 0;
|
|
614
|
+
}
|
|
615
|
+
if (sub === "list") {
|
|
616
|
+
const { values, positionals } = parse(rest, {
|
|
617
|
+
...HELP_OPTION,
|
|
618
|
+
json: { type: "boolean" }
|
|
619
|
+
}, "endpoints");
|
|
620
|
+
if (values.help) return help$3(out);
|
|
621
|
+
expectPositionals(positionals, 0, 0, "endpoints");
|
|
622
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
623
|
+
out.err(connectionLine(target));
|
|
624
|
+
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
|
|
625
|
+
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
626
|
+
else if (items.length === 0) out.out("endpoint yok — steward endpoints add --url <url> --out <dosya>");
|
|
627
|
+
else {
|
|
628
|
+
const rows = [[
|
|
629
|
+
"ID",
|
|
630
|
+
"DURUM",
|
|
631
|
+
"OLAYLAR",
|
|
632
|
+
"SON TESLİMAT",
|
|
633
|
+
"URL"
|
|
634
|
+
]];
|
|
635
|
+
for (const e of items) rows.push([
|
|
636
|
+
e.id,
|
|
637
|
+
e.status,
|
|
638
|
+
typesText(e),
|
|
639
|
+
lastDeliveryText(e),
|
|
640
|
+
e.description !== null ? `${e.url} (${e.description})` : e.url
|
|
641
|
+
]);
|
|
642
|
+
for (const line of table(rows)) out.out(line);
|
|
643
|
+
}
|
|
644
|
+
return 0;
|
|
645
|
+
}
|
|
646
|
+
if (sub === "add") {
|
|
647
|
+
const { values, positionals } = parse(rest, {
|
|
648
|
+
...HELP_OPTION,
|
|
649
|
+
url: { type: "string" },
|
|
650
|
+
out: { type: "string" },
|
|
651
|
+
"event-types": { type: "string" },
|
|
652
|
+
description: { type: "string" },
|
|
653
|
+
force: { type: "boolean" }
|
|
654
|
+
}, ENDPOINTS_USAGE);
|
|
655
|
+
if (values.help) return help$3(out);
|
|
656
|
+
expectPositionals(positionals, 0, 0, "endpoints");
|
|
657
|
+
const url = requireOption(values.url, "--url", "endpoints");
|
|
658
|
+
const file = requireOption(values.out, "--out", "endpoints");
|
|
659
|
+
const secret = generateWebhookSecret();
|
|
660
|
+
const input = {
|
|
661
|
+
url,
|
|
662
|
+
secret,
|
|
663
|
+
...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
|
|
664
|
+
...values.description !== void 0 ? { description: values.description } : {}
|
|
665
|
+
};
|
|
666
|
+
const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
|
|
667
|
+
if (!parsed.success) throw new UsageError(`endpoint geçersiz (istek gönderilmedi)\n${schemaProblems(parsed.error.issues)}`);
|
|
668
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
669
|
+
out.err(connectionLine(target));
|
|
670
|
+
const steward = clientFor(ctx, target);
|
|
671
|
+
const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
|
|
672
|
+
const endpoint = result.value;
|
|
673
|
+
out.out(`endpoint oluşturuldu → ${originOf(target.url)}`);
|
|
674
|
+
out.out(` id ${endpoint.id}`);
|
|
675
|
+
out.out(` url ${endpoint.url}`);
|
|
676
|
+
out.out(` olaylar ${typesText(endpoint)}`);
|
|
677
|
+
secretNotice(out, result.path, result.fallback, "Sırrı ürünün Secret'ına (STEWARD_WEBHOOK_SECRET) taşıyın, sonra dosyayı silin.");
|
|
678
|
+
return 0;
|
|
679
|
+
}
|
|
680
|
+
if (sub === "rotate") {
|
|
681
|
+
const { values, positionals } = parse(rest, {
|
|
682
|
+
...HELP_OPTION,
|
|
683
|
+
out: { type: "string" },
|
|
684
|
+
force: { type: "boolean" }
|
|
685
|
+
}, "endpoints");
|
|
686
|
+
if (values.help) return help$3(out);
|
|
687
|
+
expectPositionals(positionals, 1, 1, "endpoints");
|
|
688
|
+
const id = positionals[0];
|
|
689
|
+
const file = requireOption(values.out, "--out", "endpoints");
|
|
690
|
+
const secret = generateWebhookSecret();
|
|
691
|
+
const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
|
|
692
|
+
if (!parsed.success) throw new UsageError(`sır geçersiz\n${schemaProblems(parsed.error.issues)}`);
|
|
693
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
694
|
+
out.err(connectionLine(target));
|
|
695
|
+
const steward = clientFor(ctx, target);
|
|
696
|
+
const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
|
|
697
|
+
out.out(`sır döndürüldü → ${originOf(target.url)}`);
|
|
698
|
+
out.out(` id ${result.value.id}`);
|
|
699
|
+
out.out(` url ${result.value.url}`);
|
|
700
|
+
secretNotice(out, result.path, result.fallback, "Ürünün Secret'ında STEWARD_WEBHOOK_SECRET'ı \"yeni,eski\" yapın ve rollout edin; eski sır steward'da geçiş için ikinci imza olarak kalır. Sonra dosyayı silin.");
|
|
701
|
+
return 0;
|
|
702
|
+
}
|
|
703
|
+
if (sub === "deactivate") {
|
|
704
|
+
const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
|
|
705
|
+
if (values.help) return help$3(out);
|
|
706
|
+
expectPositionals(positionals, 1, 1, "endpoints");
|
|
707
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
708
|
+
out.err(connectionLine(target));
|
|
709
|
+
const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
|
|
710
|
+
out.out(`endpoint pasifleştirildi → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, durum ${endpoint.status})`);
|
|
711
|
+
return 0;
|
|
712
|
+
}
|
|
713
|
+
throw new UsageError(`bilinmeyen alt komut: endpoints ${sub} (ayrıntı: steward endpoints --help)`);
|
|
714
|
+
}
|
|
715
|
+
function help$3(out) {
|
|
716
|
+
out.out(ENDPOINTS_USAGE);
|
|
717
|
+
return 0;
|
|
718
|
+
}
|
|
719
|
+
/** Where a generated secret went (`withSecretFile`); shared by `endpoints` and `keys`. */
|
|
720
|
+
function secretNotice(out, path, fallback, next) {
|
|
721
|
+
if (fallback) out.err(`! the secret could not be moved to the target file (it may have been created meanwhile); it is in ${path} (0600)`);
|
|
722
|
+
out.out(` secret ${path} (0600; not written to the terminal)`);
|
|
723
|
+
out.err(next);
|
|
724
|
+
}
|
|
725
|
+
//#endregion
|
|
726
|
+
//#region src/commands/bank-transfers.ts
|
|
727
|
+
const BANK_TRANSFERS_USAGE = `Usage:
|
|
728
|
+
steward bank-transfers list [--status pending|expired] [--json]
|
|
729
|
+
steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso>
|
|
730
|
+
--bank-ref <ref> [--checkout <id> [--accept-expired] | --invoice <id>]
|
|
731
|
+
[--yes] [--json]
|
|
732
|
+
|
|
733
|
+
Bank transfer (havale/EFT) reconciliation (/v1/admin/bank-transfers).
|
|
734
|
+
|
|
735
|
+
list: what the bank statement is matched against. pending (default): checkouts waiting for a
|
|
736
|
+
transfer and unpaid invoices of accounts with an order code, by deadline; expired: checkouts
|
|
737
|
+
that expired in the last 30 days.
|
|
738
|
+
|
|
739
|
+
record: a transfer seen on the bank account. <code> is the order code from the transfer
|
|
740
|
+
description (case and dashes are forgiven). Only a checkout or unpaid invoice waiting for
|
|
741
|
+
EXACTLY --amount (minor units, e.g. 125000 = 1,250.00) in --currency matches. --received-at
|
|
742
|
+
is ISO-8601 with an offset (2026-09-28T10:15:00+03:00). --bank-ref is the bank's transaction
|
|
743
|
+
number; one payment per reference. When several items match, name one with --checkout or
|
|
744
|
+
--invoice; an expired checkout is accepted only with --accept-expired --checkout <id>.
|
|
745
|
+
A refused transfer is refunded through the bank. Recording needs confirmation (a prompt on a
|
|
746
|
+
terminal, otherwise --yes): it starts a subscription or pays an invoice.
|
|
747
|
+
|
|
748
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
749
|
+
const WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
750
|
+
async function bankTransfersCommand(ctx, out, args) {
|
|
751
|
+
const [sub, ...rest] = args;
|
|
752
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
753
|
+
out.out(BANK_TRANSFERS_USAGE);
|
|
754
|
+
return sub === void 0 ? 2 : 0;
|
|
755
|
+
}
|
|
756
|
+
if (sub === "list") {
|
|
757
|
+
const { values, positionals } = parse(rest, {
|
|
758
|
+
...HELP_OPTION,
|
|
759
|
+
status: { type: "string" },
|
|
760
|
+
json: { type: "boolean" }
|
|
761
|
+
}, "bank-transfers");
|
|
762
|
+
if (values.help) return help$2(out);
|
|
763
|
+
expectPositionals(positionals, 0, 0, "bank-transfers");
|
|
764
|
+
const status = values.status ?? "pending";
|
|
765
|
+
if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
|
|
766
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
767
|
+
out.err(connectionLine(target));
|
|
768
|
+
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.list(status));
|
|
769
|
+
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
770
|
+
else if (items.length === 0) out.out(`no ${status} bank transfers`);
|
|
771
|
+
else {
|
|
772
|
+
const rows = [[
|
|
773
|
+
"CODE",
|
|
774
|
+
"AMOUNT",
|
|
775
|
+
"DEADLINE",
|
|
776
|
+
"KIND",
|
|
777
|
+
"PLAN",
|
|
778
|
+
"ACCOUNT",
|
|
779
|
+
"ID"
|
|
780
|
+
]];
|
|
781
|
+
for (const i of items) rows.push([
|
|
782
|
+
i.code ?? "-",
|
|
783
|
+
formatMinor(i.totalMinor, i.currency),
|
|
784
|
+
i.deadline ?? "-",
|
|
785
|
+
i.kind,
|
|
786
|
+
i.planCode ?? "-",
|
|
787
|
+
i.accountRef,
|
|
788
|
+
i.id
|
|
789
|
+
]);
|
|
790
|
+
for (const line of table(rows)) out.out(line);
|
|
791
|
+
}
|
|
792
|
+
return 0;
|
|
793
|
+
}
|
|
794
|
+
if (sub === "record") {
|
|
795
|
+
const { values, positionals } = parse(rest, {
|
|
796
|
+
...HELP_OPTION,
|
|
797
|
+
amount: { type: "string" },
|
|
798
|
+
currency: { type: "string" },
|
|
799
|
+
"received-at": { type: "string" },
|
|
800
|
+
"bank-ref": { type: "string" },
|
|
801
|
+
checkout: { type: "string" },
|
|
802
|
+
invoice: { type: "string" },
|
|
803
|
+
"accept-expired": { type: "boolean" },
|
|
804
|
+
yes: {
|
|
805
|
+
type: "boolean",
|
|
806
|
+
short: "y"
|
|
807
|
+
},
|
|
808
|
+
json: { type: "boolean" }
|
|
809
|
+
}, "bank-transfers");
|
|
810
|
+
if (values.help) return help$2(out);
|
|
811
|
+
expectPositionals(positionals, 1, 1, "bank-transfers");
|
|
812
|
+
const receivedAt = requireOption(values["received-at"], "--received-at", "bank-transfers");
|
|
813
|
+
if (!WITH_OFFSET.test(receivedAt)) throw new UsageError("--received-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
|
|
814
|
+
const input = {
|
|
815
|
+
code: positionals[0],
|
|
816
|
+
amountMinor: parseNonNegativeInt(requireOption(values.amount, "--amount", "bank-transfers"), "--amount"),
|
|
817
|
+
currency: requireOption(values.currency, "--currency", "bank-transfers").toUpperCase(),
|
|
818
|
+
receivedAt,
|
|
819
|
+
bankRef: requireOption(values["bank-ref"], "--bank-ref", "bank-transfers"),
|
|
820
|
+
...values.checkout !== void 0 ? { checkoutSessionId: values.checkout } : {},
|
|
821
|
+
...values.invoice !== void 0 ? { invoiceId: values.invoice } : {},
|
|
822
|
+
...values["accept-expired"] ? { acceptExpired: true } : {}
|
|
823
|
+
};
|
|
824
|
+
const parsed = BankTransferRecordInputSchema.safeParse(input);
|
|
825
|
+
if (!parsed.success) throw new UsageError(`invalid transfer (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
826
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
827
|
+
out.err(connectionLine(target));
|
|
828
|
+
if (!await confirm(ctx, `Record ${formatMinor(input.amountMinor, input.currency)} for order code ${input.code} (bank ref ${input.bankRef})?`, {
|
|
829
|
+
yes: values.yes === true,
|
|
830
|
+
notConfirmed: "nothing was recorded"
|
|
831
|
+
})) {
|
|
832
|
+
out.err("not confirmed; nothing was recorded");
|
|
833
|
+
return 1;
|
|
834
|
+
}
|
|
835
|
+
const recorded = await callSteward(target, () => clientFor(ctx, target).admin.bankTransfers.record(input));
|
|
836
|
+
if (values.json) {
|
|
837
|
+
out.out(JSON.stringify(recorded, null, 2));
|
|
838
|
+
return 0;
|
|
839
|
+
}
|
|
840
|
+
out.out(recorded.invoiceId !== null ? `recorded → ${originOf(target.url)}: account ${recorded.accountRef}, invoice ${recorded.invoiceId} paid${recorded.paidAfterWriteoff ? " (after write-off)" : ""}` : `recorded → ${originOf(target.url)}: account ${recorded.accountRef}, checkout ${recorded.checkoutSessionId} completed, subscription ${recorded.subscriptionId} started${recorded.replacedSubscriptionId !== null ? `, subscription ${recorded.replacedSubscriptionId} replaced` : ""}${recorded.acceptedAfterExpiry ? " (accepted after expiry)" : ""}`);
|
|
841
|
+
return 0;
|
|
842
|
+
}
|
|
843
|
+
throw new UsageError(`unknown subcommand: bank-transfers ${sub} (see: steward bank-transfers --help)`);
|
|
844
|
+
}
|
|
845
|
+
function help$2(out) {
|
|
846
|
+
out.out(BANK_TRANSFERS_USAGE);
|
|
847
|
+
return 0;
|
|
848
|
+
}
|
|
849
|
+
//#endregion
|
|
850
|
+
//#region src/catalog-file.ts
|
|
851
|
+
const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
852
|
+
".js",
|
|
853
|
+
".mjs",
|
|
854
|
+
".cjs"
|
|
855
|
+
]);
|
|
856
|
+
const TS_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
857
|
+
".ts",
|
|
858
|
+
".mts",
|
|
859
|
+
".cts"
|
|
860
|
+
]);
|
|
861
|
+
const hasSyncInput = (value) => typeof value === "object" && value !== null && typeof value.toSyncInput === "function";
|
|
862
|
+
function pickExport(mod, file) {
|
|
863
|
+
if (mod.catalog !== void 0) return mod.catalog;
|
|
864
|
+
if (mod.default !== void 0) return mod.default;
|
|
865
|
+
const candidates = Object.values(mod).filter(hasSyncInput);
|
|
866
|
+
if (candidates.length === 1) return candidates[0];
|
|
867
|
+
throw new CliError(`${file}: katalog bulunamadı — \`export const catalog = defineCatalog(…)\` ya da default export bekleniyor`);
|
|
868
|
+
}
|
|
869
|
+
async function loadCatalogFile(ctx, file) {
|
|
870
|
+
const path = resolve(ctx.cwd, file);
|
|
871
|
+
const ext = extname(path).toLowerCase();
|
|
872
|
+
let exported;
|
|
873
|
+
if (ext === ".json") {
|
|
874
|
+
let text;
|
|
875
|
+
try {
|
|
876
|
+
text = await readFile(path, "utf8");
|
|
877
|
+
} catch (error) {
|
|
878
|
+
throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
|
|
879
|
+
}
|
|
880
|
+
try {
|
|
881
|
+
exported = JSON.parse(text);
|
|
882
|
+
} catch {
|
|
883
|
+
throw new CliError(`${file}: geçerli JSON değil`);
|
|
884
|
+
}
|
|
885
|
+
} else if (MODULE_EXTENSIONS.has(ext) || TS_EXTENSIONS.has(ext)) {
|
|
886
|
+
if (TS_EXTENSIONS.has(ext) && !ctx.typescript) throw new CliError(`${file}: bu Node sürümü TypeScript dosyasını doğrudan yükleyemiyor (${process.version}). Node ≥ 22.18 kullanın, \`NODE_OPTIONS=--experimental-strip-types\` verin ya da kataloğu .mjs/.json olarak dışa aktarın.`);
|
|
887
|
+
let mod;
|
|
888
|
+
try {
|
|
889
|
+
await readFile(path);
|
|
890
|
+
} catch (error) {
|
|
891
|
+
throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
|
|
892
|
+
}
|
|
893
|
+
try {
|
|
894
|
+
mod = await ctx.importModule(pathToFileURL(path).href);
|
|
895
|
+
} catch (error) {
|
|
896
|
+
throw new CliError(`${file} yüklenemedi: ${error instanceof Error ? error.message : String(error)}`);
|
|
897
|
+
}
|
|
898
|
+
exported = pickExport(mod, file);
|
|
899
|
+
} else throw new UsageError(`katalog dosyası .ts, .mts, .js, .mjs, .cjs ya da .json olmalı: ${file}`);
|
|
900
|
+
let input;
|
|
901
|
+
try {
|
|
902
|
+
input = hasSyncInput(exported) ? exported.toSyncInput() : exported;
|
|
903
|
+
} catch (error) {
|
|
904
|
+
throw new CliError(`${file}: toSyncInput() hata verdi: ${error instanceof Error ? error.message : String(error)}`);
|
|
905
|
+
}
|
|
906
|
+
const parsed = CatalogSyncInputSchema.safeParse(input);
|
|
907
|
+
if (!parsed.success) throw new CliError(`${file}: katalog geçersiz (istek gönderilmedi)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n")}`);
|
|
908
|
+
return input;
|
|
909
|
+
}
|
|
910
|
+
//#endregion
|
|
911
|
+
//#region src/commands/catalog.ts
|
|
912
|
+
const CATALOG_USAGE = `Kullanım: steward catalog push <dosya> [--yes]
|
|
913
|
+
|
|
914
|
+
Katalog tanımını steward'a senkronlar (PUT /v1/admin/catalog), sonra sürümü ve
|
|
915
|
+
sayıları yazar. Dosya: .ts/.mts (Node tip ayıklaması, Node ≥ 22.18), .js/.mjs/.cjs
|
|
916
|
+
(\`export const catalog = defineCatalog(…)\` ya da default export) veya .json
|
|
917
|
+
(senkron gövdesi). Geçersiz katalogda istek gönderilmez.
|
|
918
|
+
|
|
919
|
+
Before pushing, prints what changes against steward's current catalog: benefits
|
|
920
|
+
(new, changed, archived, plan benefit lists) and prices (new, deactivated, amount or
|
|
921
|
+
tax terms changed). A changed price is updated in place: existing subscriptions keep
|
|
922
|
+
the amount they locked, new subscriptions pay the new amount, a tax change applies to
|
|
923
|
+
every invoice written from now on. Price changes need confirmation: a prompt on a
|
|
924
|
+
terminal, otherwise --yes (-y). A catalog with benefits is pushed only to a steward
|
|
925
|
+
whose GET /v1/me lists the "benefits" capability (an older steward would drop them).
|
|
926
|
+
|
|
927
|
+
Metering: the diff also lists meters (new, changed, rule changed, archived), changed
|
|
928
|
+
credits (meter_credit benefits) and metered prices (new, deactivated, changed; a
|
|
929
|
+
changed metered price needs the same confirmation). A meter's filter and aggregation
|
|
930
|
+
are fixed once it has counted a period (422 meter_locked: use a new meter code). A
|
|
931
|
+
catalog with meters or metered prices is pushed only to a steward whose GET /v1/me
|
|
932
|
+
lists the "meters" capability.
|
|
933
|
+
|
|
934
|
+
Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).
|
|
935
|
+
Çıkış kodu 1: sağlayıcıda karşılığı açılamayan fiyat var (senkronu yeniden koşun);
|
|
936
|
+
the push was refused or not confirmed.`;
|
|
937
|
+
const PUSH_OPTIONS = {
|
|
938
|
+
...HELP_OPTION,
|
|
939
|
+
yes: {
|
|
940
|
+
type: "boolean",
|
|
941
|
+
short: "y"
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
const list = (items) => items.length > 0 ? items.join(", ") : "-";
|
|
945
|
+
/** Senkron + sürüm okuması; özet satırları ve sağlayıcı hatası olup olmadığı. */
|
|
946
|
+
async function pushCatalog(steward, target, input) {
|
|
947
|
+
const result = await callSteward(target, () => steward.admin.catalog.sync(input));
|
|
948
|
+
const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "bilinmiyor";
|
|
949
|
+
const benefitCount = Object.keys(input.benefits ?? {}).length;
|
|
950
|
+
const meterCount = Object.keys(input.meters ?? {}).length;
|
|
951
|
+
const meteredCount = (input.meteredPrices ?? []).length;
|
|
952
|
+
const metering = `${meterCount > 0 ? ` · ${meterCount} meter${meterCount === 1 ? "" : "s"}` : ""}${meteredCount > 0 ? ` · ${meteredCount} metered price${meteredCount === 1 ? "" : "s"}` : ""}`;
|
|
953
|
+
const lines = [`katalog senkronlandı → ${originOf(target.url)}`];
|
|
954
|
+
lines.push(` sürüm ${version}`);
|
|
955
|
+
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}`);
|
|
956
|
+
if (result.unchanged) lines.push(" değişiklik yok");
|
|
957
|
+
else {
|
|
958
|
+
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" : ""}`);
|
|
959
|
+
const changedBenefits = result.changedBenefits ?? [];
|
|
960
|
+
const archivedBenefits = result.archivedBenefits ?? [];
|
|
961
|
+
if (changedBenefits.length > 0 || archivedBenefits.length > 0) lines.push(` benefits changed: ${list(changedBenefits)} · archived: ${list(archivedBenefits)}`);
|
|
962
|
+
if ((result.updatedPrices ?? []).length > 0) lines.push(` prices updated in place: ${result.updatedPrices.length}`);
|
|
963
|
+
const changedMeters = result.changedMeters ?? [];
|
|
964
|
+
const archivedMeters = result.archivedMeters ?? [];
|
|
965
|
+
if (changedMeters.length > 0 || archivedMeters.length > 0) lines.push(` meters changed: ${list(changedMeters)} · archived: ${list(archivedMeters)}`);
|
|
966
|
+
const [created, updated, deactivated] = [
|
|
967
|
+
result.createdMeteredPrices ?? [],
|
|
968
|
+
result.updatedMeteredPrices ?? [],
|
|
969
|
+
result.deactivatedMeteredPrices ?? []
|
|
970
|
+
];
|
|
971
|
+
if (created.length + updated.length + deactivated.length > 0) lines.push(` metered new ${created.length} · updated in place ${updated.length} · deactivated ${deactivated.length}`);
|
|
972
|
+
}
|
|
973
|
+
for (const error of result.providerErrors) lines.push(` ✗ sağlayıcı hatası: fiyat ${error.priceId} (${error.provider}: ${error.code}) — senkronu yeniden koşun`);
|
|
974
|
+
return {
|
|
975
|
+
lines,
|
|
976
|
+
providerErrors: result.providerErrors.length
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
/** The steward's current catalog; null before the first push (`404 catalog_not_configured`). */
|
|
980
|
+
function currentCatalog(steward, target) {
|
|
981
|
+
return callSteward(target, () => steward.catalog.get().catch((error) => {
|
|
982
|
+
if (error instanceof StewardApiError && error.httpStatus === 404 && error.code === "catalog_not_configured") return null;
|
|
983
|
+
throw error;
|
|
984
|
+
}));
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
* Refuses a catalog whose benefits or meters steward does not understand (M27): an older steward
|
|
988
|
+
* drops the keys silently. `needed`: the capabilities the catalog needs (`benefits`, `meters`).
|
|
989
|
+
*/
|
|
990
|
+
async function requireCapabilities(steward, target, needed) {
|
|
991
|
+
if (needed.length === 0) return;
|
|
992
|
+
const me = await callSteward(target, () => steward.me());
|
|
993
|
+
const missing = needed.filter((capability) => !(me.capabilities ?? []).includes(capability));
|
|
994
|
+
if (missing.length === 0) return;
|
|
995
|
+
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.`);
|
|
996
|
+
}
|
|
997
|
+
async function catalogCommand(ctx, out, args) {
|
|
998
|
+
const [sub, ...rest] = args;
|
|
999
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
1000
|
+
out.out(CATALOG_USAGE);
|
|
1001
|
+
return sub === void 0 ? 2 : 0;
|
|
1002
|
+
}
|
|
1003
|
+
if (sub !== "push") throw new UsageError(`bilinmeyen alt komut: catalog ${sub} (ayrıntı: steward catalog --help)`);
|
|
1004
|
+
const { values, positionals } = parse(rest, PUSH_OPTIONS, "catalog push");
|
|
1005
|
+
if (values.help) {
|
|
1006
|
+
out.out(CATALOG_USAGE);
|
|
1007
|
+
return 0;
|
|
1008
|
+
}
|
|
1009
|
+
expectPositionals(positionals, 1, 1, "catalog push");
|
|
1010
|
+
const input = await loadCatalogFile(ctx, positionals[0]);
|
|
1011
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1012
|
+
out.err(connectionLine(target));
|
|
1013
|
+
const steward = clientFor(ctx, target);
|
|
1014
|
+
await requireCapabilities(steward, target, [...definesBenefits(input) ? ["benefits"] : [], ...definesMeters(input) ? ["meters"] : []]);
|
|
1015
|
+
const diff = diffCatalog(await currentCatalog(steward, target), input);
|
|
1016
|
+
for (const line of describeDiff(diff)) out.out(line);
|
|
1017
|
+
const priceChanges = priceChangeCount(diff);
|
|
1018
|
+
if (priceChanges > 0 && !values.yes) {
|
|
1019
|
+
const question = `Apply ${priceChanges} price change${priceChanges === 1 ? "" : "s"}? [y/N] `;
|
|
1020
|
+
const answer = await ctx.prompt(question);
|
|
1021
|
+
if (answer === null) throw new CliError(`${priceChanges} price change${priceChanges === 1 ? "" : "s"} need${priceChanges === 1 ? "s" : ""} confirmation: run again with --yes (nothing was pushed)`);
|
|
1022
|
+
if (!/^y(es)?$/i.test(answer.trim())) {
|
|
1023
|
+
out.err("not confirmed; nothing was pushed");
|
|
1024
|
+
return 1;
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
const { lines, providerErrors } = await pushCatalog(steward, target, input);
|
|
1028
|
+
for (const line of lines) out.out(line);
|
|
1029
|
+
return providerErrors > 0 ? 1 : 0;
|
|
1030
|
+
}
|
|
1031
|
+
//#endregion
|
|
1032
|
+
//#region src/commands/meters.ts
|
|
1033
|
+
const METERS_USAGE = `Usage:
|
|
1034
|
+
steward meters get <ref> [--periods <n>] [--json]
|
|
1035
|
+
steward meters recompute <ref> [--meter <code>] [--json]
|
|
1036
|
+
steward meters close-periods <ref> [--meter <code>] [--force] [--json]
|
|
1037
|
+
|
|
1038
|
+
Reads an account's meters (GET /v1/accounts/:ref/meters): per meter the current usage
|
|
1039
|
+
period, units used, the period's credit, the balance, the standing (ok | low | exhausted)
|
|
1040
|
+
and, for a billable meter, the estimated overage so far. Nothing is written.
|
|
1041
|
+
|
|
1042
|
+
--periods <n> also list the last n closed periods (1–100; GET …/meters/periods)
|
|
1043
|
+
--json print the response as JSON
|
|
1044
|
+
|
|
1045
|
+
recompute (admin): rebuilds the account's OPEN usage period of every meter (or --meter) from
|
|
1046
|
+
the raw events, the repair of a wrongly counted period. Closed periods never change; running it
|
|
1047
|
+
again gives the same result. Prints each meter's consumption before and after.
|
|
1048
|
+
|
|
1049
|
+
close-periods (admin): closes the account's closing periods now instead of after the late
|
|
1050
|
+
window (recount from raw events, meter.period_closed). It waits for unrolled events unless
|
|
1051
|
+
--force (those then count in a later period as late). Open periods are never touched.
|
|
1052
|
+
|
|
1053
|
+
Connection: get uses STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
|
|
1054
|
+
STEWARD_ADMIN_API_KEY); recompute and close-periods use STEWARD_ADMIN_URL +
|
|
1055
|
+
STEWARD_ADMIN_API_KEY. Environment, otherwise ./.env.local.`;
|
|
1056
|
+
const REPAIR_OPTIONS = {
|
|
1057
|
+
...HELP_OPTION,
|
|
1058
|
+
meter: { type: "string" },
|
|
1059
|
+
force: { type: "boolean" },
|
|
1060
|
+
json: { type: "boolean" }
|
|
1061
|
+
};
|
|
1062
|
+
async function repairCommand(ctx, out, sub, args) {
|
|
1063
|
+
const { values, positionals } = parse(args, REPAIR_OPTIONS, "meters");
|
|
1064
|
+
if (values.help) {
|
|
1065
|
+
out.out(METERS_USAGE);
|
|
1066
|
+
return 0;
|
|
1067
|
+
}
|
|
1068
|
+
expectPositionals(positionals, 1, 1, "meters");
|
|
1069
|
+
if (sub === "recompute" && values.force) throw new UsageError("--force is for close-periods");
|
|
1070
|
+
const ref = positionals[0];
|
|
1071
|
+
const meter = values.meter !== void 0 ? { meter: values.meter } : {};
|
|
1072
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1073
|
+
out.err(connectionLine(target));
|
|
1074
|
+
const steward = clientFor(ctx, target);
|
|
1075
|
+
if (sub === "recompute") {
|
|
1076
|
+
const result = await callSteward(target, () => steward.admin.meters.recompute(ref, meter));
|
|
1077
|
+
if (values.json) out.out(JSON.stringify(result, null, 2));
|
|
1078
|
+
else for (const item of result.items) out.out(item.periodStart === null ? ` ${item.meter} no open period` : ` ${item.meter} ${item.periodStart} → ${item.periodEnd} ${item.before} → ${item.after}`);
|
|
1079
|
+
return 0;
|
|
1080
|
+
}
|
|
1081
|
+
const result = await callSteward(target, () => steward.admin.meters.closePeriods(ref, {
|
|
1082
|
+
...meter,
|
|
1083
|
+
...values.force ? { force: true } : {}
|
|
1084
|
+
}));
|
|
1085
|
+
if (values.json) out.out(JSON.stringify(result, null, 2));
|
|
1086
|
+
else out.out(`${result.closed} period(s) closed, ${result.events} meter.period_closed event(s); ${result.pending} closing period(s) left`);
|
|
1087
|
+
return 0;
|
|
1088
|
+
}
|
|
1089
|
+
const GET_OPTIONS = {
|
|
1090
|
+
...HELP_OPTION,
|
|
1091
|
+
periods: { type: "string" },
|
|
1092
|
+
json: { type: "boolean" }
|
|
1093
|
+
};
|
|
1094
|
+
/** Units of a meter read (a JSON number with at most 6 decimals) as exact text with grouping: `1,700,000.5`. */
|
|
1095
|
+
function formatUnitsText(value) {
|
|
1096
|
+
return new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
|
|
1097
|
+
}
|
|
1098
|
+
function meterLines(code, meter, width) {
|
|
1099
|
+
const lines = [` ${code.padEnd(width)} ${meter.periodStart} → ${meter.periodEnd}`];
|
|
1100
|
+
const indent = " ".repeat(width + 4);
|
|
1101
|
+
lines.push(`${indent}used ${formatUnitsText(meter.consumedUnits)} · credit ${formatUnitsText(meter.creditedUnits)} · balance ${formatUnitsText(meter.balance)} · standing ${meter.standing}`);
|
|
1102
|
+
const included = meter.includedUnits === null ? "no credit included" : `included ${formatUnitsText(meter.includedUnits)} per period`;
|
|
1103
|
+
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)";
|
|
1104
|
+
lines.push(`${indent}${included} · ${billing}`);
|
|
1105
|
+
return lines;
|
|
1106
|
+
}
|
|
1107
|
+
/** Human-readable meter read (+ closed periods, newest first). */
|
|
1108
|
+
function formatMeters(meters, periods) {
|
|
1109
|
+
const lines = [`meters of ${meters.ref} · as of ${meters.asOf} · events received before ${meters.rolledUpThrough} are counted`];
|
|
1110
|
+
const codes = Object.keys(meters.meters);
|
|
1111
|
+
if (codes.length === 0) lines.push(" no meters (the product's catalog defines none)");
|
|
1112
|
+
else {
|
|
1113
|
+
const width = Math.max(...codes.map((code) => code.length));
|
|
1114
|
+
for (const code of codes) lines.push(...meterLines(code, meters.meters[code], width));
|
|
1115
|
+
}
|
|
1116
|
+
if (periods !== null) {
|
|
1117
|
+
lines.push("");
|
|
1118
|
+
if (periods.length === 0) lines.push("closed periods: none");
|
|
1119
|
+
else {
|
|
1120
|
+
lines.push("closed periods (newest first):");
|
|
1121
|
+
const width = Math.max(...periods.map((p) => p.meter.length));
|
|
1122
|
+
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)}`);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
return lines;
|
|
1126
|
+
}
|
|
1127
|
+
async function metersCommand(ctx, out, args) {
|
|
1128
|
+
const [sub, ...rest] = args;
|
|
1129
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
1130
|
+
out.out(METERS_USAGE);
|
|
1131
|
+
return sub === void 0 ? 2 : 0;
|
|
1132
|
+
}
|
|
1133
|
+
if (sub === "recompute" || sub === "close-periods") return repairCommand(ctx, out, sub, rest);
|
|
1134
|
+
if (sub !== "get") throw new UsageError(`unknown subcommand: meters ${sub} (see: steward meters --help)`);
|
|
1135
|
+
const { values, positionals } = parse(rest, GET_OPTIONS, "meters");
|
|
1136
|
+
if (values.help) {
|
|
1137
|
+
out.out(METERS_USAGE);
|
|
1138
|
+
return 0;
|
|
1139
|
+
}
|
|
1140
|
+
expectPositionals(positionals, 1, 1, "meters");
|
|
1141
|
+
const ref = positionals[0];
|
|
1142
|
+
const limit = values.periods === void 0 ? null : parsePositiveInt(values.periods, "--periods", { max: 100 });
|
|
1143
|
+
const target = requireReadTarget(await resolveEnv(ctx));
|
|
1144
|
+
out.err(connectionLine(target));
|
|
1145
|
+
const steward = clientFor(ctx, target);
|
|
1146
|
+
const meters = await callSteward(target, () => steward.meters.get(ref));
|
|
1147
|
+
const periods = limit === null ? null : (await callSteward(target, () => steward.meters.periods(ref, { limit }))).periods;
|
|
1148
|
+
if (values.json) out.out(JSON.stringify(periods === null ? meters : {
|
|
1149
|
+
...meters,
|
|
1150
|
+
closedPeriods: periods
|
|
1151
|
+
}, null, 2));
|
|
1152
|
+
else for (const line of formatMeters(meters, periods)) out.out(line);
|
|
1153
|
+
return 0;
|
|
1154
|
+
}
|
|
1155
|
+
//#endregion
|
|
1156
|
+
//#region src/commands/credits.ts
|
|
1157
|
+
const CREDITS_USAGE = `Usage: steward credits adjust <ref> <meter> --units=<n> --reason <text> [--json]
|
|
1158
|
+
|
|
1159
|
+
One credit ledger entry for the meter's current usage period of account <ref>
|
|
1160
|
+
(POST /v1/admin/accounts/:ref/credits). Positive units add credit (manual_grant), negative
|
|
1161
|
+
units take it back (adjustment, e.g. events sent by mistake). Write a negative value with
|
|
1162
|
+
"=": --units=-2500. Units: a non-zero decimal with at most 6 places. --reason: 3–500
|
|
1163
|
+
characters, kept on the entry. Entries are never rewritten: a wrong one is corrected by
|
|
1164
|
+
another entry.
|
|
1165
|
+
|
|
1166
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
1167
|
+
const UNITS = /^-?\d{1,16}(\.\d{1,6})?$/;
|
|
1168
|
+
async function creditsCommand(ctx, out, args) {
|
|
1169
|
+
const [sub, ...rest] = args;
|
|
1170
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
1171
|
+
out.out(CREDITS_USAGE);
|
|
1172
|
+
return sub === void 0 ? 2 : 0;
|
|
1173
|
+
}
|
|
1174
|
+
if (sub !== "adjust") throw new UsageError(`unknown subcommand: credits ${sub} (see: steward credits --help)`);
|
|
1175
|
+
const { values, positionals } = parse(rest, {
|
|
1176
|
+
...HELP_OPTION,
|
|
1177
|
+
units: { type: "string" },
|
|
1178
|
+
reason: { type: "string" },
|
|
1179
|
+
json: { type: "boolean" }
|
|
1180
|
+
}, "credits");
|
|
1181
|
+
if (values.help) {
|
|
1182
|
+
out.out(CREDITS_USAGE);
|
|
1183
|
+
return 0;
|
|
1184
|
+
}
|
|
1185
|
+
expectPositionals(positionals, 2, 2, "credits");
|
|
1186
|
+
const [ref, meter] = positionals;
|
|
1187
|
+
const unitsText = requireOption(values.units, "--units", "credits").trim();
|
|
1188
|
+
if (!UNITS.test(unitsText)) throw new UsageError(`--units: a decimal with at most 6 places, got ${unitsText}`);
|
|
1189
|
+
const input = {
|
|
1190
|
+
meter,
|
|
1191
|
+
units: Number(unitsText),
|
|
1192
|
+
reason: requireOption(values.reason, "--reason", "credits")
|
|
1193
|
+
};
|
|
1194
|
+
const parsed = CreditAdjustmentInputSchema.safeParse(input);
|
|
1195
|
+
if (!parsed.success) throw new UsageError(`invalid credit entry (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
1196
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1197
|
+
out.err(connectionLine(target));
|
|
1198
|
+
const result = await callSteward(target, () => clientFor(ctx, target).admin.credits.adjust(ref, parsed.data));
|
|
1199
|
+
if (values.json) {
|
|
1200
|
+
out.out(JSON.stringify(result, null, 2));
|
|
1201
|
+
return 0;
|
|
1202
|
+
}
|
|
1203
|
+
const { entry } = result;
|
|
1204
|
+
out.out(`${entry.kind} of ${formatUnitsText(entry.units)} ${entry.meter} written → ${originOf(target.url)} (period from ${entry.periodStart})`);
|
|
1205
|
+
const read = result.meters.meters[entry.meter];
|
|
1206
|
+
if (read !== void 0) out.out(` balance ${formatUnitsText(read.balance)} · standing ${read.standing}`);
|
|
1207
|
+
return 0;
|
|
1208
|
+
}
|
|
1209
|
+
//#endregion
|
|
1210
|
+
//#region src/commands/doctor.ts
|
|
1211
|
+
const DOCTOR_USAGE = `Kullanım: steward doctor [--json]
|
|
1212
|
+
|
|
1213
|
+
GET /v1/doctor raporu. Bölümler sırayla: durum, katalog, sağlayıcı, ayarlar,
|
|
1214
|
+
hosted (sayfa hazırlığı), endpoint'ler (teslimat teşhisi), dunning, emails ve
|
|
1215
|
+
sayaçlı üründe metering/events/overage; sonda hatalar, uyarılar ve bilgi
|
|
1216
|
+
listeleri. APP_URL tanımlıysa steward'daki appUrl ve izinli dönüş
|
|
1217
|
+
origin'leriyle karşılaştırılır.
|
|
1218
|
+
|
|
1219
|
+
Bağlantı: STEWARD_URL + STEWARD_API_KEY (ikisi de yoksa STEWARD_ADMIN_URL +
|
|
1220
|
+
STEWARD_ADMIN_API_KEY). Ortamda steward bağlantı değişkenlerinden biri bile
|
|
1221
|
+
varsa bağlantı ve APP_URL yalnızca ortamdan okunur (./.env.local okunmaz);
|
|
1222
|
+
yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
|
|
1223
|
+
|
|
1224
|
+
Çıkış kodu: 0 hazır; 1 rapor ok değil (error önemde uyarı) ya da APP_URL
|
|
1225
|
+
steward'da izinli değil.
|
|
1226
|
+
|
|
1227
|
+
Ölçümleme: kataloğunda sayaç tanımlı üründe "metering" satırı sayaçları ve
|
|
1228
|
+
ölçümlü fiyatları (GET /v1/catalog) ve steward'ın yeteneklerini (GET /v1/me:
|
|
1229
|
+
events, meters, overage) yazar; ardından raporun "events" bölümü (bekleyen olay,
|
|
1230
|
+
rollup gecikmesi, son 7 günün örneği: eşleşmeyen olay adları, geçersiz değerler,
|
|
1231
|
+
olayı olmayan sayaçlar) ve "overage" bölümü (aşım kipi, ölçümlü fiyatlar, kilitli
|
|
1232
|
+
oranı olmayan abonelikler, devreden kayıtlar) gelir. Ölçümleme uyarıları her
|
|
724
1233
|
zamanki gibi alttaki listelerdedir.
|
|
725
1234
|
|
|
726
1235
|
--json raporu JSON yazar (+ cliWarnings: yerel APP_URL karşılaştırması;
|
|
@@ -862,6 +1371,13 @@ function formatDoctorReport(report, cliWarnings, metering = null) {
|
|
|
862
1371
|
const disabled = emails.disabledTemplates.length > 0 ? ` · disabled: ${emails.disabledTemplates.join(", ")}` : "";
|
|
863
1372
|
lines.push(`emails ${emails.ready ? "ready ✓" : `not sending ✗${problems.length > 0 ? ` (${problems.join(", ")})` : ""}`}${disabled}`);
|
|
864
1373
|
}
|
|
1374
|
+
if (report.apiKeys) {
|
|
1375
|
+
lines.push(report.apiKeys.length === 0 ? "api keys none active" : "api keys");
|
|
1376
|
+
for (const key of report.apiKeys) {
|
|
1377
|
+
const expiry = key.expiresAt === null ? "never expires" : `expires ${key.expiresAt}`;
|
|
1378
|
+
lines.push(` ${key.prefix} ${key.scope} ${key.name} · ${key.ageDays} day(s) old · last used ${key.lastUsedAt ?? "never"} · ${expiry}`);
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
865
1381
|
lines.push(...formatMetering(report, metering));
|
|
866
1382
|
for (const severity of SEVERITY_ORDER) {
|
|
867
1383
|
const items = all.filter((w) => w.severity === severity);
|
|
@@ -900,208 +1416,96 @@ async function doctorCommand(ctx, out, args) {
|
|
|
900
1416
|
cliWarnings,
|
|
901
1417
|
...metering !== null ? { cliMetering: metering } : {}
|
|
902
1418
|
}, null, 2));
|
|
903
|
-
else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
|
|
904
|
-
return failed ? 1 : 0;
|
|
905
|
-
}
|
|
906
|
-
//#endregion
|
|
907
|
-
//#region src/
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
if ((await lstat(target)).isDirectory()) throw new CliError(`--out bir klasör: ${out}`);
|
|
912
|
-
if (!options.force) throw new CliError(`${out} zaten var; üzerine yazmak için --force (istek gönderilmedi)`);
|
|
913
|
-
} catch (error) {
|
|
914
|
-
if (error instanceof CliError) throw error;
|
|
915
|
-
if (errnoCode(error) !== "ENOENT") throw error;
|
|
916
|
-
}
|
|
917
|
-
const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
|
|
918
|
-
try {
|
|
919
|
-
await writeFile(temp, secret, {
|
|
920
|
-
mode: 384,
|
|
921
|
-
flag: "wx"
|
|
922
|
-
});
|
|
923
|
-
} catch (error) {
|
|
924
|
-
const code = errnoCode(error);
|
|
925
|
-
if (code === "ENOENT") throw new CliError(`--out klasörü yok: ${relative(cwd, dirname(target)) || "."}`);
|
|
926
|
-
throw new CliError(`sır dosyası yazılamadı (${code ?? "hata"}): ${out} (istek gönderilmedi)`);
|
|
927
|
-
}
|
|
928
|
-
let value;
|
|
929
|
-
try {
|
|
930
|
-
value = await action();
|
|
931
|
-
} catch (error) {
|
|
932
|
-
await unlink(temp).catch(() => {});
|
|
933
|
-
throw error;
|
|
934
|
-
}
|
|
935
|
-
try {
|
|
936
|
-
if (options.force) await rename(temp, target);
|
|
937
|
-
else {
|
|
938
|
-
await link(temp, target);
|
|
939
|
-
await unlink(temp).catch(() => {});
|
|
940
|
-
}
|
|
941
|
-
return {
|
|
942
|
-
value,
|
|
943
|
-
path: out,
|
|
944
|
-
fallback: false
|
|
945
|
-
};
|
|
946
|
-
} catch {
|
|
947
|
-
return {
|
|
948
|
-
value,
|
|
949
|
-
path: relative(cwd, temp),
|
|
950
|
-
fallback: true
|
|
951
|
-
};
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
//#endregion
|
|
955
|
-
//#region src/commands/endpoints.ts
|
|
956
|
-
const ENDPOINTS_USAGE = `Kullanım:
|
|
957
|
-
steward endpoints list [--json]
|
|
958
|
-
steward endpoints add --url <url> --out <dosya> [--event-types <a,b>] [--description <metin>] [--force]
|
|
959
|
-
steward endpoints rotate <id> --out <dosya> [--force]
|
|
960
|
-
steward endpoints deactivate <id>
|
|
1419
|
+
else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
|
|
1420
|
+
return failed ? 1 : 0;
|
|
1421
|
+
}
|
|
1422
|
+
//#endregion
|
|
1423
|
+
//#region src/commands/dunning.ts
|
|
1424
|
+
const DUNNING_USAGE = `Usage:
|
|
1425
|
+
steward dunning get [--json]
|
|
1426
|
+
steward dunning set <policy.json> [--yes]
|
|
961
1427
|
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
1428
|
+
The product's dunning policy (/v1/admin/dunning-policy): what steward does after a renewal is
|
|
1429
|
+
not paid, by days since dunning started. Steps run in order:
|
|
1430
|
+
{"steps":[{"afterDays":1,"action":"retry_payment"},{"afterDays":7,"action":"suspend"},
|
|
1431
|
+
{"afterDays":30,"action":"terminate"}],"dryRun":false}
|
|
1432
|
+
retry_payment sends a payment reminder, suspend and terminate change the subscription.
|
|
1433
|
+
With "dryRun": true (the default) steps are only audited. Turning dryRun off needs
|
|
1434
|
+
confirmation (a prompt on a terminal, otherwise --yes): customers will be suspended.
|
|
969
1435
|
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
}
|
|
974
|
-
const lastDeliveryText = (endpoint) => {
|
|
975
|
-
const last = endpoint.lastDelivery;
|
|
976
|
-
if (last === null) return "-";
|
|
977
|
-
return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
|
|
978
|
-
};
|
|
979
|
-
function table(rows) {
|
|
980
|
-
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
|
|
981
|
-
return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
|
|
982
|
-
}
|
|
983
|
-
const typesText = (endpoint) => endpoint.eventTypes === null ? "(filtre yok: 0.1 tipleri)" : endpoint.eventTypes.join(",");
|
|
984
|
-
async function endpointsCommand(ctx, out, args) {
|
|
1436
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
1437
|
+
const policyLines = (policy) => [...policy.steps.map((step) => ` day ${String(step.afterDays).padStart(3)} ${step.action}`), ` dry run ${policy.dryRun ? "yes (steps are only audited)" : "no"}`];
|
|
1438
|
+
async function dunningCommand(ctx, out, args) {
|
|
985
1439
|
const [sub, ...rest] = args;
|
|
986
1440
|
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
987
|
-
out.out(
|
|
1441
|
+
out.out(DUNNING_USAGE);
|
|
988
1442
|
return sub === void 0 ? 2 : 0;
|
|
989
1443
|
}
|
|
990
|
-
if (sub === "
|
|
1444
|
+
if (sub === "get") {
|
|
991
1445
|
const { values, positionals } = parse(rest, {
|
|
992
1446
|
...HELP_OPTION,
|
|
993
1447
|
json: { type: "boolean" }
|
|
994
|
-
}, "
|
|
995
|
-
if (values.help) return help(out);
|
|
996
|
-
expectPositionals(positionals, 0, 0, "
|
|
997
|
-
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
998
|
-
out.err(connectionLine(target));
|
|
999
|
-
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
|
|
1000
|
-
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
1001
|
-
else if (items.length === 0) out.out("endpoint yok — steward endpoints add --url <url> --out <dosya>");
|
|
1002
|
-
else {
|
|
1003
|
-
const rows = [[
|
|
1004
|
-
"ID",
|
|
1005
|
-
"DURUM",
|
|
1006
|
-
"OLAYLAR",
|
|
1007
|
-
"SON TESLİMAT",
|
|
1008
|
-
"URL"
|
|
1009
|
-
]];
|
|
1010
|
-
for (const e of items) rows.push([
|
|
1011
|
-
e.id,
|
|
1012
|
-
e.status,
|
|
1013
|
-
typesText(e),
|
|
1014
|
-
lastDeliveryText(e),
|
|
1015
|
-
e.description !== null ? `${e.url} (${e.description})` : e.url
|
|
1016
|
-
]);
|
|
1017
|
-
for (const line of table(rows)) out.out(line);
|
|
1018
|
-
}
|
|
1019
|
-
return 0;
|
|
1020
|
-
}
|
|
1021
|
-
if (sub === "add") {
|
|
1022
|
-
const { values, positionals } = parse(rest, {
|
|
1023
|
-
...HELP_OPTION,
|
|
1024
|
-
url: { type: "string" },
|
|
1025
|
-
out: { type: "string" },
|
|
1026
|
-
"event-types": { type: "string" },
|
|
1027
|
-
description: { type: "string" },
|
|
1028
|
-
force: { type: "boolean" }
|
|
1029
|
-
}, ENDPOINTS_USAGE);
|
|
1030
|
-
if (values.help) return help(out);
|
|
1031
|
-
expectPositionals(positionals, 0, 0, "endpoints");
|
|
1032
|
-
const url = requireOption(values.url, "--url", "endpoints");
|
|
1033
|
-
const file = requireOption(values.out, "--out", "endpoints");
|
|
1034
|
-
const secret = generateWebhookSecret();
|
|
1035
|
-
const input = {
|
|
1036
|
-
url,
|
|
1037
|
-
secret,
|
|
1038
|
-
...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
|
|
1039
|
-
...values.description !== void 0 ? { description: values.description } : {}
|
|
1040
|
-
};
|
|
1041
|
-
const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
|
|
1042
|
-
if (!parsed.success) throw new UsageError(`endpoint geçersiz (istek gönderilmedi)\n${schemaProblems(parsed.error.issues)}`);
|
|
1448
|
+
}, "dunning");
|
|
1449
|
+
if (values.help) return help$1(out);
|
|
1450
|
+
expectPositionals(positionals, 0, 0, "dunning");
|
|
1043
1451
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1044
1452
|
out.err(connectionLine(target));
|
|
1045
|
-
const
|
|
1046
|
-
|
|
1047
|
-
const
|
|
1048
|
-
out.out(`endpoint oluşturuldu → ${originOf(target.url)}`);
|
|
1049
|
-
out.out(` id ${endpoint.id}`);
|
|
1050
|
-
out.out(` url ${endpoint.url}`);
|
|
1051
|
-
out.out(` olaylar ${typesText(endpoint)}`);
|
|
1052
|
-
secretNotice(out, result.path, result.fallback, "Sırrı ürünün Secret'ına (STEWARD_WEBHOOK_SECRET) taşıyın, sonra dosyayı silin.");
|
|
1453
|
+
const policy = await callSteward(target, () => clientFor(ctx, target).admin.dunning.get());
|
|
1454
|
+
if (values.json) out.out(JSON.stringify(policy, null, 2));
|
|
1455
|
+
else for (const line of policyLines(policy)) out.out(line);
|
|
1053
1456
|
return 0;
|
|
1054
1457
|
}
|
|
1055
|
-
if (sub === "
|
|
1458
|
+
if (sub === "set") {
|
|
1056
1459
|
const { values, positionals } = parse(rest, {
|
|
1057
1460
|
...HELP_OPTION,
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
const
|
|
1066
|
-
|
|
1067
|
-
|
|
1461
|
+
yes: {
|
|
1462
|
+
type: "boolean",
|
|
1463
|
+
short: "y"
|
|
1464
|
+
}
|
|
1465
|
+
}, "dunning");
|
|
1466
|
+
if (values.help) return help$1(out);
|
|
1467
|
+
expectPositionals(positionals, 1, 1, "dunning");
|
|
1468
|
+
const file = positionals[0];
|
|
1469
|
+
let json;
|
|
1470
|
+
try {
|
|
1471
|
+
json = JSON.parse(await readFile(resolve(ctx.cwd, file), "utf8"));
|
|
1472
|
+
} catch (error) {
|
|
1473
|
+
throw new CliError(`cannot read ${file}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1474
|
+
}
|
|
1475
|
+
const parsed = DunningPolicySchema.strict().safeParse(json);
|
|
1476
|
+
if (!parsed.success) throw new UsageError(`invalid policy (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
1477
|
+
const policy = parsed.data;
|
|
1068
1478
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1069
1479
|
out.err(connectionLine(target));
|
|
1070
1480
|
const steward = clientFor(ctx, target);
|
|
1071
|
-
const
|
|
1072
|
-
out.out(
|
|
1073
|
-
out.out(
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
out.out(`endpoint pasifleştirildi → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, durum ${endpoint.status})`);
|
|
1481
|
+
const current = await callSteward(target, () => steward.admin.dunning.get());
|
|
1482
|
+
out.out("new policy:");
|
|
1483
|
+
for (const line of policyLines(policy)) out.out(line);
|
|
1484
|
+
if (current.dryRun && !policy.dryRun) {
|
|
1485
|
+
if (!await confirm(ctx, "This turns dry run off: suspend and terminate steps will change subscriptions. Continue?", {
|
|
1486
|
+
yes: values.yes === true,
|
|
1487
|
+
notConfirmed: "the policy was not changed"
|
|
1488
|
+
})) {
|
|
1489
|
+
out.err("not confirmed; the policy was not changed");
|
|
1490
|
+
return 1;
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
const stored = await callSteward(target, () => steward.admin.dunning.set(policy));
|
|
1494
|
+
out.out(`policy stored → ${originOf(target.url)} (${stored.steps.length} step${stored.steps.length === 1 ? "" : "s"})`);
|
|
1086
1495
|
return 0;
|
|
1087
1496
|
}
|
|
1088
|
-
throw new UsageError(`
|
|
1497
|
+
throw new UsageError(`unknown subcommand: dunning ${sub} (see: steward dunning --help)`);
|
|
1089
1498
|
}
|
|
1090
|
-
function help(out) {
|
|
1091
|
-
out.out(
|
|
1499
|
+
function help$1(out) {
|
|
1500
|
+
out.out(DUNNING_USAGE);
|
|
1092
1501
|
return 0;
|
|
1093
1502
|
}
|
|
1094
|
-
function secretNotice(out, path, fallback, next) {
|
|
1095
|
-
if (fallback) {
|
|
1096
|
-
out.err(`! sır hedef dosyaya taşınamadı (arada oluşturulmuş olabilir); sır ${path} dosyasında (0600)`);
|
|
1097
|
-
out.out(` sır ${path} (0600; terminale yazılmadı)`);
|
|
1098
|
-
} else out.out(` sır ${path} (0600; terminale yazılmadı)`);
|
|
1099
|
-
out.err(next);
|
|
1100
|
-
}
|
|
1101
1503
|
//#endregion
|
|
1102
1504
|
//#region src/commands/events.ts
|
|
1103
|
-
const EVENTS_USAGE = `Usage:
|
|
1104
|
-
|
|
1505
|
+
const EVENTS_USAGE = `Usage:
|
|
1506
|
+
steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
|
|
1507
|
+
[--timestamp <iso>] [--json]
|
|
1508
|
+
steward events redeliver <eventId> [<eventId>…]
|
|
1105
1509
|
|
|
1106
1510
|
Sends one event for account <ref> (POST /v1/events/ingest), e.g. to try a meter locally.
|
|
1107
1511
|
The event itself has no billing meaning: it counts as usage for the meters whose filter
|
|
@@ -1121,7 +1525,12 @@ Metadata must not carry personal data (names, e-mail addresses, phone numbers):
|
|
|
1121
1525
|
|
|
1122
1526
|
Connection: STEWARD_URL + STEWARD_API_KEY (or, when neither is set, STEWARD_ADMIN_URL +
|
|
1123
1527
|
STEWARD_ADMIN_API_KEY). Sent with X-Actor-Ref operator:<user>.
|
|
1124
|
-
Exit code 1: the event was rejected (unknown or deleted account, timestamp out of range)
|
|
1528
|
+
Exit code 1: the event was rejected (unknown or deleted account, timestamp out of range).
|
|
1529
|
+
|
|
1530
|
+
redeliver (admin; STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY): requeues every delivery of a
|
|
1531
|
+
webhook event (evt_…; dead ones included) with attempts reset, after the receiver's problem is
|
|
1532
|
+
fixed. The dispatcher sends it on its next tick; an account's older events go first. When only
|
|
1533
|
+
the current state matters, the product calls POST /v1/accounts/:ref/resync instead.`;
|
|
1125
1534
|
const SEND_OPTIONS = {
|
|
1126
1535
|
...HELP_OPTION,
|
|
1127
1536
|
meta: {
|
|
@@ -1164,6 +1573,7 @@ async function eventsCommand(ctx, out, args) {
|
|
|
1164
1573
|
out.out(EVENTS_USAGE);
|
|
1165
1574
|
return sub === void 0 ? 2 : 0;
|
|
1166
1575
|
}
|
|
1576
|
+
if (sub === "redeliver") return redeliverCommand(ctx, out, rest);
|
|
1167
1577
|
if (sub !== "send") throw new UsageError(`unknown subcommand: events ${sub} (see: steward events --help)`);
|
|
1168
1578
|
const { values, positionals } = parse(rest, SEND_OPTIONS, "events");
|
|
1169
1579
|
if (values.help) {
|
|
@@ -1201,82 +1611,231 @@ async function eventsCommand(ctx, out, args) {
|
|
|
1201
1611
|
}
|
|
1202
1612
|
return 0;
|
|
1203
1613
|
}
|
|
1614
|
+
async function redeliverCommand(ctx, out, args) {
|
|
1615
|
+
const { values, positionals } = parse(args, { ...HELP_OPTION }, "events");
|
|
1616
|
+
if (values.help) {
|
|
1617
|
+
out.out(EVENTS_USAGE);
|
|
1618
|
+
return 0;
|
|
1619
|
+
}
|
|
1620
|
+
expectPositionals(positionals, 1, 100, "events");
|
|
1621
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1622
|
+
out.err(connectionLine(target));
|
|
1623
|
+
const steward = clientFor(ctx, target);
|
|
1624
|
+
for (const eventId of positionals) {
|
|
1625
|
+
const result = await callSteward(target, () => steward.admin.events.redeliver(eventId));
|
|
1626
|
+
out.out(`${result.eventId} (${result.type}): ${result.deliveries.length} deliver${result.deliveries.length === 1 ? "y" : "ies"} requeued`);
|
|
1627
|
+
}
|
|
1628
|
+
return 0;
|
|
1629
|
+
}
|
|
1204
1630
|
//#endregion
|
|
1205
|
-
//#region src/commands/
|
|
1206
|
-
const
|
|
1631
|
+
//#region src/commands/keys.ts
|
|
1632
|
+
const KEYS_USAGE = `Usage:
|
|
1633
|
+
steward keys list [--json]
|
|
1634
|
+
steward keys create --name <name> --scope product|checkout|admin --out <file>
|
|
1635
|
+
[--expires-days <n> | --no-expiry] [--force]
|
|
1636
|
+
steward keys revoke <prefix>
|
|
1207
1637
|
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1638
|
+
The product's API keys (/v1/admin/api-keys). The key (stw_…) is generated on this machine and
|
|
1639
|
+
written ONLY to the --out file (0600, no trailing newline): never to the terminal, and steward
|
|
1640
|
+
never returns it. If the file exists, nothing is sent without --force. Move the key into the
|
|
1641
|
+
product's Secret (the CLI does not call kubectl), then delete the file.
|
|
1211
1642
|
|
|
1212
|
-
--
|
|
1213
|
-
|
|
1643
|
+
--scope product: the product's backend; checkout: its web app (checkout, portal,
|
|
1644
|
+
state only); admin: these management commands
|
|
1645
|
+
--expires-days days until the key stops working (1–3650). Default: admin keys 90 days,
|
|
1646
|
+
other keys never. --no-expiry: never (not allowed for an admin key)
|
|
1214
1647
|
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
const included = meter.includedUnits === null ? "no credit included" : `included ${formatUnitsText(meter.includedUnits)} per period`;
|
|
1231
|
-
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)";
|
|
1232
|
-
lines.push(`${indent}${included} · ${billing}`);
|
|
1233
|
-
return lines;
|
|
1234
|
-
}
|
|
1235
|
-
/** Human-readable meter read (+ closed periods, newest first). */
|
|
1236
|
-
function formatMeters(meters, periods) {
|
|
1237
|
-
const lines = [`meters of ${meters.ref} · as of ${meters.asOf} · events received before ${meters.rolledUpThrough} are counted`];
|
|
1238
|
-
const codes = Object.keys(meters.meters);
|
|
1239
|
-
if (codes.length === 0) lines.push(" no meters (the product's catalog defines none)");
|
|
1240
|
-
else {
|
|
1241
|
-
const width = Math.max(...codes.map((code) => code.length));
|
|
1242
|
-
for (const code of codes) lines.push(...meterLines(code, meters.meters[code], width));
|
|
1648
|
+
revoke takes the 12 hex characters after stw_ (keys list). A key cannot revoke itself: revoke
|
|
1649
|
+
the key you are using with another admin key or the pod CLI.
|
|
1650
|
+
|
|
1651
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
1652
|
+
const SCOPES = [
|
|
1653
|
+
"product",
|
|
1654
|
+
"checkout",
|
|
1655
|
+
"admin"
|
|
1656
|
+
];
|
|
1657
|
+
const keyStatus = (key, now = Date.now()) => key.revokedAt !== null ? "revoked" : key.expiresAt !== null && Date.parse(key.expiresAt) <= now ? "expired" : "active";
|
|
1658
|
+
async function keysCommand(ctx, out, args) {
|
|
1659
|
+
const [sub, ...rest] = args;
|
|
1660
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
1661
|
+
out.out(KEYS_USAGE);
|
|
1662
|
+
return sub === void 0 ? 2 : 0;
|
|
1243
1663
|
}
|
|
1244
|
-
if (
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1664
|
+
if (sub === "list") {
|
|
1665
|
+
const { values, positionals } = parse(rest, {
|
|
1666
|
+
...HELP_OPTION,
|
|
1667
|
+
json: { type: "boolean" }
|
|
1668
|
+
}, "keys");
|
|
1669
|
+
if (values.help) return help(out);
|
|
1670
|
+
expectPositionals(positionals, 0, 0, "keys");
|
|
1671
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1672
|
+
out.err(connectionLine(target));
|
|
1673
|
+
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.apiKeys.list());
|
|
1674
|
+
if (values.json) {
|
|
1675
|
+
out.out(JSON.stringify(items, null, 2));
|
|
1676
|
+
return 0;
|
|
1251
1677
|
}
|
|
1678
|
+
const rows = [[
|
|
1679
|
+
"PREFIX",
|
|
1680
|
+
"SCOPE",
|
|
1681
|
+
"STATUS",
|
|
1682
|
+
"EXPIRES",
|
|
1683
|
+
"LAST USED",
|
|
1684
|
+
"NAME"
|
|
1685
|
+
]];
|
|
1686
|
+
for (const k of items) rows.push([
|
|
1687
|
+
k.prefix,
|
|
1688
|
+
k.scope,
|
|
1689
|
+
keyStatus(k),
|
|
1690
|
+
k.expiresAt ?? "never",
|
|
1691
|
+
k.lastUsedAt ?? "-",
|
|
1692
|
+
k.name
|
|
1693
|
+
]);
|
|
1694
|
+
for (const line of table(rows)) out.out(line);
|
|
1695
|
+
return 0;
|
|
1696
|
+
}
|
|
1697
|
+
if (sub === "create") {
|
|
1698
|
+
const { values, positionals } = parse(rest, {
|
|
1699
|
+
...HELP_OPTION,
|
|
1700
|
+
name: { type: "string" },
|
|
1701
|
+
scope: { type: "string" },
|
|
1702
|
+
out: { type: "string" },
|
|
1703
|
+
"expires-days": { type: "string" },
|
|
1704
|
+
"no-expiry": { type: "boolean" },
|
|
1705
|
+
force: { type: "boolean" }
|
|
1706
|
+
}, "keys");
|
|
1707
|
+
if (values.help) return help(out);
|
|
1708
|
+
expectPositionals(positionals, 0, 0, "keys");
|
|
1709
|
+
const name = requireOption(values.name, "--name", "keys");
|
|
1710
|
+
const scope = requireOption(values.scope, "--scope", "keys");
|
|
1711
|
+
if (!SCOPES.includes(scope)) throw new UsageError(`--scope: one of ${SCOPES.join(", ")}`);
|
|
1712
|
+
const file = requireOption(values.out, "--out", "keys");
|
|
1713
|
+
if (values["expires-days"] !== void 0 && values["no-expiry"]) throw new UsageError("--expires-days and --no-expiry are mutually exclusive");
|
|
1714
|
+
const token = generateApiKeyToken();
|
|
1715
|
+
const input = {
|
|
1716
|
+
token,
|
|
1717
|
+
name,
|
|
1718
|
+
scope,
|
|
1719
|
+
...values["expires-days"] !== void 0 ? { expiresInDays: parsePositiveInt(values["expires-days"], "--expires-days", { max: 3650 }) } : {},
|
|
1720
|
+
...values["no-expiry"] ? { expiresInDays: null } : {}
|
|
1721
|
+
};
|
|
1722
|
+
const parsed = ApiKeyCreateInputSchema.safeParse(input);
|
|
1723
|
+
if (!parsed.success) throw new UsageError(`invalid key (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
1724
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1725
|
+
out.err(connectionLine(target));
|
|
1726
|
+
const steward = clientFor(ctx, target);
|
|
1727
|
+
const result = await withSecretFile(ctx.cwd, file, token, { force: values.force === true }, () => callSteward(target, () => steward.admin.apiKeys.create(input)));
|
|
1728
|
+
const key = result.value;
|
|
1729
|
+
out.out(`key created → ${originOf(target.url)}`);
|
|
1730
|
+
out.out(` prefix ${key.prefix}`);
|
|
1731
|
+
out.out(` scope ${key.scope}`);
|
|
1732
|
+
out.out(` expires ${key.expiresAt ?? "never"}`);
|
|
1733
|
+
secretNotice(out, result.path, result.fallback, "Move the key into the product's Secret, then delete the file.");
|
|
1734
|
+
return 0;
|
|
1735
|
+
}
|
|
1736
|
+
if (sub === "revoke") {
|
|
1737
|
+
const { values, positionals } = parse(rest, { ...HELP_OPTION }, "keys");
|
|
1738
|
+
if (values.help) return help(out);
|
|
1739
|
+
expectPositionals(positionals, 1, 1, "keys");
|
|
1740
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1741
|
+
out.err(connectionLine(target));
|
|
1742
|
+
const key = await callSteward(target, () => clientFor(ctx, target).admin.apiKeys.revoke(positionals[0]));
|
|
1743
|
+
out.out(`key revoked → ${originOf(target.url)}: ${key.prefix} (${key.scope}, ${key.name})`);
|
|
1744
|
+
return 0;
|
|
1252
1745
|
}
|
|
1746
|
+
throw new UsageError(`unknown subcommand: keys ${sub} (see: steward keys --help)`);
|
|
1747
|
+
}
|
|
1748
|
+
function help(out) {
|
|
1749
|
+
out.out(KEYS_USAGE);
|
|
1750
|
+
return 0;
|
|
1751
|
+
}
|
|
1752
|
+
//#endregion
|
|
1753
|
+
//#region src/commands/reprice.ts
|
|
1754
|
+
const REPRICE_USAGE = `Usage: steward reprice --plan <code> --notice-days <n> [--dry-run] [--yes] [--json]
|
|
1755
|
+
|
|
1756
|
+
Moves the live subscriptions of a plan to the plan's current price and metered rates
|
|
1757
|
+
(POST /v1/admin/subscriptions/reprice): each one changes from its first period boundary at
|
|
1758
|
+
least <n> days away (0–3650) and gets one price change notice e-mail. Subscribers otherwise
|
|
1759
|
+
keep the amount they locked at checkout.
|
|
1760
|
+
|
|
1761
|
+
The command always lists first (a dry run: nothing written, no e-mail). Without --dry-run it
|
|
1762
|
+
then asks for confirmation (a prompt on a terminal, otherwise --yes) and runs it for real.
|
|
1763
|
+
Running it again is safe: an already scheduled subscription gets no second notice.
|
|
1764
|
+
|
|
1765
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
1766
|
+
const OPTIONS = {
|
|
1767
|
+
...HELP_OPTION,
|
|
1768
|
+
plan: { type: "string" },
|
|
1769
|
+
"notice-days": { type: "string" },
|
|
1770
|
+
"dry-run": { type: "boolean" },
|
|
1771
|
+
yes: {
|
|
1772
|
+
type: "boolean",
|
|
1773
|
+
short: "y"
|
|
1774
|
+
},
|
|
1775
|
+
json: { type: "boolean" }
|
|
1776
|
+
};
|
|
1777
|
+
function summary(result) {
|
|
1778
|
+
const count = (action) => result.items.filter((item) => item.action === action).length;
|
|
1779
|
+
const lines = result.items.map((item) => {
|
|
1780
|
+
const amounts = `${formatMinor(item.oldAmountMinor, item.currency)} → ${formatMinor(item.newAmountMinor, item.currency)}`;
|
|
1781
|
+
const rates = item.meteredRates?.length ? ` (+${item.meteredRates.length} metered rate${item.meteredRates.length === 1 ? "" : "s"})` : "";
|
|
1782
|
+
const when = item.action === "skip" ? `skip: ${item.reason ?? "-"}` : `${item.action} from ${item.effectiveAt}`;
|
|
1783
|
+
return ` ${item.accountRef} ${item.interval} ${amounts}${rates} ${when}`;
|
|
1784
|
+
});
|
|
1785
|
+
lines.push(`${count("schedule")} to schedule, ${count("already_scheduled")} already scheduled, ${count("skip")} skipped; effective not before ${result.effectiveNotBefore}`);
|
|
1253
1786
|
return lines;
|
|
1254
1787
|
}
|
|
1255
|
-
async function
|
|
1256
|
-
const
|
|
1257
|
-
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
1258
|
-
out.out(METERS_USAGE);
|
|
1259
|
-
return sub === void 0 ? 2 : 0;
|
|
1260
|
-
}
|
|
1261
|
-
if (sub !== "get") throw new UsageError(`unknown subcommand: meters ${sub} (see: steward meters --help)`);
|
|
1262
|
-
const { values, positionals } = parse(rest, GET_OPTIONS, "meters");
|
|
1788
|
+
async function repriceCommand(ctx, out, args) {
|
|
1789
|
+
const { values, positionals } = parse(args, OPTIONS, "reprice");
|
|
1263
1790
|
if (values.help) {
|
|
1264
|
-
out.out(
|
|
1791
|
+
out.out(REPRICE_USAGE);
|
|
1265
1792
|
return 0;
|
|
1266
1793
|
}
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1794
|
+
if (args.length === 0) {
|
|
1795
|
+
out.out(REPRICE_USAGE);
|
|
1796
|
+
return 2;
|
|
1797
|
+
}
|
|
1798
|
+
expectPositionals(positionals, 0, 0, "reprice");
|
|
1799
|
+
const input = {
|
|
1800
|
+
planCode: requireOption(values.plan, "--plan", "reprice"),
|
|
1801
|
+
noticeDays: parseNonNegativeInt(requireOption(values["notice-days"], "--notice-days", "reprice"), "--notice-days")
|
|
1802
|
+
};
|
|
1803
|
+
const checked = RepriceInputSchema.safeParse({
|
|
1804
|
+
...input,
|
|
1805
|
+
dryRun: true
|
|
1806
|
+
});
|
|
1807
|
+
if (!checked.success) throw new UsageError(`invalid request (nothing was sent)\n${checked.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
1808
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1271
1809
|
out.err(connectionLine(target));
|
|
1272
1810
|
const steward = clientFor(ctx, target);
|
|
1273
|
-
const
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1811
|
+
const preview = await callSteward(target, () => steward.admin.subscriptions.reprice({
|
|
1812
|
+
...input,
|
|
1813
|
+
dryRun: true
|
|
1814
|
+
}));
|
|
1815
|
+
if (values["dry-run"]) {
|
|
1816
|
+
if (values.json) out.out(JSON.stringify(preview, null, 2));
|
|
1817
|
+
else for (const line of ["dry run (nothing written):", ...summary(preview)]) out.out(line);
|
|
1818
|
+
return 0;
|
|
1819
|
+
}
|
|
1820
|
+
if (!values.json) for (const line of ["dry run:", ...summary(preview)]) out.out(line);
|
|
1821
|
+
const toSchedule = preview.items.filter((item) => item.action === "schedule").length;
|
|
1822
|
+
if (toSchedule === 0) {
|
|
1823
|
+
out.out("nothing to schedule");
|
|
1824
|
+
return 0;
|
|
1825
|
+
}
|
|
1826
|
+
if (!await confirm(ctx, `Schedule ${toSchedule} subscription${toSchedule === 1 ? "" : "s"} and send the notice e-mails?`, {
|
|
1827
|
+
yes: values.yes === true,
|
|
1828
|
+
notConfirmed: "nothing was scheduled"
|
|
1829
|
+
})) {
|
|
1830
|
+
out.err("not confirmed; nothing was scheduled");
|
|
1831
|
+
return 1;
|
|
1832
|
+
}
|
|
1833
|
+
const result = await callSteward(target, () => steward.admin.subscriptions.reprice({
|
|
1834
|
+
...input,
|
|
1835
|
+
dryRun: false
|
|
1836
|
+
}));
|
|
1837
|
+
if (values.json) out.out(JSON.stringify(result, null, 2));
|
|
1838
|
+
else out.out(`scheduled → ${originOf(target.url)}: ${result.scheduled} subscription${result.scheduled === 1 ? "" : "s"} (one notice e-mail each)`);
|
|
1280
1839
|
return 0;
|
|
1281
1840
|
}
|
|
1282
1841
|
//#endregion
|
|
@@ -1291,6 +1850,7 @@ const SETTINGS_USAGE = `Kullanım:
|
|
|
1291
1850
|
[--billing-allow-multiple-subscriptions true|false]
|
|
1292
1851
|
[--metering-charge-mode off|dry_run|live]
|
|
1293
1852
|
[--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]
|
|
1853
|
+
[--provider <id>]
|
|
1294
1854
|
|
|
1295
1855
|
Ürün ayarları (GET/PATCH /v1/admin/settings). Verilmeyen alan değişmez; boş değer
|
|
1296
1856
|
(--privacy-url "") alanı temizler, --branding null markayı temizler, --branding
|
|
@@ -1311,6 +1871,8 @@ it, live adds it to the renewal invoice, off prices nothing — run one full cyc
|
|
|
1311
1871
|
dry_run before live. --metering-late-grace-minutes how long a period waits for late
|
|
1312
1872
|
events before it closes (default 60). --events-retention-days how long raw events are
|
|
1313
1873
|
kept after receipt, once their period is closed (default 120). "" restores the default.
|
|
1874
|
+
--provider sets the payment provider for NEW checkouts and payment sessions (open ones keep
|
|
1875
|
+
theirs); steward accepts only a provider configured in its deployment (iyzico, fake…).
|
|
1314
1876
|
|
|
1315
1877
|
Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
|
|
1316
1878
|
const SET_OPTIONS = {
|
|
@@ -1329,7 +1891,8 @@ const SET_OPTIONS = {
|
|
|
1329
1891
|
"billing-allow-multiple-subscriptions": { type: "string" },
|
|
1330
1892
|
"metering-charge-mode": { type: "string" },
|
|
1331
1893
|
"metering-late-grace-minutes": { type: "string" },
|
|
1332
|
-
"events-retention-days": { type: "string" }
|
|
1894
|
+
"events-retention-days": { type: "string" },
|
|
1895
|
+
provider: { type: "string" }
|
|
1333
1896
|
};
|
|
1334
1897
|
const orNull = (value) => value.trim() === "" ? null : value.trim();
|
|
1335
1898
|
/** Bayraklardan yama; sözleşme şemasıyla doğrulanır (geçersizse istek gönderilmez). */
|
|
@@ -1367,6 +1930,7 @@ function buildSettingsPatch(values) {
|
|
|
1367
1930
|
}
|
|
1368
1931
|
}
|
|
1369
1932
|
if (values["default-locale"] !== void 0) patch.defaultLocale = values["default-locale"].trim();
|
|
1933
|
+
if (values.provider !== void 0) patch.provider = values.provider.trim();
|
|
1370
1934
|
if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
|
|
1371
1935
|
if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
|
|
1372
1936
|
if (values["extra-return-origins"] !== void 0) patch.extraReturnOrigins = parseList(values["extra-return-origins"]);
|
|
@@ -1435,7 +1999,7 @@ async function settingsCommand(ctx, out, args) {
|
|
|
1435
1999
|
}
|
|
1436
2000
|
//#endregion
|
|
1437
2001
|
//#region src/main.ts
|
|
1438
|
-
const CLI_VERSION = "0.
|
|
2002
|
+
const CLI_VERSION = "0.7.0";
|
|
1439
2003
|
const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
|
|
1440
2004
|
|
|
1441
2005
|
Kullanım: steward <komut> [seçenekler]
|
|
@@ -1445,8 +2009,13 @@ Komutlar:
|
|
|
1445
2009
|
catalog push <dosya> [--yes] katalog senkronu (PUT /v1/admin/catalog)
|
|
1446
2010
|
settings get | set [bayraklar] ürün ayarları (/v1/admin/settings)
|
|
1447
2011
|
endpoints list | add | rotate | deactivate webhook endpoint'leri; sır yalnızca --out dosyasına
|
|
1448
|
-
|
|
1449
|
-
|
|
2012
|
+
keys list | create | revoke API keys; the key goes only to the --out file
|
|
2013
|
+
dunning get | set <policy.json> dunning policy (/v1/admin/dunning-policy)
|
|
2014
|
+
reprice --plan <code> --notice-days <n> move a plan's subscribers to its current price
|
|
2015
|
+
bank-transfers list | record bank transfer reconciliation (/v1/admin/bank-transfers)
|
|
2016
|
+
credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
|
|
2017
|
+
meters get | recompute | close-periods an account's meters; metering repairs (admin)
|
|
2018
|
+
events send | redeliver send one event; redeliver webhook events (admin)
|
|
1450
2019
|
|
|
1451
2020
|
Bağlantı: yönetim komutları STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY, doctor,
|
|
1452
2021
|
meters ve events STEWARD_URL + STEWARD_API_KEY (yoksa admin çifti). Ortamda bu dört değişkenden
|
|
@@ -1462,7 +2031,12 @@ const COMMANDS = {
|
|
|
1462
2031
|
settings: settingsCommand,
|
|
1463
2032
|
endpoints: endpointsCommand,
|
|
1464
2033
|
meters: metersCommand,
|
|
1465
|
-
events: eventsCommand
|
|
2034
|
+
events: eventsCommand,
|
|
2035
|
+
keys: keysCommand,
|
|
2036
|
+
dunning: dunningCommand,
|
|
2037
|
+
reprice: repriceCommand,
|
|
2038
|
+
"bank-transfers": bankTransfersCommand,
|
|
2039
|
+
credits: creditsCommand
|
|
1466
2040
|
};
|
|
1467
2041
|
async function main(argv, ctx) {
|
|
1468
2042
|
const out = createOutput(ctx.stdout, ctx.stderr);
|