@cpajs/cpa 0.1.0-rc.2 → 0.1.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +65 -19
  2. package/assets/management.html +169 -0
  3. package/dist/client/index.d.ts +1 -1
  4. package/dist/client/index.d.ts.map +1 -1
  5. package/dist/client/resources/config.d.ts +10 -3
  6. package/dist/client/resources/config.d.ts.map +1 -1
  7. package/dist/client/resources/config.js.map +1 -1
  8. package/dist/client/types/config.d.ts +8 -0
  9. package/dist/client/types/config.d.ts.map +1 -1
  10. package/dist/server/config.d.ts +8 -0
  11. package/dist/server/config.d.ts.map +1 -1
  12. package/dist/server/config.js +11 -1
  13. package/dist/server/config.js.map +1 -1
  14. package/dist/server/cpa-version.d.ts +12 -0
  15. package/dist/server/cpa-version.d.ts.map +1 -1
  16. package/dist/server/cpa-version.js +12 -0
  17. package/dist/server/cpa-version.js.map +1 -1
  18. package/dist/server/index.d.ts +2 -1
  19. package/dist/server/index.d.ts.map +1 -1
  20. package/dist/server/index.js +63 -42
  21. package/dist/server/index.js.map +1 -1
  22. package/dist/server/internal.d.ts +2 -0
  23. package/dist/server/internal.d.ts.map +1 -1
  24. package/dist/server/management.d.ts +10 -2
  25. package/dist/server/management.d.ts.map +1 -1
  26. package/dist/server/management.js +14 -6
  27. package/dist/server/management.js.map +1 -1
  28. package/dist/server/panel.d.ts +5 -0
  29. package/dist/server/panel.d.ts.map +1 -0
  30. package/dist/server/panel.js +9 -0
  31. package/dist/server/panel.js.map +1 -0
  32. package/dist/server/types.d.ts +35 -3
  33. package/dist/server/types.d.ts.map +1 -1
  34. package/dist/server/warnings.d.ts +32 -0
  35. package/dist/server/warnings.d.ts.map +1 -0
  36. package/dist/server/warnings.js +19 -0
  37. package/dist/server/warnings.js.map +1 -0
  38. package/package.json +26 -24
  39. package/src/client/index.ts +1 -1
  40. package/src/client/resources/config.ts +12 -3
  41. package/src/client/types/config.ts +18 -0
  42. package/src/server/config.ts +17 -1
  43. package/src/server/cpa-version.ts +13 -0
  44. package/src/server/index.ts +82 -43
  45. package/src/server/internal.ts +2 -0
  46. package/src/server/management.ts +18 -8
  47. package/src/server/panel.ts +10 -0
  48. package/src/server/types.ts +36 -3
  49. package/src/server/warnings.ts +43 -0
@@ -1,4 +1,4 @@
1
- import { mkdir, mkdtemp, rm } from 'node:fs/promises';
1
+ import { copyFile, mkdir, mkdtemp, rm } from 'node:fs/promises';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
@@ -7,20 +7,24 @@ import { resolveBinary, resolveLauncher } from './binary.ts';
7
7
  import { inspectConfigFile, readManagedConfig, updateManagedSecret, writeManagedConfig, type PreparedConfig } from './config.ts';
8
8
  import { CpaStartError } from './errors.ts';
9
9
  import { keyMatches, resolveManagement, type ResolvedManagement } from './management.ts';
10
+ import { bundledPanel } from './panel.ts';
10
11
  import { ManagedProcess } from './process.ts';
11
12
  import { connectHost, findFreePort, formatOrigin, isLoopbackHost, isPortFree, probeHealth, type PortReservation } from './readiness.ts';
12
13
  import { internalCommand, type InternalCommand } from './internal.ts';
13
14
  import { createRedactor } from './redact.ts';
14
- import type { CpaServer, ExitResult, LogLine, RestartOptions, StartServerOptions, StartWithConfigOptions, StopOptions } from './types.ts';
15
+ import { createWarner } from './warnings.ts';
16
+ import type { CpaServer, ExitResult, LogLine, RestartOptions, ServerClientOptions, StartServerOptions, StartWithConfigOptions, StopOptions } from './types.ts';
17
+ import { createClient } from '../client/index.ts';
15
18
 
16
19
  export { candidateTargets, currentPlatform, detectLibc, resolveBinary } from './binary.ts';
17
20
  export type { HostPlatform, Libc, ResolvedBinary } from './binary.ts';
