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