@referalli/cli 0.4.7 → 0.4.8

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.
@@ -425,15 +425,16 @@ export async function api(io, method, path, flags) {
425
425
  }
426
426
  const SECRET_FIELDS = ['webhookSecret', 'secret', 'key'];
427
427
  // --- plan / apply ------------------------------------------------------------------
428
- /** `referalli plan <file>` / `referalli apply <file> [--plan] [--check] [--secret-file PATH]`. */
428
+ /** `referalli plan <file> [--prune]` / `referalli apply <file> [--plan] [--check] [--prune] [--secret-file PATH]`. */
429
429
  export async function apply(io, file, flags, planOnly) {
430
430
  if (!file)
431
- throw new CliError(planOnly ? 'Usage: referalli plan <referalli.yaml> [--check]' : 'Usage: referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]');
431
+ throw new CliError(planOnly ? 'Usage: referalli plan <referalli.yaml> [--check] [--prune]' : 'Usage: referalli apply <referalli.yaml> [--plan] [--check] [--prune] [--secret-file PATH]');
432
432
  const { client } = signedIn(io);
433
433
  try {
434
434
  return await runApply(io, client, file, {
435
435
  apply: !planOnly && !flags.plan,
436
436
  check: flags.check === true,
437
+ prune: flags.prune === true,
437
438
  secretFile: typeof flags['secret-file'] === 'string' ? flags['secret-file'] : undefined,
438
439
  });
439
440
  }
@@ -450,7 +451,7 @@ export async function doctor(io, flags) {
450
451
  if (flags.strict && typeof flags.scan !== 'string')
451
452
  throw new CliError('--strict goes with --scan <dir>');
452
453
  if (flags.e2e && typeof flags.program !== 'string')
453
- throw new CliError('--e2e tests one program: add --program <id>');
454
+ throw new CliError('--e2e tests one program: add --program <id> (or set REFERALLI_PROGRAM_ID)');
454
455
  if (typeof flags.scan !== 'string')
455
456
  return runDoctor(io, signedIn(io).client, flags);
456
457
  try {
@@ -497,6 +498,23 @@ export async function partners(io, sub, flags) {
497
498
  io.err(`${rows.length} enrolled partner(s).`);
498
499
  return 0;
499
500
  }
501
+ // --- billing -----------------------------------------------------------------------
502
+ const BILLING_USAGE = 'Usage: referalli billing owner set <accountRef> <customerRef>';
503
+ /** `billing owner set <accountRef> <customerRef>`: the user whose referral an organization's payments earn for. */
504
+ export async function billing(io, args) {
505
+ const [what, verb, accountRef, ownerCustomerRef, ...extra] = args;
506
+ if (what !== 'owner' || verb !== 'set' || !accountRef || !ownerCustomerRef || extra.length > 0)
507
+ throw new CliError(BILLING_USAGE);
508
+ const { client } = signedIn(io);
509
+ const res = await client.request('PUT', `/v1/billing/accounts/${encodeURIComponent(accountRef)}/owner`, { ownerCustomerRef });
510
+ if (!res.changed)
511
+ io.out(`${accountRef} is already owned by ${ownerCustomerRef}: nothing changed.`);
512
+ else {
513
+ const was = res.previousOwnerCustomerRef ? ` (was ${res.previousOwnerCustomerRef})` : '';
514
+ io.out(`${accountRef} is now owned by ${ownerCustomerRef}${was}: ${res.relinked ?? 0} customer(s) relinked, ${res.reprocessedPayments ?? 0} earlier payment(s) reprocessed.`);
515
+ }
516
+ return 0;
517
+ }
500
518
  /**
501
519
  * `referalli env pull [--mode live|test]`: one mode's public ids as .env lines
502
520
  * on stdout (`> .env.test`). Default: the key's mode. Program ids differ per
@@ -8,6 +8,10 @@ export interface CliConfig {
8
8
  export declare const DEFAULT_BASE_URL = "https://referalli.com";
9
9
  export declare const configDir: (env?: NodeJS.ProcessEnv) => string;
10
10
  export declare const configPath: (env?: NodeJS.ProcessEnv) => string;
11
+ /** The pre-rename env names Referalli itself reads (the CLI's, above); no other package read a REFERALLY_* name. */
12
+ export declare const LEGACY_ENV: readonly string[];
13
+ /** When the CLI stops reading them (docs: Renamed from Referally). */
14
+ export declare const LEGACY_ENV_REMOVAL = "2027-03-31";
11
15
  /** The env with pre-rename names filled in under the new ones (a new name wins), and which were used. */
12
16
  export declare function withLegacyEnv(env: NodeJS.ProcessEnv): {
13
17
  env: NodeJS.ProcessEnv;
@@ -6,12 +6,16 @@ export const configDir = (env = process.env) => env.REFERALLI_CONFIG_DIR ?? join
6
6
  export const configPath = (env = process.env) => join(configDir(env), 'cli.json');
7
7
  const READ_ENV = ['REFERALLI_API_KEY', 'REFERALLI_API_URL', 'REFERALLI_CONFIG_DIR', 'REFERALLI_TRACKING_TOKEN', 'NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN'];
8
8
  const oldName = (name) => name.replace('REFERALLI_', 'REFERALLY_');
9
+ /** The pre-rename env names Referalli itself reads (the CLI's, above); no other package read a REFERALLY_* name. */
10
+ export const LEGACY_ENV = READ_ENV.map(oldName);
11
+ /** When the CLI stops reading them (docs: Renamed from Referally). */
12
+ export const LEGACY_ENV_REMOVAL = '2027-03-31';
9
13
  /** The env with pre-rename names filled in under the new ones (a new name wins), and which were used. */
10
14
  export function withLegacyEnv(env) {
11
15
  const used = READ_ENV.filter((name) => !env[name] && env[oldName(name)]);
12
16
  return {
13
17
  env: { ...env, ...Object.fromEntries(used.map((name) => [name, env[oldName(name)]])) },
14
- notice: used.length ? `Notice: read ${used.map((name) => `${oldName(name)} as ${name}`).join(', ')}; rename it (no removal date set).` : null,
18
+ notice: used.length ? `Notice: read ${used.map((name) => `${oldName(name)} as ${name}`).join(', ')}; rename it (read until ${LEGACY_ENV_REMOVAL}).` : null,
15
19
  };
16
20
  }
17
21
  export function readConfig(env = process.env) {
@@ -3,10 +3,14 @@ import type { Flags, Io } from './commands.js';
3
3
  /** One line of `referalli doctor`. */
4
4
  export interface Check {
5
5
  id: string;
6
- status: 'ok' | 'warn' | 'fail';
6
+ /** `info`: worth knowing, never a problem (doctor --scan: a REFERALLY_* name of the app's own). */
7
+ status: 'ok' | 'info' | 'warn' | 'fail';
7
8
  message: string;
8
9
  fix?: string;
9
10
  }
10
11
  export declare function printChecks(out: (line: string) => void, checks: Check[], json: unknown): void;
11
- /** `referalli doctor [--program <id>] [--json]`: read-only health checks, plus `--e2e`. Exit 1 when any check fails. */
12
+ /**
13
+ * `referalli doctor [--program <id>] [--json]`: read-only health checks, plus `--e2e`. Exit 1 when any check fails.
14
+ * Scope (R-08): --program (REFERALLI_PROGRAM_ID fills it in), else the key's programs, else every active program.
15
+ */
12
16
  export declare function runDoctor(io: Io, client: Client, flags: Flags, now?: Date): Promise<number>;
@@ -1,3 +1,4 @@
1
+ import { listAll } from './apply.js';
1
2
  import { ApiError } from './client.js';
2
3
  const DAY = 86_400_000;
3
4
  const reason = (err) => err instanceof ApiError ? `${err.status}${err.code ? ` ${err.code}` : ''}: ${err.message}` : err.message;
@@ -12,6 +13,7 @@ async function guard(id, fix, fn) {
12
13
  return [{ id, status: 'warn', message: `couldn't check: ${reason(err)}`, ...(fix ? { fix } : {}) }];
13
14
  }
14
15
  }
16
+ /** The key's checks, and the key itself for scoping the rest (null when it couldn't be read). */
15
17
  async function keyCheck(client, now) {
16
18
  let me;
17
19
  try {
@@ -19,13 +21,13 @@ async function keyCheck(client, now) {
19
21
  }
20
22
  catch (err) {
21
23
  if (err instanceof ApiError && err.status === 401) {
22
- return [{ id: 'key', status: 'fail', message: `the API key was refused: ${err.message}`, fix: 'referalli login' }];
24
+ return { checks: [{ id: 'key', status: 'fail', message: `the API key was refused: ${err.message}`, fix: 'referalli login' }], key: null };
23
25
  }
24
- throw err;
26
+ return { checks: [{ id: 'key', status: 'warn', message: `couldn't check: ${reason(err)}`, fix: 'referalli login' }], key: null };
25
27
  }
26
28
  const k = me.apiKey;
27
29
  if (!k)
28
- return [{ id: 'key', status: 'warn', message: 'signed in without an API key; key checks skipped', fix: 'referalli login' }];
30
+ return { checks: [{ id: 'key', status: 'warn', message: 'signed in without an API key; key checks skipped', fix: 'referalli login' }], key: null };
29
31
  const out = [
30
32
  { id: 'key', status: 'ok', message: `${k.livemode ? 'live' : 'test'} key "${k.name}", scopes: ${k.scopes.join(', ') || 'none'}` },
31
33
  ];
@@ -33,19 +35,20 @@ async function keyCheck(client, now) {
33
35
  out.push({ id: 'key.expiry', status: 'warn', message: `the key expires ${k.expiresAt}`, fix: 'referalli keys create --name NAME (then referalli login --key …)' });
34
36
  }
35
37
  if (k.programIds) {
36
- out.push({
37
- id: 'key.programs',
38
- status: 'warn',
39
- message: `the key is limited to programs ${k.programIds.join(', ')}: webhook and billing checks see only these programs, and org-wide checks are skipped (listed below)`,
40
- fix: 'run doctor with an org-wide key to check everything',
41
- });
38
+ // R-08: a scoped key is normal (one org, several products): the checks below cover its programs only.
39
+ out.push({ id: 'key.programs', status: 'ok', message: `the key is limited to programs ${k.programIds.join(', ')}: the checks below cover only these (org-wide ones it can't read say so)` });
42
40
  }
43
- return out;
41
+ return { checks: out, key: k };
44
42
  }
45
- async function termsChecks(client, programId) {
46
- const programs = programId
47
- ? [await client.request('GET', `/v1/programs/${encodeURIComponent(programId)}`)]
43
+ /** The programs doctor checks: the scope's (each fetched), else every active one. */
44
+ async function loadPrograms(client, scope) {
45
+ return scope
46
+ ? Promise.all(scope.map((id) => client.request('GET', `/v1/programs/${encodeURIComponent(id)}`)))
48
47
  : rows(await client.request('GET', '/v1/programs')).filter((p) => p.status === 'active');
48
+ }
49
+ /** Outside the scope: limited to programs, none of them in it. Org-wide (null) resources concern every program. */
50
+ const outside = (scope, programIds) => Boolean(scope && programIds && programIds.length > 0 && !programIds.some((id) => scope.includes(id)));
51
+ async function termsChecks(client, programs) {
49
52
  if (programs.length === 0)
50
53
  return [{ id: 'programs', status: 'warn', message: 'no active programs', fix: '/programs' }];
51
54
  return Promise.all(programs.map((p) => guard(`program.${p.id}.terms`, undefined, async () => {
@@ -60,8 +63,8 @@ async function termsChecks(client, programId) {
60
63
  }
61
64
  }))).then((all) => all.flat());
62
65
  }
63
- async function webhookChecks(client) {
64
- const endpoints = rows(await client.request('GET', '/v1/webhook-endpoints'));
66
+ async function webhookChecks(client, scope) {
67
+ const endpoints = rows(await client.request('GET', '/v1/webhook-endpoints')).filter((e) => !outside(scope, e.programIds));
65
68
  if (endpoints.length === 0)
66
69
  return [{ id: 'webhooks', status: 'ok', message: 'no webhook endpoints' }];
67
70
  return endpoints.map((e) => {
@@ -74,8 +77,8 @@ async function webhookChecks(client) {
74
77
  return { id, status: 'warn', message: `${e.url} is ${why}`, fix };
75
78
  });
76
79
  }
77
- async function billingChecks(client) {
78
- const conns = rows(await client.request('GET', '/v1/billing/connections'));
80
+ async function billingChecks(client, scope) {
81
+ const conns = rows(await client.request('GET', '/v1/billing/connections')).filter((c) => !outside(scope, c.programIds));
79
82
  if (conns.length === 0) {
80
83
  return [{ id: 'billing', status: 'warn', message: "no billing connection: payments won't earn commission", fix: 'POST /v1/billing/connections' }];
81
84
  }
@@ -90,9 +93,11 @@ async function billingChecks(client) {
90
93
  return { id, status: 'ok', message: `${label} is ${c.status}` };
91
94
  });
92
95
  }
93
- async function authChecks(client, now) {
94
- const conns = rows(await client.request('GET', '/v1/auth/connections'));
96
+ async function authChecks(client, now, programs, scope) {
97
+ const conns = rows(await client.request('GET', '/v1/auth/connections')).filter((c) => !scope || !c.programId || scope.includes(c.programId));
95
98
  const out = conns.map((c) => {
99
+ // Receipt time when the API has it: a late-filed sign-up must not look like a fresh one (R-30).
100
+ const lastSignupAt = c.lastSignupReceivedAt ?? c.lastSignupAt;
96
101
  const id = `auth.${c.id}`;
97
102
  const label = `${c.provider} auth connection${c.name ? ` "${c.name}"` : ''}`;
98
103
  if (c.status === 'paused')
@@ -101,19 +106,32 @@ async function authChecks(client, now) {
101
106
  return { id, status: 'warn', message: `${label} verifies tokens but has no allowedOrigins: the widget session refuses browsers`, fix: `PATCH /v1/auth/connections/${c.id} {"allowedOrigins":["https://your.app"]}` };
102
107
  }
103
108
  // A refusal newer than the last sign-up: the platform is calling, and its calls are failing.
104
- if (c.lastError && (!c.lastSignupAt || new Date(c.lastError.at) > new Date(c.lastSignupAt))) {
109
+ if (c.lastError && (!lastSignupAt || new Date(c.lastError.at) > new Date(lastSignupAt))) {
105
110
  return { id, status: 'fail', message: `${label} refused its last call (${c.lastError.at}): ${c.lastError.code}: ${c.lastError.message}`, fix: `fix the caller's request body, then retry its failed calls (Atlas: POST /v1/instance/referrals/calls/retry_failed)` };
106
111
  }
107
112
  // Protocol connections (Atlas, custom) can't be pinged with an API key: when it last filed a sign-up says it's wired.
108
113
  // undefined: an API from before lastSignupAt, nothing to say.
109
- if (c.lastSignupAt === null) {
114
+ if (lastSignupAt === null) {
110
115
  return { id, status: 'warn', message: `${label} is ${c.status} but has never filed a sign-up`, fix: `sign up a user in your app (test sign-ups don't count) and check the platform calls connection ${c.id}` };
111
116
  }
112
- if (c.lastSignupAt && now.getTime() - new Date(c.lastSignupAt).getTime() > 30 * DAY) {
113
- return { id, status: 'warn', message: `${label} is ${c.status}; no sign-up since ${c.lastSignupAt}`, fix: `check the platform still calls connection ${c.id}` };
117
+ if (lastSignupAt && now.getTime() - new Date(lastSignupAt).getTime() > 30 * DAY) {
118
+ return { id, status: 'warn', message: `${label} is ${c.status}; no sign-up since ${lastSignupAt}`, fix: `check the platform still calls connection ${c.id}` };
114
119
  }
115
- return { id, status: 'ok', message: `${label} is ${c.status}${c.lastSignupAt ? `; last sign-up ${c.lastSignupAt}` : ''}` };
120
+ return { id, status: 'ok', message: `${label} is ${c.status}${lastSignupAt ? `; last sign-up ${lastSignupAt}` : ''}` };
116
121
  });
122
+ // R-06: the Atlas referral panel mints widget tokens, which needs the program's widget set up.
123
+ for (const c of conns.filter((x) => x.provider === 'atlas' && x.status === 'active')) {
124
+ const p = programs.find((x) => x.id === c.programId);
125
+ const w = p?.settings?.widget;
126
+ if (p && !w?.autoEnroll && !w?.destinationUrl) {
127
+ out.push({
128
+ id: `widget.${p.id}`,
129
+ status: 'warn',
130
+ message: `program "${p.name}" has an Atlas connection but its widget isn't configured: the referral panel can't enroll users or build their links`,
131
+ fix: `PATCH /v1/programs/${p.id} {"widget":{"autoEnroll":true,"destinationUrl":"https://your.app/signup"}}`,
132
+ });
133
+ }
134
+ }
117
135
  if (!conns.some((c) => c.provider === 'atlas')) {
118
136
  const other = conns.find((c) => c.status === 'active');
119
137
  out.push(other
@@ -165,7 +183,80 @@ async function trackingCheck(client, env) {
165
183
  });
166
184
  return [...out, ...tokens];
167
185
  }
168
- const MARK = { ok: '✓', warn: '⚠', fail: '✗' };
186
+ /**
187
+ * Every GET /v1/integration-health check, as `health.<id>`. A failed one is ✗ when the API marks it
188
+ * `severity: "error"` (or critical), else ⚠. Scoped, never ✗: it may be about another program.
189
+ */
190
+ async function healthChecks(client, scope) {
191
+ const res = await client.request('GET', '/v1/integration-health');
192
+ return res.checks.map((h) => {
193
+ const id = `health.${h.id}`;
194
+ if (h.ok)
195
+ return { id, status: 'ok', message: h.detail };
196
+ const severe = !scope && (h.severity === 'error' || h.severity === 'critical');
197
+ const fix = [h.fix, h.docs].filter(Boolean).join(' ');
198
+ return { id, status: severe ? 'fail' : 'warn', message: h.detail, ...(fix ? { fix } : {}) };
199
+ });
200
+ }
201
+ /** A program settling by payout with no payout connection: partners can only be paid by hand. Test mode pays through the test rail. */
202
+ async function payoutChecks(client, programs, live) {
203
+ const paying = programs.filter((p) => p.status === 'active' && (p.settings?.settlement ?? 'payout') === 'payout');
204
+ if (paying.length === 0)
205
+ return [];
206
+ if (!live)
207
+ return [{ id: 'payouts.connection', status: 'ok', message: 'test mode pays every method through the test rail' }];
208
+ const active = rows(await client.request('GET', '/v1/payout-connections')).filter((c) => c.status === 'active');
209
+ if (active.length)
210
+ return [{ id: 'payouts.connection', status: 'ok', message: `payout connection: ${active.map((c) => c.provider).join(', ')}` }];
211
+ const names = paying.map((p) => `"${p.name}"`).join(', ');
212
+ return [{ id: 'payouts.connection', status: 'warn', message: `no payout connection while ${names} settle by payout: partners can only be paid by hand`, fix: 'PUT /v1/payout-connections/{provider} (Settings → Payouts), or settlement: merchant_credit' }];
213
+ }
214
+ /** Partners wait for approval (so they must hear back) but no email provider is set: nothing is sent. */
215
+ async function emailChecks(client, programs) {
216
+ const reviewing = programs.filter((p) => p.publicPage?.autoApprove === false);
217
+ if (reviewing.length === 0)
218
+ return [];
219
+ const s = await client.request('GET', '/v1/email/settings');
220
+ if (s.provider && s.hasApiKey !== false)
221
+ return [{ id: 'email.provider', status: 'ok', message: `email provider: ${s.provider}` }];
222
+ const names = reviewing.map((p) => `"${p.name}"`).join(', ');
223
+ return [{ id: 'email.provider', status: 'warn', message: `no email provider while ${names} approve partners by hand: partners get no emails`, fix: 'PUT /v1/email/settings {"provider":"…","apiKey":"…","fromAddress":"…"} (bring your own key)' }];
224
+ }
225
+ /** Approved commissions still unpaid after 30 days: a payout run is overdue (or partners have no payout method). */
226
+ async function unpaidChecks(client, programs, now) {
227
+ const headers = { 'referalli-version': '2026-11-01' }; // the paged list, not a pinned version's capped array
228
+ return Promise.all(programs.map(async (p) => {
229
+ const q = (type) => listAll(client, `/v1/commissions?programId=${encodeURIComponent(p.id)}&type=${type}`, headers);
230
+ const [approved, paid, reversed] = await Promise.all([q('approved'), q('paid'), q('reversed')]);
231
+ const settled = new Set([...paid, ...reversed].map((e) => e.relatedCommissionId));
232
+ const old = approved.filter((e) => !settled.has(e.relatedCommissionId) && now.getTime() - new Date(e.ts).getTime() > 30 * DAY);
233
+ const id = `commissions.${p.id}.unpaid`;
234
+ return old.length
235
+ ? { id, status: 'warn', message: `program "${p.name}": ${old.length} commission(s) approved over 30 days ago are still unpaid`, fix: 'run payouts (Payouts → Run), and check those partners have a payout method' }
236
+ : { id, status: 'ok', message: `program "${p.name}": no approved commission has waited over 30 days` };
237
+ }));
238
+ }
239
+ /** A program with a publicHandle: the public program and its join page answer. */
240
+ async function joinChecks(client, programs, fetchFn) {
241
+ return Promise.all(programs
242
+ .filter((p) => p.publicHandle)
243
+ .map(async (p) => {
244
+ const id = `join.${p.id}`;
245
+ const handle = encodeURIComponent(p.publicHandle);
246
+ const fix = `GET /v1/public/programs/${handle}; the program must be active`;
247
+ try {
248
+ await client.request('GET', `/v1/public/programs/${handle}`);
249
+ const res = await fetchFn(`${client.baseUrl}/join/${handle}`, { method: 'GET', signal: AbortSignal.timeout(10_000) });
250
+ return res.ok
251
+ ? { id, status: 'ok', message: `join page /join/${p.publicHandle} answers ${res.status}` }
252
+ : { id, status: 'fail', message: `join page /join/${p.publicHandle} answers ${res.status}`, fix };
253
+ }
254
+ catch (err) {
255
+ return { id, status: 'fail', message: `program "${p.name}" has publicHandle "${p.publicHandle}" but its public page doesn't answer: ${reason(err)}`, fix };
256
+ }
257
+ }));
258
+ }
259
+ const MARK = { ok: '✓', info: 'ℹ', warn: '⚠', fail: '✗' };
169
260
  export function printChecks(out, checks, json) {
170
261
  if (json) {
171
262
  out(JSON.stringify({ checks }, null, 2));
@@ -173,7 +264,7 @@ export function printChecks(out, checks, json) {
173
264
  }
174
265
  for (const c of checks) {
175
266
  out(`${MARK[c.status]} ${c.id}: ${c.message}`);
176
- if (c.fix && c.status !== 'ok')
267
+ if (c.fix && c.status !== 'ok' && c.status !== 'info')
177
268
  out(` fix: ${c.fix}`);
178
269
  }
179
270
  }
@@ -181,6 +272,9 @@ export function printChecks(out, checks, json) {
181
272
  const ORG_WIDE = {
182
273
  auth: { what: 'auth connections, Atlas sign-ups', scope: 'integrations:read or connections:read' },
183
274
  tracking: { what: 'tracking token, consent mode, configured token', scope: 'org:read' },
275
+ health: { what: 'GET /v1/integration-health', scope: 'integrations:read' },
276
+ payouts: { what: 'payout connections', scope: 'payouts:read' },
277
+ email: { what: 'email settings', scope: 'org:read' },
184
278
  };
185
279
  const OUTSIDE = { method: 'GET', headers: { 'user-agent': 'referalli-doctor-bot' } };
186
280
  /** One program from outside, as a visitor would meet it. Runs here, not on the API, so it can't be aimed at our own network. */
@@ -257,11 +351,16 @@ async function e2eChecks(client, programId, fetchFn, env) {
257
351
  }
258
352
  return out;
259
353
  }
260
- /** `referalli doctor [--program <id>] [--json]`: read-only health checks, plus `--e2e`. Exit 1 when any check fails. */
354
+ /**
355
+ * `referalli doctor [--program <id>] [--json]`: read-only health checks, plus `--e2e`. Exit 1 when any check fails.
356
+ * Scope (R-08): --program (REFERALLI_PROGRAM_ID fills it in), else the key's programs, else every active program.
357
+ */
261
358
  export async function runDoctor(io, client, flags, now = new Date()) {
262
359
  const program = typeof flags.program === 'string' ? flags.program : undefined;
263
- const key = await guard('key', 'referalli login', () => keyCheck(client, now));
264
- const scoped = key.some((c) => c.id === 'key.programs');
360
+ const { checks: key, key: apiKey } = await keyCheck(client, now);
361
+ const scoped = Boolean(apiKey?.programIds);
362
+ const scope = program ? [program] : (apiKey?.programIds ?? null);
363
+ const fetchFn = io.fetchFn ?? fetch;
265
364
  // Asks the API rather than copying its allowlist: if it opens one of these to scoped keys, the check just runs.
266
365
  const orgWide = (id, fn) => guard(id, undefined, async () => {
267
366
  try {
@@ -274,15 +373,25 @@ export async function runDoctor(io, client, flags, now = new Date()) {
274
373
  return [{ id, status: 'warn', message: `skipped, this program-scoped key can't read it (${what})`, fix: `run doctor with an org-wide key (no programs) with ${scope}; read or full also work` }];
275
374
  }
276
375
  });
376
+ let programs = [];
377
+ const programChecks = await guard('programs', undefined, async () => {
378
+ programs = await loadPrograms(client, scope);
379
+ return termsChecks(client, programs);
380
+ });
277
381
  const checks = [
278
382
  ...key,
383
+ ...programChecks,
279
384
  ...(await Promise.all([
280
- guard('programs', undefined, () => termsChecks(client, program)),
281
- guard('webhooks', undefined, () => webhookChecks(client)),
282
- guard('billing', undefined, () => billingChecks(client)),
283
- orgWide('auth', () => authChecks(client, now)),
385
+ guard('webhooks', undefined, () => webhookChecks(client, scope)),
386
+ guard('billing', undefined, () => billingChecks(client, scope)),
387
+ orgWide('auth', () => authChecks(client, now, programs, scope)),
284
388
  orgWide('tracking', () => trackingCheck(client, io.env)),
285
- ...(flags.e2e && program ? [guard('e2e', undefined, () => e2eChecks(client, program, io.fetchFn ?? fetch, io.env))] : []),
389
+ orgWide('health', () => healthChecks(client, scope)),
390
+ orgWide('payouts', () => payoutChecks(client, programs, apiKey?.livemode !== false)),
391
+ orgWide('email', () => emailChecks(client, programs)),
392
+ guard('commissions', undefined, () => unpaidChecks(client, programs, now)),
393
+ guard('join', undefined, () => joinChecks(client, programs, fetchFn)),
394
+ ...(flags.e2e && program ? [guard('e2e', undefined, () => e2eChecks(client, program, fetchFn, io.env))] : []),
286
395
  ])).flat(),
287
396
  ];
288
397
  printChecks((l) => io.out(l), checks, flags.json);
@@ -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 trigger --billing <event> --connection <id> [--data JSON] (test mode; e.g. payment.paid)\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] [--programs ID,\u2026] [--expires-days N | --expires-at ISO]\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 referalli doctor [--program <id>] [--json]\n referalli doctor --program <id> --e2e [--json] (also tests the program from outside; see the docs)\n referalli doctor --scan <dir> [--strict] [--json] (old Referally names in a source tree; no key needed)\n referalli partners list --program <id> [--since 7d|ISO] [--json]\n referalli env pull [--mode live|test] (.env lines on stdout; default: the key's mode)\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)\n REFERALLI_TRACKING_TOKEN doctor checks it is this mode's token (or NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN)\n REFERALLY_* spellings of these still work, with a notice";
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 --billing <event> --connection <id> [--data JSON] (test mode; e.g. payment.paid)\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] [--programs ID,\u2026] [--expires-days N | --expires-at ISO]\n referalli keys list [--owner WHO] [--mode live|test]\n referalli keys revoke <key id> [--pair] [--cascade]\n referalli plan <referalli.yaml> [--check] [--prune]\n referalli apply <referalli.yaml> [--plan] [--check] [--prune] [--secret-file PATH]\n referalli doctor [--program <id>] [--json]\n referalli doctor --program <id> --e2e [--json] (also tests the program from outside; see the docs)\n referalli doctor --scan <dir> [--strict] [--json] (old Referally names in a source tree; no key needed)\n referalli partners list --program <id> [--since 7d|ISO] [--json]\n referalli billing owner set <accountRef> <customerRef> (the user an organization's payments earn for)\n referalli env pull [--mode live|test] (.env lines on stdout; default: the key's mode)\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)\n REFERALLI_TRACKING_TOKEN doctor checks it is this mode's token (or NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN)\n REFERALLI_PROGRAM_ID the default for --program (doctor, partners list)\n REFERALLY_* spellings of these still work, with a notice";
7
7
  /** Run one command; returns the process exit code. */
8
8
  export declare function runCli(argv: string[], baseIo: 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, apply, CliError, doctor, env, eventsTail, keys, login, listen, logout, logsTail, open, partners, trigger, whoami } from './commands.js';
3
+ import { api, apply, billing, CliError, doctor, env, eventsTail, keys, login, listen, logout, logsTail, open, partners, trigger, whoami } from './commands.js';
4
4
  import { withLegacyEnv } from './config.js';
5
5
  import { VERSION } from './version.js';
6
6
  export { readConfig, writeConfig, configPath } from './config.js';
@@ -23,12 +23,13 @@ Usage:
23
23
  referalli keys create --name NAME [--owner WHO] [--mode both|live|test] [--scopes full,…] [--programs ID,…] [--expires-days N | --expires-at ISO]
24
24
  referalli keys list [--owner WHO] [--mode live|test]
25
25
  referalli keys revoke <key id> [--pair] [--cascade]
26
- referalli plan <referalli.yaml> [--check]
27
- referalli apply <referalli.yaml> [--plan] [--check] [--secret-file PATH]
26
+ referalli plan <referalli.yaml> [--check] [--prune]
27
+ referalli apply <referalli.yaml> [--plan] [--check] [--prune] [--secret-file PATH]
28
28
  referalli doctor [--program <id>] [--json]
29
29
  referalli doctor --program <id> --e2e [--json] (also tests the program from outside; see the docs)
30
30
  referalli doctor --scan <dir> [--strict] [--json] (old Referally names in a source tree; no key needed)
31
31
  referalli partners list --program <id> [--since 7d|ISO] [--json]
32
+ referalli billing owner set <accountRef> <customerRef> (the user an organization's payments earn for)
32
33
  referalli env pull [--mode live|test] (.env lines on stdout; default: the key's mode)
33
34
 
34
35
  Environment:
@@ -36,6 +37,7 @@ Environment:
36
37
  REFERALLI_API_URL API base URL (default: the hosted API)
37
38
  REFERALLI_CONFIG_DIR where the login is saved (default ~/.config/referalli)
38
39
  REFERALLI_TRACKING_TOKEN doctor checks it is this mode's token (or NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN)
40
+ REFERALLI_PROGRAM_ID the default for --program (doctor, partners list)
39
41
  REFERALLY_* spellings of these still work, with a notice`;
40
42
  /** Run one command; returns the process exit code. */
41
43
  export async function runCli(argv, baseIo) {
@@ -74,6 +76,7 @@ export async function runCli(argv, baseIo) {
74
76
  cascade: { type: 'boolean' },
75
77
  plan: { type: 'boolean' },
76
78
  check: { type: 'boolean' },
79
+ prune: { type: 'boolean' },
77
80
  json: { type: 'boolean' },
78
81
  scan: { type: 'string' },
79
82
  strict: { type: 'boolean' },
@@ -89,6 +92,9 @@ export async function runCli(argv, baseIo) {
89
92
  return 2;
90
93
  }
91
94
  const flags = parsed.values;
95
+ // R-08: the app's own env names its program (doctor, partners list).
96
+ if (flags.program === undefined && io.env.REFERALLI_PROGRAM_ID?.trim())
97
+ flags.program = io.env.REFERALLI_PROGRAM_ID.trim();
92
98
  const [command, ...rest] = parsed.positionals;
93
99
  if (flags.version) {
94
100
  io.out(VERSION);
@@ -138,6 +144,8 @@ export async function runCli(argv, baseIo) {
138
144
  return await env(io, rest[0], flags);
139
145
  case 'partners':
140
146
  return await partners(io, rest[0], flags);
147
+ case 'billing':
148
+ return await billing(io, rest);
141
149
  default:
142
150
  io.err(`Unknown command "${command}".`);
143
151
  io.err(HELP);
package/dist/src/scan.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
+ import { LEGACY_ENV, LEGACY_ENV_REMOVAL } from './config.js';
3
4
  import { printChecks } from './doctor.js';
4
5
  const MAX_BYTES = 1024 * 1024;
5
6
  const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', '.next']);
6
7
  const LOCKFILE = /\.(lock|lockb)$|^(pnpm-lock\.yaml|package-lock\.json|npm-shrinkwrap\.json|go\.sum)$/;
7
- const NO_DATE = 'no removal date set';
8
+ const REMOVAL = `removal ${LEGACY_ENV_REMOVAL}`;
8
9
  const PUBLISHED = new Set(['cli', 'express', 'mcp', 'next', 'react', 'react-native']);
9
10
  const packageName = (old) => {
10
11
  const name = old.slice('@referally/'.length);
@@ -12,23 +13,27 @@ const packageName = (old) => {
12
13
  return 'referalli';
13
14
  return PUBLISHED.has(name) ? `@referalli/${name}` : 'no published replacement';
14
15
  };
15
- // Dates come from docs: Renamed from Referally. Only the cookie twin has one; the rest are "until further notice".
16
+ // Dates come from docs: Renamed from Referally (the cookie twin goes first, the rest on one later date).
16
17
  const RULES = [
17
- { re: /\w*REFERALLY_\w*/g, to: (o) => o.replace('REFERALLY_', 'REFERALLI_'), removal: NO_DATE },
18
- { re: /referally-version/gi, to: () => 'referalli-version', removal: NO_DATE },
18
+ { re: /\w*REFERALLY_\w*/g, to: (o) => o.replace('REFERALLY_', 'REFERALLI_'), removal: REMOVAL },
19
+ { re: /referally-version/gi, to: () => 'referalli-version', removal: REMOVAL },
19
20
  { re: /referally_ctx/g, to: () => 'referalli_ctx', removal: 'removal 2027-01-31' },
20
- { re: /x-referally-[\w-]*/gi, to: (o) => o.toLowerCase().replace('referally', 'referalli'), removal: NO_DATE },
21
- { re: /@referally\/[\w.-]*/g, to: packageName, removal: NO_DATE },
21
+ { re: /x-referally-[\w-]*/gi, to: (o) => o.toLowerCase().replace('referally', 'referalli'), removal: REMOVAL },
22
+ { re: /@referally\/[\w.-]*/g, to: packageName, removal: REMOVAL },
22
23
  ];
23
- /** One warning per old name per line. Only the name is reported, never the line: it may be a .env value. */
24
+ /**
25
+ * One line per old name per line. An env name is a warning only when Referalli itself read it;
26
+ * any other REFERALLY_* is the app's own name (info): nothing of ours stops reading it.
27
+ */
24
28
  function scanFile(path, text) {
25
29
  if (!/referally/i.test(text))
26
30
  return [];
27
- return text.split('\n').flatMap((line, i) => RULES.flatMap(({ re, to, removal }) => [...new Set(line.match(re) ?? [])].map((old) => ({
28
- id: `${path}:${i + 1}`,
29
- status: 'warn',
30
- message: `${old} → ${to(old)} (${removal})`,
31
- }))));
31
+ return text.split('\n').flatMap((line, i) => RULES.flatMap(({ re, to, removal }) => [...new Set(line.match(re) ?? [])].map((old) => {
32
+ const own = /REFERALLY_/.test(old) && !LEGACY_ENV.includes(old);
33
+ return own
34
+ ? { id: `${path}:${i + 1}`, status: 'info', message: `${old}: your own name (Referalli never read it); rename it to ${to(old)} if you like` }
35
+ : { id: `${path}:${i + 1}`, status: 'warn', message: `${old} → ${to(old)} (${removal})` };
36
+ })));
32
37
  }
33
38
  /** `referalli doctor --scan <dir> [--strict]`: old names in a source tree. Needs no key and calls no API. */
34
39
  export function runScan(out, err, dir, opts) {
@@ -65,7 +70,8 @@ export function runScan(out, err, dir, opts) {
65
70
  if (!existsSync(dir) || !statSync(dir).isDirectory())
66
71
  throw new Error(`${dir}: not a directory`);
67
72
  walk(dir);
73
+ const warnings = hits.filter((h) => h.status === 'warn').length;
68
74
  printChecks(out, hits.length ? hits : [{ id: 'names', status: 'ok', message: 'no old Referally names found' }], opts.json);
69
- err(`Scanned ${files} file(s), ${hits.length} old name(s); skipped ${skipped} (over 1 MB, binary or unreadable).`);
70
- return opts.strict && hits.length ? 1 : 0;
75
+ err(`Scanned ${files} file(s), ${warnings} old name(s) Referalli reads, ${hits.length - warnings} of your own; skipped ${skipped} (over 1 MB, binary or unreadable).`);
76
+ return opts.strict && warnings ? 1 : 0;
71
77
  }
@@ -1,2 +1,2 @@
1
1
  /** Kept in step with package.json by test/version.test.ts. */
2
- export declare const VERSION = "0.4.7";
2
+ export declare const VERSION = "0.4.8";
@@ -1,2 +1,2 @@
1
1
  /** Kept in step with package.json by test/version.test.ts. */
2
- export const VERSION = '0.4.7';
2
+ export const VERSION = '0.4.8';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@referalli/cli",
3
- "version": "0.4.7",
3
+ "version": "0.4.8",
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",