18
21
  export { CpaBinaryError, CpaStartError } from './errors.ts';
19
22
  export type { CpaBinaryErrorCode, CpaStartErrorCode } from './errors.ts';
20
23
  export { TARGETS, NPM_SCOPE, UNSUPPORTED_PLATFORMS, binaryName, packageName } from './targets.ts';
21
- export { CPA_RELEASE } from './cpa-version.ts';
24
+ export { CPA_PANEL, CPA_RELEASE } from './cpa-version.ts';
22
25
  export type { Target, TargetBuild, TargetVerification } from './targets.ts';
23
26
  export type * from './types.ts';
27
+ export type { CpaWarning, CpaWarningCode, SuppressWarnings } from './warnings.ts';
24
28
  export type { CpaConfig } from '../client/types/config.ts';
25
29
 
26
30
  const DEFAULT_STARTUP_TIMEOUT_MS = 30_000;
@@ -49,8 +53,12 @@ function validate(options: StartServerOptions): void {
49
53
  'management and managementKey are mutually exclusive; managementKey is the deprecated alias for management.key.',
50
54
  );
51
55
  }
56
+ if (options.management === false && options.managementKey !== undefined) {
57
+ throw new CpaStartError('invalid-options', 'management: false disables the management API; do not also pass managementKey.');
58
+ }
52
59
  if (
53
60
  options.management !== undefined &&
61
+ options.management !== false &&
54
62
  (typeof options.management.key !== 'string' || options.management.key.trim() === '')
55
63
  ) {
56
64
  throw new CpaStartError('invalid-options', 'management.key must not be empty.');
@@ -58,16 +66,17 @@ function validate(options: StartServerOptions): void {
58
66
  if (typeof options.managementKey === 'string' && options.managementKey.trim() === '') {
59
67
  throw new CpaStartError('invalid-options', 'managementKey must not be empty.');
60
68
  }
61
- if (options.management?.viaEnvironment !== true && options.env?.MANAGEMENT_PASSWORD !== undefined) {
69
+ const viaEnvironment = options.management !== false && options.management?.viaEnvironment === true;
70
+ if (!viaEnvironment && options.env?.MANAGEMENT_PASSWORD !== undefined) {
62
71
  throw new CpaStartError(
63
72
  'invalid-options',
64
73
  'Do not set MANAGEMENT_PASSWORD in env: cpajs only passes it to CPA for management: { key, viaEnvironment: true }, because upstream treats it as enabling remote management.',
65
74
  );
66
75
  }
67
- const requestedKey = options.management?.key ?? options.managementKey;
76
+ const requestedKey = (options.management === false ? undefined : options.management?.key) ?? options.managementKey;
68
77
  if (requestedKey === undefined) return;
69
78
  if (options.configPath !== undefined) {
70
- if (options.management?.viaEnvironment !== true) {
79
+ if (!viaEnvironment) {
71
80
  throw new CpaStartError(
72
81
  'invalid-options',
73
82
  'management.key cannot be combined with configPath because cpajs must not edit your config file. Put management.secret-key in the file, or use management.viaEnvironment: true to pass the key through MANAGEMENT_PASSWORD (which also enables remote management).',
@@ -231,11 +240,21 @@ export async function startServer(options: StartServerOptions = {}): Promise<Cpa
231
240
  // Exec mode checks this after PR_SET_PDEATHSIG to catch a parent that died first.
232
241
  if (launcher?.mode === 'exec') env.CPAJS_PARENT_PID = String(process.pid);
233
242
  const extraArgs = buildArgs(options);
234
- if (launcher === undefined && options.launcher !== false && command === undefined && process.platform !== 'win32') {
235
- options.onLog?.({
236
- stream: 'stderr',
237
- line: `cpajs: notice: no cpa-launcher found for ${binary.path}; CPA will keep running if this process is killed. Pass launcher: false to silence this.`,
238
- });
243
+ // The pinned control panel (see panel.ts) is used only in a config cpajs manages,
244
+ // when the caller has not chosen another panel source.
245
+ const panelFile = command !== undefined ? command.panel : bundledPanel();
246
+ const pinnedPanel =
247
+ panelFile !== undefined &&
248
+ options.management !== false &&
249
+ options.configPath === undefined &&
250
+ env.MANAGEMENT_STATIC_PATH === undefined &&
251
+ options.config?.management?.['panel-github-repository'] === undefined;
252
+ const warn = createWarner(options);
253
+ if (management.generated) {
254
+ warn(
255
+ 'noManagementKey',
256
+ 'No management key given: generated one for this start (only its bcrypt hash is stored). Use server.client() for the management API, management: { key } to choose the key (which also enables the web control panel), or management: false to disable it.',
257
+ );
239
258
  }
240
259
  const ownsStateDir = options.stateDir === undefined;
241
260
  const stateDir = ownsStateDir ? await mkdtemp(join(tmpdir(), 'cpajs-')) : resolve(options.stateDir!);
@@ -251,12 +270,15 @@ export async function startServer(options: StartServerOptions = {}): Promise<Cpa
251
270
  const managedSecret =
252
271
  management.secretKeyHash === undefined
253
272
  ? undefined
254
- : { secretKeyHash: management.secretKeyHash, allowRemote: management.allowRemote };
255
- let warnedRemote = false;
273
+ : {
274
+ secretKeyHash: management.secretKeyHash,
275
+ allowRemote: management.allowRemote,
276
+ // Nobody knows a generated key, so the web panel could never log in; skip its download.
277
+ ...(management.generated ? { disableControlPanel: true } : {}),
278
+ };
256
279
 
257
280
  let reservation: PortReservation | undefined;
258
281
  let wroteConfig = false;
259
- let announcedReuse = false;
260
282
  try {
261
283
  for (let attempt = 1; ; attempt++) {
262
284
  let prepared: PreparedConfig;
@@ -284,18 +306,15 @@ export async function startServer(options: StartServerOptions = {}): Promise<Cpa
284
306
  ) {
285
307
  await updateManagedSecret(existing.configPath, managedSecret);
286
308
  prepared = (await readManagedConfig(stateDir))!;
287
- options.onLog?.({
288
- stream: 'stdout',
289
- line: `Updated management.secret-key / allow-remote in ${existing.configPath} for the management key of this start.`,
290
- });
291
- }
292
- if (!announcedReuse) {
293
- announcedReuse = true;
294
- options.onLog?.({
295
- stream: 'stdout',
296
- line: `Keeping existing config at ${existing.configPath}; pass overwriteConfig: true to replace it.`,
297
- });
309
+ // A generated key changes on every start; only a caller's key change is news.
310
+ if (!management.generated) {
311
+ warn('managementKeyUpdated', `Replaced management.secret-key / allow-remote in ${existing.configPath} for the management key of this start.`);
312
+ }
298
313
  }
314
+ warn(
315
+ 'configReused',
316
+ `Kept the existing config at ${existing.configPath}; this start's config, host and port were not applied. Pass overwriteConfig: true to replace it.`,
317
+ );
299
318
  } else {
300
319
  const listen = configListen(options);
301
320
  if (listen.port === 0) {
@@ -303,29 +322,34 @@ export async function startServer(options: StartServerOptions = {}): Promise<Cpa
303
322
  listen.port = reservation.port;
304
323
  dynamicPort = true;
305
324
  }
306
- prepared = await writeManagedConfig(options.config ?? {}, stateDir, listen, managedSecret);
325
+ prepared = await writeManagedConfig(options.config ?? {}, stateDir, listen, managedSecret, { pinnedPanel });
307
326
  wroteConfig = true;
308
327
  }
309
328
  }
310
329
 
311
330
  const { host, port, tls } = prepared.listen;
312
- if (!warnedRemote) {
313
- warnedRemote = true;
314
- const target = host === '' ? 'all interfaces' : host;
315
- const exposed = !isLoopbackHost(host);
316
- if (management.viaEnvironment) {
317
- options.onLog?.({
318
- stream: 'stderr',
319
- line:
320
- 'cpajs: warning: management.viaEnvironment passes the key through MANAGEMENT_PASSWORD, which upstream compares in plaintext and which always enables remote management' +
321
- (exposed ? `; the server binds ${target}, so the management API is reachable from non-loopback clients.` : '.'),
322
- });
323
- } else if (prepared.management.allowRemote && exposed) {
324
- options.onLog?.({
325
- stream: 'stderr',
326
- line: `cpajs: warning: management.allow-remote is true and the server binds ${target}, so the management API is reachable from non-loopback clients.`,
327
- });
328
- }
331
+ const target = host === '' ? 'all interfaces' : host;
332
+ const exposed = !isLoopbackHost(host);
333
+ if (management.viaEnvironment) {
334
+ warn(
335
+ 'managementViaEnvironment',
336
+ 'management.viaEnvironment passes the key through MANAGEMENT_PASSWORD, which upstream compares in plaintext and which always enables remote management' +
337
+ (exposed ? `; the server binds ${target}, so the management API is reachable from non-loopback clients.` : '.'),
338
+ );
339
+ } else if (prepared.management.allowRemote && exposed) {
340
+ warn(
341
+ 'remoteManagementExposed',
342
+ `management.allow-remote is true and the server binds ${target}, so the management API is reachable from non-loopback clients.`,
343
+ );
344
+ }
345
+
346
+ if (pinnedPanel && prepared.management.servesPinnedPanel) {
347
+ // A copy in stateDir, so a later opt-in to auto-update (through the management
348
+ // API) makes CPA write there instead of into the installed package.
349
+ const staticDir = join(stateDir, 'static');
350
+ await mkdir(staticDir, { recursive: true });
351
+ await copyFile(panelFile!, join(staticDir, 'management.html'));
352
+ env.MANAGEMENT_STATIC_PATH = join(staticDir, 'management.html');
329
353
  }
330
354
 
331
355
  const redact = createRedactor([management.key, options.home?.jwt, ...prepared.secrets, ...(options.redact ?? [])]);
@@ -361,6 +385,13 @@ export async function startServer(options: StartServerOptions = {}): Promise<Cpa
361
385
  if (result.kind === 'ready') {
362
386
  return createHandle(result.proc, {
363
387
  binaryPath: binary.path,
388
+ managementKey: management.key,
389
+ noClientReason:
390
+ options.management === false
391
+ ? 'the management API is disabled (management: false)'
392
+ : options.configPath !== undefined
393
+ ? 'with configPath, cpajs does not know the key; pass management: { key, viaEnvironment: true } or create a client with your own key'
394
+ : "config.management['secret-key'] is set, so the key is yours; create a client with it",
364
395
  spawnPath,
365
396
  supervised,
366
397
  prefixArgs,
@@ -417,6 +448,10 @@ async function waitUntilReady(
417
448
  interface HandleInfo {
418
449
  /** The CPA binary (exposed on the handle). */
419
450
  binaryPath: string;
451
+ /** Plaintext management key, kept private to back server.client(). */
452
+ managementKey: string | undefined;
453
+ /** Why server.client() is unavailable when there is no key. */
454
+ noClientReason: string;
420
455
  /** What is spawned: cpa-launcher or CPA itself. */
421
456
  spawnPath: string;
422
457
  supervised: boolean;
@@ -578,6 +613,10 @@ function createHandle(initialProc: ManagedProcess, info: HandleInfo): CpaServer
578
613
  exited,
579
614
  stop,
580
615
  restart,
616
+ client(clientOptions: ServerClientOptions = {}) {
617
+ if (info.managementKey === undefined) throw new Error(`server.client() is unavailable: ${info.noClientReason}.`);
618
+ return createClient({ ...clientOptions, baseUrl: info.origin, managementKey: info.managementKey });
619
+ },
581
620
  };
582
621
  liveServers.add(handle);
583
622
  return handle;
@@ -17,4 +17,6 @@ export interface InternalCommand {
17
17
  args: readonly string[];
18
18
  /** Launcher to wrap the command in; omitted means none (tests opt in explicitly). */
19
19
  launcher?: ResolvedLauncher;
20
+ /** Control panel file to use instead of the bundled one; omitted means none. */
21
+ panel?: string;
20
22
  }
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { compare, hash } from 'bcryptjs';
2
3
  import { CpaStartError } from './errors.ts';
3
4
  import type { ManagementOptions } from './types.ts';
@@ -10,8 +11,10 @@ export const BCRYPT_COST = 10;
10
11
  const MAX_BCRYPT_BYTES = 72;
11
12
 
12
13
  export interface ResolvedManagement {
13
- /** The plaintext key, when the caller supplied one. */
14
+ /** The plaintext key: supplied by the caller or generated for this start. */
14
15
  key: string | undefined;
16
+ /** True when cpajs generated the key because none was given. */
17
+ generated: boolean;
15
18
  /** True when the key travels through `MANAGEMENT_PASSWORD`. */
16
19
  viaEnvironment: boolean;
17
20
  /** Value for `management.allow-remote` in a managed config. */
@@ -26,9 +29,13 @@ export interface ResolvedManagement {
26
29
  * the old `MANAGEMENT_PASSWORD` behaviour.
27
30
  */
28
31
  export async function resolveManagement(options: {
29
- management?: ManagementOptions;
32
+ management?: ManagementOptions | false;
30
33
  managementKey?: string;
34
+ configPath?: string;
35
+ config?: { management?: { 'secret-key'?: unknown } };
31
36
  }): Promise<ResolvedManagement> {
37
+ const none: ResolvedManagement = { key: undefined, generated: false, viaEnvironment: false, allowRemote: false, secretKeyHash: undefined };
38
+ if (options.management === false) return none;
32
39
  if (options.management !== undefined && options.managementKey !== undefined) {
33
40
  throw new CpaStartError(
34
41
  'invalid-options',
@@ -38,12 +45,13 @@ export async function resolveManagement(options: {
38
45
  const management =
39
46
  options.management ?? (options.managementKey === undefined ? undefined : { key: options.managementKey });
40
47
  if (management === undefined) {
41
- return {
42
- key: undefined,
43
- viaEnvironment: false,
44
- allowRemote: false,
45
- secretKeyHash: undefined,
46
- };
48
+ // No key given: generate one for this start so server.client() works, unless the
49
+ // caller manages the secret itself (configPath, or secret-key in config), where
50
+ // cpajs cannot know or must not write the key.
51
+ const ownSecret = options.config?.management?.['secret-key'];
52
+ if (options.configPath !== undefined || (typeof ownSecret === 'string' && ownSecret.trim() !== '')) return none;
53
+ const key = randomBytes(32).toString('base64url');
54
+ return { key, generated: true, viaEnvironment: false, allowRemote: false, secretKeyHash: await hash(key, BCRYPT_COST) };
47
55
  }
48
56
  const key = management.key;
49
57
  if (typeof key !== 'string' || key.trim() === '') {
@@ -57,6 +65,7 @@ export async function resolveManagement(options: {
57
65
  }
58
66
  return {
59
67
  key,
68
+ generated: false,
60
69
  viaEnvironment: true,
61
70
  allowRemote: management.allowRemote === true,
62
71
  secretKeyHash: undefined,
@@ -70,6 +79,7 @@ export async function resolveManagement(options: {
70
79
  }
71
80
  return {
72
81
  key,
82
+ generated: false,
73
83
  viaEnvironment: false,
74
84
  allowRemote: management.allowRemote === true,
75
85
  secretKeyHash: await hash(key, BCRYPT_COST),
@@ -0,0 +1,10 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { fileURLToPath } from 'node:url';
3
+
4
+ /** Where the pinned control panel lives in the package (same depth from src/ and dist/). */
5
+ export const PANEL_FILE = fileURLToPath(new URL('../../assets/management.html', import.meta.url));
6
+
7
+ /** The bundled control panel, or undefined in a checkout where it was not fetched. */
8
+ export function bundledPanel(): string | undefined {
9
+ return existsSync(PANEL_FILE) ? PANEL_FILE : undefined;
10
+ }
@@ -1,5 +1,7 @@
1
1
  import type { ChildProcess } from 'node:child_process';
2
+ import type { CpaClient, ClientOptions } from '../client/index.ts';
2
3
  import type { CpaConfig } from '../client/types/config.ts';
4
+ import type { CpaWarning, SuppressWarnings } from './warnings.ts';
3
5
 
4
6
  export interface LogLine {
5
7
  stream: 'stdout' | 'stderr';
@@ -7,6 +9,9 @@ export interface LogLine {
7
9
  line: string;
8
10
  }
9
11
 
12
+ /** Options for `server.client()`: everything except the origin and the key. */
13
+ export type ServerClientOptions = Omit<ClientOptions, 'baseUrl' | 'managementKey'>;
14
+
10
15
  export interface HomeOptions {
11
16
  /**
12
17
  * Home control plane JWT (`-home-jwt`). It is passed through the `HOME_JWT`
@@ -43,8 +48,19 @@ interface CommonServerOptions {
43
48
  * directory. When omitted, a temporary directory is created and removed on stop.
44
49
  */
45
50
  stateDir?: string;
46
- /** Management API key and how it reaches CPA. */
47
- management?: ManagementOptions;
51
+ /**
52
+ * Management API key and how it reaches CPA.
53
+ *
54
+ * Omitted: cpajs generates a random key for this start, writes only its bcrypt
55
+ * hash into the managed config (remote management off) and keeps the plaintext
56
+ * in memory; use `server.client()` to talk to the management API. Not done in
57
+ * `configPath` mode or when `config.management['secret-key']` is set, because
58
+ * then the secret is yours. With a generated key nobody can log in to the web
59
+ * control panel, so it also defaults `management.disable-control-panel` to
60
+ * true (CPA then skips downloading the panel from GitHub); set it to false in
61
+ * `config` to keep the panel. `false`: the management API stays disabled.
62
+ */
63
+ management?: ManagementOptions | false;
48
64
  /**
49
65
  * Deprecated alias for `management: { key }`. It uses the safe default
50
66
  * (bcrypt hash in the config, remote management disabled) and will be removed
@@ -89,7 +105,17 @@ interface CommonServerOptions {
89
105
  startupTimeoutMs?: number;
90
106
  /** Cancels startup. After startup it has no effect; call `stop()` instead. */
91
107
  signal?: AbortSignal;
92
- /** Receives every output line, redacted. */
108
+ /**
109
+ * Silences individual cpajs warnings, e.g. `{ noManagementKey: true }`. Every
110
+ * warning message names the field that silences it.
111
+ */
112
+ suppressWarnings?: SuppressWarnings;
113
+ /**
114
+ * Receives cpajs warnings instead of `process.emitWarning` (which prints them
115
+ * to stderr as `CpaWarning`). CPA's own output goes to `onLog`.
116
+ */
117
+ onWarning?: (warning: CpaWarning) => void;
118
+ /** Receives every line CPA prints, redacted. */
93
119
  onLog?: (log: LogLine) => void;
94
120
  /** Additional strings to redact from logs and errors. */
95
121
  redact?: readonly string[];
@@ -181,6 +207,13 @@ export interface CpaServer {
181
207
  * terminated forcefully (there is no grace period and CPA is not asked to
182
208
  * flush state or update auth files). Idempotent.
183
209
  */
210
+ /**
211
+ * A management API client already bound to this server's origin and key. The
212
+ * key itself is not exposed. Works when cpajs knows the plaintext key (generated,
213
+ * or passed as `management.key`); throws otherwise, e.g. with `configPath` or a
214
+ * `secret-key` you put in `config` yourself.
215
+ */
216
+ client(options?: ServerClientOptions): CpaClient;
184
217
  stop(options?: StopOptions): Promise<ExitResult>;
185
218
  /**
186
219
  * Restarts CPA with the original options, reusing `origin`, `baseUrl`, `host`,
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Warnings emitted by cpajs itself (not CPA's output, which goes to `onLog`).
3
+ * Each has a stable code that can be suppressed individually.
4
+ */
5
+ export type CpaWarningCode =
6
+ /** No management key was given, so one was generated for this start. */
7
+ | 'noManagementKey'
8
+ /** `management.viaEnvironment`: plaintext comparison, and remote management is forced on. */
9
+ | 'managementViaEnvironment'
10
+ /** `management.allow-remote` is on and the server binds a non-loopback host. */
11
+ | 'remoteManagementExposed'
12
+ /** No cpa-launcher was found, so CPA can outlive this process. */
13
+ /** An existing managed config was kept; this start's `config`, `host` and `port` were not applied. */
14
+ | 'configReused'
15
+ /** The management key in a reused config was replaced with the hash of a new key. */
16
+ | 'managementKeyUpdated';
17
+
18
+ export interface CpaWarning {
19
+ code: CpaWarningCode;
20
+ message: string;
21
+ }
22
+
23
+ /** `{ noManagementKey: true }` silences that warning. */
24
+ export type SuppressWarnings = Partial<Record<CpaWarningCode, boolean>>;
25
+
26
+ /**
27
+ * Returns a function that emits each warning code at most once: to `onWarning`
28
+ * when given, otherwise through `process.emitWarning` (type `CpaWarning`), so it
29
+ * shows up on stderr by default and works with Node's usual warning handling.
30
+ */
31
+ export function createWarner(options: {
32
+ suppressWarnings?: SuppressWarnings | undefined;
33
+ onWarning?: ((warning: CpaWarning) => void) | undefined;
34
+ }): (code: CpaWarningCode, message: string) => void {
35
+ const emitted = new Set<CpaWarningCode>();
36
+ return (code, message) => {
37
+ if (options.suppressWarnings?.[code] === true || emitted.has(code)) return;
38
+ emitted.add(code);
39
+ const warning: CpaWarning = { code, message: `${message} (suppress with suppressWarnings.${code})` };
40
+ if (options.onWarning) options.onWarning(warning);
41
+ else process.emitWarning(warning.message, { type: 'CpaWarning', code });
42
+ };
43
+ }