Twenty sdk cli oauth (#18638)
<img width="1418" height="804" alt="image" src="https://github.com/user-attachments/assets/de6c8222-6496-4a71-bc21-7e5e1269d5cb" /> --------- Co-authored-by: Félix Malfait <felix.malfait@gmail.com> Co-authored-by: Félix Malfait <felix@twenty.com>
This commit is contained in:
+3
-3
@@ -1,8 +1,8 @@
|
||||
import { vi } from 'vitest';
|
||||
|
||||
import { appBuild } from '@/cli/public-operations/app-build';
|
||||
import { appUninstall } from '@/cli/public-operations/app-uninstall';
|
||||
import { functionExecute } from '@/cli/public-operations/function-execute';
|
||||
import { appBuild } from '@/cli/operations/build';
|
||||
import { appUninstall } from '@/cli/operations/uninstall';
|
||||
import { functionExecute } from '@/cli/operations/execute';
|
||||
import { FUNCTION_EXECUTE_APP_PATH } from '@/cli/__tests__/apps/fixture-paths';
|
||||
|
||||
const ADD_NUMBERS_UNIVERSAL_IDENTIFIER = 'f9e5589c-e951-4d99-85db-0a305ab53502';
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@ import { defineFrontComponentsTests } from './tests/front-components.tests';
|
||||
import { defineLogicFunctionsTests } from './tests/logic-functions.tests';
|
||||
import { defineManifestTests } from './tests/manifest.tests';
|
||||
|
||||
describe('minimal-app app:dev', () => {
|
||||
describe('minimal-app dev', () => {
|
||||
beforeAll(async () => {
|
||||
const result = await runAppDevInProcess({ appPath: MINIMAL_APP_PATH });
|
||||
|
||||
@@ -17,7 +17,7 @@ describe('minimal-app app:dev', () => {
|
||||
);
|
||||
|
||||
throw new Error(
|
||||
`app:dev did not produce manifest.json within timeout.\n${diagnostics}`,
|
||||
`dev did not produce manifest.json within timeout.\n${diagnostics}`,
|
||||
);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
+5
-3
@@ -16,11 +16,13 @@ export const defineManifestTests = (appPath: string): void => {
|
||||
|
||||
it('should have correct manifest content', async () => {
|
||||
const manifestPath = join(appPath, '.twenty/output/manifest.json');
|
||||
const manifest: Manifest = normalizeManifestForComparison(
|
||||
await readJson(manifestPath),
|
||||
const manifest = normalizeManifestForComparison(
|
||||
await readJson<Manifest>(manifestPath),
|
||||
);
|
||||
|
||||
expect(manifest).toEqual(EXPECTED_MANIFEST);
|
||||
expect(manifest).toEqual(
|
||||
normalizeManifestForComparison(EXPECTED_MANIFEST),
|
||||
);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
+6
-6
@@ -15,10 +15,10 @@ describe('Application: install delete and reinstall postcard-app', () => {
|
||||
expect(existsSync(appPath)).toBe(true);
|
||||
|
||||
const result = await runCliCommand({
|
||||
command: 'auth:status',
|
||||
args: [appPath],
|
||||
command: 'remote',
|
||||
args: ['status'],
|
||||
timeout: 5_000,
|
||||
waitForOutput: '✓ Valid',
|
||||
waitForOutput: '(valid)',
|
||||
});
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
@@ -26,7 +26,7 @@ describe('Application: install delete and reinstall postcard-app', () => {
|
||||
|
||||
it(`should successfully install ${applicationName} application`, async () => {
|
||||
await runCliCommand({
|
||||
command: 'app:dev',
|
||||
command: 'dev',
|
||||
args: [appPath],
|
||||
waitForOutput: '✓ Synced',
|
||||
});
|
||||
@@ -36,7 +36,7 @@ describe('Application: install delete and reinstall postcard-app', () => {
|
||||
|
||||
it(`should successfully delete ${applicationName} application`, async () => {
|
||||
await runCliCommand({
|
||||
command: 'app:uninstall',
|
||||
command: 'uninstall',
|
||||
args: [appPath, '-y'],
|
||||
waitForOutput: 'Application uninstalled successfully',
|
||||
});
|
||||
@@ -44,7 +44,7 @@ describe('Application: install delete and reinstall postcard-app', () => {
|
||||
|
||||
it(`should successfully re-install ${applicationName} application`, async () => {
|
||||
await runCliCommand({
|
||||
command: 'app:dev',
|
||||
command: 'dev',
|
||||
args: [appPath],
|
||||
waitForOutput: '✓ Synced',
|
||||
});
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ import { POSTCARD_APP_PATH } from '@/cli/__tests__/apps/fixture-paths';
|
||||
import { defineEntitiesTests } from './tests/entities.tests';
|
||||
import { defineManifestTests } from './tests/manifest.tests';
|
||||
|
||||
describe('postcard-app app:dev', () => {
|
||||
describe('postcard-app dev', () => {
|
||||
beforeAll(async () => {
|
||||
const result = await runAppDevInProcess({ appPath: POSTCARD_APP_PATH });
|
||||
|
||||
@@ -16,7 +16,7 @@ describe('postcard-app app:dev', () => {
|
||||
);
|
||||
|
||||
throw new Error(
|
||||
`app:dev did not produce manifest.json within timeout.\n${diagnostics}`,
|
||||
`dev did not produce manifest.json within timeout.\n${diagnostics}`,
|
||||
);
|
||||
}
|
||||
}, 60000);
|
||||
|
||||
@@ -1 +1 @@
|
||||
export const SERVER_URL = 'http://localhost:3000';
|
||||
export const SERVER_URL = process.env.TWENTY_API_URL ?? 'http://localhost:3000';
|
||||
|
||||
@@ -11,12 +11,13 @@ beforeAll(async () => {
|
||||
await ensureDir(path.dirname(testConfigPath));
|
||||
|
||||
const configFile = {
|
||||
profiles: {
|
||||
default: {
|
||||
remotes: {
|
||||
local: {
|
||||
apiUrl: process.env.TWENTY_API_URL,
|
||||
apiKey: process.env.TWENTY_API_KEY,
|
||||
},
|
||||
},
|
||||
defaultRemote: 'local',
|
||||
};
|
||||
|
||||
await writeFile(testConfigPath, JSON.stringify(configFile, null, 2));
|
||||
|
||||
+32
-10
@@ -1,5 +1,10 @@
|
||||
import { type Manifest } from 'twenty-shared/application';
|
||||
|
||||
const sortById = <T extends { universalIdentifier: string }>(items: T[]): T[] =>
|
||||
[...items].sort((a, b) =>
|
||||
a.universalIdentifier.localeCompare(b.universalIdentifier),
|
||||
);
|
||||
|
||||
export const normalizeManifestForComparison = <T extends Manifest>(
|
||||
manifest: T,
|
||||
): T => ({
|
||||
@@ -16,14 +21,31 @@ export const normalizeManifestForComparison = <T extends Manifest>(
|
||||
? '[checksum]'
|
||||
: null,
|
||||
},
|
||||
logicFunctions: manifest.logicFunctions?.map((fn) => ({
|
||||
...fn,
|
||||
builtHandlerChecksum: fn.builtHandlerChecksum ? '[checksum]' : null,
|
||||
})),
|
||||
frontComponents: manifest.frontComponents?.map((component) => ({
|
||||
...component,
|
||||
builtComponentChecksum: component.builtComponentChecksum
|
||||
? '[checksum]'
|
||||
: '',
|
||||
})),
|
||||
objects: sortById(
|
||||
manifest.objects.map((object) => ({
|
||||
...object,
|
||||
fields: sortById(object.fields),
|
||||
})),
|
||||
),
|
||||
fields: sortById(manifest.fields),
|
||||
roles: sortById(manifest.roles),
|
||||
skills: sortById(manifest.skills),
|
||||
agents: sortById(manifest.agents),
|
||||
views: sortById(manifest.views),
|
||||
navigationMenuItems: sortById(manifest.navigationMenuItems),
|
||||
pageLayouts: sortById(manifest.pageLayouts),
|
||||
logicFunctions: sortById(
|
||||
manifest.logicFunctions?.map((fn) => ({
|
||||
...fn,
|
||||
builtHandlerChecksum: fn.builtHandlerChecksum ? '[checksum]' : null,
|
||||
})),
|
||||
),
|
||||
frontComponents: sortById(
|
||||
manifest.frontComponents?.map((component) => ({
|
||||
...component,
|
||||
builtComponentChecksum: component.builtComponentChecksum
|
||||
? '[checksum]'
|
||||
: '',
|
||||
})),
|
||||
),
|
||||
});
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
import { join } from 'path';
|
||||
import { OUTPUT_DIR } from 'twenty-shared/application';
|
||||
|
||||
import { AppDevCommand } from '@/cli/commands/app/app-dev';
|
||||
import { AppDevCommand } from '@/cli/commands/dev';
|
||||
import { pathExists } from '@/cli/utilities/file/fs-utils';
|
||||
|
||||
export type RunAppDevResult = {
|
||||
|
||||
@@ -5,23 +5,11 @@ const mockApiService = {
|
||||
generateApplicationToken: vi.fn().mockResolvedValue({
|
||||
success: true,
|
||||
data: {
|
||||
applicationAccessToken: { token: 'mock-access-token', expiresAt: '' },
|
||||
applicationRefreshToken: { token: 'mock-refresh-token', expiresAt: '' },
|
||||
},
|
||||
}),
|
||||
renewApplicationToken: vi.fn().mockResolvedValue({
|
||||
success: true,
|
||||
data: {
|
||||
applicationAccessToken: {
|
||||
token: 'mock-renewed-access-token',
|
||||
expiresAt: '',
|
||||
},
|
||||
applicationRefreshToken: {
|
||||
token: 'mock-renewed-refresh-token',
|
||||
expiresAt: '',
|
||||
},
|
||||
accessToken: { token: 'mock-access-token', expiresAt: '' },
|
||||
refreshToken: { token: 'mock-refresh-token', expiresAt: '' },
|
||||
},
|
||||
}),
|
||||
refreshToken: vi.fn().mockResolvedValue('mock-renewed-access-token'),
|
||||
findApplicationRegistrationByUniversalIdentifier: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ success: true, data: null }),
|
||||
@@ -47,7 +35,7 @@ vi.mock('@/cli/utilities/api/api-service', () => ({
|
||||
ApiService: class {
|
||||
validateAuth = mockApiService.validateAuth;
|
||||
generateApplicationToken = mockApiService.generateApplicationToken;
|
||||
renewApplicationToken = mockApiService.renewApplicationToken;
|
||||
refreshToken = mockApiService.refreshToken;
|
||||
findApplicationRegistrationByUniversalIdentifier =
|
||||
mockApiService.findApplicationRegistrationByUniversalIdentifier;
|
||||
createApplicationRegistration =
|
||||
|
||||
@@ -16,8 +16,8 @@ program
|
||||
.version(packageJson.version);
|
||||
|
||||
program.option(
|
||||
'--workspace <name>',
|
||||
'Use a specific workspace configuration (overrides the default set by auth:switch)',
|
||||
'-r, --remote <name>',
|
||||
'Use a specific remote (overrides the default set by remote switch)',
|
||||
);
|
||||
|
||||
program.hook('preAction', async (thisCommand) => {
|
||||
@@ -25,17 +25,15 @@ program.hook('preAction', async (thisCommand) => {
|
||||
? (thisCommand as any).optsWithGlobals()
|
||||
: thisCommand.opts();
|
||||
|
||||
// If --workspace is provided, use it; otherwise, read the persisted default
|
||||
let workspace = opts.workspace;
|
||||
if (!workspace) {
|
||||
let remote = opts.remote;
|
||||
if (!remote) {
|
||||
const configService = new ConfigService();
|
||||
workspace = await configService.getDefaultWorkspace();
|
||||
remote = await configService.getDefaultRemote();
|
||||
} else {
|
||||
console.log(chalk.gray(`Using remote: ${remote}`));
|
||||
}
|
||||
|
||||
ConfigService.setActiveWorkspace(workspace);
|
||||
console.log(
|
||||
chalk.gray(`👩💻 Workspace - ${ConfigService.getActiveWorkspace()}`),
|
||||
);
|
||||
ConfigService.setActiveRemote(remote);
|
||||
});
|
||||
|
||||
registerCommands(program);
|
||||
|
||||
@@ -1,78 +1,31 @@
|
||||
import { formatPath } from '@/cli/utilities/file/file-path';
|
||||
import chalk from 'chalk';
|
||||
import type { Command } from 'commander';
|
||||
import { AppBuildCommand } from './app/app-build';
|
||||
import { AppDevCommand } from './app/app-dev';
|
||||
import { AppPublishCommand } from './app/app-publish';
|
||||
import { AppTypecheckCommand } from './app/app-typecheck';
|
||||
import { AppUninstallCommand } from './app/app-uninstall';
|
||||
import { AuthListCommand } from './auth/auth-list';
|
||||
import { AuthLoginCommand } from './auth/auth-login';
|
||||
import { AuthLogoutCommand } from './auth/auth-logout';
|
||||
import { AuthStatusCommand } from './auth/auth-status';
|
||||
import { LogicFunctionExecuteCommand } from './logic-function/logic-function-execute';
|
||||
import { LogicFunctionLogsCommand } from './logic-function/logic-function-logs';
|
||||
import { AuthSwitchCommand } from './auth/auth-switch';
|
||||
import { EntityAddCommand } from './entity/entity-add';
|
||||
import { AppBuildCommand } from './build';
|
||||
import { AppDevCommand } from './dev';
|
||||
import { AppPublishCommand } from './publish';
|
||||
import { AppTypecheckCommand } from './typecheck';
|
||||
import { AppUninstallCommand } from './uninstall';
|
||||
import { DeployCommand } from './deploy';
|
||||
import { LogicFunctionExecuteCommand } from './exec';
|
||||
import { LogicFunctionLogsCommand } from './logs';
|
||||
import { EntityAddCommand } from './add';
|
||||
import { registerRemoteCommands } from './remote';
|
||||
import { SyncableEntity } from 'twenty-shared/application';
|
||||
|
||||
export const registerCommands = (program: Command): void => {
|
||||
// Auth commands
|
||||
const listCommand = new AuthListCommand();
|
||||
const loginCommand = new AuthLoginCommand();
|
||||
const logoutCommand = new AuthLogoutCommand();
|
||||
const statusCommand = new AuthStatusCommand();
|
||||
const switchCommand = new AuthSwitchCommand();
|
||||
|
||||
program
|
||||
.command('auth:login')
|
||||
.description('Authenticate with Twenty')
|
||||
.option('--api-key <key>', 'API key for authentication')
|
||||
.option('--api-url <url>', 'Twenty API URL')
|
||||
.action(async (options) => {
|
||||
await loginCommand.execute(options);
|
||||
});
|
||||
|
||||
program
|
||||
.command('auth:logout')
|
||||
.description('Remove authentication credentials')
|
||||
.action(async () => {
|
||||
await logoutCommand.execute();
|
||||
});
|
||||
|
||||
program
|
||||
.command('auth:status')
|
||||
.description('Check authentication status')
|
||||
.action(async () => {
|
||||
await statusCommand.execute();
|
||||
});
|
||||
|
||||
program
|
||||
.command('auth:switch [workspace]')
|
||||
.description('Switch the default workspace for authentication')
|
||||
.action(async (workspace?: string) => {
|
||||
await switchCommand.execute({ workspace });
|
||||
});
|
||||
|
||||
program
|
||||
.command('auth:list')
|
||||
.description('List all configured workspaces')
|
||||
.action(async () => {
|
||||
await listCommand.execute();
|
||||
});
|
||||
|
||||
// App commands
|
||||
const buildCommand = new AppBuildCommand();
|
||||
const devCommand = new AppDevCommand();
|
||||
const publishCommand = new AppPublishCommand();
|
||||
const typecheckCommand = new AppTypecheckCommand();
|
||||
const uninstallCommand = new AppUninstallCommand();
|
||||
const deployCommand = new DeployCommand();
|
||||
const addCommand = new EntityAddCommand();
|
||||
const logsCommand = new LogicFunctionLogsCommand();
|
||||
const executeCommand = new LogicFunctionExecuteCommand();
|
||||
|
||||
program
|
||||
.command('app:dev [appPath]')
|
||||
.command('dev [appPath]')
|
||||
.description('Watch and sync local application changes')
|
||||
.action(async (appPath) => {
|
||||
await devCommand.execute({
|
||||
@@ -81,7 +34,7 @@ export const registerCommands = (program: Command): void => {
|
||||
});
|
||||
|
||||
program
|
||||
.command('app:build [appPath]')
|
||||
.command('build [appPath]')
|
||||
.description('Build, sync, and generate API client into .twenty/output/')
|
||||
.option('--tarball', 'Also pack into a .tgz tarball')
|
||||
.action(async (appPath, options) => {
|
||||
@@ -92,24 +45,29 @@ export const registerCommands = (program: Command): void => {
|
||||
});
|
||||
|
||||
program
|
||||
.command('app:publish [appPath]')
|
||||
.description(
|
||||
'Build and publish to npm, or to a Twenty server with --server',
|
||||
)
|
||||
.option('--server <url>', 'Publish to a Twenty server instead of npm')
|
||||
.option('--token <token>', 'Auth token for the server')
|
||||
.command('deploy [appPath]')
|
||||
.description('Build and deploy to a Twenty server')
|
||||
.option('-r, --remote <name>', 'Deploy to a specific remote')
|
||||
.action(async (appPath, options) => {
|
||||
await deployCommand.execute({
|
||||
appPath: formatPath(appPath),
|
||||
remote: options.remote,
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command('publish [appPath]')
|
||||
.description('Build and publish to npm')
|
||||
.option('--tag <tag>', 'npm dist-tag (e.g. beta, next)')
|
||||
.action(async (appPath, options) => {
|
||||
await publishCommand.execute({
|
||||
appPath: formatPath(appPath),
|
||||
server: options.server,
|
||||
token: options.token,
|
||||
tag: options.tag,
|
||||
});
|
||||
});
|
||||
|
||||
program
|
||||
.command('app:typecheck [appPath]')
|
||||
.command('typecheck [appPath]')
|
||||
.description('Run TypeScript type checking on the application')
|
||||
.action(async (appPath) => {
|
||||
await typecheckCommand.execute({
|
||||
@@ -118,7 +76,7 @@ export const registerCommands = (program: Command): void => {
|
||||
});
|
||||
|
||||
program
|
||||
.command('app:uninstall [appPath]')
|
||||
.command('uninstall [appPath]')
|
||||
.description('Uninstall application from Twenty')
|
||||
.option('-y, --yes', 'Skip confirmation prompt')
|
||||
.action(async (appPath?: string, options?: { yes?: boolean }) => {
|
||||
@@ -133,8 +91,10 @@ export const registerCommands = (program: Command): void => {
|
||||
}
|
||||
});
|
||||
|
||||
registerRemoteCommands(program);
|
||||
|
||||
program
|
||||
.command('entity:add [entityType]')
|
||||
.command('add [entityType]')
|
||||
.option('--path <path>', 'Path in which the entity should be created.')
|
||||
.description(
|
||||
`Add a new entity to your application (${Object.values(SyncableEntity).join('|')})`,
|
||||
@@ -143,35 +103,8 @@ export const registerCommands = (program: Command): void => {
|
||||
await addCommand.execute(entityType as SyncableEntity, options?.path);
|
||||
});
|
||||
|
||||
// Function commands
|
||||
program
|
||||
.command('function:logs [appPath]')
|
||||
.option(
|
||||
'-u, --functionUniversalIdentifier <functionUniversalIdentifier>',
|
||||
'Only show logs for the function with this universal ID',
|
||||
)
|
||||
.option(
|
||||
'-n, --functionName <functionName>',
|
||||
'Only show logs for the function with this name',
|
||||
)
|
||||
.description('Watch application function logs')
|
||||
.action(
|
||||
async (
|
||||
appPath?: string,
|
||||
options?: {
|
||||
functionUniversalIdentifier?: string;
|
||||
functionName?: string;
|
||||
},
|
||||
) => {
|
||||
await logsCommand.execute({
|
||||
...options,
|
||||
appPath: formatPath(appPath),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
program
|
||||
.command('function:execute [appPath]')
|
||||
.command('exec [appPath]')
|
||||
.option('--postInstall', 'Execute post-install logic function if defined')
|
||||
.option(
|
||||
'-p, --payload <payload>',
|
||||
@@ -216,4 +149,30 @@ export const registerCommands = (program: Command): void => {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
program
|
||||
.command('logs [appPath]')
|
||||
.option(
|
||||
'-u, --functionUniversalIdentifier <functionUniversalIdentifier>',
|
||||
'Only show logs for the function with this universal ID',
|
||||
)
|
||||
.option(
|
||||
'-n, --functionName <functionName>',
|
||||
'Only show logs for the function with this name',
|
||||
)
|
||||
.description('Watch application function logs')
|
||||
.action(
|
||||
async (
|
||||
appPath?: string,
|
||||
options?: {
|
||||
functionUniversalIdentifier?: string;
|
||||
functionName?: string;
|
||||
},
|
||||
) => {
|
||||
await logsCommand.execute({
|
||||
...options,
|
||||
appPath: formatPath(appPath),
|
||||
});
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export class AuthListCommand {
|
||||
private configService = new ConfigService();
|
||||
|
||||
async execute(): Promise<void> {
|
||||
try {
|
||||
const availableWorkspaces =
|
||||
await this.configService.getAvailableWorkspaces();
|
||||
const currentDefault = await this.configService.getDefaultWorkspace();
|
||||
|
||||
if (availableWorkspaces.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'⚠ No workspaces configured. Use `twenty auth:login` to create one.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(chalk.blue('Available workspaces:\n'));
|
||||
|
||||
for (const workspaceName of availableWorkspaces) {
|
||||
const config =
|
||||
await this.configService.getConfigForWorkspace(workspaceName);
|
||||
const hasCredentials = !!config.apiKey;
|
||||
const isDefault = workspaceName === currentDefault;
|
||||
|
||||
const defaultIndicator = isDefault ? chalk.green(' (default)') : '';
|
||||
const credentialStatus = hasCredentials
|
||||
? chalk.green('●')
|
||||
: chalk.gray('○');
|
||||
|
||||
console.log(
|
||||
` ${credentialStatus} ${workspaceName}${defaultIndicator}`,
|
||||
);
|
||||
console.log(chalk.gray(` API URL: ${config.apiUrl}`));
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log(chalk.gray('● = authenticated, ○ = no credentials'));
|
||||
console.log(
|
||||
chalk.gray('Use `twenty auth:switch <workspace>` to change default'),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
chalk.red('List failed:'),
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import { authLogin } from '@/cli/public-operations/auth-login';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import chalk from 'chalk';
|
||||
import inquirer from 'inquirer';
|
||||
|
||||
export class AuthLoginCommand {
|
||||
private configService = new ConfigService();
|
||||
|
||||
async execute(options: { apiKey?: string; apiUrl?: string }): Promise<void> {
|
||||
let { apiKey, apiUrl } = options;
|
||||
|
||||
const config = await this.configService.getConfig();
|
||||
|
||||
if (!apiUrl) {
|
||||
const urlAnswer = await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'apiUrl',
|
||||
message: 'Twenty API URL:',
|
||||
default: config.apiUrl,
|
||||
validate: (input) => {
|
||||
try {
|
||||
new URL(input);
|
||||
return true;
|
||||
} catch {
|
||||
return 'Please enter a valid URL';
|
||||
}
|
||||
},
|
||||
},
|
||||
]);
|
||||
apiUrl = urlAnswer.apiUrl;
|
||||
}
|
||||
|
||||
if (!apiKey) {
|
||||
const keyAnswer = await inquirer.prompt([
|
||||
{
|
||||
type: 'password',
|
||||
name: 'apiKey',
|
||||
message: 'API Key:',
|
||||
mask: '*',
|
||||
validate: (input) => input.length > 0 || 'API key is required',
|
||||
},
|
||||
]);
|
||||
apiKey = keyAnswer.apiKey;
|
||||
}
|
||||
|
||||
const result = await authLogin({ apiKey: apiKey!, apiUrl: apiUrl! });
|
||||
|
||||
if (result.success) {
|
||||
const activeWorkspace = ConfigService.getActiveWorkspace();
|
||||
console.log(
|
||||
chalk.green(
|
||||
`✓ Successfully authenticated with Twenty (workspace: ${activeWorkspace})`,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
console.log(
|
||||
chalk.red('✗ Authentication failed. Please check your credentials.'),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { authLogout } from '@/cli/public-operations/auth-logout';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export class AuthLogoutCommand {
|
||||
async execute(): Promise<void> {
|
||||
const result = await authLogout();
|
||||
|
||||
if (!result.success) {
|
||||
console.error(chalk.red('Logout failed:'), result.error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const activeWorkspace = ConfigService.getActiveWorkspace();
|
||||
console.log(
|
||||
chalk.green(`✓ Successfully logged out (workspace: ${activeWorkspace})`),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export class AuthStatusCommand {
|
||||
private configService = new ConfigService();
|
||||
private apiService = new ApiService();
|
||||
|
||||
async execute(): Promise<void> {
|
||||
try {
|
||||
const activeWorkspace = ConfigService.getActiveWorkspace();
|
||||
const config = await this.configService.getConfig();
|
||||
|
||||
console.log(chalk.blue('Authentication Status:'));
|
||||
console.log(`Workspace: ${activeWorkspace}`);
|
||||
console.log(`API URL: ${config.apiUrl}`);
|
||||
console.log(
|
||||
`API Key: ${config.apiKey ? '***' + config.apiKey.slice(-4) : 'Not set'}`,
|
||||
);
|
||||
|
||||
if (config.apiKey) {
|
||||
const validateAuth = await this.apiService.validateAuth();
|
||||
console.log(
|
||||
`Status: ${validateAuth.authValid ? chalk.green('✓ Valid') : chalk.red('✗ Invalid')}`,
|
||||
);
|
||||
} else {
|
||||
console.log(`Status: ${chalk.yellow('⚠ Not authenticated')}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
chalk.red('Status check failed:'),
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import chalk from 'chalk';
|
||||
import inquirer from 'inquirer';
|
||||
|
||||
export class AuthSwitchCommand {
|
||||
private configService = new ConfigService();
|
||||
private apiService = new ApiService();
|
||||
|
||||
async execute(options: { workspace?: string }): Promise<void> {
|
||||
try {
|
||||
let { workspace } = options;
|
||||
|
||||
const availableWorkspaces =
|
||||
await this.configService.getAvailableWorkspaces();
|
||||
const currentDefault = await this.configService.getDefaultWorkspace();
|
||||
|
||||
if (availableWorkspaces.length === 0) {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'⚠ No workspaces configured. Use `twenty auth:login` to create one.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!workspace) {
|
||||
const choices = availableWorkspaces.map((ws) => ({
|
||||
name: ws === currentDefault ? `${ws} (current default)` : ws,
|
||||
value: ws,
|
||||
}));
|
||||
|
||||
const answer = await inquirer.prompt([
|
||||
{
|
||||
type: 'list',
|
||||
name: 'workspace',
|
||||
message: 'Select a workspace to set as default:',
|
||||
choices,
|
||||
default: currentDefault,
|
||||
},
|
||||
]);
|
||||
|
||||
workspace = answer.workspace as string;
|
||||
}
|
||||
|
||||
if (!availableWorkspaces.includes(workspace!)) {
|
||||
console.log(
|
||||
chalk.red(
|
||||
`✗ Workspace "${workspace}" not found. Available workspaces: ${availableWorkspaces.join(', ')}`,
|
||||
),
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (workspace === currentDefault) {
|
||||
console.log(
|
||||
chalk.blue(`ℹ "${workspace}" is already the default workspace.`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.configService.setDefaultWorkspace(workspace!);
|
||||
ConfigService.setActiveWorkspace(workspace);
|
||||
|
||||
const config = await this.configService.getConfig();
|
||||
const hasCredentials = !!config.apiKey;
|
||||
|
||||
console.log(
|
||||
chalk.green(`✓ Switched default workspace to "${workspace}"`),
|
||||
);
|
||||
|
||||
if (hasCredentials) {
|
||||
const validateAuth = await this.apiService.validateAuth();
|
||||
|
||||
if (validateAuth.authValid) {
|
||||
console.log(chalk.green('✓ Authentication is valid'));
|
||||
} else {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'⚠ Authentication credentials exist but are invalid. Run `twenty auth:login` to re-authenticate.',
|
||||
),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'⚠ No credentials configured for this workspace. Run `twenty auth:login` to authenticate.',
|
||||
),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
chalk.red('Switch failed:'),
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { appBuild } from '@/cli/public-operations/app-build';
|
||||
import { appBuild } from '@/cli/operations/build';
|
||||
import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/current-execution-directory';
|
||||
import { checkSdkVersionCompatibility } from '@/cli/utilities/version/check-sdk-version-compatibility';
|
||||
import chalk from 'chalk';
|
||||
@@ -0,0 +1,56 @@
|
||||
import { appDeploy } from '@/cli/operations/deploy';
|
||||
import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/current-execution-directory';
|
||||
import { checkSdkVersionCompatibility } from '@/cli/utilities/version/check-sdk-version-compatibility';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export type DeployCommandOptions = {
|
||||
appPath?: string;
|
||||
remote?: string;
|
||||
};
|
||||
|
||||
export class DeployCommand {
|
||||
async execute(options: DeployCommandOptions): Promise<void> {
|
||||
const appPath = options.appPath ?? CURRENT_EXECUTION_DIRECTORY;
|
||||
|
||||
await checkSdkVersionCompatibility(appPath);
|
||||
|
||||
const configService = new ConfigService();
|
||||
let serverUrl: string;
|
||||
let token: string | undefined;
|
||||
|
||||
if (options.remote) {
|
||||
const remoteConfig = await configService.getConfigForRemote(
|
||||
options.remote,
|
||||
);
|
||||
|
||||
serverUrl = remoteConfig.apiUrl;
|
||||
token = remoteConfig.accessToken ?? remoteConfig.apiKey;
|
||||
} else {
|
||||
const config = await configService.getConfig();
|
||||
|
||||
serverUrl = config.apiUrl;
|
||||
token = config.accessToken ?? config.apiKey;
|
||||
}
|
||||
|
||||
const remoteName = options.remote ?? ConfigService.getActiveRemote();
|
||||
|
||||
console.log(chalk.blue(`Deploying to ${remoteName} (${serverUrl})...`));
|
||||
console.log(chalk.gray(`App path: ${appPath}`));
|
||||
console.log('');
|
||||
|
||||
const result = await appDeploy({
|
||||
appPath,
|
||||
serverUrl,
|
||||
token,
|
||||
onProgress: (message) => console.log(chalk.gray(message)),
|
||||
});
|
||||
|
||||
if (!result.success) {
|
||||
console.error(chalk.red(result.error.message));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(chalk.green('✓ Deployed successfully'));
|
||||
}
|
||||
}
|
||||
+3
-6
@@ -1,8 +1,5 @@
|
||||
import { functionExecute } from '@/cli/public-operations/function-execute';
|
||||
import {
|
||||
APP_ERROR_CODES,
|
||||
FUNCTION_ERROR_CODES,
|
||||
} from '@/cli/public-operations/types';
|
||||
import { functionExecute } from '@/cli/operations/execute';
|
||||
import { APP_ERROR_CODES, FUNCTION_ERROR_CODES } from '@/cli/types';
|
||||
import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/current-execution-directory';
|
||||
import chalk from 'chalk';
|
||||
import { isDefined } from 'twenty-shared/utils';
|
||||
@@ -80,7 +77,7 @@ export class LogicFunctionExecuteCommand {
|
||||
} else {
|
||||
console.log(
|
||||
chalk.yellow(
|
||||
'No functions found for this application. Have you synced your app with `yarn app:dev`?',
|
||||
'No functions found for this application. Have you synced your app with `twenty dev`?',
|
||||
),
|
||||
);
|
||||
}
|
||||
+3
-21
@@ -1,12 +1,10 @@
|
||||
import { appPublish } from '@/cli/public-operations/app-publish';
|
||||
import { appPublish } from '@/cli/operations/publish';
|
||||
import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/current-execution-directory';
|
||||
import { checkSdkVersionCompatibility } from '@/cli/utilities/version/check-sdk-version-compatibility';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export type AppPublishCommandOptions = {
|
||||
appPath?: string;
|
||||
server?: string;
|
||||
token?: string;
|
||||
tag?: string;
|
||||
};
|
||||
|
||||
@@ -16,22 +14,12 @@ export class AppPublishCommand {
|
||||
|
||||
await checkSdkVersionCompatibility(appPath);
|
||||
|
||||
const isServerPublish = !!options.server;
|
||||
|
||||
console.log(
|
||||
chalk.blue(
|
||||
isServerPublish
|
||||
? `Publishing to server ${options.server}...`
|
||||
: 'Publishing to npm...',
|
||||
),
|
||||
);
|
||||
console.log(chalk.blue('Publishing to npm...'));
|
||||
console.log(chalk.gray(`App path: ${appPath}`));
|
||||
console.log('');
|
||||
|
||||
const result = await appPublish({
|
||||
appPath,
|
||||
server: options.server,
|
||||
token: options.token,
|
||||
npmTag: options.tag,
|
||||
onProgress: (message) => console.log(chalk.gray(message)),
|
||||
});
|
||||
@@ -41,12 +29,6 @@ export class AppPublishCommand {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (result.data.target === 'npm') {
|
||||
console.log(chalk.green('✓ Published to npm successfully'));
|
||||
} else {
|
||||
console.log(
|
||||
chalk.green('✓ Published to server and installed successfully'),
|
||||
);
|
||||
}
|
||||
console.log(chalk.green('✓ Published to npm successfully'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import { authLogin } from '@/cli/operations/login';
|
||||
import { authLoginOAuth } from '@/cli/operations/login-oauth';
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import chalk from 'chalk';
|
||||
import type { Command } from 'commander';
|
||||
import inquirer from 'inquirer';
|
||||
|
||||
const deriveRemoteName = (url: string): string => {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
|
||||
return hostname.replace(/\./g, '-');
|
||||
} catch {
|
||||
return 'remote';
|
||||
}
|
||||
};
|
||||
|
||||
const authenticate = async (apiUrl: string, token?: string): Promise<void> => {
|
||||
const result = token
|
||||
? await authLogin({ apiKey: token, apiUrl })
|
||||
: await runOAuthWithApiKeyFallback(apiUrl);
|
||||
|
||||
if (!result.success) {
|
||||
console.error(chalk.red('✗ Authentication failed.'));
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
const runOAuthWithApiKeyFallback = async (
|
||||
apiUrl: string,
|
||||
): Promise<{ success: boolean }> => {
|
||||
await inquirer.prompt([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'confirm',
|
||||
message: 'Press Enter to open the browser for authentication...',
|
||||
},
|
||||
]);
|
||||
|
||||
const oauthResult = await authLoginOAuth({ apiUrl });
|
||||
|
||||
if (oauthResult.success) {
|
||||
return oauthResult;
|
||||
}
|
||||
|
||||
console.log(chalk.yellow(oauthResult.error.message));
|
||||
|
||||
const keyAnswer = await inquirer.prompt([
|
||||
{
|
||||
type: 'password',
|
||||
name: 'apiKey',
|
||||
message: 'API Key:',
|
||||
mask: '*',
|
||||
validate: (input: string) => input.length > 0 || 'API key is required',
|
||||
},
|
||||
]);
|
||||
|
||||
return authLogin({ apiKey: keyAnswer.apiKey, apiUrl });
|
||||
};
|
||||
|
||||
export const registerRemoteCommands = (program: Command): void => {
|
||||
const remote = program
|
||||
.command('remote')
|
||||
.description('Manage remote Twenty servers');
|
||||
|
||||
remote
|
||||
.command('add [nameOrUrl]')
|
||||
.description('Add a new remote or re-authenticate an existing one')
|
||||
.option('--as <name>', 'Name for this remote')
|
||||
.option('--local', 'Connect to local development server')
|
||||
.option('--token <token>', 'API key for non-interactive auth')
|
||||
.option('--url <url>', 'Server URL (alternative to positional arg)')
|
||||
.action(
|
||||
async (
|
||||
nameOrUrl: string | undefined,
|
||||
options: {
|
||||
as?: string;
|
||||
local?: boolean;
|
||||
token?: string;
|
||||
url?: string;
|
||||
},
|
||||
) => {
|
||||
const configService = new ConfigService();
|
||||
const existingRemotes = await configService.getRemotes();
|
||||
|
||||
if (options.local) {
|
||||
const remoteName = options.as ?? 'local';
|
||||
const token =
|
||||
options.token ??
|
||||
(
|
||||
await inquirer.prompt<{ apiKey: string }>([
|
||||
{
|
||||
type: 'password',
|
||||
name: 'apiKey',
|
||||
message: 'API Key for local server:',
|
||||
mask: '*',
|
||||
validate: (input: string) =>
|
||||
input.length > 0 || 'API key is required',
|
||||
},
|
||||
])
|
||||
).apiKey;
|
||||
|
||||
ConfigService.setActiveRemote(remoteName);
|
||||
await authenticate('http://localhost:3000', token);
|
||||
console.log(chalk.green(`✓ Authenticated remote "${remoteName}".`));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Re-authenticate an existing remote by name
|
||||
const isExistingRemote =
|
||||
nameOrUrl !== undefined && existingRemotes.includes(nameOrUrl);
|
||||
|
||||
if (isExistingRemote) {
|
||||
const config = await configService.getConfigForRemote(nameOrUrl);
|
||||
|
||||
ConfigService.setActiveRemote(nameOrUrl);
|
||||
await authenticate(config.apiUrl, options.token);
|
||||
console.log(chalk.green(`✓ Re-authenticated remote "${nameOrUrl}".`));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Resolve the URL — from args, flags, or interactive prompt
|
||||
const apiUrl =
|
||||
nameOrUrl ??
|
||||
options.url ??
|
||||
(options.token
|
||||
? 'http://localhost:3000'
|
||||
: (
|
||||
await inquirer.prompt<{ apiUrl: string }>([
|
||||
{
|
||||
type: 'input',
|
||||
name: 'apiUrl',
|
||||
message: 'Twenty server URL:',
|
||||
validate: (input: string) => {
|
||||
try {
|
||||
new URL(input);
|
||||
|
||||
return true;
|
||||
} catch {
|
||||
return 'Please enter a valid URL';
|
||||
}
|
||||
},
|
||||
},
|
||||
])
|
||||
).apiUrl);
|
||||
|
||||
const name = options.as ?? deriveRemoteName(apiUrl);
|
||||
|
||||
ConfigService.setActiveRemote(name);
|
||||
await authenticate(apiUrl, options.token);
|
||||
|
||||
const defaultRemote = await configService.getDefaultRemote();
|
||||
|
||||
if (defaultRemote === 'local') {
|
||||
await configService.setDefaultRemote(name);
|
||||
}
|
||||
|
||||
console.log(chalk.green(`✓ Authenticated remote "${name}".`));
|
||||
},
|
||||
);
|
||||
|
||||
remote
|
||||
.command('list')
|
||||
.description('List all configured remotes')
|
||||
.action(async () => {
|
||||
const configService = new ConfigService();
|
||||
const remotes = await configService.getRemotes();
|
||||
const defaultRemote = await configService.getDefaultRemote();
|
||||
|
||||
if (remotes.length === 0) {
|
||||
console.log('No remotes configured.');
|
||||
console.log("Use 'twenty remote add <url>' to add one.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('');
|
||||
|
||||
for (const remoteName of remotes) {
|
||||
const config = await configService.getConfigForRemote(remoteName);
|
||||
|
||||
const authMethod = config.accessToken
|
||||
? 'oauth'
|
||||
: config.apiKey
|
||||
? 'api-key'
|
||||
: 'none';
|
||||
|
||||
const isDefault = remoteName === defaultRemote;
|
||||
const marker = isDefault ? '* ' : ' ';
|
||||
const nameText = isDefault ? chalk.bold(remoteName) : remoteName;
|
||||
|
||||
console.log(
|
||||
`${marker}${nameText} ${chalk.gray(config.apiUrl)} [${authMethod}]`,
|
||||
);
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log(
|
||||
chalk.gray("Use 'twenty remote switch <name>' to change default"),
|
||||
);
|
||||
});
|
||||
|
||||
remote
|
||||
.command('switch [name]')
|
||||
.description('Set the default remote')
|
||||
.action(async (nameArg?: string) => {
|
||||
const configService = new ConfigService();
|
||||
|
||||
const remoteName =
|
||||
nameArg ??
|
||||
(
|
||||
await inquirer.prompt<{ remote: string }>([
|
||||
{
|
||||
type: 'list',
|
||||
name: 'remote',
|
||||
message: 'Select default remote:',
|
||||
choices: await configService.getRemotes(),
|
||||
},
|
||||
])
|
||||
).remote;
|
||||
|
||||
const remotes = await configService.getRemotes();
|
||||
|
||||
if (!remotes.includes(remoteName)) {
|
||||
console.error(chalk.red(`Remote "${remoteName}" not found.`));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
await configService.setDefaultRemote(remoteName);
|
||||
console.log(chalk.green(`✓ Default remote set to "${remoteName}".`));
|
||||
});
|
||||
|
||||
remote
|
||||
.command('status')
|
||||
.description('Show active remote and authentication status')
|
||||
.action(async () => {
|
||||
const configService = new ConfigService();
|
||||
const apiService = new ApiService();
|
||||
const activeRemote = ConfigService.getActiveRemote();
|
||||
const config = await configService.getConfig();
|
||||
|
||||
const authMethod = config.accessToken
|
||||
? 'oauth'
|
||||
: config.apiKey
|
||||
? 'api-key'
|
||||
: 'none';
|
||||
|
||||
console.log(` Remote: ${chalk.bold(activeRemote)}`);
|
||||
console.log(` Server: ${config.apiUrl}`);
|
||||
|
||||
if (authMethod === 'none') {
|
||||
console.log(` Auth: ${chalk.yellow('not configured')}`);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const { authValid } = await apiService.validateAuth();
|
||||
|
||||
const statusText = authValid
|
||||
? chalk.green(`${authMethod} (valid)`)
|
||||
: chalk.red(`${authMethod} (invalid)`);
|
||||
|
||||
console.log(` Auth: ${statusText}`);
|
||||
});
|
||||
|
||||
remote
|
||||
.command('remove <name>')
|
||||
.description('Remove a remote')
|
||||
.action(async (name: string) => {
|
||||
const configService = new ConfigService();
|
||||
const remotes = await configService.getRemotes();
|
||||
|
||||
if (!remotes.includes(name)) {
|
||||
console.error(chalk.red(`Remote "${name}" not found.`));
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
ConfigService.setActiveRemote(name);
|
||||
await configService.clearConfig();
|
||||
|
||||
console.log(chalk.green(`✓ Remote "${name}" removed.`));
|
||||
});
|
||||
};
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { appUninstall } from '@/cli/public-operations/app-uninstall';
|
||||
import { appUninstall } from '@/cli/operations/uninstall';
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import { CURRENT_EXECUTION_DIRECTORY } from '@/cli/utilities/config/current-execution-directory';
|
||||
import chalk from 'chalk';
|
||||
+1
-1
@@ -7,7 +7,7 @@ import { runTypecheck } from '@/cli/utilities/build/common/typecheck-plugin';
|
||||
import { buildAndValidateManifest } from '@/cli/utilities/build/manifest/build-and-validate-manifest';
|
||||
import { ClientService } from '@/cli/utilities/client/client-service';
|
||||
import { runSafe } from '@/cli/utilities/run-safe';
|
||||
import { APP_ERROR_CODES, type CommandResult } from './types';
|
||||
import { APP_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
|
||||
export type AppBuildOptions = {
|
||||
appPath: string;
|
||||
@@ -0,0 +1,82 @@
|
||||
import fs from 'fs';
|
||||
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { runSafe } from '@/cli/utilities/run-safe';
|
||||
import { appBuild } from './build';
|
||||
import { APP_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
|
||||
export type AppDeployOptions = {
|
||||
appPath: string;
|
||||
serverUrl: string;
|
||||
token?: string;
|
||||
onProgress?: (message: string) => void;
|
||||
};
|
||||
|
||||
export type AppDeployResult = {
|
||||
universalIdentifier: string;
|
||||
};
|
||||
|
||||
const innerAppDeploy = async (
|
||||
options: AppDeployOptions,
|
||||
): Promise<CommandResult<AppDeployResult>> => {
|
||||
const { appPath, serverUrl, token, onProgress } = options;
|
||||
|
||||
const buildResult = await appBuild({
|
||||
appPath,
|
||||
tarball: true,
|
||||
onProgress,
|
||||
});
|
||||
|
||||
if (!buildResult.success) {
|
||||
return buildResult;
|
||||
}
|
||||
|
||||
onProgress?.(`Uploading ${buildResult.data.tarballPath}...`);
|
||||
|
||||
const tarballBuffer = fs.readFileSync(buildResult.data.tarballPath!);
|
||||
|
||||
const apiService = new ApiService({
|
||||
serverUrl,
|
||||
token,
|
||||
});
|
||||
|
||||
const uploadResult = await apiService.uploadAppTarball({ tarballBuffer });
|
||||
|
||||
if (!uploadResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: APP_ERROR_CODES.DEPLOY_FAILED,
|
||||
message: `Upload failed: ${uploadResult.error}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
onProgress?.('Installing application...');
|
||||
|
||||
const installResult = await apiService.installTarballApp({
|
||||
universalIdentifier: uploadResult.data.universalIdentifier,
|
||||
});
|
||||
|
||||
if (!installResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: APP_ERROR_CODES.DEPLOY_FAILED,
|
||||
message: `Install failed: ${installResult.error}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
universalIdentifier: uploadResult.data.universalIdentifier,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const appDeploy = (
|
||||
options: AppDeployOptions,
|
||||
): Promise<CommandResult<AppDeployResult>> =>
|
||||
runSafe(() => innerAppDeploy(options), APP_ERROR_CODES.DEPLOY_FAILED);
|
||||
+5
-5
@@ -8,11 +8,11 @@ import {
|
||||
FUNCTION_ERROR_CODES,
|
||||
type CommandResult,
|
||||
type FunctionExecutionResult,
|
||||
} from './types';
|
||||
} from '@/cli/types';
|
||||
|
||||
export type FunctionExecuteOptions = {
|
||||
appPath: string;
|
||||
workspace?: string;
|
||||
remote?: string;
|
||||
payload?: Record<string, unknown>;
|
||||
} & (
|
||||
| { postInstall: true }
|
||||
@@ -49,8 +49,8 @@ const resolveIdentifier = (options: FunctionExecuteOptions): string => {
|
||||
const innerFunctionExecute = async (
|
||||
options: FunctionExecuteOptions,
|
||||
): Promise<CommandResult<FunctionExecutionResult>> => {
|
||||
if (options.workspace) {
|
||||
ConfigService.setActiveWorkspace(options.workspace);
|
||||
if (options.remote) {
|
||||
ConfigService.setActiveRemote(options.remote);
|
||||
}
|
||||
|
||||
const apiService = new ApiService();
|
||||
@@ -61,7 +61,7 @@ const innerFunctionExecute = async (
|
||||
success: false,
|
||||
error: {
|
||||
code: APP_ERROR_CODES.MANIFEST_NOT_FOUND,
|
||||
message: 'Manifest not found. Run `app:build` or `app:dev` first.',
|
||||
message: 'Manifest not found. Run `build` or `dev` first.',
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Auth
|
||||
export { authLogin } from './login';
|
||||
export type { AuthLoginOptions } from './login';
|
||||
export { authLoginOAuth } from './login-oauth';
|
||||
export type { AuthLoginOAuthOptions } from './login-oauth';
|
||||
export { authLogout } from './logout';
|
||||
export type { AuthLogoutOptions } from './logout';
|
||||
|
||||
// App
|
||||
export { appBuild } from './build';
|
||||
export type { AppBuildOptions, AppBuildResult } from './build';
|
||||
export { appDeploy } from './deploy';
|
||||
export type { AppDeployOptions, AppDeployResult } from './deploy';
|
||||
export { appPublish } from './publish';
|
||||
export type { AppPublishOptions, AppPublishResult } from './publish';
|
||||
export { appUninstall } from './uninstall';
|
||||
export type { AppUninstallOptions } from './uninstall';
|
||||
|
||||
// Functions
|
||||
export { functionExecute } from './execute';
|
||||
export type { FunctionExecuteOptions } from './execute';
|
||||
|
||||
// Shared types and error codes
|
||||
export {
|
||||
APP_ERROR_CODES,
|
||||
AUTH_ERROR_CODES,
|
||||
FUNCTION_ERROR_CODES,
|
||||
} from '@/cli/types';
|
||||
export type {
|
||||
AuthListRemote,
|
||||
AuthStatusResult,
|
||||
CommandError,
|
||||
CommandResult,
|
||||
FunctionExecutionResult,
|
||||
TypecheckResult,
|
||||
} from '@/cli/types';
|
||||
@@ -0,0 +1,143 @@
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { startCallbackServer } from '@/cli/utilities/auth/callback-server';
|
||||
import { openBrowser } from '@/cli/utilities/auth/open-browser';
|
||||
import { generatePkceChallenge } from '@/cli/utilities/auth/pkce';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import { runSafe } from '@/cli/utilities/run-safe';
|
||||
import axios from 'axios';
|
||||
|
||||
import { AUTH_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
|
||||
export type AuthLoginOAuthOptions = {
|
||||
apiUrl: string;
|
||||
remote?: string;
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
export type OAuthDiscoveryResponse = {
|
||||
authorization_endpoint: string;
|
||||
token_endpoint: string;
|
||||
cli_client_id?: string;
|
||||
};
|
||||
|
||||
const innerAuthLoginOAuth = async (
|
||||
options: AuthLoginOAuthOptions,
|
||||
): Promise<CommandResult> => {
|
||||
const { apiUrl, remote, timeoutMs } = options;
|
||||
|
||||
if (remote) {
|
||||
ConfigService.setActiveRemote(remote);
|
||||
}
|
||||
|
||||
const configService = new ConfigService();
|
||||
|
||||
const discoveryUrl = `${apiUrl}/.well-known/oauth-authorization-server`;
|
||||
|
||||
let discovery: OAuthDiscoveryResponse;
|
||||
|
||||
try {
|
||||
const response = await axios.get(discoveryUrl);
|
||||
|
||||
discovery = response.data;
|
||||
} catch {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: AUTH_ERROR_CODES.OAUTH_NOT_SUPPORTED,
|
||||
message: `Could not reach the OAuth discovery endpoint at ${discoveryUrl}. Ensure the server is running. Use --api-key instead.`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (!discovery.cli_client_id) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: AUTH_ERROR_CODES.OAUTH_NOT_SUPPORTED,
|
||||
message:
|
||||
'Server does not expose a CLI client ID. Ensure the server is up to date. Use --api-key instead.',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const clientId = discovery.cli_client_id;
|
||||
|
||||
const { codeVerifier, codeChallenge } = generatePkceChallenge();
|
||||
|
||||
const callbackServer = await startCallbackServer({ timeoutMs });
|
||||
|
||||
try {
|
||||
const authUrl = new URL(discovery.authorization_endpoint);
|
||||
|
||||
authUrl.searchParams.set('clientId', clientId);
|
||||
authUrl.searchParams.set('codeChallenge', codeChallenge);
|
||||
authUrl.searchParams.set('redirectUrl', callbackServer.callbackUrl);
|
||||
|
||||
const browserOpened = await openBrowser(authUrl.toString());
|
||||
|
||||
if (!browserOpened) {
|
||||
console.log(
|
||||
`\nOpen this URL in your browser to authenticate:\n${authUrl.toString()}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
const callbackResult = await callbackServer.waitForCallback();
|
||||
|
||||
if (!callbackResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: AUTH_ERROR_CODES.AUTH_FAILED,
|
||||
message: callbackResult.error,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const tokenResponse = await axios.post(discovery.token_endpoint, {
|
||||
grant_type: 'authorization_code',
|
||||
code: callbackResult.code,
|
||||
code_verifier: codeVerifier,
|
||||
redirect_uri: callbackServer.callbackUrl,
|
||||
client_id: clientId,
|
||||
});
|
||||
|
||||
const { access_token: accessToken, refresh_token: refreshToken } =
|
||||
tokenResponse.data;
|
||||
|
||||
await configService.setConfig({
|
||||
apiUrl,
|
||||
accessToken,
|
||||
refreshToken,
|
||||
oauthClientId: clientId,
|
||||
});
|
||||
|
||||
const apiService = new ApiService({
|
||||
serverUrl: apiUrl,
|
||||
token: accessToken,
|
||||
});
|
||||
|
||||
const validateAuth = await apiService.validateAuth();
|
||||
|
||||
if (!validateAuth.authValid) {
|
||||
await configService.clearConfig();
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: AUTH_ERROR_CODES.AUTH_FAILED,
|
||||
message:
|
||||
'OAuth tokens received but authentication validation failed.',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, data: undefined };
|
||||
} finally {
|
||||
callbackServer.close();
|
||||
}
|
||||
};
|
||||
|
||||
export const authLoginOAuth = (
|
||||
options: AuthLoginOAuthOptions,
|
||||
): Promise<CommandResult> =>
|
||||
runSafe(() => innerAuthLoginOAuth(options), AUTH_ERROR_CODES.AUTH_FAILED);
|
||||
+12
-6
@@ -1,26 +1,32 @@
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import { runSafe } from '@/cli/utilities/run-safe';
|
||||
import { AUTH_ERROR_CODES, type CommandResult } from './types';
|
||||
import { AUTH_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
|
||||
export type AuthLoginOptions = {
|
||||
apiKey: string;
|
||||
apiUrl: string;
|
||||
workspace?: string;
|
||||
remote?: string;
|
||||
};
|
||||
|
||||
const innerAuthLogin = async (
|
||||
options: AuthLoginOptions,
|
||||
): Promise<CommandResult> => {
|
||||
const { apiKey, apiUrl, workspace } = options;
|
||||
const { apiKey, apiUrl, remote } = options;
|
||||
|
||||
if (workspace) {
|
||||
ConfigService.setActiveWorkspace(workspace);
|
||||
if (remote) {
|
||||
ConfigService.setActiveRemote(remote);
|
||||
}
|
||||
|
||||
const configService = new ConfigService();
|
||||
|
||||
await configService.setConfig({ apiUrl, apiKey });
|
||||
await configService.setConfig({
|
||||
apiUrl,
|
||||
apiKey,
|
||||
accessToken: undefined,
|
||||
refreshToken: undefined,
|
||||
oauthClientId: undefined,
|
||||
});
|
||||
|
||||
const apiService = new ApiService();
|
||||
const validateAuth = await apiService.validateAuth();
|
||||
+4
-4
@@ -1,16 +1,16 @@
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import { runSafe } from '@/cli/utilities/run-safe';
|
||||
import { AUTH_ERROR_CODES, type CommandResult } from './types';
|
||||
import { AUTH_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
|
||||
export type AuthLogoutOptions = {
|
||||
workspace?: string;
|
||||
remote?: string;
|
||||
};
|
||||
|
||||
const innerAuthLogout = async (
|
||||
options?: AuthLogoutOptions,
|
||||
): Promise<CommandResult> => {
|
||||
if (options?.workspace) {
|
||||
ConfigService.setActiveWorkspace(options.workspace);
|
||||
if (options?.remote) {
|
||||
ConfigService.setActiveRemote(options.remote);
|
||||
}
|
||||
|
||||
const configService = new ConfigService();
|
||||
@@ -0,0 +1,57 @@
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
import { runSafe } from '@/cli/utilities/run-safe';
|
||||
import { appBuild } from './build';
|
||||
import { APP_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
|
||||
export type AppPublishOptions = {
|
||||
appPath: string;
|
||||
npmTag?: string;
|
||||
onProgress?: (message: string) => void;
|
||||
};
|
||||
|
||||
export type AppPublishResult = {
|
||||
target: 'npm';
|
||||
};
|
||||
|
||||
const innerAppPublish = async (
|
||||
options: AppPublishOptions,
|
||||
): Promise<CommandResult<AppPublishResult>> => {
|
||||
const { appPath, onProgress } = options;
|
||||
|
||||
const buildResult = await appBuild({
|
||||
appPath,
|
||||
onProgress,
|
||||
});
|
||||
|
||||
if (!buildResult.success) {
|
||||
return buildResult;
|
||||
}
|
||||
|
||||
onProgress?.('Publishing to npm...');
|
||||
|
||||
const tagArg = options.npmTag ? ` --tag ${options.npmTag}` : '';
|
||||
|
||||
try {
|
||||
execSync(`npm publish${tagArg}`, {
|
||||
cwd: buildResult.data.outputDir,
|
||||
stdio: 'inherit',
|
||||
});
|
||||
} catch {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: APP_ERROR_CODES.PUBLISH_FAILED,
|
||||
message:
|
||||
'npm publish failed. Make sure you are logged in (`npm login`) and the package name is available.',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, data: { target: 'npm' } };
|
||||
};
|
||||
|
||||
export const appPublish = (
|
||||
options: AppPublishOptions,
|
||||
): Promise<CommandResult<AppPublishResult>> =>
|
||||
runSafe(() => innerAppPublish(options), APP_ERROR_CODES.PUBLISH_FAILED);
|
||||
+5
-5
@@ -2,18 +2,18 @@ import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { readManifestFromFile } from '@/cli/utilities/build/manifest/manifest-reader';
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import { runSafe } from '@/cli/utilities/run-safe';
|
||||
import { APP_ERROR_CODES, type CommandResult } from './types';
|
||||
import { APP_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
|
||||
export type AppUninstallOptions = {
|
||||
appPath: string;
|
||||
workspace?: string;
|
||||
remote?: string;
|
||||
};
|
||||
|
||||
const innerAppUninstall = async (
|
||||
options: AppUninstallOptions,
|
||||
): Promise<CommandResult> => {
|
||||
if (options.workspace) {
|
||||
ConfigService.setActiveWorkspace(options.workspace);
|
||||
if (options.remote) {
|
||||
ConfigService.setActiveRemote(options.remote);
|
||||
}
|
||||
|
||||
const apiService = new ApiService();
|
||||
@@ -24,7 +24,7 @@ const innerAppUninstall = async (
|
||||
success: false,
|
||||
error: {
|
||||
code: APP_ERROR_CODES.MANIFEST_NOT_FOUND,
|
||||
message: 'Manifest not found. Run `app:build` or `app:dev` first.',
|
||||
message: 'Manifest not found. Run `build` or `dev` first.',
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import { execSync } from 'child_process';
|
||||
import fs from 'fs';
|
||||
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { runSafe } from '@/cli/utilities/run-safe';
|
||||
import { appBuild } from './app-build';
|
||||
import { APP_ERROR_CODES, type CommandResult } from './types';
|
||||
|
||||
export type AppPublishOptions = {
|
||||
appPath: string;
|
||||
server?: string;
|
||||
token?: string;
|
||||
npmTag?: string;
|
||||
onProgress?: (message: string) => void;
|
||||
};
|
||||
|
||||
export type AppPublishResult = {
|
||||
target: 'npm' | 'server';
|
||||
universalIdentifier?: string;
|
||||
};
|
||||
|
||||
const innerAppPublish = async (
|
||||
options: AppPublishOptions,
|
||||
): Promise<CommandResult<AppPublishResult>> => {
|
||||
const { appPath, onProgress } = options;
|
||||
const isServerPublish = !!options.server;
|
||||
|
||||
const buildResult = await appBuild({
|
||||
appPath,
|
||||
tarball: isServerPublish,
|
||||
onProgress,
|
||||
});
|
||||
|
||||
if (!buildResult.success) {
|
||||
return buildResult;
|
||||
}
|
||||
|
||||
if (isServerPublish) {
|
||||
return publishToServer({
|
||||
tarballPath: buildResult.data.tarballPath!,
|
||||
server: options.server!,
|
||||
token: options.token,
|
||||
onProgress,
|
||||
});
|
||||
}
|
||||
|
||||
return publishToNpm({
|
||||
outputDir: buildResult.data.outputDir,
|
||||
npmTag: options.npmTag,
|
||||
onProgress,
|
||||
});
|
||||
};
|
||||
|
||||
const publishToNpm = async ({
|
||||
outputDir,
|
||||
npmTag,
|
||||
onProgress,
|
||||
}: {
|
||||
outputDir: string;
|
||||
npmTag?: string;
|
||||
onProgress?: (message: string) => void;
|
||||
}): Promise<CommandResult<AppPublishResult>> => {
|
||||
onProgress?.('Publishing to npm...');
|
||||
|
||||
const tagArg = npmTag ? ` --tag ${npmTag}` : '';
|
||||
|
||||
try {
|
||||
execSync(`npm publish${tagArg}`, {
|
||||
cwd: outputDir,
|
||||
stdio: 'inherit',
|
||||
});
|
||||
} catch {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: APP_ERROR_CODES.PUBLISH_FAILED,
|
||||
message:
|
||||
'npm publish failed. Make sure you are logged in (`npm login`) and the package name is available.',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, data: { target: 'npm' } };
|
||||
};
|
||||
|
||||
const publishToServer = async ({
|
||||
tarballPath,
|
||||
server,
|
||||
token,
|
||||
onProgress,
|
||||
}: {
|
||||
tarballPath: string;
|
||||
server: string;
|
||||
token?: string;
|
||||
onProgress?: (message: string) => void;
|
||||
}): Promise<CommandResult<AppPublishResult>> => {
|
||||
onProgress?.(`Uploading ${tarballPath}...`);
|
||||
|
||||
const tarballBuffer = fs.readFileSync(tarballPath);
|
||||
|
||||
const apiService = new ApiService({
|
||||
serverUrl: server,
|
||||
token,
|
||||
});
|
||||
|
||||
const uploadResult = await apiService.uploadAppTarball({ tarballBuffer });
|
||||
|
||||
if (!uploadResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: APP_ERROR_CODES.PUBLISH_FAILED,
|
||||
message: `Upload failed: ${uploadResult.error}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
onProgress?.('Installing application...');
|
||||
|
||||
const installResult = await apiService.installTarballApp({
|
||||
universalIdentifier: uploadResult.data.universalIdentifier,
|
||||
});
|
||||
|
||||
if (!installResult.success) {
|
||||
return {
|
||||
success: false,
|
||||
error: {
|
||||
code: APP_ERROR_CODES.PUBLISH_FAILED,
|
||||
message: `Install failed: ${installResult.error}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
target: 'server',
|
||||
universalIdentifier: uploadResult.data.universalIdentifier,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const appPublish = (
|
||||
options: AppPublishOptions,
|
||||
): Promise<CommandResult<AppPublishResult>> =>
|
||||
runSafe(() => innerAppPublish(options), APP_ERROR_CODES.PUBLISH_FAILED);
|
||||
@@ -1,32 +0,0 @@
|
||||
// Auth
|
||||
export { authLogin } from './auth-login';
|
||||
export type { AuthLoginOptions } from './auth-login';
|
||||
export { authLogout } from './auth-logout';
|
||||
export type { AuthLogoutOptions } from './auth-logout';
|
||||
|
||||
// App
|
||||
export { appBuild } from './app-build';
|
||||
export type { AppBuildOptions, AppBuildResult } from './app-build';
|
||||
export { appPublish } from './app-publish';
|
||||
export type { AppPublishOptions, AppPublishResult } from './app-publish';
|
||||
export { appUninstall } from './app-uninstall';
|
||||
export type { AppUninstallOptions } from './app-uninstall';
|
||||
|
||||
// Functions
|
||||
export { functionExecute } from './function-execute';
|
||||
export type { FunctionExecuteOptions } from './function-execute';
|
||||
|
||||
// Shared types and error codes
|
||||
export {
|
||||
APP_ERROR_CODES,
|
||||
AUTH_ERROR_CODES,
|
||||
FUNCTION_ERROR_CODES,
|
||||
} from './types';
|
||||
export type {
|
||||
AuthListWorkspace,
|
||||
AuthStatusResult,
|
||||
CommandError,
|
||||
CommandResult,
|
||||
FunctionExecutionResult,
|
||||
TypecheckResult,
|
||||
} from './types';
|
||||
+6
-4
@@ -10,8 +10,9 @@ export type CommandResult<T = void> =
|
||||
|
||||
export const AUTH_ERROR_CODES = {
|
||||
AUTH_FAILED: 'AUTH_FAILED',
|
||||
NO_WORKSPACES: 'NO_WORKSPACES',
|
||||
WORKSPACE_NOT_FOUND: 'WORKSPACE_NOT_FOUND',
|
||||
NO_REMOTES: 'NO_REMOTES',
|
||||
REMOTE_NOT_FOUND: 'REMOTE_NOT_FOUND',
|
||||
OAUTH_NOT_SUPPORTED: 'OAUTH_NOT_SUPPORTED',
|
||||
} as const;
|
||||
|
||||
export const APP_ERROR_CODES = {
|
||||
@@ -22,6 +23,7 @@ export const APP_ERROR_CODES = {
|
||||
UNINSTALL_FAILED: 'UNINSTALL_FAILED',
|
||||
SYNC_FAILED: 'SYNC_FAILED',
|
||||
TYPECHECK_FAILED: 'TYPECHECK_FAILED',
|
||||
DEPLOY_FAILED: 'DEPLOY_FAILED',
|
||||
} as const;
|
||||
|
||||
export const FUNCTION_ERROR_CODES = {
|
||||
@@ -31,14 +33,14 @@ export const FUNCTION_ERROR_CODES = {
|
||||
} as const;
|
||||
|
||||
export type AuthStatusResult = {
|
||||
workspace: string;
|
||||
remote: string;
|
||||
apiUrl: string;
|
||||
apiKeyMasked: string | null;
|
||||
isAuthenticated: boolean;
|
||||
isValid: boolean;
|
||||
};
|
||||
|
||||
export type AuthListWorkspace = {
|
||||
export type AuthListRemote = {
|
||||
name: string;
|
||||
apiUrl: string;
|
||||
hasCredentials: boolean;
|
||||
@@ -0,0 +1,177 @@
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import axios, { type AxiosInstance } from 'axios';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export class ApiClient {
|
||||
readonly client: AxiosInstance;
|
||||
readonly configService: ConfigService;
|
||||
private readonly tokenOverride?: string;
|
||||
readonly serverUrlOverride?: string;
|
||||
|
||||
constructor(options?: {
|
||||
disableInterceptors?: boolean;
|
||||
serverUrl?: string;
|
||||
token?: string;
|
||||
}) {
|
||||
const { disableInterceptors = false, serverUrl, token } = options || {};
|
||||
this.configService = new ConfigService();
|
||||
this.tokenOverride = token;
|
||||
this.serverUrlOverride = serverUrl;
|
||||
this.client = axios.create();
|
||||
|
||||
this.client.interceptors.request.use(async (config) => {
|
||||
const twentyConfig = await this.configService.getConfig();
|
||||
|
||||
config.baseURL = this.serverUrlOverride ?? twentyConfig.apiUrl;
|
||||
|
||||
if (!config.headers.Authorization) {
|
||||
const authToken = await this.resolveAuthToken();
|
||||
|
||||
if (authToken) {
|
||||
config.headers.Authorization = `Bearer ${authToken}`;
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
if (disableInterceptors) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.client.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
if (error.response?.status === 401) {
|
||||
console.error(
|
||||
chalk.red(
|
||||
'Authentication failed. Run `twenty remote add` to authenticate.',
|
||||
),
|
||||
);
|
||||
} else if (error.response?.status === 403) {
|
||||
console.error(
|
||||
chalk.red(
|
||||
'Access denied. Check your API key and workspace permissions.',
|
||||
),
|
||||
);
|
||||
} else if (error.code === 'ECONNREFUSED') {
|
||||
console.error(
|
||||
chalk.red('Cannot connect to Twenty server. Is it running?'),
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async validateAuth(): Promise<{ authValid: boolean; serverUp: boolean }> {
|
||||
try {
|
||||
const query = `
|
||||
query CurrentWorkspace {
|
||||
currentWorkspace {
|
||||
id
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
authValid: response.status === 200 && !response.data.errors,
|
||||
serverUp: response.status === 200,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
authValid: false,
|
||||
serverUp: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
authValid: false,
|
||||
serverUp: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async refreshToken(): Promise<string | null> {
|
||||
const config = await this.configService.getConfig();
|
||||
|
||||
if (!config.refreshToken || !config.oauthClientId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const tokenResponse = await axios.post(`${config.apiUrl}/oauth/token`, {
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: config.refreshToken,
|
||||
client_id: config.oauthClientId,
|
||||
});
|
||||
|
||||
const { access_token: newAccessToken, refresh_token: newRefreshToken } =
|
||||
tokenResponse.data;
|
||||
|
||||
await this.configService.setConfig({
|
||||
accessToken: newAccessToken,
|
||||
...(newRefreshToken ? { refreshToken: newRefreshToken } : {}),
|
||||
});
|
||||
|
||||
return newAccessToken;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async resolveAuthToken(): Promise<string | undefined> {
|
||||
if (this.tokenOverride) {
|
||||
return this.tokenOverride;
|
||||
}
|
||||
|
||||
const envToken = process.env.TWENTY_TOKEN;
|
||||
|
||||
if (envToken) {
|
||||
return envToken;
|
||||
}
|
||||
|
||||
const config = await this.configService.getConfig();
|
||||
const accessToken = config.accessToken;
|
||||
|
||||
if (accessToken && this.isTokenExpired(accessToken)) {
|
||||
const refreshed = await this.refreshToken();
|
||||
|
||||
if (refreshed) {
|
||||
return refreshed;
|
||||
}
|
||||
}
|
||||
|
||||
return accessToken ?? config.apiKey;
|
||||
}
|
||||
|
||||
private isTokenExpired(token: string): boolean {
|
||||
try {
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(token.split('.')[1], 'base64').toString(),
|
||||
);
|
||||
|
||||
const EXPIRATION_MARGIN_IN_SECONDS = 30;
|
||||
|
||||
return (
|
||||
payload.exp * 1_000 < Date.now() + EXPIRATION_MARGIN_IN_SECONDS * 1_000
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,286 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
|
||||
import { type Manifest } from 'twenty-shared/application';
|
||||
|
||||
export class ApplicationApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
async findApplicationRegistrationByUniversalIdentifier(
|
||||
universalIdentifier: string,
|
||||
): Promise<
|
||||
ApiResponse<{
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
oAuthClientId: string;
|
||||
} | null>
|
||||
> {
|
||||
try {
|
||||
const query = `
|
||||
query FindApplicationRegistrationByUniversalIdentifier($universalIdentifier: String!) {
|
||||
findApplicationRegistrationByUniversalIdentifier(universalIdentifier: $universalIdentifier) {
|
||||
id
|
||||
universalIdentifier
|
||||
name
|
||||
oAuthClientId
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query,
|
||||
variables: { universalIdentifier },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data
|
||||
.findApplicationRegistrationByUniversalIdentifier,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async createApplicationRegistration(input: {
|
||||
name: string;
|
||||
description?: string;
|
||||
universalIdentifier: string;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
applicationRegistration: {
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
oAuthClientId: string;
|
||||
};
|
||||
clientSecret: string;
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation CreateApplicationRegistration($input: CreateApplicationRegistrationInput!) {
|
||||
createApplicationRegistration(input: $input) {
|
||||
applicationRegistration {
|
||||
id
|
||||
universalIdentifier
|
||||
oAuthClientId
|
||||
}
|
||||
clientSecret
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: { input },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.createApplicationRegistration,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async createDevelopmentApplication(input: {
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
}): Promise<ApiResponse<{ id: string; universalIdentifier: string }>> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation CreateDevelopmentApplication($universalIdentifier: String!, $name: String!) {
|
||||
createDevelopmentApplication(universalIdentifier: $universalIdentifier, name: $name) {
|
||||
id
|
||||
universalIdentifier
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: input,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.createDevelopmentApplication,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async syncApplication(manifest: Manifest): Promise<ApiResponse> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation SyncApplication($manifest: JSON!) {
|
||||
syncApplication(manifest: $manifest) {
|
||||
applicationUniversalIdentifier
|
||||
actions
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = { manifest };
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.syncApplication,
|
||||
message: `Successfully synced application: ${manifest.application.displayName}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
const graphqlErrors = error.response.data?.errors;
|
||||
|
||||
if (Array.isArray(graphqlErrors) && graphqlErrors.length > 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: graphqlErrors[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error.response.data?.message ||
|
||||
`HTTP ${error.response.status}: ${error.message}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async uninstallApplication(
|
||||
universalIdentifier: string,
|
||||
): Promise<ApiResponse> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation UninstallApplication($universalIdentifier: String!) {
|
||||
uninstallApplication(universalIdentifier: $universalIdentifier)
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = { universalIdentifier };
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to delete application',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uninstallApplication,
|
||||
message: 'Successfully uninstalled application',
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { type FileFolder } from 'twenty-shared/types';
|
||||
import { pascalCase } from 'twenty-shared/utils';
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.png': 'image/png',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.bmp': 'image/bmp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.pdf': 'application/pdf',
|
||||
'.doc': 'application/msword',
|
||||
'.docx':
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'.xls': 'application/vnd.ms-excel',
|
||||
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'.ppt': 'application/vnd.ms-powerpoint',
|
||||
'.pptx':
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'.txt': 'text/plain',
|
||||
'.csv': 'text/csv',
|
||||
'.json': 'application/json',
|
||||
'.xml': 'application/xml',
|
||||
'.zip': 'application/zip',
|
||||
'.tar': 'application/x-tar',
|
||||
'.gz': 'application/gzip',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.mp4': 'video/mp4',
|
||||
'.avi': 'video/x-msvideo',
|
||||
'.mov': 'video/quicktime',
|
||||
'.js': 'application/javascript',
|
||||
'.ts': 'application/typescript',
|
||||
'.jsx': 'application/javascript',
|
||||
'.tsx': 'application/typescript',
|
||||
'.html': 'text/html',
|
||||
'.css': 'text/css',
|
||||
};
|
||||
|
||||
const getMimeType = (filename: string): string => {
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
|
||||
return MIME_TYPES[ext] || 'application/octet-stream';
|
||||
};
|
||||
|
||||
export class FileApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
// TODO: Migrate to MetadataClient once available
|
||||
// (see https://github.com/twentyhq/core-team-issues/issues/2289)
|
||||
async uploadAppTarball({
|
||||
tarballBuffer,
|
||||
universalIdentifier,
|
||||
}: {
|
||||
tarballBuffer: Buffer;
|
||||
universalIdentifier?: string;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation UploadAppTarball($file: Upload!, $universalIdentifier: String) {
|
||||
uploadAppTarball(file: $file, universalIdentifier: $universalIdentifier) {
|
||||
id
|
||||
universalIdentifier
|
||||
name
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const operations = JSON.stringify({
|
||||
query: mutation,
|
||||
variables: {
|
||||
file: null,
|
||||
universalIdentifier: universalIdentifier ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
const map = JSON.stringify({
|
||||
'0': ['variables.file'],
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('operations', operations);
|
||||
formData.append('map', map);
|
||||
formData.append(
|
||||
'0',
|
||||
new Blob([new Uint8Array(tarballBuffer)], {
|
||||
type: 'application/gzip',
|
||||
}),
|
||||
'app.tar.gz',
|
||||
);
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
formData,
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0]?.message || 'Failed to upload tarball',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uploadAppTarball,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async installTarballApp({
|
||||
universalIdentifier,
|
||||
}: {
|
||||
universalIdentifier: string;
|
||||
}): Promise<ApiResponse<boolean>> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation InstallMarketplaceApp($universalIdentifier: String!) {
|
||||
installMarketplaceApp(universalIdentifier: $universalIdentifier)
|
||||
}
|
||||
`;
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: { universalIdentifier },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to install application',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.installMarketplaceApp,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async uploadFile({
|
||||
filePath,
|
||||
builtHandlerPath,
|
||||
fileFolder,
|
||||
applicationUniversalIdentifier,
|
||||
}: {
|
||||
filePath: string;
|
||||
builtHandlerPath: string;
|
||||
fileFolder: FileFolder;
|
||||
applicationUniversalIdentifier: string;
|
||||
}): Promise<ApiResponse<boolean>> {
|
||||
try {
|
||||
const absolutePath = path.resolve(filePath);
|
||||
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
return {
|
||||
success: false,
|
||||
error: `File not found: ${absolutePath}`,
|
||||
};
|
||||
}
|
||||
|
||||
const filename = path.basename(absolutePath);
|
||||
const buffer = fs.readFileSync(absolutePath);
|
||||
const mimeType = getMimeType(filename);
|
||||
|
||||
const mutation = `
|
||||
mutation UploadApplicationFile($file: Upload!, $applicationUniversalIdentifier: String!, $fileFolder: FileFolder!, $filePath: String!) {
|
||||
uploadApplicationFile(file: $file, applicationUniversalIdentifier: $applicationUniversalIdentifier, fileFolder: $fileFolder, filePath: $filePath)
|
||||
{ path }
|
||||
}
|
||||
`;
|
||||
|
||||
const graphqlEnumFileFolder = pascalCase(fileFolder);
|
||||
|
||||
const operations = JSON.stringify({
|
||||
query: mutation,
|
||||
variables: {
|
||||
file: null,
|
||||
applicationUniversalIdentifier,
|
||||
filePath: builtHandlerPath,
|
||||
fileFolder: graphqlEnumFileFolder,
|
||||
},
|
||||
});
|
||||
|
||||
const map = JSON.stringify({
|
||||
'0': ['variables.file'],
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('operations', operations);
|
||||
formData.append('map', map);
|
||||
formData.append(
|
||||
'0',
|
||||
new Blob([new Uint8Array(buffer)], { type: mimeType }),
|
||||
filename,
|
||||
);
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
formData,
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0]?.message || 'Failed to upload file',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uploadApplicationFile,
|
||||
message: `Successfully uploaded ${filename}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { type ApiClient } from '@/cli/utilities/api/api-client';
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import { createClient } from 'graphql-sse';
|
||||
|
||||
export class LogicFunctionApi {
|
||||
constructor(private readonly apiClient: ApiClient) {}
|
||||
|
||||
async findLogicFunctions(): Promise<
|
||||
ApiResponse<
|
||||
Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
universalIdentifier: string;
|
||||
applicationId: string | null;
|
||||
}>
|
||||
>
|
||||
> {
|
||||
try {
|
||||
const query = `
|
||||
query FindManyLogicFunctions {
|
||||
findManyLogicFunctions {
|
||||
id
|
||||
name
|
||||
universalIdentifier
|
||||
applicationId
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.apiClient.client.post(
|
||||
'/metadata',
|
||||
{ query },
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to fetch functions',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.findManyLogicFunctions,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async executeLogicFunction({
|
||||
functionId,
|
||||
payload,
|
||||
}: {
|
||||
functionId: string;
|
||||
payload: Record<string, unknown>;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
data: unknown;
|
||||
logs: string;
|
||||
duration: number;
|
||||
status: string;
|
||||
error?: {
|
||||
errorType: string;
|
||||
errorMessage: string;
|
||||
stackTrace: string;
|
||||
};
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation ExecuteOneLogicFunction($input: ExecuteOneLogicFunctionInput!) {
|
||||
executeOneLogicFunction(input: $input) {
|
||||
data
|
||||
logs
|
||||
duration
|
||||
status
|
||||
error
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = {
|
||||
input: {
|
||||
id: functionId,
|
||||
payload,
|
||||
},
|
||||
};
|
||||
|
||||
const response = await this.apiClient.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message ||
|
||||
'Failed to execute logic function',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.executeOneLogicFunction,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async subscribeToLogs({
|
||||
applicationUniversalIdentifier,
|
||||
functionUniversalIdentifier,
|
||||
functionName,
|
||||
}: {
|
||||
applicationUniversalIdentifier: string;
|
||||
functionUniversalIdentifier?: string;
|
||||
functionName?: string;
|
||||
}) {
|
||||
const twentyConfig = await this.apiClient.configService.getConfig();
|
||||
const baseUrl = this.apiClient.serverUrlOverride ?? twentyConfig.apiUrl;
|
||||
|
||||
const wsClient = createClient({
|
||||
url: baseUrl + '/metadata',
|
||||
headers: async () => {
|
||||
const authToken = await this.apiClient.resolveAuthToken();
|
||||
|
||||
return {
|
||||
Authorization: authToken ? `Bearer ${authToken}` : '',
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'text/event-stream',
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const query = `
|
||||
subscription SubscribeToLogs($input: LogicFunctionLogsInput!) {
|
||||
logicFunctionLogs(input: $input) {
|
||||
logs
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = {
|
||||
input: {
|
||||
applicationUniversalIdentifier,
|
||||
universalIdentifier: functionUniversalIdentifier,
|
||||
name: functionName,
|
||||
},
|
||||
};
|
||||
|
||||
wsClient.subscribe<{ logicFunctionLogs: { logs: string } }>(
|
||||
{
|
||||
query,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
next: ({ data }) => console.log(data?.logicFunctionLogs.logs),
|
||||
error: (err: unknown) => console.error(err),
|
||||
complete: () => console.log('Completed'),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance } from 'axios';
|
||||
import { buildClientSchema, getIntrospectionQuery, printSchema } from 'graphql';
|
||||
|
||||
export class SchemaApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
async getSchema(options?: {
|
||||
authToken?: string;
|
||||
}): Promise<ApiResponse<string>> {
|
||||
return this.introspectEndpoint('/graphql', options);
|
||||
}
|
||||
|
||||
async getMetadataSchema(options?: {
|
||||
authToken?: string;
|
||||
}): Promise<ApiResponse<string>> {
|
||||
return this.introspectEndpoint('/metadata', options);
|
||||
}
|
||||
|
||||
private async introspectEndpoint(
|
||||
endpoint: string,
|
||||
options?: { authToken?: string },
|
||||
): Promise<ApiResponse<string>> {
|
||||
try {
|
||||
const introspectionQuery = getIntrospectionQuery();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
};
|
||||
|
||||
if (options?.authToken) {
|
||||
headers.Authorization = `Bearer ${options.authToken}`;
|
||||
}
|
||||
|
||||
const response = await this.client.post(
|
||||
endpoint,
|
||||
{
|
||||
query: introspectionQuery,
|
||||
},
|
||||
{ headers },
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: `GraphQL introspection errors: ${JSON.stringify(response.data.errors)}`,
|
||||
};
|
||||
}
|
||||
|
||||
const schema = buildClientSchema(response.data.data);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: printSchema(schema),
|
||||
message: `Successfully loaded schema from ${endpoint}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error.response.data?.errors?.[0]?.message ||
|
||||
`Failed to load schema from ${endpoint}`,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import http from 'node:http';
|
||||
|
||||
import { startCallbackServer } from '../callback-server';
|
||||
|
||||
const httpGet = (url: string): Promise<{ status: number; body: string }> =>
|
||||
new Promise((resolve, reject) => {
|
||||
http
|
||||
.get(url, (res) => {
|
||||
let body = '';
|
||||
|
||||
res.on('data', (chunk: string) => (body += chunk));
|
||||
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }));
|
||||
})
|
||||
.on('error', reject);
|
||||
});
|
||||
|
||||
describe('startCallbackServer', () => {
|
||||
it('should start on a random port and provide a callback URL', async () => {
|
||||
const server = await startCallbackServer();
|
||||
|
||||
try {
|
||||
expect(server.port).toBeGreaterThan(0);
|
||||
expect(server.callbackUrl).toBe(
|
||||
`http://127.0.0.1:${server.port}/callback`,
|
||||
);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('should resolve with the authorization code on successful callback', async () => {
|
||||
const server = await startCallbackServer();
|
||||
|
||||
try {
|
||||
const waitPromise = server.waitForCallback();
|
||||
|
||||
await httpGet(`${server.callbackUrl}?code=test-auth-code`);
|
||||
|
||||
const result = await waitPromise;
|
||||
|
||||
expect(result).toEqual({ success: true, code: 'test-auth-code' });
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('should resolve with error when callback contains an error', async () => {
|
||||
const server = await startCallbackServer();
|
||||
|
||||
try {
|
||||
const waitPromise = server.waitForCallback();
|
||||
|
||||
await httpGet(`${server.callbackUrl}?error=access_denied`);
|
||||
|
||||
const result = await waitPromise;
|
||||
|
||||
expect(result).toEqual({ success: false, error: 'access_denied' });
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('should return 404 for non-callback paths', async () => {
|
||||
const server = await startCallbackServer();
|
||||
|
||||
try {
|
||||
const response = await httpGet(
|
||||
`http://127.0.0.1:${server.port}/other-path`,
|
||||
);
|
||||
|
||||
expect(response.status).toBe(404);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('should time out if no callback is received', async () => {
|
||||
const server = await startCallbackServer({ timeoutMs: 500 });
|
||||
|
||||
try {
|
||||
const result = await server.waitForCallback();
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
|
||||
if (!result.success) {
|
||||
expect(result.error).toContain('Timed out');
|
||||
}
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
import { generatePkceChallenge } from '../pkce';
|
||||
|
||||
describe('generatePkceChallenge', () => {
|
||||
it('should return a code verifier and code challenge', () => {
|
||||
const { codeVerifier, codeChallenge } = generatePkceChallenge();
|
||||
|
||||
expect(codeVerifier).toBeDefined();
|
||||
expect(codeChallenge).toBeDefined();
|
||||
expect(codeVerifier.length).toBeGreaterThan(0);
|
||||
expect(codeChallenge.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should produce a challenge that is the SHA256 hash of the verifier', () => {
|
||||
const { codeVerifier, codeChallenge } = generatePkceChallenge();
|
||||
|
||||
const expectedChallenge = crypto
|
||||
.createHash('sha256')
|
||||
.update(codeVerifier)
|
||||
.digest('base64url');
|
||||
|
||||
expect(codeChallenge).toBe(expectedChallenge);
|
||||
});
|
||||
|
||||
it('should generate unique values on each call', () => {
|
||||
const first = generatePkceChallenge();
|
||||
const second = generatePkceChallenge();
|
||||
|
||||
expect(first.codeVerifier).not.toBe(second.codeVerifier);
|
||||
expect(first.codeChallenge).not.toBe(second.codeChallenge);
|
||||
});
|
||||
|
||||
it('should use base64url encoding with no padding', () => {
|
||||
const { codeVerifier, codeChallenge } = generatePkceChallenge();
|
||||
|
||||
// base64url uses - and _ instead of + and /, and no = padding
|
||||
expect(codeVerifier).not.toMatch(/[+/=]/);
|
||||
expect(codeChallenge).not.toMatch(/[+/=]/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import http from 'node:http';
|
||||
|
||||
type CallbackResult =
|
||||
| { success: true; code: string }
|
||||
| { success: false; error: string };
|
||||
|
||||
type CallbackServer = {
|
||||
port: number;
|
||||
callbackUrl: string;
|
||||
waitForCallback: () => Promise<CallbackResult>;
|
||||
close: () => void;
|
||||
};
|
||||
|
||||
const TWENTY_LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 96 96">
|
||||
<rect width="96" height="96" rx="11.3" fill="#000"/>
|
||||
<path fill="#fff" d="M19.25 35.75c0-5.25 4.26-9.5 9.5-9.5h18.29c.27 0 .51.16.63.4.11.25.06.54-.12.75l-4.01 4.35c-.7.76-1.68 1.2-2.71 1.2H28.8c-1.57 0-2.85 1.27-2.85 2.85v7.18c0 .93-.75 1.67-1.68 1.67h-3.34c-.93 0-1.67-.75-1.67-1.67v-7.23z"/>
|
||||
<path fill="#fff" d="M76.15 60.25c0 5.25-4.26 9.5-9.5 9.5h-7.77c-5.25 0-9.5-4.25-9.5-9.5V46.65c0-.93.35-1.82.98-2.5l4.53-4.92c.19-.2.49-.27.75-.17.26.11.44.36.44.64v20.52c0 1.57 1.28 2.85 2.85 2.85h7.68c1.57 0 2.85-1.28 2.85-2.85V35.8c0-1.57-1.28-2.85-2.85-2.85h-8.93c-1.02 0-2 .43-2.7 1.18L28.35 63.06h16c.92 0 1.67.75 1.67 1.68v3.34c0 .93-.75 1.67-1.67 1.67H22.79c-1.95 0-3.55-1.59-3.55-3.54v-1.77c0-.89.33-1.75.94-2.4l29.86-32.43c1.98-2.15 4.75-3.36 7.67-3.36h8.93c5.25 0 9.5 4.25 9.5 9.5v24.5z"/>
|
||||
</svg>`;
|
||||
|
||||
const pageHtml = ({
|
||||
title,
|
||||
message,
|
||||
isSuccess,
|
||||
}: {
|
||||
title: string;
|
||||
message: string;
|
||||
isSuccess: boolean;
|
||||
}) => `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${title} — Twenty</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
background: #fafafa;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 100dvh;
|
||||
color: #333;
|
||||
}
|
||||
.card {
|
||||
background: #fff;
|
||||
border-radius: 8px;
|
||||
box-shadow: 2px 4px 16px rgba(0,0,0,0.08), 0 2px 4px rgba(0,0,0,0.04);
|
||||
padding: 32px;
|
||||
width: 400px;
|
||||
max-width: calc(100vw - 32px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
}
|
||||
.logo { margin-bottom: 4px; }
|
||||
.icon {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.icon-success { background: #f0faf0; }
|
||||
.icon-error { background: #fef0f0; }
|
||||
.icon svg { width: 24px; height: 24px; }
|
||||
h2 {
|
||||
font-size: 1.23rem;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
}
|
||||
p {
|
||||
font-size: 0.92rem;
|
||||
color: #666;
|
||||
text-align: center;
|
||||
line-height: 1.5;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="logo">${TWENTY_LOGO_SVG}</div>
|
||||
<div class="icon ${isSuccess ? 'icon-success' : 'icon-error'}">
|
||||
${
|
||||
isSuccess
|
||||
? '<svg viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>'
|
||||
: '<svg viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>'
|
||||
}
|
||||
</div>
|
||||
<h2>${title}</h2>
|
||||
<p>${message}</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
|
||||
const SUCCESS_HTML = pageHtml({
|
||||
title: 'Authentication successful',
|
||||
message: 'You can close this window and return to the terminal.',
|
||||
isSuccess: true,
|
||||
});
|
||||
|
||||
const escapeHtml = (text: string): string =>
|
||||
text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
|
||||
const errorHtml = (error: string) =>
|
||||
pageHtml({
|
||||
title: 'Authentication failed',
|
||||
message: `${escapeHtml(error)}<br>Please return to the terminal and try again.`,
|
||||
isSuccess: false,
|
||||
});
|
||||
|
||||
export const startCallbackServer = (options?: {
|
||||
timeoutMs?: number;
|
||||
}): Promise<CallbackServer> => {
|
||||
const timeoutMs = options?.timeoutMs ?? 120_000;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let callbackResolve: (result: CallbackResult) => void;
|
||||
let timeoutHandle: ReturnType<typeof setTimeout>;
|
||||
|
||||
const callbackPromise = new Promise<CallbackResult>((res) => {
|
||||
callbackResolve = res;
|
||||
});
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url ?? '/', `http://127.0.0.1`);
|
||||
|
||||
if (url.pathname !== '/callback') {
|
||||
res.writeHead(404);
|
||||
res.end('Not found');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const code = url.searchParams.get('code');
|
||||
const error = url.searchParams.get('error');
|
||||
|
||||
const headers = {
|
||||
'Content-Type': 'text/html',
|
||||
Connection: 'close',
|
||||
};
|
||||
|
||||
if (code) {
|
||||
res.writeHead(200, headers);
|
||||
res.end(SUCCESS_HTML);
|
||||
callbackResolve({ success: true, code });
|
||||
} else {
|
||||
const errorMessage =
|
||||
error ?? url.searchParams.get('error_description') ?? 'Unknown error';
|
||||
|
||||
res.writeHead(200, headers);
|
||||
res.end(errorHtml(errorMessage));
|
||||
callbackResolve({ success: false, error: errorMessage });
|
||||
}
|
||||
});
|
||||
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const address = server.address();
|
||||
|
||||
if (!address || typeof address === 'string') {
|
||||
reject(new Error('Failed to start callback server'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const port = address.port;
|
||||
|
||||
resolve({
|
||||
port,
|
||||
callbackUrl: `http://127.0.0.1:${port}/callback`,
|
||||
waitForCallback: () => {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
callbackResolve({
|
||||
success: false,
|
||||
error: `Timed out waiting for authorization (${timeoutMs / 1000}s)`,
|
||||
});
|
||||
}, timeoutMs);
|
||||
|
||||
return callbackPromise.finally(() => {
|
||||
clearTimeout(timeoutHandle);
|
||||
});
|
||||
},
|
||||
close: () => {
|
||||
clearTimeout(timeoutHandle);
|
||||
server.closeAllConnections();
|
||||
server.close();
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
server.on('error', reject);
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
|
||||
export const openBrowser = (url: string): Promise<boolean> => {
|
||||
try {
|
||||
new URL(url);
|
||||
} catch {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
const [command, args]: [string, string[]] =
|
||||
process.platform === 'darwin'
|
||||
? ['open', [url]]
|
||||
: process.platform === 'win32'
|
||||
? ['cmd', ['/c', 'start', '', url]]
|
||||
: ['xdg-open', [url]];
|
||||
|
||||
return new Promise((resolve) => {
|
||||
execFile(command, args, (error) => {
|
||||
resolve(!error);
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
export type PkceChallenge = {
|
||||
codeVerifier: string;
|
||||
codeChallenge: string;
|
||||
};
|
||||
|
||||
export const generatePkceChallenge = (): PkceChallenge => {
|
||||
const codeVerifier = crypto.randomBytes(32).toString('base64url');
|
||||
const codeChallenge = crypto
|
||||
.createHash('sha256')
|
||||
.update(codeVerifier)
|
||||
.digest('base64url');
|
||||
|
||||
return { codeVerifier, codeChallenge };
|
||||
};
|
||||
@@ -1,7 +1,4 @@
|
||||
import {
|
||||
APP_ERROR_CODES,
|
||||
type CommandResult,
|
||||
} from '@/cli/public-operations/types';
|
||||
import { APP_ERROR_CODES, type CommandResult } from '@/cli/types';
|
||||
import { ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { type BuiltFileInfo } from '@/cli/utilities/build/common/build-application';
|
||||
import { manifestUpdateChecksums } from '@/cli/utilities/build/manifest/manifest-update-checksums';
|
||||
@@ -12,7 +9,7 @@ import { type Manifest } from 'twenty-shared/application';
|
||||
|
||||
export type AppSyncOptions = {
|
||||
appPath: string;
|
||||
workspace?: string;
|
||||
remote?: string;
|
||||
};
|
||||
|
||||
const ensureApplicationRegistrationExists = async (
|
||||
|
||||
@@ -368,21 +368,27 @@ export const buildManifest = async (
|
||||
};
|
||||
}
|
||||
|
||||
const byId = <T extends { universalIdentifier: string }>(a: T, b: T) =>
|
||||
a.universalIdentifier.localeCompare(b.universalIdentifier);
|
||||
|
||||
const byPath = <T extends { filePath: string }>(a: T, b: T) =>
|
||||
a.filePath.localeCompare(b.filePath);
|
||||
|
||||
const manifest = !application
|
||||
? null
|
||||
: {
|
||||
application,
|
||||
objects,
|
||||
fields,
|
||||
roles,
|
||||
skills,
|
||||
agents,
|
||||
logicFunctions,
|
||||
frontComponents,
|
||||
publicAssets,
|
||||
views,
|
||||
navigationMenuItems,
|
||||
pageLayouts,
|
||||
objects: objects.sort(byId),
|
||||
fields: fields.sort(byId),
|
||||
roles: roles.sort(byId),
|
||||
skills: skills.sort(byId),
|
||||
agents: agents.sort(byId),
|
||||
logicFunctions: logicFunctions.sort(byId),
|
||||
frontComponents: frontComponents.sort(byId),
|
||||
publicAssets: publicAssets.sort(byPath),
|
||||
views: views.sort(byId),
|
||||
navigationMenuItems: navigationMenuItems.sort(byId),
|
||||
pageLayouts: pageLayouts.sort(byId),
|
||||
};
|
||||
|
||||
const entityFilePaths: EntityFilePaths = {
|
||||
|
||||
@@ -5,158 +5,233 @@ import { ensureDir, ensureFile } from '@/cli/utilities/file/fs-utils';
|
||||
|
||||
import { getConfigPath } from '@/cli/utilities/config/get-config-path';
|
||||
|
||||
export type TwentyConfig = {
|
||||
export type RemoteConfig = {
|
||||
apiUrl: string;
|
||||
apiKey?: string;
|
||||
applicationAccessToken?: string;
|
||||
applicationRefreshToken?: string;
|
||||
accessToken?: string;
|
||||
refreshToken?: string;
|
||||
oauthClientId?: string;
|
||||
oauthClientSecret?: string;
|
||||
};
|
||||
|
||||
type PersistedConfig = TwentyConfig & {
|
||||
profiles?: Record<string, TwentyConfig>;
|
||||
defaultWorkspace?: string;
|
||||
type PersistedConfig = {
|
||||
version?: number;
|
||||
defaultRemote?: string;
|
||||
remotes?: Record<string, RemoteConfig>;
|
||||
};
|
||||
|
||||
const DEFAULT_WORKSPACE_NAME = 'default';
|
||||
const CONFIG_VERSION = 1;
|
||||
|
||||
const DEFAULT_REMOTE_NAME = 'local';
|
||||
|
||||
export class ConfigService {
|
||||
private readonly configPath: string;
|
||||
private static activeWorkspace = DEFAULT_WORKSPACE_NAME;
|
||||
private static activeRemote = DEFAULT_REMOTE_NAME;
|
||||
|
||||
constructor() {
|
||||
this.configPath = getConfigPath();
|
||||
}
|
||||
|
||||
static setActiveWorkspace(name?: string) {
|
||||
this.activeWorkspace = name ?? DEFAULT_WORKSPACE_NAME;
|
||||
static setActiveRemote(name?: string) {
|
||||
this.activeRemote = name ?? DEFAULT_REMOTE_NAME;
|
||||
}
|
||||
|
||||
static getActiveWorkspace(): string {
|
||||
return this.activeWorkspace;
|
||||
static getActiveRemote(): string {
|
||||
return this.activeRemote;
|
||||
}
|
||||
|
||||
private getActiveWorkspaceName(): string {
|
||||
return ConfigService.getActiveWorkspace();
|
||||
private getActiveRemoteName(): string {
|
||||
return ConfigService.getActiveRemote();
|
||||
}
|
||||
|
||||
private async readRawConfig(): Promise<PersistedConfig> {
|
||||
await ensureFile(this.configPath);
|
||||
const content = await readFile(this.configPath, 'utf8');
|
||||
return JSON.parse(content || '{}');
|
||||
const raw = JSON.parse(content || '{}');
|
||||
|
||||
return this.migrateConfigIfNeeded(raw);
|
||||
}
|
||||
|
||||
async getConfig(): Promise<TwentyConfig> {
|
||||
return this.getConfigForWorkspace(this.getActiveWorkspaceName());
|
||||
// TODO: Remove after 2026-04-30 — migrates legacy config format
|
||||
// (profiles, top-level keys, applicationAccessToken/applicationRefreshToken)
|
||||
// to the current format (remotes, accessToken/refreshToken)
|
||||
private async migrateConfigIfNeeded(
|
||||
raw: Record<string, unknown>,
|
||||
): Promise<PersistedConfig> {
|
||||
if ((raw as PersistedConfig).version === CONFIG_VERSION) {
|
||||
return raw as PersistedConfig;
|
||||
}
|
||||
|
||||
const hasLegacyProfiles = 'profiles' in raw;
|
||||
const hasTopLevelApiUrl = 'apiUrl' in raw && !('remotes' in raw);
|
||||
|
||||
if (!hasLegacyProfiles && !hasTopLevelApiUrl) {
|
||||
return raw as PersistedConfig;
|
||||
}
|
||||
|
||||
const migrated: PersistedConfig = { version: CONFIG_VERSION };
|
||||
|
||||
const str = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' ? value : undefined;
|
||||
|
||||
const migrateRemoteFields = (
|
||||
source: Record<string, unknown>,
|
||||
): RemoteConfig => ({
|
||||
apiUrl: str(source.apiUrl) ?? '',
|
||||
apiKey: str(source.apiKey),
|
||||
accessToken:
|
||||
str(source.accessToken) ?? str(source.applicationAccessToken),
|
||||
refreshToken:
|
||||
str(source.refreshToken) ?? str(source.applicationRefreshToken),
|
||||
oauthClientId: str(source.oauthClientId),
|
||||
});
|
||||
|
||||
const profiles =
|
||||
(raw.profiles as Record<string, Record<string, unknown>> | undefined) ??
|
||||
{};
|
||||
|
||||
migrated.remotes = {};
|
||||
|
||||
for (const [name, profile] of Object.entries(profiles)) {
|
||||
const remoteName = name === 'default' ? DEFAULT_REMOTE_NAME : name;
|
||||
|
||||
migrated.remotes[remoteName] = migrateRemoteFields(profile);
|
||||
}
|
||||
|
||||
// Current-format remotes override legacy profiles — they're newer.
|
||||
const existingRemotes =
|
||||
(raw.remotes as Record<string, RemoteConfig> | undefined) ?? {};
|
||||
|
||||
for (const [name, remote] of Object.entries(existingRemotes)) {
|
||||
const remoteName = name === 'default' ? DEFAULT_REMOTE_NAME : name;
|
||||
|
||||
migrated.remotes[remoteName] = remote;
|
||||
}
|
||||
|
||||
if (hasTopLevelApiUrl && !migrated.remotes[DEFAULT_REMOTE_NAME]) {
|
||||
migrated.remotes[DEFAULT_REMOTE_NAME] = migrateRemoteFields(
|
||||
raw as Record<string, unknown>,
|
||||
);
|
||||
}
|
||||
|
||||
const legacyDefault = raw.defaultWorkspace as string | undefined;
|
||||
|
||||
if (legacyDefault) {
|
||||
migrated.defaultRemote =
|
||||
legacyDefault === 'default' ? DEFAULT_REMOTE_NAME : legacyDefault;
|
||||
}
|
||||
|
||||
await ensureDir(path.dirname(this.configPath));
|
||||
await writeFile(this.configPath, JSON.stringify(migrated, null, 2));
|
||||
|
||||
return migrated;
|
||||
}
|
||||
|
||||
async getConfigForWorkspace(workspaceName: string): Promise<TwentyConfig> {
|
||||
async getConfig(): Promise<RemoteConfig> {
|
||||
if (process.env.TWENTY_TOKEN && process.env.TWENTY_API_URL) {
|
||||
return {
|
||||
apiUrl: process.env.TWENTY_API_URL,
|
||||
accessToken: process.env.TWENTY_TOKEN,
|
||||
};
|
||||
}
|
||||
|
||||
return this.getConfigForRemote(this.getActiveRemoteName());
|
||||
}
|
||||
|
||||
async getConfigForRemote(remoteName: string): Promise<RemoteConfig> {
|
||||
const defaultConfig = this.getDefaultConfig();
|
||||
|
||||
try {
|
||||
const raw = await this.readRawConfig();
|
||||
const remoteConfig = raw.remotes?.[remoteName];
|
||||
|
||||
const profileConfig =
|
||||
workspaceName === DEFAULT_WORKSPACE_NAME &&
|
||||
!raw.profiles?.[DEFAULT_WORKSPACE_NAME]
|
||||
? raw
|
||||
: raw.profiles?.[workspaceName];
|
||||
|
||||
// Fallback to legacy top-level values if profile value is missing
|
||||
const apiUrl = profileConfig?.apiUrl ?? defaultConfig.apiUrl;
|
||||
const apiKey = profileConfig?.apiKey;
|
||||
const applicationAccessToken = profileConfig?.applicationAccessToken;
|
||||
const applicationRefreshToken = profileConfig?.applicationRefreshToken;
|
||||
if (!remoteConfig) {
|
||||
return defaultConfig;
|
||||
}
|
||||
|
||||
return {
|
||||
apiUrl,
|
||||
apiKey,
|
||||
applicationAccessToken,
|
||||
applicationRefreshToken,
|
||||
apiUrl: remoteConfig.apiUrl ?? defaultConfig.apiUrl,
|
||||
apiKey: remoteConfig.apiKey,
|
||||
accessToken: remoteConfig.accessToken,
|
||||
refreshToken: remoteConfig.refreshToken,
|
||||
oauthClientId: remoteConfig.oauthClientId,
|
||||
};
|
||||
} catch {
|
||||
return defaultConfig;
|
||||
}
|
||||
}
|
||||
|
||||
async setConfig(config: Partial<TwentyConfig>): Promise<void> {
|
||||
async setConfig(config: Partial<RemoteConfig>): Promise<void> {
|
||||
const raw = await this.readRawConfig();
|
||||
const profile = this.getActiveWorkspaceName();
|
||||
const remote = this.getActiveRemoteName();
|
||||
|
||||
// Ensure profiles map exists
|
||||
if (!raw.profiles) {
|
||||
raw.profiles = {};
|
||||
raw.version = CONFIG_VERSION;
|
||||
|
||||
if (!raw.remotes) {
|
||||
raw.remotes = {};
|
||||
}
|
||||
|
||||
const currentProfile = raw.profiles[profile] || { apiUrl: '' };
|
||||
const currentRemote = raw.remotes[remote] || { apiUrl: '' };
|
||||
|
||||
raw.profiles[profile] = { ...currentProfile, ...config };
|
||||
raw.remotes[remote] = { ...currentRemote, ...config };
|
||||
|
||||
await ensureDir(path.dirname(this.configPath));
|
||||
await writeFile(this.configPath, JSON.stringify(raw, null, 2));
|
||||
}
|
||||
|
||||
async clearConfig(): Promise<void> {
|
||||
// Clear only the active profile credentials (non-breaking for other profiles)
|
||||
const raw = await this.readRawConfig();
|
||||
const profile = this.getActiveWorkspaceName();
|
||||
const remote = this.getActiveRemoteName();
|
||||
|
||||
if (!raw.profiles) {
|
||||
raw.profiles = {};
|
||||
if (!raw.remotes) {
|
||||
raw.remotes = {};
|
||||
}
|
||||
|
||||
if (raw.profiles[profile]) {
|
||||
delete raw.profiles[profile];
|
||||
}
|
||||
|
||||
// Also clear legacy top-level apiKey for compatibility when active profile is default
|
||||
if (profile === DEFAULT_WORKSPACE_NAME) {
|
||||
const defaultConfig = this.getDefaultConfig();
|
||||
delete raw.apiKey;
|
||||
raw.apiUrl = defaultConfig.apiUrl;
|
||||
if (raw.remotes[remote]) {
|
||||
delete raw.remotes[remote];
|
||||
}
|
||||
|
||||
await ensureDir(path.dirname(this.configPath));
|
||||
await writeFile(this.configPath, JSON.stringify(raw, null, 2));
|
||||
}
|
||||
|
||||
private getDefaultConfig(): TwentyConfig {
|
||||
private getDefaultConfig(): RemoteConfig {
|
||||
return {
|
||||
apiUrl: 'http://localhost:3000',
|
||||
};
|
||||
}
|
||||
|
||||
async getAvailableWorkspaces(): Promise<string[]> {
|
||||
async getRemotes(): Promise<string[]> {
|
||||
try {
|
||||
const raw = await this.readRawConfig();
|
||||
const workspaces = new Set<string>();
|
||||
const remotes = new Set<string>();
|
||||
|
||||
// Always include the default workspace
|
||||
workspaces.add(DEFAULT_WORKSPACE_NAME);
|
||||
remotes.add(DEFAULT_REMOTE_NAME);
|
||||
|
||||
// Add all profiles
|
||||
if (raw.profiles) {
|
||||
Object.keys(raw.profiles).forEach((name) => workspaces.add(name));
|
||||
if (raw.remotes) {
|
||||
Object.keys(raw.remotes).forEach((name) => remotes.add(name));
|
||||
}
|
||||
|
||||
return Array.from(workspaces).sort();
|
||||
return Array.from(remotes).sort();
|
||||
} catch {
|
||||
return [DEFAULT_WORKSPACE_NAME];
|
||||
return [DEFAULT_REMOTE_NAME];
|
||||
}
|
||||
}
|
||||
|
||||
async getDefaultWorkspace(): Promise<string> {
|
||||
async getDefaultRemote(): Promise<string> {
|
||||
try {
|
||||
const raw = await this.readRawConfig();
|
||||
return raw.defaultWorkspace ?? DEFAULT_WORKSPACE_NAME;
|
||||
|
||||
return raw.defaultRemote ?? DEFAULT_REMOTE_NAME;
|
||||
} catch {
|
||||
return DEFAULT_WORKSPACE_NAME;
|
||||
return DEFAULT_REMOTE_NAME;
|
||||
}
|
||||
}
|
||||
|
||||
async setDefaultWorkspace(name: string): Promise<void> {
|
||||
async setDefaultRemote(name: string): Promise<void> {
|
||||
const raw = await this.readRawConfig();
|
||||
raw.defaultWorkspace = name;
|
||||
|
||||
raw.defaultRemote = name;
|
||||
|
||||
await ensureDir(path.dirname(this.configPath));
|
||||
await writeFile(this.configPath, JSON.stringify(raw, null, 2));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import { type OrchestratorState } from '@/cli/utilities/dev/orchestrator/dev-mode-orchestrator-state';
|
||||
import { BuildManifestOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/build-manifest-orchestrator-step';
|
||||
import { CheckServerOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/check-server-orchestrator-step';
|
||||
import { EnsureValidTokensOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/ensure-valid-tokens-orchestrator-step';
|
||||
import { GenerateApiClientOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/generate-api-client-orchestrator-step';
|
||||
import { RegisterAppOrchestratorStep } from '@/cli/utilities/dev/orchestrator/steps/register-app-orchestrator-step';
|
||||
import {
|
||||
@@ -33,7 +32,6 @@ export class DevModeOrchestrator {
|
||||
private clientService: ClientService;
|
||||
private skipTypecheck = true;
|
||||
private checkServerStep: CheckServerOrchestratorStep;
|
||||
private ensureValidTokensStep: EnsureValidTokensOrchestratorStep;
|
||||
private buildManifestStep: BuildManifestOrchestratorStep;
|
||||
private registerAppStep: RegisterAppOrchestratorStep;
|
||||
private uploadFilesStep: UploadFilesOrchestratorStep;
|
||||
@@ -55,11 +53,6 @@ export class DevModeOrchestrator {
|
||||
...stepDeps,
|
||||
apiService,
|
||||
});
|
||||
this.ensureValidTokensStep = new EnsureValidTokensOrchestratorStep({
|
||||
...stepDeps,
|
||||
apiService,
|
||||
configService,
|
||||
});
|
||||
this.buildManifestStep = new BuildManifestOrchestratorStep(stepDeps);
|
||||
this.registerAppStep = new RegisterAppOrchestratorStep({
|
||||
...stepDeps,
|
||||
@@ -167,10 +160,6 @@ export class DevModeOrchestrator {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.ensureValidTokensStep.execute({
|
||||
applicationId: this.state.steps.resolveApplication.output.applicationId,
|
||||
});
|
||||
|
||||
const buildResult = await this.buildManifestStep.execute({
|
||||
appPath: this.state.appPath,
|
||||
});
|
||||
@@ -244,10 +233,6 @@ export class DevModeOrchestrator {
|
||||
{ message: 'Application created', status: 'success' },
|
||||
]);
|
||||
|
||||
await this.ensureValidTokensStep.exchangeTokens({
|
||||
applicationId: createResult.data.id,
|
||||
});
|
||||
|
||||
this.uploadFilesStep.initialize({
|
||||
appPath: this.state.appPath,
|
||||
universalIdentifier: manifest.application.universalIdentifier,
|
||||
|
||||
+16
-2
@@ -34,7 +34,17 @@ export class CheckServerOrchestratorStep {
|
||||
step.output = { isReady: false, errorLogged: true };
|
||||
step.status = 'error';
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Cannot reach server', status: 'error' },
|
||||
{
|
||||
message:
|
||||
'Cannot reach Twenty at localhost:3000.\n\n' +
|
||||
' Start a local server with Docker:\n' +
|
||||
' curl -sL https://raw.githubusercontent.com/twentyhq/twenty/main/packages/twenty-docker/docker-compose.yml -o docker-compose.yml\n' +
|
||||
' docker compose up -d\n\n' +
|
||||
' Or from the monorepo:\n' +
|
||||
' yarn start\n\n' +
|
||||
' Waiting for server...',
|
||||
status: 'error',
|
||||
},
|
||||
]);
|
||||
this.state.updatePipeline({ status: 'error' });
|
||||
}
|
||||
@@ -47,7 +57,11 @@ export class CheckServerOrchestratorStep {
|
||||
step.output = { isReady: false, errorLogged: true };
|
||||
step.status = 'error';
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Authentication failed', status: 'error' },
|
||||
{
|
||||
message:
|
||||
'Authentication failed. Run `twenty remote add --local` to authenticate.',
|
||||
status: 'error',
|
||||
},
|
||||
]);
|
||||
this.state.updatePipeline({ status: 'error' });
|
||||
}
|
||||
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
import { type ApiService } from '@/cli/utilities/api/api-service';
|
||||
import { type ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import { type OrchestratorState } from '@/cli/utilities/dev/orchestrator/dev-mode-orchestrator-state';
|
||||
|
||||
export class EnsureValidTokensOrchestratorStep {
|
||||
private apiService: ApiService;
|
||||
private configService: ConfigService;
|
||||
private state: OrchestratorState;
|
||||
private notify: () => void;
|
||||
|
||||
constructor({
|
||||
apiService,
|
||||
configService,
|
||||
state,
|
||||
notify,
|
||||
}: {
|
||||
apiService: ApiService;
|
||||
configService: ConfigService;
|
||||
state: OrchestratorState;
|
||||
notify: () => void;
|
||||
}) {
|
||||
this.apiService = apiService;
|
||||
this.configService = configService;
|
||||
this.state = state;
|
||||
this.notify = notify;
|
||||
}
|
||||
|
||||
async execute(input: { applicationId: string | null }): Promise<void> {
|
||||
if (!input.applicationId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const step = this.state.steps.ensureValidTokens;
|
||||
|
||||
step.status = 'in_progress';
|
||||
this.notify();
|
||||
|
||||
const config = await this.configService.getConfig();
|
||||
|
||||
if (
|
||||
config.applicationAccessToken &&
|
||||
!this.isTokenExpired(config.applicationAccessToken)
|
||||
) {
|
||||
step.status = 'done';
|
||||
this.notify();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
config.applicationRefreshToken &&
|
||||
!this.isTokenExpired(config.applicationRefreshToken)
|
||||
) {
|
||||
const renewResult = await this.apiService.renewApplicationToken(
|
||||
config.applicationRefreshToken,
|
||||
);
|
||||
|
||||
if (renewResult.success) {
|
||||
await this.configService.setConfig({
|
||||
applicationAccessToken: renewResult.data.applicationAccessToken.token,
|
||||
applicationRefreshToken:
|
||||
renewResult.data.applicationRefreshToken.token,
|
||||
});
|
||||
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Renewing application tokens', status: 'info' },
|
||||
{ message: 'Application tokens renewed', status: 'success' },
|
||||
]);
|
||||
step.status = 'done';
|
||||
this.notify();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Renewing application tokens', status: 'info' },
|
||||
{
|
||||
message: `Failed to renew application tokens: ${JSON.stringify(renewResult.error, null, 2)}`,
|
||||
status: 'error',
|
||||
},
|
||||
]);
|
||||
|
||||
await this.exchangeTokens({ applicationId: input.applicationId });
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await this.exchangeTokens({ applicationId: input.applicationId });
|
||||
}
|
||||
|
||||
async exchangeTokens(input: { applicationId: string }): Promise<void> {
|
||||
const tokenResult = await this.apiService.generateApplicationToken(
|
||||
input.applicationId,
|
||||
);
|
||||
|
||||
if (!tokenResult.success) {
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Generating application tokens', status: 'info' },
|
||||
{
|
||||
message: `Failed to generate application tokens: ${JSON.stringify(tokenResult.error, null, 2)}`,
|
||||
status: 'error',
|
||||
},
|
||||
]);
|
||||
this.state.steps.ensureValidTokens.status = 'error';
|
||||
this.notify();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await this.configService.setConfig({
|
||||
applicationAccessToken: tokenResult.data.applicationAccessToken.token,
|
||||
applicationRefreshToken: tokenResult.data.applicationRefreshToken.token,
|
||||
});
|
||||
|
||||
this.state.applyStepEvents([
|
||||
{ message: 'Generating application tokens', status: 'info' },
|
||||
{ message: 'Application tokens stored in config', status: 'success' },
|
||||
]);
|
||||
this.state.steps.ensureValidTokens.status = 'done';
|
||||
this.notify();
|
||||
}
|
||||
|
||||
private isTokenExpired(token: string): boolean {
|
||||
try {
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(token.split('.')[1], 'base64').toString(),
|
||||
);
|
||||
|
||||
return Date.now() >= payload.exp * 1000 - 60_000;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -36,7 +36,7 @@ export class GenerateApiClientOrchestratorStep {
|
||||
|
||||
await this.clientService.generateCoreClient({
|
||||
appPath: input.appPath,
|
||||
authToken: config.applicationAccessToken,
|
||||
authToken: config.accessToken,
|
||||
});
|
||||
|
||||
step.status = 'done';
|
||||
|
||||
-1
@@ -88,7 +88,6 @@ export class RegisterAppOrchestratorStep {
|
||||
|
||||
await this.configService.setConfig({
|
||||
oauthClientId: createResult.data.applicationRegistration.oAuthClientId,
|
||||
oauthClientSecret: createResult.data.clientSecret,
|
||||
});
|
||||
|
||||
this.state.applyStepEvents([
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type CommandResult } from '@/cli/public-operations/types';
|
||||
import { type CommandResult } from '@/cli/types';
|
||||
|
||||
export const runSafe = async <T>(
|
||||
operation: () => Promise<CommandResult<T>>,
|
||||
|
||||
Reference in New Issue
Block a user