@referalli/cli 0.1.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -5,7 +5,22 @@ All notable changes to `@referalli/cli` are recorded here. The format follows
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html). Before 1.0, a minor
6
6
  bump may include breaking changes; they are called out under **Changed**.
7
7
 
8
+ ## 0.3.0 - 2026-11-02
9
+
10
+ - `trigger --stripe <event> --connection <id> [--data JSON]`: send a Stripe event fixture into a test-mode billing connection (`POST /v1/sandbox/stripe-fixtures`) and print the commissions it created.
11
+ - `plan <file>` and `apply <file> [--plan] [--check] [--secret-file PATH]`: declarative config for programs, commission rules, Stripe credit settings, webhook endpoints and API keys (YAML or JSON). Matched by slug, url and name + owner; creates send an `Idempotency-Key`; `--check` exits 2 on drift (1 is an error); no deletes, rotations or revocations.
12
+ - New runtime dependency: `js-yaml`.
13
+ - `api --secret-file <path>`: write a returned secret (API key, webhook signing secret) to a new 0600 file instead of printing it.
14
+ - API additions from `referalli` 0.3.0: one-call referrers, partner summary, portal links, program-scoped API keys and the Stripe balance credit rail.
15
+
16
+ ## 0.2.0 - 2026-10-24
17
+
18
+ - API 2026-11-01 additions: 56 new operations (inbound signup connectors, billing product filters, per-org SSO and partner-portal sign-in, support-tool context cards, data-rights executors, account closure, rewards, integration health, plans, the event feed and bulk webhook replay) and 2 webhook topics (`webhook_endpoint.failing`, `webhook_endpoint.recovered`).
19
+ - New error code `reauth_required` (401): sign in again before changing payout details.
20
+ - `events tail --since` backfills from `/v1/events` before tailing live.
21
+
8
22
  ## [Unreleased]
9
23
 
10
24
  ### Added
11
25
  - First public release: `referalli login`, `whoami`, `keys`, `listen --forward-to`, `trigger`, `events tail`, `logs tail`, `api` and `open`.
26
+ - `events tail --since 1h` (or an ISO time) prints the events since then from `GET /v1/events`, then tails live without repeating them.
package/README.md CHANGED
@@ -45,6 +45,7 @@ A triggered event is sent to every running `listen` session and to your webhook
45
45
  ```sh
46
46
  referalli events tail # every event, one line each
47
47
  referalli events tail --events payout.sent --json # full event bodies, for piping into jq
48
+ referalli events tail --since 2h # backfill the last two hours, then tail live
48
49
  referalli logs tail # your API requests: method, path, status, latency
49
50
  ```
50
51
 
@@ -57,6 +58,8 @@ referalli keys revoke key_…
57
58
  referalli api GET /v1/partners
58
59
  referalli api POST /v1/links --data '{"partnerId":"prt_…","programId":"prg_…"}'
59
60
  referalli open docs # also: dashboard, keys, webhooks, spec, status
