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
20 changes: 20 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Promotional
release
.env

node_modules
.DS_Store
dist
coverage
.vscode
.idea
*.log
*.env.local
*.env.development.local
*.env.test.local
*.env.production.local
*.env.*.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

136 changes: 93 additions & 43 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@ CodeTranslateAI is a powerful Chrome extension that allows you to translate code
## ✨ Key Features

- **On-the-Fly Translation:** Instantly translate code on platforms like Stack Overflow, Medium, and technical blogs.
- **Secure Backend:** Uses a serverless Cloudflare Worker so your AI API key is never exposed on the frontend.
- **Secure Serverless Backend:** Uses a Cloudflare Worker.
- **Multi-Language Tabs:** Translate the same code block into multiple languages and switch between them easily.
- **Smart Caching:** Translations are cached in your browser for 10 days to reduce API calls and provide instant results for previously translated code.
- **Elegant UI:** A clean, non-intrusive UI that matches the width of the original code block and uses a tabbed layout for multiple translations.
- **Powered by Gemini:** Leverages the power of Google's Gemini AI for high-quality code translations.
- **Smart Caching:** Translations are cached in your browser for 10 days to reduce API calls and provide instant results.
- **Powered by Gemini:** Leverages Google's Gemini AI for high-quality code translations with syntax highlighting.

---

## 🔧 Tech Stack

- **Frontend:**
- Plain JavaScript (ES6+)
- Modular JavaScript (ES6+)
- **esbuild** & **dotenv** (for bundling and environment variables)
- HTML5 & CSS3
- Chrome Extension APIs (`storage`, `runtime`, `scripting`)
- Chrome Extension APIs (`storage`, `activeTab`)
- Shadow DOM for style isolation.
- **Backend:**
- Cloudflare Workers
Expand All @@ -34,13 +34,13 @@ To get a local copy up and running, follow these simple steps.

### Prerequisites

You must have Node.js and npm installed on your machine.
You must have **Node.js** and **npm** installed on your machine.

