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
4 changes: 3 additions & 1 deletion .node-scripts/validate-changed-package-versions.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ function getLatestReleasedVersion(changedPackage) {

function isPackageThatHasNotPublished(changedPackage) {
return [
"packages/ENGINE-TEMPLATE"
"packages/ENGINE-TEMPLATE",
// TODO: remove once @salesforce/code-analyzer-uibundle-engine is published to npm (W-23659201)
"packages/code-analyzer-uibundle-engine"
].includes(changedPackage.replace("\\","/"));
}

Expand Down
1,538 changes: 411 additions & 1,127 deletions package-lock.json

Large diffs are not rendered by default.

14 changes: 14 additions & 0 deletions packages/code-analyzer-uibundle-engine/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
BSD 3-Clause License

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is the license file present for all engines ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

yes, it seems like other engines have this too


Copyright (c) 2024, Salesforce.com, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Salesforce.com nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
16 changes: 16 additions & 0 deletions packages/code-analyzer-uibundle-engine/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';

export default tseslint.config(
eslint.configs.recommended,
...tseslint.configs.recommended,
{
rules: {
"@typescript-eslint/no-unused-vars": ["error", {
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"caughtErrorsIgnorePattern": "^_"
}]
}
}
);
69 changes: 69 additions & 0 deletions packages/code-analyzer-uibundle-engine/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"name": "@salesforce/code-analyzer-uibundle-engine",
"description": "Plugin package that adds the 'uibundle' engine into Salesforce Code Analyzer. Validates UI Bundle build-output integrity — currently ships sourcemap-based verification of each shipped dist/ artifact against its declared sourcemap and the submitted src/ tree.",
"version": "0.1.0-SNAPSHOT",
"author": "The Salesforce Code Analyzer Team",
"license": "BSD-3-Clause",
"homepage": "https://developer.salesforce.com/docs/platform/salesforce-code-analyzer/overview",
"repository": {
"type": "git",
"url": "git+https://github.com/forcedotcom/code-analyzer-core.git",
"directory": "packages/code-analyzer-uibundle-engine"
},
"main": "dist/index.js",
"types": "dist/index.d.ts",
"dependencies": {
"@babel/parser": "^7.25.0",
"@babel/traverse": "^7.25.0",
"@babel/types": "^7.25.0",
"@jridgewell/sourcemap-codec": "^1.5.5",
"@jridgewell/trace-mapping": "^0.3.31",
"@salesforce/code-analyzer-engine-api": "0.42.0-SNAPSHOT",
"@types/node": "^20.0.0"
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"@types/babel__traverse": "^7.28.0",
"@types/jest": "^30.0.0",
"eslint": "^9.39.5",
"jest": "^30.4.2",
"rimraf": "^6.1.3",
"ts-jest": "^29.4.11",
"typescript": "^5.9.3",
"typescript-eslint": "^8.64.0"
},
"engines": {
"node": ">=20.0.0"
},
"files": [
"dist",
"LICENSE",
"package.json"
],
"scripts": {
"build": "tsc --build tsconfig.build.json --verbose",
"test": "tsc --build tsconfig.json && jest --coverage",
"lint": "eslint src/**/*.ts",
"package": "npm pack",
"all": "npm run build && npm run lint && npm run test && npm run package",
"clean": "tsc --build tsconfig.build.json --clean",
"postclean": "rimraf dist && rimraf coverage && rimraf ./*.tgz && rimraf vulnerabilities",
"scrub": "npm run clean && rimraf node_modules",
"showcoverage": "open ./coverage/lcov-report/index.html"
},
"jest": {
"preset": "ts-jest",
"testEnvironment": "node",
"testMatch": [
"**/*.test.ts"
],
"testPathIgnorePatterns": [
"/node_modules/",
"/dist/"
],
"collectCoverageFrom": [
"src/**/*.ts",
"!src/index.ts"
]
}
}
214 changes: 214 additions & 0 deletions packages/code-analyzer-uibundle-engine/src/engine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
import path from "node:path";
import * as fsp from "node:fs/promises";
import {
Engine,
LogLevel,
type DescribeOptions,
type EngineRunResults,
type RuleDescription,
type RunOptions,
type Violation,
} from "@salesforce/code-analyzer-engine-api";
import { RULES, RULE_NAMES } from "./rules";
import {
COVERAGE_ANALYSIS_RULE,
validateCoverageAnalysis,
} from "./validators/coverage-analysis";
import {
INVALID_SOURCE_REFERENCES_RULE,
validateInvalidSourceReferences,
} from "./validators/invalid-source-references";
import {
MISSING_SOURCEMAP_RULE,
validateMissingSourcemaps,
} from "./validators/missing-sourcemap";
import { PATH_LEAKAGE_RULE, validatePathLeakage } from "./validators/path-leakage";
import {
SOURCE_CONTENT_VERIFICATION_RULE,
validateSourceContent,
} from "./validators/source-content-verification";
import {
STRUCTURAL_COHERENCE_RULE,
validateStructuralCoherence,
} from "./validators/structural-coherence";
import {
TOKEN_CONSISTENCY_RULE,
validateTokenConsistency,
} from "./validators/token-consistency";
import { buildSourceIndex, type SourceIndex } from "./validators/sourcemap-io";
import type { ValidatorFinding, ValidatorResult } from "./validators/types";
import { VLQ_INTEGRITY_RULE, validateVlqIntegrity } from "./validators/vlq-integrity";
import { getMessage } from "./messages";

