Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
🤖 Plandex → Add Chrome extension manifest, background script, authentication UI, Plandex API service, fuzzy search, content script, utility functions, and build setup.
Dane Schneider162c13f11dcc
diff --git a/.gitignore b/.gitignoreindex 6764afc8..7b2ba911 100644--- a/.gitignore+++ b/.gitignore@@ -1,20 +1,33 @@-.plandex/-.plandex-dev/-.plandex-v2/-.plandex-dev-v2/-.envkey-plandex-plandex-dev-plandex-server-*.exe+# Node.jsnode_modules/-/tools/-/static/-/infra/-/payments-dashboard/-.DS_Store-.goreleaser.yml+npm-debug.log+yarn-debug.log+yarn-error.log+.npm/++# Build outputdist/+build/+*.bundle.js++# IDE and editor files+.idea/+.vscode/+*.swp+*.swo+.DS_Store++# Environment variables+.env+.env.local+.env.development.local+.env.test.local+.env.production.local++# Testing+coverage/+.nyc_output/-.aider.*-*.code-workspace+# Logs+logs/+*.logdiff --git a/api.js b/api.jsnew file mode 100644index 00000000..bfd6433c--- /dev/null+++ b/api.js@@ -0,0 +1,318 @@+/**+ * Plandex API Service+ * Handles API requests, authentication, and data fetching+ */++// Default API URL+const DEFAULT_API_URL = "https://api.plandex.ai";++// Storage keys+const STORAGE_KEYS = {+ AUTH_TOKEN: "plandex_auth_token",+ ORG_ID: "plandex_org_id",+ API_URL: "plandex_api_url",+ USER_INFO: "plandex_user_info"+};++/**+ * PlandexAPI class for handling API requests+ */+class PlandexAPI {+ constructor() {+ this.apiUrl = DEFAULT_API_URL;+ this.token = null;+ this.orgId = null;+ this.initialized = false;+ }++ /**+ * Initialize the API service+ * Loads saved API URL, auth token, and org ID from storage+ */+ async initialize() {+ try {+ // Load API URL from storage+ const apiUrlData = await chrome.storage.local.get(STORAGE_KEYS.API_URL);+ this.apiUrl = apiUrlData[STORAGE_KEYS.API_URL] || DEFAULT_API_URL;++ // Load auth token from storage+ const tokenData = await chrome.storage.local.get(STORAGE_KEYS.AUTH_TOKEN);+ this.token = tokenData[STORAGE_KEYS.AUTH_TOKEN] || null;++ // Load org ID from storage+ const orgIdData = await chrome.storage.local.get(STORAGE_KEYS.ORG_ID);+ this.orgId = orgIdData[STORAGE_KEYS.ORG_ID] || null;++ this.initialized = true;+ return true;+ } catch (error) {+ console.error("Error initializing API service:", error);+ return false;+ }+ }++ /**+ * Check if the user is authenticated+ */+ isAuthenticated() {+ return !!(this.token && this.orgId);+ }++ /**+ * Get request headers with authentication+ */+ getHeaders(includeAuth = true) {+ const headers = {+ "Content-Type": "application/json"+ };++ if (includeAuth && this.token && this.orgId) {+ headers["Authorization"] = `Bearer ${this.token}`;+ headers["X-Org-Id"] = this.orgId;+ }++ return headers;+ }++ /**+ * Make an API request+ * @param {string} endpoint - API endpoint+ * @param {Object} options - Request options+ * @param {boolean} requiresAuth - Whether the request requires authentication+ */+ async request(endpoint, options = {}, requiresAuth = true) {+ if (!this.initialized) {+ await this.initialize();+ }++ if (requiresAuth && !this.isAuthenticated()) {+ throw new Error("Authentication required");+ }++ const url = `${this.apiUrl}${endpoint}`;++ const requestOptions = {+ ...options,+ headers: {+ ...this.getHeaders(requiresAuth),+ ...(options.headers || {})+ }+ };++ try {+ const response = await fetch(url, requestOptions);++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.message || `Request failed with status ${response.status}`);+ }++ return await response.json();+ } catch (error) {+ console.error(`API request error (${endpoint}):`, error);+ throw error;+ }+ }++ /**+ * Authenticate with a sign-in code+ * @param {string} code - Sign-in code+ */+ async authenticate(code) {+ if (!this.initialized) {+ await this.initialize();+ }++ try {+ const response = await fetch(`${this.apiUrl}/accounts/sign_in`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json"+ },+ body: JSON.stringify({+ pin: code,+ isSignInCode: true+ })+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.message || "Authentication failed");+ }++ const data = await response.json();++ // Store authentication data+ this.token = data.token;+ this.orgId = data.orgId;++ // Save to storage+ await chrome.storage.local.set({+ [STORAGE_KEYS.AUTH_TOKEN]: data.token,+ [STORAGE_KEYS.ORG_ID]: data.orgId,+ [STORAGE_KEYS.USER_INFO]: {+ name: data.name,+ email: data.email+ }+ });++ return {+ success: true,+ user: {+ name: data.name,+ email: data.email+ }+ };+ } catch (error) {+ console.error("Authentication error:", error);+ throw error;+ }+ }++ /**+ * Logout and clear authentication data+ */+ async logout() {+ try {+ // Clear authentication data+ this.token = null;+ this.orgId = null;++ // Clear from storage+ await chrome.storage.local.remove([+ STORAGE_KEYS.AUTH_TOKEN,+ STORAGE_KEYS.ORG_ID,+ STORAGE_KEYS.USER_INFO+ ]);++ return { success: true };+ } catch (error) {+ console.error("Logout error:", error);+ throw error;+ }+ }++ /**+ * Update the API URL+ * @param {string} apiUrl - New API URL+ */+ async updateApiUrl(apiUrl) {+ try {+ this.apiUrl = apiUrl;++ // Save to storage+ await chrome.storage.local.set({+ [STORAGE_KEYS.API_URL]: apiUrl+ });++ return { success: true };+ } catch (error) {+ console.error("Error updating API URL:", error);+ throw error;+ }+ }++ /**+ * Fetch all plans+ */+ async fetchPlans() {+ try {+ const data = await this.request("/plans");+ return data.plans || [];+ } catch (error) {+ console.error("Error fetching plans:", error);+ throw error;+ }+ }++ /**+ * Fetch all projects+ */+ async fetchProjects() {+ try {+ const data = await this.request("/projects");+ return data.projects || [];+ } catch (error) {+ console.error("Error fetching projects:", error);+ throw error;+ }+ }++ /**+ * Get the current branch for a plan+ * @param {string} planId - Plan ID+ */+ async getCurrentBranch(planId) {+ try {+ const data = await this.request(`/plans/${planId}/current_branch`);+ return data.branch || "main";+ } catch (error) {+ console.error(`Error fetching current branch for plan ${planId}:`, error);+ throw error;+ }+ }++ /**+ * Send text to a plan+ * @param {string} planId - Plan ID+ * @param {string} branch - Branch name+ * @param {string} text - Text to send+ * @param {string} name - Name for the context item+ */+ async sendTextToPlan(planId, branch, text, name = "Selected text from web") {+ try {+ if (!planId) {+ throw new Error("Plan ID is required");+ }++ if (!branch) {+ branch = await this.getCurrentBranch(planId);+ }++ const contextParams = {+ contextType: "note",+ name: name,+ body: text,+ autoLoaded: false+ };++ await this.request(`/plans/${planId}/${branch}/context`, {+ method: "POST",+ body: JSON.stringify([contextParams])+ });++ return { success: true };+ } catch (error) {+ console.error("Error sending text to plan:", error);+ throw error;+ }+ }++ /**+ * Search plans by name+ * @param {string} query - Search query+ * @param {Array} plans - List of plans to search+ */+ searchPlans(query, plans) {+ if (!query || !plans || !plans.length) {+ return plans || [];+ }++ const lowerQuery = query.toLowerCase();+ return plans.filter(plan =>+ plan.name.toLowerCase().includes(lowerQuery) ||+ (plan.description && plan.description.toLowerCase().includes(lowerQuery))+ );+ }+}++// Create and export a singleton instance+const plandexAPI = new PlandexAPI();++// Initialize the API service+plandexAPI.initialize().catch(error => {+ console.error("Failed to initialize Plandex API service:", error);+});++// Export the API service+export default plandexAPI;diff --git a/background.js b/background.jsnew file mode 100644index 00000000..197f9f8f--- /dev/null+++ b/background.js@@ -0,0 +1,275 @@+// Constants+const API_URL = "https://api.plandex.ai";+const CONTEXT_MENU_ID = "send-to-plandex";+const STORAGE_KEYS = {+ AUTH_TOKEN: "plandex_auth_token",+ ORG_ID: "plandex_org_id",+ API_URL: "plandex_api_url",+ USER_INFO: "plandex_user_info"+};++// Initialize the extension+function initializeExtension() {+ // Create context menu item+ createContextMenu();++ // Set up message listeners+ setupMessageListeners();++ // Check authentication status and update badge+ checkAuthStatus();+}++// Create the context menu item+function createContextMenu() {+ chrome.contextMenus.create({+ id: CONTEXT_MENU_ID,+ title: "Send to Plandex",+ contexts: ["selection"],+ visible: false // Hide until authenticated+ });++ // Add listener for context menu clicks+ chrome.contextMenus.onClicked.addListener((info, tab) => {+ if (info.menuItemId === CONTEXT_MENU_ID) {+ handleContextMenuClick(info, tab);+ }+ });+}++// Handle context menu click+async function handleContextMenuClick(info, tab) {+ if (info.selectionText) {+ // Open plan selector popup+ chrome.windows.create({+ url: chrome.runtime.getURL("planSelector.html"),+ type: "popup",+ width: 400,+ height: 500,+ focused: true+ }, (window) => {+ // Store the selected text and tab info for later use+ chrome.storage.local.set({+ "selectedText": info.selectionText,+ "sourceTab": tab.id,+ "sourceUrl": tab.url+ });+ });+ }+}++// Set up message listeners for communication between different parts of the extension+function setupMessageListeners() {+ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {+ switch (message.action) {+ case "authenticate":+ handleAuthentication(message.code)+ .then(result => sendResponse(result))+ .catch(error => sendResponse({ success: false, error: error.message }));+ return true; // Indicates async response++ case "checkAuth":+ checkAuthStatus()+ .then(status => sendResponse(status))+ .catch(error => sendResponse({ authenticated: false, error: error.message }));+ return true;++ case "logout":+ handleLogout()+ .then(() => sendResponse({ success: true }))+ .catch(error => sendResponse({ success: false, error: error.message }));+ return true;++ case "sendToPlan":+ sendTextToPlan(message.planId, message.branch, message.text)+ .then(result => sendResponse(result))+ .catch(error => sendResponse({ success: false, error: error.message }));+ return true;++ case "updateApiUrl":+ updateApiUrl(message.apiUrl)+ .then(() => sendResponse({ success: true }))+ .catch(error => sendResponse({ success: false, error: error.message }));+ return true;+ }+ });+}++// Handle authentication with sign-in code+async function handleAuthentication(code) {+ try {+ const apiUrl = await getApiUrl();++ const response = await fetch(`${apiUrl}/accounts/sign_in`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json"+ },+ body: JSON.stringify({+ pin: code,+ isSignInCode: true+ })+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.message || "Authentication failed");+ }++ const data = await response.json();++ // Store authentication data+ await chrome.storage.local.set({+ [STORAGE_KEYS.AUTH_TOKEN]: data.token,+ [STORAGE_KEYS.ORG_ID]: data.orgId,+ [STORAGE_KEYS.USER_INFO]: {+ name: data.name,+ email: data.email+ }+ });++ // Update context menu visibility+ chrome.contextMenus.update(CONTEXT_MENU_ID, {+ visible: true+ });++ // Update badge+ chrome.action.setBadgeText({ text: "✓" });+ chrome.action.setBadgeBackgroundColor({ color: "#4CAF50" });++ return { success: true, user: data };+ } catch (error) {+ console.error("Authentication error:", error);+ return { success: false, error: error.message };+ }+}++// Check authentication status+async function checkAuthStatus() {+ try {+ const token = await chrome.storage.local.get(STORAGE_KEYS.AUTH_TOKEN);+ const orgId = await chrome.storage.local.get(STORAGE_KEYS.ORG_ID);++ const isAuthenticated = token[STORAGE_KEYS.AUTH_TOKEN] && orgId[STORAGE_KEYS.ORG_ID];++ // Update context menu visibility+ chrome.contextMenus.update(CONTEXT_MENU_ID, {+ visible: isAuthenticated+ });++ // Update badge+ if (isAuthenticated) {+ chrome.action.setBadgeText({ text: "✓" });+ chrome.action.setBadgeBackgroundColor({ color: "#4CAF50" });+ } else {+ chrome.action.setBadgeText({ text: "×" });+ chrome.action.setBadgeBackgroundColor({ color: "#F44336" });+ }++ return { authenticated: isAuthenticated };+ } catch (error) {+ console.error("Error checking auth status:", error);+ return { authenticated: false, error: error.message };+ }+}++// Handle logout+async function handleLogout() {+ try {+ // Clear authentication data+ await chrome.storage.local.remove([+ STORAGE_KEYS.AUTH_TOKEN,+ STORAGE_KEYS.ORG_ID,+ STORAGE_KEYS.USER_INFO+ ]);++ // Update context menu visibility+ chrome.contextMenus.update(CONTEXT_MENU_ID, {+ visible: false+ });++ // Update badge+ chrome.action.setBadgeText({ text: "×" });+ chrome.action.setBadgeBackgroundColor({ color: "#F44336" });++ return { success: true };+ } catch (error) {+ console.error("Logout error:", error);+ return { success: false, error: error.message };+ }+}++// Send text to a Plandex plan+async function sendTextToPlan(planId, branch, text) {+ try {+ const token = await getAuthToken();+ const orgId = await getOrgId();+ const apiUrl = await getApiUrl();++ if (!token || !orgId) {+ throw new Error("Not authenticated");+ }++ const contextParams = {+ contextType: "note",+ name: "Selected text from web",+ body: text,+ autoLoaded: false+ };++ const response = await fetch(`${apiUrl}/plans/${planId}/${branch}/context`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Authorization": `Bearer ${token}`,+ "X-Org-Id": orgId+ },+ body: JSON.stringify([contextParams])+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.message || "Failed to send text to plan");+ }++ return { success: true };+ } catch (error) {+ console.error("Error sending text to plan:", error);+ return { success: false, error: error.message };+ }+}++// Update API URL+async function updateApiUrl(apiUrl) {+ try {+ await chrome.storage.local.set({+ [STORAGE_KEYS.API_URL]: apiUrl+ });++ return { success: true };+ } catch (error) {+ console.error("Error updating API URL:", error);+ return { success: false, error: error.message };+ }+}++// Helper function to get auth token+async function getAuthToken() {+ const data = await chrome.storage.local.get(STORAGE_KEYS.AUTH_TOKEN);+ return data[STORAGE_KEYS.AUTH_TOKEN];+}++// Helper function to get org ID+async function getOrgId() {+ const data = await chrome.storage.local.get(STORAGE_KEYS.ORG_ID);+ return data[STORAGE_KEYS.ORG_ID];+}++// Helper function to get API URL+async function getApiUrl() {+ const data = await chrome.storage.local.get(STORAGE_KEYS.API_URL);+ return data[STORAGE_KEYS.API_URL] || API_URL;+}++// Initialize the extension when the service worker starts+initializeExtension();diff --git a/content.js b/content.jsnew file mode 100644index 00000000..2f935f4e--- /dev/null+++ b/content.js@@ -0,0 +1,245 @@+/**+ * Plandex Extension Content Script+ * Handles selected text and notifications+ */++// Create a notification container if it doesn't exist+let notificationContainer = document.getElementById('plandex-notification-container');+if (!notificationContainer) {+ notificationContainer = document.createElement('div');+ notificationContainer.id = 'plandex-notification-container';+ notificationContainer.style.cssText = `+ position: fixed;+ bottom: 20px;+ right: 20px;+ z-index: 9999;+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;+ `;+ document.body.appendChild(notificationContainer);+}++// Create and show a notification+function showNotification(message, type = 'info', duration = 3000) {+ // Create notification element+ const notification = document.createElement('div');+ notification.className = `plandex-notification plandex-notification-${type}`;+ notification.style.cssText = `+ padding: 12px 16px;+ margin-bottom: 10px;+ border-radius: 4px;+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);+ font-size: 14px;+ line-height: 1.5;+ display: flex;+ align-items: center;+ transition: opacity 0.3s ease-in-out, transform 0.3s ease-in-out;+ opacity: 0;+ transform: translateY(20px);+ max-width: 300px;+ word-break: break-word;+ `;++ // Set background color based on notification type+ if (type === 'success') {+ notification.style.backgroundColor = '#e6f4ea';+ notification.style.color = '#137333';+ notification.style.borderLeft = '4px solid #137333';+ } else if (type === 'error') {+ notification.style.backgroundColor = '#fdecea';+ notification.style.color = '#d93025';+ notification.style.borderLeft = '4px solid #d93025';+ } else if (type === 'warning') {+ notification.style.backgroundColor = '#fef7e0';+ notification.style.color = '#b06000';+ notification.style.borderLeft = '4px solid #b06000';+ } else {+ notification.style.backgroundColor = '#e8f0fe';+ notification.style.color = '#1a73e8';+ notification.style.borderLeft = '4px solid #1a73e8';+ }++ // Create icon based on notification type+ const icon = document.createElement('div');+ icon.style.cssText = `+ margin-right: 10px;+ width: 20px;+ height: 20px;+ display: flex;+ align-items: center;+ justify-content: center;+ `;++ // Set icon content based on notification type+ if (type === 'success') {+ icon.innerHTML = `+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>+ <polyline points="22 4 12 14.01 9 11.01"></polyline>+ </svg>+ `;+ } else if (type === 'error') {+ icon.innerHTML = `+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="10"></circle>+ <line x1="15" y1="9" x2="9" y2="15"></line>+ <line x1="9" y1="9" x2="15" y2="15"></line>+ </svg>+ `;+ } else if (type === 'warning') {+ icon.innerHTML = `+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>+ <line x1="12" y1="9" x2="12" y2="13"></line>+ <line x1="12" y1="17" x2="12.01" y2="17"></line>+ </svg>+ `;+ } else {+ icon.innerHTML = `+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="10"></circle>+ <line x1="12" y1="8" x2="12" y2="12"></line>+ <line x1="12" y1="16" x2="12.01" y2="16"></line>+ </svg>+ `;+ }++ // Create message element+ const messageElement = document.createElement('div');+ messageElement.textContent = message;++ // Create close button+ const closeButton = document.createElement('div');+ closeButton.style.cssText = `+ margin-left: 10px;+ cursor: pointer;+ opacity: 0.7;+ transition: opacity 0.2s;+ `;+ closeButton.innerHTML = `+ <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <line x1="18" y1="6" x2="6" y2="18"></line>+ <line x1="6" y1="6" x2="18" y2="18"></line>+ </svg>+ `;+ closeButton.addEventListener('mouseover', () => {+ closeButton.style.opacity = '1';+ });+ closeButton.addEventListener('mouseout', () => {+ closeButton.style.opacity = '0.7';+ });+ closeButton.addEventListener('click', () => {+ removeNotification(notification);+ });++ // Append elements to notification+ notification.appendChild(icon);+ notification.appendChild(messageElement);+ notification.appendChild(closeButton);++ // Append notification to container+ notificationContainer.appendChild(notification);++ // Show notification with animation+ setTimeout(() => {+ notification.style.opacity = '1';+ notification.style.transform = 'translateY(0)';+ }, 10);++ // Remove notification after duration+ if (duration > 0) {+ setTimeout(() => {+ removeNotification(notification);+ }, duration);+ }++ return notification;+}++// Remove a notification with animation+function removeNotification(notification) {+ notification.style.opacity = '0';+ notification.style.transform = 'translateY(20px)';++ setTimeout(() => {+ if (notification.parentNode) {+ notification.parentNode.removeChild(notification);+ }+ }, 300);+}++// Listen for messages from the background script or popup+chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {+ if (message.action === 'showNotification') {+ showNotification(message.message, message.type || 'info', message.duration || 3000);+ sendResponse({ success: true });+ return true;+ }+});++// Function to get selected text+function getSelectedText() {+ return window.getSelection().toString().trim();+}++// Function to check if text is selected+function hasSelectedText() {+ return getSelectedText().length > 0;+}++// Listen for context menu clicks+document.addEventListener('contextmenu', (event) => {+ // Check if text is selected+ const selectedText = getSelectedText();++ // Store selected text in local storage for context menu handler+ if (selectedText) {+ chrome.storage.local.set({ 'tempSelectedText': selectedText });+ } else {+ chrome.storage.local.remove('tempSelectedText');+ }+});++// Listen for keyboard shortcuts+document.addEventListener('keydown', (event) => {+ // Check for Ctrl+Shift+P (Windows/Linux) or Command+Shift+P (Mac)+ if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key === 'p') {+ const selectedText = getSelectedText();++ if (selectedText) {+ // Store selected text+ chrome.storage.local.set({+ 'selectedText': selectedText,+ 'sourceUrl': window.location.href+ });++ // Show notification+ showNotification('Opening Plandex plan selector...', 'info');++ // Send message to background script to open plan selector+ chrome.runtime.sendMessage({+ action: 'openPlanSelector',+ selectedText: selectedText,+ sourceUrl: window.location.href+ });+ } else {+ showNotification('No text selected', 'warning');+ }+ }+});++// Function to handle text selection changes+function handleSelectionChange() {+ // This function can be used to update UI elements based on selection+ // For now, we'll just use it to update the context menu visibility+ const hasSelection = hasSelectedText();++ // We can't directly update the context menu from here,+ // but we can store the selection state for the background script+ chrome.storage.local.set({ 'hasSelectedText': hasSelection });+}++// Listen for selection changes+document.addEventListener('selectionchange', handleSelectionChange);++// Initialize+console.log('Plandex content script loaded');diff --git a/manifest.json b/manifest.jsonnew file mode 100644index 00000000..9073a12e--- /dev/null+++ b/manifest.json@@ -0,0 +1,38 @@+{+ "manifest_version": 3,+ "name": "Plandex Extension",+ "version": "1.0.0",+ "description": "Send selected text to Plandex plans via the context menu",+ "permissions": [+ "contextMenus",+ "storage",+ "activeTab"+ ],+ "host_permissions": [+ "https://api.plandex.ai/*"+ ],+ "background": {+ "service_worker": "background.js"+ },+ "action": {+ "default_popup": "popup.html",+ "default_icon": {+ "16": "icons/icon16.png",+ "32": "icons/icon32.png",+ "48": "icons/icon48.png",+ "128": "icons/icon128.png"+ }+ },+ "content_scripts": [+ {+ "matches": ["<all_urls>"],+ "js": ["content.js"]+ }+ ],+ "icons": {+ "16": "icons/icon16.png",+ "32": "icons/icon32.png",+ "48": "icons/icon48.png",+ "128": "icons/icon128.png"+ }+}diff --git a/package.json b/package.jsonnew file mode 100644index 00000000..fba07f95--- /dev/null+++ b/package.json@@ -0,0 +1,37 @@+{+ "name": "plandex-chrome-extension",+ "version": "1.0.0",+ "description": "Chrome extension for sending selected text to Plandex plans",+ "private": true,+ "scripts": {+ "build": "webpack --mode=production",+ "dev": "webpack --mode=development --watch",+ "lint": "eslint src/",+ "test": "jest",+ "clean": "rimraf dist"+ },+ "keywords": [+ "plandex",+ "chrome-extension"+ ],+ "author": "",+ "license": "MIT",+ "devDependencies": {+ "@babel/core": "^7.22.5",+ "@babel/preset-env": "^7.22.5",+ "babel-loader": "^9.1.2",+ "copy-webpack-plugin": "^11.0.0",+ "css-loader": "^6.8.1",+ "eslint": "^8.42.0",+ "html-webpack-plugin": "^5.5.3",+ "jest": "^29.5.0",+ "jest-environment-jsdom": "^29.5.0",+ "rimraf": "^5.0.1",+ "style-loader": "^3.3.3",+ "webpack": "^5.86.0",+ "webpack-cli": "^5.1.4"+ },+ "dependencies": {+ "fuse.js": "^6.6.2"+ }+}diff --git a/planSelector.css b/planSelector.cssnew file mode 100644index 00000000..529ab90a--- /dev/null+++ b/planSelector.css@@ -0,0 +1,256 @@+/* Reset and base styles */+* {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+}++body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;+ font-size: 14px;+ line-height: 1.5;+ color: #333;+ background-color: #f5f5f5;+}++.container {+ width: 400px;+ min-height: 500px;+ background-color: #fff;+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);+ display: flex;+ flex-direction: column;+}++/* Header styles */+header {+ padding: 15px;+ background-color: #4285f4;+ color: white;+ text-align: center;+}++header h1 {+ font-size: 18px;+ font-weight: 500;+}++/* Main content styles */+main {+ padding: 15px;+ flex-grow: 1;+ display: flex;+ flex-direction: column;+}++h2 {+ font-size: 16px;+ margin-bottom: 10px;+ color: #333;+}++/* Search section styles */+#search-section {+ margin-bottom: 15px;+}++.form-group {+ position: relative;+}++#search-input {+ width: 100%;+ padding: 8px 10px 8px 35px;+ border: 1px solid #ddd;+ border-radius: 4px;+ font-size: 14px;+}++#search-input:focus {+ outline: none;+ border-color: #4285f4;+ box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);+}++#search-icon {+ position: absolute;+ left: 10px;+ top: 50%;+ transform: translateY(-50%);+ color: #666;+}++/* Plans list styles */+#plans-section {+ margin-bottom: 15px;+ flex-grow: 1;+}++.plans-list {+ max-height: 200px;+ overflow-y: auto;+ border: 1px solid #ddd;+ border-radius: 4px;+}++.plan-item {+ padding: 10px 15px;+ border-bottom: 1px solid #eee;+ cursor: pointer;+ transition: background-color 0.2s;+}++.plan-item:last-child {+ border-bottom: none;+}++.plan-item:hover {+ background-color: #f5f5f5;+}++.plan-item.selected {+ background-color: #e8f0fe;+ border-left: 3px solid #4285f4;+}++.plan-name {+ font-weight: 500;+ margin-bottom: 3px;+}++.plan-description {+ font-size: 12px;+ color: #666;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++/* Loading indicator styles */+.loading-indicator {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: 20px;+}++.spinner {+ width: 24px;+ height: 24px;+ border: 3px solid #f3f3f3;+ border-top: 3px solid #4285f4;+ border-radius: 50%;+ animation: spin 1s linear infinite;+ margin-bottom: 10px;+}++@keyframes spin {+ 0% { transform: rotate(0deg); }+ 100% { transform: rotate(360deg); }+}++/* Selected text preview styles */+#selected-text-section {+ margin-bottom: 15px;+}++.selected-text-preview {+ padding: 10px;+ border: 1px solid #ddd;+ border-radius: 4px;+ max-height: 100px;+ overflow-y: auto;+ font-size: 13px;+ background-color: #f9f9f9;+}++/* Action section styles */+#action-section {+ display: flex;+ justify-content: space-between;+ margin-top: auto;+}++/* Button styles */+.btn {+ display: inline-block;+ padding: 8px 16px;+ border: none;+ border-radius: 4px;+ font-size: 14px;+ font-weight: 500;+ cursor: pointer;+ transition: background-color 0.2s;+}++.btn:disabled {+ opacity: 0.6;+ cursor: not-allowed;+}++.primary-btn {+ background-color: #4285f4;+ color: white;+}++.primary-btn:hover:not(:disabled) {+ background-color: #3367d6;+}++.secondary-btn {+ background-color: #f1f3f4;+ color: #333;+}++.secondary-btn:hover {+ background-color: #e8eaed;+}++/* Message styles */+.error-message {+ padding: 10px;+ background-color: #fdecea;+ color: #d93025;+ border-radius: 4px;+ margin-bottom: 15px;+}++/* No plans message */+#no-plans {+ padding: 20px;+ text-align: center;+ color: #666;+}++/* Utility classes */+.hidden {+ display: none;+}++/* Footer styles */+footer {+ padding: 10px 15px;+ text-align: center;+ font-size: 12px;+ color: #666;+ background-color: #f8f9fa;+}++/* Scrollbar styles */+::-webkit-scrollbar {+ width: 8px;+}++::-webkit-scrollbar-track {+ background: #f1f1f1;+}++::-webkit-scrollbar-thumb {+ background: #c1c1c1;+ border-radius: 4px;+}++::-webkit-scrollbar-thumb:hover {+ background: #a8a8a8;+}diff --git a/planSelector.html b/planSelector.htmlnew file mode 100644index 00000000..fbb27141--- /dev/null+++ b/planSelector.html@@ -0,0 +1,65 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Select Plandex Plan</title>+ <link rel="stylesheet" href="planSelector.css">+</head>+<body>+ <div class="container">+ <header>+ <h1>Send to Plandex Plan</h1>+ </header>++ <main>+ <div id="search-section">+ <div class="form-group">+ <input type="text" id="search-input" placeholder="Search plans..." autocomplete="off">+ <div id="search-icon">+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="11" cy="11" r="8"></circle>+ <line x1="21" y1="21" x2="16.65" y2="16.65"></line>+ </svg>+ </div>+ </div>+ </div>++ <div id="plans-section">+ <div id="plans-list" class="plans-list">+ <!-- Plans will be populated here -->+ <div class="loading-indicator">+ <div class="spinner"></div>+ <p>Loading plans...</p>+ </div>+ </div>++ <div id="no-plans" class="hidden">+ <p>No plans found. Try a different search term.</p>+ </div>++ <div id="error-message" class="error-message hidden">+ <p>Failed to load plans. Please try again.</p>+ </div>+ </div>++ <div id="selected-text-section">+ <h2>Selected Text</h2>+ <div id="selected-text-preview" class="selected-text-preview"></div>+ </div>++ <div id="action-section">+ <button id="send-btn" class="btn primary-btn" disabled>Send to Plan</button>+ <button id="cancel-btn" class="btn secondary-btn">Cancel</button>+ </div>+ </main>++ <footer>+ <p>Select a plan to send the selected text to</p>+ </footer>+ </div>++ <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>+ <script src="planSelector.js"></script>+</body>+</html>diff --git a/planSelector.js b/planSelector.jsnew file mode 100644index 00000000..3f1659df--- /dev/null+++ b/planSelector.js@@ -0,0 +1,374 @@+// DOM Elements+const searchInput = document.getElementById('search-input');+const plansList = document.getElementById('plans-list');+const noPlansMessage = document.getElementById('no-plans');+const errorMessage = document.getElementById('error-message');+const selectedTextPreview = document.getElementById('selected-text-preview');+const sendButton = document.getElementById('send-btn');+const cancelButton = document.getElementById('cancel-btn');++// State+let plans = [];+let filteredPlans = [];+let selectedPlan = null;+let selectedText = '';+let sourceTab = null;+let sourceUrl = '';+let fuseInstance = null;++// Constants+const STORAGE_KEYS = {+ AUTH_TOKEN: "plandex_auth_token",+ ORG_ID: "plandex_org_id",+ API_URL: "plandex_api_url"+};++// Initialize the popup+document.addEventListener('DOMContentLoaded', async () => {+ // Load selected text and source info+ await loadSelectedText();++ // Load plans+ await loadPlans();++ // Set up event listeners+ setupEventListeners();++ // Focus search input+ searchInput.focus();+});++// Load selected text and source info from storage+async function loadSelectedText() {+ try {+ const data = await chrome.storage.local.get(['selectedText', 'sourceTab', 'sourceUrl']);++ selectedText = data.selectedText || '';+ sourceTab = data.sourceTab || null;+ sourceUrl = data.sourceUrl || '';++ // Update selected text preview+ updateSelectedTextPreview();+ } catch (error) {+ console.error('Error loading selected text:', error);+ showError('Failed to load selected text');+ }+}++// Update selected text preview+function updateSelectedTextPreview() {+ // Truncate text if too long+ const maxLength = 200;+ let previewText = selectedText;++ if (selectedText.length > maxLength) {+ previewText = selectedText.substring(0, maxLength) + '...';+ }++ selectedTextPreview.textContent = previewText || 'No text selected';+}++// Load plans from API+async function loadPlans() {+ try {+ showLoading();++ // Get auth token and org ID+ const tokenData = await chrome.storage.local.get(STORAGE_KEYS.AUTH_TOKEN);+ const orgIdData = await chrome.storage.local.get(STORAGE_KEYS.ORG_ID);+ const apiUrlData = await chrome.storage.local.get(STORAGE_KEYS.API_URL);++ const token = tokenData[STORAGE_KEYS.AUTH_TOKEN];+ const orgId = orgIdData[STORAGE_KEYS.ORG_ID];+ const apiUrl = apiUrlData[STORAGE_KEYS.API_URL] || 'https://api.plandex.ai';++ if (!token || !orgId) {+ throw new Error('Not authenticated');+ }++ // Fetch plans from API+ const response = await fetch(`${apiUrl}/plans`, {+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'X-Org-Id': orgId+ }+ });++ if (!response.ok) {+ throw new Error('Failed to fetch plans');+ }++ const data = await response.json();+ plans = data.plans || [];++ // Initialize Fuse.js for fuzzy search+ initializeFuseSearch();++ // Update plans list+ filteredPlans = [...plans];+ updatePlansList();++ hideLoading();+ } catch (error) {+ console.error('Error loading plans:', error);+ hideLoading();+ showError('Failed to load plans: ' + error.message);+ }+}++// Initialize Fuse.js for fuzzy search+function initializeFuseSearch() {+ const options = {+ keys: ['name', 'description'],+ threshold: 0.3,+ ignoreLocation: true+ };++ fuseInstance = new Fuse(plans, options);+}++// Update plans list in the UI+function updatePlansList() {+ // Clear current list+ plansList.innerHTML = '';++ if (filteredPlans.length === 0) {+ noPlansMessage.classList.remove('hidden');+ return;+ }++ noPlansMessage.classList.add('hidden');++ // Create plan items+ filteredPlans.forEach(plan => {+ const planItem = document.createElement('div');+ planItem.className = 'plan-item';+ planItem.dataset.planId = plan.id;++ if (selectedPlan && selectedPlan.id === plan.id) {+ planItem.classList.add('selected');+ }++ const planName = document.createElement('div');+ planName.className = 'plan-name';+ planName.textContent = plan.name;++ const planDescription = document.createElement('div');+ planDescription.className = 'plan-description';+ planDescription.textContent = plan.description || 'No description';++ planItem.appendChild(planName);+ planItem.appendChild(planDescription);++ // Add click event+ planItem.addEventListener('click', () => {+ selectPlan(plan);+ });++ plansList.appendChild(planItem);+ });+}++// Select a plan+function selectPlan(plan) {+ selectedPlan = plan;++ // Update UI+ const planItems = plansList.querySelectorAll('.plan-item');+ planItems.forEach(item => {+ if (item.dataset.planId === plan.id) {+ item.classList.add('selected');+ } else {+ item.classList.remove('selected');+ }+ });++ // Enable send button+ sendButton.disabled = false;+}++// Search plans+function searchPlans(query) {+ if (!query) {+ filteredPlans = [...plans];+ } else {+ const results = fuseInstance.search(query);+ filteredPlans = results.map(result => result.item);+ }++ updatePlansList();+}++// Show loading indicator+function showLoading() {+ plansList.innerHTML = `+ <div class="loading-indicator">+ <div class="spinner"></div>+ <p>Loading plans...</p>+ </div>+ `;+ noPlansMessage.classList.add('hidden');+ errorMessage.classList.add('hidden');+}++// Hide loading indicator+function hideLoading() {+ const loadingIndicator = plansList.querySelector('.loading-indicator');+ if (loadingIndicator) {+ loadingIndicator.remove();+ }+}++// Show error message+function showError(message) {+ errorMessage.textContent = message;+ errorMessage.classList.remove('hidden');+}++// Send selected text to plan+async function sendTextToPlan() {+ if (!selectedPlan || !selectedText) {+ return;+ }++ try {+ // Disable send button and show loading state+ sendButton.disabled = true;+ sendButton.textContent = 'Sending...';++ // Get current branch for the plan+ const tokenData = await chrome.storage.local.get(STORAGE_KEYS.AUTH_TOKEN);+ const orgIdData = await chrome.storage.local.get(STORAGE_KEYS.ORG_ID);+ const apiUrlData = await chrome.storage.local.get(STORAGE_KEYS.API_URL);++ const token = tokenData[STORAGE_KEYS.AUTH_TOKEN];+ const orgId = orgIdData[STORAGE_KEYS.ORG_ID];+ const apiUrl = apiUrlData[STORAGE_KEYS.API_URL] || 'https://api.plandex.ai';++ if (!token || !orgId) {+ throw new Error('Not authenticated');+ }++ // Get current branch+ const branchResponse = await fetch(`${apiUrl}/plans/${selectedPlan.id}/current_branch`, {+ headers: {+ 'Authorization': `Bearer ${token}`,+ 'X-Org-Id': orgId+ }+ });++ if (!branchResponse.ok) {+ throw new Error('Failed to fetch current branch');+ }++ const branchData = await branchResponse.json();+ const branch = branchData.branch || 'main';++ // Create context name with source URL if available+ let contextName = 'Selected text from web';+ if (sourceUrl) {+ contextName = `Selected text from ${new URL(sourceUrl).hostname}`;+ }++ // Send text to plan+ const response = await chrome.runtime.sendMessage({+ action: 'sendToPlan',+ planId: selectedPlan.id,+ branch: branch,+ text: selectedText,+ name: contextName+ });++ if (!response.success) {+ throw new Error(response.error || 'Failed to send text to plan');+ }++ // Show success message in the source tab+ if (sourceTab) {+ chrome.tabs.sendMessage(sourceTab, {+ action: 'showNotification',+ type: 'success',+ message: `Text sent to plan: ${selectedPlan.name}`+ });+ }++ // Close the popup+ window.close();+ } catch (error) {+ console.error('Error sending text to plan:', error);++ // Reset send button+ sendButton.disabled = false;+ sendButton.textContent = 'Send to Plan';++ // Show error message+ showError('Failed to send text: ' + error.message);++ // Show error notification in the source tab+ if (sourceTab) {+ chrome.tabs.sendMessage(sourceTab, {+ action: 'showNotification',+ type: 'error',+ message: 'Failed to send text to plan'+ });+ }+ }+}++// Set up event listeners+function setupEventListeners() {+ // Search input+ searchInput.addEventListener('input', () => {+ searchPlans(searchInput.value.trim());+ });++ // Send button+ sendButton.addEventListener('click', sendTextToPlan);++ // Cancel button+ cancelButton.addEventListener('click', () => {+ window.close();+ });++ // Keyboard navigation+ document.addEventListener('keydown', (event) => {+ // Enter key to send+ if (event.key === 'Enter' && selectedPlan) {+ sendTextToPlan();+ }++ // Escape key to cancel+ if (event.key === 'Escape') {+ window.close();+ }++ // Arrow keys to navigate plans+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {+ event.preventDefault();++ if (filteredPlans.length === 0) {+ return;+ }++ const currentIndex = selectedPlan+ ? filteredPlans.findIndex(plan => plan.id === selectedPlan.id)+ : -1;++ let newIndex;++ if (event.key === 'ArrowDown') {+ newIndex = currentIndex < filteredPlans.length - 1 ? currentIndex + 1 : 0;+ } else {+ newIndex = currentIndex > 0 ? currentIndex - 1 : filteredPlans.length - 1;+ }++ selectPlan(filteredPlans[newIndex]);++ // Scroll to selected plan+ const selectedElement = plansList.querySelector('.selected');+ if (selectedElement) {+ selectedElement.scrollIntoView({ block: 'nearest' });+ }+ }+ });+}diff --git a/popup.css b/popup.cssnew file mode 100644index 00000000..e48b5092--- /dev/null+++ b/popup.css@@ -0,0 +1,157 @@+/* Reset and base styles */+* {+ margin: 0;+ padding: 0;+ box-sizing: border-box;+}++body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;+ font-size: 14px;+ line-height: 1.5;+ color: #333;+ background-color: #f5f5f5;+}++.container {+ width: 350px;+ min-height: 400px;+ background-color: #fff;+ box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);+}++/* Header styles */+header {+ padding: 15px;+ background-color: #4285f4;+ color: white;+ text-align: center;+}++header h1 {+ font-size: 18px;+ font-weight: 500;+}++/* Main content styles */+main {+ padding: 15px;+}++h2 {+ font-size: 16px;+ margin-bottom: 10px;+ color: #333;+}++/* Section styles */+#auth-section,+#settings-section,+#status-section {+ margin-bottom: 20px;+ padding-bottom: 20px;+ border-bottom: 1px solid #eee;+}++#status-section {+ border-bottom: none;+}++/* Form styles */+.form-group {+ margin-bottom: 15px;+}++label {+ display: block;+ margin-bottom: 5px;+ font-weight: 500;+}++input {+ width: 100%;+ padding: 8px 10px;+ border: 1px solid #ddd;+ border-radius: 4px;+ font-size: 14px;+}++input:focus {+ outline: none;+ border-color: #4285f4;+ box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);+}++/* Button styles */+.btn {+ display: inline-block;+ padding: 8px 16px;+ border: none;+ border-radius: 4px;+ font-size: 14px;+ font-weight: 500;+ cursor: pointer;+ transition: background-color 0.2s;+}++.primary-btn {+ background-color: #4285f4;+ color: white;+}++.primary-btn:hover {+ background-color: #3367d6;+}++.secondary-btn {+ background-color: #f1f3f4;+ color: #333;+}++.secondary-btn:hover {+ background-color: #e8eaed;+}++/* Status info styles */+.status-info p,+.user-info p {+ margin-bottom: 5px;+}++.status-info span,+.user-info span {+ font-weight: 500;+}++/* Message styles */+.message,+.error-message {+ margin-top: 10px;+ padding: 8px 12px;+ border-radius: 4px;+ font-size: 13px;+}++.error-message {+ background-color: #fdecea;+ color: #d93025;+}++.success-message {+ background-color: #e6f4ea;+ color: #137333;+}++/* Utility classes */+.hidden {+ display: none;+}++/* Footer styles */+footer {+ padding: 10px 15px;+ text-align: center;+ font-size: 12px;+ color: #666;+ background-color: #f8f9fa;+}diff --git a/popup.html b/popup.htmlnew file mode 100644index 00000000..9ed2477a--- /dev/null+++ b/popup.html@@ -0,0 +1,67 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Plandex Extension</title>+ <link rel="stylesheet" href="popup.css">+</head>+<body>+ <div class="container">+ <header>+ <h1>Plandex Extension</h1>+ </header>++ <main>+ <div id="auth-section">+ <div id="not-authenticated" class="auth-state">+ <h2>Sign In</h2>+ <p>Enter the sign-in code generated by the Plandex CLI:</p>+ <form id="auth-form">+ <div class="form-group">+ <input type="text" id="sign-in-code" placeholder="Sign-in code" required>+ </div>+ <button type="submit" id="sign-in-btn" class="btn primary-btn">Sign In</button>+ </form>+ <div id="auth-error" class="error-message hidden"></div>+ </div>++ <div id="authenticated" class="auth-state hidden">+ <h2>Signed In</h2>+ <div class="user-info">+ <p>You are signed in as <span id="user-name">User</span></p>+ <p>Email: <span id="user-email">[email protected]</span></p>+ </div>+ <button id="sign-out-btn" class="btn secondary-btn">Sign Out</button>+ </div>+ </div>++ <div id="settings-section">+ <h2>Settings</h2>+ <form id="settings-form">+ <div class="form-group">+ <label for="api-url">API URL:</label>+ <input type="url" id="api-url" placeholder="https://api.plandex.ai">+ </div>+ <button type="submit" id="save-settings-btn" class="btn primary-btn">Save Settings</button>+ </form>+ <div id="settings-message" class="message hidden"></div>+ </div>++ <div id="status-section">+ <h2>Status</h2>+ <div class="status-info">+ <p>Context Menu: <span id="context-menu-status">Disabled</span></p>+ <p>Authentication: <span id="auth-status">Not authenticated</span></p>+ </div>+ </div>+ </main>++ <footer>+ <p>Plandex Extension v1.0.0</p>+ </footer>+ </div>++ <script src="popup.js"></script>+</body>+</html>diff --git a/popup.js b/popup.jsnew file mode 100644index 00000000..8a2f3d61--- /dev/null+++ b/popup.js@@ -0,0 +1,277 @@+// Constants+const STORAGE_KEYS = {+ AUTH_TOKEN: "plandex_auth_token",+ ORG_ID: "plandex_org_id",+ API_URL: "plandex_api_url",+ USER_INFO: "plandex_user_info"+};++// DOM Elements+const authForm = document.getElementById('auth-form');+const signInCode = document.getElementById('sign-in-code');+const signInBtn = document.getElementById('sign-in-btn');+const signOutBtn = document.getElementById('sign-out-btn');+const authError = document.getElementById('auth-error');+const notAuthenticatedSection = document.getElementById('not-authenticated');+const authenticatedSection = document.getElementById('authenticated');+const userName = document.getElementById('user-name');+const userEmail = document.getElementById('user-email');+const settingsForm = document.getElementById('settings-form');+const apiUrlInput = document.getElementById('api-url');+const saveSettingsBtn = document.getElementById('save-settings-btn');+const settingsMessage = document.getElementById('settings-message');+const contextMenuStatus = document.getElementById('context-menu-status');+const authStatus = document.getElementById('auth-status');++// Initialize the popup+document.addEventListener('DOMContentLoaded', async () => {+ // Load saved API URL+ loadApiUrl();++ // Check authentication status+ await checkAuthStatus();++ // Set up event listeners+ setupEventListeners();+});++// Load saved API URL+async function loadApiUrl() {+ try {+ const data = await chrome.storage.local.get(STORAGE_KEYS.API_URL);+ const apiUrl = data[STORAGE_KEYS.API_URL] || 'https://api.plandex.ai';+ apiUrlInput.value = apiUrl;+ } catch (error) {+ console.error('Error loading API URL:', error);+ apiUrlInput.value = 'https://api.plandex.ai';+ }+}++// Check authentication status+async function checkAuthStatus() {+ try {+ // Send message to background script to check auth status+ const response = await chrome.runtime.sendMessage({ action: 'checkAuth' });++ if (response.authenticated) {+ // Load user info+ const userInfo = await loadUserInfo();++ // Update UI for authenticated state+ updateAuthenticatedUI(userInfo);+ } else {+ // Update UI for not authenticated state+ updateNotAuthenticatedUI();+ }+ } catch (error) {+ console.error('Error checking auth status:', error);+ updateNotAuthenticatedUI();+ }+}++// Load user info from storage+async function loadUserInfo() {+ try {+ const data = await chrome.storage.local.get(STORAGE_KEYS.USER_INFO);+ return data[STORAGE_KEYS.USER_INFO] || { name: 'User', email: '[email protected]' };+ } catch (error) {+ console.error('Error loading user info:', error);+ return { name: 'User', email: '[email protected]' };+ }+}++// Update UI for authenticated state+function updateAuthenticatedUI(userInfo) {+ // Update user info+ userName.textContent = userInfo.name || 'User';+ userEmail.textContent = userInfo.email || '[email protected]';++ // Show authenticated section, hide not authenticated section+ notAuthenticatedSection.classList.add('hidden');+ authenticatedSection.classList.remove('hidden');++ // Update status+ contextMenuStatus.textContent = 'Enabled';+ authStatus.textContent = 'Authenticated';++ // Clear sign-in code input+ signInCode.value = '';++ // Clear error message+ authError.textContent = '';+ authError.classList.add('hidden');+}++// Update UI for not authenticated state+function updateNotAuthenticatedUI() {+ // Show not authenticated section, hide authenticated section+ notAuthenticatedSection.classList.remove('hidden');+ authenticatedSection.classList.add('hidden');++ // Update status+ contextMenuStatus.textContent = 'Disabled';+ authStatus.textContent = 'Not authenticated';+}++// Set up event listeners+function setupEventListeners() {+ // Auth form submit+ authForm.addEventListener('submit', handleSignIn);++ // Sign out button click+ signOutBtn.addEventListener('click', handleSignOut);++ // Settings form submit+ settingsForm.addEventListener('submit', handleSaveSettings);+}++// Handle sign in+async function handleSignIn(event) {+ event.preventDefault();++ const code = signInCode.value.trim();++ if (!code) {+ showAuthError('Please enter a sign-in code');+ return;+ }++ try {+ // Disable sign in button and show loading state+ signInBtn.disabled = true;+ signInBtn.textContent = 'Signing in...';++ // Send message to background script to authenticate+ const response = await chrome.runtime.sendMessage({+ action: 'authenticate',+ code: code+ });++ // Reset sign in button+ signInBtn.disabled = false;+ signInBtn.textContent = 'Sign In';++ if (response.success) {+ // Update UI for authenticated state+ updateAuthenticatedUI(response.user);+ } else {+ // Show error message+ showAuthError(response.error || 'Authentication failed');+ }+ } catch (error) {+ console.error('Error signing in:', error);++ // Reset sign in button+ signInBtn.disabled = false;+ signInBtn.textContent = 'Sign In';++ // Show error message+ showAuthError('An error occurred while signing in');+ }+}++// Show authentication error+function showAuthError(message) {+ authError.textContent = message;+ authError.classList.remove('hidden');+}++// Handle sign out+async function handleSignOut() {+ try {+ // Disable sign out button and show loading state+ signOutBtn.disabled = true;+ signOutBtn.textContent = 'Signing out...';++ // Send message to background script to logout+ const response = await chrome.runtime.sendMessage({ action: 'logout' });++ // Reset sign out button+ signOutBtn.disabled = false;+ signOutBtn.textContent = 'Sign Out';++ if (response.success) {+ // Update UI for not authenticated state+ updateNotAuthenticatedUI();+ } else {+ // Show error message+ console.error('Error signing out:', response.error);+ }+ } catch (error) {+ console.error('Error signing out:', error);++ // Reset sign out button+ signOutBtn.disabled = false;+ signOutBtn.textContent = 'Sign Out';+ }+}++// Handle save settings+async function handleSaveSettings(event) {+ event.preventDefault();++ const apiUrl = apiUrlInput.value.trim();++ if (!apiUrl) {+ showSettingsMessage('Please enter an API URL', false);+ return;+ }++ try {+ // Validate URL format+ new URL(apiUrl);++ // Disable save button and show loading state+ saveSettingsBtn.disabled = true;+ saveSettingsBtn.textContent = 'Saving...';++ // Send message to background script to update API URL+ const response = await chrome.runtime.sendMessage({+ action: 'updateApiUrl',+ apiUrl: apiUrl+ });++ // Reset save button+ saveSettingsBtn.disabled = false;+ saveSettingsBtn.textContent = 'Save Settings';++ if (response.success) {+ // Show success message+ showSettingsMessage('Settings saved successfully', true);++ // Check authentication status again+ await checkAuthStatus();+ } else {+ // Show error message+ showSettingsMessage(response.error || 'Failed to save settings', false);+ }+ } catch (error) {+ console.error('Error saving settings:', error);++ // Reset save button+ saveSettingsBtn.disabled = false;+ saveSettingsBtn.textContent = 'Save Settings';++ // Show error message+ showSettingsMessage('Please enter a valid URL', false);+ }+}++// Show settings message+function showSettingsMessage(message, isSuccess) {+ settingsMessage.textContent = message;+ settingsMessage.classList.remove('hidden');++ if (isSuccess) {+ settingsMessage.classList.add('success-message');+ settingsMessage.classList.remove('error-message');+ } else {+ settingsMessage.classList.add('error-message');+ settingsMessage.classList.remove('success-message');+ }++ // Hide message after 3 seconds+ setTimeout(() => {+ settingsMessage.classList.add('hidden');+ }, 3000);+}diff --git a/utils.js b/utils.jsnew file mode 100644index 00000000..c2344624--- /dev/null+++ b/utils.js@@ -0,0 +1,685 @@+/**+ * Plandex Extension Utilities+ * Contains helper functions for common tasks, error handling, storage management, and notifications+ */++// Constants+const STORAGE_KEYS = {+ AUTH_TOKEN: "plandex_auth_token",+ ORG_ID: "plandex_org_id",+ API_URL: "plandex_api_url",+ USER_INFO: "plandex_user_info",+ SELECTED_TEXT: "selectedText",+ SOURCE_TAB: "sourceTab",+ SOURCE_URL: "sourceUrl",+ HAS_SELECTED_TEXT: "hasSelectedText"+};++/**+ * Storage utilities+ */+const storage = {+ /**+ * Get a value from storage+ * @param {string} key - Storage key+ * @param {any} defaultValue - Default value if key doesn't exist+ * @returns {Promise<any>} - Value from storage or default value+ */+ async get(key, defaultValue = null) {+ try {+ const data = await chrome.storage.local.get(key);+ return data[key] !== undefined ? data[key] : defaultValue;+ } catch (error) {+ console.error(`Error getting ${key} from storage:`, error);+ return defaultValue;+ }+ },++ /**+ * Set a value in storage+ * @param {string} key - Storage key+ * @param {any} value - Value to store+ * @returns {Promise<boolean>} - Success status+ */+ async set(key, value) {+ try {+ await chrome.storage.local.set({ [key]: value });+ return true;+ } catch (error) {+ console.error(`Error setting ${key} in storage:`, error);+ return false;+ }+ },++ /**+ * Remove a value from storage+ * @param {string} key - Storage key+ * @returns {Promise<boolean>} - Success status+ */+ async remove(key) {+ try {+ await chrome.storage.local.remove(key);+ return true;+ } catch (error) {+ console.error(`Error removing ${key} from storage:`, error);+ return false;+ }+ },++ /**+ * Clear all storage+ * @returns {Promise<boolean>} - Success status+ */+ async clear() {+ try {+ await chrome.storage.local.clear();+ return true;+ } catch (error) {+ console.error('Error clearing storage:', error);+ return false;+ }+ },++ /**+ * Get authentication token from storage+ * @returns {Promise<string|null>} - Authentication token or null+ */+ async getAuthToken() {+ return await this.get(STORAGE_KEYS.AUTH_TOKEN, null);+ },++ /**+ * Get organization ID from storage+ * @returns {Promise<string|null>} - Organization ID or null+ */+ async getOrgId() {+ return await this.get(STORAGE_KEYS.ORG_ID, null);+ },++ /**+ * Get API URL from storage+ * @returns {Promise<string>} - API URL or default+ */+ async getApiUrl() {+ return await this.get(STORAGE_KEYS.API_URL, 'https://api.plandex.ai');+ },++ /**+ * Get user info from storage+ * @returns {Promise<Object|null>} - User info or null+ */+ async getUserInfo() {+ return await this.get(STORAGE_KEYS.USER_INFO, null);+ },++ /**+ * Check if user is authenticated+ * @returns {Promise<boolean>} - Authentication status+ */+ async isAuthenticated() {+ const token = await this.getAuthToken();+ const orgId = await this.getOrgId();+ return !!(token && orgId);+ },++ /**+ * Store selected text and source info+ * @param {string} text - Selected text+ * @param {number} tabId - Source tab ID+ * @param {string} url - Source URL+ * @returns {Promise<boolean>} - Success status+ */+ async storeSelectedText(text, tabId, url) {+ try {+ await chrome.storage.local.set({+ [STORAGE_KEYS.SELECTED_TEXT]: text,+ [STORAGE_KEYS.SOURCE_TAB]: tabId,+ [STORAGE_KEYS.SOURCE_URL]: url+ });+ return true;+ } catch (error) {+ console.error('Error storing selected text:', error);+ return false;+ }+ },++ /**+ * Get selected text and source info+ * @returns {Promise<Object>} - Selected text and source info+ */+ async getSelectedText() {+ try {+ const data = await chrome.storage.local.get([+ STORAGE_KEYS.SELECTED_TEXT,+ STORAGE_KEYS.SOURCE_TAB,+ STORAGE_KEYS.SOURCE_URL+ ]);++ return {+ text: data[STORAGE_KEYS.SELECTED_TEXT] || '',+ tabId: data[STORAGE_KEYS.SOURCE_TAB] || null,+ url: data[STORAGE_KEYS.SOURCE_URL] || ''+ };+ } catch (error) {+ console.error('Error getting selected text:', error);+ return { text: '', tabId: null, url: '' };+ }+ }+};++/**+ * Error handling utilities+ */+const errorHandler = {+ /**+ * Handle API errors+ * @param {Error} error - Error object+ * @param {string} operation - Operation description+ * @returns {Object} - Formatted error object+ */+ handleApiError(error, operation) {+ console.error(`API Error (${operation}):`, error);++ let message = 'An unexpected error occurred';+ let status = 500;++ if (error.response) {+ // Server responded with an error status+ status = error.response.status;++ switch (status) {+ case 401:+ message = 'Authentication failed. Please sign in again.';+ break;+ case 403:+ message = 'You do not have permission to perform this action.';+ break;+ case 404:+ message = 'The requested resource was not found.';+ break;+ case 429:+ message = 'Too many requests. Please try again later.';+ break;+ default:+ message = error.response.data?.message || 'Server error. Please try again later.';+ }+ } else if (error.request) {+ // Request was made but no response received+ message = 'No response from server. Please check your connection.';+ } else {+ // Error setting up the request+ message = error.message || 'Error setting up the request.';+ }++ return {+ success: false,+ status,+ message,+ operation,+ originalError: error+ };+ },++ /**+ * Handle authentication errors+ * @param {Error} error - Error object+ * @returns {Object} - Formatted error object+ */+ handleAuthError(error) {+ console.error('Authentication Error:', error);++ // Clear authentication data+ storage.remove(STORAGE_KEYS.AUTH_TOKEN);+ storage.remove(STORAGE_KEYS.ORG_ID);+ storage.remove(STORAGE_KEYS.USER_INFO);++ return this.handleApiError(error, 'authentication');+ },++ /**+ * Format error for display+ * @param {Error|string} error - Error object or message+ * @returns {string} - Formatted error message+ */+ formatErrorMessage(error) {+ if (typeof error === 'string') {+ return error;+ }++ if (error.message) {+ return error.message;+ }++ return 'An unexpected error occurred';+ }+};++/**+ * Notification utilities+ */+const notifications = {+ /**+ * Show a notification in a tab+ * @param {number} tabId - Tab ID+ * @param {string} message - Notification message+ * @param {string} type - Notification type (success, error, warning, info)+ * @param {number} duration - Duration in milliseconds+ * @returns {Promise<boolean>} - Success status+ */+ async showInTab(tabId, message, type = 'info', duration = 3000) {+ try {+ await chrome.tabs.sendMessage(tabId, {+ action: 'showNotification',+ message,+ type,+ duration+ });+ return true;+ } catch (error) {+ console.error('Error showing notification:', error);+ return false;+ }+ },++ /**+ * Show a Chrome notification+ * @param {string} title - Notification title+ * @param {string} message - Notification message+ * @param {string} type - Notification type (basic, image, list, progress)+ * @returns {Promise<string>} - Notification ID+ */+ async showChromeNotification(title, message, type = 'basic') {+ try {+ const notificationId = 'plandex-' + Date.now();++ await chrome.notifications.create(notificationId, {+ type: type,+ iconUrl: chrome.runtime.getURL('icons/icon48.png'),+ title: title,+ message: message+ });++ return notificationId;+ } catch (error) {+ console.error('Error showing Chrome notification:', error);+ return null;+ }+ }+};++/**+ * URL utilities+ */+const urlUtils = {+ /**+ * Get domain from URL+ * @param {string} url - URL+ * @returns {string} - Domain+ */+ getDomain(url) {+ try {+ const urlObj = new URL(url);+ return urlObj.hostname;+ } catch (error) {+ console.error('Error parsing URL:', error);+ return '';+ }+ },++ /**+ * Check if URL is valid+ * @param {string} url - URL+ * @returns {boolean} - Validity status+ */+ isValidUrl(url) {+ try {+ new URL(url);+ return true;+ } catch (error) {+ return false;+ }+ },++ /**+ * Ensure URL has protocol+ * @param {string} url - URL+ * @returns {string} - URL with protocol+ */+ ensureProtocol(url) {+ if (!url) return '';++ if (!url.startsWith('http://') && !url.startsWith('https://')) {+ return 'https://' + url;+ }++ return url;+ }+};++/**+ * Text utilities+ */+const textUtils = {+ /**+ * Truncate text+ * @param {string} text - Text to truncate+ * @param {number} maxLength - Maximum length+ * @param {string} suffix - Suffix to add+ * @returns {string} - Truncated text+ */+ truncate(text, maxLength = 100, suffix = '...') {+ if (!text) return '';++ if (text.length <= maxLength) {+ return text;+ }++ return text.substring(0, maxLength) + suffix;+ },++ /**+ * Create context name from URL+ * @param {string} url - URL+ * @returns {string} - Context name+ */+ createContextName(url) {+ if (!url) {+ return 'Selected text from web';+ }++ try {+ const domain = urlUtils.getDomain(url);+ return `Selected text from ${domain}`;+ } catch (error) {+ return 'Selected text from web';+ }+ },++ /**+ * Sanitize text for display+ * @param {string} text - Text to sanitize+ * @returns {string} - Sanitized text+ */+ sanitize(text) {+ if (!text) return '';++ // Replace HTML tags with their entities+ return text+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+ }+};++/**+ * DOM utilities+ */+const domUtils = {+ /**+ * Create element with attributes and children+ * @param {string} tag - Element tag+ * @param {Object} attributes - Element attributes+ * @param {Array|string|Node} children - Element children+ * @returns {HTMLElement} - Created element+ */+ createElement(tag, attributes = {}, children = []) {+ const element = document.createElement(tag);++ // Set attributes+ Object.entries(attributes).forEach(([key, value]) => {+ if (key === 'style' && typeof value === 'object') {+ Object.entries(value).forEach(([styleKey, styleValue]) => {+ element.style[styleKey] = styleValue;+ });+ } else if (key === 'className') {+ element.className = value;+ } else if (key === 'dataset' && typeof value === 'object') {+ Object.entries(value).forEach(([dataKey, dataValue]) => {+ element.dataset[dataKey] = dataValue;+ });+ } else if (key.startsWith('on') && typeof value === 'function') {+ const eventName = key.substring(2).toLowerCase();+ element.addEventListener(eventName, value);+ } else {+ element.setAttribute(key, value);+ }+ });++ // Add children+ if (children) {+ if (Array.isArray(children)) {+ children.forEach(child => {+ if (child) {+ if (typeof child === 'string') {+ element.appendChild(document.createTextNode(child));+ } else {+ element.appendChild(child);+ }+ }+ });+ } else if (typeof children === 'string') {+ element.textContent = children;+ } else {+ element.appendChild(children);+ }+ }++ return element;+ },++ /**+ * Show element+ * @param {HTMLElement} element - Element to show+ */+ showElement(element) {+ if (element) {+ element.classList.remove('hidden');+ }+ },++ /**+ * Hide element+ * @param {HTMLElement} element - Element to hide+ */+ hideElement(element) {+ if (element) {+ element.classList.add('hidden');+ }+ },++ /**+ * Toggle element visibility+ * @param {HTMLElement} element - Element to toggle+ * @param {boolean} show - Show or hide+ */+ toggleElement(element, show) {+ if (element) {+ if (show) {+ this.showElement(element);+ } else {+ this.hideElement(element);+ }+ }+ },++ /**+ * Create a notification element+ * @param {string} message - Notification message+ * @param {string} type - Notification type (success, error, warning, info)+ * @param {number} duration - Duration in milliseconds+ * @returns {HTMLElement} - Notification element+ */+ createNotification(message, type = 'info', duration = 3000) {+ // Create container if it doesn't exist+ let container = document.getElementById('plandex-notification-container');+ if (!container) {+ container = this.createElement('div', {+ id: 'plandex-notification-container',+ style: {+ position: 'fixed',+ bottom: '20px',+ right: '20px',+ zIndex: '9999',+ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif'+ }+ });+ document.body.appendChild(container);+ }++ // Create notification+ const notification = this.createElement('div', {+ className: `plandex-notification plandex-notification-${type}`,+ style: {+ padding: '12px 16px',+ marginBottom: '10px',+ borderRadius: '4px',+ boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',+ fontSize: '14px',+ lineHeight: '1.5',+ display: 'flex',+ alignItems: 'center',+ transition: 'opacity 0.3s ease-in-out, transform 0.3s ease-in-out',+ opacity: '0',+ transform: 'translateY(20px)',+ maxWidth: '300px',+ wordBreak: 'break-word'+ }+ });++ // Set background color based on notification type+ if (type === 'success') {+ notification.style.backgroundColor = '#e6f4ea';+ notification.style.color = '#137333';+ notification.style.borderLeft = '4px solid #137333';+ } else if (type === 'error') {+ notification.style.backgroundColor = '#fdecea';+ notification.style.color = '#d93025';+ notification.style.borderLeft = '4px solid #d93025';+ } else if (type === 'warning') {+ notification.style.backgroundColor = '#fef7e0';+ notification.style.color = '#b06000';+ notification.style.borderLeft = '4px solid #b06000';+ } else {+ notification.style.backgroundColor = '#e8f0fe';+ notification.style.color = '#1a73e8';+ notification.style.borderLeft = '4px solid #1a73e8';+ }++ // Create icon+ let iconSvg = '';+ if (type === 'success') {+ iconSvg = `+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>+ <polyline points="22 4 12 14.01 9 11.01"></polyline>+ </svg>+ `;+ } else if (type === 'error') {+ iconSvg = `+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="10"></circle>+ <line x1="15" y1="9" x2="9" y2="15"></line>+ <line x1="9" y1="9" x2="15" y2="15"></line>+ </svg>+ `;+ } else if (type === 'warning') {+ iconSvg = `+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path>+ <line x1="12" y1="9" x2="12" y2="13"></line>+ <line x1="12" y1="17" x2="12.01" y2="17"></line>+ </svg>+ `;+ } else {+ iconSvg = `+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <circle cx="12" cy="12" r="10"></circle>+ <line x1="12" y1="8" x2="12" y2="12"></line>+ <line x1="12" y1="16" x2="12.01" y2="16"></line>+ </svg>+ `;+ }++ const icon = this.createElement('div', {+ style: {+ marginRight: '10px'+ },+ innerHTML: iconSvg+ });++ // Create message+ const messageElement = this.createElement('div', {}, message);++ // Create close button+ const closeButton = this.createElement('div', {+ style: {+ marginLeft: '10px',+ cursor: 'pointer',+ opacity: '0.7',+ transition: 'opacity 0.2s'+ },+ innerHTML: `+ <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <line x1="18" y1="6" x2="6" y2="18"></line>+ <line x1="6" y1="6" x2="18" y2="18"></line>+ </svg>+ `,+ onmouseover: () => { closeButton.style.opacity = '1'; },+ onmouseout: () => { closeButton.style.opacity = '0.7'; },+ onclick: () => { this.removeNotification(notification); }+ });++ // Append elements+ notification.appendChild(icon);+ notification.appendChild(messageElement);+ notification.appendChild(closeButton);++ // Append to container+ container.appendChild(notification);++ // Show notification with animation+ setTimeout(() => {+ notification.style.opacity = '1';+ notification.style.transform = 'translateY(0)';+ }, 10);++ // Remove notification after duration+ if (duration > 0) {+ setTimeout(() => {+ this.removeNotification(notification);+ }, duration);+ }++ return notification;+ },++ /**+ * Remove a notification with animation+ * @param {HTMLElement} notification - Notification element+ */+ removeNotification(notification) {+ if (notification) {+ notification.style.opacity = '0';+ notification.style.transform = 'translateY(20px)';++ setTimeout(() => {+ if (notification.parentNode) {+ notification.parentNode.removeChild(notification);+ }+ }, 300);+ }+ }+};++// Export utilities+export {+ STORAGE_KEYS,+ storage,+ errorHandler,+ notifications,+ urlUtils,+ textUtils,+ domUtils+};diff --git a/webpack.config.js b/webpack.config.jsnew file mode 100644index 00000000..3c2d7ca0--- /dev/null+++ b/webpack.config.js@@ -0,0 +1,66 @@+const path = require('path');+const CopyPlugin = require('copy-webpack-plugin');+const HtmlWebpackPlugin = require('html-webpack-plugin');++module.exports = {+ entry: {+ background: './background.js',+ content: './content.js',+ popup: './popup.js',+ planSelector: './planSelector.js',+ api: './api.js',+ utils: './utils.js'+ },+ output: {+ path: path.resolve(__dirname, 'dist'),+ filename: '[name].js',+ clean: true+ },+ module: {+ rules: [+ {+ test: /\\.js$/,+ exclude: /node_modules/,+ use: {+ loader: 'babel-loader',+ options: {+ presets: ['@babel/preset-env']+ }+ }+ },+ {+ test: /\\.css$/,+ use: ['style-loader', 'css-loader']+ }+ ]+ },+ plugins: [+ new CopyPlugin({+ patterns: [+ { from: 'manifest.json', to: 'manifest.json' },+ { from: 'popup.css', to: 'popup.css' },+ { from: 'planSelector.css', to: 'planSelector.css' },+ {+ from: 'icons',+ to: 'icons',+ noErrorOnMissing: true+ }+ ]+ }),+ new HtmlWebpackPlugin({+ template: './popup.html',+ filename: 'popup.html',+ chunks: ['popup']+ }),+ new HtmlWebpackPlugin({+ template: './planSelector.html',+ filename: 'planSelector.html',+ chunks: ['planSelector']+ })+ ],+ optimization: {+ splitChunks: {+ chunks: 'all'+ }+ }+};