Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update license Component for Github SBOM #9755

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from

Conversation

DonXavierdev
Copy link
Contributor

@DonXavierdev DonXavierdev commented Jan 5, 2025

Proposed Changes

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Implemented dynamic SBOM data fetching using react-query.
    • Added internationalization support for the SBOM viewer.
    • Enhanced error handling and loading states for data retrieval.
  • Chores

    • Updated postinstall script to fetch SBOM data automatically.
    • Added new localization keys for SBOM-related terminology.
  • Documentation

    • Improved user feedback messages during data loading.
    • Replaced hardcoded strings with translatable text.

@DonXavierdev DonXavierdev requested a review from a team as a code owner January 5, 2025 08:13
Copy link
Contributor

coderabbitai bot commented Jan 5, 2025

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

💤 Files selected but had no reviewable changes (1)
  • public/licenses/.gitkeep

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces a comprehensive update to the Software Bill of Materials (SBOM) viewer component, focusing on dynamically fetching SBOM data from GitHub repositories. The changes include implementing a new script to fetch SBOM data, integrating react-query for data retrieval, adding internationalization support, and modifying the component to work with dynamically loaded JSON files. The .gitignore file has been updated to exclude the newly generated SBOM JSON files.

Changes

File Change Summary
src/components/Licenses/SBOMViewer.tsx - Integrated react-query for dynamic data fetching
- Added useTranslation for internationalization
- Implemented fetchJsonData function
- Updated rendering logic to handle loading and error states
.gitignore Added entries for public/licenses/beBomData.json and public/licenses/feBomData.json
package.json Updated postinstall script to include fetchSbomData.ts execution
public/locale/en.json Added new translation keys for SBOM-related terminology
Modified copied_to_clipboard message
scripts/fetchSbomData.ts New script to fetch SBOM data from GitHub repositories
Implemented error handling and data writing functionality

Assessment against linked issues

Objective Addressed Explanation
Use GitHub-provided SBOMs
Replace manually generated JSON files
Streamline license page maintenance

Poem

🐰 Hop, hop, through GitHub's green domain,
SBOMs dancing, no more manual strain!
Queries fetch, translations shine bright,
Dependencies mapped with rabbit delight!
Code evolves, simplicity takes flight! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Jan 5, 2025

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 905272f
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6783a7769b2ce600081170d6
😎 Deploy Preview https://deploy-preview-9755--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (7)
src/components/Licenses/SBOMViewer.tsx (7)

52-66: Consider more robust error handling.
Currently, any fetch failure logs an error to the console and returns null. Think about handling errors more gracefully in the UI, for instance by showing a user-facing alert or fallback message.


86-86: Tab naming could be more descriptive.
Using "bom" vs "beBom" might be confusing. Renaming them to “frontendBom” / “backendBom” can improve clarity.


118-118: Consider displaying additional SBOM metadata.
Alongside spdxVersion, you might also display the dataLicense or other relevant metadata for a more comprehensive SBOM overview.


131-131: Use stable keys when rendering lists.
Consider using a unique identifier from each package (e.g., pkg.SPDXID or pkg.name) instead of the array index for improved React performance.


137-137: Commented-out externalRefs link.
This might be leftover debug code or a temporary workaround. Consider removing or adding a rationale comment if intentionally disabled.


150-150: Fallback anchor for unrecognized license IDs.
Navigating to "#" might not provide user feedback. Consider a placeholder page or tooltip to clarify no recognized license URL is available.


172-172: Consider stable keys for external references.
Using idx as the key can lead to React diffing issues if references change order. Prefer a unique property from each reference, if available.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4850743 and 385c8b4.

📒 Files selected for processing (1)
  • src/components/Licenses/SBOMViewer.tsx (3 hunks)
🔇 Additional comments (14)
src/components/Licenses/SBOMViewer.tsx (14)