interface BundleTarget {
distPath: string;
sourcePath: string | null;
}

export class UIBundleEngine extends Engine {
static readonly NAME = "uibundle";

getName(): string {
return UIBundleEngine.NAME;
}

async getEngineVersion(): Promise<string> {
const pathToPackageJson: string = path.join(__dirname, '..', 'package.json');
const packageJson: {version: string} = JSON.parse(await fsp.readFile(pathToPackageJson, 'utf-8'));
return packageJson.version;
}

async describeRules(_describeOptions: DescribeOptions): Promise<RuleDescription[]> {
return [...RULES];
}

async runRules(ruleNames: string[], runOptions: RunOptions): Promise<EngineRunResults> {
const selected: string[] = ruleNames.filter((name) => RULE_NAMES.has(name));
if (selected.length === 0) return { violations: [] };

const targets: BundleTarget[] = await this.findBundleTargets(runOptions);
if (targets.length === 0) {
this.emitLogEvent(LogLevel.Info, getMessage('NoBundleTargetsFound', UIBundleEngine.NAME));
return { violations: [] };
}

const violations: Violation[] = [];
for (const target of targets) {
await this.runOnTarget(target, selected, violations);
}
return { violations };
}

private async runOnTarget(
target: BundleTarget,
selected: string[],
violations: Violation[],
): Promise<void> {
const distOnlyDispatch: [string, () => Promise<ValidatorResult>][] = [
[MISSING_SOURCEMAP_RULE, () => validateMissingSourcemaps(target.distPath)],
[PATH_LEAKAGE_RULE, () => validatePathLeakage(target.distPath)],
[INVALID_SOURCE_REFERENCES_RULE, () => validateInvalidSourceReferences(target.distPath)],
[VLQ_INTEGRITY_RULE, () => validateVlqIntegrity(target.distPath)],
[COVERAGE_ANALYSIS_RULE, () => validateCoverageAnalysis(target.distPath)],
];

for (const [ruleName, runValidator] of distOnlyDispatch) {
if (!selected.includes(ruleName)) continue;
const result: ValidatorResult = await runValidator();
this.consumeResult(ruleName, target.distPath, result, violations);
}

const sourceDispatch: [
string,
(opts: {
sourcePath: string;
distPath: string;
sourceIndex?: SourceIndex;
}) => Promise<ValidatorResult>,
][] = [
[SOURCE_CONTENT_VERIFICATION_RULE, validateSourceContent],
[STRUCTURAL_COHERENCE_RULE, validateStructuralCoherence],
[TOKEN_CONSISTENCY_RULE, validateTokenConsistency],
];

const activeSourceRules = sourceDispatch.filter(([r]) => selected.includes(r));
if (activeSourceRules.length === 0) return;

if (!target.sourcePath) {
for (const [ruleName] of activeSourceRules) {
this.emitLogEvent(
LogLevel.Warn,
getMessage('SkippedNoSourceTree', UIBundleEngine.NAME, ruleName, target.distPath),
);
}
return;
}

const sourceIndex: SourceIndex = await buildSourceIndex(target.sourcePath);

for (const [ruleName, runValidator] of activeSourceRules) {
const result: ValidatorResult = await runValidator({
sourcePath: target.sourcePath,
distPath: target.distPath,
sourceIndex,
});
this.consumeResult(ruleName, target.distPath, result, violations);
}
}

private consumeResult(
ruleName: string,
distPath: string,
result: ValidatorResult,
violations: Violation[],
): void {
if (result.skipped) {
this.emitLogEvent(
LogLevel.Warn,
getMessage('SkippedForTarget', UIBundleEngine.NAME, ruleName, distPath, result.skipped.reason),
);
return;
}
for (const finding of result.findings) {
violations.push(toViolation(finding));
}
}

private async findBundleTargets(runOptions: RunOptions): Promise<BundleTarget[]> {
const targetedFiles: string[] = await runOptions.workspace.getTargetedFiles();

const bundleRoots: Set<string> = new Set();
for (const file of targetedFiles) {
const base = path.basename(file);
if (base === "ui-bundle.json" || base.endsWith(".uibundle-meta.xml")) {
bundleRoots.add(path.dirname(file));
}
}

for (const file of targetedFiles) {
const dist = findAncestorNamed(file, "dist");
if (dist) bundleRoots.add(path.dirname(dist));
}

const targets: BundleTarget[] = [];
for (const bundleRoot of bundleRoots) {
const distPath = path.join(bundleRoot, "dist");
if (!(await isDirectory(distPath))) continue;

const srcPath = path.join(bundleRoot, "src");
const sourcePath = (await isDirectory(srcPath)) ? srcPath : null;

targets.push({ distPath, sourcePath });
}
return targets;
}
}

