All files / src/cli trpc-client.ts

62.5% Statements 5/8
33.33% Branches 2/6
66.66% Functions 2/3
62.5% Lines 5/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                      1x     1x                                   2x 2x     8x                                          
/**
 * tRPC Client for CLI
 *
 * Type-safe client for communicating with the coordination server.
 * Uses splitLink to route subscriptions to SSE and queries/mutations to HTTP batch.
 */
 
import { createTRPCClient, httpBatchLink, splitLink, httpSubscriptionLink } from '@trpc/client';
import type { AppRouter } from '../trpc/index.js';
 
/** Default server port */
const DEFAULT_PORT = 3847;
 
/** Default server host */
const DEFAULT_HOST = '127.0.0.1';
 
/**
 * Type-safe tRPC client for the coordination server.
 */
export type TrpcClient = ReturnType<typeof createTRPCClient<AppRouter>>;
 
/**
 * Creates a tRPC client for the coordination server.
 *
 * @param port - Server port (default: 3847)
 * @param host - Server host (default: 127.0.0.1)
 * @returns Type-safe tRPC client
 */
export function createTrpcClient(
  port: number = DEFAULT_PORT,
  host: string = DEFAULT_HOST
): TrpcClient {
  const url = `http://${host}:${port}/trpc`;
  return createTRPCClient<AppRouter>({
    links: [
      splitLink({
        condition: (op) => op.type === 'subscription',
        true: httpSubscriptionLink({ url }),
        false: httpBatchLink({ url }),
      }),
    ],
  });
}
 
/**
 * Creates a tRPC client using environment variables or defaults.
 *
 * Uses CW_PORT and CW_HOST environment variables if available,
 * falling back to defaults (127.0.0.1:3847).
 *
 * @returns Type-safe tRPC client
 */
export function createDefaultTrpcClient(): TrpcClient {
  const port = process.env.CW_PORT ? parseInt(process.env.CW_PORT, 10) : DEFAULT_PORT;
  const host = process.env.CW_HOST ?? DEFAULT_HOST;
  return createTrpcClient(port, host);
}