Skip to content
Open
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
62 changes: 60 additions & 2 deletions src/commands/template/generate/ui-bundle/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import path from 'node:path';
import fs from 'node:fs/promises';
import { Flags, SfCommand, Ux } from '@salesforce/sf-plugins-core';
import { CreateOutput, UIBundleOptions, TemplateType } from '@salesforce/templates';
import { Messages, SfProject } from '@salesforce/core';
Expand All @@ -15,6 +16,7 @@ Messages.importMessagesDirectoryFromMetaUrl(import.meta.url);
const messages = Messages.loadMessages('@salesforce/plugin-templates', 'ui-bundle.generate');

export const UI_BUNDLES_DIR = 'uiBundles';
const GRAPHQLRC_FILENAME = '.graphqlrc.yml';

export default class UiBundleGenerate extends SfCommand<CreateOutput> {
public static readonly summary = messages.getMessage('summary');
Expand Down Expand Up @@ -62,6 +64,43 @@ export default class UiBundleGenerate extends SfCommand<CreateOutput> {
}
}

/**
* Creates a new `.graphqlrc.yml` at the sfdx project root so the GraphQL LSP extension
* can auto-discover it. The file at the project root references `schema.graphql` as a
* sibling and uses a recursive glob for documents so nested ui-bundle src trees are picked up.
*
* Returns the new file path on success, or undefined when not running inside an sfdx project,
* when the bundle's `.graphqlrc.yml` was not generated, or when a `.graphqlrc.yml` already
* exists at the project root.
*/
private static async createGraphqlrcAtProjectRoot(bundleSourcePath: string): Promise<string | undefined> {
let projectRoot: string;
try {
const project = await SfProject.resolve();
projectRoot = project.getPath();
} catch {
return undefined;
}

try {
await fs.access(bundleSourcePath);
} catch {
return undefined;
}

const targetPath = path.join(projectRoot, GRAPHQLRC_FILENAME);
try {
await fs.access(targetPath);
return undefined;
} catch {
// target does not exist — proceed
}

const content = "schema: 'schema.graphql'\ndocuments: './**/src/**/*.{graphql,js,ts,jsx,tsx}'\n";
await fs.writeFile(targetPath, content);
return targetPath;
}

