@referalli/cli 0.4.7 → 0.4.9

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.
@@ -375,7 +375,7 @@ export async function keys(io, sub, arg, flags) {
375
375
  const rows = Array.isArray(res) ? res : res.data;
376
376
  for (const k of rows) {
377
377
  const state = k.revokedAt ? 'revoked' : k.expired ? 'expired' : 'active';
378
- io.out([k.id, k.livemode ? 'live' : 'test', state, `${k.prefix}…`, k.name, k.owner ?? '-', k.scopes.join(','), k.lastUsedAt ? `used ${k.lastUsedAt}` : 'never used']
378
+ io.out([k.id, k.livemode ? 'live' : 'test', state, `${k.prefix}…`, k.name, k.owner ?? '-', k.scopes.join(','), k.programIds?.length ? `programs ${k.programIds.join(',')}` : 'all programs', k.lastUsedAt ? `used ${k.lastUsedAt}` : 'never used']
379
379
  .join(' '));
380
380
  }
381
381
  return 0;
@@ -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,25 @@ 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
+ /**
52
+ * RF-1: a scoped run meets an org-wide resource the scoped programs don't use (each has one of its own):
53
+ * its failure is ⚠ with a note, never ✗.
54
+ */
55
+ const unusedOrgWide = (c, note) => c.status === 'fail' ? { ...c, status: 'warn', message: `${c.message} (org-wide, ${note})` } : c;
56
+ async function termsChecks(client, programs) {
49
57
  if (programs.length === 0)
50
58
  return [{ id: 'programs', status: 'warn', message: 'no active programs', fix: '/programs' }];
51
59
  return Promise.all(programs.map((p) => guard(`program.${p.id}.terms`, undefined, async () => {
@@ -60,8 +68,10 @@ async function termsChecks(client, programId) {
60
68
  }
61
69
  }))).then((all) => all.flat());
62
70
  }
63
- async function webhookChecks(client) {
64
- const endpoints = rows(await client.request('GET', '/v1/webhook-endpoints'));
71
+ async function webhookChecks(client, scope, tally) {
72
+ const all = rows(await client.request('GET', '/v1/webhook-endpoints'));
73
+ tally.other += all.filter((e) => outside(scope, e.programIds) && e.health !== 'healthy').length;
74
+ const endpoints = all.filter((e) => !outside(scope, e.programIds));
65
75
  if (endpoints.length === 0)
66
76
  return [{ id: 'webhooks', status: 'ok', message: 'no webhook endpoints' }];
67
77
  return endpoints.map((e) => {
@@ -74,25 +84,36 @@ async function webhookChecks(client) {
74
84
  return { id, status: 'warn', message: `${e.url} is ${why}`, fix };
75
85
  });
76
86
  }
77
- async function billingChecks(client) {
78
- const conns = rows(await client.request('GET', '/v1/billing/connections'));
87
+ function billingChecks(scope, all, tally) {
88
+ const conns = all.filter((c) => !outside(scope, c.programIds));
89
+ tally.other += all.filter((c) => outside(scope, c.programIds) && billingCheck(c).status !== 'ok').length;
79
90
  if (conns.length === 0) {
80
91
  return [{ id: 'billing', status: 'warn', message: "no billing connection: payments won't earn commission", fix: 'POST /v1/billing/connections' }];
81
92
  }
93
+ // An org-wide connection matters to the scope only when one of its programs has no connection of its own.
94
+ const usesOrgWide = !scope || scope.some((p) => !all.some((c) => c.programIds?.includes(p)));
82
95
  return conns.map((c) => {
83
- const id = `billing.${c.id}`;
84
- const label = `${c.provider} connection "${c.name}"`;
85
- if (c.status === 'awaiting_secret') {
86
- return { id, status: 'fail', message: `${label}: provider secret not set, every event is refused`, fix: `PUT /v1/billing/connections/${c.id}/secret {"webhookSecret":"…"}` };
87
- }
88
- if (c.status === 'paused')
89
- return { id, status: 'warn', message: `${label} is paused`, fix: `PATCH /v1/billing/connections/${c.id} {"status":"active"}` };
90
- return { id, status: 'ok', message: `${label} is ${c.status}` };
96
+ const check = billingCheck(c);
97
+ return usesOrgWide || c.programIds?.length ? check : unusedOrgWide(check, 'not used by this program: it has its own billing connection');
91
98
  });
92
99
  }
93
- async function authChecks(client, now) {
94
- const conns = rows(await client.request('GET', '/v1/auth/connections'));
95
- const out = conns.map((c) => {
100
+ function billingCheck(c) {
101
+ const id = `billing.${c.id}`;
102
+ const label = `${c.provider} connection "${c.name}"`;
103
+ if (c.status === 'awaiting_secret') {
104
+ return { id, status: 'fail', message: `${label}: provider secret not set, every event is refused`, fix: `PUT /v1/billing/connections/${c.id}/secret {"webhookSecret":"…"}` };
105
+ }
106
+ if (c.status === 'paused')
107
+ return { id, status: 'warn', message: `${label} is paused`, fix: `PATCH /v1/billing/connections/${c.id} {"status":"active"}` };
108
+ return { id, status: 'ok', message: `${label} is ${c.status}` };
109
+ }
110
+ async function authChecks(client, now, programs, scope, tally) {
111
+ const all = rows(await client.request('GET', '/v1/auth/connections'));
112
+ const isOutside = (c) => outside(scope, c.programId ? [c.programId] : null);
113
+ const conns = all.filter((c) => !isOutside(c));
114
+ const check = (c) => {
115
+ // Receipt time when the API has it: a late-filed sign-up must not look like a fresh one (R-30).
116
+ const lastSignupAt = c.lastSignupReceivedAt ?? c.lastSignupAt;
96
117
  const id = `auth.${c.id}`;
97
118
  const label = `${c.provider} auth connection${c.name ? ` "${c.name}"` : ''}`;
98
119
  if (c.status === 'paused')
@@ -101,19 +122,36 @@ async function authChecks(client, now) {
101
122
  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
123
  }
103
124
  // 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))) {
125
+ if (c.lastError && (!lastSignupAt || new Date(c.lastError.at) > new Date(lastSignupAt))) {
105
126
  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
127
  }
107
128
  // Protocol connections (Atlas, custom) can't be pinged with an API key: when it last filed a sign-up says it's wired.
108
129
  // undefined: an API from before lastSignupAt, nothing to say.
109
- if (c.lastSignupAt === null) {
110
- 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}` };
130
+ const rejected = c.lastRejectedAt ? `; last refused call ${c.lastRejectedAt}${c.lastRejectedReason ? ` (${c.lastRejectedReason})` : ''}` : '';
131
+ if (lastSignupAt === null) {
132
+ return { id, status: 'warn', message: `${label} is ${c.status} but has never filed a sign-up${rejected}`, fix: `sign up a user in your app (test sign-ups don't count) and check the platform calls connection ${c.id}` };
111
133
  }
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}` };
134
+ if (lastSignupAt && now.getTime() - new Date(lastSignupAt).getTime() > 30 * DAY) {
135
+ return { id, status: 'warn', message: `${label} is ${c.status}; no sign-up since ${lastSignupAt}`, fix: `check the platform still calls connection ${c.id}` };
114
136
  }
115
- return { id, status: 'ok', message: `${label} is ${c.status}${c.lastSignupAt ? `; last sign-up ${c.lastSignupAt}` : ''}` };
116
- });
137
+ return { id, status: 'ok', message: `${label} is ${c.status}${lastSignupAt ? `; last sign-up ${lastSignupAt}` : ''}${rejected}` };
138
+ };
139
+ tally.other += all.filter((c) => isOutside(c) && check(c).status !== 'ok').length;
140
+ const usesOrgWide = !scope || scope.some((p) => !all.some((c) => c.programId === p));
141
+ const out = conns.map((c) => (usesOrgWide || c.programId ? check(c) : unusedOrgWide(check(c), 'not used by this program: it has its own auth connection')));
142
+ // R-06: the Atlas referral panel mints widget tokens, which needs the program's widget set up.
143
+ for (const c of conns.filter((x) => x.provider === 'atlas' && x.status === 'active')) {
144
+ const p = programs.find((x) => x.id === c.programId);
145
+ const w = p?.settings?.widget;
146
+ if (p && !w?.autoEnroll && !w?.destinationUrl) {
147
+ out.push({
148
+ id: `widget.${p.id}`,
149
+ status: 'warn',
150
+ 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`,
151
+ fix: `PATCH /v1/programs/${p.id} {"widget":{"autoEnroll":true,"destinationUrl":"https://your.app/signup"}}`,
152
+ });
153
+ }
154
+ }
117
155
  if (!conns.some((c) => c.provider === 'atlas')) {
118
156
  const other = conns.find((c) => c.status === 'active');
119
157
  out.push(other
@@ -122,7 +160,33 @@ async function authChecks(client, now) {
122
160
  }
123
161
  return out;
124
162
  }
125
- async function trackingCheck(client, env) {
163
+ /**
164
+ * RF-2: the consent mode aff.js serves each program: its own trackingConsent, else the org's.
165
+ * Scoped: the scope's programs. Unscoped: the org's mode, naming the programs that override it.
166
+ */
167
+ function consentCheck(c, programs, scope) {
168
+ const id = 'tracking.consent';
169
+ const overrides = c.programOverrides ?? [];
170
+ const own = (p) => p.trackingConsent ?? overrides.find((o) => o.programId === p.id)?.mode ?? null;
171
+ const why = 'aff.js stores the referral before the visitor chooses';
172
+ if (scope && programs.length > 0) {
173
+ const none = programs.filter((p) => (own(p) ?? c.mode) === 'none');
174
+ if (none.length > 0) {
175
+ const fixes = none.map((p) => (own(p) ? `PATCH /v1/programs/${p.id} {"trackingConsent":"auto"}` : null));
176
+ const fix = [...new Set(fixes.map((f) => f ?? `PUT /v1/org/tracking-consent {"mode":"auto"} (or /settings → Install)`))].join('; ');
177
+ return [{ id, status: 'warn', message: `tracking consent is 'none' for ${none.map((p) => `"${p.name}"`).join(', ')}: ${why}`, fix }];
178
+ }
179
+ const modes = programs.map((p) => (own(p) ? `uses ${own(p)}` : `uses the org's mode, ${c.mode}`));
180
+ return [{ id, status: 'ok', message: programs.length === 1 ? `program ${modes[0]}` : programs.map((p, i) => `"${p.name}" ${modes[i]}`).join('; ') }];
181
+ }
182
+ const listed = overrides.length ? `; programs with their own mode: ${overrides.map((o) => `"${o.programName}" ${o.mode}`).join(', ')}` : '';
183
+ // Every active program overrides 'none': the org's mode reaches nobody, so nothing to change org-wide.
184
+ const covered = programs.length > 0 && programs.every((p) => own(p));
185
+ return c.mode === 'none' && !covered
186
+ ? [{ id, status: 'warn', message: `tracking consent is 'none': ${why}${listed}`, fix: `PUT /v1/org/tracking-consent {"mode":"auto"} (or /settings → Install)` }]
187
+ : [{ id, status: 'ok', message: `tracking consent: ${c.mode}${listed}` }];
188
+ }
189
+ async function trackingCheck(client, env, programs, scope) {
126
190
  const org = await client.request('GET', '/v1/org');
127
191
  const out = [];
128
192
  try {
@@ -136,12 +200,7 @@ async function trackingCheck(client, env) {
136
200
  }
137
201
  // Consent mode `none` (orgs from before consent support start there): aff.js stores the referral before the visitor chooses.
138
202
  if (org.livemode !== false) {
139
- out.push(...(await guard('tracking.consent', '/settings → Install', async () => {
140
- const c = await client.request('GET', '/v1/org/tracking-consent');
141
- return c.mode === 'none'
142
- ? [{ id: 'tracking.consent', status: 'warn', message: "tracking consent is 'none': aff.js stores the referral before the visitor chooses", fix: `PUT /v1/org/tracking-consent {"mode":"auto"} (or /settings → Install)` }]
143
- : [{ id: 'tracking.consent', status: 'ok', message: `tracking consent: ${c.mode}` }];
144
- })));
203
+ out.push(...(await guard('tracking.consent', '/settings → Install', async () => consentCheck(await client.request('GET', '/v1/org/tracking-consent'), programs, scope))));
145
204
  }
146
205
  // The token the product is configured with (run doctor with the app's env) must be this mode's.
147
206
  const name = env.REFERALLI_TRACKING_TOKEN ? 'REFERALLI_TRACKING_TOKEN' : env.NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN ? 'NEXT_PUBLIC_REFERALLI_TRACKING_TOKEN' : null;
@@ -165,7 +224,84 @@ async function trackingCheck(client, env) {
165
224
  });
166
225
  return [...out, ...tokens];
167
226
  }
168
- const MARK = { ok: '✓', warn: '⚠', fail: '✗' };
227
+ /**
228
+ * Every GET /v1/integration-health check, as `health.<id>`. A failed one is ✗ when the API marks it
229
+ * `severity: "error"` (or critical), else ⚠. Scoped, never ✗: it may be about another program.
230
+ */
231
+ async function healthChecks(client, scope, billing, tally) {
232
+ const res = await client.request('GET', '/v1/integration-health');
233
+ // RF-1: a check about another program's billing connection (billing.<provider>.<id>) goes into the tally.
234
+ const others = new Set(billing.filter((c) => outside(scope, c.programIds)).map((c) => c.id));
235
+ const theirs = (h) => h.id.split('.').some((part) => others.has(part));
236
+ tally.other += res.checks.filter((h) => !h.ok && theirs(h)).length;
237
+ return res.checks.filter((h) => !theirs(h)).map((h) => {
238
+ const id = `health.${h.id}`;
239
+ if (h.ok)
240
+ return { id, status: 'ok', message: h.detail };
241
+ const severe = !scope && (h.severity === 'error' || h.severity === 'critical');
242
+ const fix = [h.fix, h.docs].filter(Boolean).join(' ');
243
+ return { id, status: severe ? 'fail' : 'warn', message: h.detail, ...(fix ? { fix } : {}) };
244
+ });
245
+ }
246
+ /** A program settling by payout with no payout connection: partners can only be paid by hand. Test mode pays through the test rail. */
247
+ async function payoutChecks(client, programs, live) {
248
+ const paying = programs.filter((p) => p.status === 'active' && (p.settings?.settlement ?? 'payout') === 'payout');
249
+ if (paying.length === 0)
250
+ return [];
251
+ if (!live)
252
+ return [{ id: 'payouts.connection', status: 'ok', message: 'test mode pays every method through the test rail' }];
253
+ const active = rows(await client.request('GET', '/v1/payout-connections')).filter((c) => c.status === 'active');
254
+ if (active.length)
255
+ return [{ id: 'payouts.connection', status: 'ok', message: `payout connection: ${active.map((c) => c.provider).join(', ')}` }];
256
+ const names = paying.map((p) => `"${p.name}"`).join(', ');
257
+ 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' }];
258
+ }
259
+ /** Partners wait for approval (so they must hear back) but no email provider is set: nothing is sent. */
260
+ async function emailChecks(client, programs) {
261
+ const reviewing = programs.filter((p) => p.publicPage?.autoApprove === false);
262
+ if (reviewing.length === 0)
263
+ return [];
264
+ const s = await client.request('GET', '/v1/email/settings');
265
+ if (s.provider && s.hasApiKey !== false)
266
+ return [{ id: 'email.provider', status: 'ok', message: `email provider: ${s.provider}` }];
267
+ const names = reviewing.map((p) => `"${p.name}"`).join(', ');
268
+ 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)' }];
269
+ }
270
+ /** Approved commissions still unpaid after 30 days: a payout run is overdue (or partners have no payout method). */
271
+ async function unpaidChecks(client, programs, now) {
272
+ const headers = { 'referalli-version': '2026-11-01' }; // the paged list, not a pinned version's capped array
273
+ return Promise.all(programs.map(async (p) => {
274
+ const q = (type) => listAll(client, `/v1/commissions?programId=${encodeURIComponent(p.id)}&type=${type}`, headers);
275
+ const [approved, paid, reversed] = await Promise.all([q('approved'), q('paid'), q('reversed')]);
276
+ const settled = new Set([...paid, ...reversed].map((e) => e.relatedCommissionId));
277
+ const old = approved.filter((e) => !settled.has(e.relatedCommissionId) && now.getTime() - new Date(e.ts).getTime() > 30 * DAY);
278
+ const id = `commissions.${p.id}.unpaid`;
279
+ return old.length
280
+ ? { 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' }
281
+ : { id, status: 'ok', message: `program "${p.name}": no approved commission has waited over 30 days` };
282
+ }));
283
+ }
284
+ /** A program with a publicHandle: the public program and its join page answer. */
285
+ async function joinChecks(client, programs, fetchFn) {
286
+ return Promise.all(programs
287
+ .filter((p) => p.publicHandle)
288
+ .map(async (p) => {
289
+ const id = `join.${p.id}`;
290
+ const handle = encodeURIComponent(p.publicHandle);
291
+ const fix = `GET /v1/public/programs/${handle}; the program must be active`;
292
+ try {
293
+ await client.request('GET', `/v1/public/programs/${handle}`);
294
+ const res = await fetchFn(`${client.baseUrl}/join/${handle}`, { method: 'GET', signal: AbortSignal.timeout(10_000) });
295
+ return res.ok
296
+ ? { id, status: 'ok', message: `join page /join/${p.publicHandle} answers ${res.status}` }
297
+ : { id, status: 'fail', message: `join page /join/${p.publicHandle} answers ${res.status}`, fix };
298
+ }
299
+ catch (err) {
300
+ return { id, status: 'fail', message: `program "${p.name}" has publicHandle "${p.publicHandle}" but its public page doesn't answer: ${reason(err)}`, fix };
301
+ }
302
+ }));
303
+ }
304
+ const MARK = { ok: '✓', info: 'ℹ', warn: '⚠', fail: '✗' };
169
305
  export function printChecks(out, checks, json) {
170
306
  if (json) {
171
307
  out(JSON.stringify({ checks }, null, 2));
@@ -173,7 +309,7 @@ export function printChecks(out, checks, json) {
173
309
  }
174
310
  for (const c of checks) {
175
311
  out(`${MARK[c.status]} ${c.id}: ${c.message}`);
176
- if (c.fix && c.status !== 'ok')
312
+ if (c.fix && c.status !== 'ok' && c.status !== 'info')
177
313
  out(` fix: ${c.fix}`);
178
314
  }
179
315
  }
@@ -181,6 +317,9 @@ export function printChecks(out, checks, json) {
181
317
  const ORG_WIDE = {
182
318
  auth: { what: 'auth connections, Atlas sign-ups', scope: 'integrations:read or connections:read' },
183
319
  tracking: { what: 'tracking token, consent mode, configured token', scope: 'org:read' },
320
+ health: { what: 'GET /v1/integration-health', scope: 'integrations:read' },
321
+ payouts: { what: 'payout connections', scope: 'payouts:read' },
322
+ email: { what: 'email settings', scope: 'org:read' },
184
323
  };
185
324
  const OUTSIDE = { method: 'GET', headers: { 'user-agent': 'referalli-doctor-bot' } };
186
325
  /** 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 +396,16 @@ async function e2eChecks(client, programId, fetchFn, env) {
257
396
  }
258
397
  return out;
259
398
  }
260
- /** `referalli doctor [--program <id>] [--json]`: read-only health checks, plus `--e2e`. Exit 1 when any check fails. */
399
+ /**
400
+ * `referalli doctor [--program <id>] [--json]`: read-only health checks, plus `--e2e`. Exit 1 when any check fails.
401
+ * Scope (R-08): --program (REFERALLI_PROGRAM_ID fills it in), else the key's programs, else every active program.
402
+ */
261
403
  export async function runDoctor(io, client, flags, now = new Date()) {
262
404
  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');
405
+ const { checks: key, key: apiKey } = await keyCheck(client, now);
406
+ const scoped = Boolean(apiKey?.programIds);
407
+ const scope = program ? [program] : (apiKey?.programIds ?? null);
408
+ const fetchFn = io.fetchFn ?? fetch;
265
409
  // Asks the API rather than copying its allowlist: if it opens one of these to scoped keys, the check just runs.
266
410
  const orgWide = (id, fn) => guard(id, undefined, async () => {
267
411
  try {
@@ -274,17 +418,34 @@ export async function runDoctor(io, client, flags, now = new Date()) {
274
418
  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
419
  }
276
420
  });
421
+ const tally = { other: 0 };
422
+ let programs = [];
423
+ const programChecks = await guard('programs', undefined, async () => {
424
+ programs = await loadPrograms(client, scope);
425
+ return termsChecks(client, programs);
426
+ });
427
+ // Read once: the billing checks and the health checks' tally both need it (health: empty if it can't be read; billing says why).
428
+ const billingList = client.request('GET', '/v1/billing/connections').then(rows);
277
429
  const checks = [
278
430
  ...key,
431
+ ...programChecks,
279
432
  ...(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)),
284
- orgWide('tracking', () => trackingCheck(client, io.env)),
285
- ...(flags.e2e && program ? [guard('e2e', undefined, () => e2eChecks(client, program, io.fetchFn ?? fetch, io.env))] : []),
433
+ guard('webhooks', undefined, () => webhookChecks(client, scope, tally)),
434
+ guard('billing', undefined, async () => billingChecks(scope, await billingList, tally)),
435
+ orgWide('auth', () => authChecks(client, now, programs, scope, tally)),
436
+ orgWide('tracking', () => trackingCheck(client, io.env, programs, scope)),
437
+ orgWide('health', async () => healthChecks(client, scope, await billingList.catch(() => []), tally)),
438
+ orgWide('payouts', () => payoutChecks(client, programs, apiKey?.livemode !== false)),
439
+ orgWide('email', () => emailChecks(client, programs)),
440
+ guard('commissions', undefined, () => unpaidChecks(client, programs, now)),
441
+ guard('join', undefined, () => joinChecks(client, programs, fetchFn)),
442
+ ...(flags.e2e && program ? [guard('e2e', undefined, () => e2eChecks(client, program, fetchFn, io.env))] : []),
286
443
  ])).flat(),
287
444
  ];
445
+ if (tally.other > 0) {
446
+ const how = program ? 'run without --program (and REFERALLI_PROGRAM_ID)' : 'run with an org-wide key';
447
+ checks.push({ id: 'scope.other', status: 'info', message: `${tally.other} issue(s) in other programs; ${how} to see them` });
448
+ }
288
449
  printChecks((l) => io.out(l), checks, flags.json);
289
450
  return checks.some((c) => c.status === 'fail') ? 1 : 0;
290
451
  }
@@ -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);