Files
bookmarkmagic/docs/02_ARCHITECTURE.md
T
poli0981andClaude Opus 5.5 355443ef6b docs: specify Firefox (AMO) and Edge Add-ons support for v1.3.0
Docs first, as CLAUDE.md requires; the code follows in this branch.

- 08: the manifest per target (two packages from one source, MV3 for
  both); Firefox's gecko id, data-collection declaration, floor 140 and
  source-code submission; Edge takes the Chrome package unchanged.
- 02 §4, 03 §1/§3, 04, 05 §10: Firefox's GUID roots and fourth root, the
  Bookmarks Menu (`root: "menu"`, unmarked entries routed into it on
  Firefox); separators recognised by type, kept out of the file model and
  shown as untouchable lines in #edit; the move index sent by each browser's
  own rule and checked against the reply; addresses Firefox refuses dropped
  before planning; separators a file holds counted.
- 06/07: the About link follows the install; three strings that blamed
  Chrome for what every browser does are reworded; new keys listed.
- 11: a Firefox flavour of the fake, and a manual pass on real Firefox and
  Edge (including Edge signed in with sync) before the first submissions.
- 12/13: three store jobs, each in its own environment with only its own
  secrets and a four-package install; CWS API v2 (v1.1 died 2026-10-15);
  AMO and Edge runbooks for the first, manual uploads.
- 09/14 and legal/: three stores named; a clarification, not a
  LEGAL_VERSION bump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:10:35 +07:00

23 KiB
Raw Blame History

02 — Architecture

1. High-level shape

Two UI surfaces, no background service worker, one pure-logic core:

┌───────────────┐     opens      ┌─────────────────────────────────┐
│  Popup (mini) │ ─────────────▶ │  Manager (full-tab SPA)         │
│  3 actions    │                │  #import #export #edit          │
└───────────────┘                │  #settings #about (+ LegalGate) │
                                 └───────────┬─────────────────────┘
                                             │ calls
                              ┌──────────────▼──────────────┐
                              │ src/lib/browser  (adapters) │  chrome.bookmarks
                              │ thin async wrappers          │  chrome.storage
                              └──────────────┬──────────────┘  chrome.i18n
                                             │ uses
                              ┌──────────────▼──────────────┐
                              │ src/lib/core (PURE TS)      │  ← 90%+ test coverage
                              │ parse · serialize · dedupe  │  ← zero browser APIs
                              │ diff · normalize · plan     │
                              └─────────────────────────────┘

Why no background worker: every feature runs while an extension page is open. Long imports run in the Manager tab (popups die on blur — never run work there). Fewer moving parts, fewer review questions.

2. Directory layout (WXT conventions)

wxt.config.ts sets srcDir: 'src', so WXT resolves entrypoints/, components/ and assets/ under src/, and its @ alias points at src/ — i.e. @/lib/core/model → src/lib/core/model.ts. (The WXT default, srcDir: '.', would put entrypoints/ at the repo root and is incompatible with keeping library code under src/lib/.)

⚠️ publicDir must also be set explicitly — WXT resolves it against the project root, not srcDir (resolve-config.mjs: path.resolve(root, publicDir ?? 'public')). Without publicDir: 'src/public' the build silently omits _locales/ and icon/, and Chrome then refuses to load the extension because __MSG_appName__ and the declared icons resolve to nothing. The build log gives no warning — verify the output tree, not just the exit code.

