@stewardhq/cli 0.1.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 +85 -0
  2. package/dist/bin.js +1462 -0
  3. package/package.json +43 -0
package/dist/bin.js ADDED
@@ -0,0 +1,1462 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { userInfo } from "node:os";
4
+ import { setTimeout } from "node:timers/promises";
5
+ import { CatalogSyncInputSchema, ProductSettingsPatchSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateWebhookSecret } from "@stewardhq/sdk";
6
+ import { parseArgs } from "node:util";
7
+ import { chmod, link, lstat, mkdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
8
+ import { basename, dirname, extname, join, relative, resolve } from "node:path";
9
+ import { pathToFileURL } from "node:url";
10
+ import { createHash, randomUUID } from "node:crypto";
11
+ //#region src/io.ts
12
+ const SECRET_PATTERN = /\b(whsec_|stw_)[A-Za-z0-9_\-+/=]+/g;
13
+ /** Sır biçimindeki değerleri maskeler (`whsec_***`). */
14
+ function redactSecrets(text) {
15
+ return text.replace(SECRET_PATTERN, "$1***");
16
+ }
17
+ function createOutput(stdout, stderr) {
18
+ return {
19
+ out: (line = "") => stdout.write(`${redactSecrets(line)}\n`),
20
+ err: (line = "") => stderr.write(`${redactSecrets(line)}\n`)
21
+ };
22
+ }
23
+ /** Kullanıcıya gösterilecek, yığın izi basılmayan hata. */
24
+ var CliError = class extends Error {
25
+ exitCode;
26
+ constructor(message, exitCode = 1) {
27
+ super(message);
28
+ this.name = "CliError";
29
+ this.exitCode = exitCode;
30
+ }
31
+ };
32
+ /** Yanlış kullanım (bilinmeyen bayrak, eksik argüman): çıkış kodu 2. */
33
+ var UsageError = class extends CliError {
34
+ constructor(message) {
35
+ super(message, 2);
36
+ this.name = "UsageError";
37
+ }
38
+ };
39
+ /** `node:fs` hatasının kodu (`ENOENT`…). */
40
+ function errnoCode(error) {
41
+ const code = typeof error === "object" && error !== null ? error.code : void 0;
42
+ return typeof code === "string" ? code : void 0;
43
+ }
44
+ //#endregion
45
+ //#region src/args.ts
46
+ const HELP_OPTION = { help: {
47
+ type: "boolean",
48
+ short: "h"
49
+ } };
50
+ const hint = (command) => ` (ayrıntı: steward ${command} --help)`;
51
+ /** `command`: hata mesajındaki yardım ipucu için komut adı (`endpoints`). */
52
+ function parse(args, options, command) {
53
+ try {
54
+ return parseArgs({
55
+ args: [...args],
56
+ options,
57
+ strict: true,
58
+ allowPositionals: true
59
+ });
60
+ } catch (error) {
61
+ throw new UsageError(`${error instanceof Error ? error.message : String(error)}${hint(command)}`);
62
+ }
63
+ }
64
+ /** Konumsal argüman sayısı `[min, max]` aralığında olmalı. */
65
+ function expectPositionals(positionals, min, max, command) {
66
+ if (positionals.length < min) throw new UsageError(`eksik argüman${hint(command)}`);
67
+ if (positionals.length > max) throw new UsageError(`beklenmeyen argüman: ${positionals.slice(max).join(" ")}${hint(command)}`);
68
+ }
69
+ function requireOption(value, flag, command) {
70
+ if (value === void 0 || value.trim() === "") throw new UsageError(`${flag} gerekli${hint(command)}`);
71
+ return value;
72
+ }
73
+ /** `a, b,,c` → `["a", "b", "c"]`. */
74
+ function parseList(value) {
75
+ return value.split(",").map((item) => item.trim()).filter((item) => item !== "");
76
+ }
77
+ /** Pozitif tam sayı (yalnızca rakam). */
78
+ function parsePositiveInt(value, flag, { max = Number.MAX_SAFE_INTEGER } = {}) {
79
+ const trimmed = value.trim();
80
+ const n = /^\d+$/.test(trimmed) ? Number(trimmed) : NaN;
81
+ if (!Number.isSafeInteger(n) || n < 1 || n > max) throw new UsageError(`${flag}: 1–${max} arası tam sayı olmalı`);
82
+ return n;
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;
95
+ }
96
+ //#endregion
97
+ //#region src/catalog-file.ts
98
+ const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
99
+ ".js",
100
+ ".mjs",
101
+ ".cjs"
102
+ ]);
103
+ const TS_EXTENSIONS = /* @__PURE__ */ new Set([
104
+ ".ts",
105
+ ".mts",
106
+ ".cts"
107
+ ]);
108
+ const hasSyncInput = (value) => typeof value === "object" && value !== null && typeof value.toSyncInput === "function";
109
+ function pickExport(mod, file) {
110
+ if (mod.catalog !== void 0) return mod.catalog;
111
+ if (mod.default !== void 0) return mod.default;
112
+ const candidates = Object.values(mod).filter(hasSyncInput);
113
+ if (candidates.length === 1) return candidates[0];
114
+ throw new CliError(`${file}: katalog bulunamadı — \`export const catalog = defineCatalog(…)\` ya da default export bekleniyor`);
115
+ }
116
+ async function loadCatalogFile(ctx, file) {
117
+ const path = resolve(ctx.cwd, file);
118
+ const ext = extname(path).toLowerCase();
119
+ let exported;
120
+ if (ext === ".json") {
121
+ let text;
122
+ try {
123
+ text = await readFile(path, "utf8");
124
+ } catch (error) {
125
+ throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
126
+ }
127
+ try {
128
+ exported = JSON.parse(text);
129
+ } catch {
130
+ throw new CliError(`${file}: geçerli JSON değil`);
131
+ }
132
+ } else if (MODULE_EXTENSIONS.has(ext) || TS_EXTENSIONS.has(ext)) {
133
+ 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.`);
134
+ let mod;
135
+ try {
136
+ await readFile(path);
137
+ } catch (error) {
138
+ throw new CliError(errnoCode(error) === "ENOENT" ? `katalog dosyası yok: ${file}` : `katalog dosyası okunamadı: ${file}`);
139
+ }
140
+ try {
141
+ mod = await ctx.importModule(pathToFileURL(path).href);
142
+ } catch (error) {
143
+ throw new CliError(`${file} yüklenemedi: ${error instanceof Error ? error.message : String(error)}`);
144
+ }
145
+ exported = pickExport(mod, file);
146
+ } else throw new UsageError(`katalog dosyası .ts, .mts, .js, .mjs, .cjs ya da .json olmalı: ${file}`);
147
+ let input;
148
+ try {
149
+ input = hasSyncInput(exported) ? exported.toSyncInput() : exported;
150
+ } catch (error) {
151
+ throw new CliError(`${file}: toSyncInput() hata verdi: ${error instanceof Error ? error.message : String(error)}`);
152
+ }
153
+ const parsed = CatalogSyncInputSchema.safeParse(input);
154
+ 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")}`);
155
+ return input;
156
+ }
157
+ //#endregion
158
+ //#region src/dotenv.ts
159
+ const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
160
+ function unquote(rest) {
161
+ const value = rest.trim();
162
+ const quote = value[0];
163
+ if (quote === "\"" || quote === "'" || quote === "`") {
164
+ const end = value.indexOf(quote, 1);
165
+ if (end > 0) {
166
+ const inner = value.slice(1, end);
167
+ return quote === "\"" ? inner.replace(/\\n/g, "\n") : inner;
168
+ }
169
+ }
170
+ const comment = value.search(/\s#/);
171
+ return (comment >= 0 ? value.slice(0, comment) : value).trim();
172
+ }
173
+ function parseDotenv(text) {
174
+ const values = /* @__PURE__ */ new Map();
175
+ for (const line of text.split(/\r?\n/)) {
176
+ const match = LINE.exec(line);
177
+ if (match) values.set(match[3], unquote(match[4]));
178
+ }
179
+ return values;
180
+ }
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
+ async function readDotenvFile(path) {
227
+ try {
228
+ return parseDotenv(await readFile(path, "utf8"));
229
+ } catch (error) {
230
+ if (errnoCode(error) === "ENOENT") return null;
231
+ throw error;
232
+ }
233
+ }
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
+ //#endregion
262
+ //#region src/env.ts
263
+ const ENV_LOCAL = ".env.local";
264
+ /** Biri bile süreç ortamındaysa `.env.local` okunmaz. */
265
+ const CONNECTION_VARIABLES = [
266
+ "STEWARD_URL",
267
+ "STEWARD_API_KEY",
268
+ "STEWARD_ADMIN_URL",
269
+ "STEWARD_ADMIN_API_KEY"
270
+ ];
271
+ const ADMIN_PAIR = {
272
+ url: "STEWARD_ADMIN_URL",
273
+ key: "STEWARD_ADMIN_API_KEY"
274
+ };
275
+ const PRODUCT_PAIR = {
276
+ url: "STEWARD_URL",
277
+ key: "STEWARD_API_KEY"
278
+ };
279
+ const clean = (value) => {
280
+ const text = value?.trim();
281
+ return text === void 0 || text === "" ? void 0 : text;
282
+ };
283
+ async function resolveEnv(ctx) {
284
+ const fromEnv = CONNECTION_VARIABLES.some((name) => clean(ctx.env[name]) !== void 0);
285
+ const local = fromEnv ? null : await readDotenvFile(join(ctx.cwd, ENV_LOCAL));
286
+ const source = local === null ? "ortam" : ".env.local";
287
+ const get = (name) => local === null ? clean(ctx.env[name]) : clean(local.get(name));
288
+ return {
289
+ source,
290
+ envLocal: fromEnv ? "skipped" : local === null ? "missing" : "read",
291
+ get,
292
+ pair: (names) => {
293
+ const url = get(names.url);
294
+ const apiKey = get(names.key);
295
+ if (url !== void 0 && apiKey !== void 0) return {
296
+ url,
297
+ apiKey,
298
+ source,
299
+ pair: names
300
+ };
301
+ const both = [names.url, names.key];
302
+ return {
303
+ missing: both.filter((name) => get(name) === void 0),
304
+ present: both.filter((name) => get(name) !== void 0)
305
+ };
306
+ }
307
+ };
308
+ }
309
+ function whereMissing(env) {
310
+ switch (env.envLocal) {
311
+ case "skipped": return `ortamda tanımlı değil (ortamda steward bağlantı değişkeni olduğu için ./${ENV_LOCAL} okunmadı; kaynaklar karıştırılmaz)`;
312
+ case "read": return `./${ENV_LOCAL}'de tanımlı değil (ortamda steward bağlantı değişkeni yok)`;
313
+ case "missing": return `tanımlı değil (ortam değişkeni ya da ./${ENV_LOCAL}; dosya yok)`;
314
+ }
315
+ }
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.";
317
+ function pairError(names, missing, env) {
318
+ return new CliError(`${names.url} + ${names.key} gerekli: ${missing.join(" ve ")} ${whereMissing(env)}.\n${ADMIN_HINT}`);
319
+ }
320
+ function requireAdminTarget(env) {
321
+ const pair = env.pair(ADMIN_PAIR);
322
+ if ("missing" in pair) throw pairError(ADMIN_PAIR, pair.missing, env);
323
+ return pair;
324
+ }
325
+ /** Ürün çifti; ikisi de tanımsızsa admin çifti (`GET /v1/doctor` ikisine de açık). Yarım çift hatadır. */
326
+ function requireReadTarget(env) {
327
+ const product = env.pair(PRODUCT_PAIR);
328
+ if (!("missing" in product)) return product;
329
+ if (product.present.length > 0) throw pairError(PRODUCT_PAIR, product.missing, env);
330
+ const admin = env.pair(ADMIN_PAIR);
331
+ if (!("missing" in admin)) return admin;
332
+ if (admin.present.length > 0) throw pairError(ADMIN_PAIR, admin.missing, env);
333
+ throw new CliError(`${PRODUCT_PAIR.url} + ${PRODUCT_PAIR.key} (ya da ${ADMIN_PAIR.url} + ${ADMIN_PAIR.key}) gerekli: ${whereMissing(env)}.\n${ADMIN_HINT}`);
334
+ }
335
+ /** Kullanılan kaynak, çift ve hedefin origin'i (stderr satırı; anahtar değeri yok). */
336
+ function connectionLine(target) {
337
+ return `bağlantı: ${target.source} · ${target.pair.url} + ${target.pair.key} → ${originOf(target.url)}`;
338
+ }
339
+ /** İşletim sistemi kullanıcı adından `operator:<ad>` (sözleşmenin `tür[:kimlik]` biçimi). */
340
+ function actorRefOf(username) {
341
+ const id = username.replace(/[^A-Za-z0-9_.@-]/g, "_").slice(0, 190);
342
+ return id === "" ? "operator" : `operator:${id}`;
343
+ }
344
+ /** Hedefin origin'i (kimlik bilgisi ve yol yazdırılmaz). */
345
+ function originOf(url) {
346
+ try {
347
+ return new URL(url).origin;
348
+ } catch {
349
+ return "(geçersiz adres)";
350
+ }
351
+ }
352
+ /**
353
+ * Hedefe bağlı istemci. Aynı URL/anahtar hem ürün hem admin tabanı olarak verilir:
354
+ * komut yalnızca hedefin kapsamına uygun metotları çağırır.
355
+ */
356
+ function clientFor(ctx, target, options = {}) {
357
+ return createSteward({
358
+ env: {},
359
+ baseUrl: target.url,
360
+ apiKey: target.apiKey,
361
+ adminBaseUrl: target.url,
362
+ adminApiKey: target.apiKey,
363
+ fetch: ctx.fetch,
364
+ actorRef: actorRefOf(ctx.username()),
365
+ timeoutMs: 6e4,
366
+ retries: options.retries === false ? { attempts: 0 } : { sleep: ctx.sleep }
367
+ });
368
+ }
369
+ /** Steward çağrısı: SDK hatası hedefin origin'iyle `CliError`'a çevrilir. */
370
+ async function callSteward(target, fn) {
371
+ try {
372
+ return await fn();
373
+ } catch (error) {
374
+ if (error instanceof StewardError) throw new CliError(describeStewardError(error, target));
375
+ throw error;
376
+ }
377
+ }
378
+ /** SDK hatasını tek satırlık kullanıcı mesajına çevirir (değer/anahtar içermez). */
379
+ function describeStewardError(error, target) {
380
+ const where = target ? ` (${originOf(target.url)})` : "";
381
+ 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ı?`;
383
+ if (error instanceof StewardConfigError) return `yapılandırma hatası: ${error.message}`;
384
+ 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" : "";
386
+ const message = error.message !== error.code ? `: ${error.message}` : "";
387
+ return `steward hatası${where}: ${error.code} (HTTP ${error.httpStatus})${message}${hint}${request}`;
388
+ }
389
+ return `steward yanıtı sözleşmeye uymuyor${where}: ${error.code} (HTTP ${error.httpStatus}) — CLI ile steward sürümleri uyumsuz olabilir${request}`;
390
+ }
391
+ //#endregion
392
+ //#region src/commands/catalog.ts
393
+ const CATALOG_USAGE = `Kullanım: steward catalog push <dosya>
394
+
395
+ Katalog tanımını steward'a senkronlar (PUT /v1/admin/catalog), sonra sürümü ve
396
+ sayıları yazar. Dosya: .ts/.mts (Node tip ayıklaması, Node ≥ 22.18), .js/.mjs/.cjs
397
+ (\`export const catalog = defineCatalog(…)\` ya da default export) veya .json
398
+ (senkron gövdesi). Geçersiz katalogda istek gönderilmez.
399
+
400
+ 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).`;
402
+ const list = (items) => items.length > 0 ? items.join(", ") : "-";
403
+ /** 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);
406
+ const result = await callSteward(target, () => steward.admin.catalog.sync(input));
407
+ const version = (await callSteward(target, () => steward.catalog.read())).etag?.replace(/^W\//, "").replace(/"/g, "") ?? "bilinmiyor";
408
+ const lines = [`katalog senkronlandı → ${originOf(target.url)}`];
409
+ 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}`);
411
+ 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" : ""}`);
413
+ for (const error of result.providerErrors) lines.push(` ✗ sağlayıcı hatası: fiyat ${error.priceId} (${error.provider}: ${error.code}) — senkronu yeniden koşun`);
414
+ return {
415
+ lines,
416
+ providerErrors: result.providerErrors.length
417
+ };
418
+ }
419
+ async function catalogCommand(ctx, out, args) {
420
+ const [sub, ...rest] = args;
421
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
422
+ out.out(CATALOG_USAGE);
423
+ return sub === void 0 ? 2 : 0;
424
+ }
425
+ 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");
427
+ if (values.help) {
428
+ out.out(CATALOG_USAGE);
429
+ return 0;
430
+ }
431
+ expectPositionals(positionals, 1, 1, "catalog push");
432
+ const input = await loadCatalogFile(ctx, positionals[0]);
433
+ const target = requireAdminTarget(await resolveEnv(ctx));
434
+ out.err(connectionLine(target));
435
+ const { lines, providerErrors } = await pushCatalog(ctx, target, input);
436
+ for (const line of lines) out.out(line);
437
+ return providerErrors > 0 ? 1 : 0;
438
+ }
439
+ const POSTGRES_IMAGE = "postgres:17.6-alpine";
440
+ const STATE_DIR = ".steward";
441
+ const COMPOSE_FILE = `${STATE_DIR}/compose.yml`;
442
+ const CREDENTIALS_FILE = `${STATE_DIR}/credentials.json`;
443
+ /** Servisin ürettiği dev şifreleme anahtarı (kimlik dosyasının yanında). */
444
+ const ENCRYPTION_KEY_FILE = `${STATE_DIR}/encryption-key`;
445
+ const CONTAINER_STATE_DIR = "/steward-dev";
446
+ const CONTAINER_PORT = 3002;
447
+ const STEWARD_SERVICE = "steward";
448
+ const PLACEHOLDER_TAG = "dev-unreleased";
449
+ /** İmaj referansı: etiket ya da digest zorunlu, `latest` ve yer tutucu reddedilir. */
450
+ function checkImage(image) {
451
+ const value = image.trim();
452
+ if (value === "" || /\s/.test(value)) throw new UsageError("--image: geçerli bir imaj referansı değil");
453
+ if (value.includes("@sha256:")) return value;
454
+ const lastSlash = value.lastIndexOf("/");
455
+ const colon = value.lastIndexOf(":");
456
+ const tag = colon > lastSlash ? value.slice(colon + 1) : "";
457
+ if (tag === PLACEHOLDER_TAG) throw new UsageError("bu CLI sürümü henüz bir dev imajı sabitlemiyor: --image ghcr.io/z9cloud/steward:dev-<etiket> verin (etiketler image-publish'te; latest yok)");
458
+ if (tag === "") throw new UsageError(`--image: etiket ya da digest gerekli (latest kullanılmaz): ${value}`);
459
+ if (/(^|-)latest$/.test(tag)) throw new UsageError(`--image: ${tag} kayan etiket; sabit bir etiket verin (AGENTS.md kural 4)`);
460
+ return value;
461
+ }
462
+ function composeProjectName(projectDir, product) {
463
+ const digest = createHash("sha256").update(projectDir).digest("hex").slice(0, 8);
464
+ return `steward-dev-${product.replace(/_/g, "-")}-${digest}`;
465
+ }
466
+ /** Tırnaklı YAML skaleri; compose `$` yerleştirmesi kaçışlı. */
467
+ const q = (value) => JSON.stringify(String(value).replace(/\$/g, "$$$$"));
468
+ function localBaseUrl(port) {
469
+ return `http://localhost:${port}`;
470
+ }
471
+ function composeFile(options) {
472
+ const env = [
473
+ ["STEWARD_DATABASE_URL", "postgres://steward:steward@db:5432/steward"],
474
+ ["STEWARD_PUBLIC_URL", localBaseUrl(options.port)],
475
+ ["STEWARD_DEV_PRODUCT", options.product],
476
+ ["STEWARD_DEV_CREDENTIALS_FILE", `${CONTAINER_STATE_DIR}/credentials.json`],
477
+ ["STEWARD_DEV_APP_URL", options.appUrl],
478
+ ...options.webhookUrl !== void 0 ? [["STEWARD_DEV_WEBHOOK_URL", options.webhookUrl]] : []
479
+ ];
480
+ return `${[
481
+ "# steward dev tarafından üretildi — elle düzenlemeyin, her `steward dev` yeniden yazar.",
482
+ "# Durdur: docker compose -f .steward/compose.yml down · Sıfırla: steward dev reset --yes",
483
+ `name: ${q(composeProjectName(options.projectDir, options.product))}`,
484
+ "services:",
485
+ " db:",
486
+ ` image: ${q(POSTGRES_IMAGE)}`,
487
+ " environment:",
488
+ ` POSTGRES_USER: ${q("steward")}`,
489
+ ` POSTGRES_PASSWORD: ${q("steward")}`,
490
+ ` POSTGRES_DB: ${q("steward")}`,
491
+ " volumes:",
492
+ ` - ${q("db:/var/lib/postgresql/data")}`,
493
+ " healthcheck:",
494
+ ` test: [${[
495
+ "CMD",
496
+ "pg_isready",
497
+ "-h",
498
+ "127.0.0.1",
499
+ "-U",
500
+ "steward",
501
+ "-d",
502
+ "steward"
503
+ ].map(q).join(", ")}]`,
504
+ ` interval: ${q("2s")}`,
505
+ ` timeout: ${q("5s")}`,
506
+ " retries: 30",
507
+ ` ${STEWARD_SERVICE}:`,
508
+ ` image: ${q(options.image)}`,
509
+ ...options.user ? [` user: ${q(`${options.user.uid}:${options.user.gid}`)}`] : [],
510
+ " depends_on:",
511
+ " db:",
512
+ " condition: service_healthy",
513
+ " ports:",
514
+ ` - ${q(`127.0.0.1:${options.port}:${CONTAINER_PORT}`)}`,
515
+ " environment:",
516
+ ...env.map(([key, value]) => ` ${key}: ${q(value)}`),
517
+ " extra_hosts:",
518
+ ` - ${q("host.docker.internal:host-gateway")}`,
519
+ " volumes:",
520
+ ` - ${q(`.:${CONTAINER_STATE_DIR}`)}`,
521
+ "volumes:",
522
+ " db: {}"
523
+ ].join("\n")}\n`;
524
+ }
525
+ //#endregion
526
+ //#region src/dev/credentials.ts
527
+ const isString = (value) => typeof value === "string" && value !== "";
528
+ const nullableString = (value) => value === null || isString(value);
529
+ async function readCredentials(path) {
530
+ let text;
531
+ try {
532
+ text = await readFile(path, "utf8");
533
+ } catch (error) {
534
+ return {
535
+ ok: false,
536
+ reason: errnoCode(error) === "ENOENT" ? "missing" : "unreadable"
537
+ };
538
+ }
539
+ let data;
540
+ try {
541
+ data = JSON.parse(text);
542
+ } catch {
543
+ return {
544
+ ok: false,
545
+ reason: "invalid"
546
+ };
547
+ }
548
+ if (typeof data !== "object" || data === null) return {
549
+ ok: false,
550
+ reason: "invalid"
551
+ };
552
+ const record = data;
553
+ if (typeof record.version === "number" && record.version !== 1) return {
554
+ ok: false,
555
+ reason: "unsupported_version"
556
+ };
557
+ if (!(record.version === 1 && isString(record.product) && isString(record.apiKey) && record.apiKey.startsWith("stw_") && isString(record.adminApiKey) && record.adminApiKey.startsWith("stw_") && nullableString(record.webhookSecret) && (record.webhookSecret === null || record.webhookSecret.startsWith("whsec_")) && nullableString(record.endpointId) && isString(record.createdAt))) return {
558
+ ok: false,
559
+ reason: "invalid"
560
+ };
561
+ const safe = (value) => value === null || /^[A-Za-z0-9_\-+/=.]+$/.test(value);
562
+ if (!safe(record.apiKey) || !safe(record.adminApiKey) || !safe(record.webhookSecret)) return {
563
+ ok: false,
564
+ reason: "invalid"
565
+ };
566
+ return {
567
+ ok: true,
568
+ credentials: record
569
+ };
570
+ }
571
+ /** Başkalarınca okunabiliyorsa 0600'e indirir (en iyi çaba; dosya başkasınınsa sessizce geçer). */
572
+ async function tightenMode(path) {
573
+ if (process.platform === "win32") return;
574
+ try {
575
+ if (((await stat(path)).mode & 63) !== 0) await chmod(path, 384);
576
+ } catch {}
577
+ }
578
+ const CREDENTIALS_PROBLEM = {
579
+ missing: "kimlik dosyası henüz yok",
580
+ unreadable: "kimlik dosyası okunamıyor (izin?)",
581
+ invalid: "kimlik dosyası beklenen biçimde değil",
582
+ unsupported_version: "kimlik dosyası sürümü bu CLI'da desteklenmiyor (CLI'ı güncelleyin)"
583
+ };
584
+ //#endregion
585
+ //#region src/commands/doctor.ts
586
+ const DOCTOR_USAGE = `Kullanım: steward doctor [--json]
587
+
588
+ GET /v1/doctor raporu: katalog, sağlayıcı, ayarlar, hosted sayfa hazırlığı,
589
+ endpoint teslimat teşhisi ve uyarılar. APP_URL tanımlıysa steward'daki appUrl
590
+ ve izinli dönüş origin'leriyle karşılaştırılır.
591
+
592
+ Bağlantı: STEWARD_URL + STEWARD_API_KEY (ikisi de yoksa STEWARD_ADMIN_URL +
593
+ STEWARD_ADMIN_API_KEY). Ortamda steward bağlantı değişkenlerinden biri bile
594
+ varsa bağlantı ve APP_URL yalnızca ortamdan okunur (./.env.local okunmaz);
595
+ yoksa ./.env.local'den. Kaynak ve hedefin origin'i stderr'e yazılır.
596
+
597
+ Çıkış kodu: 0 hazır; 1 rapor ok değil (error önemde uyarı) ya da APP_URL
598
+ steward'da izinli değil.
599
+
600
+ --json raporu JSON yazar (+ cliWarnings: yerel APP_URL karşılaştırması)`;
601
+ /** `APP_URL` (ürünün kendi adresi; checkout `successUrl`'i bundan kurulur) ↔ steward ayarları. */
602
+ function appUrlWarnings(appUrl, report) {
603
+ if (appUrl === void 0) return [];
604
+ let origin;
605
+ try {
606
+ origin = new URL(appUrl).origin;
607
+ } catch {
608
+ return [{
609
+ code: "app_url_env_invalid",
610
+ severity: "error",
611
+ message: "APP_URL geçerli bir adres değil"
612
+ }];
613
+ }
614
+ if (!report.settings.returnOrigins.includes(origin)) return [{
615
+ code: "app_url_not_allowed",
616
+ severity: "error",
617
+ message: `APP_URL origin'i (${origin}) steward'da izinli dönüş origin'i değil (appUrl: ${report.settings.appUrl ?? "yok"}): checkout return_url_not_allowed alır — steward settings set --app-url ${origin}`
618
+ }];
619
+ if (report.settings.appUrl !== null && originOf(report.settings.appUrl) !== origin) return [{
620
+ code: "app_url_mismatch",
621
+ severity: "warning",
622
+ message: `APP_URL (${origin}) steward appUrl'inden (${report.settings.appUrl}) farklı: hosted sayfanın "ürüne dön" bağı appUrl'e gider`
623
+ }];
624
+ return [];
625
+ }
626
+ const MARK = {
627
+ error: "✗",
628
+ warning: "!",
629
+ info: "i"
630
+ };
631
+ const SEVERITY_ORDER = [
632
+ "error",
633
+ "warning",
634
+ "info"
635
+ ];
636
+ const SEVERITY_TITLE = {
637
+ error: "hatalar",
638
+ warning: "uyarılar",
639
+ info: "bilgi"
640
+ };
641
+ const yesNo = (value) => value ? "✓" : "✗";
642
+ function countBySeverity(warnings) {
643
+ return {
644
+ errors: warnings.filter((w) => w.severity === "error").length,
645
+ warnings: warnings.filter((w) => w.severity === "warning").length
646
+ };
647
+ }
648
+ /** Tam insan okunur rapor. */
649
+ function formatDoctorReport(report, cliWarnings) {
650
+ const all = [...report.warnings, ...cliWarnings];
651
+ const { errors, warnings } = countBySeverity(all);
652
+ const ready = errors === 0;
653
+ const lines = [];
654
+ lines.push(`steward doctor — ${report.product.code} (${report.product.name}) · ${report.checkedAt}`);
655
+ lines.push(`durum ${ready ? "HAZIR ✓" : "SORUN VAR ✗"} (${errors} hata, ${warnings} uyarı)`);
656
+ lines.push("");
657
+ const { catalog, provider, settings, hosted } = report;
658
+ lines.push(`katalog senkron ${yesNo(catalog.synced)}${catalog.version !== null ? ` · sürüm ${catalog.version}` : ""} · ${catalog.plans} plan · ${catalog.sellablePrices} satılabilir fiyat · ${catalog.unsellablePrices.length} satılamaz`);
659
+ for (const price of catalog.unsellablePrices) lines.push(` ✗ ${price.planCode} ${price.interval}×${price.intervalCount} ${price.currency}: ${price.reason}`);
660
+ const providerState = !provider.configured ? "yapılandırılmamış ✗" : provider.healthy === false ? "erişilemiyor !" : "yapılandırılmış ✓";
661
+ const providerError = provider.lastError ? ` · son hata ${provider.lastError.code} (${provider.lastError.operation}, ${provider.lastError.at})` : "";
662
+ lines.push(`sağlayıcı ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${providerError}`);
663
+ lines.push(`ayarlar appUrl ${settings.appUrl ?? "yok"} · dönüş origin'leri: ${settings.returnOrigins.length > 0 ? settings.returnOrigins.join(", ") : "yok"}`);
664
+ const missing = [...hosted.branding.missing.map((field) => `branding.${field}`), ...hosted.legalLinks.missing];
665
+ lines.push(`hosted ${hosted.ready ? "hazır ✓" : `hazır değil ✗${missing.length > 0 ? ` (eksik: ${missing.join(", ")})` : ""}`}`);
666
+ if (report.endpoints.length === 0) lines.push("endpoint'ler yok");
667
+ else {
668
+ lines.push("endpoint'ler");
669
+ for (const endpoint of report.endpoints) {
670
+ const types = endpoint.eventTypes === null ? "filtre yok (0.1 tipleri)" : endpoint.eventTypes.join(",");
671
+ const last = endpoint.lastDelivery ? ` · son teslimat ${endpoint.lastDelivery.status}${endpoint.lastDelivery.httpStatus !== null ? ` ${endpoint.lastDelivery.httpStatus}` : ""}` : "";
672
+ lines.push(` ${endpoint.id} ${endpoint.status} ${endpoint.diagnosis} ${endpoint.url} [${types}] · bekleyen ${endpoint.pending} · dead ${endpoint.dead}${last}`);
673
+ }
674
+ }
675
+ lines.push(`dunning ${report.dunning.dryRun ? "dry-run (askı/sonlandırma uygulanmaz)" : "etkin"}`);
676
+ for (const severity of SEVERITY_ORDER) {
677
+ const items = all.filter((w) => w.severity === severity);
678
+ if (items.length === 0) continue;
679
+ lines.push("");
680
+ lines.push(SEVERITY_TITLE[severity]);
681
+ for (const item of items) {
682
+ const endpoint = "endpointId" in item && typeof item.endpointId === "string" ? ` [${item.endpointId}]` : "";
683
+ lines.push(` ${MARK[severity]} ${item.code}${endpoint}: ${item.message}`);
684
+ }
685
+ }
686
+ return lines;
687
+ }
688
+ /** `steward dev` sonundaki kısa özet. */
689
+ function formatDoctorSummary(report) {
690
+ const { errors, warnings } = countBySeverity(report.warnings);
691
+ const lines = [report.ok ? `doctor: hazır ✓ (${warnings} uyarı)` : `doctor: ${errors} hata, ${warnings} uyarı`];
692
+ for (const severity of SEVERITY_ORDER) for (const item of report.warnings.filter((w) => w.severity === severity)) lines.push(` ${MARK[severity]} ${item.code}: ${item.message}`);
693
+ return lines;
694
+ }
695
+ async function doctorCommand(ctx, out, args) {
696
+ const { values, positionals } = parse(args, {
697
+ ...HELP_OPTION,
698
+ json: { type: "boolean" }
699
+ }, "doctor");
700
+ if (values.help) {
701
+ out.out(DOCTOR_USAGE);
702
+ return 0;
703
+ }
704
+ expectPositionals(positionals, 0, 0, "doctor");
705
+ const env = await resolveEnv(ctx);
706
+ const target = requireReadTarget(env);
707
+ const appUrl = env.get("APP_URL");
708
+ out.err(connectionLine(target));
709
+ if (appUrl === void 0) out.err(`APP_URL tanımlı değil (${env.source}): steward appUrl karşılaştırması atlandı`);
710
+ const report = await callSteward(target, () => clientFor(ctx, target).doctor());
711
+ const cliWarnings = appUrlWarnings(appUrl, report);
712
+ const failed = !report.ok || cliWarnings.some((w) => w.severity === "error");
713
+ if (values.json) out.out(JSON.stringify({
714
+ ...report,
715
+ cliWarnings
716
+ }, null, 2));
717
+ else for (const line of formatDoctorReport(report, cliWarnings)) out.out(line);
718
+ return failed ? 1 : 0;
719
+ }
720
+ //#endregion
721
+ //#region src/commands/dev.ts
722
+ const DEV_USAGE = `Kullanım:
723
+ steward dev [--product <kod>] [--catalog <dosya>] [--port 3002] [--app-url <url>]
724
+ [--webhook-url <url>] [--image <imaj>] [--timeout <sn>]
725
+ steward dev reset --yes
726
+
727
+ Yerel steward: dev imajı + Postgres (Docker compose, yalnızca 127.0.0.1), sahte
728
+ ödeme sağlayıcısı; hosted checkout ve portal http://localhost:<port>/public altında.
729
+
730
+ 1. .steward/compose.yml yazılır, .steward/ .gitignore'a eklenir (yoksa)
731
+ 2. docker compose -f .steward/compose.yml up -d, /health beklenir
732
+ 3. servis ürünü ve anahtarları oluşturur; .steward/credentials.json okunur
733
+ 4. .env.local'e STEWARD_URL, STEWARD_ADMIN_URL, STEWARD_API_KEY,
734
+ STEWARD_ADMIN_API_KEY (+ STEWARD_WEBHOOK_SECRET) yazılır — değerler
735
+ terminale yazılmaz, diğer satırlar korunur; --webhook-url verilmezse
736
+ önceki koşunun STEWARD_WEBHOOK_SECRET satırı silinir
737
+ 5. --catalog verilmişse katalog senkronlanır; doctor özeti
738
+
739
+ --product <kod> ürün kodu (varsayılan: package.json adından)
740
+ --catalog <dosya> katalog (.ts/.mjs/.js/.json; bkz. steward catalog push)
741
+ --port <n> host portu (varsayılan 3002)
742
+ --app-url <url> ürünün yerel adresi (varsayılan http://localhost:3000)
743
+ --webhook-url <url> webhook alıcısı, ör. http://host.docker.internal:3000/api/billing/events
744
+ --image <imaj> dev imajı. İlk dev imajı yayınına kadar ZORUNLU (varsayılan
745
+ etiket yer tutucu): ghcr.io/z9cloud/steward:dev-<etiket> ya da
746
+ steward reposunda docker build --target dev -t steward-dev:local .
747
+ → --image steward-dev:local
748
+ --timeout <sn> hazır olma beklemesi (varsayılan 180)
749
+
750
+ dev reset --yes: compose'u durdurur, veritabanı volume'ünü (docker compose down -v),
751
+ kimlik dosyasını ve servisin dev şifreleme anahtarını (.steward/encryption-key) siler.
752
+ .env.local'deki anahtarlar geçersiz kalır; sonraki steward dev yenilerini yazar.`;
753
+ const DEV_OPTIONS = {
754
+ ...HELP_OPTION,
755
+ product: { type: "string" },
756
+ catalog: { type: "string" },
757
+ port: { type: "string" },
758
+ "app-url": { type: "string" },
759
+ "webhook-url": { type: "string" },
760
+ image: { type: "string" },
761
+ timeout: { type: "string" }
762
+ };
763
+ const PRODUCT_CODE = /^[a-z][a-z0-9_]{0,62}$/;
764
+ const WEBHOOK_SECRET_KEY = "STEWARD_WEBHOOK_SECRET";
765
+ const GITIGNORE_ENTRIES = /* @__PURE__ */ new Set([
766
+ ".steward",
767
+ ".steward/",
768
+ "/.steward",
769
+ "/.steward/",
770
+ ".steward/*",
771
+ "/.steward/*"
772
+ ]);
773
+ /**
774
+ Servis kimlik dosyasını `serve`'den önce yazar: /health yanıt verdiğinde dosya hazırdır. Yine de
775
+ (yeniden başlatma, yavaş dosya sistemi) kısa bir süre tekrar okunur; sonra açık hata.
776
+ */
777
+ const CREDENTIALS_GRACE_MS = 15e3;
778
+ /** Paket adı ya da klasör adından ürün kodu (`@acme/Web-App` → `web_app`). */
779
+ function toProductCode(value) {
780
+ if (value === void 0) return null;
781
+ const code = value.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9_]+/g, "_").replace(/^[^a-z]+/, "").replace(/_+$/, "").slice(0, 63);
782
+ return PRODUCT_CODE.test(code) ? code : null;
783
+ }
784
+ async function inferProductCode(cwd) {
785
+ try {
786
+ const pkg = JSON.parse(await readFile(join(cwd, "package.json"), "utf8"));
787
+ const code = toProductCode(typeof pkg.name === "string" ? pkg.name : void 0);
788
+ if (code !== null) return {
789
+ code,
790
+ from: "package.json adı"
791
+ };
792
+ } catch {}
793
+ const code = toProductCode(basename(cwd));
794
+ return code !== null ? {
795
+ code,
796
+ from: "klasör adı"
797
+ } : {
798
+ code: "dev",
799
+ from: "varsayılan"
800
+ };
801
+ }
802
+ async function exists(path) {
803
+ try {
804
+ await stat(path);
805
+ return true;
806
+ } catch (error) {
807
+ if (errnoCode(error) === "ENOENT") return false;
808
+ throw error;
809
+ }
810
+ }
811
+ async function ensureDockerCompose(ctx) {
812
+ if ((await ctx.run("docker", ["compose", "version"], {
813
+ cwd: ctx.cwd,
814
+ capture: true
815
+ })).code !== 0) throw new CliError("docker compose bulunamadı ya da Docker çalışmıyor (Docker Desktop / OrbStack açık mı?)");
816
+ }
817
+ /** `.steward/` .gitignore'da değilse ekler (dosya yoksa oluşturur). Eklendiyse true. */
818
+ async function ensureGitignored(cwd) {
819
+ const path = join(cwd, ".gitignore");
820
+ let text = "";
821
+ try {
822
+ text = await readFile(path, "utf8");
823
+ } catch (error) {
824
+ if (errnoCode(error) !== "ENOENT") throw error;
825
+ }
826
+ if (text.split(/\r?\n/).some((line) => GITIGNORE_ENTRIES.has(line.trim()))) return false;
827
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
828
+ const prefix = text === "" ? "" : text.endsWith("\n") ? eol : `${eol}${eol}`;
829
+ await writeFile(path, `${text}${prefix}# steward dev (yerel veritabanı ve kimlik bilgileri)${eol}${STATE_DIR}/${eol}`);
830
+ return true;
831
+ }
832
+ async function waitForHealth(ctx, baseUrl, deadline, timeoutSeconds) {
833
+ let last = "bağlantı yok";
834
+ for (let attempt = 1;; attempt++) {
835
+ try {
836
+ const res = await ctx.fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(2e3) });
837
+ if (res.ok) {
838
+ const body = await res.json().catch(() => null);
839
+ return { env: typeof body?.env === "string" ? body.env : null };
840
+ }
841
+ last = `HTTP ${res.status}`;
842
+ } catch {
843
+ last = "bağlantı yok";
844
+ }
845
+ if (ctx.now() >= deadline) throw new CliError(`steward ${timeoutSeconds} sn içinde hazır olmadı (/health: ${last}). Loglar: docker compose -f ${COMPOSE_FILE} logs ${STEWARD_SERVICE}`);
846
+ if (attempt % 5 === 0) {
847
+ const ps = await ctx.run("docker", [
848
+ "compose",
849
+ "-f",
850
+ COMPOSE_FILE,
851
+ "ps",
852
+ "--status",
853
+ "running",
854
+ "--services"
855
+ ], {
856
+ cwd: ctx.cwd,
857
+ capture: true
858
+ });
859
+ if (ps.code === 0 && !ps.stdout.split(/\r?\n/).includes("steward")) throw new CliError(`steward konteyneri çalışmıyor. Loglar: docker compose -f ${COMPOSE_FILE} logs ${STEWARD_SERVICE}`);
860
+ }
861
+ await ctx.sleep(1e3);
862
+ }
863
+ }
864
+ /** Anahtarlar bu steward'da geçerli ve beklenen ürün/kapsamda mı; sorun varsa açıklaması. */
865
+ async function verifyKeys(ctx, baseUrl, credentials) {
866
+ const keys = [{
867
+ apiKey: credentials.apiKey,
868
+ scope: "product",
869
+ label: "ürün anahtarı"
870
+ }, {
871
+ apiKey: credentials.adminApiKey,
872
+ scope: "admin",
873
+ label: "admin anahtarı"
874
+ }];
875
+ for (const key of keys) try {
876
+ const me = await clientFor(ctx, {
877
+ url: baseUrl,
878
+ apiKey: key.apiKey
879
+ }, { retries: false }).me();
880
+ if (me.product !== credentials.product) return `kimlik dosyasındaki ${key.label} başka bir ürünün (${me.product})`;
881
+ if (me.scope !== key.scope) return `kimlik dosyasındaki ${key.label} kapsamı beklenen değil (${me.scope})`;
882
+ } catch (error) {
883
+ if (error instanceof StewardApiError && error.httpStatus === 401) return `kimlik dosyasındaki ${key.label} bu veritabanında geçersiz (veritabanı elle silindiyse: steward dev reset --yes)`;
884
+ if (error instanceof StewardError) return describeStewardError(error, { url: baseUrl });
885
+ throw error;
886
+ }
887
+ return null;
888
+ }
889
+ async function waitForCredentials(ctx, options) {
890
+ const giveUpAt = Math.min(options.deadline, ctx.now() + CREDENTIALS_GRACE_MS);
891
+ for (;;) {
892
+ const read = await readCredentials(options.path);
893
+ let problem;
894
+ if (read.ok) {
895
+ const { credentials } = read;
896
+ const invalid = (credentials.product !== options.product ? `kimlik dosyası başka bir ürünün (${credentials.product}); servis yeniden başlatılınca yeniden yazar` : null) ?? await verifyKeys(ctx, options.baseUrl, credentials);
897
+ if (invalid === null) {
898
+ await tightenMode(options.path);
899
+ return credentials;
900
+ }
901
+ problem = invalid;
902
+ } else {
903
+ if (read.reason === "unsupported_version") throw new CliError(CREDENTIALS_PROBLEM.unsupported_version);
904
+ problem = read.reason === "missing" ? `${CREDENTIALS_PROBLEM.missing} (imaj dev sağlamayı destekliyor mu? ghcr.io/z9cloud/steward:dev-<etiket>)` : CREDENTIALS_PROBLEM[read.reason];
905
+ }
906
+ if (ctx.now() >= giveUpAt) throw new CliError(`steward kimlik bilgileri alınamadı: ${problem}. Loglar: docker compose -f ${COMPOSE_FILE} logs ${STEWARD_SERVICE}`);
907
+ await ctx.sleep(1e3);
908
+ }
909
+ }
910
+ /** `.env.local` gitignore'da değilse uyarır (git yoksa ya da repo değilse sessiz). */
911
+ async function warnIfEnvLocalTracked(ctx, out) {
912
+ if ((await ctx.run("git", [
913
+ "check-ignore",
914
+ "-q",
915
+ ".env.local"
916
+ ], {
917
+ cwd: ctx.cwd,
918
+ capture: true
919
+ })).code === 1) out.err(`! ${ENV_LOCAL} .gitignore'da değil: anahtarlar içerir, commit'lenmemeli (ör. .gitignore'a \`.env*.local\` ekleyin)`);
920
+ }
921
+ async function devCommand(ctx, out, args) {
922
+ if (args[0] === "reset") return devReset(ctx, out, args.slice(1));
923
+ const { values, positionals } = parse(args, DEV_OPTIONS, "dev");
924
+ if (values.help) {
925
+ out.out(DEV_USAGE);
926
+ return 0;
927
+ }
928
+ if (positionals.length > 0) throw new UsageError(`bilinmeyen alt komut: dev ${positionals[0]} (ayrıntı: steward dev --help)`);
929
+ let product;
930
+ if (values.product !== void 0) {
931
+ product = values.product.trim();
932
+ if (!PRODUCT_CODE.test(product)) throw new UsageError("--product: küçük harf, rakam ve _ (harfle başlar, en çok 63)");
933
+ } else {
934
+ const inferred = await inferProductCode(ctx.cwd);
935
+ product = inferred.code;
936
+ out.err(`ürün kodu: ${product} (${inferred.from}; değiştirmek için --product)`);
937
+ }
938
+ const port = parsePositiveInt(values.port ?? "3002", "--port", { max: 65535 });
939
+ const appUrl = parseHttpUrl(values["app-url"] ?? "http://localhost:3000", "--app-url");
940
+ const webhookUrl = values["webhook-url"] !== void 0 ? parseHttpUrl(values["webhook-url"], "--webhook-url") : void 0;
941
+ const image = checkImage(values.image ?? "ghcr.io/z9cloud/steward:dev-unreleased");
942
+ const timeoutSeconds = parsePositiveInt(values.timeout ?? "180", "--timeout", { max: 3600 });
943
+ let catalog = null;
944
+ if (values.catalog !== void 0) catalog = await loadCatalogFile(ctx, values.catalog);
945
+ const baseUrl = localBaseUrl(port);
946
+ await ensureDockerCompose(ctx);
947
+ const stateDir = join(ctx.cwd, STATE_DIR);
948
+ await mkdir(stateDir, {
949
+ recursive: true,
950
+ mode: 448
951
+ });
952
+ await writeFile(join(ctx.cwd, COMPOSE_FILE), composeFile({
953
+ projectDir: resolve(ctx.cwd),
954
+ product,
955
+ port,
956
+ appUrl,
957
+ ...webhookUrl !== void 0 ? { webhookUrl } : {},
958
+ image,
959
+ user: ctx.platform === "linux" ? ctx.hostUser() : null
960
+ }));
961
+ if (await ensureGitignored(ctx.cwd)) out.err(`.gitignore'a ${STATE_DIR}/ eklendi (yerel veritabanı ve kimlik bilgileri)`);
962
+ await warnIfEnvLocalTracked(ctx, out);
963
+ out.err(`steward başlatılıyor (${image}) → ${baseUrl}`);
964
+ const up = await ctx.run("docker", [
965
+ "compose",
966
+ "-f",
967
+ COMPOSE_FILE,
968
+ "up",
969
+ "-d"
970
+ ], { cwd: ctx.cwd });
971
+ if (up.code !== 0) throw new CliError(`docker compose up başarısız (çıkış ${up.code}); port ${port} kullanımda olabilir (--port)`);
972
+ const deadline = ctx.now() + timeoutSeconds * 1e3;
973
+ const health = await waitForHealth(ctx, baseUrl, deadline, timeoutSeconds);
974
+ if (health.env === "production") throw new CliError(`${image} üretim imajı (env: production): dev imajı verin (ghcr.io/z9cloud/steward:dev-<etiket>)`);
975
+ const credentials = await waitForCredentials(ctx, {
976
+ path: join(ctx.cwd, CREDENTIALS_FILE),
977
+ product,
978
+ baseUrl,
979
+ deadline
980
+ });
981
+ const entries = [
982
+ ["STEWARD_URL", baseUrl],
983
+ ["STEWARD_ADMIN_URL", baseUrl],
984
+ ["STEWARD_API_KEY", credentials.apiKey],
985
+ ["STEWARD_ADMIN_API_KEY", credentials.adminApiKey],
986
+ ...credentials.webhookSecret !== null ? [[WEBHOOK_SECRET_KEY, credentials.webhookSecret]] : []
987
+ ];
988
+ const remove = credentials.webhookSecret === null ? [WEBHOOK_SECRET_KEY] : [];
989
+ const env = await upsertDotenvFile(join(ctx.cwd, ENV_LOCAL), entries, remove);
990
+ const written = entries.map(([key]) => key).filter((key) => env.added.includes(key) || env.updated.includes(key));
991
+ const removed = env.removed.length > 0 ? `; kaldırıldı: ${env.removed.join(", ")} (webhook endpoint'i yok)` : "";
992
+ if (env.created) out.err(`${ENV_LOCAL} oluşturuldu (0600): ${written.join(", ")} (değerler yazdırılmaz)`);
993
+ else if (written.length > 0 || removed !== "") {
994
+ const changed = written.length > 0 ? written.join(", ") : "değer değişmedi";
995
+ out.err(`${ENV_LOCAL} güncellendi: ${changed}${removed} (değerler yazdırılmaz; diğer satırlar korundu)`);
996
+ } else out.err(`${ENV_LOCAL} güncel: ${env.unchanged.join(", ")}`);
997
+ if (env.looseMode) out.err(`! ${ENV_LOCAL} başka kullanıcılarca okunabilir: chmod 600 ${ENV_LOCAL}`);
998
+ if (credentials.webhookSecret === null) out.err("webhook endpoint'i yok (laptop'a webhook gelmez); gerekirse --webhook-url http://host.docker.internal:<port>/<yol>");
999
+ let exitCode = 0;
1000
+ if (catalog !== null) {
1001
+ const pushed = await pushCatalog(ctx, {
1002
+ url: baseUrl,
1003
+ apiKey: credentials.adminApiKey
1004
+ }, catalog);
1005
+ for (const line of pushed.lines) out.err(line);
1006
+ if (pushed.providerErrors > 0) exitCode = 1;
1007
+ }
1008
+ const target = {
1009
+ url: baseUrl,
1010
+ apiKey: credentials.apiKey
1011
+ };
1012
+ const report = await callSteward(target, () => clientFor(ctx, target).doctor());
1013
+ for (const line of formatDoctorSummary(report)) out.err(line);
1014
+ out.out(`steward dev hazır: ${baseUrl} (ürün ${product}${health.env !== null ? `, env ${health.env}` : ""})`);
1015
+ out.out(` hosted checkout/portal: ${baseUrl}/public/… · uygulamanızı başlatın (ör. pnpm dev)`);
1016
+ out.out(` durdur: docker compose -f ${COMPOSE_FILE} down · sıfırla: steward dev reset --yes`);
1017
+ return exitCode;
1018
+ }
1019
+ async function devReset(ctx, out, args) {
1020
+ const { values, positionals } = parse(args, {
1021
+ ...HELP_OPTION,
1022
+ yes: { type: "boolean" }
1023
+ }, "dev");
1024
+ if (values.help) {
1025
+ out.out(DEV_USAGE);
1026
+ return 0;
1027
+ }
1028
+ expectPositionals(positionals, 0, 0, "dev");
1029
+ if (!values.yes) throw new UsageError(`dev reset yerel steward veritabanını (Docker volume), ${CREDENTIALS_FILE} ve ${ENCRYPTION_KEY_FILE} dosyalarını siler; onaylamak için --yes`);
1030
+ const files = [CREDENTIALS_FILE, ENCRYPTION_KEY_FILE];
1031
+ if (await exists(join(ctx.cwd, COMPOSE_FILE))) {
1032
+ await ensureDockerCompose(ctx);
1033
+ const down = await ctx.run("docker", [
1034
+ "compose",
1035
+ "-f",
1036
+ COMPOSE_FILE,
1037
+ "down",
1038
+ "-v",
1039
+ "--remove-orphans"
1040
+ ], { cwd: ctx.cwd });
1041
+ if (down.code !== 0) throw new CliError(`docker compose down başarısız (çıkış ${down.code}); dosyalar silinmedi`);
1042
+ } else {
1043
+ const leftovers = [];
1044
+ for (const file of files) if (await exists(join(ctx.cwd, file))) leftovers.push(file);
1045
+ if (leftovers.length > 0) throw new CliError(`${COMPOSE_FILE} yok, veritabanı volume'ü silinemiyor; ${leftovers.join(" ve ")} korunuyor. Önce steward dev (aynı --product) ile compose'u yeniden yazın.`);
1046
+ out.out("sıfırlanacak yerel steward yok");
1047
+ return 0;
1048
+ }
1049
+ for (const file of files) await rm(join(ctx.cwd, file), { force: true });
1050
+ out.out(`yerel steward sıfırlandı: veritabanı volume'ü, ${CREDENTIALS_FILE} ve ${ENCRYPTION_KEY_FILE} silindi. ${ENV_LOCAL}'deki anahtarlar geçersiz; steward dev yenilerini yazar.`);
1051
+ return 0;
1052
+ }
1053
+ //#endregion
1054
+ //#region src/secret-file.ts
1055
+ async function withSecretFile(cwd, out, secret, options, action) {
1056
+ const target = resolve(cwd, out);
1057
+ try {
1058
+ if ((await lstat(target)).isDirectory()) throw new CliError(`--out bir klasör: ${out}`);
1059
+ if (!options.force) throw new CliError(`${out} zaten var; üzerine yazmak için --force (istek gönderilmedi)`);
1060
+ } catch (error) {
1061
+ if (error instanceof CliError) throw error;
1062
+ if (errnoCode(error) !== "ENOENT") throw error;
1063
+ }
1064
+ const temp = join(dirname(target), `.${basename(target)}.${randomUUID().slice(0, 8)}.tmp`);
1065
+ try {
1066
+ await writeFile(temp, secret, {
1067
+ mode: 384,
1068
+ flag: "wx"
1069
+ });
1070
+ } catch (error) {
1071
+ const code = errnoCode(error);
1072
+ if (code === "ENOENT") throw new CliError(`--out klasörü yok: ${relative(cwd, dirname(target)) || "."}`);
1073
+ throw new CliError(`sır dosyası yazılamadı (${code ?? "hata"}): ${out} (istek gönderilmedi)`);
1074
+ }
1075
+ let value;
1076
+ try {
1077
+ value = await action();
1078
+ } catch (error) {
1079
+ await unlink(temp).catch(() => {});
1080
+ throw error;
1081
+ }
1082
+ try {
1083
+ if (options.force) await rename(temp, target);
1084
+ else {
1085
+ await link(temp, target);
1086
+ await unlink(temp).catch(() => {});
1087
+ }
1088
+ return {
1089
+ value,
1090
+ path: out,
1091
+ fallback: false
1092
+ };
1093
+ } catch {
1094
+ return {
1095
+ value,
1096
+ path: relative(cwd, temp),
1097
+ fallback: true
1098
+ };
1099
+ }
1100
+ }
1101
+ //#endregion
1102
+ //#region src/commands/endpoints.ts
1103
+ const ENDPOINTS_USAGE = `Kullanım:
1104
+ steward endpoints list [--json]
1105
+ steward endpoints add --url <url> --out <dosya> [--event-types <a,b>] [--description <metin>] [--force]
1106
+ steward endpoints rotate <id> --out <dosya> [--force]
1107
+ steward endpoints deactivate <id>
1108
+
1109
+ Webhook endpoint'leri (/v1/admin/webhook-endpoints). İmza sırrı (whsec_…) bu
1110
+ makinede üretilir ve YALNIZCA --out dosyasına yazılır (0600, satır sonu yok);
1111
+ terminale yazılmaz, steward hiçbir yanıtta geri vermez. Dosya varsa --force
1112
+ olmadan istek gönderilmez. Sırrı ürünün Secret'ına operatör taşır (CLI kubectl
1113
+ çağırmaz); rotasyonda ürün "yeni,eski" listesiyle geçer. Taşıdıktan sonra dosyayı
1114
+ silin. --event-types verilmezse yalnızca account.state_changed. deactivate geri
1115
+ alınmaz (yeni endpoint açılır).
1116
+
1117
+ Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
1118
+ function schemaProblems(issues) {
1119
+ return issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(kök)"}: ${issue.message}`).join("\n");
1120
+ }
1121
+ const lastDeliveryText = (endpoint) => {
1122
+ const last = endpoint.lastDelivery;
1123
+ if (last === null) return "-";
1124
+ return `${last.status}${last.httpStatus !== null ? ` ${last.httpStatus}` : ""}${last.error !== null ? ` ${last.error}` : ""} (${last.at})`;
1125
+ };
1126
+ function table(rows) {
1127
+ const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => row[column].length)));
1128
+ return rows.map((row) => row.map((cell, column) => column === row.length - 1 ? cell : cell.padEnd(widths[column])).join(" "));
1129
+ }
1130
+ const typesText = (endpoint) => endpoint.eventTypes === null ? "(filtre yok: 0.1 tipleri)" : endpoint.eventTypes.join(",");
1131
+ async function endpointsCommand(ctx, out, args) {
1132
+ const [sub, ...rest] = args;
1133
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1134
+ out.out(ENDPOINTS_USAGE);
1135
+ return sub === void 0 ? 2 : 0;
1136
+ }
1137
+ if (sub === "list") {
1138
+ const { values, positionals } = parse(rest, {
1139
+ ...HELP_OPTION,
1140
+ json: { type: "boolean" }
1141
+ }, "endpoints");
1142
+ if (values.help) return help(out);
1143
+ expectPositionals(positionals, 0, 0, "endpoints");
1144
+ const target = requireAdminTarget(await resolveEnv(ctx));
1145
+ out.err(connectionLine(target));
1146
+ const { items } = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.list());
1147
+ if (values.json) out.out(JSON.stringify(items, null, 2));
1148
+ else if (items.length === 0) out.out("endpoint yok — steward endpoints add --url <url> --out <dosya>");
1149
+ else {
1150
+ const rows = [[
1151
+ "ID",
1152
+ "DURUM",
1153
+ "OLAYLAR",
1154
+ "SON TESLİMAT",
1155
+ "URL"
1156
+ ]];
1157
+ for (const e of items) rows.push([
1158
+ e.id,
1159
+ e.status,
1160
+ typesText(e),
1161
+ lastDeliveryText(e),
1162
+ e.description !== null ? `${e.url} (${e.description})` : e.url
1163
+ ]);
1164
+ for (const line of table(rows)) out.out(line);
1165
+ }
1166
+ return 0;
1167
+ }
1168
+ if (sub === "add") {
1169
+ const { values, positionals } = parse(rest, {
1170
+ ...HELP_OPTION,
1171
+ url: { type: "string" },
1172
+ out: { type: "string" },
1173
+ "event-types": { type: "string" },
1174
+ description: { type: "string" },
1175
+ force: { type: "boolean" }
1176
+ }, ENDPOINTS_USAGE);
1177
+ if (values.help) return help(out);
1178
+ expectPositionals(positionals, 0, 0, "endpoints");
1179
+ const url = requireOption(values.url, "--url", "endpoints");
1180
+ const file = requireOption(values.out, "--out", "endpoints");
1181
+ const secret = generateWebhookSecret();
1182
+ const input = {
1183
+ url,
1184
+ secret,
1185
+ ...values["event-types"] !== void 0 ? { eventTypes: parseList(values["event-types"]) } : {},
1186
+ ...values.description !== void 0 ? { description: values.description } : {}
1187
+ };
1188
+ const parsed = WebhookEndpointCreateInputSchema.safeParse(input);
1189
+ if (!parsed.success) throw new UsageError(`endpoint geçersiz (istek gönderilmedi)\n${schemaProblems(parsed.error.issues)}`);
1190
+ const target = requireAdminTarget(await resolveEnv(ctx));
1191
+ out.err(connectionLine(target));
1192
+ const steward = clientFor(ctx, target);
1193
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.create(input)));
1194
+ const endpoint = result.value;
1195
+ out.out(`endpoint oluşturuldu → ${originOf(target.url)}`);
1196
+ out.out(` id ${endpoint.id}`);
1197
+ out.out(` url ${endpoint.url}`);
1198
+ out.out(` olaylar ${typesText(endpoint)}`);
1199
+ secretNotice(out, result.path, result.fallback, "Sırrı ürünün Secret'ına (STEWARD_WEBHOOK_SECRET) taşıyın, sonra dosyayı silin.");
1200
+ return 0;
1201
+ }
1202
+ if (sub === "rotate") {
1203
+ const { values, positionals } = parse(rest, {
1204
+ ...HELP_OPTION,
1205
+ out: { type: "string" },
1206
+ force: { type: "boolean" }
1207
+ }, "endpoints");
1208
+ if (values.help) return help(out);
1209
+ expectPositionals(positionals, 1, 1, "endpoints");
1210
+ const id = positionals[0];
1211
+ const file = requireOption(values.out, "--out", "endpoints");
1212
+ const secret = generateWebhookSecret();
1213
+ const parsed = WebhookEndpointRotateInputSchema.safeParse({ secret });
1214
+ if (!parsed.success) throw new UsageError(`sır geçersiz\n${schemaProblems(parsed.error.issues)}`);
1215
+ const target = requireAdminTarget(await resolveEnv(ctx));
1216
+ out.err(connectionLine(target));
1217
+ const steward = clientFor(ctx, target);
1218
+ const result = await withSecretFile(ctx.cwd, file, secret, { force: values.force === true }, () => callSteward(target, () => steward.admin.endpoints.rotate(id, { secret })));
1219
+ out.out(`sır döndürüldü → ${originOf(target.url)}`);
1220
+ out.out(` id ${result.value.id}`);
1221
+ out.out(` url ${result.value.url}`);
1222
+ 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.");
1223
+ return 0;
1224
+ }
1225
+ if (sub === "deactivate") {
1226
+ const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
1227
+ if (values.help) return help(out);
1228
+ expectPositionals(positionals, 1, 1, "endpoints");
1229
+ const target = requireAdminTarget(await resolveEnv(ctx));
1230
+ out.err(connectionLine(target));
1231
+ const endpoint = await callSteward(target, () => clientFor(ctx, target).admin.endpoints.deactivate(positionals[0]));
1232
+ out.out(`endpoint pasifleştirildi → ${originOf(target.url)}: ${endpoint.id} (${endpoint.url}, durum ${endpoint.status})`);
1233
+ return 0;
1234
+ }
1235
+ throw new UsageError(`bilinmeyen alt komut: endpoints ${sub} (ayrıntı: steward endpoints --help)`);
1236
+ }
1237
+ function help(out) {
1238
+ out.out(ENDPOINTS_USAGE);
1239
+ return 0;
1240
+ }
1241
+ function secretNotice(out, path, fallback, next) {
1242
+ if (fallback) {
1243
+ out.err(`! sır hedef dosyaya taşınamadı (arada oluşturulmuş olabilir); sır ${path} dosyasında (0600)`);
1244
+ out.out(` sır ${path} (0600; terminale yazılmadı)`);
1245
+ } else out.out(` sır ${path} (0600; terminale yazılmadı)`);
1246
+ out.err(next);
1247
+ }
1248
+ //#endregion
1249
+ //#region src/commands/settings.ts
1250
+ const SETTINGS_USAGE = `Kullanım:
1251
+ steward settings get
1252
+ steward settings set [--app-url <url>] [--privacy-url <url>] [--terms-url <url>]
1253
+ [--branding <json>] [--default-locale tr|en]
1254
+ [--checkout-ttl <dakika>] [--portal-ttl <dakika>]
1255
+ [--extra-return-origins <a,b>]
1256
+
1257
+ Ürün ayarları (GET/PATCH /v1/admin/settings). Verilmeyen alan değişmez; boş değer
1258
+ (--privacy-url "") alanı temizler, --branding null markayı temizler, --branding
1259
+ '{"name":"Acme","supportEmail":"destek@acme.com"}' sığ birleşir (alanı null ile
1260
+ temizleyin). --extra-return-origins "" listeyi boşaltır.
1261
+
1262
+ Bağlantı: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (ortam, yoksa ./.env.local).`;
1263
+ const SET_OPTIONS = {
1264
+ ...HELP_OPTION,
1265
+ "app-url": { type: "string" },
1266
+ "privacy-url": { type: "string" },
1267
+ "terms-url": { type: "string" },
1268
+ branding: { type: "string" },
1269
+ "default-locale": { type: "string" },
1270
+ "checkout-ttl": { type: "string" },
1271
+ "portal-ttl": { type: "string" },
1272
+ "extra-return-origins": { type: "string" }
1273
+ };
1274
+ const orNull = (value) => value.trim() === "" ? null : value.trim();
1275
+ /** Bayraklardan yama; sözleşme şemasıyla doğrulanır (geçersizse istek gönderilmez). */
1276
+ function buildSettingsPatch(values) {
1277
+ const patch = {};
1278
+ if (values["app-url"] !== void 0) patch.appUrl = orNull(values["app-url"]);
1279
+ if (values["privacy-url"] !== void 0) patch.privacyUrl = orNull(values["privacy-url"]);
1280
+ if (values["terms-url"] !== void 0) patch.termsUrl = orNull(values["terms-url"]);
1281
+ if (values.branding !== void 0) {
1282
+ const text = values.branding.trim();
1283
+ if (text === "" || text === "null") patch.branding = null;
1284
+ else {
1285
+ let branding;
1286
+ try {
1287
+ branding = JSON.parse(text);
1288
+ } catch {
1289
+ throw new UsageError("--branding: JSON nesnesi olmalı, ör. '{\"name\":\"Acme\",\"supportEmail\":\"destek@acme.com\"}'");
1290
+ }
1291
+ if (typeof branding !== "object" || branding === null || Array.isArray(branding)) throw new UsageError("--branding: JSON nesnesi olmalı");
1292
+ patch.branding = branding;
1293
+ }
1294
+ }
1295
+ if (values["default-locale"] !== void 0) patch.defaultLocale = values["default-locale"].trim();
1296
+ if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
1297
+ if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
1298
+ if (values["extra-return-origins"] !== void 0) patch.extraReturnOrigins = parseList(values["extra-return-origins"]);
1299
+ if (Object.keys(patch).length === 0) throw new UsageError(`en az bir ayar bayrağı gerekli (ayrıntı: steward settings --help)`);
1300
+ const parsed = ProductSettingsPatchSchema.safeParse(patch);
1301
+ 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")}`);
1302
+ return patch;
1303
+ }
1304
+ async function settingsCommand(ctx, out, args) {
1305
+ const [sub, ...rest] = args;
1306
+ if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
1307
+ out.out(SETTINGS_USAGE);
1308
+ return sub === void 0 ? 2 : 0;
1309
+ }
1310
+ if (sub === "get") {
1311
+ const { values, positionals } = parse(rest, { ...HELP_OPTION }, "settings");
1312
+ if (values.help) {
1313
+ out.out(SETTINGS_USAGE);
1314
+ return 0;
1315
+ }
1316
+ expectPositionals(positionals, 0, 0, "settings");
1317
+ const target = requireAdminTarget(await resolveEnv(ctx));
1318
+ out.err(connectionLine(target));
1319
+ const settings = await callSteward(target, () => clientFor(ctx, target).admin.settings.get());
1320
+ out.out(JSON.stringify(settings, null, 2));
1321
+ return 0;
1322
+ }
1323
+ if (sub === "set") {
1324
+ const { values, positionals } = parse(rest, SET_OPTIONS, "settings");
1325
+ if (values.help) {
1326
+ out.out(SETTINGS_USAGE);
1327
+ return 0;
1328
+ }
1329
+ expectPositionals(positionals, 0, 0, "settings");
1330
+ const { help: _help, ...flags } = values;
1331
+ const patch = buildSettingsPatch(flags);
1332
+ const target = requireAdminTarget(await resolveEnv(ctx));
1333
+ out.err(connectionLine(target));
1334
+ const settings = await callSteward(target, () => clientFor(ctx, target).admin.settings.update(patch));
1335
+ out.err(`ayarlar güncellendi → ${originOf(target.url)} (${Object.keys(patch).join(", ")})`);
1336
+ out.out(JSON.stringify(settings, null, 2));
1337
+ return 0;
1338
+ }
1339
+ throw new UsageError(`bilinmeyen alt komut: settings ${sub} (ayrıntı: steward settings --help)`);
1340
+ }
1341
+ //#endregion
1342
+ //#region src/main.ts
1343
+ const CLI_VERSION = "0.1.0";
1344
+ const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
1345
+
1346
+ Kullanım: steward <komut> [seçenekler]
1347
+
1348
+ Komutlar:
1349
+ dev [--product <kod>] [--catalog <dosya>] yerel steward (Docker) + .env.local
1350
+ dev reset --yes yerel veritabanını ve kimlik dosyasını sıfırla
1351
+ doctor [--json] kurulum teşhisi (GET /v1/doctor)
1352
+ catalog push <dosya> katalog senkronu (PUT /v1/admin/catalog)
1353
+ settings get | set [bayraklar] ürün ayarları (/v1/admin/settings)
1354
+ endpoints list | add | rotate | deactivate webhook endpoint'leri; sır yalnızca --out dosyasına
1355
+
1356
+ Bağlantı: yönetim komutları STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY, doctor
1357
+ STEWARD_URL + STEWARD_API_KEY (yoksa admin çifti). Ortamda bu dört değişkenden
1358
+ biri bile varsa hepsi (ve APP_URL) ortamdan okunur, ./.env.local hiç okunmaz;
1359
+ yoksa ./.env.local'den. Kullanılan kaynak stderr'e yazılır (bağlantı: …).
1360
+ Değişikliklerde X-Actor-Ref operator:<kullanıcı>. CLI sırları terminale yazmaz
1361
+ ve kubectl çağırmaz.
1362
+
1363
+ Ayrıntı: steward <komut> --help`;
1364
+ const COMMANDS = {
1365
+ dev: devCommand,
1366
+ doctor: doctorCommand,
1367
+ catalog: catalogCommand,
1368
+ settings: settingsCommand,
1369
+ endpoints: endpointsCommand
1370
+ };
1371
+ async function main(argv, ctx) {
1372
+ const out = createOutput(ctx.stdout, ctx.stderr);
1373
+ const [name, ...args] = argv[0] === "--" ? argv.slice(1) : argv;
1374
+ if (name === void 0) {
1375
+ out.err(USAGE);
1376
+ return 2;
1377
+ }
1378
+ if (name === "--help" || name === "-h" || name === "help") {
1379
+ out.out(USAGE);
1380
+ return 0;
1381
+ }
1382
+ if (name === "--version" || name === "-v") {
1383
+ out.out(CLI_VERSION);
1384
+ return 0;
1385
+ }
1386
+ const command = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : void 0;
1387
+ if (command === void 0) {
1388
+ out.err(`steward: bilinmeyen komut: ${name}\n\n${USAGE}`);
1389
+ return 2;
1390
+ }
1391
+ try {
1392
+ return await command(ctx, out, args);
1393
+ } catch (error) {
1394
+ if (error instanceof CliError) {
1395
+ out.err(`steward ${name}: ${error.message}`);
1396
+ return error.exitCode;
1397
+ }
1398
+ if (error instanceof StewardError) {
1399
+ out.err(`steward ${name}: ${describeStewardError(error)}`);
1400
+ return 1;
1401
+ }
1402
+ out.err(`steward ${name}: beklenmeyen hata: ${error instanceof Error ? error.message : String(error)}`);
1403
+ return 1;
1404
+ }
1405
+ }
1406
+ //#endregion
1407
+ //#region src/bin.ts
1408
+ const run = (command, args, { cwd, capture = false }) => new Promise((resolve) => {
1409
+ const child = spawn(command, [...args], {
1410
+ cwd,
1411
+ stdio: capture ? [
1412
+ "ignore",
1413
+ "pipe",
1414
+ "pipe"
1415
+ ] : [
1416
+ "ignore",
1417
+ 2,
1418
+ 2
1419
+ ]
1420
+ });
1421
+ let stdout = "";
1422
+ let stderr = "";
1423
+ child.stdout?.setEncoding("utf8").on("data", (chunk) => stdout += chunk);
1424
+ child.stderr?.setEncoding("utf8").on("data", (chunk) => stderr += chunk);
1425
+ child.on("error", (error) => resolve({
1426
+ code: 127,
1427
+ stdout,
1428
+ stderr: error.message
1429
+ }));
1430
+ child.on("close", (code) => resolve({
1431
+ code: code ?? 1,
1432
+ stdout,
1433
+ stderr
1434
+ }));
1435
+ });
1436
+ const ctx = {
1437
+ cwd: process.cwd(),
1438
+ env: process.env,
1439
+ stdout: process.stdout,
1440
+ stderr: process.stderr,
1441
+ fetch: globalThis.fetch,
1442
+ run,
1443
+ sleep: (ms) => setTimeout(ms),
1444
+ now: () => Date.now(),
1445
+ username: () => {
1446
+ try {
1447
+ return userInfo().username;
1448
+ } catch {
1449
+ return process.env.USER ?? process.env.USERNAME ?? "";
1450
+ }
1451
+ },
1452
+ platform: process.platform,
1453
+ hostUser: () => typeof process.getuid === "function" && typeof process.getgid === "function" ? {
1454
+ uid: process.getuid(),
1455
+ gid: process.getgid()
1456
+ } : null,
1457
+ typescript: Boolean(process.features.typescript),
1458
+ importModule: (url) => import(url)
1459
+ };
1460
+ process.exitCode = await main(process.argv.slice(2), ctx);
1461
+ //#endregion
1462
+ export {};