- [Download Node.js](https://nodejs.org/)

### ⚙️ Part 1: Backend Setup (Cloudflare Worker)

1. **Clone the Repository** (or set up your backend folder).
1. **Clone the Repository**

```sh
git clone https://github.com/dineshsutihar/CodeTranslateAI.git
Expand All @@ -65,7 +65,9 @@ You must have Node.js and npm installed on your machine.

5. **Set the Secret Key**

- Run the following command and paste your Gemini API key when prompted. This stores it securely on Cloudflare.
- Run the following command and paste your Gemini API key when prompted.

<!-- end list -->

```sh
npx wrangler secret put GEMINI_API_KEY
Expand All @@ -75,33 +77,97 @@ You must have Node.js and npm installed on your machine.

- Deploy the backend to make it live.

<!-- end list -->

```sh
npx wrangler deploy
```

- After deployment, **copy the URL** that Wrangler provides. It will look like `https://backend.<your-worker-name>.dev`.
- After deployment, **copy the URL** that Wrangler provides.

### 🖥️ Part 2: Frontend Setup (Chrome Extension)

1. **Configure the Backend URL**
1. **Navigate to the Frontend Directory**

```sh
cd ../frontend
```

2. **Install Dependencies**

```sh
npm install
```

- Navigate to your Chrome extension folder (e.g., `my-code-translator`).
- Open the `background.js` file.
- Find the `BACKEND_URL` constant and **paste the Cloudflare Worker URL** you copied in the previous step.
3. **Configure the Backend URL**

- In the `frontend` folder, create a new file named `.env`.
- Add the Cloudflare Worker URL you copied in the previous step to this file:

<!-- end list -->

```
# .env file
BACKEND_URL="https://your-worker-url.workers.dev"
```

4. **Create the Build Configuration**

- In the `frontend` folder, create a file named `build.js` and add the following content. This file tells our build script how to use the `.env` variable.

<!-- end list -->

```javascript
// background.js
const BACKEND_URL = "https://backend.<your-worker-name>.dev"; // PASTE YOUR URL HERE
// build.js
import esbuild from "esbuild";
import "dotenv/config";

const define = {};
for (const k in process.env) {
define[`process.env.${k}`] = JSON.stringify(process.env[k]);
}

esbuild
.build({
entryPoints: ["scripts/content.js", "background.js"],
bundle: true,
outdir: "dist",
define: define,
})
.catch(() => process.exit(1));
```

2. **Load the Extension in Chrome**
5. **Build the Extension**

- Run the build command to bundle your scripts and inject the environment variable.

<!-- end list -->

```sh
npm run build
```

This will create a `dist` folder containing your final `content.js` and `background.js` files.

6. **Load the Extension in Chrome**

- Open Google Chrome and navigate to `chrome://extensions`.
- Enable **"Developer mode"** using the toggle in the top-right corner.
- Enable **"Developer mode"**.
- Click the **"Load unpacked"** button.
- Select your Chrome extension folder (the one containing `manifest.json`).
- Select your Chrome extension folder (the `frontend` folder that contains `manifest.json`).

The **CodeTranslateAI** icon should now appear in your Chrome toolbar, and the extension is ready to use\!
The **CodeTranslateAI** icon should now appear in your Chrome toolbar\!

---

## 💻 Development Workflow

1. Make any changes to your JavaScript files in the `scripts/` folder or `background.js`.
2. Run the build command in your terminal:
```sh
npm run build
```
3. Go to `chrome://extensions` and click the **reload** button for the CodeTranslateAI extension.

---

Expand All @@ -110,40 +176,24 @@ The **CodeTranslateAI** icon should now appear in your Chrome toolbar, and the e
1. Click the extension icon in the Chrome toolbar.
2. Select your desired target language from the dropdown menu.
3. Click the **"Enable Code Selector"** button.
4. Your cursor will change to a crosshair. Hover over any code block on a webpage and click on it.
5. A "Translating..." message will appear, followed by a new UI element containing the translated code.
6. If you translate the same block into another language, a new tab will be added to the UI.
4. Your cursor will change to a crosshair. Click on any code block on a webpage.
5. A "Translating..." message will appear, followed by the translated code in a new UI.

---

## 🐛 Debugging the Backend

If you encounter errors or the translation isn't working, the first step is to check the live logs from your Cloudflare Worker. This allows you to see what's happening on the server in real-time.

1. **Navigate to your Backend Directory**

- Open your terminal and change into the directory where your Cloudflare Worker code is located (e.g., `CodeTranslateAI/backend`).

2. **Run the Tail Command**

- Execute the following command to start streaming the logs:
If you encounter errors, check the live logs from your Cloudflare Worker.

1. **Navigate to your Backend Directory**.
2. **Run the Tail Command**:
```sh
npx wrangler tail
```

- The terminal will connect and say `Connected to [worker-name], waiting for logs...`.

3. **Trigger the Error**

- With the log stream running, go to your browser and use the extension to perform an action that causes an error.

4. **Check the Terminal**

- Look back at your terminal. Any errors or log messages from your worker will appear instantly. Look for lines that start with `(error)`. This will give you the exact reason for the failure, such as an invalid API key or a quota issue.
3. **Trigger the Error** by using the extension in your browser and check the terminal for error messages.

---

## ⚖️ License

Distributed under the MIT License. See `LICENSE.txt` for more information.
Distributed under the MIT License.
1 change: 1 addition & 0 deletions frontend/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
BACKEND_URL="https://backend.your-cloudflare-worker.workers.dev"
4 changes: 2 additions & 2 deletions frontend/background.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
chrome.runtime.onMessage.addListener((request, _, sendResponse) => {
if (request.type === "TRANSLATE_CODE") {
const BACKEND_URL = "https://backend.dineshsutihar123.workers.dev";
const BACKEND_URL = process.env.BACKEND_URL;

chrome.storage.sync.get(['targetLanguage'], (result) => {
const targetLanguage = result.targetLanguage || 'Java';
Expand Down
16 changes: 16 additions & 0 deletions frontend/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import esbuild from 'esbuild';
import 'dotenv/config';

const define = {};
for (const k in process.env) {
define[`process.env.${k}`] = JSON.stringify(process.env[k]);
}

esbuild.build({
entryPoints: ['scripts/content.js', 'background.js'],
bundle: true,
outdir: 'dist',
define: define,
}).catch(() => process.exit(1));

console.log('Build complete. Files are in the /dist folder.');
Loading