public async run(): Promise<CreateOutput> {
const { flags } = await this.parse(UiBundleGenerate);

Expand All @@ -75,11 +114,30 @@ export default class UiBundleGenerate extends SfCommand<CreateOutput> {
apiversion: flags['api-version'],
};

return runGenerator({
const ux = new Ux({ jsonEnabled: this.jsonEnabled() });

const result = await runGenerator({
templateType: TemplateType.UIBundle,
opts: flagsAsOptions,
ux: new Ux({ jsonEnabled: this.jsonEnabled() }),
ux,
templates: getCustomTemplates(this.configAggregator),
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Where's the origin of these "CustomTemplates"? what's the difference between adding it here (flags.template below), versus in the reactbasic "customTemplate"?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

@jodarove I'm not familiar with that construct, so here is claude's analysis of it:

getCustomTemplates and this.configAggregator    
                                                                                                                       
  What it does                                                                                                               
                
  getCustomTemplates (src/utils/templateCommand.ts:26-33) is a tiny wrapper that reads a single Salesforce config property — 
  customOrgMetadataTemplates — from the supplied ConfigAggregator. It returns either the configured value (a string,         
  typically a path or git URL pointing to a custom templates source) or undefined if the key isn't set or reading throws.    
                                                                                                                             
  export const getCustomTemplates = (configAggregator: ConfigAggregator): string | undefined => {                            
    try {                                                                                                                    
      return configAggregator.getPropertyValue(OrgConfigProperties.ORG_CUSTOM_METADATA_TEMPLATES) as string;                 
    } catch (err) {                                                                                                          
      return undefined;                                     
    }                                                                                                                        
  };                                                        
                                                                                                                             
  The returned string is forwarded into runGenerator as the templates option, which TemplateService.create(templateType,     
  opts, templates) uses to override the bundled templates with the user's custom set.
                                                                                                                             
  Why it's wrapped in try/catch                                                                                              
   
  configAggregator.getPropertyValue can throw if the property metadata isn't registered or the config layer fails to resolve.
   Swallowing the error to undefined lets TemplateService fall back to the default built-in templates instead of failing the
  whole command.                                                                                                             
                                                            
  How this.configAggregator gets there                                                                                       
   
  this.configAggregator is not something this codebase constructs. It's a lazy-loaded property inherited from SfCommand      
  (which extends oclif's Command). When you read it inside a command class, sf-plugins-core resolves it on demand using
  ConfigAggregator.create() from @salesforce/core, which:                                                                    
                                                            
  1. Loads the global sfdx config (~/.sfdx/sfdx-config.json)                                                                 
  2. Loads the local project config (<project>/.sfdx/sfdx-config.json)
  3. Layers env vars on top                                                                                                  
                                                                                                                             
  Each command in this repo follows the same one-liner pattern at the call site — for example in                             
  src/commands/template/generate/ui-bundle/index.ts:123:                                                                     
                                                                                                                             
  templates: getCustomTemplates(this.configAggregator),     
                                                                                                                             
  So this.configAggregator is the per-command aggregated view of all sf config sources, and getCustomTemplates queries one   
  specific key from it. If the user has set sf config set customOrgMetadataTemplates=<path-or-url>, that value flows through 
  here and overrides the bundled generators; otherwise the call returns undefined and the default templates are used.   

});

if (flags.template === 'reactbasic') {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

in theory, this should be part of all UIBundles, in fact, maybe all of the sfdx projects. the issue is that in lwc ones, we don't pull the schema down.

Note: i would feel more comfortable if we add it for the ones we know and pull the schema.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I had a question regarding the flags.template, according to Charles he said that he would expect it for reactbasic but not default because default is so minimal and unopinionated.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Also, IIUC regarding the graphql schema file, I thought that the graphql.schema pulling happens outside of scope of running the sf cli commands sf template generate ui-bundle, it requires setup or manual calling of the script (or via graphiti CLI now)

  • npm run graphql:schema
  • node scripts/get-graphql-schema.mjs

const bundleSourcePath = path.join(result.outputDir, flags.name, GRAPHQLRC_FILENAME);
const newPath = await UiBundleGenerate.createGraphqlrcAtProjectRoot(bundleSourcePath);
if (newPath) {
const targetRelative = path.relative(process.cwd(), newPath);
const createLine = ` create ${targetRelative}`;
ux.log(createLine);
return {
...result,
created: [...result.created, targetRelative],
rawOutput: `${result.rawOutput.replace(/\n$/, '')}\n${createLine}\n`,
};
}
}

return result;
}
}
72 changes: 68 additions & 4 deletions test/commands/template/generate/ui-bundle/index.nut.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import path from 'node:path';
import fs from 'node:fs';
import { expect } from 'chai';
import { TestSession, execCmd } from '@salesforce/cli-plugins-testkit';
import { nls } from '@salesforce/templates/lib/i18n/index.js';
Expand Down Expand Up @@ -38,6 +39,7 @@ describe('template generate ui-bundle:', () => {
path.join(outputDir, 'MyUiBundle', 'MyUiBundle.uibundle-meta.xml'),
'<masterLabel>My Ui Bundle</masterLabel>'
);
assert.noFile(path.join(projectDir, '.graphqlrc.yml'));
});

it('should default to project uiBundles directory when --output-dir is omitted', () => {
Expand All @@ -64,18 +66,80 @@ describe('template generate ui-bundle:', () => {
});

describe('Check UI bundle creation with reactbasic template', () => {
it('should create React UI bundle with all required files', () => {
afterEach(() => {
const rootGraphqlrc = path.join(projectDir, '.graphqlrc.yml');
if (fs.existsSync(rootGraphqlrc)) {
fs.unlinkSync(rootGraphqlrc);
}
});

it('should create React UI bundle with all required files and create .graphqlrc.yml at the project root', () => {
const outputDir = path.join(projectDir, 'force-app', 'main', 'default', UI_BUNDLES_DIR);
execCmd(`template generate ui-bundle --name MyReactApp --template reactbasic --output-dir "${outputDir}"`, {
ensureExitCode: 0,
});
const firstResult = execCmd(
`template generate ui-bundle --name MyReactApp --template reactbasic --output-dir "${outputDir}"`,
{
ensureExitCode: 0,
}
);
assert.file([
path.join(outputDir, 'MyReactApp', 'MyReactApp.uibundle-meta.xml'),
path.join(outputDir, 'MyReactApp', 'index.html'),
path.join(outputDir, 'MyReactApp', 'ui-bundle.json'),
path.join(outputDir, 'MyReactApp', 'package.json'),
]);
assert.fileContent(path.join(outputDir, 'MyReactApp', 'package.json'), '"name": "base-react-app"');

const rootGraphqlrc = path.join(projectDir, '.graphqlrc.yml');
assert.file(rootGraphqlrc);
assert.fileContent(rootGraphqlrc, "schema: 'schema.graphql'");
assert.fileContent(rootGraphqlrc, "documents: './**/src/**/*.{graphql,js,ts,jsx,tsx}'");
expect(firstResult.shellOutput.stdout).to.contain('create .graphqlrc.yml');

const contentBefore = fs.readFileSync(rootGraphqlrc, 'utf8');
const mtimeBefore = fs.statSync(rootGraphqlrc).mtimeMs;

const secondResult = execCmd(
`template generate ui-bundle --name MyReactApp2 --template reactbasic --output-dir "${outputDir}"`,
{
ensureExitCode: 0,
}
);
assert.file([
path.join(outputDir, 'MyReactApp2', 'MyReactApp2.uibundle-meta.xml'),
path.join(outputDir, 'MyReactApp2', 'package.json'),
]);
expect(secondResult.shellOutput.stdout).to.not.contain('create .graphqlrc.yml');

const contentAfter = fs.readFileSync(rootGraphqlrc, 'utf8');
const mtimeAfter = fs.statSync(rootGraphqlrc).mtimeMs;
expect(contentAfter).to.equal(contentBefore);
expect(mtimeAfter).to.equal(mtimeBefore);
});

it('should write the same project-root .graphqlrc.yml regardless of bundle output-dir', () => {
const outputDir = path.join(projectDir, 'force-app', 'main', 'default', 'custom-dir');
execCmd(
`template generate ui-bundle --name CustomDirReactApp --template reactbasic --output-dir "${outputDir}"`,
{
ensureExitCode: 0,
}
);
assert.file(path.join(projectDir, '.graphqlrc.yml'));
assert.fileContent(path.join(projectDir, '.graphqlrc.yml'), "schema: 'schema.graphql'");
assert.fileContent(path.join(projectDir, '.graphqlrc.yml'), "documents: './**/src/**/*.{graphql,js,ts,jsx,tsx}'");
});

it('should not overwrite an existing .graphqlrc.yml at the project root', () => {
const outputDir = path.join(projectDir, 'force-app', 'main', 'default', UI_BUNDLES_DIR);
const rootGraphqlrc = path.join(projectDir, '.graphqlrc.yml');
const preexisting = "schema: 'preexisting.graphql'\ndocuments: 'preexisting/**/*.ts'\n";
fs.writeFileSync(rootGraphqlrc, preexisting);

execCmd(`template generate ui-bundle --name SecondReactApp --template reactbasic --output-dir "${outputDir}"`, {
ensureExitCode: 0,
});

assert.fileContent(rootGraphqlrc, "schema: 'preexisting.graphql'");
});
});

Expand Down