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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"@salesforce/core": "^8.23.1",
"@salesforce/kit": "^3.2.3",
"@salesforce/sf-plugins-core": "^12.2.4",
"@salesforce/source-deploy-retrieve": "^12.22.1",
"@salesforce/source-deploy-retrieve": "^12.25.0",
"@salesforce/types": "^1.4.0",
"ansis": "^3.3.2",
"fast-xml-parser": "^4.5.1",
Expand Down
12 changes: 8 additions & 4 deletions src/commands/agent/publish/authoring-bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { Agent, findAuthoringBundle } from '@salesforce/agents';
import { RequestStatus, type ScopedPostRetrieve } from '@salesforce/source-deploy-retrieve';
import { ensureArray } from '@salesforce/kit';
import { FlaggablePrompt, promptForAgentFiles } from '../../../flags.js';
import { throwAgentCompilationError } from '../../../common.js';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-agent', 'agent.publish.authoring-bundle');
Expand Down Expand Up @@ -103,12 +104,15 @@ export default class AgentPublishAuthoringBundle extends SfCommand<AgentPublishA
const conn = targetOrg.getConnection(flags['api-version']);

// First compile the .agent file to get the Agent JSON
const agentJson = await Agent.compileAgentScript(
const compileResponse = await Agent.compileAgentScript(
conn,
readFileSync(join(authoringBundleDir, `${apiName}.agent`), 'utf8')
);
mso.skipTo('Publish Agent');

if (compileResponse.status === 'success') {
mso.skipTo('Publish Agent');
} else {
throwAgentCompilationError(compileResponse.errors);
}
// Then publish the Agent JSON to create the agent
// Set up lifecycle listeners for retrieve events
Lifecycle.getInstance().on('scopedPreRetrieve', () => {
Expand All @@ -129,7 +133,7 @@ export default class AgentPublishAuthoringBundle extends SfCommand<AgentPublishA
}
return Promise.resolve();
});
const result = await Agent.publishAgentJson(conn, this.project!, agentJson);
const result = await Agent.publishAgentJson(conn, this.project!, compileResponse.compiledArtifact);
mso.stop();