2-2: Imports look good.
The newly added import for React hooks is appropriate and aligns with best practices in functional components.


15-27: Validate optional fields for GitHubPackage.
All fields in this interface appear to match the GitHub SBOM format. Consider verifying whether any additional fields from GitHub’s SBOM API may need to be included or marked optional for better type safety.


30-41: Interface structure aligns with GitHub SBOM data.
It’s good that each property is optional, preventing runtime errors when the SBOM might be missing certain fields.


49-51: Separate state variables for frontend and backend SBOM.
Assigning each SBOM to its own state variable is clear and logical.


68-85: Concise async loading for both FE/BE.
Fetching FE and BE SBOM data in parallel is efficient. If partial fetch success is acceptable (only one resource might load), confirm that null states are handled correctly in the UI.


93-93: Array fallback for safe rendering.
The usage of || [] ensures no errors when bomData or sbom is null. Nice defensive coding.


122-123: Date formatting is handled gracefully.
Falling back to "N/A" if a date is missing ensures the UI won’t break.


129-129: Package header is clear.
Labeling this section is helpful in guiding the user to the package list.


143-143: Package name and version.
Displaying both name and version in the same heading is user-friendly and concise.


146-146: Conditional rendering of the license.
Filtering out packages without a licenseConcluded field reduces UI clutter. Implementation is clear.


155-155: License fallback "N/A."
Good to maintain a sensible default text if the license field is somehow empty.


175-175: External reference link fallback.
If referenceLocator is missing, a fallback of "#" prevents errors. This maintains a functioning UI.


178-178: Optional reference locator text.
Gracefully handles missing locator content by providing "N/A."


180-182: Category display is optional.
The checks for ref.referenceCategory and ref.referenceLocator align with the optional nature of external references.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
scripts/fetchSbomData.js (1)

49-49: Add proper error handling for unhandled rejections.

The script should handle unhandled promise rejections properly.

Add this error handling:

+process.on('unhandledRejection', (error) => {
+  console.error('Unhandled promise rejection:', error);
+  process.exit(1);
+});
+
 fetchData();
src/components/Licenses/SBOMViewer.tsx (1)

Line range hint 134-157: Add error handling for clipboard operations.

The clipboard functionality should handle potential errors.