bookmarkmagic/
├── CLAUDE.md                    # AI build instructions (root)
├── wxt.config.ts                # srcDir + manifest + svelte module
├── biome.json / knip.json / tsconfig.json / tsconfig.scripts.json / vitest.config.ts
├── sonar-project.properties     # SonarCloud CI analysis (12 §2.5)
├── .nvmrc / .npmrc              # Node 26; min-release-age=7 (01 §2, §6)
├── scripts/                     # all plain .mjs, type-checked via checkJs
│   ├── guard.mjs                # the source gate (08 §3), run by npm run guard
│   ├── check-manifest.mjs       # the built-artifact gate (08 §3), npm run check:manifest
│   ├── gen-icons.mjs            # zero-dep PNG writer — the icons' source of truth
│   ├── gen-fixture.mjs          # large Netscape files for 11 §5/§6, never committed
│   ├── sanitize-bookmarks.mjs   # reporter-facing sanitizer (CLI entry, 09 §6)
│   └── sanitize/                # its format modules: detect, mappers, spans, html, json, csv, leaks
├── docs/                        # this suite (00–15)
├── legal/                       # EULA.md, DISCLAIMER.md, PRIVACY.md, THIRD_PARTY_NOTICES.md
├── README.md / CHANGELOG.md     # what users read; CHANGELOG is linked from #about
├── ACCESSIBILITY.md             # the accessibility statement (06 §5), linked from #about
├── CONTRIBUTING.md / SECURITY.md / CODE_OF_CONDUCT.md
├── .github/                     # issue forms, PR template, workflows (12), dependabot, FUNDING
├── src/
│   ├── public/
│   │   ├── icon/                # 16/32/48/128 png
│   │   ├── _locales/{en,vi,ja,zh_CN,ro}/messages.json   # manifest-level strings only (07 §1)
│   │   └── THIRD_PARTY_NOTICES.txt  # MIT notices for what the build compiles in (14 §5)
│   ├── entrypoints/
│   │   ├── popup/               # index.html + App.svelte + main.ts
│   │   └── manager/             # index.html + App.svelte + main.ts (unlisted page)
│   ├── lib/
│   │   ├── core/                # PURE — see below
│   │   │   ├── model.ts             # BookmarkNode, ImportPlan, Stats types
│   │   │   ├── parse-file.ts        # parseBookmarkFile: sniff, parse once, route (04 intro)
│   │   │   ├── parse/
│   │   │   │   ├── shared.ts            # WarningBag, NodeBudget, bookmarkTitle, RootTitles
│   │   │   │   ├── netscape-html.ts
│   │   │   │   ├── bm-json.ts
│   │   │   │   ├── chrome-json.ts       # Chrome profile `Bookmarks` file (04 §2a)
│   │   │   │   ├── firefox-json.ts      # Firefox JSON backup (04 §2b)
│   │   │   │   └── csv.ts
│   │   │   ├── serialize/
│   │   │   │   ├── netscape-html.ts
│   │   │   │   ├── bm-json.ts
│   │   │   │   ├── csv.ts
│   │   │   │   └── markdown.ts
│   │   │   ├── normalize-url.ts
│   │   │   ├── timestamps.ts
│   │   │   ├── dedupe.ts
│   │   │   ├── diff.ts
│   │   │   ├── detect-format.ts     # sniffFormat + jsonFormatOf
│   │   │   ├── href.ts              # classifyHref: what an address is worth importing
│   │   │   ├── csv-dialect.ts       # columns, delimiters, formula guard
│   │   │   ├── route.ts             # top-level root routing / unwrapping (03 §1)
│   │   │   ├── merge.ts             # Merge folder reuse (05 §5)
│   │   │   ├── caps.ts              # would the import read this back? (03 §1 step 6b)
│   │   │   ├── plan.ts              # buildImportPlan → segments (§4)
│   │   │   ├── search.ts            # #edit filter + ancestor expansion
│   │   │   ├── select.ts            # tri-state export selection → subtree
│   │   │   ├── csv-path.ts          # folder-path encoding shared by CSV both ways
│   │   │   └── limits.ts            # MAX_FILE_BYTES, MAX_NODES, MAX_DEPTH, LEGAL_VERSION
│   │   ├── browser/
│   │   │   ├── bookmarks.ts         # getTree/create/move/update/remove wrappers
│   │   │   ├── write-queue.ts       # sequential tree writer + progress + abort
│   │   │   ├── storage.ts           # typed settings/legal accessors
│   │   │   ├── download.ts          # Blob → <a download>
│   │   │   ├── app-info.ts          # manifest version — the ONE source (06 §3.5)
│   │   │   ├── errors.ts            # BmBrowserError / BmBackupError / BmAborted (§7)
│   │   │   ├── open-url.ts          # http(s) allowlist before tabs.create (09 T3)
│   │   │   ├── open-manager.ts      # getContexts() focus-or-create + route broadcast (§6)
│   │   │   ├── write-lock.ts        # one writer across Manager tabs (03 §5)
│   │   │   ├── diagnostics.ts       # in-memory, allowlisted event log (09 §7)
│   │   │   ├── describe-error.ts    # error → i18n key + detail (§7)
│   │   │   └── clipboard.ts         # write-only clipboard (09 T8)
│   │   ├── import/run-import.ts     # the import pipeline (03 §1)
│   │   ├── export/run-export.ts     # the export pipeline (03 §2)
│   │   ├── edit/                    # edit-node, patch-tree, move-target (incl. planDrop),
│   │   │                            # tree-keyboard, tree-keys, sort, live-sync,
│   │   │                            # search-expansion, focus-repair, row-window (03 §3)
│   │   ├── import/folder-name.ts    # the new-folder import's date (07 §3)
│   │   ├── settings/options.ts      # the six Settings choice tables (06 §3.4)
│   │   ├── links.ts                 # repo / legal / donate URLs (14 §4, §5)
│   │   ├── stores/                  # Svelte 5 runes state (.svelte.ts)
│   │   │   ├── settings.svelte.ts   # locale, theme, defaults (persisted)
│   │   │   ├── legal.svelte.ts      # acceptedVersion
│   │   │   ├── toast.svelte.ts      # transient status queue + its timers (06 §4)
│   │   │   ├── route.svelte.ts      # location.hash + hashchange wrapper (§5)
│   │   │   ├── import-session.svelte.ts
│   │   │   ├── edit-view.svelte.ts      # #edit: what the tree shows (03 §3)
│   │   │   ├── edit-commands.svelte.ts  # #edit: single-item writes, extends the view
│   │   │   ├── edit-session.svelte.ts   # #edit: duplicates + bulk commands, extends both
│   │   │   └── edit-live.ts             # #edit: subscribes a session to the browser's events (03 §3)
│   │   ├── i18n/                    # runtime UI i18n (see 07_I18N.md)
│   │   │   ├── index.svelte.ts
│   │   │   ├── format.ts            # pure Intl number/date helpers (07 §3)
│   │   │   ├── resolve-locale.ts
│   │   │   └── locales/{en,vi,ja,zh-CN,ro}{,-notices,-import}.ts   # split by namespace (07 §2)
│   │   └── components/              # Svelte components (see 06_UI.md); icons/Icon.svelte,
│   │                                # focus-heading.ts (the step-heading focus attachment)
│   └── styles/
│       ├── tokens.css               # CSS custom properties, themes
│       └── base.css
└── tests/
    ├── fixtures/                    # real exports: chrome/edge/firefox/safari + malformed
    └── unit/                        # mirrors src/lib/core structure