function toViolation(finding: ValidatorFinding): Violation {
// SFCA requires 1-based line/column; validators emit 0-based columns.
const startLine: number = Math.max(1, finding.startLine ?? 1);
const rawCol: number | undefined = finding.startColumn;
const startColumn: number = rawCol == null ? 1 : Math.max(1, rawCol + 1);
return {
ruleName: finding.ruleName,
message: finding.message,
primaryLocationIndex: 0,
codeLocations: [{ file: finding.file, startLine, startColumn }],
};
}

async function isDirectory(p: string): Promise<boolean> {
try {
const stat = await fsp.stat(p);
return stat.isDirectory();
} catch {
return false;
}
}

function findAncestorNamed(filePath: string, name: string): string | null {
const parts = filePath.split(path.sep);
const lastNameSegmentIdx = parts.lastIndexOf(name);
if (lastNameSegmentIdx <= 0) return null;
return parts.slice(0, lastNameSegmentIdx + 1).join(path.sep);
}
8 changes: 8 additions & 0 deletions packages/code-analyzer-uibundle-engine/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { EnginePlugin } from "@salesforce/code-analyzer-engine-api";
import { UIBundleEnginePlugin } from "./plugin";

function createEnginePlugin(): EnginePlugin {
return new UIBundleEnginePlugin();
}

export { createEnginePlugin, UIBundleEnginePlugin };
Loading
Loading