diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3468613 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + branches: [master] + push: + branches: [master] + +permissions: + contents: read + +jobs: + test-and-build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: npm ci + - run: npm test + - run: npm run build + - run: npm run build:chromium diff --git a/.gitignore b/.gitignore index 28f44c0..72fbaf1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ node_modules/ dist/ +dist-chromium/ *.log .DS_Store web-ext-artifacts/ diff --git a/README.md b/README.md index 761d7cb..6e711b6 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # BagMark πŸŽ’ -> An advanced, lightweight Firefox extension to quickly save bookmarks to customizable or date-organized folders with rich metadata and duplicate detection. +> An advanced, lightweight extension for Firefox, Chrome, and Brave to quickly save bookmarks to customizable or date-organized folders with rich metadata and duplicate detection. ![BagMark Icon](public/assets/icon.svg) @@ -12,10 +12,11 @@ - **Context Submenus for Custom Folders**: Right-click submenu (`"Bag It to β–Έ"`) dynamically lists your favorite / pinned bookmark folders. - **Chronological Date Organization**: Optional auto-filing into year-month subfolders (e.g. `BagMark / 2026-09 / ...`), created on the fly. - **Rich Metadata Capture**: Automatically records exact timestamps (`dateAdded`), originating webpage URL/title, and any highlighted quote/text excerpt into local storage. -- **Duplicate Link Detection**: Alerts you if a link has already been bookmarked, showing where and when it was saved. +- **Duplicate Link Detection**: Skips links already saved in the destination folder while allowing the same link in other collections. Compares both URLs without known tracking parameters, preserving meaningful query parameters, fragments, and path differences. Disable this in Settings to allow repeated links in the same folder. - **Interactive Popup Dashboard**: Fast, search-as-you-type dashboard to filter bookmarks by title, URL, quote, or tags, with folder filters, relative time badges, and 1-click clipboard copy. +- **Save Open Tabs**: Expand **Save open tabs** in the popup, choose an existing folder or create a new subfolder, and save all web tabs from the current window in tab order. Tabs stay open, browser pages are skipped, and the result shows saved, skipped, and failed counts. The chosen folder is used directly, without automatic date subfolders. - **Options & Customization**: Configure default folder name, toggle date-based subfolders, manage pinned submenu folders, and adjust alert notifications. -- **Modern Stack**: Built with TypeScript, Vite, Vitest, and Firefox Manifest V3. +- **Modern Stack**: Built with TypeScript, Vite, Vitest, and Manifest V3. --- @@ -25,7 +26,7 @@ - Node.js (v18+) - npm or pnpm -- Mozilla Firefox (v115+) +- Mozilla Firefox (v115+), Chrome (v123+), or Brave based on Chromium v123+ ### Installation & Development @@ -56,6 +57,21 @@ - Select `dist/manifest.json` from this project directory. - Right-click any link on the web to start bagging links! +### Chrome & Brave + +Both browsers use the same Chromium build: + +```bash +npm run build:chromium +``` + +1. Open `chrome://extensions` in Chrome or `brave://extensions` in Brave. +2. Enable **Developer mode**. +3. Click **Load unpacked** and select the project's `dist-chromium` folder. +4. Pin BagMark to the toolbar, then right-click a webpage or link to save it. + +Firefox builds remain in `dist`; Chromium builds go to `dist-chromium` so rebuilding one does not remove the other. After rebuilding, click **Reload** on the extension's card. The existing packaging and signing commands produce Firefox artifacts; Chrome and Brave use the unpacked Chromium folder for local testing. + --- ## πŸ“¦ Distribution & Packaging @@ -111,7 +127,7 @@ bagmark/ β”‚ β”œβ”€β”€ utils.ts # Date formatters & URL normalizer β”‚ β”œβ”€β”€ storage.ts # Metadata local storage manager β”‚ β”œβ”€β”€ config.ts # Settings persistence -β”‚ └── bookmarks.ts # Firefox bookmark tree traversal & creation +β”‚ └── bookmarks.ts # Cross-browser bookmark tree traversal & creation └── tests/ # Vitest automated test suite ``` diff --git a/manifest.json b/manifest.json index ef9c26e..fad3020 100644 --- a/manifest.json +++ b/manifest.json @@ -1,11 +1,11 @@ { "manifest_version": 3, "name": "BagMark - Advanced Bookmarks", - "version": "1.0.2", + "version": "1.1.0", "description": "Right-click to save bookmarks to custom or date-based folders with rich metadata.", "permissions": [ "bookmarks", - "menus", + "contextMenus", "storage", "notifications", "tabs" diff --git a/package-lock.json b/package-lock.json index a588180..2b1bc40 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "bag-bookmark", - "version": "1.0.2", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "bag-bookmark", - "version": "1.0.2", + "version": "1.1.0", "devDependencies": { "@types/firefox-webext-browser": "^143.0.1", "@types/node": "^22.0.0", diff --git a/package.json b/package.json index b990c54..0183167 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,12 @@ { "name": "bag-bookmark", - "version": "1.0.2", - "description": "Advanced Firefox bookmark extension with date tracking, custom folders, and context menu quick-save", + "version": "1.1.0", + "description": "Advanced bookmark extension for Firefox, Chrome, and Brave with date tracking, custom folders, and context menu quick-save", "type": "module", "scripts": { "dev": "vite build --watch", "build": "tsc --noEmit && vite build", + "build:chromium": "tsc --noEmit && vite build --mode chromium", "lint": "tsc --noEmit", "test": "vitest run", "test:watch": "vitest", diff --git a/src/background/index.ts b/src/background/index.ts index 9451e02..48730b3 100644 --- a/src/background/index.ts +++ b/src/background/index.ts @@ -1,19 +1,19 @@ -import { ensureRootFolder, ensureDateSubfolder, findDuplicateBookmark } from '../lib/bookmarks'; +import '../lib/browser'; +import { saveBookmark } from '../lib/bookmarks'; import { getSettings } from '../lib/config'; -import { saveMetadata } from '../lib/storage'; -import { BookmarkMetadata } from '../lib/types'; import { formatDisplayDate } from '../lib/utils'; +import { saveOpenTabs } from '../lib/tabs'; const QUICK_SAVE_ID = 'bagmark_quick_save'; const SUBMENU_ROOT_ID = 'bagmark_submenu_root'; async function updateContextMenus() { - await browser.menus.removeAll(); + await browser.contextMenus.removeAll(); const settings = await getSettings(); // 1. Top-level 1-click Quick Save to default folder - browser.menus.create({ + browser.contextMenus.create({ id: QUICK_SAVE_ID, title: `Bag It (Save to ${settings.defaultFolderName})`, contexts: ['link', 'page', 'selection'], @@ -21,7 +21,7 @@ async function updateContextMenus() { // 2. Submenu for custom / favorite folders if (settings.favoriteFolderIds && settings.favoriteFolderIds.length > 0) { - browser.menus.create({ + browser.contextMenus.create({ id: SUBMENU_ROOT_ID, title: 'Bag It to β–Έ', contexts: ['link', 'page', 'selection'], @@ -31,7 +31,7 @@ async function updateContextMenus() { try { const nodes = await browser.bookmarks.get(folderId); if (nodes && nodes[0]) { - browser.menus.create({ + browser.contextMenus.create({ id: `bagmark_target_${folderId}`, parentId: SUBMENU_ROOT_ID, title: nodes[0].title, @@ -46,7 +46,7 @@ async function updateContextMenus() { } async function handleSaveAction( - info: browser.menus.OnClickData, + info: browser.contextMenus.OnClickData, tab?: browser.tabs.Tab ) { if (info.menuItemId === SUBMENU_ROOT_ID) { @@ -58,82 +58,39 @@ async function handleSaveAction( if (!targetUrl) return; const targetTitle = info.linkText || tab?.title || targetUrl; - const quote = info.selectionText || undefined; - const sourcePageUrl = info.pageUrl; - const sourcePageTitle = tab?.title; + try { + const targetFolderId = info.menuItemId.toString().startsWith('bagmark_target_') + ? info.menuItemId.toString().replace('bagmark_target_', '') + : undefined; + const { node, isDuplicate, folderTitle } = await saveBookmark({ + url: targetUrl, + title: targetTitle, + targetFolderId, + defaultFolderName: settings.defaultFolderName, + enableDateSubfolders: settings.enableDateSubfolders, + warnDuplicates: settings.warnDuplicates, + sourcePageUrl: info.pageUrl, + sourcePageTitle: tab?.title, + quote: info.selectionText || undefined, + }); - // Duplicate Check - if (settings.warnDuplicates) { - const duplicate = await findDuplicateBookmark(targetUrl); - if (duplicate) { - if (settings.showNotifications) { - const addedDate = duplicate.dateAdded ? formatDisplayDate(duplicate.dateAdded) : 'previously'; + if (settings.showNotifications) { + if (isDuplicate) { + const addedDate = node.dateAdded ? formatDisplayDate(node.dateAdded) : 'previously'; + browser.notifications.create({ + type: 'basic', + iconUrl: 'assets/icon-48.png', + title: 'Already in this folder!', + message: `"${node.title}" was already saved in ${folderTitle} on ${addedDate}.`, + }); + } else { browser.notifications.create({ type: 'basic', iconUrl: 'assets/icon-48.png', - title: 'Already in BagMark!', - message: `"${duplicate.title}" was already saved on ${addedDate}.`, + title: 'Bagged Successfully! πŸŽ’', + message: `Saved "${targetTitle}" to ${folderTitle}`, }); } - return; - } - } - - try { - // Determine base folder - let baseFolderId: string; - let baseFolderTitle: string = settings.defaultFolderName; - - if (info.menuItemId.toString().startsWith('bagmark_target_')) { - baseFolderId = info.menuItemId.toString().replace('bagmark_target_', ''); - const folderNodes = await browser.bookmarks.get(baseFolderId); - baseFolderTitle = folderNodes[0]?.title || 'Folder'; - } else { - const rootNode = await ensureRootFolder(settings.defaultFolderName); - baseFolderId = rootNode.id; - baseFolderTitle = rootNode.title; - } - - // Determine destination folder (auto-date subfolder if enabled) - let destFolderId = baseFolderId; - let destFolderTitle = baseFolderTitle; - - if (settings.enableDateSubfolders) { - const dateNode = await ensureDateSubfolder(baseFolderId, new Date()); - destFolderId = dateNode.id; - destFolderTitle = `${baseFolderTitle} / ${dateNode.title}`; - } - - // Create Bookmark - const newBookmark = await browser.bookmarks.create({ - parentId: destFolderId, - title: targetTitle, - url: targetUrl, - }); - - // Store Rich Metadata - const metadata: BookmarkMetadata = { - id: newBookmark.id, - url: targetUrl, - title: targetTitle, - dateAdded: newBookmark.dateAdded || Date.now(), - folderId: destFolderId, - folderTitle: destFolderTitle, - sourcePageUrl, - sourcePageTitle, - quote, - tags: [], - }; - await saveMetadata(metadata); - - // Notification confirmation - if (settings.showNotifications) { - browser.notifications.create({ - type: 'basic', - iconUrl: 'assets/icon-48.png', - title: 'Bagged Successfully! πŸŽ’', - message: `Saved "${targetTitle}" to ${destFolderTitle}`, - }); } } catch (error) { console.error('Failed to save bookmark:', error); @@ -142,7 +99,7 @@ async function handleSaveAction( type: 'basic', iconUrl: 'assets/icon-48.png', title: 'BagMark Save Failed', - message: 'Could not save bookmark. Target folder may no longer exist.', + message: 'Could not save bookmark or metadata. Check the destination folder before retrying.', }); } } @@ -162,10 +119,15 @@ browser.storage.onChanged.addListener((changes, area) => { } }); -browser.menus.onClicked.addListener((info, tab) => { - handleSaveAction(info, tab); +browser.contextMenus.onClicked.addListener((info, tab) => { + return handleSaveAction(info, tab); }); -// Call immediately on background script execution -updateContextMenus(); - +browser.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message?.type !== 'save-open-tabs' || sender.id !== browser.runtime.id) return false; + saveOpenTabs(message).then(sendResponse, (error) => { + sendResponse({ error: error instanceof Error ? error.message : 'Could not save open tabs.' }); + }); + // Keep the response channel open on Chromium versions without async listener support. + return true; +}); diff --git a/src/lib/bookmarks.ts b/src/lib/bookmarks.ts index ff2946d..25b47a2 100644 --- a/src/lib/bookmarks.ts +++ b/src/lib/bookmarks.ts @@ -1,4 +1,5 @@ import { formatYearMonth, normalizeUrl } from './utils'; +import { saveMetadata } from './storage'; export interface SaveBookmarkInput { url: string; @@ -6,22 +7,27 @@ export interface SaveBookmarkInput { targetFolderId?: string; enableDateSubfolders?: boolean; defaultFolderName?: string; + warnDuplicates?: boolean; + sourcePageUrl?: string; + sourcePageTitle?: string; + quote?: string; +} + +export interface SaveBookmarkResult { + node: browser.bookmarks.BookmarkTreeNode; + isDuplicate: boolean; + folderTitle: string; } export async function ensureRootFolder(name: string = 'BagMark'): Promise { const tree = await browser.bookmarks.getTree(); - // Find "unfiled" (Other Bookmarks) or fallback to root children - let parentId = 'unfiled_____'; - if (tree[0]?.children) { - const other = tree[0].children.find( - (c) => c.id === 'unfiled_____' || c.title.toLowerCase().includes('other') - ); - if (other) { - parentId = other.id; - } else if (tree[0].children[0]) { - parentId = tree[0].children[0].id; - } - } + const writable = tree[0]?.children?.filter((node) => !node.unmodifiable) || []; + const parent = writable.find((node) => + node.id === 'unfiled_____' || + (node as browser.bookmarks.BookmarkTreeNode & { folderType?: string }).folderType === 'other' + ) || writable[0]; + if (!parent) throw new Error('No writable bookmark folder available'); + const parentId = parent.id; // Look for existing folder with `name` under parentId const siblings = await browser.bookmarks.getChildren(parentId); @@ -53,44 +59,16 @@ export async function ensureDateSubfolder( }); } -export async function findDuplicateBookmark( - rawUrl: string -): Promise { - const cleanUrl = normalizeUrl(rawUrl); - // Search exact raw URL first - let results = await browser.bookmarks.search({ url: rawUrl }); - if (results && results.length > 0) return results[0]; - - // If cleanUrl is different, search clean URL - if (cleanUrl !== rawUrl) { - results = await browser.bookmarks.search({ url: cleanUrl }); - if (results && results.length > 0) return results[0]; - } - - // Also check slash-normalized variant (e.g. root domain with or without trailing slash) - const altUrl = cleanUrl.endsWith('/') ? cleanUrl.slice(0, -1) : cleanUrl + '/'; - if (altUrl !== rawUrl && altUrl !== cleanUrl) { - results = await browser.bookmarks.search({ url: altUrl }); - if (results && results.length > 0) return results[0]; - } - - return null; -} - export async function getFolderHierarchy(): Promise> { const tree = await browser.bookmarks.getTree(); const folders: Array<{ id: string; title: string; path: string }> = []; function traverse(nodes: browser.bookmarks.BookmarkTreeNode[], currentPath: string) { for (const node of nodes) { - if (!node.url) { - const title = node.title || (node.id === 'root________' ? '' : 'Folder'); - const nextPath = node.id === 'root________' - ? '' - : (currentPath ? `${currentPath} / ${title}` : title); - if (node.id !== 'root________' && title) { - folders.push({ id: node.id, title, path: nextPath }); - } + if (!node.url && !node.unmodifiable) { + const title = node.title || 'Folder'; + const nextPath = currentPath ? `${currentPath} / ${title}` : title; + folders.push({ id: node.id, title, path: nextPath }); if (node.children) { traverse(node.children, nextPath); } @@ -98,35 +76,74 @@ export async function getFolderHierarchy(): Promise { - const duplicate = await findDuplicateBookmark(details.url); - if (duplicate) { - return { node: duplicate, isDuplicate: true }; - } - - let baseFolderId = details.targetFolderId; - if (!baseFolderId) { - const root = await ensureRootFolder(details.defaultFolderName || 'BagMark'); - baseFolderId = root.id; - } +// shortcut: this queue is per context; keep all save callers in the background when adding popup saves. +let saveQueue: Promise = Promise.resolve(); + +export function saveBookmarks(details: SaveBookmarkInput[]): Promise> { + const operation = saveQueue.then(async () => { + const destinations = new Map(); + const indexes = new Map>(); + const results: Array = []; + const date = new Date(); + + for (const input of details) { + try { + const key = JSON.stringify([input.targetFolderId, input.defaultFolderName || 'BagMark', !!input.enableDateSubfolders]); + let destination = destinations.get(key); + if (!destination) { + const base = input.targetFolderId + ? (await browser.bookmarks.get(input.targetFolderId))[0] + : await ensureRootFolder(input.defaultFolderName || 'BagMark'); + if (!base || base.url || base.unmodifiable) throw new Error('Target is not a writable folder'); + const folder = input.enableDateSubfolders ? await ensureDateSubfolder(base.id, date) : base; + destination = { id: folder.id, title: input.enableDateSubfolders ? `${base.title} / ${folder.title}` : base.title }; + destinations.set(key, destination); + } - let destFolderId = baseFolderId; - if (details.enableDateSubfolders) { - const dateFolder = await ensureDateSubfolder(baseFolderId, new Date()); - destFolderId = dateFolder.id; - } + let index = indexes.get(destination.id); + if (!index) { + const children = await browser.bookmarks.getChildren(destination.id); + index = new Map(children.filter((node) => !!node.url).map((node) => [normalizeUrl(node.url!), node])); + indexes.set(destination.id, index); + } + const normalizedUrl = normalizeUrl(input.url); + const duplicate = input.warnDuplicates !== false && index.get(normalizedUrl); + if (duplicate) { + results.push({ node: duplicate, isDuplicate: true, folderTitle: destination.title }); + continue; + } - const node = await browser.bookmarks.create({ - parentId: destFolderId, - title: details.title, - url: details.url, + const node = await browser.bookmarks.create({ parentId: destination.id, title: input.title, url: input.url }); + index.set(normalizedUrl, node); + await saveMetadata({ + id: node.id, + url: input.url, + title: input.title, + dateAdded: node.dateAdded || Date.now(), + folderId: destination.id, + folderTitle: destination.title, + sourcePageUrl: input.sourcePageUrl, + sourcePageTitle: input.sourcePageTitle, + quote: input.quote, + tags: [], + }); + results.push({ node, isDuplicate: false, folderTitle: destination.title }); + } catch (error) { + results.push({ error }); + } + } + return results; }); + saveQueue = operation.catch(() => {}); + return operation; +} - return { node, isDuplicate: false }; +export async function saveBookmark(details: SaveBookmarkInput): Promise { + const [result] = await saveBookmarks([details]); + if ('error' in result) throw result.error; + return result; } diff --git a/src/lib/browser.ts b/src/lib/browser.ts new file mode 100644 index 0000000..98dbc19 --- /dev/null +++ b/src/lib/browser.ts @@ -0,0 +1,7 @@ +// Chromium before 148 exposes these APIs only as chrome. +if (typeof browser === 'undefined') { + const globals = globalThis as typeof globalThis & { browser: typeof browser; chrome: typeof browser }; + globals.browser = globals.chrome; +} + +export {}; diff --git a/src/lib/tabs.ts b/src/lib/tabs.ts new file mode 100644 index 0000000..60339d7 --- /dev/null +++ b/src/lib/tabs.ts @@ -0,0 +1,42 @@ +import { saveBookmarks } from './bookmarks'; +import { getSettings } from './config'; +import { isBookmarkableUrl } from './utils'; +import type { SaveOpenTabsRequest, SaveOpenTabsResult } from './types'; + +export async function saveOpenTabs(request: SaveOpenTabsRequest): Promise { + if (!Number.isInteger(request.windowId) || request.windowId < 0 || + typeof request.targetFolderId !== 'string' || !request.targetFolderId.trim()) { + throw new Error('Choose a valid window and destination folder.'); + } + if (request.newFolderName !== undefined && + (typeof request.newFolderName !== 'string' || !request.newFolderName.trim())) { + throw new Error('Enter a name for the new folder.'); + } + + const tabs = await browser.tabs.query({ windowId: request.windowId }); + const eligible = tabs.filter((tab) => isBookmarkableUrl(tab.url)).sort((a, b) => a.index - b.index); + const summary: SaveOpenTabsResult = { saved: 0, skipped: tabs.length - eligible.length, failed: 0 }; + if (!eligible.length) return summary; + + const [parent] = await browser.bookmarks.get(request.targetFolderId); + if (!parent || parent.url || parent.unmodifiable) throw new Error('Choose an existing writable folder.'); + const settings = await getSettings(); + const folder = request.newFolderName !== undefined + ? await browser.bookmarks.create({ parentId: parent.id, title: request.newFolderName.trim() }) + : parent; + summary.folderId = folder.id; + const results = await saveBookmarks(eligible.map((tab) => ({ + url: tab.url!, + title: tab.title || tab.url!, + targetFolderId: folder.id, + warnDuplicates: settings.warnDuplicates, + sourcePageUrl: tab.url, + sourcePageTitle: tab.title, + }))); + for (const result of results) { + if ('error' in result) summary.failed++; + else if (result.isDuplicate) summary.skipped++; + else summary.saved++; + } + return summary; +} diff --git a/src/lib/types.ts b/src/lib/types.ts index 14c081a..ba69513 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -1,5 +1,5 @@ export interface BookmarkMetadata { - id: string; // Firefox bookmark ID + id: string; // Browser bookmark ID url: string; // Destination URL title: string; // Bookmark title dateAdded: number; // Epoch milliseconds @@ -26,3 +26,17 @@ export const DEFAULT_SETTINGS: BagMarkSettings = { favoriteFolderIds: [], showNotifications: true, }; + +export interface SaveOpenTabsRequest { + type: 'save-open-tabs'; + windowId: number; + targetFolderId: string; + newFolderName?: string; +} + +export interface SaveOpenTabsResult { + saved: number; + skipped: number; + failed: number; + folderId?: string; +} diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 5250912..5873358 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -34,19 +34,23 @@ export function normalizeUrl(rawUrl: string): string { // Strip common tracking parameters const paramsToDelete: string[] = []; url.searchParams.forEach((_, key) => { - if (key.startsWith('utm_') || key === 'ref' || key === 'fbclid' || key === 'gclid') { + if (key.startsWith('utm_') || key === 'fbclid' || key === 'gclid') { paramsToDelete.push(key); } }); paramsToDelete.forEach((key) => url.searchParams.delete(key)); - // Remove hash - url.hash = ''; - // Strip trailing slash if pathname ends with / - if (url.pathname.length > 1 && url.pathname.endsWith('/')) { - url.pathname = url.pathname.slice(0, -1); - } return url.toString(); } catch { return rawUrl.trim(); } } + +export function isBookmarkableUrl(rawUrl?: string): boolean { + if (!rawUrl) return false; + try { + const { protocol } = new URL(rawUrl); + return protocol === 'http:' || protocol === 'https:'; + } catch { + return false; + } +} diff --git a/src/options/index.html b/src/options/index.html index b30d5df..bf3b98b 100644 --- a/src/options/index.html +++ b/src/options/index.html @@ -32,7 +32,7 @@