3. Layer rules (enforced in review)

  1. core/ imports nothing from browser/, stores/, Svelte, or chrome.*. It may use DOMParser (available in extension pages). Tests provide it via jsdom, which is required rather than optional: the Netscape walk depends on HTML5 "generate implied end tags" (the <DL> nesting inside an unclosed <DT>) and on :scope > h3 from an element root. jsdom uses parse5 and is spec-compliant on both; happy-dom implements neither reliably, so a suite run there would validate a DOM the browser never produces. 11 §3 carries a canary test so an environment swap fails loudly instead of silently.
  2. browser/ may import core/. Never the reverse.
  3. Svelte components never call chrome.* directly — always through browser/ wrappers (mockability + one place for error mapping).
  4. Stores hold state; components render; browser/ performs effects.
  5. One file = one responsibility. Format converters are one file per format per direction.

4. Core data model

// src/lib/core/model.ts
export interface BookmarkNode {
  title: string;
  url?: string;            // undefined ⇒ folder
  addDate?: number;        // epoch SECONDS (normalized, see timestamps.ts)
  lastModified?: number;   // epoch SECONDS
  toolbar?: boolean;       // Netscape PERSONAL_TOOLBAR_FOLDER
  root?: 'other' | 'mobile' | 'menu'; // folder IS that browser root (since v1.1.0; 'menu' since v1.3.0; toolbar wins)
  children?: BookmarkNode[];
}

export type FileFormat =      // what a file was read as — sniffed, never the extension
  'netscape-html' | 'bm-json' | 'csv' | 'chrome-json' | 'firefox-json';

export interface ParseResult {
  roots: BookmarkNode[];        // top-level nodes from the file
  stats: TreeStats;             // bookmarks, folders, maxDepth
  warnings: ParseWarning[];     // tolerated anomalies (dropped ICON, bad dates…)
}

export type MergeMode = 'new-folder' | 'merge' | 'replace';

export interface PlanSegment {
  parentId: string;             // live folder to write under: a root, or (Merge) a folder that exists
  nodes: BookmarkNode[];        // created in order and appended; each node's children nest inside it
  trail?: string[];             // titles from the root down to parentId, for the progress line
}