return {
Expand Down
30 changes: 18 additions & 12 deletions src/commands/agent/validate/authoring-bundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
import { Messages, SfError } from '@salesforce/core';
import { MultiStageOutput } from '@oclif/multi-stage-output';
import { Agent, findAuthoringBundle } from '@salesforce/agents';
import { Duration, sleep } from '@salesforce/kit';
import { colorize } from '@oclif/core/ux';
import { throwAgentCompilationError } from '../../../common.js';
import { FlaggablePrompt, promptForAgentFiles } from '../../../flags.js';

Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
Expand Down Expand Up @@ -103,25 +103,31 @@ export default class AgentValidateAuthoringBundle extends SfCommand<AgentValidat
mso.skipTo('Validating Authoring Bundle');
const targetOrg = flags['target-org'];
const conn = targetOrg.getConnection(flags['api-version']);
// Call Agent.compileAgent() API
await sleep(Duration.seconds(2));
await Agent.compileAgentScript(conn, readFileSync(join(authoringBundleDir, `${apiName}.agent`), 'utf8'));
mso.updateData({ status: 'COMPLETED' });
mso.stop('completed');
return {
success: true,
};
const result = await Agent.compileAgentScript(
conn,
readFileSync(join(authoringBundleDir, `${apiName}.agent`), 'utf8')
);
if (result.status === 'success') {
mso.updateData({ status: 'COMPLETED' });
mso.stop('completed');
return {
success: true,
};
} else {
throwAgentCompilationError(result.errors);
}
} catch (error) {
// Handle validation errors
const err = SfError.wrap(error);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't this be using the throwAgentCompilationError method?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This catch block is used to handle all error, not only compilation errors returned from the api

let count = 0;
const formattedError = err.message
const rawError = err.message ? err.message : err.name;
const formattedError = rawError
.split('\n')
.map((line) => {
count += 1;
const type = line.split(':')[0];
const rest = line.substring(line.indexOf(':')).trim();
return `- ${colorize('red', type)} ${rest}`;
const rest = line.includes(':') ? line.substring(line.indexOf(':')).trim() : '';
return `- ${colorize('red', type)}${rest}`;
})
.join('\n');

Expand Down
42 changes: 42 additions & 0 deletions src/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2025, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { EOL } from 'node:os';
import { SfError } from '@salesforce/core';
import { CompilationError } from '@salesforce/agents';

/**
* Utility function to generate SfError when there are agent compilation errors.
*
* @param compilationErrors - The compilation errors as strings, CompilationError objects, or array of either
* @throws SfError - Always throws a Salesforce CLI error
*/
export function throwAgentCompilationError(compilationErrors: CompilationError[]): never {
if (compilationErrors.length === 0) {
throw SfError.create({
name: 'CompileAgentScriptError',
message: 'Unknown compilation error occurred',
data: compilationErrors,
});
}

const errors = compilationErrors;

throw SfError.create({
name: 'CompileAgentScriptError',
message: errors.map((e) => `${e.errorType}: ${e.description} [Ln ${e.lineStart}, Col ${e.colStart}]`).join(EOL),
data: errors,
});
}
90 changes: 90 additions & 0 deletions test/commands/agent/validate/authoring-bundle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright 2025, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { expect } from 'chai';
import { SfError } from '@salesforce/core';
import { type CompilationError } from '@salesforce/agents';
import AgentValidateAuthoringBundle, {
type AgentValidateAuthoringBundleResult,
} from '../../../../src/commands/agent/validate/authoring-bundle.js';
import { throwAgentCompilationError } from '../../../../src/common.js';

describe('Agent Validate Authoring Bundle', () => {
describe('prompt configuration', () => {
it('should have correct prompt messages', () => {
const prompts = AgentValidateAuthoringBundle['FLAGGABLE_PROMPTS'];

expect(prompts['api-name'].message).to.equal('API name of the authoring bundle you want to validate.');
expect(prompts['api-name'].promptMessage).to.equal('API name of the authoring bundle to validate');
});
});

describe('command result type', () => {
it('should export correct result type', () => {
const result: AgentValidateAuthoringBundleResult = {
success: true,
};
expect(result.success).to.be.true;
expect(result.errors).to.be.undefined;
});

it('should support error result type', () => {
const result: AgentValidateAuthoringBundleResult = {
success: false,
errors: ['Compilation failed', 'Invalid syntax'],
};
expect(result.success).to.be.false;
expect(result.errors).to.deep.equal(['Compilation failed', 'Invalid syntax']);
});
});

describe('throwAgentCompilationError utility', () => {
it('should throw SfError with compilation errors', () => {
const errors: CompilationError[] = [
{
errorType: 'SyntaxError',
description: 'Invalid syntax',
lineStart: 10,
colStart: 5,
lineEnd: 10,
colEnd: 10,
},
{ errorType: 'SyntaxError', description: 'Unknown error', lineStart: 15, colStart: 1, lineEnd: 15, colEnd: 5 },
];

try {
throwAgentCompilationError(errors);
expect.fail('Expected function to throw an error');
} catch (error) {
expect(error).to.be.instanceOf(SfError);
expect((error as SfError).name).to.equal('CompileAgentScriptError');
expect((error as SfError).message).to.include('SyntaxError: Invalid syntax [Ln 10, Col 5]');
expect((error as SfError).message).to.include('SyntaxError: Unknown error [Ln 15, Col 1]');
}
});

it('should handle empty error array', () => {
try {
throwAgentCompilationError([]);
expect.fail('Expected function to throw an error');
} catch (error) {
expect(error).to.be.instanceOf(SfError);
expect((error as SfError).name).to.equal('CompileAgentScriptError');
expect((error as SfError).message).to.equal('Unknown compilation error occurred');
}
});
});
});
Loading
Loading