61
+ referalli plan referalli.yaml --check # declarative config; see https://referalli.com/docs (CLI page)
62
+ referalli apply referalli.yaml --secret-file new-secrets.json
60
63
  ```
61
64
 
62
65
  ## Environment
@@ -0,0 +1,71 @@
1
+ import type { Client } from './client.js';
2
+ /**
3
+ * `referalli plan|apply <file>`: make the account match a declarative file.
4
+ * Every resource is matched by a stable key (program slug, webhook url, API key
5
+ * name + owner); creates carry an Idempotency-Key derived from that key and the
6
+ * request, so a retried apply never creates twice. Nothing missing from the file
7
+ * is ever deleted, rotated or revoked.
8
+ */
9
+ export declare class ConfigError extends Error {
10
+ }
11
+ type Obj = Record<string, unknown>;
12
+ interface ProgramSpec extends Obj {
13
+ slug: string;
14
+ commissionRule?: Obj;
15
+ stripeCredits?: Obj & {
16
+ secretKeyEnv?: string;
17
+ };
18
+ }
19
+ interface WebhookSpec extends Obj {
20
+ url: string;
21
+ topics?: string[];
22
+ programs?: string[];
23
+ status?: 'active' | 'paused';
24
+ }
25
+ interface ApiKeySpec extends Obj {
26
+ name: string;
27
+ owner?: string;
28
+ programs?: string[];
29
+ }
30
+ export interface ApplyConfig {
31
+ programs: ProgramSpec[];
32
+ webhooks: WebhookSpec[];
33
+ apiKeys: ApiKeySpec[];
34
+ }
35
+ /** Parse and check a referalli.yaml (JSON is YAML too). */
36
+ export declare function parseConfig(text: string, file?: string): ApplyConfig;
37
+ export type Field = [name: string, from: unknown, to: unknown];
38
+ export interface Change {
39
+ action: 'create' | 'update' | 'noop';
40
+ kind: string;
41
+ label: string;
42
+ fields: Field[];
43
+ /** Performs the change; returns once-shown secrets as [label, value]. */
44
+ run?: (ctx: RunCtx) => Promise<Array<[string, string]>>;
45
+ }
46
+ interface RunCtx {
47
+ client: Client;
48
+ /** Program slug → id, filled in as programs are created. */
49
+ ids: Map<string, string>;
50
+ }
51
+ /** Compare the file with the account; nothing is written. */
52
+ export declare function buildPlan(client: Client, config: ApplyConfig, env: NodeJS.ProcessEnv): Promise<{
53
+ changes: Change[];
54
+ ids: Map<string, string>;
55
+ }>;
56
+ /** Plan lines. Values come from the file and the API's public fields: no secret is ever in them. */
57
+ export declare function formatPlan(changes: Change[]): string[];
58
+ export interface ApplyIo {
59
+ out(line: string): void;
60
+ env: NodeJS.ProcessEnv;
61
+ }
62
+ /**
63
+ * Plan (and with `apply`, perform) the file. Returns the exit code: 0, or 2
64
+ * with `check` when anything would change.
65
+ */
66
+ export declare function runApply(io: ApplyIo, client: Client, file: string, opts: {
67
+ apply: boolean;
68
+ check: boolean;
69
+ secretFile?: string;
70
+ }): Promise<number>;
71
+ export {};
@@ -0,0 +1,344 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { load } from 'js-yaml';
4
+ /**
5
+ * `referalli plan|apply <file>`: make the account match a declarative file.
6
+ * Every resource is matched by a stable key (program slug, webhook url, API key
7
+ * name + owner); creates carry an Idempotency-Key derived from that key and the
8
+ * request, so a retried apply never creates twice. Nothing missing from the file
9
+ * is ever deleted, rotated or revoked.
10
+ */
11
+ export class ConfigError extends Error {
12
+ }
13
+ // Program fields compared against GET /v1/programs/{id} and sent as-is on PATCH.
14
+ const PROGRAM_TOP = ['name', 'attributionModel', 'cookieWindowDays', 'signupToConversionDays', 'termsMd', 'status', 'publicHandle'];
15
+ // Program settings: PATCH takes them top-level, GET returns them under `settings`.
16
+ const PROGRAM_SETTINGS = ['probabilisticPolicy', 'selfReferralPolicy', 'splitCommissions', 'allowPaidSearch', 'challengeLinks', 'settlement'];
17
+ const PROGRAM_KEYS = ['slug', ...PROGRAM_TOP, ...PROGRAM_SETTINGS, 'destinationUrl', 'commissionRule', 'stripeCredits'];
18
+ const STRIPE_KEYS = ['enabled', 'referrerMatch', 'metadataKey', 'refereeRewards', 'secretKeyEnv'];
19
+ const WEBHOOK_KEYS = ['url', 'topics', 'programs', 'status', 'alertContacts'];
20
+ const API_KEY_KEYS = ['name', 'owner', 'mode', 'scopes', 'expiresInDays', 'programs', 'apiVersion'];
21
+ // What the API stores when a rule leaves these out (packages/commissions ruleConfigSchema).
22
+ const RULE_DEFAULTS = { appliesTo: 'gross', recurring: { type: 'lifetime' }, holdDays: 30, rounding: 'half_even', overrides: [] };
23
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
24
+ function checkKeys(o, allowed, where, required) {
25
+ if (!isObj(o))
26
+ throw new ConfigError(`${where}: expected a mapping`);
27
+ for (const k of Object.keys(o)) {
28
+ if (k === 'secretKey')
29
+ throw new ConfigError(`${where}: secrets never go in the file; use secretKeyEnv: ENV_VAR_NAME`);
30
+ if (!allowed.includes(k))
31
+ throw new ConfigError(`${where}: unknown field "${k}" (allowed: ${allowed.join(', ')})`);
32
+ }
33
+ if (required && (typeof o[required] !== 'string' || !o[required]))
34
+ throw new ConfigError(`${where}: "${required}" is required`);
35
+ }
36
+ const list = (v, where) => {
37
+ if (v === undefined || v === null)
38
+ return [];
39
+ if (!Array.isArray(v))
40
+ throw new ConfigError(`${where}: expected a list`);
41
+ return v;
42
+ };
43
+ /** Parse and check a referalli.yaml (JSON is YAML too). */
44
+ export function parseConfig(text, file = 'config') {
45
+ let doc;
46
+ try {
47
+ doc = load(text);
48
+ }
49
+ catch (err) {
50
+ throw new ConfigError(`${file}: ${err.message}`);
51
+ }
52
+ checkKeys(doc ?? {}, ['programs', 'webhooks', 'apiKeys'], file);
53
+ const d = (doc ?? {});
54
+ const programs = list(d.programs, 'programs').map((p, i) => {
55
+ const where = `programs[${i}]`;
56
+ checkKeys(p, PROGRAM_KEYS, where, 'slug');
57
+ if (p.commissionRule !== undefined && !isObj(p.commissionRule))
58
+ throw new ConfigError(`${where}.commissionRule: expected a mapping`);
59
+ if (p.stripeCredits !== undefined) {
60
+ checkKeys(p.stripeCredits, STRIPE_KEYS, `${where}.stripeCredits`);
61
+ if (typeof p.stripeCredits.enabled !== 'boolean')
62
+ throw new ConfigError(`${where}.stripeCredits: "enabled" (true/false) is required`);
63
+ }
64
+ return p;
65
+ });
66
+ const slugs = programs.map((p) => p.slug);
67
+ const dup = slugs.find((s, i) => slugs.indexOf(s) !== i);
68
+ if (dup)
69
+ throw new ConfigError(`programs: slug "${dup}" is listed twice`);
70
+ const webhooks = list(d.webhooks, 'webhooks').map((w, i) => {
71
+ checkKeys(w, WEBHOOK_KEYS, `webhooks[${i}]`, 'url');
72
+ if (w.status !== undefined && w.status !== 'active' && w.status !== 'paused')
73
+ throw new ConfigError(`webhooks[${i}].status: active or paused`);
74
+ return w;
75
+ });
76
+ const apiKeys = list(d.apiKeys, 'apiKeys').map((k, i) => {
77
+ checkKeys(k, API_KEY_KEYS, `apiKeys[${i}]`, 'name');
78
+ return k;
79
+ });
80
+ return { programs, webhooks, apiKeys };
81
+ }
82
+ /** Key-order-insensitive JSON, for comparing values. */
83
+ const canon = (v) => JSON.stringify(v, (_k, x) => (isObj(x) ? Object.fromEntries(Object.entries(x).sort(([a], [b]) => a.localeCompare(b))) : x));
84
+ const same = (a, b) => canon(a ?? null) === canon(b ?? null);
85
+ const sorted = (v) => [...(v ?? [])].sort();
86
+ /** An Idempotency-Key that is the same for a retry of the same create, and only for that. */
87
+ const idemKey = (kind, key, body) => `referalli-apply-${kind}-${createHash('sha256').update(`${key}\n${canon(body)}`).digest('hex').slice(0, 40)}`;
88
+ const create = (client, path, kind, key, body) => client.request('POST', path, body, { headers: { 'idempotency-key': idemKey(kind, key, body) } });
89
+ /** Every row of a list endpoint: a plain array, or the 2026-11-01 list envelope followed page by page. */
90
+ async function listAll(client, path) {
91
+ const out = [];
92
+ let url = path;
93
+ for (;;) {
94
+ const res = await client.request('GET', url);
95
+ if (Array.isArray(res))
96
+ return res;
97
+ out.push(...res.data);
98
+ if (!res.has_more || res.data.length === 0)
99
+ return out;
100
+ url = `${path}${path.includes('?') ? '&' : '?'}limit=100&starting_after=${encodeURIComponent(res.data.at(-1).id)}`;
101
+ }
102
+ }
103
+ const programIdsFor = (ctx, slugs) => slugs?.length
104
+ ? slugs.map((s) => {
105
+ const id = ctx.ids.get(s);
106
+ if (!id)
107
+ throw new ConfigError(`unknown program "${s}" (not on the account and not in the file)`);
108
+ return id;
109
+ })
110
+ : null;
111
+ /** Compare the file with the account; nothing is written. */
112
+ export async function buildPlan(client, config, env) {
113
+ const changes = [];
114
+ const programs = await listAll(client, '/v1/programs');
115
+ const ids = new Map(programs.map((p) => [p.slug, p.id]));
116
+ const slugOf = new Map(programs.map((p) => [p.id, p.slug]));
117
+ const known = new Set([...ids.keys(), ...config.programs.map((p) => p.slug)]);
118
+ const checkRefs = (refs, where) => {
119
+ for (const s of refs ?? [])
120
+ if (!known.has(s))
121
+ throw new ConfigError(`${where}: unknown program "${s}"`);
122
+ };
123
+ for (const spec of config.programs) {
124
+ const cur = programs.find((p) => p.slug === spec.slug);
125
+ const label = `program "${spec.slug}"`;
126
+ const desired = {};
127
+ for (const k of [...PROGRAM_TOP, ...PROGRAM_SETTINGS, 'destinationUrl'])
128
+ if (spec[k] !== undefined)
129
+ desired[k] = spec[k];
130
+ if (!cur) {
131
+ const { destinationUrl, ...rest } = desired;
132
+ // POST takes the destination as the widget setting; PATCH moves it (and its links).
133
+ const body = { slug: spec.slug, name: spec.slug, ...rest, ...(destinationUrl ? { widget: { destinationUrl } } : {}) };
134
+ changes.push({
135
+ action: 'create',
136
+ kind: 'program',
137
+ label,
138
+ fields: Object.entries(desired).map(([k, v]) => [k, undefined, v]),
139
+ run: async (ctx) => {
140
+ const made = await create(ctx.client, '/v1/programs', 'program', spec.slug, body);
141
+ ctx.ids.set(spec.slug, made.id);
142
+ return [];
143
+ },
144
+ });
145
+ }
146
+ else {
147
+ const now = (k) => k === 'destinationUrl'
148
+ ? (cur.settings.widget?.destinationUrl ?? null)
149
+ : PROGRAM_SETTINGS.includes(k)
150
+ ? cur.settings[k]
151
+ : cur[k];
152
+ const fields = Object.entries(desired)
153
+ .filter(([k, v]) => !same(now(k), v))
154
+ .map(([k, v]) => [k, now(k), v]);
155
+ const patch = Object.fromEntries(fields.map(([k, , v]) => [k, v]));
156
+ changes.push({
157
+ action: fields.length ? 'update' : 'noop',
158
+ kind: 'program',
159
+ label,
160
+ fields,
161
+ run: async (ctx) => {
162
+ await ctx.client.request('PATCH', `/v1/programs/${cur.id}`, patch);
163
+ return [];
164
+ },
165
+ });
166
+ }
167
+ if (spec.commissionRule) {
168
+ const want = { ...RULE_DEFAULTS, ...spec.commissionRule };
169
+ const rlabel = `commissionRule "${spec.slug}"`;
170
+ const latest = cur ? (await listAll(client, `/v1/commission-rules?programId=${encodeURIComponent(cur.id)}`))[0] : undefined;
171
+ const publish = async (ctx) => {
172
+ const programId = ctx.ids.get(spec.slug);
173
+ await create(ctx.client, '/v1/commission-rules', 'rule', spec.slug, { programId, config: spec.commissionRule });
174
+ return [];
175
+ };
176
+ if (!latest) {
177
+ changes.push({ action: 'create', kind: 'commissionRule', label: rlabel, fields: Object.entries(spec.commissionRule).map(([k, v]) => [k, undefined, v]), run: publish });
178
+ }
179
+ else {
180
+ const keys = [...new Set([...Object.keys(want), ...Object.keys(latest.config)])];
181
+ const fields = keys.filter((k) => !same(latest.config[k], want[k])).map((k) => [k, latest.config[k], want[k]]);
182
+ changes.push({ action: fields.length ? 'update' : 'noop', kind: 'commissionRule', label: `${rlabel} (v${latest.version})`, fields, run: publish });
183
+ }
184
+ }
185
+ if (spec.stripeCredits) {
186
+ const { secretKeyEnv, ...s } = spec.stripeCredits;
187
+ const want = { enabled: s.enabled, referrerMatch: s.referrerMatch ?? 'billing_link', metadataKey: s.metadataKey ?? null, refereeRewards: s.refereeRewards ?? false };
188
+ const curS = cur ? await client.request('GET', `/v1/programs/${cur.id}/stripe-credits`) : null;
189
+ const fields = Object.keys(want)
190
+ .filter((k) => !curS || !same(curS[k], want[k]))
191
+ .map((k) => [k, curS?.[k], want[k]]);
192
+ // shortcut: the API never returns the key, so one already set is left alone; replace it with `referalli api PUT`.
193
+ const sendKey = Boolean(secretKeyEnv) && !curS?.hasOwnKey;
194
+ if (sendKey) {
195
+ if (!env[secretKeyEnv])
196
+ throw new ConfigError(`programs "${spec.slug}".stripeCredits: environment variable ${secretKeyEnv} is not set`);
197
+ fields.push(['secretKey', curS ? '(none)' : undefined, `(from $${secretKeyEnv})`]);
198
+ }
199
+ changes.push({
200
+ action: !curS ? 'create' : fields.length ? 'update' : 'noop',
201
+ kind: 'stripeCredits',
202
+ label: `stripeCredits "${spec.slug}"`,
203
+ fields,
204
+ run: async (ctx) => {
205
+ const body = { ...want, metadataKey: want.metadataKey ?? undefined, ...(sendKey ? { secretKey: env[secretKeyEnv] } : {}) };
206
+ await ctx.client.request('PUT', `/v1/programs/${ctx.ids.get(spec.slug)}/stripe-credits`, body);
207
+ return [];
208
+ },
209
+ });
210
+ }
211
+ }
212
+ if (config.webhooks.length) {
213
+ const endpoints = await listAll(client, '/v1/webhook-endpoints');
214
+ for (const spec of config.webhooks) {
215
+ checkRefs(spec.programs, `webhook ${spec.url}`);
216
+ const cur = endpoints.find((e) => e.url === spec.url);
217
+ const want = { topics: sorted(spec.topics ?? ['*']), programs: sorted(spec.programs), status: spec.status ?? 'active' };
218
+ if (spec.alertContacts !== undefined)
219
+ want.alertContacts = sorted(spec.alertContacts);
220
+ const label = `webhook ${spec.url}`;
221
+ const body = (ctx) => ({
222
+ topics: want.topics,
223
+ programIds: programIdsFor(ctx, spec.programs),
224
+ status: want.status,
225
+ ...(want.alertContacts ? { alertContacts: want.alertContacts } : {}),
226
+ });
227
+ if (!cur) {
228
+ changes.push({
229
+ action: 'create',
230
+ kind: 'webhook',
231
+ label,
232
+ fields: Object.entries(want).map(([k, v]) => [k, undefined, v]),
233
+ run: async (ctx) => {
234
+ const made = await create(ctx.client, '/v1/webhook-endpoints', 'webhook', spec.url, { url: spec.url, ...body(ctx) });
235
+ return [[`webhook ${spec.url}`, made.secret]];
236
+ },
237
+ });
238
+ continue;
239
+ }
240
+ const now = {
241
+ topics: sorted(cur.topics),
242
+ programs: sorted((cur.programIds ?? []).map((id) => slugOf.get(id) ?? id)),
243
+ status: cur.status,
244
+ alertContacts: sorted(cur.alertContacts),
245
+ };
246
+ const fields = Object.keys(want).filter((k) => !same(now[k], want[k])).map((k) => [k, now[k], want[k]]);
247
+ changes.push({
248
+ action: fields.length ? 'update' : 'noop',
249
+ kind: 'webhook',
250
+ label,
251
+ fields,
252
+ run: async (ctx) => {
253
+ await ctx.client.request('PATCH', `/v1/webhook-endpoints/${cur.id}`, body(ctx));
254
+ return [];
255
+ },
256
+ });
257
+ }
258
+ }
259
+ for (const spec of config.apiKeys) {
260
+ checkRefs(spec.programs, `apiKey "${spec.name}"`);
261
+ const owner = spec.owner ?? null;
262
+ const label = `apiKey "${spec.name}"${owner ? ` (owner ${owner})` : ''}`;
263
+ const existing = await listAll(client, `/v1/api-keys${owner ? `?owner=${encodeURIComponent(owner)}` : ''}`);
264
+ // Create-only: an existing key is never rotated, revoked or edited from the file.
265
+ if (existing.some((k) => k.name === spec.name && (k.owner ?? null) === owner && !k.revokedAt)) {
266
+ changes.push({ action: 'noop', kind: 'apiKey', label, fields: [] });
267
+ continue;
268
+ }
269
+ const { programs: refs, ...rest } = spec;
270
+ const shown = { mode: 'both', ...rest };
271
+ changes.push({
272
+ action: 'create',
273
+ kind: 'apiKey',
274
+ label,
275
+ fields: Object.entries({ ...shown, ...(refs ? { programs: refs } : {}) }).map(([k, v]) => [k, undefined, v]),
276
+ run: async (ctx) => {
277
+ const programIds = programIdsFor(ctx, refs);
278
+ const res = await create(ctx.client, '/v1/api-keys', 'apikey', `${spec.name}\n${owner ?? ''}`, { ...shown, ...(programIds ? { programIds } : {}) });
279
+ const issued = (isObj(res.live) ? [res.live, res.test] : [res]);
280
+ return issued.map((k) => [`apiKey ${spec.name}${owner ? ` (${owner})` : ''} ${k.livemode ? 'live' : 'test'}`, k.key]);
281
+ },
282
+ });
283
+ }
284
+ return { changes, ids };
285
+ }
286
+ // --- output ----------------------------------------------------------------------
287
+ const show = (v) => (v === undefined ? '(unset)' : JSON.stringify(v));
288
+ const SIGN = { create: '+ create', update: '~ update', noop: '= unchanged' };
289
+ /** Plan lines. Values come from the file and the API's public fields: no secret is ever in them. */
290
+ export function formatPlan(changes) {
291
+ const lines = [];
292
+ for (const c of changes) {
293
+ lines.push(`${SIGN[c.action]} ${c.label}`);
294
+ for (const [k, from, to] of c.fields)
295
+ lines.push(c.action === 'create' ? ` ${k}: ${show(to)}` : ` ${k}: ${show(from)} → ${show(to)}`);
296
+ }
297
+ const n = (a) => changes.filter((c) => c.action === a).length;
298
+ lines.push(`Plan: ${n('create')} to create, ${n('update')} to update, ${n('noop')} unchanged.`);
299
+ return lines;
300
+ }
301
+ /**
302
+ * Plan (and with `apply`, perform) the file. Returns the exit code: 0, or 2
303
+ * with `check` when anything would change.
304
+ */
305
+ export async function runApply(io, client, file, opts) {
306
+ const config = parseConfig(readFileSync(file, 'utf8'), file);
307
+ const { changes, ids } = await buildPlan(client, config, io.env);
308
+ for (const line of formatPlan(changes))
309
+ io.out(line);
310
+ const pending = changes.filter((c) => c.action !== 'noop');
311
+ if (opts.check) {
312
+ if (pending.length)
313
+ io.out('Drift: the account does not match the file.');
314
+ return pending.length ? 2 : 0; // 2, not 1: CI can tell drift from an error
315
+ }
316
+ if (!opts.apply || pending.length === 0)
317
+ return 0;
318
+ // Checked first: a secret file that can't be written after the creates would lose the secrets.
319
+ if (opts.secretFile && existsSync(opts.secretFile))
320
+ throw new ConfigError(`--secret-file ${opts.secretFile} already exists; pick a new path`);
321
+ const ctx = { client, ids };
322
+ const secrets = [];
323
+ try {
324
+ for (const c of pending) {
325
+ secrets.push(...(await c.run(ctx)));
326
+ io.out(`${c.action === 'create' ? 'Created' : 'Updated'} ${c.label}`);
327
+ }
328
+ }
329
+ finally {
330
+ // Even when a later change fails, secrets already issued are handed over: they can't be fetched again.
331
+ if (secrets.length && opts.secretFile) {
332
+ writeFileSync(opts.secretFile, `${JSON.stringify(Object.fromEntries(secrets), null, 2)}\n`, { mode: 0o600, flag: 'wx' });
333
+ chmodSync(opts.secretFile, 0o600);
334
+ io.out(`New secrets written to ${opts.secretFile} (mode 600). They are shown once.`);
335
+ }
336
+ else if (secrets.length) {
337
+ io.out('New secrets, shown once. Store them now:');
338
+ for (const [label, value] of secrets)
339
+ io.out(` ${label} ${value}`);
340
+ }
341
+ }
342
+ io.out(`Apply complete: ${pending.length} change(s).`);
343
+ return 0;
344
+ }
@@ -9,6 +9,7 @@ export interface Client {
9
9
  baseUrl: string;
10
10
  request<T = unknown>(method: string, path: string, body?: unknown, opts?: {
11
11
  signal?: AbortSignal;
12
+ headers?: Record<string, string>;
12
13
  }): Promise<T>;
13
14
  }
14
15
  export declare function createClient(opts: {
@@ -15,7 +15,7 @@ export function createClient(opts) {
15
15
  return {
16
16
  baseUrl,
17
17
  async request(method, path, body, ropts = {}) {
18
- const headers = { 'user-agent': `referalli-cli/${VERSION}` };
18
+ const headers = { 'user-agent': `referalli-cli/${VERSION}`, ...ropts.headers };
19
19
  if (opts.key)
20
20
  headers.authorization = `Bearer ${opts.key}`;
21
21
  if (body !== undefined)
@@ -25,6 +25,8 @@ export declare function listen(io: Io, flags: Flags): Promise<number>;
25
25
  * `listen` does, without forwarding, and closes it on exit.
26
26
  */
27
27
  export declare function eventsTail(io: Io, flags: Flags): Promise<number>;
28
+ /** `--since`: an ISO time, or a duration back from now (`30m`, `2h`, `7d`). */
29
+ export declare function parseSince(raw: string, now: Date): Date;
28
30
  export declare const OPEN_TARGETS: Record<string, string>;
29
31
  /** `referalli open [docs|dashboard|keys|webhooks|spec|status]`: open the page, or print it. */
30
32
  export declare function open(io: Io, target: string | undefined, flags: Flags): Promise<number>;
@@ -36,3 +38,5 @@ export declare function logsTail(io: Io, flags: Flags): Promise<number>;
36
38
  */
37
39
  export declare function keys(io: Io, sub: string | undefined, arg: string | undefined, flags: Flags): Promise<number>;
38
40
  export declare function api(io: Io, method: string | undefined, path: string | undefined, flags: Flags): Promise<number>;
41
+ /** `referalli plan <file>` / `referalli apply <file> [--plan] [--check] [--secret-file PATH]`. */
42
+ export declare function apply(io: Io, file: string | undefined, flags: Flags, planOnly: boolean): Promise<number>;
@@ -1,4 +1,6 @@
1
+ import { chmodSync, writeFileSync } from 'node:fs';
1
2
  import { hostname } from 'node:os';
3
+ import { ConfigError, runApply } from './apply.js';
2
4
  import { ApiError, createClient } from './client.js';
3
5
  import { DEFAULT_BASE_URL, readConfig, removeConfig, writeConfig } from './config.js';
4
6
  /** A user-facing failure: printed without a stack trace, exit code 1. */
@@ -132,10 +134,38 @@ export async function eventsTail(io, flags) {
132
134
  const topics = typeof flags.events === 'string' ? flags.events.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
133
135
  const max = typeof flags.max === 'string' ? Number(flags.max) : Infinity;
134
136
  const wait = typeof flags.wait === 'string' ? Number(flags.wait) : 20;
137
+ const since = typeof flags.since === 'string' ? parseSince(flags.since, new Date()) : null;
138
+ // Open the listener first so nothing emitted during the backfill is missed.
135
139
  const listener = await client.request('POST', '/v1/cli/listeners', topics ? { topics } : {});
140
+ let seen = 0;
141
+ const backfilled = new Set();
142
+ if (since) {
143
+ if (!flags.json)
144
+ io.err(`Events since ${since.toISOString()}:`);
145
+ let after = null;
146
+ do {
147
+ const qs = new URLSearchParams({ since: since.toISOString(), limit: '100' });
148
+ if (topics)
149
+ qs.set('topics', topics.join(','));
150
+ if (after)
151
+ qs.set('after', after);
152
+ const page = await client.request('GET', `/v1/events?${qs.toString()}`, undefined, { signal: io.signal });
153
+ for (const e of page.events) {
154
+ if (seen >= max)
155
+ break;
156
+ seen++;
157
+ backfilled.add(e.id);
158
+ const body = JSON.stringify(e);
159
+ if (flags.json)
160
+ io.out(body);
161
+ else
162
+ io.out(`${time(new Date(e.createdAt))} ${e.topic.padEnd(24)} ${e.id}${summarize(body)}`);
163
+ }
164
+ after = page.nextCursor;
165
+ } while (after && seen < max && !io.signal.aborted);
166
+ }
136
167
  if (!flags.json)
137
168
  io.err(`Tailing ${listener.topics.join(', ')} (Ctrl-C to stop)…`);
138
- let seen = 0;
139
169
  try {
140
170
  while (!io.signal.aborted && seen < max) {
141
171
  let batch;
@@ -152,6 +182,8 @@ export async function eventsTail(io, flags) {
152
182
  continue;
153
183
  }
154
184
  for (const e of batch) {
185
+ if (backfilled.has(e.eventId))
186
+ continue; // already printed by the backfill
155
187
  seen++;
156
188
  if (flags.json)
157
189
  io.out(e.body);
@@ -167,6 +199,18 @@ export async function eventsTail(io, flags) {
167
199
  }
168
200
  return 0;
169
201
  }
202
+ /** `--since`: an ISO time, or a duration back from now (`30m`, `2h`, `7d`). */
203
+ export function parseSince(raw, now) {
204
+ const m = /^(\d+)\s*([mhd])$/i.exec(raw.trim());
205
+ if (m) {
206
+ const unit = { m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2].toLowerCase()];
207
+ return new Date(now.getTime() - Number(m[1]) * unit);
208
+ }
209
+ const d = new Date(raw);
210
+ if (Number.isNaN(d.getTime()))
211
+ throw new CliError('--since takes a duration (30m, 2h, 7d) or an ISO 8601 time');
212
+ return d;
213
+ }
170
214
  /** A short "key=value" tail for an event line: the ids and amounts a developer looks for. */
171
215
  function summarize(body) {
172
216
  try {
@@ -203,6 +247,8 @@ export async function open(io, target, flags) {
203
247
  // --- trigger -----------------------------------------------------------------------
204
248
  export async function trigger(io, topic, flags) {
205
249
  const { client } = signedIn(io);
250
+ if (typeof flags.stripe === 'string')
251
+ return triggerStripe(io, client, flags.stripe, flags);
206
252
  if (!topic) {
207
253
  const { topics } = await client.request('GET', '/v1/cli/topics');
208
254
  throw new CliError(`Usage: referalli trigger <topic>. Topics: ${topics.join(', ')}`);
@@ -220,6 +266,29 @@ export async function trigger(io, topic, flags) {
220
266
  io.out(`Triggered ${topic} [${res.eventId}]: ${res.deliveredTo.listeners} listener(s), ${res.deliveredTo.endpoints} webhook endpoint(s).`);
221
267
  return 0;
222
268
  }
269
+ /** `trigger --stripe <event> --connection <id> [--data overrides]`: a Stripe fixture into a test-mode billing connection. */
270
+ async function triggerStripe(io, client, event, flags) {
271
+ if (typeof flags.connection !== 'string') {
272
+ throw new CliError('Usage: referalli trigger --stripe <event> --connection <billing connection id> [--data JSON]');
273
+ }
274
+ let overrides = {};
275
+ if (typeof flags.data === 'string') {
276
+ try {
277
+ overrides = JSON.parse(flags.data);
278
+ }
279
+ catch {
280
+ throw new CliError('--data must be a JSON object, e.g. --data \'{"customerRef": "cus_123", "amountMinor": 4900}\'');
281
+ }
282
+ }
283
+ // `eventId` in --data replays that event instead of sending a new one.
284
+ const { eventId, ...rest } = overrides;
285
+ const res = await client.request('POST', '/v1/sandbox/stripe-fixtures', { connectionId: flags.connection, event, overrides: rest, ...(eventId !== undefined ? { eventId } : {}) });
286
+ const dup = res.results.some((r) => r.duplicate) ? ' (duplicate)' : '';
287
+ io.out(`Sent ${event} [${res.eventId}]${dup}: ${res.received} billing event(s), ${res.commissions.length} commission event(s).`);
288
+ for (const c of res.commissions)
289
+ io.out(` ${c.type} ${c.amountMinor} ${c.currency} ${c.id}`);
290
+ return 0;
291
+ }
223
292
  const logLine = (e) => `${time(e.ts)} ${e.method.padEnd(6)} ${e.path} ${e.status} ${e.latencyMs}ms ${e.requestId}`;
224
293
  export async function logsTail(io, flags) {
225
294
  const { client } = signedIn(io);
@@ -312,7 +381,7 @@ export async function keys(io, sub, arg, flags) {
312
381
  // --- api ---------------------------------------------------------------------------
313
382
  export async function api(io, method, path, flags) {
314
383
  if (!method || !path)
315
- throw new CliError('Usage: referalli api <METHOD> <path> [--data JSON]');
384
+ throw new CliError('Usage: referalli api <METHOD> <path> [--data JSON] [--secret-file PATH]');
316
385
  const { client } = signedIn(io);
317
386
  let body;
318
387
  if (typeof flags.data === 'string') {
@@ -324,6 +393,39 @@ export async function api(io, method, path, flags) {
324
393
  }
325
394
  }
326
395
  const res = await client.request(method.toUpperCase(), path.startsWith('/') ? path : `/${path}`, body);
396
+ if (typeof flags['secret-file'] === 'string') {
397
+ // A secret shown once (a billing connection's webhookSecret, a new key): to a 0600 file, never to the terminal.
398
+ const field = SECRET_FIELDS.find((f) => typeof res?.[f] === 'string');
399
+ if (!field)
400
+ throw new CliError(`--secret-file: the response has no ${SECRET_FIELDS.join(', ')} field`);
401
+ const file = flags['secret-file'];
402
+ writeFileSync(file, `${res[field]}\n`, { mode: 0o600, flag: 'wx' });
403
+ chmodSync(file, 0o600);
404
+ io.out(JSON.stringify({ ...res, [field]: `(written to ${file})` }, null, 2));
405
+ return 0;
406
+ }
327
407
  io.out(JSON.stringify(res, null, 2));
328
408
  return 0;
329
409
  }
410
+ const SECRET_FIELDS = ['webhookSecret', 'secret', 'key'];
411
+ // --- plan / apply ------------------------------------------------------------------
412
+ /** `referalli plan <file>` / `referalli apply <file> [--plan] [--check] [--secret-file PATH]`. */
413
+ export async function apply(io, file, flags, planOnly) {
414
+ if (!file)
415
+ throw new CliError(planOnly ? 'Usage: referalli plan <referalli.yaml> [--check]' : 'Usage: referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]');
416
+ const { client } = signedIn(io);
417
+ try {
418
+ return await runApply(io, client, file, {
419
+ apply: !planOnly && !flags.plan,
420
+ check: flags.check === true,
421
+ secretFile: typeof flags['secret-file'] === 'string' ? flags['secret-file'] : undefined,
422
+ });
423
+ }
424
+ catch (err) {
425
+ if (err instanceof ConfigError)
426
+ throw new CliError(err.message);
427
+ if (err.code === 'ENOENT')
428
+ throw new CliError(`${file}: no such file`);
429
+ throw err;
430
+ }
431
+ }
@@ -3,6 +3,6 @@ export { readConfig, writeConfig, configPath, type CliConfig } from './config.js
3
3
  export { createClient, ApiError } from './client.js';
4
4
  export type { Io } from './commands.js';
5
5
  export { VERSION } from './version.js';
6
- export declare const HELP = "referalli: the Referalli command line\n\nUsage:\n referalli login [--key rk_\u2026] [--base-url URL] [--no-browser]\n referalli logout\n referalli whoami\n referalli listen [--forward-to URL] [--events topic,topic] [--max-events N]\n referalli trigger <topic> [--data JSON]\n referalli events tail [--events topic,topic] [--json] [--max N]\n referalli logs tail [--max N]\n referalli open [docs|dashboard|keys|webhooks|spec|status]\n referalli api <METHOD> <path> [--data JSON]\n referalli keys create --name NAME [--owner WHO] [--mode both|live|test] [--scopes full,\u2026] [--expires-days N]\n referalli keys list [--owner WHO] [--mode live|test]\n referalli keys revoke <key id> [--pair] [--cascade]\n\nEnvironment:\n REFERALLI_API_KEY use this key instead of the saved login\n REFERALLI_API_URL API base URL (default: the hosted API)\n REFERALLI_CONFIG_DIR where the login is saved (default ~/.config/referalli)";
6
+ export declare const HELP = "referalli: the Referalli command line\n\nUsage:\n referalli login [--key rk_\u2026] [--base-url URL] [--no-browser]\n referalli logout\n referalli whoami\n referalli listen [--forward-to URL] [--events topic,topic] [--max-events N]\n referalli trigger <topic> [--data JSON]\n referalli trigger --stripe <event> --connection <id> [--data JSON] (test mode)\n referalli events tail [--events topic,topic] [--since 1h|ISO] [--json] [--max N]\n referalli logs tail [--max N]\n referalli open [docs|dashboard|keys|webhooks|spec|status]\n referalli api <METHOD> <path> [--data JSON] [--secret-file PATH]\n referalli keys create --name NAME [--owner WHO] [--mode both|live|test] [--scopes full,\u2026] [--expires-days N]\n referalli keys list [--owner WHO] [--mode live|test]\n referalli keys revoke <key id> [--pair] [--cascade]\n referalli plan <referalli.yaml> [--check]\n referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]\n\nEnvironment:\n REFERALLI_API_KEY use this key instead of the saved login\n REFERALLI_API_URL API base URL (default: the hosted API)\n REFERALLI_CONFIG_DIR where the login is saved (default ~/.config/referalli)";
7
7
  /** Run one command; returns the process exit code. */
8
8
  export declare function runCli(argv: string[], io: Io): Promise<number>;
package/dist/src/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { parseArgs } from 'node:util';
2
2
  import { ApiError } from './client.js';
3
- import { api, CliError, eventsTail, keys, login, listen, logout, logsTail, open, trigger, whoami } from './commands.js';
3
+ import { api, apply, CliError, eventsTail, keys, login, listen, logout, logsTail, open, trigger, whoami } from './commands.js';
4
4
  import { VERSION } from './version.js';
5
5
  export { readConfig, writeConfig, configPath } from './config.js';
6
6
  export { createClient, ApiError } from './client.js';
@@ -13,13 +13,16 @@ Usage:
13
13
  referalli whoami
14
14
  referalli listen [--forward-to URL] [--events topic,topic] [--max-events N]
15
15
  referalli trigger <topic> [--data JSON]
16
- referalli events tail [--events topic,topic] [--json] [--max N]
16
+ referalli trigger --stripe <event> --connection <id> [--data JSON] (test mode)
17
+ referalli events tail [--events topic,topic] [--since 1h|ISO] [--json] [--max N]
17
18
  referalli logs tail [--max N]
18
19
  referalli open [docs|dashboard|keys|webhooks|spec|status]
19
- referalli api <METHOD> <path> [--data JSON]
20
+ referalli api <METHOD> <path> [--data JSON] [--secret-file PATH]
20
21
  referalli keys create --name NAME [--owner WHO] [--mode both|live|test] [--scopes full,…] [--expires-days N]
21
22
  referalli keys list [--owner WHO] [--mode live|test]
22
23
  referalli keys revoke <key id> [--pair] [--cascade]
24
+ referalli plan <referalli.yaml> [--check]
25
+ referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]
23
26
 
24
27
  Environment:
25
28
  REFERALLI_API_KEY use this key instead of the saved login
@@ -39,10 +42,14 @@ export async function runCli(argv, io) {
39
42
  'no-browser': { type: 'boolean' },
40
43
  'forward-to': { type: 'string' },
41
44
  events: { type: 'string' },
45
+ since: { type: 'string' },
42
46
  'max-events': { type: 'string' },
43
47
  max: { type: 'string' },
44
48
  wait: { type: 'string' },
45
49
  data: { type: 'string' },
50
+ stripe: { type: 'string' },
51
+ connection: { type: 'string' },
52
+ 'secret-file': { type: 'string' },
46
53
  name: { type: 'string' },
47
54
  owner: { type: 'string' },
48
55
  mode: { type: 'string' },
@@ -50,6 +57,8 @@ export async function runCli(argv, io) {
50
57
  'expires-days': { type: 'string' },
51
58
  pair: { type: 'boolean' },
52
59
  cascade: { type: 'boolean' },
60
+ plan: { type: 'boolean' },
61
+ check: { type: 'boolean' },
53
62
  json: { type: 'boolean' },
54
63
  help: { type: 'boolean', short: 'h' },
55
64
  version: { type: 'boolean', short: 'v' },
@@ -100,6 +109,9 @@ export async function runCli(argv, io) {
100
109
  return await api(io, rest[0], rest[1], flags);
101
110
  case 'keys':
102
111
  return await keys(io, rest[0], rest[1], flags);
112
+ case 'plan':
113
+ case 'apply':
114
+ return await apply(io, rest[0], flags, command === 'plan');
103
115
  default:
104
116
  io.err(`Unknown command "${command}".`);
105
117
  io.err(HELP);
@@ -1,2 +1,2 @@
1
1
  /** Kept in step with package.json by test/version.test.ts. */
2
- export declare const VERSION = "0.1.0";
2
+ export declare const VERSION = "0.3.0";
@@ -1,2 +1,2 @@
1
1
  /** Kept in step with package.json by test/version.test.ts. */
2
- export const VERSION = '0.1.0';
2
+ export const VERSION = '0.3.0';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@referalli/cli",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "The Referalli command line: sign in, forward webhooks to localhost, trigger test events, tail events and API logs.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -48,6 +48,9 @@
48
48
  "typecheck": "tsc --noEmit",
49
49
  "start": "tsx bin/referalli.ts"
50
50
  },
51
+ "dependencies": {
52
+ "js-yaml": "4.3.1"
53
+ },
51
54
  "devDependencies": {
52
55
  "@types/node": "^22.9.0",
53
56
  "tsx": "^4.19.2",