Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/cli/__tests__/commands/migrate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ describe('migrate <provider>', () => {

expect(mockIntegration.launchChat).toHaveBeenCalledWith(
expect.objectContaining({
prompt: expect.stringContaining('Statsig'),
userPrompt: expect.stringContaining('Statsig'),
cwd: process.cwd(),
}),
);
Expand All @@ -101,9 +101,9 @@ describe('migrate <provider>', () => {

await run(['migrate', 'statsig', '--ide', 'claude']);

const { prompt } = vi.mocked(mockIntegration.launchChat).mock.calls[0][0];
expect(prompt).toContain('migrate-statsig');
expect(prompt).toContain('(statsig)');
const { userPrompt } = vi.mocked(mockIntegration.launchChat).mock.calls[0][0];
expect(userPrompt).toContain('migrate-statsig');
expect(userPrompt).toContain('(statsig)');
});

it('fails when plugin is not installed', async () => {
Expand Down
212 changes: 212 additions & 0 deletions packages/cli/__tests__/features/sdk/install.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { FrameworkConfig } from '@spotify-confidence/core';
import { createProjectDir } from '@spotify-confidence/testing/scaffold';
import { runSdkInstall } from '@features/sdk/install.js';

const mockExecFile = vi.fn<() => Promise<void>>();
const mockDetectFramework = vi.fn<() => Promise<FrameworkConfig | null>>();
const mockMessage = vi.fn();

vi.mock('ora', () => ({
default: () => ({ start: () => ({ succeed: vi.fn(), fail: vi.fn() }) }),
}));

vi.mock('@spotify-confidence/core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@spotify-confidence/core')>();
return {
...actual,
detectFramework: (...args: unknown[]) => mockDetectFramework(...(args as [])),
execFile: (...args: unknown[]) => mockExecFile(...(args as [])),
};
});

vi.mock('@output/print.js', () => ({
message: (...args: unknown[]) => mockMessage(...args),
fail: vi.fn(),
}));

const REACT_FRAMEWORK: FrameworkConfig = {
id: 'react',
name: 'React',
docsUrl: 'https://confidence.spotify.com/docs/sdk/react',
sdkPackage: '@spotify-confidence/sdk',
detect: async () => true,
};

const PYTHON_FRAMEWORK: FrameworkConfig = {
id: 'python',
name: 'Python',
docsUrl: 'https://confidence.spotify.com/docs/sdk/python',
sdkPackage: 'spotify-confidence-sdk',
detect: async () => true,
};

beforeEach(() => {
mockExecFile.mockResolvedValue(undefined);
mockDetectFramework.mockResolvedValue(REACT_FRAMEWORK);
});

describe('runSdkInstall workspace root handling', () => {
it('passes -w when pnpm-workspace.yaml is present', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'pnpm-lock.yaml'), '');
writeFileSync(join(project.path, 'pnpm-workspace.yaml'), 'packages:\n - packages/*');

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'pnpm',
['add', '-w', '@spotify-confidence/sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('omits -w for pnpm without workspace config', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'pnpm-lock.yaml'), '');

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'pnpm',
['add', '@spotify-confidence/sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('passes -W for yarn classic with workspaces', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'yarn.lock'), '');
writeFileSync(
join(project.path, 'package.json'),
JSON.stringify({ workspaces: ['packages/*'] }),
);

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'yarn',
['add', '-W', '@spotify-confidence/sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('omits -W for yarn berry with workspaces', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'yarn.lock'), '');
writeFileSync(
join(project.path, 'package.json'),
JSON.stringify({ workspaces: ['packages/*'] }),
);
writeFileSync(join(project.path, '.yarnrc.yml'), 'nodeLinker: node-modules');

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'yarn',
['add', '@spotify-confidence/sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('omits -W for yarn without workspaces', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'yarn.lock'), '');

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'yarn',
['add', '@spotify-confidence/sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('does not add flags for npm at a workspace root', async () => {
using project = createProjectDir('empty');
writeFileSync(
join(project.path, 'package.json'),
JSON.stringify({ workspaces: ['packages/*'] }),
);

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'npm',
['add', '@spotify-confidence/sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('does not add flags for bun at a workspace root', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'bun.lockb'), '');
writeFileSync(
join(project.path, 'package.json'),
JSON.stringify({ workspaces: ['packages/*'] }),
);

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'bun',
['add', '@spotify-confidence/sdk'],
expect.objectContaining({ cwd: project.path }),
);
});
});

describe('runSdkInstall Python package manager detection', () => {
beforeEach(() => {
mockDetectFramework.mockResolvedValue(PYTHON_FRAMEWORK);
});

it('uses poetry add when poetry.lock is present', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'poetry.lock'), '');

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'poetry',
['add', 'spotify-confidence-sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('uses uv add when uv.lock is present', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'uv.lock'), '');

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'uv',
['add', 'spotify-confidence-sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('uses pipenv install when Pipfile is present', async () => {
using project = createProjectDir('empty');
writeFileSync(join(project.path, 'Pipfile'), '');

await runSdkInstall({ dir: project.path });

expect(mockExecFile).toHaveBeenCalledWith(
'pipenv',
['install', 'spotify-confidence-sdk'],
expect.objectContaining({ cwd: project.path }),
);
});

it('falls back to manual install when no Python PM is detected', async () => {
using project = createProjectDir('empty');

await runSdkInstall({ dir: project.path });

expect(mockExecFile).not.toHaveBeenCalled();
expect(mockMessage).toHaveBeenCalledWith(expect.stringContaining('pip install'));
});
});
2 changes: 2 additions & 0 deletions packages/cli/bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
eventsCommand,
flagsCommand,
recordingsCommand,
sdkCommand,
quickstartCommand,
mcpCommand,
updateCommand,
Expand Down Expand Up @@ -70,6 +71,7 @@ const cli = yargs(hideBin(process.argv))
.command(eventsCommand)
.command(flagsCommand)
.command(recordingsCommand)
.command(sdkCommand)
.command(quickstartCommand)
.command(mcpCommand)
.command(updateCommand)
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export { configCommand } from './config.js';
export { eventsCommand } from './events.js';
export { flagsCommand } from './flags.js';
export { recordingsCommand } from './recordings.js';
export { sdkCommand } from './sdk.js';
export { quickstartCommand } from './quickstart.js';
export { mcpCommand } from './mcp.js';
export { pluginCommand } from './plugin.js';
Expand Down
41 changes: 41 additions & 0 deletions packages/cli/src/commands/sdk.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { Argv } from 'yargs';
import { runSdkInstall, runSdkSetup } from '@features/sdk/index.js';
import { safely } from '../utils/safely.js';

export const sdkCommand = {
command: 'sdk <action>',
describe: 'Manage SDK installation and setup',
builder(yargs: Argv) {
return yargs
.option('dir', {
type: 'string',
describe: 'Target project directory',
normalize: true,
})
.command(
'install',
'Detect framework and install the Confidence SDK',
() => {},
safely(runSdkInstall),
)
.command(
'setup',
'Set up the Confidence SDK in your project',
(y: Argv) =>
y
.option('ide', {
type: 'string',
choices: ['claude', 'cursor', 'codex'] as const,
describe: 'AI coding agent to use',
})
.option('profile', {
type: 'string',
describe: 'Auth profile to use',
}),
safely(runSdkSetup),
)
.demandCommand(1, 'Run "confidence sdk --help" to see available actions.')
.strict();
},
handler() {},
};
4 changes: 2 additions & 2 deletions packages/cli/src/features/migrate/launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ export async function launchMigration(
const token = await resolveAuthToken({ profile: resolveFlag('profile', argv) });
if (!token) return;

const prompt = buildMigrationPrompt(provider);
integration.launchChat({ prompt, cwd: projectDir, token });
const userPrompt = buildMigrationPrompt(provider);
integration.launchChat({ userPrompt, cwd: projectDir, token });
}
2 changes: 2 additions & 0 deletions packages/cli/src/features/sdk/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { runSdkInstall } from './install.js';
export { runSdkSetup } from './setup.js';
29 changes: 29 additions & 0 deletions packages/cli/src/features/sdk/install-jvm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import type { InstallCommand } from './install-types.js';

export function buildKotlinInstall(pkg: string): InstallCommand {
return {
type: 'manual',
snippet:
`Add the following to your module's build.gradle.kts:\n\n` +
` dependencies {\n` +
` implementation("${pkg}:<version>")\n` +
` }`,
};
}

export function buildJavaInstall(pkg: string): InstallCommand {
const [groupId, artifactId] = pkg.split(':');
return {
type: 'manual',
snippet:
`Add the following to your build.gradle.kts or pom.xml:\n\n` +
` Gradle:\n` +
` implementation("${pkg}:<version>")\n\n` +
` Maven:\n` +
` <dependency>\n` +
` <groupId>${groupId}</groupId>\n` +
` <artifactId>${artifactId}</artifactId>\n` +
` <version><version></version>\n` +
` </dependency>`,
};
}
17 changes: 17 additions & 0 deletions packages/cli/src/features/sdk/install-native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { InstallCommand } from './install-types.js';

export function buildGoInstall(pkg: string): InstallCommand {
return { type: 'auto', cmd: 'go', args: ['get', pkg] };
}

export function buildSwiftInstall(pkg: string): InstallCommand {
return {
type: 'manual',
snippet:
`Add the following to your Package.swift dependencies:\n\n` +
` .package(\n` +
` url: "https://github.com/spotify/${pkg}.git",\n` +
` from: "<version>"\n` +
` )`,
};
}
38 changes: 38 additions & 0 deletions packages/cli/src/features/sdk/install-node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { InstallCommand } from './install-types.js';

type NodePM = 'npm' | 'pnpm' | 'yarn' | 'bun';

function detectNodePM(dir: string): NodePM {
if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
if (existsSync(join(dir, 'yarn.lock'))) return 'yarn';
if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun';
return 'npm';
}

function hasPackageJsonWorkspaces(dir: string): boolean {
const pkgPath = join(dir, 'package.json');
if (!existsSync(pkgPath)) return false;

try {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'));
return Array.isArray(pkg.workspaces) || typeof pkg.workspaces === 'object';
} catch {
return false;
}
}

function workspaceRootArgs(pm: NodePM, dir: string): string[] {
if (pm === 'pnpm' && existsSync(join(dir, 'pnpm-workspace.yaml'))) return ['-w'];
if (pm === 'yarn' && hasPackageJsonWorkspaces(dir) && !existsSync(join(dir, '.yarnrc.yml'))) {
return ['-W'];
}

return [];
}

export function buildNodeInstall(pkg: string, dir: string): InstallCommand {
const pm = detectNodePM(dir);
return { type: 'auto', cmd: pm, args: ['add', ...workspaceRootArgs(pm, dir), pkg] };
}
Loading
Loading