General Preferences

diff --git a/src/options/options.ts b/src/options/options.ts index a94b662..b2f6fc3 100644 --- a/src/options/options.ts +++ b/src/options/options.ts @@ -1,3 +1,4 @@ +import '../lib/browser'; import { getSettings, saveSettings } from '../lib/config'; import { getFolderHierarchy } from '../lib/bookmarks'; diff --git a/src/popup/index.html b/src/popup/index.html index f965f92..c0474d9 100644 --- a/src/popup/index.html +++ b/src/popup/index.html @@ -17,6 +17,30 @@

BagMark

+
+ Save open tabs +
+

Loading tabs in this window…

+
+ + + + + +
+

Tabs stay open. Browser pages are skipped; your duplicate setting applies.

+ +
+
+ diff --git a/src/popup/popup.css b/src/popup/popup.css index e49195e..4bb4703 100644 --- a/src/popup/popup.css +++ b/src/popup/popup.css @@ -8,6 +8,7 @@ --accent-hover: #d97706; --border: #3f3f4e; --danger: #ef4444; + --error-text: #fca5a5; --font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; } @@ -101,9 +102,50 @@ h1 { gap: 8px; overflow-y: auto; max-height: 400px; + min-height: 0; padding-right: 4px; } +.save-tabs { + margin-bottom: 12px; + flex-shrink: 0; + font-size: 13px; +} + +.save-tabs summary { cursor: pointer; padding: 6px 0; font-weight: 600; } +.save-tabs fieldset { border: 0; margin: 0; padding: 0; } +.save-tabs label { display: block; margin: 8px 0 4px; } +.save-tabs select, .save-tabs input[type="text"] { + width: 100%; + box-sizing: border-box; + padding: 8px; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--card-bg); + color: var(--text-main); + font: inherit; +} +.save-tabs .new-folder-toggle { display: flex; align-items: center; gap: 6px; margin: 10px 0; } +.save-tabs input[type="checkbox"] { accent-color: var(--accent); } +.save-tabs-button { + width: 100%; + margin-top: 10px; + padding: 9px; + border: 0; + border-radius: 6px; + background: var(--accent); + color: var(--bg-color); + font: inherit; + font-weight: 600; + cursor: pointer; +} +.save-tabs-button:hover:not(:disabled) { background: var(--accent-hover); } +.save-tabs-button:disabled { opacity: 0.5; cursor: default; } +.save-tabs :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +#tabPreview, .save-tabs-hint { font-size: 12px; color: var(--text-muted); line-height: 1.5; margin: 6px 0; } +#saveTabsStatus { display: block; line-height: 1.5; overflow-wrap: anywhere; } +#saveTabsStatus[data-error="true"] { color: var(--error-text); } + .bookmark-card { background: var(--card-bg); border: 1px solid var(--border); @@ -155,7 +197,7 @@ h1 { color: var(--text-muted); background: rgba(0, 0, 0, 0.2); padding: 4px 8px; - border-left: 2px solid var(--accent); + border-left: 1px solid var(--accent); border-radius: 2px; overflow: hidden; text-overflow: ellipsis; diff --git a/src/popup/popup.ts b/src/popup/popup.ts index 43a2f24..44637d6 100644 --- a/src/popup/popup.ts +++ b/src/popup/popup.ts @@ -1,6 +1,8 @@ +import '../lib/browser'; import { getAllMetadata, deleteMetadata } from '../lib/storage'; -import { BookmarkMetadata } from '../lib/types'; -import { formatRelativeTime } from '../lib/utils'; +import { BookmarkMetadata, SaveOpenTabsResult } from '../lib/types'; +import { formatRelativeTime, isBookmarkableUrl } from '../lib/utils'; +import { getFolderHierarchy } from '../lib/bookmarks'; let allItems: BookmarkMetadata[] = []; @@ -143,6 +145,89 @@ function filterAndRender() { renderList(filtered); } +async function initTabSaving() { + const form = document.getElementById('saveTabsForm') as HTMLFormElement; + const fields = document.getElementById('saveTabsFields') as HTMLFieldSetElement; + const folderSelect = document.getElementById('saveTabsFolder') as HTMLSelectElement; + const createFolder = document.getElementById('createTabFolder') as HTMLInputElement; + const folderName = document.getElementById('tabFolderName') as HTMLInputElement; + const button = document.getElementById('btnSaveTabs') as HTMLButtonElement; + const status = document.getElementById('saveTabsStatus')!; + let windowId: number; + let count = 0; + + function updateFolderMode() { + document.getElementById('tabFolderNameField')!.hidden = !createFolder.checked; + document.getElementById('saveTabsFolderLabel')!.textContent = createFolder.checked ? 'Parent folder' : 'Save to folder'; + folderName.disabled = !createFolder.checked; + folderName.required = createFolder.checked; + } + createFolder.addEventListener('change', updateFolderMode); + + async function loadFolders(selectedId = '') { + const folders = await getFolderHierarchy(); + folderSelect.replaceChildren(new Option('Choose a folder', '')); + for (const folder of folders) folderSelect.add(new Option(folder.path, folder.id)); + folderSelect.value = selectedId; + if (!folders.length) throw new Error('No writable folders available. Create a folder in the bookmark manager first.'); + } + + form.addEventListener('submit', async (event) => { + event.preventDefault(); + if (fields.disabled) return; + if (createFolder.checked && !folderName.value.trim()) { + folderName.setCustomValidity('Enter a folder name.'); + folderName.reportValidity(); + return; + } + fields.disabled = true; + status.dataset.error = 'false'; + status.textContent = 'Saving tabs…'; + try { + const result: SaveOpenTabsResult | { error: string } = await browser.runtime.sendMessage({ + type: 'save-open-tabs', + windowId, + targetFolderId: folderSelect.value, + newFolderName: createFolder.checked ? folderName.value.trim() : undefined, + }); + if (!result) throw new Error('No response. Reload BagMark and try again.'); + if ('error' in result) throw new Error(result.error); + status.textContent = `${result.saved} saved Β· ${result.skipped} skipped Β· ${result.failed} failed.`; + status.dataset.error = String(result.failed > 0); + if (result.failed) status.textContent += ' Check the folder before retrying.'; + if (result.folderId) { + await loadFolders(result.folderId); + createFolder.checked = false; + updateFolderMode(); + } + await loadBookmarks(); + } catch (error) { + status.dataset.error = 'true'; + status.textContent = error instanceof Error ? error.message : 'Could not save tabs. Check the folder and try again.'; + } finally { + fields.disabled = false; + button.disabled = count === 0; + } + }); + folderName.addEventListener('input', () => folderName.setCustomValidity('')); + + try { + const currentWindow = await browser.windows.getCurrent(); + if (currentWindow.id === undefined) throw new Error('Could not identify this window. Reopen BagMark.'); + windowId = currentWindow.id; + const [tabs] = await Promise.all([browser.tabs.query({ windowId }), loadFolders()]); + count = tabs.filter((tab) => isBookmarkableUrl(tab.url)).length; + document.getElementById('tabPreview')!.textContent = `${count} web ${count === 1 ? 'tab' : 'tabs'} in this window`; + button.textContent = `Save ${count} ${count === 1 ? 'tab' : 'tabs'}`; + fields.disabled = false; + button.disabled = count === 0; + } catch (error) { + status.dataset.error = 'true'; + status.textContent = error instanceof Error ? error.message : 'Could not load tabs or folders. Reopen BagMark to retry.'; + document.getElementById('tabPreview')!.textContent = 'Tab saving unavailable'; + } +} + document.addEventListener('DOMContentLoaded', () => { const listEl = document.getElementById('bookmarkList'); listEl?.addEventListener('click', async (e) => { @@ -176,6 +261,7 @@ document.addEventListener('DOMContentLoaded', () => { }); loadBookmarks(); + initTabSaving(); document.getElementById('searchInput')?.addEventListener('input', filterAndRender); document.getElementById('folderFilter')?.addEventListener('change', filterAndRender); diff --git a/tests/bookmarks.test.ts b/tests/bookmarks.test.ts index bb062e0..b79d139 100644 --- a/tests/bookmarks.test.ts +++ b/tests/bookmarks.test.ts @@ -2,15 +2,18 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { ensureRootFolder, ensureDateSubfolder, - findDuplicateBookmark, getFolderHierarchy, saveBookmark, + saveBookmarks, } from '../src/lib/bookmarks'; +import { saveOpenTabs } from '../src/lib/tabs'; describe('bookmarks operations', () => { let nodes: any[] = []; + let metadata: Record = {}; beforeEach(() => { + metadata = {}; nodes = [ { id: 'root________', @@ -26,7 +29,20 @@ describe('bookmarks operations', () => { ]; (globalThis as any).browser = { + storage: { local: { set: vi.fn(async (values: any) => Object.assign(metadata, values)) } }, bookmarks: { + get: vi.fn(async (id: string) => { + const find = (items: any[]): any => { + for (const item of items) { + if (item.id === id) return item; + const nested = item.children && find(item.children); + if (nested) return nested; + } + }; + const node = find(nodes); + if (!node) throw new Error('Folder not found'); + return [node]; + }), getTree: vi.fn(async () => nodes), getChildren: vi.fn(async (id: string) => { const find = (arr: any[]): any => { @@ -37,9 +53,9 @@ describe('bookmarks operations', () => { if (sub) return sub; } } - return []; + return null; }; - return find(nodes); + return find(nodes) || []; }), create: vi.fn(async (details: any) => { const newNode = { @@ -64,17 +80,6 @@ describe('bookmarks operations', () => { findAndAdd(nodes); return newNode; }), - search: vi.fn(async (query: any) => { - const matches: any[] = []; - const traverse = (arr: any[]) => { - for (const n of arr) { - if (query.url && n.url === query.url) matches.push(n); - if (n.children) traverse(n.children); - } - }; - traverse(nodes); - return matches; - }), }, }; }); @@ -107,9 +112,9 @@ describe('bookmarks operations', () => { url: 'https://vite.dev/guide', }); - const dup = await findDuplicateBookmark('https://vite.dev/guide?utm_source=docs'); - expect(dup).not.toBeNull(); - expect(dup?.title).toBe('Vite Guide'); + const dup = await saveBookmark({ url: 'https://vite.dev/guide?utm_source=docs', title: 'Vite', targetFolderId: rootFolder.id }); + expect(dup.isDuplicate).toBe(true); + expect(dup.node.title).toBe('Vite Guide'); }); it('retrieves folder hierarchy excluding root node', async () => { @@ -184,8 +189,166 @@ describe('bookmarks operations', () => { expect(folder.parentId).toBe('toolbar_____'); }); - it('returns null when duplicate URL is not found', async () => { - const dup = await findDuplicateBookmark('https://nonexistent.org'); - expect(dup).toBeNull(); + it('saves into another folder even when the URL already exists elsewhere', async () => { + await saveBookmark({ url: 'https://example.com', title: 'First', defaultFolderName: 'First' }); + const second = await saveBookmark({ url: 'https://example.com', title: 'Second', defaultFolderName: 'Second' }); + expect(second.isDuplicate).toBe(false); + expect(second.node.title).toBe('Second'); + expect(second.folderTitle).toBe('Second'); + }); + + it('compares tracking variants on both sides without replacing existing metadata', async () => { + const first = await saveBookmark({ url: 'https://example.com?utm_source=first', title: 'Original', quote: 'Keep this quote' }); + const original = { ...metadata[`bagmark_meta_${first.node.id}`] }; + const second = await saveBookmark({ url: 'https://example.com?fbclid=second', title: 'Replacement', quote: 'Another quote' }); + expect(second.isDuplicate).toBe(true); + expect(second.node.id).toBe(first.node.id); + expect(metadata[`bagmark_meta_${first.node.id}`]).toEqual(original); + expect(original.quote).toBe('Keep this quote'); + }); + + it('checks the final date folder rather than the base folder', async () => { + const base = await saveBookmark({ url: 'https://example.com', title: 'Base' }); + const dated = await saveBookmark({ url: 'https://example.com', title: 'Dated', enableDateSubfolders: true }); + expect(dated.isDuplicate).toBe(false); + expect(dated.node.parentId).not.toBe(base.node.parentId); + expect((await saveBookmark({ url: 'https://example.com', title: 'Again', enableDateSubfolders: true })).node.id).toBe(dated.node.id); + }); + + it('allows duplicates when prevention is disabled', async () => { + const first = await saveBookmark({ url: 'https://example.com', title: 'First' }); + const second = await saveBookmark({ url: 'https://example.com', title: 'Second', warnDuplicates: false }); + expect(second.isDuplicate).toBe(false); + expect(second.node.id).not.toBe(first.node.id); + }); + + it('serializes simultaneous saves including default and date folder creation', async () => { + const [first, second] = await Promise.all([ + saveBookmark({ url: 'https://example.com', title: 'First', enableDateSubfolders: true }), + saveBookmark({ url: 'https://example.com', title: 'Second', enableDateSubfolders: true }), + ]); + expect(first.isDuplicate).toBe(false); + expect(second.isDuplicate).toBe(true); + expect(second.node.id).toBe(first.node.id); + expect(nodes[0].children[0].children).toHaveLength(1); + expect(nodes[0].children[0].children[0].children).toHaveLength(1); + }); + + it('reads destination bookmarks once per batch and reports failures without stopping later saves', async () => { + const folder = await ensureRootFolder(); + vi.mocked(browser.bookmarks.getChildren).mockClear(); + vi.mocked(browser.bookmarks.create).mockRejectedValueOnce(new Error('Failed save')); + const results = await saveBookmarks([ + { url: 'https://failed.example', title: 'Failed', targetFolderId: folder.id }, + { url: 'https://example.com?utm_source=first', title: 'First', targetFolderId: folder.id }, + { url: 'https://example.com?gclid=second', title: 'Second', targetFolderId: folder.id }, + ]); + expect(results[0]).toMatchObject({ error: new Error('Failed save') }); + expect(results[1]).toMatchObject({ isDuplicate: false }); + expect(results[2]).toMatchObject({ isDuplicate: true }); + expect(browser.bookmarks.getChildren).toHaveBeenCalledTimes(1); + expect(nodes[0].children[0].children[0].children).toHaveLength(1); + expect((await saveBookmark({ url: 'https://after.example', title: 'After', targetFolderId: folder.id })).isDuplicate).toBe(false); + }); + + it('uses Chromium Other Bookmarks regardless of its ID or language', async () => { + nodes = [{ id: '0', title: '', children: [ + { id: '1', title: 'Favoritenleiste', children: [] }, + { id: '42', title: 'Weitere Lesezeichen', folderType: 'other', children: [] }, + ] }]; + + const folder = await ensureRootFolder(); + expect(folder.parentId).toBe('42'); + expect((await ensureRootFolder()).id).toBe(folder.id); + }); + + it('routes right-click saves through destination deduplication and metadata storage', async () => { + let click!: (info: any, tab?: any) => Promise; + const settings = { enableDateSubfolders: false, showNotifications: false }; + (browser.storage.local as any).get = vi.fn(async () => ({ bagmark_settings: settings })); + (browser.storage as any).onChanged = { addListener: vi.fn() }; + (browser as any).runtime = { onInstalled: { addListener: vi.fn() }, onStartup: { addListener: vi.fn() }, onMessage: { addListener: vi.fn() } }; + (browser as any).contextMenus = { onClicked: { addListener: (handler: typeof click) => { click = handler; } } }; + vi.resetModules(); + await import('../src/background/index'); + + const firstFolder = await ensureRootFolder('First'); + const secondFolder = await ensureRootFolder('Second'); + const info = { menuItemId: `bagmark_target_${firstFolder.id}`, pageUrl: 'https://example.com?utm_source=first', selectionText: 'Original quote' }; + await click(info, { title: 'Page title' }); + await click({ ...info, pageUrl: 'https://example.com?gclid=second', selectionText: 'Replacement quote' }, { title: 'New title' }); + await click({ ...info, menuItemId: `bagmark_target_${secondFolder.id}` }, { title: 'Other collection' }); + + const firstChildren = await browser.bookmarks.getChildren(firstFolder.id); + const secondChildren = await browser.bookmarks.getChildren(secondFolder.id); + expect(firstChildren).toHaveLength(1); + expect(secondChildren).toHaveLength(1); + expect(metadata[`bagmark_meta_${firstChildren[0].id}`]).toMatchObject({ title: 'Page title', quote: 'Original quote', folderTitle: 'First' }); + expect(metadata[`bagmark_meta_${secondChildren[0].id}`]).toMatchObject({ title: 'Other collection', folderTitle: 'Second' }); + }); + + it('saves only the requested window in tab order and counts duplicate and unsupported tabs', async () => { + const folder = await ensureRootFolder(); + const tabs = [ + { id: 3, windowId: 7, index: 2, url: 'https://second.example', title: 'Second' }, + { id: 1, windowId: 7, index: 0, url: 'https://first.example?utm_source=one', title: 'First' }, + { id: 2, windowId: 7, index: 1, url: 'https://first.example?gclid=two', title: 'Repeated' }, + { id: 4, windowId: 7, index: 3, url: 'chrome://settings', title: 'Settings' }, + { id: 5, windowId: 8, index: 0, url: 'https://other-window.example', title: 'Another window' }, + ]; + (browser as any).tabs = { query: vi.fn(async ({ windowId }: any) => tabs.filter((tab) => tab.windowId === windowId)) }; + (browser.storage.local as any).get = vi.fn(async () => ({ bagmark_settings: { enableDateSubfolders: true } })); + const result = await saveOpenTabs({ type: 'save-open-tabs', windowId: 7, targetFolderId: folder.id }); + expect(result).toEqual({ saved: 2, skipped: 2, failed: 0, folderId: folder.id }); + const children = await browser.bookmarks.getChildren(folder.id); + expect(children.map((node) => node.title)).toEqual(['First', 'Second']); + expect(metadata[`bagmark_meta_${children[0].id}`]).toMatchObject({ sourcePageTitle: 'First', folderId: folder.id }); + expect(await saveOpenTabs({ type: 'save-open-tabs', windowId: 7, targetFolderId: folder.id })).toMatchObject({ saved: 0, skipped: 4 }); + }); + + it('creates a new folder under the chosen parent only when web tabs exist', async () => { + const parent = await ensureRootFolder(); + (browser as any).tabs = { query: vi.fn(async () => [{ index: 0, url: 'https://example.com', title: 'Page' }]) }; + (browser.storage.local as any).get = vi.fn(async () => ({})); + const result = await saveOpenTabs({ type: 'save-open-tabs', windowId: 7, targetFolderId: parent.id, newFolderName: ' Research ' }); + expect(result).toMatchObject({ saved: 1, skipped: 0, failed: 0 }); + const [folder] = await browser.bookmarks.get(result.folderId!); + expect(folder).toMatchObject({ title: 'Research', parentId: parent.id }); + expect((await browser.bookmarks.getChildren(folder.id)).map((node) => node.title)).toEqual(['Page']); + (browser as any).tabs = { query: vi.fn(async () => [{ index: 0, url: 'about:blank' }, { index: 1 }]) }; + expect(await saveOpenTabs({ type: 'save-open-tabs', windowId: 7, targetFolderId: parent.id, newFolderName: 'Empty' })).toEqual({ saved: 0, skipped: 2, failed: 0 }); + expect(await browser.bookmarks.getChildren(parent.id)).toHaveLength(1); + }); + + it('rejects an empty new-folder name without creating bookmarks', async () => { + await expect(saveOpenTabs({ type: 'save-open-tabs', windowId: 7, targetFolderId: 'folder', newFolderName: ' ' })).rejects.toThrow(); + expect(nodes[0].children[0].children).toHaveLength(0); + }); + + it('reports individual save failures while continuing the window batch', async () => { + const folder = await ensureRootFolder(); + (browser as any).tabs = { query: vi.fn(async () => [ + { index: 0, url: 'https://failed.example', title: 'Failed' }, + { index: 1, url: 'https://saved.example', title: 'Saved' }, + ]) }; + (browser.storage.local as any).get = vi.fn(async () => ({})); + vi.mocked(browser.bookmarks.create).mockRejectedValueOnce(new Error('Cannot save')); + expect(await saveOpenTabs({ type: 'save-open-tabs', windowId: 7, targetFolderId: folder.id })).toMatchObject({ saved: 1, skipped: 0, failed: 1 }); + expect((await browser.bookmarks.getChildren(folder.id)).map((node) => node.title)).toEqual(['Saved']); + }); + + it('excludes Chromium root and managed folders from folder choices', async () => { + nodes = [{ id: '0', title: '', children: [ + { id: '1', title: 'Bookmarks bar', children: [] }, + { id: '2', title: 'Other bookmarks', folderType: 'other', children: [] }, + { id: '3', title: 'Company', unmodifiable: 'managed', children: [ + { id: '4', title: 'Policies' }, + ] }, + ] }]; + + expect(await getFolderHierarchy()).toEqual([ + { id: '1', title: 'Bookmarks bar', path: 'Bookmarks bar' }, + { id: '2', title: 'Other bookmarks', path: 'Other bookmarks' }, + ]); }); }); diff --git a/tests/browser.test.ts b/tests/browser.test.ts new file mode 100644 index 0000000..f263c53 --- /dev/null +++ b/tests/browser.test.ts @@ -0,0 +1,13 @@ +import { afterEach, it, expect, vi } from 'vitest'; + +afterEach(() => vi.unstubAllGlobals()); + +it.each([false, true])('initializes the API namespace while preserving native browser=%s', async (native) => { + const chromeApi = { runtime: { id: 'chromium' } }; + const nativeApi = { runtime: { id: 'native' } }; + vi.stubGlobal('chrome', chromeApi); + vi.stubGlobal('browser', native ? nativeApi : undefined); + vi.resetModules(); + await import('../src/lib/browser'); + expect(browser.runtime.id).toBe(native ? 'native' : 'chromium'); +}); diff --git a/tests/build.test.ts b/tests/build.test.ts new file mode 100644 index 0000000..50b80e4 --- /dev/null +++ b/tests/build.test.ts @@ -0,0 +1,26 @@ +import { describe, it, expect } from 'vitest'; +import { build } from 'vite'; +import type { RollupOutput } from 'rollup'; + +describe('browser builds', () => { + it.each(['production', 'chromium'])('emits a usable %s manifest and entry points', async (mode) => { + const result = await build({ mode, logLevel: 'silent', build: { write: false } }) as RollupOutput; + const asset = result.output.find((item) => item.fileName === 'manifest.json'); + if (!asset || asset.type !== 'asset') throw new Error('Missing manifest'); + const manifest = JSON.parse(String(asset.source)); + expect(manifest.permissions).toContain('contextMenus'); + expect(manifest.permissions).not.toContain('menus'); + expect(result.output.some((item) => item.fileName === 'background.js')).toBe(true); + for (const path of [manifest.action.default_popup, manifest.options_ui.page]) { + expect(result.output.some((item) => item.fileName === path)).toBe(true); + } + if (mode === 'chromium') { + expect(manifest.background).toEqual({ service_worker: 'background.js', type: 'module' }); + expect(manifest.minimum_chrome_version).toBe('123'); + expect(manifest.browser_specific_settings).toBeUndefined(); + } else { + expect(manifest.background).toEqual({ scripts: ['background.js'], type: 'module' }); + expect(manifest.browser_specific_settings.gecko.id).toBe('bagmark@local.extension'); + } + }); +}); diff --git a/tests/utils.test.ts b/tests/utils.test.ts index 1257a44..54dfc06 100644 --- a/tests/utils.test.ts +++ b/tests/utils.test.ts @@ -20,14 +20,16 @@ describe('utils', () => { expect(formatted).toMatch(/3:30\s*PM/); }); - it('normalizes URLs by stripping trailing slashes and common tracking parameters', () => { + it('strips known tracking parameters while preserving paths and fragments', () => { const raw = 'https://example.com/article/?utm_source=twitter&utm_medium=social#heading'; - expect(normalizeUrl(raw)).toBe('https://example.com/article'); + expect(normalizeUrl(raw)).toBe('https://example.com/article/#heading'); }); - it('strips trailing slash while preserving query parameters', () => { - const raw = 'https://example.com/article/?id=1&category=books'; - expect(normalizeUrl(raw)).toBe('https://example.com/article?id=1&category=books'); + it('preserves functional query parameters and distinct paths', () => { + const raw = 'https://example.com/article/?id=1&ref=books#chapter'; + expect(normalizeUrl(raw)).toBe(raw); + expect(normalizeUrl('https://example.com/article')).not.toBe(normalizeUrl('https://example.com/article/')); + expect(normalizeUrl('https://example.com/#/one')).not.toBe(normalizeUrl('https://example.com/#/two')); }); it('formats relative time for recent timestamps', () => { diff --git a/vite.config.ts b/vite.config.ts index c6ef216..ff87ff0 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -2,7 +2,7 @@ import { defineConfig, Plugin } from 'vite'; import { resolve } from 'path'; import { readFileSync } from 'fs'; -function manifestPlugin(): Plugin { +function manifestPlugin(chromium: boolean): Plugin { return { name: 'vite-plugin-bagmark-manifest', generateBundle() { @@ -10,10 +10,17 @@ function manifestPlugin(): Plugin { const manifestContent = JSON.parse(readFileSync(manifestPath, 'utf-8')); // Transform background script entry from TypeScript source to compiled bundle - manifestContent.background = { + manifestContent.background = chromium ? { + service_worker: 'background.js', + type: 'module' + } : { scripts: ['background.js'], type: 'module' }; + if (chromium) { + delete manifestContent.browser_specific_settings; + manifestContent.minimum_chrome_version = '123'; + } this.emitFile({ type: 'asset', @@ -24,10 +31,10 @@ function manifestPlugin(): Plugin { }; } -export default defineConfig({ - plugins: [manifestPlugin()], +export default defineConfig(({ mode }) => ({ + plugins: [manifestPlugin(mode === 'chromium')], build: { - outDir: 'dist', + outDir: mode === 'chromium' ? 'dist-chromium' : 'dist', emptyOutDir: true, rollupOptions: { input: { @@ -47,4 +54,4 @@ export default defineConfig({ } } } -}); +}));