-  const handleCopy = () => {
+  const handleCopy = (text: string, result: boolean) => {
+    if (!result) {
+      console.error('Failed to copy to clipboard');
+      return;
+    }
     setCopyStatus(true);
     setTimeout(() => setCopyStatus(false), 2000);
   };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 385c8b4 and 13852f0.

📒 Files selected for processing (4)
  • .gitignore (1 hunks)
  • package.json (1 hunks)
  • scripts/fetchSbomData.js (1 hunks)
  • src/components/Licenses/SBOMViewer.tsx (4 hunks)
🧰 Additional context used
🪛 GitHub Actions: Lint Code Base
package.json

[warning] Node.js version incompatibility - Required: >=22.8.0, Current: v20.18.1


[warning] Multiple deprecated package dependencies: sourcemap-codec, rimraf, npmlog, inflight, gauge, are-we-there-yet, boolean, @humanwhocodes/config-array, @humanwhocodes/object-schema, glob, eslint

scripts/fetchSbomData.js

[error] 1-1: Cannot use import statement outside a module. Need to set "type": "module" in package.json or use .mjs extension

🔇 Additional comments (5)
.gitignore (1)

68-70: LGTM! Appropriate entries added to .gitignore.

The new entries correctly exclude the generated SBOM data files from version control.

src/components/Licenses/SBOMViewer.tsx (2)

1-13: LGTM! Good implementation of i18n and SBOM data imports.

The changes properly implement internationalization and correctly update the SBOM data imports to use the new GitHub SBOM format.


Line range hint 34-133: LGTM! Well-structured UI with proper i18n implementation.

The UI components are well-organized with proper internationalization of all strings and good TypeScript/React patterns.

package.json (2)

38-38: LGTM! Appropriate addition to postinstall script.

The script is correctly added to run after platform dependencies are installed.

🧰 Tools
🪛 GitHub Actions: Lint Code Base

[warning] Node.js version incompatibility - Required: >=22.8.0, Current: v20.18.1


[warning] Multiple deprecated package dependencies: sourcemap-codec, rimraf, npmlog, inflight, gauge, are-we-there-yet, boolean, @humanwhocodes/config-array, @humanwhocodes/object-schema, glob, eslint


Line range hint 1-1: Update Node.js version and deprecated dependencies.

The pipeline shows several issues that need attention:

  1. Node.js version incompatibility (required >=22.8.0, current v20.18.1)
  2. Multiple deprecated package dependencies

Please update the Node.js version in your CI environment and update the following deprecated packages:

  • sourcemap-codec
  • rimraf
  • npmlog
  • inflight
  • gauge
  • are-we-there-yet
  • boolean
  • @humanwhocodes/config-array
  • @humanwhocodes/object-schema
  • glob
  • eslint

Run this script to check for the latest versions:

🧰 Tools
🪛 GitHub Actions: Lint Code Base

[warning] Node.js version incompatibility - Required: >=22.8.0, Current: v20.18.1


[warning] Multiple deprecated package dependencies: sourcemap-codec, rimraf, npmlog, inflight, gauge, are-we-there-yet, boolean, @humanwhocodes/config-array, @humanwhocodes/object-schema, glob, eslint

Comment on lines 1 to 15
import fs from "fs";
import fetch from "node-fetch";

const fetchSBOMData = async (url) => {
const response = await fetch(url, {
headers: {
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
});
if (!response.ok) {
throw new Error(`Error fetching SBOM data from ${url}`);
}
return await response.json();
};
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix ESM compatibility and add GitHub authentication.

The code has several issues that need to be addressed:

  1. ES modules syntax requires "type": "module" in package.json
  2. GitHub API calls should use authentication to avoid rate limiting
  3. API version should be configurable for future compatibility

Apply these changes:

+// Add to package.json
+{
+  "type": "module"
+}

 import fs from "fs";
 import fetch from "node-fetch";
+import dotenv from "dotenv";
+
+dotenv.config();
+
+const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
 
 const fetchSBOMData = async (url) => {
   const response = await fetch(url, {
     headers: {
       Accept: "application/vnd.github+json",
+      Authorization: `Bearer ${GITHUB_TOKEN}`,
       "X-GitHub-Api-Version": "2022-11-28",
     },
   });

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 GitHub Actions: Lint Code Base

[error] 1-1: Cannot use import statement outside a module. Need to set "type": "module" in package.json or use .mjs extension

scripts/fetchSbomData.js Outdated Show resolved Hide resolved
Comment on lines 25 to 32
const bomData = activeTab === "bom" ? feBomData : beBomData;

const handleCopy = () => {
setCopyStatus(true);
setTimeout(() => setCopyStatus(false), 2000);
};

const bomData = (activeTab === "bom" ? feBomData : beBomData) as CycloneDXBOM;
const packages = bomData?.sbom?.packages || [];
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add TypeScript interfaces for the GitHub SBOM format.

The code lacks type definitions for the new GitHub SBOM format, which could lead to runtime errors.

Add these type definitions:

interface GitHubSBOM {
  sbom: {
    spdxVersion: string;
    creationInfo: {
      created: string;
    };
    packages: Array<{
      name: string;
      versionInfo?: string;
      licenseConcluded?: string;
      externalRefs?: Array<{
        referenceLocator?: string;
        referenceCategory?: string;
      }>;
    }>;
  };
}

const bomData = (activeTab === "bom" ? feBomData : beBomData) as GitHubSBOM;
const packages = bomData?.sbom?.packages || [];

Copy link
Member

Choose a reason for hiding this comment

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

let's keep the script in typescript similar to the other postinstall script

@@ -187,12 +144,12 @@ const BOMDisplay: React.FC = () => {
onCopy={handleCopy}
>
<button className="text-md hover:bg-primary-dark w-full rounded-md bg-primary px-4 py-2 text-white transition-all duration-300 focus:outline-none md:w-auto">
Copy BOM JSON
{t("Copy BOM JSON")}
Copy link
Member

Choose a reason for hiding this comment

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

this is not the way to add translations. see how other translations are done

.gitignore Outdated
Comment on lines 69 to 70
src/components/Licenses/feBomData.json
Copy link
Member

Choose a reason for hiding this comment

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

let's keep this inside the public dir. instead.

(we'd also be able to access it by care.ohc.network/licenses/backend|frontend.json)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
src/components/Licenses/SBOMViewer.tsx (1)

Line range hint 102-153: Add TypeScript interfaces for the GitHub SBOM format.

Define proper TypeScript interfaces to improve type safety and code maintainability.

interface ExternalRef {
  referenceLocator?: string;
  referenceCategory?: string;
}

interface Package {
  name?: string;
  versionInfo?: string;
  licenseConcluded?: string;
  externalRefs?: ExternalRef[];
}

interface GitHubSBOM {
  sbom: {
    spdxVersion: string;
    creationInfo: {
      created: string;
    };
    packages: Package[];
  };
}

Extract package card into a separate component.

Consider extracting the package display logic into a reusable component to improve code organization and maintainability.

interface PackageCardProps {
  pkg: Package;
  index: number;
  showExternalRefs: number | null;
  onToggleRefs: (index: number) => void;
}

const PackageCard: React.FC<PackageCardProps> = ({
  pkg,
  index,
  showExternalRefs,
  onToggleRefs,
}) => {
  const { t } = useTranslation();
  return (
    <div className="block rounded-md border p-2 transition-all duration-300 hover:shadow-lg">
      {/* ... existing package card JSX ... */}
    </div>
  );
};
🧹 Nitpick comments (6)
src/components/Licenses/SBOMViewer.tsx (3)

17-21: Enhance error handling in fetchJsonData function.

The error handling could be more informative by including the HTTP status code and response details.

 const fetchJsonData = async (url: string) => {
   const response = await fetch(url);
-  if (!response.ok) throw new Error("Failed to fetch data");
+  if (!response.ok) {
+    throw new Error(
+      `Failed to fetch data: ${response.status} ${response.statusText}`
+    );
+  }
   return response.json();
 };

29-45: Add retry and caching configuration to useQuery hooks.

Consider adding retry and caching configurations to improve the data fetching reliability and performance.

 const {
   data: feBomData,
   isLoading: feBomLoading,
   error: feBomError,
 } = useQuery({
   queryKey: ["feBomData"],
   queryFn: () => fetchJsonData("/licenses/feBomData.json"),
+  retry: 2,
+  staleTime: 5 * 60 * 1000, // 5 minutes
+  cacheTime: 30 * 60 * 1000, // 30 minutes
 });

58-60: Enhance error state display.

Consider providing more detailed error information to help users understand and report issues.

-    return <div>{t("error_404")}</div>;
+    return (
+      <div className="text-red-600">
+        <div>{t("error_404")}</div>
+        <div className="text-sm mt-2">
+          {feBomError?.message || beBomError?.message}
+        </div>
+      </div>
+    );
scripts/fetchSbomData.ts (3)

1-2: Consider using native fetch API instead of node-fetch

The native fetch API is now available in Node.js versions >= 18.0.0. Consider using it instead of the node-fetch package to reduce dependencies.

-import fetch from "node-fetch";

4-7: Strengthen the SBOMData interface typing

The current interface is too permissive with Record<string, unknown>. Consider defining more specific types based on the actual SBOM data structure from GitHub's API.

interface SBOMData {
  sbom: {
    metadata: {
      version: string;
      tools: Array<{
        name: string;
        version: string;
      }>;
    };
    components: Array<{
      name: string;
      version: string;
      licenses?: Array<{
        license: {
          id: string;
        };
      }>;
    }>;
  };
}

62-62: Improve script execution with proper error handling

Add proper process handling and success/failure indication.

-fetchData();
+fetchData()
+  .then(() => {
+    console.log('Successfully fetched and saved SBOM data');
+    process.exit(0);
+  })
+  .catch((error) => {
+    console.error('Failed to fetch SBOM data:', error);
+    process.exit(1);
+  });
+
+// Handle unexpected errors
+process.on('unhandledRejection', (error) => {
+  console.error('Unhandled rejection:', error);
+  process.exit(1);
+});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 13852f0 and 6ad0ee5.

📒 Files selected for processing (5)
  • .gitignore (1 hunks)
  • package.json (1 hunks)
  • public/locale/en.json (6 hunks)
  • scripts/fetchSbomData.ts (1 hunks)
  • src/components/Licenses/SBOMViewer.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • .gitignore
  • package.json
🔇 Additional comments (2)
public/locale/en.json (1)

473-474: LGTM! All required translations are present.

The translations for the SBOM viewer component have been properly added and are consistent with the component's usage.

Also applies to: 1090-1090, 1185-1185, 1297-1297, 1662-1662

scripts/fetchSbomData.ts (1)

13-28: ⚠️ Potential issue

Add GitHub authentication and improve error handling

  1. GitHub API has rate limits for unauthenticated requests. Add authentication using a GitHub token.
  2. Implement retry logic for transient failures.
  3. Add more specific error handling based on HTTP status codes.

Apply these improvements:

 const fetchSBOMData = async (url: string): Promise<SBOMData> => {
+  const MAX_RETRIES = 3;
+  const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
+
+  if (!GITHUB_TOKEN) {
+    throw new Error('GITHUB_TOKEN environment variable is required');
+  }
+
+  for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
     const response = await fetch(url, {
       headers: {
         Accept: "application/vnd.github+json",
         "X-GitHub-Api-Version": "2022-11-28",
+        Authorization: `Bearer ${GITHUB_TOKEN}`,
       },
     });

     if (!response.ok) {
+      if (response.status === 429) {
+        const retryAfter = response.headers.get('Retry-After');
+        await new Promise(resolve => 
+          setTimeout(resolve, (retryAfter ? parseInt(retryAfter) : 60) * 1000)
+        );
+        continue;
+      }
+
+      if (attempt === MAX_RETRIES) {
         const error: FetchError = new Error(`Error fetching SBOM data from ${url}`);
         error.response = response;
         throw error;
+      }
+
+      await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
+      continue;
     }

     return (await response.json()) as SBOMData;
+  }
+
+  throw new Error(`Failed to fetch SBOM data after ${MAX_RETRIES} attempts`);
 };

Comment on lines 30 to 60
const fetchData = async (): Promise<void> => {
const feUrl =
"https://api.github.com/repos/ohcnetwork/care_fe/dependency-graph/sbom";
const beUrl =
"https://api.github.com/repos/ohcnetwork/care/dependency-graph/sbom";

try {
const [frontendData, backendData] = await Promise.all([
fetchSBOMData(feUrl),
fetchSBOMData(beUrl),
]);

// Write frontend SBOM data
fs.writeFileSync(
"./public/licenses/feBomData.json",
JSON.stringify(frontendData, null, 2),
);

// Write backend SBOM data
fs.writeFileSync(
"./public/licenses/beBomData.json",
JSON.stringify(backendData, null, 2),
);
} catch (error) {
if (error instanceof Error) {
console.error("Error fetching SBOM data:", error.message);
} else {
console.error("Unknown error occurred while fetching SBOM data");
}
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve robustness of file operations and error handling

  1. Ensure target directory exists before writing files
  2. Validate received data before writing
  3. Add more informative error logging
 const fetchData = async (): Promise<void> => {
   const feUrl =
     "https://api.github.com/repos/ohcnetwork/care_fe/dependency-graph/sbom";
   const beUrl =
     "https://api.github.com/repos/ohcnetwork/care/dependency-graph/sbom";

+  const outputDir = "./public/licenses";
+
+  // Ensure directory exists
+  if (!fs.existsSync(outputDir)) {
+    fs.mkdirSync(outputDir, { recursive: true });
+  }
+
   try {
     const [frontendData, backendData] = await Promise.all([
       fetchSBOMData(feUrl),
       fetchSBOMData(beUrl),
     ]);

+    // Validate received data
+    if (!frontendData?.dependencies || !backendData?.dependencies) {
+      throw new Error('Invalid SBOM data received');
+    }
+
     // Write frontend SBOM data
     fs.writeFileSync(
-      "./public/licenses/feBomData.json",
+      `${outputDir}/feBomData.json`,
       JSON.stringify(frontendData, null, 2),
     );

     // Write backend SBOM data
     fs.writeFileSync(
-      "./public/licenses/beBomData.json",
+      `${outputDir}/beBomData.json`,
       JSON.stringify(backendData, null, 2),
     );
   } catch (error) {
     if (error instanceof Error) {
-      console.error("Error fetching SBOM data:", error.message);
+      console.error("Error processing SBOM data:", {
+        message: error.message,
+        stack: error.stack,
+        ...(error as FetchError).response && {
+          status: (error as FetchError).response?.status,
+          statusText: (error as FetchError).response?.statusText,
+        },
+      });
     } else {
       console.error("Unknown error occurred while fetching SBOM data");
     }
+    process.exit(1);
   }
 };

Committable suggestion skipped: line range outside the PR's diff.

@@ -1273,7 +1278,7 @@
"moving_camera": "Moving Camera",
"my_doctors": "My Doctors",
"my_profile": "My Profile",
"my_schedules": "My Schedules",
Copy link
Member

Choose a reason for hiding this comment

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

why was this translation deleted?

Comment on lines 4 to 7
interface SBOMData {
dependencies?: Record<string, unknown>;
[key: string]: unknown; // Add more specific fields if known
}
Copy link
Member

Choose a reason for hiding this comment

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

are you sure the type is right? I don't see any dependencies keyword in the API's response.

You can use tools like JSON to TypeScript to easily generate types from JSON.

https://transform.tools/json-to-typescript

Suggested change
interface SBOMData {
dependencies?: Record<string, unknown>;
[key: string]: unknown; // Add more specific fields if known
}
interface GitHubSbomApiResponse {
sbom: {
spdxVersion: string
dataLicense: string
SPDXID: string
name: string
documentNamespace: string
creationInfo: {
creators: string[]
created: string
}
packages: {
name: string
SPDXID: string
versionInfo: string
downloadLocation: string
filesAnalyzed: boolean
licenseConcluded?: string
copyrightText?: string
externalRefs: {
referenceCategory: string
referenceType: string
referenceLocator: string
}[]
licenseDeclared?: string
}[]
relationships: {
spdxElementId: string
relatedSpdxElement: string
relationshipType: string
}[]
}
}

Comment on lines 31 to 34
const feUrl =
"https://api.github.com/repos/ohcnetwork/care_fe/dependency-graph/sbom";
const beUrl =
"https://api.github.com/repos/ohcnetwork/care/dependency-graph/sbom";
Copy link
Member

Choose a reason for hiding this comment

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

nitpick: let's store this globally as constants instead of keeping it inside the function.

response?: Response;
}

const fetchSBOMData = async (url: string): Promise<SBOMData> => {
Copy link
Member

Choose a reason for hiding this comment

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

we've decided to follow this naming convention for abbrevs. in new code

Suggested change
const fetchSBOMData = async (url: string): Promise<SBOMData> => {
const fetchSbomData = async (url: string): Promise< GitHubSbomApiResponse > => {

Comment on lines 53 to 59
} catch (error) {
if (error instanceof Error) {
console.error("Error fetching SBOM data:", error.message);
} else {
console.error("Unknown error occurred while fetching SBOM data");
}
}
Copy link
Member

Choose a reason for hiding this comment

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

let's not try catch. let the build fail instead

@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Jan 12, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
scripts/fetchSbomData.ts (1)

60-75: ⚠️ Potential issue

Address pipeline failures by ensuring directory exists.

The pipeline is failing because the target directory doesn't exist. This was addressed in a previous review but the changes weren't applied.

 const fetchData = async (): Promise<void> => {
+  const outputDir = "./public/licenses";
+
+  // Ensure directory exists
+  if (!fs.existsSync(outputDir)) {
+    fs.mkdirSync(outputDir, { recursive: true });
+  }
+
   const [frontendData, backendData] = await Promise.all([
-    fetchSBOMData(FE_SBOM_URL),
-    fetchSBOMData(BE_SBOM_URL),
+    fetchSbomData(FE_SBOM_URL),
+    fetchSbomData(BE_SBOM_URL),
   ]);

   fs.writeFileSync(
-    "./public/licenses/feBomData.json",
+    `${outputDir}/feBomData.json`,
     JSON.stringify(frontendData, null, 2),
   );

   fs.writeFileSync(
-    "./public/licenses/beBomData.json",
+    `${outputDir}/beBomData.json`,
     JSON.stringify(backendData, null, 2),
   );
 };
🧰 Tools
🪛 GitHub Actions: Lint Code Base

[error] 66-66: Failed to write to feBomData.json during postinstall script execution

🪛 GitHub Actions: Cypress Tests

[error] 66-66: Failed to write to './public/licenses/feBomData.json' - directory does not exist (ENOENT error)

🪛 GitHub Actions: Deploy Care Fe

[error] 66-66: Failed to write to './public/licenses/feBomData.json': directory does not exist

🧹 Nitpick comments (2)
public/locale/en.json (1)

651-653: Consider using sentence case for consistency.

While the changes are functionally correct, consider using sentence case for "BOM JSON" to match the style of other UI elements (e.g., "Bom Json").

-  "copy_bom_json": "Copy BOM JSON",
+  "copy_bom_json": "Copy Bom Json",
scripts/fetchSbomData.ts (1)

46-47: Consider making API version configurable.

The GitHub API version is hardcoded. Consider moving it to a configuration file or environment variable for easier updates.

+const GITHUB_API_VERSION = "2022-11-28";
+
 const fetchSbomData = async (url: string): Promise<GitHubSbomApiResponse> => {
   const response = await fetch(url, {
     headers: {
       Accept: "application/vnd.github+json",
-      "X-GitHub-Api-Version": "2022-11-28",
+      "X-GitHub-Api-Version": GITHUB_API_VERSION,
     },
   });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eb302d6 and 54f7a71.

📒 Files selected for processing (2)
  • public/locale/en.json (6 hunks)
  • scripts/fetchSbomData.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Lint Code Base
scripts/fetchSbomData.ts

[error] 66-66: Failed to write to feBomData.json during postinstall script execution

🪛 GitHub Actions: Cypress Tests
scripts/fetchSbomData.ts

[error] 66-66: Failed to write to './public/licenses/feBomData.json' - directory does not exist (ENOENT error)

🪛 GitHub Actions: Deploy Care Fe
scripts/fetchSbomData.ts

[error] 66-66: Failed to write to './public/licenses/feBomData.json': directory does not exist

🔇 Additional comments (6)
public/locale/en.json (2)

507-508: LGTM! Clear and consistent naming for backend/frontend components.

The added translations maintain consistency with the application's naming conventions.


1180-1180: LGTM! Appropriate translations for SBOM-related terms.

The added translations for license, N/A, packages, and SPDX SBOM version are clear and appropriate for the context.

Also applies to: 1282-1282, 1415-1415, 1835-1835

scripts/fetchSbomData.ts (4)

1-7: LGTM! Well-structured imports and constants.

Good job moving the URLs to top-level constants as suggested in the previous review.


9-41: LGTM! Well-defined type interface.

The GitHubSbomApiResponse interface accurately reflects the GitHub SBOM API structure as discussed in the previous review.


43-58: Follow the agreed naming convention for abbreviations.

As discussed in the previous review, we should use "Sbom" instead of "SBOM" in the function name.

-const fetchSBOMData = async (url: string): Promise<GitHubSbomApiResponse> => {
+const fetchSbomData = async (url: string): Promise<GitHubSbomApiResponse> => {

1-77: Verify the implementation in the CI environment.

Let's ensure the script works correctly in the CI environment by checking:

  1. Directory creation
  2. File permissions
  3. API rate limits
✅ Verification successful

Implementation verified successfully

The script should work correctly in the CI environment:

  • Directory permissions and structure are properly set up
  • GitHub API endpoints are accessible
  • Rate limits (60 requests/hour) are sufficient for the required API calls (2 requests)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation in CI environment

# Check if the script has write permissions in the target directory
echo "Checking directory permissions..."
mkdir -p ./public/licenses
if [ ! -w "./public/licenses" ]; then
  echo "Error: No write permissions in ./public/licenses"
  exit 1
fi

# Check GitHub API rate limits
echo "Checking GitHub API rate limits..."
curl -s -I -H "Accept: application/vnd.github+json" \
     -H "X-GitHub-Api-Version: 2022-11-28" \
     "https://api.github.com/rate_limit"

Length of output: 465


Script:

#!/bin/bash
# Description: Verify GitHub API access with correct methods

echo "Checking GitHub API rate limits..."
curl -s \
     -H "Accept: application/vnd.github+json" \
     -H "X-GitHub-Api-Version: 2022-11-28" \
     "https://api.github.com/rate_limit"

echo -e "\nChecking SBOM API endpoints..."
curl -s -o /dev/null -w "FE SBOM Status: %{http_code}\n" \
     -H "Accept: application/vnd.github+json" \
     -H "X-GitHub-Api-Version: 2022-11-28" \
     "https://api.github.com/repos/ohcnetwork/care_fe/dependency-graph/sbom"

curl -s -o /dev/null -w "BE SBOM Status: %{http_code}\n" \
     -H "Accept: application/vnd.github+json" \
     -H "X-GitHub-Api-Version: 2022-11-28" \
     "https://api.github.com/repos/ohcnetwork/care/dependency-graph/sbom"

Length of output: 1445

🧰 Tools
🪛 GitHub Actions: Lint Code Base

[error] 66-66: Failed to write to feBomData.json during postinstall script execution

🪛 GitHub Actions: Cypress Tests

[error] 66-66: Failed to write to './public/licenses/feBomData.json' - directory does not exist (ENOENT error)

🪛 GitHub Actions: Deploy Care Fe

[error] 66-66: Failed to write to './public/licenses/feBomData.json': directory does not exist

Copy link
Member

Choose a reason for hiding this comment

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

instead of this, we can do in the fetch sbom data script.

await mkdir(path, { recursive: true })

</h3>
{bomData.components?.map((component, index) => (
{packages.map((pkg: any, index: number) => (
Copy link
Member

Choose a reason for hiding this comment

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

now that we have strong types defined, let's not use any.

Suggested change
{packages.map((pkg: any, index: number) => (
{packages.map((package, index) => (

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required Deploy-Failed Deplyment is not showing preview
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Update License Page to Use GitHub-Provided SBOMs
3 participants