export interface ImportPlan {
  mode: MergeMode;
  dedupe: boolean;              // the EFFECTIVE value: always false for Replace
  segments: PlanSegment[];      // final, post-dedupe trees + their destinations
  stats: {
    toCreate: number;           // total nodes across ALL segments (folders + bookmarks)
    bookmarkCount: number;      // bookmarks only — the "Import n bookmarks" button label
    folderCount: number;        // folders to create, the new-folder wrapper included
    reusedFolders: number;      // existing folders Merge writes into instead of copying
    skippedExisting: number;    // dropped because the URL is already in the browser
    skippedInFile: number;      // dropped because the URL repeats within the file
  };
}

Why segments and not a single root. Top-level nodes go to three different roots (bar, Other, Mobile), Replace deletes the children of all of them before writing, and Merge writes into folders that already exist at any depth. A single destination cannot express any of that.

Segment construction per mode — spelled out so it is not left to interpretation:

Mode Segments
new-folder Exactly one. parentId = Other Bookmarks; nodes = the single Imported <date> wrapper folder containing the whole parsed tree, root folders included. Markers are informational only (03 §1).
merge Top-level nodes are routed first (core/route.ts, 03 §1 step 7): a toolbar folder's children → the bar; a root: "other" folder's children → Other, in its place in the order; a root: "mobile" folder's children → Mobile (an ordinary folder under Other when the profile has no Mobile root); a root: "menu" folder's children → the Bookmarks Menu (an ordinary folder under Other where there is none — every Chromium browser); everything else → the Bookmarks Menu where the browser has one (Firefox — what Firefox's own HTML import does with loose entries), else Other. Each root's list is then matched against that root's live children (core/merge.ts, 05 §5): a folder with the exact title of a writable live child folder is reused — not created — and its children are matched one level down; everything else becomes a node in the segment of the live folder it lands in. One segment per live folder that receives anything, in first-use order.
replace As merge, but planned against emptied roots, so nothing matches and every node is created.

A root nothing is bound for gets no segment. stats.toCreate is the total across all segments — progress and the final report keep one denominator and one done counter for the whole import (05 §6). Every node is accounted for: toCreate + reusedFolders + unwrapped root folders equals the deduped tree (asserted over 200 random trees in merge.test.ts).

Firefox (since v1.3.0). Firefox has no folderType, its roots are GUIDs — menu________, toolbar_____, unfiled_____, mobile______, in that order — and it has a fourth root Chromium lacks, the Bookmarks Menu. getRoots() tries those GUIDs after the Chromium ids and before position, so the position fallback (which on Firefox would take the Menu for the bar) is never reached, and returns the Menu as a fourth destination that Replace also empties. Separators exist only in Firefox's live tree: type: "separator" and, for historical reasons, url: "data:". They are recognised by type, never by the url; toBookmarkNodes drops them, so the file model never holds one, and #edit shows them as lines no command can touch (03 §3). Counting helpers in browser/bookmarks.ts keep them out of every bookmark count.

Chrome root mapping: browser/bookmarks.ts getRoots() resolves the three destinations by folderType (bookmarks-bar, other, mobile, Chrome 134+), among this device's roots only — a signed-in account's own roots (syncing: true, Chrome 134+) are listed but never written to or emptied. Without folderType it falls back to the stable Chromium ids ("1"/"2"/"3") and then to position. Desktop Chrome leaves an empty Mobile root out of getTree(), so a missing Mobile is looked up with bookmarks.get("3"); only if that fails do Mobile-marked folders land under Other. Segment parentIds always come from that resolution or from live folders found in the same read, never a literal — but tests may rely on the ids.

Address length inside the browser. Firefox refuses an address longer than 65 536 characters (and shortens titles past 4 096). The import drops such addresses before planning, as URL_TOO_LONG, using a limit the browser layer passes in — Chromium has none, so nothing changes there (03 §1).

Depth inside the browser is capped separately from the parse cap: MAX_WRITE_DEPTH (90 levels below a root). Chrome stores its bookmarks as JSON it reads back with a 200-level nesting limit, two levels per folder, so a tree past about 98 folders deep saves and then fails to load on the next start. The plan reports stats.writeDepth; a plan past the cap is refused with TOO_DEEP before any backup or deletion, and the preview says so first.

Note the live tree is not BookmarkNode. BookmarkNode is the file model (no ids — core/ may not know about chrome.*, layer rule 1). Anything touching the browser tree (#edit, the duplicate panel, live sync) works with chrome.bookmarks.BookmarkTreeNode, which already carries id, parentId, index. Export maps the latter down to the former (03 §2).

5. Manager routing

Hash-based, zero-dependency: #import (default) · #export · #edit · #settings · #about. A tiny route.svelte.ts store wraps location.hash + hashchange. options_ui in the manifest points to manager.html#settings (open_in_tab: true).

⚠️ Right-click → Options lands on #settings only when no Manager tab is already open. With open_in_tab: true, Chrome opens the options page via singleton-tab matching, which ignores the fragment — so if a Manager tab is already sitting on #edit, Chrome just activates that tab and no navigation occurs. Whether the view then switches depends entirely on route.svelte.ts reacting to hashchange. A URL fragment in options_ui.page is also undocumented (the Chrome reference defines the value as a path); it works in current Chromium, so keep it, but treat it as behaviour to re-verify at each submission (08 §8).

6. Popup → Manager handoff

browser/open-manager.ts:

  1. browser.runtime.getContexts({ contextTypes: ['TAB'] }) → find an existing manager context (requires Chrome 116+; the floor is 136 — 01 §1).
  2. Found → browser.tabs.update(tabId, { active: true }) + browser.windows.update(windowId, { focused: true }) (no tabs permission needed for these calls). Before focusing, it posts { kind: 'navigate', route, tabId } on the bookmarkmagic-manager BroadcastChannel (same-origin, in-browser, no permission). Each Manager compares tabId with its own, from tabs.getCurrent() (no permission), so only the tab being focused acts; with two Managers open, 1.1.0's first cut switched both. The Manager validates the message and the route and switches to it — unless an import is writing, when it refuses with the same "busy" toast the tab bar uses (03 §5). 1.0.x only focused the tab, so "Export…" in the popup landed wherever the Manager had been left.
  3. Not found → browser.tabs.create({ url: browser.runtime.getURL('/manager.html') + hash }).

Popup may pass an intent (#import / #export / #edit / #settings) via the hash for a new tab, or via the broadcast for an open one.

7. Error handling strategy

  • core/ throws typed errors (BmParseError { code, line?, detail }). The code set is closed — add to this table before adding to the code:

    Code Raised when
    NOT_NETSCAPE No NETSCAPE-Bookmark-file-1 doctype and no <DL> found
    NOT_BM_JSON The file is valid JSON but none of the three dialects BookmarkMagic reads (BM JSON, Chrome Bookmarks, Firefox backup — 04 intro). Before v1.1.0: "not format: "bookmarkmagic"".
    MALFORMED_JSON JSON.parse throws
    INVALID_NODE Structural check fails (missing/non-string title, non-string url, children on a bookmark)
    BAD_CSV_HEADER Header row missing or columns not in the fixed order
    CSV_ROW_MISMATCH Row field count ≠ header field count
    CSV_UNCLOSED_QUOTE A quoted CSV field never closes; line is where it opened (since v1.1.0)
    UNKNOWN_FORMAT detect-format.ts matched nothing
    FILE_TOO_LARGE Size > MAX_FILE_BYTES
    TOO_MANY_NODES Node count > MAX_NODES
    TOO_DEEP Nesting depth > MAX_DEPTH

    Non-fatal anomalies are ParseWarnings, never errors. The set is closed too (PARSE_WARNING_CODES in core/model.ts; dictionaries.test.ts requires a plural message for each in every locale): NO_BOOKMARKS, DESCRIPTIONS_DROPPED, FAVICONS_IGNORED, INVALID_DATE, MISSING_URL, NEWER_VERSION, EMPTY_TITLE, and since v1.1.0 INVALID_URL (an address chrome.bookmarks.create would reject), PLACE_QUERIES_SKIPPED (Firefox smart bookmarks), EXTRA_ROOTS_SKIPPED (vendor roots in a browser JSON file) and UNREADABLE_ENTRIES (a <DT> with no readable <A> or <H3>).

  • browser/ adds BmBackupError { code } for the forced safety backup (03 §1 step 6b) — BACKUP_SERIALIZE_FAILED, BACKUP_EXCEEDS_LIMITS (since v1.1.0: the backup would be refused by the import's own caps, so it is no backup), BACKUP_CANCELLED, BACKUP_WRITE_FAILED; the runtime list BM_BACKUP_ERROR_CODES is held to a message per locale like the parse codes — and BmAborted { done } for a cancelled write.

  • browser/ maps chrome.runtime.lastError / promise rejections into typed results; never lets raw errors reach components.

  • UI shows human-readable, localized messages + a copyable technical detail block (for GitHub issue reports).

  • The write queue is abortable (AbortController) and reports { done, total, currentPath } progress events.