Compare commits

...
110 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 80c7190864 chore(release): 1.3.0
Firefox and Microsoft Edge Add-ons, and maintenance mode. Permissions are
unchanged; nothing re-asks for consent (LEGAL_VERSION stays 1).

- package.json and the lockfile's root at 1.3.0; CHANGELOG [1.3.0] with
  Added / Changed / Fixed / Packages.
- docs/00 §10 items 19-26: what only the owner can do for this release
  (the store uploads, the first AMO and Edge submissions by hand, the store
  environments, real-browser QA, native review).
- docs/15: Phase 10 in the progress table; 1.2.1 may be skipped on the
  store, since 1.3.0 contains it.
- docs/13 §8: the sources archive rebuilt every file of the Firefox
  package byte for byte. docs/08 §9: Options can open a second Manager tab
  on Firefox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:10:35 +07:00
poli0981andClaude Opus 5.5 ffceb4bd54 fix: review findings — separators are not items, Replace counts what it deletes
An adversarial review of the Firefox port found:

- #edit treated a Firefox separator as an item in three places: a folder's
  count badge, whether a folder can be expanded, and whether it can be
  sorted. A folder of separators and one bookmark offered Sort A-Z.
- Replace's confirmation counted every writable root, so a signed-in
  Chrome's account roots, which Replace never empties, were counted among
  what it would delete. In every release since 1.1.0; it now counts the
  replaceable roots only.
- The store jobs checked their files against the SHA256SUMS.txt that came
  in the same artifact, with --ignore-missing. Each file is now checked by
  name against the published Release's checksums.
- Qodana's publish job ran only after a successful scan, so a scan failing
  on findings never published them.
- getRoots' position fallback had no test. It now has two, with unknown
  ids and a Bookmarks Menu listed first.

Docs follow: the two browser modules and the warning codes (02), where the
landed index is compared (05), the separator markup and folder count (06),
what the Firefox suites are (11), the release staging and environments
limited to v* tags (12, 00), and which loose entries reach the Bookmarks
Menu on Firefox (03, 04, README).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:10:35 +07:00
poli0981andClaude Opus 5.5 23f6386d3d docs: Firefox and Edge for users — install, build, limits, listings
- BUILD.md: rebuilding the release packages, written for Firefox Add-ons'
  source review (Node.js 26 stated outright: the sources archive drops
  .nvmrc), and useful to anyone checking a store build against the source.
- README: a browser/store/requirement table (Edge and Firefox listings not
  live yet, and said so), the Firefox package on each Release is for
  checking, not installing; the privacy section names the same CSP in every
  browser; limits gain Firefox's separators, address and title lengths.
- SECURITY.md: the latest version on each of the three stores is supported.
- ACCESSIBILITY.md: Firefox and Edge are best effort and untested with
  assistive technology; separators are drawn but not announced, and Alt+↑/↓
  past one leaves the spoken position unchanged — a known limitation.
- store/listing.*.md: the AMO and Edge blocks — the two bullets that named
  Chrome rewritten for browsers in general, one more limitation for Firefox,
  and each store's fields. Translations best-effort.
- CHANGELOG: the 1.3.0 entry under [Unreleased] until the bump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:10:35 +07:00
poli0981andClaude Opus 5.5 dc4cd06cbb ci: build both packages, and publish to three stores from isolated jobs
- ci.yml: the Firefox package is built and checked beside the Chrome one.
- release.yml: three release files — the Chromium package (Chrome Web Store
  and Edge Add-ons), the Firefox package and AMO's sources archive — each
  staged by exact name so a missing one fails the run, both manifests checked
  against the tag, SHA256SUMS over all three.
- One store job per store (docs/12 §3), each off until its repo variable is
  true, each in its own GitHub Environment holding only its own secrets, each
  checking the downloaded file against SHA256SUMS before uploading. They
  install tools/publish — publish-browser-extension 6.2.0 and its three
  dependencies, from their own lockfile, scripts off — instead of the ~320
  packages of the dev toolchain, which the single old job installed next to
  four Chrome secrets.
- The old job could not have worked: it sent CWS API v1.1 credentials, and
  v1.1 was shut down on 2026-10-15. store-chrome uses v2 (publisher id and a
  service account) and sets CHROME_API_VERSION explicitly. store-firefox is
  listed and desktop-only; store-edge sends the Chromium package.
- Dependabot watches tools/publish; the licence gate reads its lockfile too.
- qodana.yaml: clean since the first run's findings were handled, so any new
  one now fails that (non-required) workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:10:35 +07:00
poli0981andClaude Opus 5.5 2eaa1acce4 feat(firefox): the right roots, the Bookmarks Menu, separators and move index
What made Firefox more than a build target (docs/02 §4, 03, 04, 05 §10):

- Roots. getRoots (now browser/roots.ts) tries Firefox's GUIDs after
  folderType and the Chromium ids, and never takes the Bookmarks Menu by
  position — Firefox lists it first, and the old fallback took it for the
  bar, so a Replace emptied the Menu and the toolbar and restored into the
  wrong roots. The Menu is a fourth destination Replace also empties.
- The Menu in the file model: root "menu" (BM JSON, additive); HTML writes
  its entries loose at the top level, as Firefox's own export does; on
  Firefox loose top-level entries are routed into the Menu, elsewhere a menu
  folder stays a folder under Other. New-folder mode is unchanged.
- Separators come back as { type: "separator", url: "data:" }. Recognised by
  type (browser/live-tree.ts): left out of exports and backups, of every
  count, of the dedupe index and the duplicate finder, never a search match;
  in #edit they are aria-hidden lines that take no focus or command, with
  posinset counting items only, Alt+↑/↓ stepping past one as one place, and
  Sort A→Z sorting each run between them. The Replace confirmation says how
  many will go and that nothing brings them back; files' separators are
  counted (SEPARATORS_SKIPPED).
- Move index: Chromium counts a rightward same-folder move before removal,
  Firefox after. The adapter sends each its own number and the reply's index
  is checked — a mismatch re-reads the tree. Before this, every rightward drag
  on Firefox landed one place too far and Alt+↓ moved two.
- Firefox refuses addresses over 65 536 characters, mid-write: dropped before
  planning on Firefox (URL_TOO_LONG); nothing changes on Chromium.
- Strings true in every browser: the date note says "the browser", the About
  link is "Store listing" and goes to the listing the copy came from (AMO by
  gecko id, the Chrome Web Store by item id, else the README's install
  section); the smart-bookmark note drops "dead link". Diagnostics names the
  browser. All five locales (ja/zh-CN/ro best-effort).

bookmarks.ts was over the 300-line target, so its pure half moved to
live-tree.ts and root resolution to roots.ts before anything was added.
Tests run the root, Replace, export and #edit paths over a Firefox flavour of
the fake (docs/11 §4). Also fixes the last Qodana finding, a redundant escape
in the i18n interpolation regex.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:10:35 +07:00
poli0981andClaude Opus 5.5 779335802a build(firefox): a second package, MV3, held to its own manifest gate
wxt.config.ts now builds for the target browser (docs/08 §1, §9):

- `manifestVersion: 3` for every target — WXT built Firefox as MV2;
- Firefox gets browser_specific_settings.gecko — the permanent id
  bookmarkmagic@poli0981.dev, strict_min_version 140.0 (the first that
  accepts data_collection_permissions, which AMO requires of new add-ons),
  and data_collection_permissions { required: ["none"] } — and no
  minimum_chrome_version; Chrome keeps its floor of 136;
- Vite targets firefox140 for that package;
- the sources archive AMO reviews leaves out coverage, captures, store copy,
  docs, tests and tools.

Permissions, CSP, pages and icons are identical in both packages.
check-manifest.mjs takes --browser chrome|firefox, mapped through a fixed
table to .output/<target>-mv3 (still no path from the command line), and
pins each package's exact key set and floor; the gecko block is compared key
order aside. New npm scripts: build:firefox, zip:firefox; verify:full builds
and checks both packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 22:10:35 +07:00
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
poli0981andClaude Opus 5.5 8519e7c39e fix(qodana): act on the first run, and read the report where it really is
The first scan found 27 issues and no defect:
- two regular expressions that could be simpler, fixed: the sanitizer's
  [\p{Extended_Pictographic}] class and wxt.config.ts's split(/[/]/). A third
  is in src/ and waits for the 1.3.0 change, so this branch still builds
  byte-for-byte what v1.2.1 shipped;
- 24 that contradict a rule of this repository, switched off in
  qodana.yaml with the reason beside each: JSDoc completeness (doc comments
  here are prose, docs/10 §6), bitwise operators in the PNG CRC-32 of
  gen-icons.mjs, and the deliberately doubled dark palette in tokens.css.

`publish` failed: the qodana-report artifact holds a zip whose entries have
absolute names, so a glob for the SARIF found nothing. It now extracts the
one entry /qodana.sarif.json by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:03:47 +07:00
poli0981andClaude Opus 5.5 76a57fb739 docs: GO for Firefox and Edge as v1.3; the roadmap under maintenance mode
Recorded now rather than with the port, because the maintenance
announcement names it (docs/15, docs/00 §7). Settled with the owner: gecko
id bookmarkmagic@poli0981.dev, desktop only (Firefox for Android has no
bookmarks API), MV3 everywhere, and Firefox separators shown, protected and
warned about rather than stored in a file format.

The roadmap is pruned to what MAINTENANCE.md allows: scheduled snapshots
need the alarms permission and leave it; the permission rule joins the never
list; the fflate zip export, the duplicate auto-merge assistant and
bookmarklet notes are not planned; the old v1.3 "resilience" becomes v1.4.

MAINTENANCE.md no longer lists "a dependency advisory" as a release trigger
on its own: with no runtime dependencies, an advisory against the build
tools needs a release only if it changed what ships.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:03:47 +07:00
poli0981andClaude Opus 5.5 0ec5187e4b ci: Qodana for JS, and a harder triage workflow
qodana.yml runs qodana-js (Ultimate, QODANA_TOKEN) on pushes to main, pull
requests, a weekly schedule and by hand, in two jobs (docs/12 §2.7):

- `scan` installs the dev dependencies with scripts off — qodana-js resolves
  types through them — and holds only a read-only GITHUB_TOKEN; PR comments
  and annotations are off, the SARIF report is kept as an artifact;
- `publish` installs nothing and uploads that SARIF to code scanning
  (category qodana), so the findings sit beside CodeQL's.

The action is pinned to the commit of v2026.2.2 (the newest tag is younger
than the 7-day cooldown). Sharing a runner with dependency code is recorded
as an exception to the Sonar rule: the token can only upload reports.

triage.yml, from review of the first draft:
- comment and close first, label last — the label is what a re-run reads as
  done, so it must not exist before the work;
- an `enhancement` issue with no answer to the form is closed only when the
  owner added the label; otherwise it goes to needs-triage;
- checkout and setup-node pinned to commits, no cache: this workflow runs
  them with a write token on events anyone can trigger.

README gains the Qodana badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:03:47 +07:00
poli0981andClaude Opus 5.5 eabffbe652 feat(repo): maintenance mode, with triage that closes out-of-policy requests
MAINTENANCE.md is the policy: dependency updates on a schedule, high and
critical advisories fixed as soon as a fix exists, major platform upgrades,
bug/UI/UX/accessibility/translation fixes, and features only when they are
on docs/15's roadmap or genuinely needed.

- The feature form asks one required question — on the roadmap, needed for
  a fix, or something new — and links the policy and Discussions › Ideas.
- scripts/triage.mjs decides what happens, as a pure, unit-tested function;
  .github/workflows/triage.yml carries it out with `gh` alone. Something new
  is labelled maintenance-mode, commented and closed as not planned; the two
  in-policy answers get needs-triage; an outside `feat…` pull request is
  closed the same way. Owner, members, collaborators, bots and `roadmap` are
  exempt.
- pull_request_target checks out the base branch only, runs nothing from the
  pull request, and never interpolates a title or body into the shell.
- README gains a status badge and a "Project status" section; CONTRIBUTING,
  the PR template and the issue chooser say what is accepted.
- docs: 00 status, 11 inventory, 12 §2.6 and §5 (labels), 13 §6, 15 (a
  pointer to the policy, not a copy, and the decision-log rows); CLAUDE.md
  Phase 10.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:03:47 +07:00
poli0981andClaude Opus 5.5 11e7e50fe6 build: a licence gate over every package in the lockfile
scripts/check-licenses.mjs reads package-lock.json, where npm records each
package's own `license` field, and fails on anything outside two lists
(docs/09 §3.2):

- what the build compiles into the extension (svelte, clsx, wxt,
  @wxt-dev/browser) must be permissive and GPL-3.0-compatible;
- everything else is build tooling that never ships, so file-level copyleft
  (MPL-2.0, lightningcss) is also accepted; AGPL, source-available terms and
  missing or custom licences are not.

SPDX expressions are evaluated, nothing is installed or fetched, and the
tests call the functions directly rather than spawning the script. It runs
in `verify`, CI's quality job and the release build.

The shipped list moves out of wxt.config.ts into
scripts/credited-packages.mjs, so the build gate, the notices test and the
licence gate read one list instead of two copies and a regex.

legal/THIRD_PARTY_NOTICES.md said the tooling was all MIT/Apache-2.0/ISC; the
lockfile also has BSD, 0BSD, MIT-0, BlueOak, CC0 and MPL-2.0. Corrected — a
description of tooling that never ships, so no LEGAL_VERSION bump (14 §3.1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:03:47 +07:00
poli0981andClaude Opus 5.5 4b10749582 chore(deps): finish the Dependabot bumps and record the picomatch advisory
Dependabot's #39-#41 moved the packages and left the rest behind, as
docs/15 (2026-11-10) says it always does:

- biome.json and docs/10 name the schema of Biome 2.6.6;
- docs/01 records Biome 2.6.6, knip 6.44.2 and jsdom ^31.0;
- docs/12 §2.5 names the scan action's new pin, v8.4.1;
- docs/11 §6 gains a jsdom 31 column for the 100k parse (median of three
  runs, 2 484 ms) instead of overwriting the jsdom 29 figure.

docs/09 §3.1: npm audit now reports 14 high findings with one root cause,
picomatch GHSA-fc5q-39xc-vjpf, for which no fixed version exists. It is the
toolchain's glob engine, matching patterns this repository writes, and
never ships (--omit=dev stays 0). The deepmerge row goes: GitHub withdrew
that advisory on 2026-11-16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:03:47 +07:00
dependabot[bot] 77de0de1d5 chore(deps-dev): Bump jsdom from 30.1.3 to 31.0.0
Bumps [jsdom](https://github.com/jsdom/jsdom) from 30.1.3 to 31.0.0.
- [Release notes](https://github.com/jsdom/jsdom/releases)
- [Commits](https://github.com/jsdom/jsdom/compare/v30.1.3...v31.0.0)

---
updated-dependencies:
- dependency-name: jsdom
  dependency-version: 31.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-18 20:32:06 +07:00
dependabot[bot] 43681ecd1f chore(deps-dev): Bump the dev-minor-and-patch group with 2 updates
Bumps the dev-minor-and-patch group with 2 updates: [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) and [knip](https://github.com/webpro-nl/knip/tree/HEAD/packages/knip).


Updates `@biomejs/biome` from 2.6.4 to 2.6.6
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/CHANGELOG_v1.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.6.6/packages/@biomejs/biome)

Updates `knip` from 6.44.1 to 6.44.2
- [Release notes](https://github.com/webpro-nl/knip/releases)
- [Commits](https://github.com/webpro-nl/knip/commits/knip@6.44.2/packages/knip)

---
updated-dependencies:
- dependency-name: "@biomejs/biome"
  dependency-version: 2.6.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-minor-and-patch
- dependency-name: knip
  dependency-version: 6.44.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-18 20:26:58 +07:00
dependabot[bot] 6047f5bf30 ci(deps): Bump SonarSource/sonarqube-scan-action
Bumps the actions group with 1 update: [SonarSource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action).


Updates `SonarSource/sonarqube-scan-action` from 8.4.0 to 8.4.1
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](https://github.com/sonarsource/sonarqube-scan-action/compare/4d1dc0c91ee400dcf8a6dddf2f705ac36542e304...e805d875275f728fac1885b413934be6d7c63f65)

---
updated-dependencies:
- dependency-name: SonarSource/sonarqube-scan-action
  dependency-version: 8.4.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-18 20:26:38 +07:00
poli0981andClaude Fable 5.2 47206cc6c2 docs: record v1.2.1 as released on GitHub
Signed tag v1.2.1 on d61318a (PR #37, merged at the reviewed head). The
Release asset verifies against SHA256SUMS.txt (4975b5df…ca13254, 106 290
bytes); its manifest differs from 1.2.0's in `version` alone and the file
inventory is the same. `announce` and the store publish were skipped, as
their variables are unset.

Still the owner's: the docs/11 §5 pass with the 1.2.0 -> 1.2.1 upgrade over
an existing profile, a real Windows contrast theme and a screen-reader pass
over Alt+Up/Down, and the store upload.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:29:46 +07:00
poli0981andClaude Fable 5.2 d61318aed7 test(edit): cover the live-sync wiring that left EditTab
stores/edit-live.ts was untested — it is the block that used to sit in
EditTab's onMount, where nothing measured it. As a .ts module it counts, and
SonarCloud's new-code gate failed at 73.6 % (80 % required).

edit-live.test.ts drives it with wxt/browser mocked to hand-fired event
emitters and a hand-fired frame: one patch per frame, a parentless created
node ignored, nothing patched during Chrome's own import and one re-read
after it, a re-read on a wholesale reorder, and a teardown that detaches every
listener and drops what was queued. connectLive takes the batcher's scheduler
as an optional argument for that.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 0bd2aabbf2 chore(release): 1.2.1
Accessibility. An accessibility statement and its intake, Alt+Up/Down to
reorder from the keyboard, Windows contrast themes, and the focus and
target-size fixes an audit of src/ found. Permissions unchanged;
LEGAL_VERSION unchanged.

The built manifest differs from the v1.2.0 release asset in `version` only;
the file inventory is identical.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 2be6955087 fix(review): code and documentation review findings for 1.2.1
Two independent reviews, of the code and of the documentation against it.

Code:
- A first click on a row button or a chevron jumped the tree to the top:
  handing focus to the tree with no row focused made it pick the first one.
  The clicked control's row becomes the focused one, and the tree only picks
  the first row for a focus that came from the keyboard — which also stops a
  plain click on a row in a scrolled tree from landing on the wrong row.
- Three forced-colours rules lost to more specific ones: the selected theme
  lost its label on hover, About's status-bar entry had no right edge, and a
  drop into the focused folder showed nothing.
- Under a search, Alt+Up/Down announced the position among all siblings while
  the row's aria-posinset counts the ones on screen; it announces the latter.
  Moves run one at a time, and the live region is emptied before each
  message so a repeated text is spoken.
- The preview's "Show more" was still 22 px; the ring on "Show earlier / Show
  more" and on the "Move to…" folders was clipped; placeholders used the
  browser's grey, which no contrast test saw.
- EditTab's script was over the 150-line limit: its live-sync wiring moves to
  stores/edit-live.ts.

Documentation:
- ACCESSIBILITY.md promised more than the code does in nine places ("every
  clickable target is 24 px", "nothing times out", "focus is always a 2-pixel
  ring", four operating systems "supported"). Rewritten to what the source
  supports; the untested list and the known limitations grew.
- docs/05, 06, 10, 11, 13, 15 and CLAUDE.md corrected where they named tests
  that did not exist, miscounted, or were overtaken by the fixes above.

tests: a managed node, hidden siblings under a search and an in-flight move
for nudge; the statement's key table is checked against tree-keyboard.ts.
capture/about.png shows the new About link.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 8d9739cab4 build: svelte-check fails on warnings; the harness gives every node a parentId
Svelte's a11y_* checks are compiler warnings, and a warning never failed
anything: `npm run check` now runs svelte-check with --fail-on-warnings. It is
the only lint that reads the markup (Biome skips .svelte). The suite is at
zero warnings; the two deliberate exceptions carry a svelte-ignore.

scripts/screenshots.mjs built its sample tree without parentId, which Chrome
gives every node but the root. In the harness nothing could be placed beside
a sibling and the toolbar's Sort stayed disabled on a bookmark — found while
driving Alt+Up/Down through it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 9d4458ae4b feat(about): link the accessibility statement
The tree's keys are shown nowhere in the UI, and someone who meets a barrier
has no route from inside the product to reporting it. About now links
ACCESSIBILITY.md beside the changelog — the file, not an address: no email
appears on an in-product surface (docs/06 §3.5).

links.test.ts pins the URL and the file's existence, as it does for the
changelog. The label is new in all five locales; ja, zh-CN and ro are
best-effort like the rest of those files.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 e4f2a93820 fix(edit): Alt+Up/Down reorders from the keyboard; focus is no longer dropped
Placing an item before or after a sibling took a drag: "Move to…" only
appends, and Sort A→Z was the one keyboard reorder (WCAG 2.1.1; backlog since
the 1.1.0 review). Alt+Up and Alt+Down now move the focused row one place
among the siblings on screen.

No second write path: nudgeTarget picks the neighbour, and the drag's own
planDrop and moveTo do the rest, so a key and a drag cannot disagree about
what is legal — nothing happens at either end of a folder, on a permanent
root, on a managed node or while a bulk command runs. A polite live region
speaks "<title>: position n of m": aria-posinset changes too, but a screen
reader does not re-read the active descendant for an attribute change.

Focus no longer falls to <body>:
- a route change that takes the focused control with it ("Open in Edit" on
  the import report) moves focus to <main> — only when it was lost, and not
  while the page loads;
- after "keep the first of each", to the panel's close button;
- after a confirmed toolbar Sort A→Z, whose button is disabled while it runs,
  to the tree.

EditTab's dialogs move to EditDialogs.svelte to keep the tab under 300 lines.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 bf3eb9f22b fix(a11y): a focus ring that shows on a filled control, forced colours, 24 px targets
Found by an audit of src/ after a keyboard-only and Narrator pass over 1.2.0
found nothing; verified in a headless Chrome driven over CDP against the
harness, with forced-colors emulated.

- The theme control's ring was invisible. It is inset to stay inside the
  group's border, and roving focus only ever lands on the selected segment,
  which is filled with --accent: accent on accent. It is --accent-fg now, 4px
  in, so the fill shows on both sides of it.
- Contrast themes (forced-colors) remove every fill, shadow and background
  image. The tree's focused row and drop lines, the selected theme, the
  current tab and status-bar entry, the selected mode and format cards, the
  progress fill and the drop zone's dashed edge each get a system-colour
  equivalent. A border or outline wherever the state has a label: Chrome
  paints a backplate behind forced text, and a label on a Highlight fill
  became a box that hid it.
- Every pointer target is at least 24 x 24 px: the row buttons (22), the
  three disclosure chevrons (16, now one Disclosure component with a grown
  hit area), the toast and dialog dismiss buttons, the popup's gear, the
  picker's "Show more".
- A click on a row button or the chevron hands focus back to the tree.
  Chrome focuses a tabindex="-1" button on click and the tree ignores keys
  aimed at a row's own control, so one click switched the arrow keys off;
  "Move to…" from the row button now returns focus to the tree as well.

tests: focus-ring.test.ts fails on an inset ring over an accent fill;
forced-colors.test.ts holds the list of components that must carry the block.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 073a7cd654 docs(a11y): an accessibility statement, and a way to report a barrier
ACCESSIBILITY.md at the repository root, after opensource.guide's
accessibility practices and the accessibility-toolkit template: WCAG 2.2 AA
as a goal and not a conformance claim, supported environments, the tree's
full key table (shown nowhere in the UI), what was tested and with what
(keyboard only and Narrator with Chrome on Windows 11), what was not, the
known limitations, and how a report is handled by a one-person project.

Intake: an "accessibility" issue form and label, accessibility@poli0981.dev
in the issue chooser and the README's contact table, an interface section in
CONTRIBUTING.md and in the PR checklist.

tests/unit/accessibility-statement.test.ts pins the routes and the key
table, since nothing in the build reads the file.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 e5d1cf5bf5 docs: specify the accessibility work for v1.2.1; record v1.2.0 as live
v1.2.0 is on the store (listing observed 2026-11-10: version 1.2.0, updated
November 7, five languages); CLAUDE.md, docs/00 and docs/15 still said it had
not been submitted.

docs/06 §5 now specifies what an audit of src/ found the 1.2.0 keyboard and
Narrator pass could not: a ring inside a filled control takes the fill's text
colour, forced-colours equivalents for every state shown by a fill or a
shadow, Alt+Up/Down as the keyboard's before/after (through planDrop, docs/05
§10), three more places focus fell to <body>, row buttons handing focus back
to the tree, and 24 px targets.

docs/11 §5 gains the checks no script runs: a screen reader, a contrast
theme, 200 % zoom, and "ACCESSIBILITY.md is still true". docs/12 §4 says an
accessibility fix is a patch. docs/15 schedules what is not closed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
poli0981andClaude Fable 5.2 21b04c3e96 chore(deps): sync the Biome schema, the Vitest range and the pinned-version docs
Dependabot bumped @biomejs/biome to 2.6.4 and left the `$schema` URL in
biome.json at 2.6.2; `vitest` stayed at ^5.0.5 beside a ^5.1.0 coverage
plugin that docs/01 says must match it.

docs/01 §2 now states what is installed (WXT 0.21.5, Svelte 5.57.3,
svelte-check 4.7.8, Knip 6.44.1, Vitest 5.1.0) and docs/12 the Sonar scan
action's pin (v8.4.0).

WXT 0.21.4 -> 0.21.5 passed the built-manifest diff docs/12 §2.3 requires:
manifest.json byte-identical to the v1.2.0 release asset, same file
inventory, CSS identical, +33 bytes in one chunk from Svelte 5.57.3.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-10 11:18:58 +07:00
dependabot[bot] 8c4d75fe08 chore(deps-dev): Bump the dev-minor-and-patch group with 6 updates
Bumps the dev-minor-and-patch group with 6 updates:

| Package | From | To |
| --- | --- | --- |
| [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) | `2.6.3` | `2.6.4` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `26.6.5` | `26.6.6` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `5.0.5` | `5.1.0` |
| [knip](https://github.com/webpro-nl/knip/tree/HEAD/packages/knip) | `6.43.0` | `6.44.1` |
| [svelte-check](https://github.com/sveltejs/language-tools) | `4.7.7` | `4.7.8` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `5.0.5` | `5.1.0` |


Updates `@biomejs/biome` from 2.6.3 to 2.6.4
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/CHANGELOG_v1.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.6.4/packages/@biomejs/biome)

Updates `@types/node` from 26.6.5 to 26.6.6
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `@vitest/coverage-v8` from 5.0.5 to 5.1.0
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v5.1.0/packages/coverage-v8)

Updates `knip` from 6.43.0 to 6.44.1
- [Release notes](https://github.com/webpro-nl/knip/releases)
- [Commits](https://github.com/webpro-nl/knip/commits/knip@6.44.1/packages/knip)

Updates `svelte-check` from 4.7.7 to 4.7.8
- [Release notes](https://github.com/sveltejs/language-tools/releases)
- [Commits](https://github.com/sveltejs/language-tools/compare/svelte-check@4.7.7...svelte-check@4.7.8)

Updates `vitest` from 5.0.5 to 5.1.0
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v5.1.0/packages/vitest)

---
updated-dependencies:
- dependency-name: "@biomejs/biome"
  dependency-version: 2.6.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-minor-and-patch
- dependency-name: "@types/node"
  dependency-version: 26.6.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-minor-and-patch
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 5.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-and-patch
- dependency-name: knip
  dependency-version: 6.44.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-and-patch
- dependency-name: svelte-check
  dependency-version: 4.7.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-minor-and-patch
- dependency-name: vitest
  dependency-version: 5.1.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-10 08:28:08 +07:00
dependabot[bot] 533809ce4f ci(deps): Bump SonarSource/sonarqube-scan-action
Bumps the actions group with 1 update: [SonarSource/sonarqube-scan-action](https://github.com/sonarsource/sonarqube-scan-action).


Updates `SonarSource/sonarqube-scan-action` from 8.3.0 to 8.4.0
- [Release notes](https://github.com/sonarsource/sonarqube-scan-action/releases)
- [Commits](https://github.com/sonarsource/sonarqube-scan-action/compare/d209202bc7d53ff1cc128f7f907dac145c9d6ae9...4d1dc0c91ee400dcf8a6dddf2f705ac36542e304)

---
updated-dependencies:
- dependency-name: SonarSource/sonarqube-scan-action
  dependency-version: 8.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-10 08:27:54 +07:00
dependabot[bot] f65264a020 chore(deps-dev): Bump wxt from 0.21.4 to 0.21.5
Bumps [wxt](https://github.com/wxt-dev/wxt) from 0.21.4 to 0.21.5.
- [Release notes](https://github.com/wxt-dev/wxt/releases)
- [Commits](https://github.com/wxt-dev/wxt/compare/wxt-v0.21.4...wxt-v0.21.5)

---
updated-dependencies:
- dependency-name: wxt
  dependency-version: 0.21.5
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-06 20:21:22 +07:00
dependabot[bot] c5dd04a1b8 chore(deps-dev): Bump the dev-minor-and-patch group with 3 updates
Bumps the dev-minor-and-patch group with 3 updates: [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome), [knip](https://github.com/webpro-nl/knip/tree/HEAD/packages/knip) and [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte).


Updates `@biomejs/biome` from 2.6.2 to 2.6.3
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/CHANGELOG_v1.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.6.3/packages/@biomejs/biome)

Updates `knip` from 6.42.1 to 6.43.0
- [Release notes](https://github.com/webpro-nl/knip/releases)
- [Commits](https://github.com/webpro-nl/knip/commits/knip@6.43.0/packages/knip)

Updates `svelte` from 5.57.2 to 5.57.3
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.57.3/packages/svelte)

---
updated-dependencies:
- dependency-name: "@biomejs/biome"
  dependency-version: 2.6.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-minor-and-patch
- dependency-name: knip
  dependency-version: 6.43.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dev-minor-and-patch
- dependency-name: svelte
  dependency-version: 5.57.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dev-minor-and-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-06 20:06:02 +07:00
poli0981andClaude Opus 5.5 c42681fb04 docs: record v1.2.0 as released on GitHub
Signed tag on e2f36bc; the Release zip (105 284 bytes) passes
`sha256sum -c`, and its manifest differs from 1.1.0's only in `version`,
with _locales/zh_CN and _locales/ro added. Store submission, the upgrade
pass and the two new listing languages stay with the owner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:41:02 +07:00
poli0981andClaude Opus 5.5 e2f36bc6b1 chore(github): the PR checklist names every locale
The template still asked for "all three" locales; it now points at
LOCALES and the Romanian `few` form (docs/07 §5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +07:00
poli0981andClaude Opus 5.5 46606dce94 chore(release): 1.2.0
Simplified Chinese and Romanian (docs/07). Permissions, the Chrome
floor and LEGAL_VERSION are unchanged; the built manifest differs from
1.1.0 only in `version`, plus the two new _locales directories.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +07:00
poli0981andClaude Opus 5.5 63dcf0d4fc fix(review): translation and code review findings for zh-CN and ro
Translations (an independent native-style review of every key):
- ro export.csvNote said the bookmarks-bar folder itself is lost on CSV
  export; only *which* folder is the bar is lost.
- ro: counts that are plain numbers use a label form ("Omise — deja în
  acest browser: {n}") so 1 never reads as a plural; "din Chrome" for
  the brand; mode names quoted exactly; the tagline, appDesc and listing
  summary as a noun phrase instead of an informal imperative; the
  backup promise in replaceWarning made explicit; GPL wording.
- zh-CN: quoted mode names match the real labels (全部替换); 一半 no
  longer claims 50%; one name for Chrome's Bookmarks file; 您 only where
  it earns its place; the English-only note no longer implies
  translations exist.
- Uncertain strings carry TODO(review-zh/ro) for the native pass.

Code:
- Each language option carries its own `lang`, so endonyms are voiced
  and drawn in their language (WCAG 3.1.2; Chinese vs Japanese glyphs).
- resolveLocale ignores -u-/-x- subtags; the docs/07 table states that
  an explicit script wins and other zh regions get zh-CN.
- The listings' LANGUAGES line is built from LOCALES, and format tests
  derive their locale lists, so a new locale cannot slip past them.
- screenshots.mjs back under 300 lines: one job list for --shoot.
- Unneeded casts removed from dictionaries.test.ts; docs/11 describes
  the popup shots and what the sweep cannot cover.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +07:00
poli0981andClaude Opus 5.5 c667a0b4c9 chore(i18n): store listings, translation form and harness for zh-CN and ro
- store/listing.zh_CN.md and store/listing.ro.md (best-effort, marked
  TODO(review-zh) / TODO(review-ro)); every listing and the README now
  name all five languages.
- The translation issue form offers 简体中文 and Română; CONTRIBUTING
  explains the plural forms and the comma-below rule, and points at
  docs/07 §6.
- scripts/screenshots.mjs photographs every locale, and the popup per
  theme and language.
- tests/unit/i18n/touch-points.test.ts holds the files that cannot import
  LOCALES (harness, check-manifest, the form, the listings) to the list;
  the cedilla scan covers the Romanian listing too.
- Comments that said "three locales" or "VI/JA" now say what they mean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +07:00
poli0981andClaude Opus 5.5 49ce0bf868 feat(i18n): Romanian (ro)
- ro.ts, ro-notices.ts and ro-import.ts, written from Chrome's own ro
  terminology (marcaj, Bara de marcaje, dosar) in the polite plural, and
  marked TODO(review-ro) until a native pass (docs/07 §4).
- The first locale with three plural forms: every plural key carries
  one / few / other ("1 marcaj", "5 marcaje", "20 de marcaje"); count-less
  labels repeat the bare noun (docs/07 §5).
- Tests: comma-below ș ț only (a cedilla anywhere in the Romanian files
  fails, comments included), "de" only in `other`, selectPluralForm at
  the CLDR boundaries (0, 1, 2, 19, 20, 101, 120), tPlural end to end,
  and ro-RO collation for Sort A→Z.
- _locales/ro/messages.json; check-manifest requires it.
- Română joins every dictionary's endonym list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +07:00
poli0981andClaude Opus 5.5 254409dd3b feat(i18n): Simplified Chinese (zh-CN)
- zh-CN.ts, zh-CN-notices.ts and zh-CN-import.ts, written from Chrome's
  own zh-CN terminology (书签, 书签栏, 文件夹, 导入, 导出) and marked
  TODO(review-zh) until a native pass (docs/07 §4).
- _locales/zh_CN/messages.json; check-manifest requires it.
- resolveLocale maps zh, zh-CN, zh-SG and zh-Hans* to zh-CN. zh-TW,
  zh-HK, zh-MO and zh-Hant* get English, matching Chrome's own manifest
  fallback (docs/07 §1-2).
- <html lang="zh-CN"> makes Chrome draw Simplified glyphs rather than
  Japanese ones; Sort A→Z collates by pinyin.
- 简体中文 joins every dictionary's endonym list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +07:00
poli0981andClaude Opus 5.5 a95663a1f9 refactor(i18n): one LOCALES list and a third plural form
Groundwork for zh-CN and ro, with no new language yet (docs/07 §2, §5):

- resolve-locale.ts exports LOCALES; Locale is derived from it. dicts,
  TAGS, the storage allow-list and the Settings choices all follow it, the
  first two as Record<Locale, ...> so a missing table is a compile error.
- Dict is Localized<typeof dict>: plural branches may carry `few`.
  selectPluralForm keeps `few`; requiredPluralForms says which forms a
  locale's own Intl.PluralRules need.
- dictionaries.test.ts checks plural shape per locale, guards against
  locales that need zero/two/many, holds the endonyms equal, and pins
  the Dict type with @ts-expect-error cases.
- manifest.test.ts maps locales to _locales directories, rejects strays
  and caps appDesc at 132 characters; options, links and storage tests
  iterate LOCALES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +07:00
poli0981andClaude Opus 5.5 71d969e673 docs: record v1.1.0 as live; specify zh-CN and ro for v1.2.0
v1.1.0 cleared CWS review (listing shows 1.1.0, 6 users, observed
2026-11-06). The dashboard's install figures make Simplified Chinese and
Romanian the next minor, so the spec says the new thing before the code:

- 07: one LOCALES list, the zh-CN/ro resolution table (Traditional
  Chinese falls back to English, matching Chrome's manifest fallback),
  a third plural form for Romanian, tone and glossary per language,
  the best-effort review policy, and a new §6 "Adding a locale".
- 12 §4: a new UI language is a minor; translation fixes stay patches.
- 15: v1.2 is languages; the old v1.2 items move to v1.3.
- 00, 02, 03, 06, 08, 11, 13, 14 and CLAUDE.md follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:31:50 +07:00
poli0981andClaude Opus 5.5 b73803a718 docs: record v1.1.0 as released on GitHub, and the moved tag
- docs/15: Phase 7 done (#26–#29); a "v1.1.0 released" row with the signed
  tag on 9040f84, the checksum-verified zip and its manifest diff against
  1.0.1 (version, Chrome floor, CSP — nothing else); a pending "submitted"
  row; a decision-log row on why the tag moved.
- docs/00: the header says released, not in preparation; §10 item 12 lists
  what is still human-only for the store; doc suite 1.9.
- docs/13 §7: the one case where re-pointing a tag is right — a run that
  failed before any Release existed.
- CLAUDE.md: phases 0–7 complete; the Phase 7 exit as it stands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 04:22:22 +07:00
poli0981andClaude Opus 5.5 9040f84fe2 ci(release): stage the release files outside the hidden .output directory
The first tag run of the split release workflow (v1.1.0) failed in "Gate +
package": actions/upload-artifact skips hidden paths by default, `.output`
is one, so `.output/*-chrome.zip` and `.output/SHA256SUMS.txt` matched
nothing and `if-no-files-found: error` stopped the job. The publish job was
skipped, so no Release or asset was created.

The build job now copies both files into a plain `dist/` and uploads that.
The artifact layout the publish and store jobs download is unchanged, and
`include-hidden-files` stays off, so nothing else under `.output` can be
swept into a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 04:13:17 +07:00
poli0981andClaude Opus 5.5 70f535eeba fix(review): focus after a delete, the webkit WebRTC alias, one new folder, a sturdier harness
A second adversarial review, of the review-fix commits themselves, found
six problems. All are fixed here.

- Focus after a delete: a delete from the duplicate panel, or from the trash
  button of a row that did not have focus, left keyboard focus on <body>.
  The dialog cannot hand focus back to a button that went with what it
  deleted. `confirmDelete` now says where the delete was asked for: the
  tree gets focus back, and the panel moves it to the next copy's button,
  else to its close button. Checking for <body> was not enough: after a
  dialog closes, focus sits on its button until the browser's next
  rendering update, so a control in a closed dialog, or a detached one,
  now counts as lost too. Confirmed in the harness for all three paths.
- Import step 04: confirming the safety backup removed both of its buttons
  and dropped focus. A phase change now hands focus back to the heading.
- WebRTC: both gates matched `\bRTCPeerConnection\b`, which no word
  boundary lets match `webkitRTCPeerConnection`, an alias Chrome still
  ships. Prefixed aliases now count. The evasion comment in guard.mjs no
  longer claims to cover every way of hiding a member name.
- New folder: Chrome fires onCreated before create() resolves, so the live
  event could insert the folder first and newFolder then inserted a second
  row with the same id. It now inserts only when the folder is not already
  there, with a test that loses the race on purpose.
- Screenshot harness: `wxt build` empties .output first, and re-listing it
  threw inside the request handler, which ended the process. It now answers
  404 or 503 and recovers once the build is back.
- The duplicate summary uses one wrapper key instead of two fragments glued
  together in markup (docs/07 §2); Japanese gets its own separator again.
- Docs: the popup's tabId and `tabs.getCurrent` (docs/02 §6, 08 §2), the
  new-folder race (03 §3), focus after deletes and import phases (06 §5).
  SonarCloud's scan job now also receives the generated .wxt/, so
  tsconfig.json's `extends` and the `@/` alias resolve (12 §2.5).
- Tests for edit/tree-keys.ts, which had none, and for the focus helpers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 04:03:56 +07:00
poli0981andClaude Opus 5.5 7f306d1271 fix(scripts): serve the harness from a file index, and a linear CSV number test
SonarCloud's quality gate failed PR #27 on two findings in new code.

- S2083 (blocker): the screenshot harness built the file path from the
  request and then checked it stayed inside the build. The check held, but
  taint analysis cannot see a prefix test, so the harness now lists the
  build once and serves only files from that index; a request can name a
  file only by looking it up. It re-lists once on a miss, so a rebuild
  while it runs still works. Probed: valid files 200; `..`, `%2e%2e`,
  `%2F` and `%5C` traversals 404; a malformed escape 400.
- S8786: `^\s*\d*\s*$` in the CSV sanitizer let two `\s*` compete for the
  same blanks. `^\d*$` on the trimmed value means the same and is linear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 cd8fdcebcc docs: sync for the review fixes; regenerate the screenshots
- docs/03 §3: one bulk command at a time, focus that stays on a rendered
  row, the search that remembers closed folders, the new-folder path.
- docs/05 §9: the 500-row window around the focus replaces the growing
  prefix; measured numbers in place of the old "not done".
- docs/06: rename focus, the pinned failure toast, step-heading focus and
  the import's live region, dialog naming, the new component names.
- docs/02 layout, docs/07 plurals (eighteen since v1.1.0), docs/08 §3 CSP
  with default-src 'none' and the wider bundle gate, docs/09 §7 typed
  diagnostics, docs/12 the Sonar job split and the ops build job's plain
  `npm ci`, docs/15 decision rows and the review's backlog.
- README and PRIVACY say what the CSP refuses instead of "any request".
- capture/: the README set regenerated by `screenshots.mjs --shoot` from
  neutral sample data, lowercase names as the harness writes them; the
  1.0.0 shots are gone. store/screenshots/: 1280×800 dark candidates.
- CHANGELOG [1.1.0] Fixed; CLAUDE.md size figures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 47aefc1845 fix(security): typed diagnostics, wider gates, default-src 'none', Sonar job split
Findings 5–9 of the security review of 1.1.0. None broke the zero-network
or permission promises of the shipped build; each made a claim stronger
than the code behind it.

- Diagnostics: every DiagEvent string field is now a union of fixed values
  (import phases, FileFormat, the ErrorKeys describeError returns, the two
  edit actions, the three storage issues), and error names pass an
  allowlist, logged as 'other' otherwise. `@ts-expect-error` cases keep a
  title from compiling instead of trusting review.
- guard.mjs: optional-chained computed access on globals, `Reflect`, and
  member names assembled from strings or templates (`el['inner' + 'HTML']`)
  all got past it.
- check-manifest.mjs: the bundle is scanned for the same identifiers as the
  source, as bare words — `fetch.call`, aliases, RTCPeerConnection and
  importScripts shipped unseen — and every src/href in the built pages must
  exist inside the package.
- CSP: `default-src 'none'` closes everything unlisted. Every directive the
  pages use is listed, so nothing changes for them; the harness pages load
  with no violation.
- screenshots.mjs: listens on 127.0.0.1 only, checks `OUT + sep` rather than
  a bare prefix, decodes paths safely, and runs Chrome asynchronously — the
  synchronous exec blocked the very server Chrome was waiting on, so
  `--shoot` hung forever.
- SonarCloud: coverage runs in a job with no secret; the scan job installs
  nothing and receives lcov as an artifact. A job's secrets are readable by
  every step on its runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 04c04d4410 fix(ui): act on the 1.1.0 UI review — focus, bulk lock, windowed tree, toasts
The adversarial review of the 1.1.0 UI found fifteen problems that the unit
tests and svelte-check could not see; all but one were reproduced in the
built harness first.

- Edit tree: F2 and New folder now focus and select the rename box (Svelte's
  autofocus only acts when nothing else has focus, which was never the case
  here), and Enter or Esc returns focus to the tree. A folder created during
  a search is inserted at once and every folder above it is opened as the
  user's own, so clearing the search no longer hides it and locks the keys.
  A focused row that leaves the screen hands focus to its nearest visible
  folder (edit/focus-repair.ts), and a rename whose row is hidden is
  dropped. A folder closed during a search stays closed until the text
  changes. Right arrow on an empty folder does nothing.
- One bulk command at a time: sort and keep-first now lock every other
  write in the session itself, not just the toolbar, and only the command
  that set `busy` clears it.
- #edit mounts a 500-row window around the focus (edit/row-window.ts) with
  "Show earlier" / "Show more": End on 20k rows mounted all of them.
- Failures get a pinned toast slot; later toasts still show and announce.
- Import: the preview's new/dup badges show again (`$state.raw` — a deep
  proxy broke the WeakMap lookups, already broken in 1.0.x), each step's
  heading takes focus, and one live region announces the outcome.
- Dialogs name their close button "Dismiss" and are described by their
  body, so the counts are read with the title.
- 375 px: the edit toolbar wraps; titles keep their room before the domain.
- Wording: untitled items named by their address in dialogs; plurals for
  show-more and the duplicate summary; a diagnostics copy failure says so;
  the Move dialog's filter is labelled as a folder filter; the Japanese
  notices spell ブラウザ and フォルダ like the rest of the dictionary.
- The logo pulse stops after two cycles (WCAG 2.2.2), and the popup
  switches only the Manager tab it brings forward.
- Back under the size limits: EditSession is three layers (edit-view,
  edit-commands, edit-session); RowActions, RenameInput, ImportProgress,
  ImportAnnouncer and StatusBar are their own components; the tree's key
  handling lives in edit/tree-keys.ts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 9dd6dc317f fix(import): a Replace backup that matches what it deletes, the right roots, and depth Chrome can keep
From the v1.1.0 adversarial review (data integrity):

- Replace re-reads the tree once the backup is on disk. If anything changed
  while the save dialog was open (or while the user checked Downloads on the
  fallback path), the picker path writes the fresh snapshot to the same file
  and checks again (up to 3 times); the fallback path stops with BACKUP_STALE.
  Before, a bookmark added meanwhile inside an existing folder was deleted with
  no copy anywhere.
- Roots resolve by folderType among this device's roots; a signed-in account's
  own roots (Chrome 134+, syncing) are never emptied or written. Replace backs
  up and clears exactly the three destinations.
- An empty Mobile root, which desktop Chrome leaves out of getTree, is found
  with bookmarks.get('3'), so Mobile content stops landing under Other. The
  fake now hides it the same way.
- Plans report writeDepth; past MAX_WRITE_DEPTH (90) the import is refused with
  TOO_DEEP before any backup — Chrome re-reads its own bookmarks file with a
  200-level JSON nesting limit, two levels per folder.
- The suggested backup name carries seconds, and a picked file that never
  received a backup is removed again.
- Edit tab: a stale "created" event for an id the view already holds is
  dropped, and the duplicate finder never pairs a node with itself — together
  they made "Keep first" delete the only copy. Sort re-plans from the folder's
  children at confirm time.
- Netscape: an unescaped <h3> inside a bookmark title no longer turns the
  bookmark into an empty folder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 434c05b85f fix(review): credit everything the build compiles in, close three sanitizer leaks, sync the spec
From the v1.1.0 adversarial review (security) and the docs pass:

- clsx (MIT) ships too — the Svelte runtime imports it — and wxt's browser
  module as well as @wxt-dev/browser. All four are now credited in About,
  PRIVACY, README and both notice files, and wxt.config.ts fails the build when
  code from any uncredited package would ship; tests/unit/third-party.test.ts
  keeps the notices in step with that list.
- Sanitizer, CSV: default-deny. A title with an unquoted comma — the row that
  makes the extension report CSV_ROW_MISMATCH — shifted a file: path and free
  text into columns no rule rewrote, and the host-only check passed them.
- Sanitizer, HTML: unknown attributes (Firefox POST_DATA, any DATA-*) are
  rewritten; only dates, root markers and the charset line are kept.
- Sanitizer: a value-level leak check over CSV fields, attribute values and
  JSON strings, and a refusal that prints counts only — it used to print the
  leaked words and ask for them in a public issue.
- BM_ENV_ERROR_CODES joins the per-locale message check, with the four fixed
  keys describeError maps; the popup no longer logs crashes nothing can read.
- docs 00/02/03/05/06/07/08/09/11/13 describe v1.1.0 (diagnostics moved to
  09 §7; 13 §3 points at store/listing.* instead of a drifting copy); tokens
  and gen-icons comments corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 9ae5f4aa67 chore(release): 1.1.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 de744f2d54 docs(changelog): the rest of 1.1.0 — sort, reorder, the redesign, diagnostics, the write lock
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 fee423b453 docs(legal): clarify all four documents, disclose what is compiled in, and give each purpose its own address
No LEGAL_VERSION bump: every change clarifies, corrects or removes an
obligation (docs/14 §3.1, new "contact details → No" row and a table of what
version 1 means).

- All four documents: version/date header and a copyright line.
- EULA clause 3 becomes a non-binding note — GPL-3.0 §10 forbids adding
  restrictions; clause 6 gives legal@ and dmca@.
- DISCLAIMER describes Replace as it now behaves, and adds the name/fork
  notice with takedown@ and dmca@.
- PRIVACY describes the in-memory diagnostics log, the Chrome Web Store's own
  role, and that opening a bookmark is the browser's request, not ours;
  contact privacy@.
- THIRD_PARTY_NOTICES lists the Svelte runtime and WXT's browser shim (MIT),
  which the build always compiled in; the notices now ship as
  THIRD_PARTY_NOTICES.txt and check:manifest requires the file.
- security@ (SECURITY.md), code@ (CoC, issue chooser), README Contact table;
  contact@ retired. links.test.ts now scans all of src/ for an address.
- README: new formats and features, Sonar/CWS badges, verify:full, the
  screenshot harness. Store listings EN/VI/JA follow.
- docs/15 decision rows, next direction and backlog; CLAUDE.md Phase 7, the
  TS 7 / TS 6 alias rule and --ignore-scripts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 500a75b5e7 fix(i18n): say what is compiled in, localize the save dialog, and tidy VI/JA wording
- About no longer claims "no runtime libraries at all": the build compiles in
  the Svelte runtime and WXT's one-line browser shim, both MIT (sC2.1).
- The backup save dialog's file-type label was hardcoded English.
- VI: a browser tab is "tab", an in-app section is "thẻ", consistently. JA:
  the katakana middle dot instead of "·".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 db4b720936 feat(diagnostics): a local log to copy into bug reports, and one writer across tabs
- browser/diagnostics.ts: an in-memory ring buffer of 200 allowlisted events —
  import phases, failure codes (logged where every failure is described, by
  code, never by detail text), bulk edits, storage read failures, uncaught
  errors by name only. Page-relative times, no storage, no network. About →
  "Copy diagnostics" copies it with the version, locale, theme and Chrome major.
- browser/write-lock.ts: Web Locks, ifAvailable — a second Manager tab trying
  to import, sort or delete duplicates while another writes is refused at once
  with WRITE_LOCKED, before anything is touched. The import takes the lock after
  opening the save picker, so the click's activation still holds.
- The settings store reads the UI language through browser/ (uM15); progress
  reports the first create, so a slow start no longer looks like a hang (uL9).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 0577215fd0 feat(ui): a technical redesign of every surface, and the import report says what and where
Every surface moves to the v1.1 design system: a header with the brand mark,
a route crumb and icon tabs with a sliding indicator; an IDE-style status bar
(local only · bookmarks, storage · version · licence · Settings · About);
numbered mono step labels on #import and #export; readout stats; mode and
format cards; marching-ants drop zone; striped progress; slide-in toasts; the
popup as launcher tiles over a live readout. Emoji glyphs are gone in favour of
the self-drawn icon set; all motion sits behind prefers-reduced-motion.

Behaviour fixed on the way:
- The Start button counts what will really be imported (a preview plan), and
  Replace asks first, with the exact numbers it will delete and write (T4).
- The report counts bookmarks and folders separately, what was skipped and
  reused, and where it all went — after a cancel or failure too (uM10, uM11).
- The backup hint names the file as the user saved it, not as suggested.
- Failure toasts stay until dismissed; export says "download started" and
  keeps a failure's technical detail on screen.
- The popup routes an open Manager over a BroadcastChannel (refused while an
  import writes), and no longer counts the three permanent roots as folders.
- Read-only previews and the export picker drop the role="tree" they never
  implemented; both render 500 children at a time; "Everything" shows
  indeterminate on a partial selection; the drop zone stops flickering.
- Per-route document titles; the status bar stays at the bottom of the window.
- The Move-to dialog no longer renders every folder while closed.

The Import tab's strings move to <lang>-import.ts so each locale file stays
under the size limit. scripts/screenshots.mjs serves the built extension with
a fake chrome and the production CSP, for visual QA and store screenshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 5bd6f2ebc8 feat(edit): sort A→Z, drag to reorder, batched live sync, and a tab inside the size rule
EditTab's state and commands move to stores/edit-session.svelte.ts (an
injectable bookmarks API, tested against the in-memory fake); the component is
markup and wiring, 481 → 290 lines. New:

- Sort A→Z per folder (edit/sort.ts): folders first, natural, case- and
  accent-insensitive, stable; planned first so the confirmation states how many
  items move; moves only what is out of place, with indices valid for
  chrome.bookmarks.move; a refusal part-way says how far it got and re-reads.
- Drag to reorder: before/after/into zones (edit/move-target.ts planDrop, which
  converts between Chrome's pre-removal indices and onMoved's post-removal
  ones); dragend clears a cancelled drag.
- Live sync batched per frame, re-read once on bursts and after Chrome's own
  import or a wholesale reorder; handlers isolated so one exception cannot stop
  the tree following the browser. Duplicates are scanned only while shown.
- Bounded rendering: rows mount 500 at a time with "Show more", growing to keep
  the focused row in the DOM; explicit aria-setsize/posinset.
- Move-to is a real modal (shared Modal: focus in, Esc, focus returned, no
  cancel-after-confirm) with a filter; the menu key / Shift+F10 opens it, Ctrl+C
  copies a link, row buttons leave the tab order; loading state, focus follows a
  delete, a new folder clears a search that would hide it, resyncs keep
  expansion and focus, renames are trimmed and Esc never commits.
- Duplicate rows show the folder each copy lives in.

Also the v1.1 design foundation these use: new tokens (sunken/subtle surfaces,
--border-strong ≥ 3:1, mono stack, motion/shadow/z tokens, color-scheme,
accent-color, faint grid), a self-drawn SVG icon set with motion, and
tests/unit/styles/motion.test.ts, which fails any animation or moving
transition outside prefers-reduced-motion: no-preference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 7493aceefb fix(core): a bare ? or # no longer defeats dedupe, and the export picker stops going quadratic
normalizeUrl trimmed the last character of a root URL to drop its slash, but
`x/?` and `x/#` serialize with the delimiter last, so the `?` was cut instead
and `x/?` never matched `x/`. Empty query and fragment are now removed first.
The default-port code was dead: the URL parser already drops default ports.

The export folder picker looked up each row's check state by walking the tree
from the roots - O(n) per visible row. checkStates builds the whole map in one
pass, once per selection change.

The seeded round-trip now asserts no warnings per tree as docs/11 §3 says.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 bb2b175551 feat(import): Chrome and Firefox bookmark files, a Merge that merges, restores that do not nest
Import Chrome's profile `Bookmarks` file and Firefox's JSON backup directly.
Each reader is held to a parity rule against its browser's own HTML exporter,
tested on Chromium/Firefox-faithful fixture pairs. One entry point,
parseBookmarkFile, sniffs by content (JSON first, parsed exactly once, routed
by shape); the picker loses its extension filter, which hid the extensionless
`Bookmarks` file. Firefox's internal root names are localized by the caller.

Merge finally reuses the folders a user already has, level by level, appending
new items (core/merge.ts) - 1.0.x planned it exactly like Replace. Root folders
are unwrapped by marker (core/route.ts), so restoring a backup no longer nests
Other and Mobile one level deeper each time, 1.0.x backups included. Replace
never dedupes, plans before the backup is taken, and refuses a backup the
import could not read back (BACKUP_EXCEEDS_LIMITS) before anything is written,
downloaded or deleted. The save dialog's late rejection is marked handled.

Also found: the seeded round-trip suite had compared 200 empty trees since
Phase 1 (xorshift32 seeded with 1-200 draws near zero first). makeRng now
scrambles the seed and every seeded suite checks its corpus is non-trivial.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 e86a1d77b3 fix(import): read every entry a file holds, and skip what Chrome would reject
Several shapes made v1.0.x import a smaller tree than the file held, with no
warning at all:

- a loose bookmark before the wrapper list (no </DT>) swallowed the whole
  list; with an explicit </DT> the bookmark "consumed" the next list;
- an unescaped <b> in one title re-opened around every later entry
  (dt > b > a, dl > b > dt) and hid them from a direct-children walk;
- a root list wrapped in <div>/<table> was invisible;
- PERSONAL_TOOLBAR_FOLDER="false" made a folder the bar.

Every reader now classifies addresses before anything is written (core/
href.ts): blank -> MISSING_URL, unparseable -> INVALID_URL (chrome.bookmarks.
create rejects those mid-write, after a Replace has already cleared the
tree), Firefox place: -> PLACE_QUERIES_SKIPPED in browser-written formats
(kept in BM JSON and CSV, our restore formats). A DT that still yields
nothing is counted as UNREADABLE_ENTRIES instead of vanishing.

Also:
- empty titles stay empty (the URL fallback ruined favicon-only bars);
- the HTML node cap is counted on the raw text before DOMParser builds a
  DOM; the depth cap no longer rejects an empty list one level past it;
- root markers for Other and Mobile (UNFILED_/MOBILE_BOOKMARKS_FOLDER in
  HTML, "root" in BM JSON, version stays 1), and a 1.0.x full-tree backup
  is recognised by shape and marked on read;
- BM JSON dates go through the shared normalizer; url "" (which Chrome
  makes a folder) is skipped;
- CSV: an unclosed quote is CSV_UNCLOSED_QUOTE with its line instead of one
  cell eating the file; formula cells get one reversible guard quote; sep=
  lines and padding rows are skipped; folder lookup is a Map, not a scan;
- Markdown escapes every CommonMark-active character and collapses line
  breaks in titles (raw HTML used to pass through);
- shared WarningBag/NodeBudget/title rule, an iterative walkTree, an
  isBookmark type guard, a CSV dialect module, chromeTimeToSeconds and
  microsToSeconds for the JSON formats that follow;
- locales split warnings/errors into <lang>-notices.ts to stay under the
  size limit; every warning and error code must have a message (test).

Four new fixtures, golden serializer suites for HTML and BM JSON (docs/11
named one; neither existed), and docs/02, 04, 05, 07, 09, 11, 15 updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 03:22:56 +07:00
poli0981andClaude Opus 5.5 83decd92cc fix(scripts): check-manifest takes no path argument
SonarCloud's second pass still flagged S8707: the directory to check came
from argv and flowed into file reads, and a startsWith() allowlist did not
count as sanitizing it. The CLI now only ever checks the repository's own
.output/chrome-mv3; the logic is an exported checkExtension(dir) (typed by
check-manifest.d.mts) that the tests call directly, so no command-line path
reaches a file read at all.

Path resolution moved inside the entry point: under Vitest's jsdom
environment import.meta.url is not a file: URL, so resolving it at module
load threw on import. The two Node-script suites now run in the node
environment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5.5 1bd6aca93c fix(security): clear SonarCloud's findings on the new gates, and close remote stylesheets
The first CI-based SonarCloud scan failed the quality gate on its new-code
security rating, with two findings in check-manifest.mjs:
- S8707: it read whatever directory the CLI argument named. It now accepts
  only paths inside this repository or the OS temp directory (where its
  tests build fake extensions), and says so when it refuses.
- S8689: its success line echoed values read from the file. It now prints
  constants — the manifest has just been proven equal to them.

And four S8786 regexes in guard.mjs plus one in the sanitizer, where a \s*
beside an optional quote beside another \s* could backtrack: each is now
written so no two quantifiers compete for the same characters, and the
markup rule is two linear steps (find the tag, then look inside it). The
sanitizer's JSON tokenizer no longer reassigns its loop counter (S2310).

While here: with no default-src, style-src was open, so a remote stylesheet
could still load. The CSP now adds `style-src 'self' 'unsafe-inline'`
(Svelte sets style attributes); check-manifest pins the new string.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5.5 0671bb3c33 fix(scripts): the sanitizer stops leaking Chrome profile titles, and every script is checked
sanitize-bookmarks.mjs accepted any JSON object and rewrote only "url" and
"title". Chrome's profile Bookmarks file keeps titles under "name" (plus
meta_info and a base64 sync_metadata blob), so it came out with every title
intact, passed the host-only leak check, and was written as "sanitized" —
the exact file a reporter whose import failed would attach.

- JSON dialects are recognised by shape (BookmarkMagic, Chrome profile,
  Firefox backup); any other JSON is refused. Rewriting is default-deny: a
  small tokenizer tracks the key of every string value and replaces all of
  them except structural keys (types, ids, timestamps, root GUIDs), by span,
  so layout and key order stay byte-identical.
- The backstop now reads the output's TEXT: for HTML it strips markup and
  refuses on any word that is not a placeholder — independent of the
  rewriting rules, unlike the old host-only check whose test shared its
  blind spots. <DD class=…> notes, file: ICON_URIs and <H1>/<TITLE>
  owner names are rewritten.
- Attribute values decode in one pass (CodeQL js/double-escaping), <DD>
  bodies are found in linear time (Sonar S8786), the input is never
  overwritten, size is checked before reading, and bytes are bytes.
- The 627-line file is split into scripts/sanitize/ modules; the
  user-facing entry stays plain .mjs for reporters on any Node.

gen-fixture.mjs validates its flags (whole numbers >= 1, values required, no
unknown flags) and its loop visibly advances (Sonar S2189 blocker).
gen-icons.mjs says what is true: it is the icons' source of truth.

Every script now carries // @ts-check and tsconfig.scripts.json runs them
through the TS 7 tsc in `npm run check`; docs/10's size rule names .mjs.
Regenerated icons are byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5.5 94b74f6ac4 fix(security): enforce zero-network in the browser, and gates that cannot be talked past
The "no network access" claim rested on one grep gate. An audit ran its
exact patterns against 28 bypasses and every one got through — an alias
(`const go = fetch`), computed global access, a call split over two lines,
`innerHTML +=`, `{ @html }`, remote url() in CSS — and a checkout path with
a space or diacritic made it scan nothing and print "clean". Now:

1. The production manifest declares an extension-page CSP with
   `connect-src 'none'` (plus closed img/font/media/frame/form sources), so
   Chrome itself refuses every fetch, XHR, WebSocket, EventSource and beacon.
   No default-src, so Svelte styles are untouched; dev builds omit it so
   the HMR websocket works. docs/08 used to say "never add a CSP" because
   MV3 forbids loosening — tightening was always allowed.
2. check:manifest scans every shipped .js for network APIs (dependency code
   included), pins the exact CSP and the Chrome floor, checks that every
   file the manifest and pages reference exists, resolves paths from the
   script instead of the cwd, and sets exitCode instead of exit().
   Vite's modulepreload polyfill — the one network call in the bundle — is
   disabled; every Chrome at the floor supports modulepreload natively.
3. guard.mjs matches whole files (so \s* spans newlines), bans the API
   identifiers outright, bans computed access on globals, scans .html and
   .css, has no test-file exemption, uses fileURLToPath, and fails when it
   scanned nothing. docs/08 §3 points at the file instead of restating it;
   the restated copy had already drifted.

Both scripts finally have tests (48 + 18 cases, every audited bypass
included). One src comment named the API in prose and is reworded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5.5 d9e5815dfe ci: SonarCloud CI analysis with coverage, and a release that never installs while holding a write token
SonarCloud ran Automatic Analysis: no coverage, and a scan of the repo rather
than of what CI builds. sonarcloud.yml replaces it — full-history checkout,
the coverage run, then the scan with the package version as the new-code
baseline. It is its own workflow so a Sonar outage or gate opinion can never
turn CI red, the scan action is pinned to a commit because it holds
SONAR_TOKEN, the token reaches only the two steps that use it, and runs
without secrets (Dependabot, forks) skip with a notice instead of failing.

Coverage now measures every src/**/*.ts module and emits lcov, but the CI
gate is unchanged: a glob threshold applies the docs/11 §1 numbers to
src/lib/core/** only (verified to still fail a run below them).

Hardening, from SonarCloud's findings and the scripts/config audit:
- npm ci --ignore-scripts everywhere, with `wxt prepare` run explicitly;
- checkouts drop persisted credentials;
- release.yml is split: gates and zip run with a read-only token; only a
  job that installs nothing and runs no repo code creates the Release; the
  store submit uses the local wxt binary, never `npx` with secrets in scope;
- reusables get named secrets instead of `inherit`. The announce job could
  never have worked: this repo stores RELEASES_WEBHOOK/REPO_WEBHOOK, the
  reusable reads DISCORD_*, and inherit passed neither;
- CI runs `npm audit --omit=dev`, which docs/09 already claimed it did;
- a non-required Windows smoke job (guard + unit tests).

serializeMarkdown's trailing-newline trim used /\n+$/, which backtracks
quadratically over a long newline run that is not at the end (S8786); it is
now a single backward scan, with a 20k-newline regression test.

docs/12 no longer copies the workflow YAML — the copies drifted three times,
and under docs-win a stale copy invites reverting a pinned action.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5.5 37c72636cb build(deps): take the dev toolchain to its newest week-old releases
Every dev dependency moves to the newest release that has been public for
at least 7 days, and that rule is now enforced rather than remembered:
.npmrc sets min-release-age=7 and Dependabot gets a 7-day cooldown on both
ecosystems. `npm ci` was verified to ignore the age rule for versions
already in the lockfile, so it only shapes what gets locked.

  vitest / coverage-v8  4.1.10 -> 5.0.5   (suite passed unchanged)
  @biomejs/biome        2.5.5  -> 2.6.2   (exact)
  svelte                5.56.8 -> 5.57.2
  vite-plugin-svelte    7.2.0  -> 7.3.1
  svelte-check          4.7.4  -> 4.7.7
  jsdom                 30.0.1 -> 30.1.3  (dom-environment canary first)
  knip                  6.29.0 -> 6.42.1
  wxt                   0.21.3 -> 0.21.4  (+ transitive vite 8.3.5)

npm audit: 13 (7 high) -> 3 low, all one deepmerge advisory with no fixed
release, inside vite-plugin-svelte's dev-time option merging; documented in
docs/09 §3.1. --omit=dev stays 0. This supersedes Dependabot #19-#25.

The six-entry overrides block is deleted: none of those packages is in the
tree any more (WXT 0.21 dropped web-ext-run, Vite 8 bundles with rolldown),
and a stale override would silently pin a package the day it came back.

WXT got the built-manifest diff the 2026-08-03 decision requires: identical
keys and values apart from the deliberate minimum_chrome_version, identical
file inventory. Biome 2.6 began formatting Markdown and YAML, so both are
excluded rather than letting a formatter reflow hand-written docs.
dependabot.yml now keeps WXT out of the routine group and ignores majors of
the TypeScript pair and @types/node.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5.5 85f9fb4d13 build: Node 26 LTS, TypeScript 7 alongside the TS 6 API, ES2025 at a Chrome 136 floor
Node 26 entered Active LTS on 2026-10-28 and Node 24 went to maintenance on
2026-10-20, so the toolchain moves with them: .nvmrc, engines and @types/node
all say 26.

TypeScript 7.0 is GA but still has no programmatic API, and svelte-check
peers `typescript ^5 || ^6`. So this uses Microsoft's documented
side-by-side aliases instead of choosing one:

  "@typescript/native": "npm:typescript@~7.0.2"           -> tsc (7.0.2)
  "typescript": "npm:@typescript/typescript6@~6.0.2"     -> the 6.0.3 API

`npm run check` therefore type-checks .svelte files with TS 6 (svelte-check)
and every .ts file with both. `tsc --version` is 7.0.2; `tsc6` is 6.0.3.

tsconfig targets ES2025 with lib ES2025, which is only honest if the oldest
Chrome allowed to install has every ES2025 built-in. That is Chrome 136
(RegExp.escape), so minimum_chrome_version goes 120 -> 136 and Vite's
build.target follows the same CHROME_FLOOR constant. manifest.test.ts pins
all three so they cannot drift apart. Users below 136 keep what they have
installed; they just stop receiving updates.

Built output: the manifest changes only minimum_chrome_version, the JS chunks
are byte-identical apart from a CSS hash, and the CSS loses one
-webkit-user-select prefix Chrome 136 no longer needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5.5 273560e475 docs: record that v1.0.1 is published
The listing has shown version 1.0.1 since it cleared review; the suite still
said "in review, not yet approved" in docs/00, docs/15 and CLAUDE.md, the
exact mirror of the week it spent claiming review after 1.0.0 was live.

Recorded only what was observed (2026-10-28: listing shows 1.0.1, 5 users).
The approval date and the 13 §1b step-10 clean-profile check of the
published build stay marked as unrecorded rather than inferred. CLAUDE.md's
EditTab figures were the v1.0.0 numbers; they are now the current ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5.5 49323d91df chore: check text files out with LF on every platform
A Windows clone with core.autocrlf=true checked every text file out with
CRLF, and Biome's formatter (which expects LF) then failed `npm run lint`
on all 114 files before a single line had been edited. The two scripts
with a `#!/usr/bin/env node` line were also unusable from WSL.

`eol=lf` fixes the checkout, not the repository: the index already held
LF everywhere (`git add --renormalize .` stages nothing else), and
tests/fixtures/** stays -text so the CRLF records the CSV fixtures exist
to exercise are untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:06:52 +07:00
poli0981andClaude Opus 5 3fc8fd1d5d docs: record that v1.0.1 is released and submitted — and only that
The owner tagged, released and uploaded v1.0.1 to the dashboard on 2026-08-03.
Recorded as **submitted, in review** — deliberately not as published.

That distinction is the whole reason Phase 6 existed. This suite spent a week
asserting "in review" after the listing had already gone public, and the
opposite error is the worse half of the same mistake: telling a future reader
that users have a fix they have not received yet. Users are on 1.0.0 until the
review clears.

docs/15's progress table gains two rows — released (signed tag, checksum-verified
zip, announce and store-publish both correctly skipped for want of their repo
variables) and submitted. docs/00 §10 gains item 11: what to write down when it
clears, and the pointer to §7 if it is rejected instead, because a rejection and
its resolution are the only memory this project would have of what reviewers
actually object to.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 21:25:38 +07:00
poli0981andClaude Opus 5 d09a118c3c docs(ci): record branch protection, and correct the check names it needs
Applying the §5 checklist item exposed two errors in it.

The required check is `Build + package / build`, not `Build + package`. A job
that calls a reusable workflow publishes its check as `<caller job> / <reusable
job>`, so requiring the caller's name alone matches nothing that will ever be
reported — every PR waits forever and `main` becomes permanently unmergeable.
The doc was confidently specific about this ("the job names — not the workflow
name") and confidently wrong, which is the worst combination.

"Require review" is set to zero approvals, deliberately. It is correct advice
for a team and a lockout for one maintainer, who cannot approve their own pull
request. Zero still forces every change through a PR and through the checks;
it only drops a second pair of eyes that does not exist. Admins are not
enforced, for the same reason: with a single maintainer, an escape hatch from
your own rules is what separates a safety net from a locked door.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:35:22 +07:00
poli0981andClaude Opus 5 4654086b5b fix(deps): declare @types/node, which CI proved was never really there
The first CI run on this branch failed `npm run check` with 18 errors —
"Cannot find name 'node:fs'" — including in `tests/unit/styles/contrast.test.ts`,
which this branch never touched. So it was not the new test: the package has
always used Node types without declaring them.

Two things hid it. WXT 0.20 supplied `@types/node` transitively and 0.21 does
not, and this worktree sits under the parent checkout, so TypeScript walked up
to `E:\bookmarkmagic\node_modules\@types\node` and resolved them anyway — even
after a correct `npm ci` in the worktree itself. A green local type-check in a
worktree is therefore weaker evidence than it looks, which is now written down
in CLAUDE.md next to the existing worktree gotcha.

Types only: erased at build, nothing ships, so hard rule 2 — zero *runtime*
dependencies — is untouched, and the built manifest and bundle are unchanged.
docs/01 §2 records it with the reason, since that table is the pinned-version
spec rather than a summary of it.

This is the failure the tag run would otherwise have hit, and the reason a red
CI is worth reading before merging rather than after tagging.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 302dc2e4dd chore(release): 1.0.1
Exactly the two files a patch touches — package.json's version and CHANGELOG.md,
section plus the link references at the bottom. wxt.config.ts declares no
version key, so it must not appear in this diff, and it does not; the built
manifest reads 1.0.1 and `npm run zip` emits bookmarkmagic-1.0.1-chrome.zip.

`npm run verify:full` green: lint, svelte-check + tsc, knip, the grep gate, 694
tests, core coverage 97.4%/92.1%, the build, and check:manifest against the
built artifact. The built manifest is byte-identical to the pre-phase baseline —
same permissions, same key set — across ten commits and a WXT major-slot bump.

The changelog is written for users rather than for the diff: what changed for
someone who already has this installed, and the fact that they need do nothing.

⚠️ Stops here, deliberately. The tag and the store upload are human steps:
  git tag -s v1.0.1 && git push origin v1.0.1
and then docs/13 §1b from step 5 — which begins with the manual QA pass,
including the 1.0.0 → 1.0.1 upgrade over an existing profile that nothing here
can perform.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 28f6befcd0 fix: close the eighteen findings the Phase 6 review confirmed
Six lenses over the branch, each finding independently attacked by a verifier
told to refute it. 31 filed, 18 survived, clustering into five real defects —
and the pattern held: every one is in work added earlier in this same branch.

**The sanitizer did not keep its promise (9 findings).** It is the single
privacy control in the intake flow, named as mandatory in SECURITY.md, README,
CONTRIBUTING, the privacy policy and the issue form — and it leaked in nine
distinct ways. Worst: `detectKind` fell back to 'csv' for anything it could not
identify, `sanitizeCsv` then matched no columns, and the input was emitted
verbatim with exit code 0. The users who run this tool are by definition the
ones whose file did not import, so a truncated or hand-excerpted file is the
TYPICAL input — and `tests/fixtures/malformed/no-doctype.html`, already in the
repo, reproduced it. The test could not catch any of this: it returned early
whenever the original failed to parse, so it passed vacuously on precisely the
dangerous inputs.

Nine holes found in one pass is not a signal to patch nine holes. The rules are
regexes over untrusted markup, so "we thought of every shape" is not a claim
anyone can make honestly. So the tool now fails safe:

- unidentified input is REFUSED, matching core detectFormat rather than being
  weaker than the parser it fronts;
- the output is checked before it is written — any host that is not one of our
  own `*.example` aliases means a rule missed something, and the file is refused
  with the leaked host named. A rule this misses now degrades into an annoying
  refusal instead of a published browsing history.

The individual holes are fixed too: single-quoted and bare attribute values were
never matched (a straight leak); `spansFrom` located capture groups by searching
the match text, landing on the wrong copy — replaced with the `d` flag's exact
offsets; overlapping spans spliced already-rewritten text using offsets measured
against the original; `[^<]*` made a title containing a raw `<` fail to match
entirely; `<DD>` stopped at the first newline, publishing the rest of a wrapped
note; and replaceSpans rebuilt the whole string per span, O(spans x file).

**The import report pointed users at a backup that was never written.** The
guard was "mode is replace and this is not a BmBackupError", but runImport
resolves the roots BEFORE proving the backup — so NO_WRITABLE_ROOTS, added in
this same branch, reaches the catch with nothing on disk. Now keyed on the
onClearing callback, which is the only signal that proveBackup actually
returned.

**Cancelling a Replace after the clear read as a harmless no-op.** The tree is
gone and only `created` of it rebuilt; "N items created" alone, on a browser
that is now nearly empty, is the wrong story. It now says so and names the
backup.

**Collapsing a folder while a search was active re-opened it instantly.** The
$effect read and wrote the same two `$state` sets, making it its own dependency:
every write re-invalidated it and it re-merged an unchanged `search.expand`.
Reproduced against the real Svelte runtime — `$effect` is stripped under this
repo's vitest config, so no unit test could have seen it. Fixed with `untrack`,
which also removes the self-retrigger loop.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 dc0672ea28 fix(ci): remove a keyword GitHub rejects on reusable-workflow callers
`continue-on-error` is not allowed on a job that calls a reusable workflow.
GitHub answers with "Property continue-on-error is not allowed" and refuses the
**whole file** — a startup_failure with zero jobs and no log, not one failed
job. Confirmed against two GitHub community discussions, one of which is an
open, unanswered feature request asking for the capability.

release.yml's announce job has carried that keyword since 5f4c6e7. That commit
landed *after* the v1.0.0 tag object and no tag has been pushed since, so the
first v1.0.1 tag would have been its first execution — and the release would
have died before running a single job, in exactly the silent shape this project
already hit once with the `contents: write` grant (2c8fba9). The previous commit
in this branch then copied the same mistake into notify-ci-failure.yml.

Both are now gated with `if:` on a repo variable instead. A variable and not a
secret because secrets cannot be referenced in a job-level `if:`, and unset
means skipped — so the release stays green and CI stays quiet until the owner
opts in by setting DISCORD_ANNOUNCE / DISCORD_CI_NOTIFY alongside the webhooks.
Same idiom as the CWS_AUTOPUBLISH gate already in release.yml.

docs/12's samples and its §5 checklist updated in the same commit; docs are
binding here, and leaving the invalid keyword in the spec would have had the
next reader put it straight back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 f3d4dfb023 chore(deps): take the two open Dependabot bumps, with the manifest proved unchanged
Applied directly rather than merged: both branches predate this phase and would
have reverted `verify:full`.

**wxt ^0.20.27 → ^0.21.3.** A 0.x minor is semver's breaking slot, and WXT is
what emits the shipped manifest — so the acceptance test was a byte diff of the
built artifact, not a green suite. Manifest, file inventory (content hashes
stripped) and bundle size all came out identical, permissions unchanged, zip
name unchanged. It *did* break two things, both dev-only: `wxt/testing` split
into `wxt/testing/fake-browser` and `wxt/testing/vitest-plugin`, and
`tabs.create` is now typed as returning void.

That split is the point of the ritual. `npm run test` passed before the bump and
the *config load* failed after it — while `tests/unit/manifest.test.ts`, the
test that looks like it guards the manifest, would have stayed green whatever
WXT emitted, because it reads wxt.config.ts and a WXT upgrade cannot change that
file. The check-manifest key-set gate added in the previous commit is what makes
the next one CI's problem rather than a manual comparison someone has to
remember to do.

**jsdom ^29.1.1 → ^30.0.1.** Canary first: tests/unit/dom-environment.test.ts
pins the parse5 behaviour the Netscape walk depends on — implied end tags, and
`:scope >` from an element root. It passed, then the parser, fixture and
round-trip suites, then coverage, all unchanged. The 2 869 ms figure in
docs/11 §6 is now labelled as a jsdom 29 number; a DOM major invalidates it
rather than updating it.

**svelte-check ^4.7.3 → ^4.7.4.** A patch.

npm audit stays at 0, and none of the six `overrides` can be dropped yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 f6e6999a4d ci: stop CI being red for a reason nobody acts on, and gate the manifest key set
notify-ci-failure.yml called a reusable that declares DISCORD_CI_WEBHOOK as
`required: true`, which GitHub validates before any of the reusable's own logic
runs. With the secret unset — docs/00 §10.6 lists it as still open — that
workflow failed on *every* CI completion, success included, from the first push
after it landed. The file's own header comment admitted it. This is precisely
the failure mode commit 5f4c6e7 fixed for releases: a run that is red for a
reason nobody acts on teaches everyone to stop reading the colour, and the next
genuine failure goes unnoticed.

release.yml's `gh release create` had no existence check, so any failure after
it — realistically the CWS publish step, once autopublish is on — stranded the
tag: a re-run could not get past that line, and recovery meant deleting the
Release and the tag by hand. v1.0.1 is the first tag to exercise that path at
all, since both the continue-on-error announce fix and tag_override landed
after the v1.0.0 tag object.

check-manifest.mjs now asserts the exact top-level key SET, not just the absence
of ten enumerated reach-widening keys. The forbidden list can only catch what
someone thought to name; this catches a build tool that starts emitting a key
nobody asked for. That matters immediately: WXT is a 0.x dependency, so a
routine minor bump is exactly when it happens, and tests/unit/manifest.test.ts
is structurally blind to it — it reads wxt.config.ts, which a WXT upgrade cannot
change. Verified by injecting a `commands` key into a built manifest and
watching the gate fail.

docs/12's sample YAML updated in the same commit, so the drift this phase just
finished correcting does not immediately start again.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 3b6bc42897 feat(about): link the Chrome Web Store listing
docs/13 §6 counts store ratings and reviews as one of the three post-launch
channels this project has, and there was no way to reach the listing from
inside the extension — the listing URL appeared in exactly one place in the
repo, the README, which a user who installed from the store never reads.

Deliberately no support email alongside it. Publishing an address on an
in-product surface invites people to mail their real bookmarks file, and a
bookmarks export is a browsing history — the exact receipt of personal data
legal/PRIVACY.md and docs/09 §6 are written to bound. contact@poli0981.dev
stays in SECURITY.md and CONTRIBUTING.md, where it arrives next to the
instruction to sanitize first. A test asserts links.ts contains no address, so
the decision has to be made again on purpose rather than by accident.

docs/06 §3.5 sanctioned the fourth link in PR A, before the code added it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 741c07ffad feat(settings): make two Manager tabs agree with each other
docs/15 recorded this as a known v1 limitation, and with real users it is a
one-star review waiting to happen: `save()` writes the whole settings object
rather than a patch, so a tab opened before the language changed reverted that
change the moment its own theme toggle fired. From the user's side that reads as
"I changed it and it didn't stick" — unfalsifiable, and indistinguishable from
a bug. Accepting the legal terms in one tab likewise left the other padlocked
until reload.

The adoption rule is field equality plus an in-flight guard, and between them
they solve the echo problem and the debounce problem at once:

1. If this context has an unflushed write, ignore the incoming change entirely.
   It is about to overwrite that value anyway, and adopting first would clobber
   the choice the user just made — in the UI *and* in what gets persisted 200 ms
   later. That is last-write-wins, exactly the semantic docs/15 documented, and
   it converges because our write fires the same event in the other tab.
2. Otherwise adopt only fields that actually differ. Our own write always
   matches what we already hold, so self-echo suppression falls out for free —
   no `lastWritten` snapshot to keep in step and go stale, and no dependence on
   key order, which a $state spread and coerceSettings do not agree on.

The fake-timer test covering rule 1 is the one that matters; without it the
guard is an unverified assertion about a race.

Legal acceptance is adopted **one way only, toward accepted.** App.svelte
renders the gate in place of the tab body, so an externally-raised gate would
unmount ImportTab mid-write and strand the import it was driving — recreating,
through a third door, the deadlock the routing guard and the store-held
attestation resolver were just written to close. Clearing storage elsewhere
therefore does nothing; a reload re-evaluates it, and a reload has no in-flight
work to strand. Three tests pin that asymmetry so a future simplification that
makes it symmetrical fails loudly.

subscribeStorage coerces through the same functions the read path uses — a
second tab is not a more trustworthy source than disk, it is the same disk — and
swallows a throwing handler, because an exception inside a chrome.* listener
surfaces in chrome://extensions and docs/11 §5 counts that as a failed QA pass.

Verified before writing any of it that WXT's fakeBrowser does implement
storage.onChanged (unlike bookmarks.*), so no injectable event source was
needed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 cfd1e77cb2 fix(edit): localized failures, and a search that collapses again
**#edit and #export showed a raw English Chrome string as the entire message.**
docs/02 §7 requires a localized sentence plus a separate technical block, and
LegalGate carries a comment describing this exact mistake as a defect that was
already fixed once — writing `detail ?? t(key)` looks like a sensible fallback,
but the raw string is almost always present, so the translation becomes dead
code. Three sites still had it: EditTab's load failure, ExportTab's load
failure, and ExportTab's export toast. A Vietnamese or Japanese user got an
untranslated Chrome message as their whole explanation.

One ErrorCallout now owns that contract, so there is a single place it can be
got wrong, and all three tabs go through the shared describeError.

**Clearing the search box rendered the whole tree in one synchronous pass.**
Search-opened ancestors merge into `expanded` (deliberately — a render-time
union made the disclosure button and ArrowLeft dead keys), but nothing ever
un-merged them. A one-character query expands most of a large profile, and
clearing the box then rendered every row the search had opened at once, with no
virtualization behind it; the 150 ms debounce delayed that growth without
bounding it. src/lib/edit/search-expansion.ts tracks search-owned ids
separately, and toggling a folder transfers it to the user so the collapse
cannot steal it back.

**"Keep the first of each" targeted nodes it cannot delete, then gave up
silently.** The duplicate list had no isEditable filter — unlike the
single-delete path — so duplicates inside a policy-managed subtree were offered
for bulk deletion, and the browser rejects every one of them. The loop then
abandoned the rest on the first rejection, leaving a partial delete measured
against a dialog that had promised an exact number, with no way to tell how many
copies remained. deleteEach never throws and reports how far it got.

EditTab was at 481/500 before this, so the ARIA tree container came out into
TreeList.svelte first — 466 now, and the tree pattern lives somewhere it is not
surrounded by loading, searching, mutation and five dialogs. That extraction
immediately caught a real bug the shorthand had hidden: `{ontoggle}` bound
`window.ontoggle`, not the local `toggle`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 d8bbd4ca79 fix(import): never lose the count, and close the Back-button deadlock
Three defects on the paths that touch a user's real bookmarks.

**A mid-import rejection used to lose everything needed to recover.**
writeTree awaited create() and let a rejection propagate bare — while the
bookmarks it had already written sat in the user's tree, uncounted. The
neighbouring BmAborted has always carried `done` for exactly this reason.
clearRoots was worse: it is the one path that deletes, and it reported nothing
at all, plus threw BmAborted(0) on cancellation regardless of how many root
children were already gone. Both now throw BmPartialWrite{phase, done}, and the
error state carries the safety backup's filename — which `attesting` knew and
`error` threw away, so the one string that lets someone restore a half-replaced
tree was the one thing not on screen. Only when a backup was actually produced:
on a BmBackupError the file may never have been written, and sending a
frightened user to look for a backup that does not exist is worse than silence.

BmAborted is re-thrown before the wrap, with a test pinning it. Wrapping it
would relabel every user cancellation as a failure and make the `cancelled`
state — and its copy in three languages — unreachable.

**Browser Back during the backup attestation deadlocked the Manager
permanently.** The attestation resolver was a component-local `let`, so Back
unmounted ImportTab, stranded the promise runImport was awaiting, and left
isWriting() true forever: every tab and footer control disabled, beforeunload
prompting, and a remounted tab rendering two inert buttons against a fresh empty
resolver. Closing the tab was the only escape. Phase 4 closed this same hole for
the footer and the tab bar; hashchange was the door left open.

Two independent fixes, because one is not enough: startRouting now takes an
injected isBlocked predicate (injected, not imported, so route stays uncoupled
from the import session), and the resolver moved into the store where it
outlives any component. A stale or reset resolver settles **false** — an
unanswered attestation is not consent, and this is the last gate before deleting
every bookmark someone has. The restore-the-hash path has an explicit test for
not recursing; an infinite hashchange loop in a released extension, on the path
a panicking user takes, is not a defect worth discovering from a review.

**Nothing told users their imported bookmarks are re-dated to today.** docs/05
§6 instructs saying so in the import report and docs/00 §8 repeats it as a
success criterion; no string ever did. The README and store listing say it to
prospective users, and the product never said it to actual ones — so someone
migrating a decade-old archive finds every bookmark dated today with no
explanation and no way to tell it from corruption. Now shown before the import
as well as after: telling someone before they commit is worth more.

Also: a profile whose every root is policy-managed now reports
NO_WRITABLE_ROOTS rather than "the browser refused a bookmark operation". The
browser refused nothing; it is an absence, not a refusal, and the old wording
sent people looking for a permission problem that was not there.

describeError moves out of ImportTab into browser/describe-error.ts so #edit and
#export can share it next, with tests asserting the two properties that have
been defects before: it returns a key rather than a resolved sentence, and it
omits `detail` rather than setting it to undefined.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 875eae5de5 feat: build the intake the v1.0.x plan has always assumed
docs/13 §6 stated as present-tense fact that "GitHub issues — templates route
bug reports with sample files", and docs/12 §5 carried the same as an unticked
box. Neither was true: .github/ held only FUNDING.yml, dependabot.yml and
workflows. Meanwhile the entire v1.0.x roadmap is "fixture + test per report",
which cannot happen if reports arrive without the file that broke.

Five issue forms plus a chooser, blank issues disabled. parser_report.yml is
the one that matters: it requires the sanitized sample, asks which browser
*version* produced the file, and asks explicitly for consent to commit the
sample as a GPL-3.0 fixture — it lives in a public repo forever, and nothing
previously asked.

scripts/sanitize-bookmarks.mjs makes "attach a sanitized sample" something a
reporter can actually do. It works by span replacement rather than by
reparsing, so every byte outside a replaced address or title is provably
untouched: BOM, doctype, line endings, tag and attribute case, quoting,
indentation and every timestamp survive, and so do the properties a parser
branches on — port, path depth, trailing slash, query-parameter count and
order, percent-escapes, HTML entities, and the distinctness of hosts that
dedupe depends on.

Its test asserts the promise rather than the implementation: for every fixture
in the repo, the sanitized file must detect as the same format, parse to the
same stats, warnings and topology — or fail with the same error code — and leak
no original hostname. Writing it immediately found three real defects: a data:
URL containing markup broke the title regex and left that bookmark's title
unsanitized; an &amp; in an HREF came back as a bare &, silently repairing the
escaping of the file being reported; and Firefox's ICON_URI leaked a full
hostname past every other check. The last one is why URL-valued attributes are
now swept by value shape instead of by an enumerated list.

scripts/gen-fixture.mjs is the generator docs/11 §2 named, .gitignore has
always reserved a directory for, and the 2 s parse budget needed in order to be
measurable at all.

CONTRIBUTING.md collects the five-file ritual for turning a user's file into a
regression test, which was previously spread across CLAUDE.md, docs/04 and
docs/11 with no single entry point — including the .gitattributes rule that
stops EOL normalization destroying the bytes a bug depends on.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 20ddba5472 docs(store): put the listing copy under version control
docs/13 §4 has always said the VI/JA listing text should live in
store/listing.{vi,ja}.md "so listing text is version-controlled". It never did,
which meant every listing edit — one of the three things the v1.0.x roadmap
anticipates — would be made straight into the dashboard with no diff, no
history and no reviewer.

Reconstructed from docs/13 §3, with EN added as the canonical file since it is
the one CWS requires. Marked ⚠️ throughout: these were written after the listing
went live, so they are a copy of the specified copy, not a transcript of what
the dashboard shows. Until someone diffs the two, the dashboard wins.

Summary lengths are recorded per file and verified against the 132-character
dashboard cap — VI has only 7 characters of slack, which is worth knowing
before someone edits it and gets rejected at submission time.

JA carries the same TODO(review-ja) caveat as the in-app dictionary.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 1c0da6f0e8 docs: write the runbooks a shipped extension needs
docs/13 had only a first-submission runbook, so nothing described how to ship
v1.0.1 — nor what to do when an update is rejected, when the item is taken
down, or when a tag was pushed and the release run died half-way. All four are
now reachable in a way they were not before the listing went public.

- docs/13: §1 marked historical (and its never-performed step 8 handed to
  docs/11 §5). New §1b update runbook — the bump must reach main *before* the
  tag, because release.yml compares the built manifest against the tag; the
  store artifact is the Release asset, not the CI artifact, because that is
  what SHA256SUMS.txt covers. New §7: a rejected update leaves the published
  version live, so it is not an emergency; a rejected version string can never
  be reused, so the fix ships as the next patch, not as a re-upload; and there
  is no rollback in CWS at all — only a higher version carrying the revert.
- docs/12: the sample YAML had drifted twice (setup-node v6 vs the live v7, and
  a missing check:manifest in the release job). Docs win here, so reconciling
  the wrong way would have downgraded a pinned action and deleted a gate — both
  fixed, with a note that this is the one doc where the running pipeline is the
  ground truth. §2.4 gains the if:/continue-on-error that stops
  notify-ci-failure failing on every green CI run for want of a secret.
  §5's checklist now distinguishes verified from unknown instead of reading as
  eight things nobody did.
- docs/11: §2's inventory named four fixtures that do not exist and omitted two
  that do; each phantom is removed only after naming the test that actually
  covers its behaviour. §5 gains the upgrade pass — installing the published
  build, updating over it, and proving the legal flag and settings survive —
  which is the only failure mode that hits every user at once. §6's parse
  budget gains a procedure now that a generator exists to make the file.
- docs/14 §3 stopped embedding drafts of documents users have already accepted
  (its copy still carried `Last updated: 2026-⚠️`). It now points at the
  committed files and specifies when a change bumps LEGAL_VERSION, since that
  re-shows the gate to everybody.
- SECURITY.md: supported versions (latest published only — Chrome auto-updates,
  so there is no population to back-port for), an email fallback for reporters
  without a GitHub account, and an honest split between "fix prepared in 14
  days" and "fix reaching users", which additionally needs store review.
- legal/PRIVACY.md: says what happens to a file you send us. Deliberately not a
  LEGAL_VERSION bump — it clarifies handling of data a user chooses to send,
  which was never inside "what the Extension collects", and re-gating every
  installed user over a clarification is the worse outcome.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981andClaude Opus 5 18d112a00f docs: record that v1.0.0 is published, not in review
The suite froze at the moment of submission and still said "in review" a week
after the listing went public. Since docs win over code here, a stale spec is a
false spec — and one of its "still open" items (the store URL for the README)
had already been closed by ea246aa.

- docs/00: status is published with the listing URL; the store item id and
  listing URL join the §9 canonical identifiers table, because the id is also
  the CHROME_EXTENSION_ID secret v1.1 automation needs; §8's approval criterion
  marked achieved; §10 item 5 resolved and item 6 rewritten — DISCORD_CI_WEBHOOK
  is not optional in practice, since notify-ci-failure.yml fails on every CI
  completion without it. Two new post-launch items: the JA native review pass
  (now shipping to users) and the never-performed post-approval smoke test.
- docs/15: the progress table gains a published row and a Phase 6 row; v1.0.x
  stops being speculative and becomes the live workstream, with the intake path
  spelled out end to end and a release trigger. Decision log: the Changelog-link
  row is marked resolved, the two-tab known limitation superseded, and twelve
  rows added for the Phase 6 design — recorded before the code, as the project's
  own docs-first rule requires.
- docs/06 §3.5: the Changelog link points at CHANGELOG.md (it has since Phase 5)
  and About gains a store listing entry. Also states why no support email
  appears in the UI: an in-product address invites unsanitized bookmark files.
- CLAUDE.md: leads with the fact that this is shipped software, and what that
  changes. Records EditTab.svelte back at 481 lines rather than the 459 it
  claimed, adds a Phase 6 section, and adds the worktree bootstrap gotcha.

Also adds `verify:full`, because hard rule 8 now points at it. `verify` omits
coverage, build and check:manifest, all of which a tag run enforces — so a core
change can pass every documented local step and fail only after the tag is
pushed, when gh release create has already run and cannot be re-run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-03 20:20:05 +07:00
poli0981 ea246aad68 Update Chrome Web Store link in README 2026-07-27 11:12:22 +07:00
poli0981andClaude Opus 5 bbf0ae73b2 docs: record the v1.0.0 release and what is still open
Status header, the docs/15 progress table and the docs/00 §10 manual list now
say where the project actually is: all six phases done, v1.0.0 tagged and
released, submitted to the Chrome Web Store and in review.

§10 gains two items that were being carried in commit messages and memory
rather than anywhere a reader would find them:

- `npm run dev:firefox` is untested against the dependency overrides. Four of
  them sit under web-ext-run and no gate exercises that script. Firefox is a
  v1.0 non-goal so it blocks nothing, but nobody should assume it works.
- The 2 s parse budget is unmeasured on a real browser. The recorded 2869 ms is
  a jsdom figure and settles nothing either way.

The decision log gains the overrides rationale and why the release
announcement is continue-on-error.

The review-habit note is updated with phase 4 and 5 (19-of-33 and 8-of-20
confirmed), plus the two patterns this build kept demonstrating: the worst
findings were in work added earlier in the same branch, and three defects
reached main that no automated gate could have caught — a missing space, a
glyph that reads as a letter, and a permission grant that failed CI at startup
with no jobs and no log.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 18:35:45 +07:00
poli0981andClaude Opus 5 5f4c6e7b1f fix(ci): a missing Discord webhook must not fail a good release
The real v1.0.0 run went red. The release job itself succeeded — the GitHub
Release, bookmarkmagic-1.0.0-chrome.zip and SHA256SUMS.txt all published, and
`sha256sum -c` verifies against the downloaded asset. Only `announce` failed,
with "No webhooks configured", because DISCORD_RELEASES_WEBHOOK and
DISCORD_REPO_WEBHOOK are unset — which docs/12 §5 lists as optional.

A red run on a correct release is worse than a missing announcement: it trains
you to stop reading the colour. `continue-on-error: true` on the announce job.

The tag_override fix from the Phase 5 review did work — the job reached the
webhook check, which it could only do after resolving the tag.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 17:45:42 +07:00
poli0981andClaude Opus 5 9c6ecaaa75 fix(deps): take npm audit to zero with overrides for six transitive dev CVEs
Six Dependabot alerts (1 critical, 3 high, 1 medium, 1 low) plus six further
`npm audit` highs, all in transitive DEV dependencies whose parents pin them to
vulnerable ranges. That pinning is why Dependabot's own per-package PRs could
not fix any of them — every one of those runs failed. `overrides` is the npm
mechanism for precisely this case.

  shell-quote     1.7.3   -> ^1.9.0    wxt > web-ext-run > fx-runner
  adm-zip         0.5.18  -> ^0.6.0    wxt > web-ext-run > firefox-profile
  tmp             0.2.5   -> ^0.2.6    wxt > web-ext-run
  uuid            8.3.2   -> ^11.1.1   wxt > web-ext-run > node-notifier
  esbuild         0.27.7  -> ^0.28.1   vite, wxt, unplugin
  brace-expansion 1.1.16  -> ^5.0.8    web-ext-run > multimatch > minimatch

The last one is the whole second cluster: `npm audit` reported six highs that
were one brace-expansion DoS propagating through minimatch -> multimatch ->
web-ext-run -> wxt, with fixAvailable:false because multimatch pins minimatch.

`npm audit` now reports 0. It already reported 0 for `--omit=dev`, and still
does: the shipped extension has no runtime dependencies, so none of this was
ever in the artifact.

Correcting something I wrote in the dependabot.yml comment and repeated in a
PR: I said these advisories had "no reachable patched version". That was wrong
— every one of them had a patched version. What they lacked was a path
Dependabot could take on its own.

Re-verified after the overrides: lint, check, knip, coverage, guard, build,
check:manifest and zip all pass, and the built manifest is still exactly
["bookmarks","storage"] at version 1.0.0.

⚠️ Four of the six live only under web-ext-run, the Firefox dev runner behind
`npm run dev:firefox` — a v1.0 non-goal per docs/00 §7, and the one script no
gate exercises. docs/09 §3.1 records that, plus when each override can be
dropped.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 17:36:30 +07:00
dependabot[bot] 8d8c3f3d9f ci(deps): Bump actions/setup-node from 6 to 7 in the actions group
Bumps the actions group with 1 update: [actions/setup-node](https://github.com/actions/setup-node).


Updates `actions/setup-node` from 6 to 7
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/setup-node
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-26 17:27:47 +07:00
poli0981andClaude Opus 5 626e4fab3d feat: release prep for 1.0.0 — Dependabot, version bump, and two screenshot fixes
Two defects visible in the owner's screenshots of the running extension, both
invisible to every gate the repo has:

- The footer rendered "v0.1.0 ·GPL-3.0". Svelte trims trailing whitespace at an
  {#if} boundary, so the space after the separator inside the block was
  dropped. Separators are `{' · '}` expressions now, which are never trimmed;
  verified in the built bundle.
- The compact theme toggle's dark option used U+263E (☾), a thin crescent that
  reads as a capital "C" at ~13px — clearly visible in all four screenshots.
  Now ☀️/🌙, which also matches the popup's existing ⬆/⬇/🗂 vocabulary. The
  accessible name came from aria-label either way, so this is purely visual.

Adds .github/dependabot.yml (docs/12 §5): weekly npm and github-actions, dev
minor+patch grouped into one PR so CI runs once, Conventional Commit prefixes,
and TypeScript majors held because svelte-check needs the TS 6 programmatic API
until 7.1. The comment records what the file cannot do — security updates run
from the repo's alerts regardless, and the ones failing today are transitive
DEV dependencies with no reachable patch, which is why `npm audit --omit=dev`
is still 0.

Version bumped to 1.0.0 with the CHANGELOG section dated, and the icon set
closed in docs/00 §10: the owner adopted the gen-icons.mjs output as final, so
the generator is the source of truth rather than a placeholder. README's
screenshot placeholder is replaced with the four real captures.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 17:20:17 +07:00
poli0981andClaude Opus 5 2c8fba9a74 fix(ci): grant contents: write so the reusable build job can start at all
The first real run of ci.yml was a startup_failure — no jobs, no log, just
"this run likely failed because of a workflow file issue".

reusable-chrome-extension.yml declares two mutually exclusive jobs: `build`
(contents: read, `if: !inputs.release`) and `release` (contents: write,
`if: inputs.release`). GitHub validates the caller's grant against EVERY job
the reusable declares, before evaluating any `if:` — so passing `release: false`
does not exempt the caller from the release job's requirement, and the
least-privilege `contents: read` in docs/12 §2.1's sample rejects the whole run.

CodeQL succeeded on the same push because its caller happened to grant a
superset of what its single job needs, which is what isolated the cause.

docs/12 §2.1 updated with the same grant and a warning, since its sample is
what this stub was written from.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 674ac341e5 fix: close the eight findings the Phase 5 review confirmed
Five lenses filed 20; 8 survived verification.

**release.yml would have failed on the first tag.** The `announce` job called
the ops reusable with no `with:` block, but that reusable resolves
TAG="${INPUT_TAG:-$EVENT_TAG}" where EVENT_TAG is github.event.release.tag_name
-- empty, because this workflow is triggered by `on: push: tags`, not
`on: release`. The job would have exited 1 on "No release tag available" for
every release. Filed independently by three lenses and confirmed against the
reusable's actual source; docs/12 §2.3 had the same omission and is fixed too.
Ironically the comment right above it explains why the workflow deliberately is
not event-driven -- which is exactly what makes tag_override mandatory.

**Nothing checked the BUILT manifest.** The unit test reads wxt.config.ts,
which proves what we ask for, not what WXT emits. Those differ: a dev build of
this same config carries ["bookmarks","storage","tabs","scripting"] and
host_permissions ["http://localhost/*"]. Production is clean, but that is
WXT's behaviour, not ours. scripts/check-manifest.mjs now gates the artifact
and runs in both CI and release; verified by editing a built manifest. The
README sentence claiming a test asserted the built manifest was false and is
corrected -- the same overclaim I had already made once verbally.

**The contrast test I added last commit could not see its own bypass.**
TabBar's `.locked { opacity: 0.65 }` composites --fg-muted against the page and
drops the label to 2.83:1. The test reads token values, so alpha applied on top
is invisible to it. Opacity removed; the padlock and title already carried the
signal. TEXT_PAIRS also widened to check the status colours on --bg, not only
--bg-raised.

**docs/09 T3 was signed off with half its mitigation unbuilt.** The row has
always specified a ⚠ badge for dangerous schemes; only the blocking existed. A
`javascript:` bookmark titled "Your bank" rendered identically to a safe one
and its Open button silently did nothing. isBlockedUrl now drives a badge, and
a refused open raises a toast.

Also: the five row action buttons had glyphs as their accessible names (content
beats title in accname), so voice control could not address them; the manifest
test's literal-harvesting regex would have passed a spread or identifier;
resolveNewFolderParent returned a focused unmodifiable folder's id, which every
create rejects; and clipboard.ts was the only new module with no test.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 6a8ede7373 feat(security): close the two gaps the T1-T8 pass found
Walking docs/09's threat model against the shipped code turned up two things
that had gone unnoticed because nothing mechanical was watching either.

**The permission list had no test.** "Exactly bookmarks + storage" is
CLAUDE.md's first hard rule, the README's headline privacy claim, the store's
privacy-tab answer and a line in the privacy policy -- and a single added
string in wxt.config.ts would have shipped silently. tests/unit/manifest.test.ts
now asserts the list exactly, plus the absence of host_permissions,
content_scripts, a background worker and eight other reach-widening keys.
Verified to fail by sneaking in 'tabs'. It reads the config as text, with
comments stripped, so the assertion cannot be satisfied by something computed
at build time -- and because the file's own header says "No host_permissions,
no content_scripts", a naive substring check failed on the prose promising the
very thing it checks.

**"Copy URL" was never built.** docs/06 §3.3 lists it in the row menu and
docs/09 T8 describes its mitigation, so the threat model documented a control
for a feature that did not exist. Now implemented in browser/clipboard.ts:
write-only, on an explicit click, never reads the clipboard, and needs no
permission because a transient user activation grants clipboard-write.

Also records the measured pass in docs/09 §2 and the reproducibility finding in
§5: content-identical rebuilds (every zip entry matches by CRC32) but not
byte-identical, because wxt zip records mtimes. The old wording implied more
than is true.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 ba11fbf229 ci: add the four caller workflows
Per docs/12 §2, with every input checked against the ops repo's actual
workflow_call blocks rather than the doc — docs/12 originally described a
template family that had never existed.

Verified before writing: reusable-chrome-extension.yml takes
package-manager/node-version/build-command/source-dir/release and declares NO
secrets block, so passing a named secret to it would be a compile error;
reusable-codeql.yml takes `languages` as a JSON-array string (the older
codeql.yml's singular `language` is the wrong one); notify-ci-failure.yml
declares DISCORD_CI_WEBHOOK required:true; announce-release.yml's secrets are
optional. actions/checkout@v7 and setup-node@v6 are what the ops repo itself
runs.

Three traps the comments now carry, because each costs a run to rediscover:
- leaving package-manager at its 'none' default skips install and build, then
  fails on `test -f ./manifest.json`, a file WXT never writes to the repo root;
- reusable workflows do not inherit the caller's permissions, so every caller
  repeats its permissions block on the job;
- the release announcement is a job INSIDE release.yml, not an
  `on: release: [published]` caller — a Release created by gh under the default
  GITHUB_TOKEN emits no event that starts new workflow runs, so the
  event-driven version silently never fires.

The quality job is local because the reusable runs no quality gates at all.
All four parse, and `npm run zip` emits .output/bookmarkmagic-0.1.0-chrome.zip,
matching the glob release.yml uses.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 f929336007 docs: add CHANGELOG and README, and point About's link at the real file
CHANGELOG.md follows Keep a Changelog with the semver policy docs/12 §4
defines, and carries a marker for the human step at first release (rename
[Unreleased] to [1.0.0]).

README leads with what the project is actually for and then spends its longest
section on privacy, because that is the product's reason to exist and every
claim in it is mechanically enforced: the grep gate for network calls, the
manifest assertion for permissions, zero runtime dependencies. It also keeps
docs/13's honesty corner -- favicons, import dates, CSV flattening -- rather
than only listing what works.

src/lib/links.ts now points "Changelog" at blob/main/CHANGELOG.md instead of
the /releases placeholder it used through Phase 4, and the links test asserts
the file exists, the same way it already does for the four legal documents. A
link shipped inside the product must not 404 because someone renamed the
target.

Screenshots and the store URL are marked ⚠️ in the README -- both need a human
and neither blocks the code.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 a447d550bf refactor(edit): split EditTab under the size limit and test what came out
EditTab.svelte was 589 lines against the 500-line hard limit in docs/10 §1 --
the one place in the codebase that broke it. Now 459.

Extracted, in each case because the thing was genuinely cohesive rather than to
hit a number:

- src/lib/edit/edit-node.ts -- toEditNode, flattenTree, isEditable,
  resolveNewFolderParent, countDescendants, extraCopyIds. All pure, all
  previously inline and therefore untestable. resolveNewFolderParent in
  particular encodes a fixed bug (a focused root resolving to the synthetic
  root "0", which every create rejects) that nothing was pinning.
- src/lib/browser/open-url.ts -- the docs/09 T3 scheme allowlist, which is the
  only thing between a crafted `javascript:` bookmark in someone's import file
  and the browser acting on it. It had NO test. It does now, including the
  case-shouting dodge and data:/file:/chrome:.
- EditToolbar.svelte and MoveToDialog.svelte -- presentational, with their
  styles copied verbatim. This is a move, not a redesign.

The script block is still 279 lines against docs/10 §1's 150-line guidance. The
remainder is the mutation layer (guardEdit and the six operations), which is
coupled to reactive state and would need accessor indirection to move. Adding
that indirection to the app's delete paths immediately before a release is a
worse trade than the line count, so it stays and is recorded in CLAUDE.md
rather than quietly ignored.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 9e937bff30 fix(ui): make every colour token meet the contrast the spec has always required
docs/06 §5 has said "≥ 4.5:1 in both themes (tokens chosen accordingly)" since
the spec was written. Nothing enforced it, and the tokens were not chosen
accordingly. Measured:

  white on dark --accent      3.67:1   (fixed in Phase 4)
  white on dark --danger      2.74:1   Button/ConfirmDialog .danger
  light --warn on --bg-raised 3.40:1   WarningList summary
  light --success  "     "    3.26:1   TreePreviewNode badge, DuplicatePanel
  light --danger   "     "    4.27:1   DuplicatePanel count
  dark --accent    "     "    4.40:1   links inside raised panels

Adds --danger-fg, which like --accent-fg must be redefined in the dark block in
the OPPOSITE direction: dark mode lightens the colour for contrast against the
page, and that is exactly what breaks white ink sitting on it.

The light status colours are now darker than an eyeball would pick, because all
three are rendered as text on --bg-raised. Adjustments preserve hue and were
solved for numerically rather than guessed; each clears 4.5 with margin.

The real deliverable is tests/unit/styles/contrast.test.ts, which parses
tokens.css and fails on any text pair below 4.5:1 — verified to actually fail
by restoring the old --warn and watching it report 3.40:1. It also pins the two
dark blocks (explicit override and prefers-color-scheme) against each other,
because they already drifted once when --accent-fg was added to only one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 14:57:15 +07:00
poli0981andClaude Opus 5 72e7c29428 docs: record the Phase 4 browser verification and the resolved contact email
Phase 4 is now verified on a real browser, which every earlier phase had been
and this one had not: the gate's block/reach/persist behaviour, EN→VI→JA live
switching with localized numbers and dates, the theme control, settings
surviving an immediate tab close (the path the $state-proxy DataCloneError
would have broken), and the Phase 2–3 flows still working after Phase 4 touched
their tabs and the settings store.

docs/00 §10 item 4 closes: the contact email in legal/PRIVACY.md is filled in
and confirmed live. That was the last thing standing between the repo and the
docs/13 §1 store runbook that is not Phase 5 work.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 01c46beecb docs: record the Phase 4 review outcome
The plural helper docs/07 §5 asked for now exists, so §5 names it and the two
shape tests that enforce it. The decision log gains the five design choices
the review forced, and the progress note records that 19 of 33 findings
survived verification -- including the first-run dead-end where the gate was
reachable only from the routes it blocked.

Adds one measured defect to the Phase 5 list rather than fixing it silently:
Button's .danger/.success hardcode white, which is 2.75:1 on dark-theme
--danger. Same class of bug as the --accent-fg one Phase 4 fixed, but it needs
new tokens and a visual decision rather than a mechanical change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 0e0f041eb8 fix(i18n): plural forms, the count the retrofit missed, and error text that re-translates
Last batch from the Phase 4 adversarial review, including one the completeness
critic caught that none of the six lenses looked for.

The num() retrofit was incomplete: FolderPickNode rendered its per-folder count
raw, so a Vietnamese user saw "12345" in the export pick tree while StatsCard
showed "12.345" on the adjacent tab. docs/07 §3, written in this same phase,
enumerates exactly three exemptions and this was on none of them.

ImportTab resolved t('errors.…') inside a catch block and stored the resulting
STRING in the session store. t() is only reactive where it is called, so the
error message froze in whatever language was active when it happened and never
followed a language switch. Phase 4 is what makes that observable -- until now
there was no way to switch language at runtime. The store holds the key now.

docs/07 §5 specifies plural keys as { one, other } objects in every locale with
a helper that selects by locale. No such helper existed and the dictionaries
used "(s)" instead, which produced "1 unreadable date(s) were left blank." --
wrong in more ways than the parenthesis. selectPluralForm uses Intl.PluralRules
(en gives one/other, vi/ja only ever other, so two forms cover every locale we
ship) and tPlural supplies a locale-grouped {n} so callers pass a raw count.
All seven warning codes are plural keys, including the two that interpolate no
count, so WarningList can call tPlural unconditionally instead of maintaining a
list of which codes count things.

Also splits getGeneratorVersion from getAppVersion: the UI hides an unknown
version, but a file field cannot be hidden, and "BookmarkMagic " with a
trailing space is a worse artifact in an export -- and in the forced Replace
safety backup -- than the bare product name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 bb7962d98a fix(a11y): contrast, focus ring, radiogroup keys, live region and document language
Five findings from the Phase 4 adversarial review, all of them things a green
build cannot see.

tokens.css redefined --accent in both dark blocks but never --accent-fg, so
dark mode painted white on #8b6dff -- 3.67:1, under the 4.5:1 docs/06 §5
requires. That hit the ThemeToggle's selected chip and every primary button.
Dark ink on the same violet measures 4.84:1.

ThemeToggle's `overflow: hidden` clipped the global :focus-visible ring, which
base.css draws at outline-offset: 2px, i.e. entirely outside the clip region.
The theme control had no keyboard focus indicator at all. Corner rounding is
per-child now and the ring is inset.

ThemeToggle also claimed role="radiogroup"/"radio" while implementing neither
roving tabindex nor arrow keys, so a screen reader announced "radio button,
1 of 3", switched to forms mode, and then the arrows did nothing while all
three stayed separate tab stops -- the inverse of the pattern (WCAG 4.1.2).
Arrow/Home/End now work and only the selected radio is a tab stop. The handler
sits on the radios, not the group: a keydown handler on a non-focusable
container never fires.

Toast built its role="status" region and its text in one DOM insertion. Screen
readers derive announcements from mutations to a region that was ALREADY
present, so success toasts were never announced. Two permanently-mounted
regions now, polite and assertive, with only their text changing -- two rather
than one with a swapped aria-live, because changing politeness at runtime is
not reliably picked up.

applyLocale never touched <html lang>, and both entrypoints ship lang="en", so
a screen reader read Vietnamese and Japanese with an English voice. It also
fixes the toast's dismiss button, which was labelled "Cancel" -- there is
nothing to call off, the operation already finished.

Also routes the last three hardcoded English aria-labels ("Sections",
"Preview" x2) through the dictionary. They date from Phase 2, but full EN/VI/JA
coverage is this phase's exit criterion.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 72b169f5a0 fix(i18n): show the localized failure message, not the raw browser error
Found by the Phase 4 adversarial review; three lenses filed it.

Every failure path was written `outcome.detail ?? t('...saveFailed')`. But
`detail` is set for any rejection that is an Error, which is the normal case
for chrome.storage.local.set -- so the `??` almost never fell through and the
localized sentence was dead code in all three locales. A Vietnamese user over
quota saw "QUOTA_BYTES quota exceeded".

The worst instance was legal.saveFailed: "Your acceptance could not be saved,
so nothing was recorded. Check that this browser allows extension storage,
then try again." Translated into VI and JA, and unreachable -- at the one
moment a first-run user most needs an actionable instruction.

docs/02 §7 already specified the right shape: "human-readable, localized
messages + a copyable technical detail block", which ImportTab has done since
Phase 2. The message is now the translated sentence and the raw error moves
into a <pre class="detail"> beside it, in both #settings and the gate. The
header controls show the sentence alone -- there is no room for a detail block
there, and #settings has one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 02817bdfe0 fix(legal): make the gate reachable from every route, and stop About lying after a bump
Found by the Phase 4 adversarial review; four of six lenses filed it
independently.

The gate rendered only on #import/#export/#edit, and TabBar rendered exactly
those three tabs `disabled` while it was up. But they are the only in-app
navigation to a gated route, and the footer only offers #settings and #about.
So a first-run user who reached #settings -- the flow docs/14 §2 explicitly
prescribes, "so a VI/JA user can switch language and theme first" -- had no
enabled control that led back to the accept UI.

Worst path, introduced by the popup gear this same phase: fresh profile, no
Manager tab, click ⚙. openManager creates a NEW tab at #settings, so there is
no history entry to go Back to. Reopening from the popup does not rescue it
either -- open-manager deliberately focuses the existing tab without touching
its hash (docs/02 §6). The only escapes were editing the URL fragment or
closing the tab.

The fix is that disabling was never what blocked anything: App.svelte already
substitutes <LegalGate> for the tab body on any gated route, which is what
keeps Import/Export/Edit from mounting pre-acceptance. So the tabs are now
clickable and clicking one shows the gate. They carry legal.blocked as their
title -- a key that was translated into all three locales and rendered
nowhere, which is its own half of the same defect: the dead tabs gave no
reason at all.

Separately: decideLegalStatus dropped the stored record on the `updated` path,
so the first time LEGAL_VERSION is bumped, About would tell a user who
accepted v1 that they have never accepted anything. It now carries the
superseded acceptance. Dead code today (LEGAL_VERSION is 1), a wrong statement
about consent the day it is not.

Also clears LegalGate's close timer before setting a new one; repeated clicks
stacked timers and only the last was ever cleaned up.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 432645ca43 docs: reconcile the spec with Phase 4
The docs are binding, so where Phase 4 diverged from them the divergence has
to be written down rather than left as an undocumented difference between
spec and code.

Three owner decisions recorded: six settings rows (markdownStyle was persisted
but only editable as a transient #export control), all five donate handles in
About, and a three-way segmented theme control rather than a cycling glyph.

One genuine conflict resolved: docs/06 §3 called the Legal Gate "a full
overlay" while docs/14 §2 -- echoed in docs/03 §4 and the decision log --
requires #settings and #about to stay reachable while it is up. Those cannot
both be satisfied literally, so docs/06 now says the gate fills the content
region and explains why.

Also: docs/02's directory tree had been stale since Phase 2 (it predated
lib/edit, lib/export and lib/import entirely); docs/03 §4 documented a
five-field Settings shape that had six fields in code; docs/07 §3 now names
where the Intl helpers live and, more usefully, the three sites that
deliberately do NOT use them; docs/11 §5 gains the QA items Phase 4 created.

The decision log gains fifteen rows, including the cross-tab sync limitation,
recorded as a known limitation rather than left to be rediscovered in review.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 636182f1ef feat(legal): the first-run Legal Gate
docs/14 §1: the Chrome Web Store has no pre-install acceptance mechanism, so a
first-run gate is what makes the terms reachable at all. Without it the
extension cannot be submitted.

acceptLegal writes, awaits, and flips to `accepted` ONLY once the write
resolves. Getting this backwards is the exact defect shape the last three
phase reviews kept finding: dismiss optimistically, await a chrome.* call that
can reject, never handle the rejection. Here that would leave the user
accepted in the UI and unaccepted on disk, so the gate would silently return
next launch with no explanation. There is a test that rejects the write and
asserts the gate stays up and storage stays empty.

It fails CLOSED: an unreadable store gates. Showing the gate to someone who
already accepted costs one click; skipping it for someone who has not is not
recoverable. A stored version NEWER than LEGAL_VERSION still counts as
accepted -- re-gating on a downgrade is noise, not consent.

The gate fills the content region rather than covering the viewport. docs/06
§3 calls it "a full overlay", but docs/14 §2 -- echoed in docs/03 §4 and the
docs/15 log -- requires #settings and #about to stay reachable while it is up,
and a literal inset:0 scrim buries the footer links that get you there. The
docs edit reconciling this follows in the docs commit. A side effect worth
keeping: Import/Export/Edit never mount before acceptance, so nothing touches
chrome.bookmarks until the user has agreed.

"Close tab" does not bet the decline path on window.close(): the Manager is
opened by tabs.create, so window.opener is null and close() may no-op. It
waits 150 ms and says so plainly if the document is still there. tabs.remove
is not an option -- that needs the `tabs` permission docs/08 §2 forbids.

Also finally consumes TabBar's `blocked` prop, which has sat unused since
Phase 2, and adds About's acceptance line -- showing the version the user
ACCEPTED, not the current constant.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 e5b0d667a2 feat(about): the #about tab, manifest version, and outbound links
Completes docs/06 §3.5: identity, tagline, GitHub/issues/changelog links, the
"Third-party dependencies: None" statement, all five donate handles from
.github/FUNDING.yml (docs/14 §5), and the four legal documents. The
acceptance-date line follows in the Legal Gate commit, which owns that store.

The displayed version now comes from the manifest, as docs/06 §3.5 requires.
It was hardcoded as "0.1.0" in THREE places -- the Manager footer, run-export
and run-import -- so a release bump had three chances to leave a stale number
in a footer users quote in bug reports, and two chances to write a lying
`generator` field into an exported backup. getAppVersion() returns '' rather
than a plausible fallback, and every render site hides the line instead.

Static links are <a target="_blank" rel="noopener noreferrer">. docs/09 T3
bans <a href> for *imported* bookmark URLs, which is untrusted data and keeps
using tabs.create in #edit; these are compile-time literals in one module.
Using tabs.create here would add an awaited call that can reject, for nothing.

Changelog points at /releases: CHANGELOG.md is Phase 5 work, and a 404 opened
from a legal-adjacent surface is worse than an empty releases page. A test
pins it, and another asserts every legal URL resolves to a file that actually
exists in legal/ -- a rename would otherwise ship four dead links inside the
legal gate with nothing else noticing.

Also drops common.comingSoon now that no route falls through to a placeholder.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 2ea92da4ef feat(settings): the #settings tab, header controls, and a save path that tells the truth
Six rows per docs/06 §3.4 as amended -- the doc drew five, but Settings has
carried markdownStyle since Phase 3 and #export was the only place to change
it, so it never actually persisted. Plus the header language/theme controls
from the docs/06 §3 layout, which have been missing since Phase 0.

Three defects in the store had to be fixed for any of this to work, and none
of them could fail before, because updateSettings and resetSettings had zero
callers in src/:

- writeSettings handed the Svelte $state proxy to chrome.storage.local.set,
  which structured-clones its argument. Proxies are not cloneable, so every
  save would have thrown DataCloneError in a real browser. fakeBrowser stores
  the reference without cloning, which is why 338 green tests never saw it;
  the new test clones explicitly to reproduce Chrome.
- updateSettings replaced the settings object rather than mutating it, so any
  component capturing getSettings() into a local would silently stop updating.
  Four new components read this store. Now in-place, with an identity test.
- resetSettings left the pending debounce running, so a reset within 200 ms of
  a change wrote twice -- the first write persisting values just discarded.

updateSettings now returns a SaveOutcome that resolves when the write settles
and never rejects, so the "Saved" toast reports what happened instead of
assuming. flushSettings on visibilitychange shrinks the loss window from
200 ms to roughly nothing; the comment is explicit that it does not reach zero.

Both entrypoints now await settings before mount() and drop the unguarded
browser.i18n.getUILanguage() call at module scope, which could blank the page
on a throw. Awaiting means the pre-load frame is an empty #app rather than
content painted in the wrong locale and theme. Verified top-level await
survives wxt build.

Also gates the footer nav on isWriting(): navigating away during `attesting`
unmounts ImportTab and strands its attestation resolver, deadlocking the
import until reload. TabBar already guarded this; the footer was the way
around it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 4f77bd17fd feat(ui): store-backed Toast with a real queue
docs/06 §4 specifies a Toast (queue, auto-dismiss 4s, ARIA status) and §3.4
needs one for the Settings auto-save. All that existed was an inline
<p role="status"> in #export that never dismissed -- and that assigned error
strings to the same variable its CSS painted var(--success), so a failed
export reported itself in success-green. That is fixed here.

The store owns the timers rather than the component, because <Toast> mounts
once at the App root while the route chain below it unmounts on every
navigation. Component-owned timers would leak by construction.

Two queue rules exist for specific races, and both are pinned by tests:
timeouts are keyed by item id and re-check the head before shifting, so a user
dismiss racing a timer cannot double-shift and flash the next toast for a
frame; and a repeat of the visible message restarts its timer instead of
queueing a twin, because one debounced save resolves one promise that may have
several subscribers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 c104754e8b refactor(i18n): route every rendered count through Intl.NumberFormat
docs/07 §3 says counts follow the UI locale, and the docs/11 §5 QA item is
"Language switch EN→VI→JA live-updates all tabs; dates/numbers localized".
Every count was being interpolated raw, so a Vietnamese user saw "1,284" where
their locale writes "1.284".

Three sites are deliberately left alone, each with a comment saying why, since
they all look like the retrofit missed them:

- ProgressBar's percentage is 0–100, no locale groups two digits, and it is
  the hottest render path in the app.
- ImportTab.formatFolderDate stays ISO — docs/07 §3 pins the created folder to
  the localized *word* plus an ISO date ("Đã nhập 2026-07-03"). Localizing it
  would change the names of folders written into the user's browser.
- run-export.isoDate and every filename stay locale-neutral so an exported
  file means the same thing whoever opens it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
poli0981andClaude Opus 5 c955e071a9 feat(i18n): locale-aware formatting and the Phase 4 dictionaries
docs/07 §3 requires Intl for every rendered count and timestamp, but nothing
in src/ constructed an Intl formatter and there was no Locale -> BCP 47 tag
map at all. Adds a pure format.ts (cached formatters, since StatsCard alone
formats four counts per paint) plus num()/dateTime() wrappers that follow the
reactive locale.

formatDateTime returns undefined rather than a string on an unparseable date.
That is load-bearing: readLegal deliberately coerces a missing acceptedAt to
"", and Intl.format(new Date("")) throws a RangeError *inside a render* --
which would blank the About tab that Phase 4 is about to add.

Also lands the whole settings.*/about.*/legal.* tree in en, vi and ja ahead of
every consumer, and two runtime companions to the `satisfies Dict` compile
check. The token-equality test is the one that earns its keep: a translation
that drops {total} from "Importing... {done} / {total}" type-checks perfectly
and renders a broken sentence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 13:54:25 +07:00
318 changed files with 33970 additions and 7995 deletions

No files matched your search

+7 -2
View File
@@ -1,5 +1,10 @@
# Default: normalize to LF in the repo, check out native.
* text=auto
# Default: normalize to LF in the repo AND in every checkout.
#
# `eol=lf` and not "check out native": Biome's formatter (and every gate built
# on it) expects LF, so a Windows clone with core.autocrlf=true used to fail
# `npm run lint` on all 114 files before a single line had been edited. The
# two `#!/usr/bin/env node` scripts are also unusable from WSL with CRLF.
* text=auto eol=lf
# Fixtures are byte-exact samples of what real browsers and spreadsheets emit.
# EOL normalization would rewrite the CRLF records in the CSV exports, so a
+106
View File
@@ -0,0 +1,106 @@
name: Something is hard or impossible to use
description: A barrier with the keyboard, a screen reader, a contrast theme, zoom, or voice control.
title: '[a11y] '
labels: [accessibility]
body:
- type: markdown
attributes:
value: |
Thank you — a report like this is treated as a defect, not a wish.
[ACCESSIBILITY.md](https://github.com/poli0981/bookmarkmagic/blob/main/ACCESSIBILITY.md)
lists what is already known not to work well; it is fine to report
something on that list if it is in your way.
You do not need to explain why you use the tools you use.
**Please do not attach your real bookmarks file**, and check a
screenshot or recording for bookmark titles first — your bookmarks are
your browsing history.
- type: textarea
id: task
attributes:
label: What were you trying to do, and what happened instead?
placeholder: |
I tabbed to the tree on the Edit tab and pressed F2 to rename a
folder. Nothing was announced and I could not tell whether …
validations:
required: true
- type: dropdown
id: severity
attributes:
label: How badly does it get in the way?
options:
- Blocked — I could not finish what I was doing
- Hard — I finished, but only with a workaround
- Annoying — it works, but badly
validations:
required: true
- type: dropdown
id: area
attributes:
label: Where does it happen?
options:
- Import
- Export
- Edit
- Settings
- About / legal gate
- The toolbar popup
- Everywhere
validations:
required: true
- type: textarea
id: assistive-tech
attributes:
label: Assistive technology and settings
description: >-
Whatever applies, with a version if you know it — a screen reader
(Narrator, NVDA, JAWS, VoiceOver, ChromeVox, Orca), a contrast theme,
zoom level, reduced motion, voice control, switch access, a keyboard
only. "None, keyboard only" is a complete answer.
placeholder: NVDA 2026.3, Windows contrast theme "Night sky", 150 % zoom
validations:
required: true
- type: input
id: version
attributes:
label: BookmarkMagic version
description: Shown in the About tab, and on chrome://extensions.
placeholder: '1.2.1'
validations:
required: true
- type: input
id: browser
attributes:
label: Browser and operating system
placeholder: Chrome 142 on Windows 11
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: The keys you pressed are as useful as anything else here.
placeholder: |
1. Open the manager, go to Edit
2. Tab to the tree, press ↓ three times
3. …
validations:
required: false
- type: checkboxes
id: confirmations
attributes:
label: Before submitting
options:
- label: >-
Anything I attached contains no real addresses, titles or personal
data.
required: true
+104
View File
@@ -0,0 +1,104 @@
name: Something else is broken
description: Anything that is not a bookmark file failing to import.
title: '[bug] '
labels: [bug]
body:
- type: markdown
attributes:
value: |
If a **bookmark file** will not import correctly, please use the
"A bookmark file will not import correctly" form instead — it asks for
the one thing that makes those fixable.
If something is hard or impossible to use with a **keyboard, a screen
reader, a contrast theme or zoom**, the "Something is hard or
impossible to use" form asks better questions for that.
If this is a **security** problem, do not file it here. See
[SECURITY.md](https://github.com/poli0981/bookmarkmagic/blob/main/SECURITY.md).
- type: input
id: version
attributes:
label: BookmarkMagic version
description: Shown in the About tab and at the bottom of the window.
placeholder: '1.0.0'
validations:
required: true
- type: input
id: browser
attributes:
label: Browser and version
placeholder: Chrome 138, or Brave 1.79, or Edge 138
validations:
required: true
- type: dropdown
id: os
attributes:
label: Operating system
options:
- Windows
- macOS
- Linux
- ChromeOS
- Other
validations:
required: true
- type: dropdown
id: area
attributes:
label: Where does it happen?
options:
- Import
- Export
- Edit
- Settings
- About / legal gate
- The toolbar popup
- Somewhere else
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
placeholder: |
1. Open the manager
2. …
validations:
required: true
- type: textarea
id: expected-actual
attributes:
label: What did you expect, and what happened instead?
validations:
required: true
- type: textarea
id: console
attributes:
label: Console output
description: >-
Go to `chrome://extensions`, turn on Developer mode, and check whether
BookmarkMagic shows an "Errors" button. If it does, paste what is
there. Blank is a perfectly good answer.
render: shell
validations:
required: false
- type: checkboxes
id: confirmations
attributes:
label: Before submitting
options:
- label: >-
Anything I attached contains no real addresses, titles or personal
data.
required: true
- label: I searched the existing issues first.
required: false
+34
View File
@@ -0,0 +1,34 @@
# Issue chooser — docs/12 §5, docs/13 §6.
#
# Blank issues are disabled on purpose. The whole v1.0.x plan is "fixture +
# test per report" (docs/15), and that only works if a parser report arrives
# with a sanitized sample. A blank issue is the path that skips that ask.
blank_issues_enabled: false
contact_links:
- name: An idea, to talk through first
url: https://github.com/poli0981/bookmarkmagic/discussions/categories/ideas
about: >-
BookmarkMagic is in maintenance mode (MAINTENANCE.md). A new idea is
welcome here, where it can be discussed without an issue that has to be
accepted or refused.
- name: Security vulnerability
url: https://github.com/poli0981/bookmarkmagic/security/advisories/new
about: Report privately, never as a public issue. See SECURITY.md.
- name: Rate or review on the Chrome Web Store
url: https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg
about: Reviews are read, but a bug reported here gets fixed faster.
- name: Accessibility barrier, by email
url: mailto:accessibility@poli0981.dev
about: >-
The "Something is hard or impossible to use" form above is the quickest
route; email works too. See ACCESSIBILITY.md.
- name: Question, or no GitHub account
url: mailto:code@poli0981.dev
about: >-
Email works. Please do not attach your real bookmarks file — see the
privacy policy for what happens to anything you send.
@@ -0,0 +1,86 @@
name: Suggest a feature
description: BookmarkMagic is in maintenance mode — read what that means before asking for something new.
title: '[feature] '
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
**BookmarkMagic is in maintenance mode**
([MAINTENANCE.md](https://github.com/poli0981/bookmarkmagic/blob/main/MAINTENANCE.md)).
A feature is added only when it is already on the
[roadmap](https://github.com/poli0981/bookmarkmagic/blob/main/docs/15_ROADMAP.md),
or when it is genuinely needed to fix a defect or remove a barrier.
**The first question below decides what happens to this issue.** A
request for something new is closed automatically and labelled
`maintenance-mode` — not deleted, and read; the
[Ideas discussions](https://github.com/poli0981/bookmarkmagic/discussions/categories/ideas)
are the place to talk one through. The other two answers keep the issue
open for the maintainer.
Out of scope permanently, whatever the mode: cloud sync, accounts,
analytics of any kind, and anything that would need a new browser
permission. "Offline, two permissions, no network" is the point of the
extension.
- type: dropdown
id: kind
attributes:
label: Which kind of change is this?
description: See MAINTENANCE.md. Please answer honestly — a mislabelled request is closed by hand.
options:
- Something already on the roadmap (docs/15)
- Needed to fix a bug, a UI/UX defect or an accessibility barrier
- Something new — not on the roadmap
validations:
required: true
- type: input
id: reference
attributes:
label: Which roadmap item, or which defect?
description: >-
The line in docs/15, or the issue or behaviour it fixes. Leave empty
for something new.
validations:
required: false
- type: textarea
id: problem
attributes:
label: What are you trying to do?
description: >-
The situation, not the solution. "I move between four machines and
cannot tell which export is newest" tells us more than "add a
timestamp column".
validations:
required: true
- type: textarea
id: proposal
attributes:
label: What would you like it to do?
validations:
required: true
- type: textarea
id: workaround
attributes:
label: How do you handle it today?
description: Including "I don't" — that is useful signal about severity.
validations:
required: false
- type: checkboxes
id: confirmations
attributes:
label: Before submitting
options:
- label: >-
As far as I can tell, this would not need any new browser
permission, and does not involve a server, an account, or sending
data anywhere.
required: true
- label: I read MAINTENANCE.md and checked the roadmap and the never list.
required: true
+118
View File
@@ -0,0 +1,118 @@
name: A bookmark file will not import correctly
description: A file was rejected, or imported with the wrong structure, titles or dates.
title: '[parser] '
labels: [bug, parser]
body:
- type: markdown
attributes:
value: |
Thank you — this is the most useful kind of report this project gets.
A sanitized sample of the file becomes a permanent test, so the same
bug can never come back.
**Please sanitize the file first.** From a clone of this repository:
```bash
node scripts/sanitize-bookmarks.mjs your-file.html
```
It replaces every address and title but keeps the structure, encoding
and date format the bug actually depends on — so the sanitized file
still reproduces the problem, without telling us where you browse.
- type: input
id: source-browser
attributes:
label: Which browser produced the file, and which version?
description: >-
The exact version matters more than you would expect — export formats
differ between browsers and change between versions.
placeholder: Firefox 145, or Safari 18.2 on macOS, or "no idea, it is old"
validations:
required: true
- type: dropdown
id: format
attributes:
label: File format
options:
- HTML (the usual "bookmarks.html" export)
- Chrome / Edge / Brave profile "Bookmarks" file
- Firefox JSON backup (bookmarks-YYYY-MM-DD.json)
- BookmarkMagic JSON
- CSV
- Not sure
validations:
required: true
- type: dropdown
id: symptom
attributes:
label: What went wrong?
options:
- The whole file was rejected
- It imported, but folders are missing
- It imported, but the nesting is wrong
- It imported, but titles are mangled or empty
- It imported, but the dates are wrong
- Duplicates were detected wrongly (too many, or not at all)
- Something else
validations:
required: true
- type: textarea
id: message
attributes:
label: The exact message the extension showed
description: Copy it as shown, including the technical detail block if there was one.
render: text
validations:
required: false
- type: textarea
id: expected
attributes:
label: What did you expect instead?
description: >-
For a structure problem, describing the shape you expected — "these
three folders should be inside Bookmarks Bar" — is usually enough.
validations:
required: true
- type: textarea
id: sample
attributes:
label: Sanitized sample file
description: >-
Drag the sanitized file into this box to attach it. If the file is
large, a trimmed sanitized version that still reproduces the problem is
better than a complete one.
placeholder: Attach the file here.
validations:
required: true
- type: input
id: version
attributes:
label: BookmarkMagic version
description: Shown in the About tab and at the bottom of the window.
placeholder: '1.0.0'
validations:
required: true
- type: checkboxes
id: confirmations
attributes:
label: Before submitting
options:
- label: >-
I ran the sanitizer, or I checked the file by hand and it contains
no real addresses, titles or personal data.
required: true
- label: >-
I agree that this sanitized sample may be committed to this
repository as a test fixture under GPL-3.0, where it will stay
permanently and publicly.
required: true
- label: I searched the existing issues first.
required: false
+75
View File
@@ -0,0 +1,75 @@
name: A translation is wrong or awkward
description: Vietnamese, Japanese, Chinese or Romanian wording that is incorrect, unnatural, or untranslated.
title: '[i18n] '
labels: [i18n]
body:
- type: markdown
attributes:
value: |
Native speakers are the only people who can catch this. English is the
source language; Vietnamese is reviewed by the maintainer. Japanese,
Simplified Chinese and Romanian are best-effort until a native pass,
so reports in those three are especially welcome.
You do **not** need to open a pull request or install anything — just
tell us the wording. If you would rather send the change yourself,
[CONTRIBUTING.md](https://github.com/poli0981/bookmarkmagic/blob/main/CONTRIBUTING.md)
has the whole path.
- type: dropdown
id: locale
attributes:
label: Language
options:
- Tiếng Việt (vi)
- 日本語 (ja)
- 简体中文 (zh-CN)
- Română (ro)
validations:
required: true
- type: input
id: location
attributes:
label: Where does the text appear?
description: >-
A tab name and a description is plenty — "the Export tab, on the CSV
format card". If you happen to know the key path from
`src/lib/i18n/locales/`, even better.
placeholder: Settings tab, the theme row — or export.formats.csv.hint
validations:
required: true
- type: textarea
id: current
attributes:
label: Current text
description: Copy it exactly as it appears.
validations:
required: true
- type: textarea
id: proposed
attributes:
label: Suggested text
validations:
required: true
- type: textarea
id: why
attributes:
label: Why is the current wording wrong?
description: >-
Grammar, register, an unnatural loanword, a term inconsistent with the
rest of the UI — whatever it is. This is the part that makes the change
reviewable by someone who does not speak the language.
validations:
required: false
- type: markdown
attributes:
value: |
**One constraint worth knowing:** placeholders like `{n}` or `{name}`
must appear in the translation exactly as they do in English — same
names, same count. A build gate enforces it, so a suggestion that drops
one cannot be merged as-is.
+78
View File
@@ -0,0 +1,78 @@
<!--
Thank you for sending a patch. Delete anything below that does not apply —
a translation fix does not need the parser section, and vice versa.
-->
## What and why
<!-- What changes, and what problem it solves. Link the issue if there is one. -->
**Kind of change** ([MAINTENANCE.md](https://github.com/poli0981/bookmarkmagic/blob/main/MAINTENANCE.md) — the project
is in maintenance mode): <!-- bug fix · UI/UX fix · accessibility · translation
· dependency or security update · roadmap item (which?) -->
A pull request titled `feat…` from outside the project is closed automatically
unless its feature is on the roadmap — open a feature request first.
## Checklist
- [ ] `npm run verify` is green. (Release-bearing? `npm run verify:full` —
`verify` does not run coverage, build or the built-manifest gate.)
- [ ] Conventional Commits title (`fix(import): …`, `feat(edit): …`, `docs: …`).
- [ ] `CHANGELOG.md` `[Unreleased]` updated, if a user would notice this.
### If it changes behaviour
- [ ] The relevant `docs/` chapter is updated. **The docs are the specification
here** — when code and docs disagree, the docs win, so a behaviour change
that skips the doc leaves the spec lying.
### If it touches user-visible text
- [ ] The key exists in **every** locale — `en`, `vi`, `ja`, `zh-CN`, `ro`
(`LOCALES`). `en.ts` is the schema; the others use `satisfies Dict`, so a
missing key fails the type check. Never add `as const` to a locale file.
- [ ] Interpolation tokens (`{n}`, `{name}`) match across every locale, and a
plural key carries the forms its language needs (`few` in Romanian —
`docs/07 §5`).
### If it changes the interface
`ACCESSIBILITY.md` is a public promise and `docs/06 §5` is its specification.
- [ ] Everything new works from the **keyboard alone**, and focus is visible
on it — including on a control with a filled background.
- [ ] Focus goes somewhere sensible when the thing that had it disappears
(a closed dialog, a removed row, a replaced step). It never falls to
the top of the page.
- [ ] Every control has an accessible **name**; an icon-only button takes a
`label`. Text a screen reader speaks is an i18n key like any other.
- [ ] No state is shown by **colour alone**, and a state shown by a fill or a
shadow has a `@media (forced-colors: active)` equivalent
(`tests/unit/styles/forced-colors.test.ts` holds the list).
- [ ] Anything that moves sits inside
`@media (prefers-reduced-motion: no-preference)`; pointer targets are at
least 24 × 24 CSS px.
- [ ] One pass with a **screen reader** over the changed screen (Narrator,
NVDA or VoiceOver) — or the PR says that it was not done.
- [ ] `ACCESSIBILITY.md` is still true: its key table and its known
limitations.
### If it is a parser fix
- [ ] A fixture is committed under `tests/fixtures/`, sanitized, with the
reporter's consent recorded in the issue.
- [ ] A regression test lands **in this same PR** — a fixture with no test is
just a file.
- [ ] The quirk is noted in the parser source **and** in `docs/04 §1.2`.
- [ ] `docs/11 §2`'s inventory lists the new fixture.
### Things that are never OK
- [ ] No new runtime dependency. (Zero is the number, and it is a public claim
in the store listing and the README. A new dep needs approval first —
`docs/01 §4`.)
- [ ] No new permission. The manifest is exactly `["bookmarks", "storage"]`, and
changing that is a minor-version event that also requires re-certifying
the Chrome Web Store privacy answers.
- [ ] No `fetch`, `eval`, `{@html}` or `innerHTML`. `npm run guard` enforces it.
+88
View File
@@ -0,0 +1,88 @@
# docs/12 §5. Two ecosystems: the npm dev toolchain, and the pinned actions in
# .github/workflows/.
#
# Note what this file cannot do: Dependabot *security* updates run from the
# repo's alerts regardless of any config here, and they ignore `cooldown`.
# BookmarkMagic has zero runtime dependencies, so `npm audit --omit=dev`
# reports 0 and an advisory against the dev toolchain never reaches the
# published extension (docs/09 T5).
#
# `.npmrc` sets `min-release-age=7`, the same rule as `cooldown` below, for
# installs made by hand. A security PR for a version younger than 7 days can
# therefore fail to resolve until that version ages — the price of not being
# the first to install a compromised release. `npm ci` is unaffected: it
# installs whatever the lockfile pins.
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
day: monday
open-pull-requests-limit: 5
# Supply-chain cooldown (docs/01 §6): only propose releases that have been
# public for a week.
cooldown:
default-days: 7
commit-message:
# Conventional Commits — docs/10 §7 applies to bot commits too.
prefix: chore
prefix-development: chore
include: scope
groups:
# One PR per week for the routine churn, so CI runs once rather than
# eight times and the review is a single diff.
dev-minor-and-patch:
dependency-type: development
update-types:
- minor
- patch
# WXT is 0.x, so its "minor" is semver's breaking slot, and every WXT
# bump needs the BUILT manifest diffed by hand (docs/15 decision log,
# 2026-08-03). It gets its own PR so it can never ride along unseen.
exclude-patterns:
- 'wxt'
- '@wxt-dev/*'
ignore:
# The TypeScript pair is held on purpose (docs/01 §2): `@typescript/native`
# is the TS 7 `tsc`, `typescript` is the TS 6 API that svelte-check needs.
# A major on either is a documented decision, not a weekly bump.
- dependency-name: typescript
update-types: [version-update:semver-major]
- dependency-name: '@typescript/native'
update-types: [version-update:semver-major]
# Tracks the Node major in .nvmrc (docs/01 §2), so it moves with Node.
- dependency-name: '@types/node'
update-types: [version-update:semver-major]
# The store-upload tool release.yml installs on its own (docs/12 §3): four
# packages, kept apart from the toolchain because they run beside store
# credentials. Its own directory, so its bumps arrive as their own PRs.
- package-ecosystem: npm
directory: /tools/publish
schedule:
interval: weekly
day: monday
open-pull-requests-limit: 2
cooldown:
default-days: 7
commit-message:
prefix: chore
prefix-development: chore
include: scope
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
day: monday
open-pull-requests-limit: 3
cooldown:
default-days: 7
commit-message:
prefix: ci
include: scope
groups:
actions:
patterns: ['*']
+116
View File
@@ -0,0 +1,116 @@
# Caller stub — docs/12 §2.1.
#
# The `quality` job is local because the ops reusable runs NO quality gates at
# all: its entire surface is install → build → assert manifest_version == 3 →
# zip → upload. Lint, type-check, knip, coverage, audit and the grep gate are
# ours.
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
quality:
name: Quality gates
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
# --ignore-scripts: no dependency runs code at install time. `wxt prepare`
# (our postinstall) generates .wxt/tsconfig.json, which tsconfig.json
# extends, so it runs explicitly from the local binary.
- run: npm ci --ignore-scripts
- run: npx --no-install wxt prepare
- run: npm run lint # biome check .
- run: npm run check # svelte-check (TS 6 API) + tsc (TS 7) + scripts checkJs
- run: npm run knip
- run: npm run coverage # vitest --coverage, thresholds per docs/11 §1
- run: npm run guard # the zero-network / no-raw-HTML gate, docs/08 §3
# Every licence in the lockfile, shipped packages held to the stricter
# list (docs/09 §3.2). Reads package-lock.json only — no network.
- run: npm run check:licenses
# Zero runtime dependencies is a public claim (README, docs/09 T5); this
# is the check that keeps it true. Dev-only advisories are tracked by
# Dependabot and docs/09 §3.1, not here.
- run: npm audit --omit=dev --audit-level=low
# The unit test proves what wxt.config.ts ASKS for. Only this proves what
# WXT actually emitted — a dev build of the same config carries
# tabs/scripting/host_permissions that never appear in the config file.
- run: npm run build
- run: npm run check:manifest
# The second package (docs/08 §9), held to its own key set and floor.
- run: npm run build:firefox
- run: npm run check:manifest -- --browser firefox
windows:
# Not a required check. The owner develops on Windows, and the paths that
# only break there — drive letters and percent-encoding in script paths,
# CRLF in a checkout — had no CI coverage at all.
name: Windows smoke (guard + unit tests)
runs-on: windows-latest
timeout-minutes: 20
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci --ignore-scripts
- run: npx --no-install wxt prepare
- run: npm run guard
- run: npm test
build:
name: Build + package
needs: quality
# No `secrets:` here — the reusable declares no secrets block at all, and
# passing a named secret to it is a workflow-compile error.
uses: poli0981/.github/.github/workflows/reusable-chrome-extension.yml@main
permissions:
# `contents: write`, not `read`, even though nothing here writes.
#
# The reusable has two mutually exclusive jobs: `build` (contents: read,
# `if: !inputs.release`) and `release` (contents: write, `if:
# inputs.release`). GitHub validates the caller's grant against EVERY job
# the reusable declares, BEFORE evaluating any `if:` — so passing
# `release: false` does not exempt us from the release job's requirement.
# Granting only `contents: read` makes the whole run fail at startup with
# no jobs and no log, which is how this was found (docs/12 §2.1's sample
# had the same too-narrow grant).
contents: write
with:
# All four are required in practice. Leaving package-manager at its
# 'none' default skips install and build, then fails on
# `test -f ./manifest.json` — a file WXT never writes to the repo root.
package-manager: 'npm'
# A string input, so it cannot read .nvmrc — keep it equal by hand
# (docs/01 §2).
node-version: '26'
build-command: 'npm run build'
source-dir: '.output/chrome-mv3'
release: false
+36
View File
@@ -0,0 +1,36 @@
# Caller stub — docs/12 §2.2.
#
# Uses `reusable-codeql.yml` (CodeQL Action v4), NOT the older `codeql.yml`,
# whose input is the singular `language`. This one takes `languages`: a JSON
# array encoded as a string.
#
# ⚠️ Prerequisite: repo Settings → Advanced Security → CodeQL "Default setup"
# must be DISABLED, or this advanced-setup workflow is rejected at SARIF upload.
name: CodeQL
on:
push:
branches: [main]
pull_request:
branches: [main]
schedule:
- cron: '0 14 * * 1' # weekly, Monday
permissions:
security-events: write
actions: read
contents: read
packages: read
jobs:
analyze:
# Reusable workflows do not inherit the caller's permissions — the block
# below is repeated on the job on purpose.
uses: poli0981/.github/.github/workflows/reusable-codeql.yml@main
permissions:
security-events: write
actions: read
contents: read
packages: read
with:
languages: '["javascript-typescript"]'
+45
View File
@@ -0,0 +1,45 @@
# Caller stub — docs/12 §2.4.
#
# The reusable filters to `conclusion == 'failure'` on the default branch
# internally, so the `if:` below is redundant for behaviour — but not for this:
# the reusable declares `DISCORD_CI_WEBHOOK` as `required: true`, and GitHub
# validates that BEFORE any of the reusable's own logic runs. With the secret
# unset (docs/00 §10.6) this workflow therefore failed on *every* CI completion,
# success included, from the first push after it landed.
#
# The `vars.DISCORD_CI_NOTIFY` gate on top of that, for the same reason
# `release.yml`'s announce job has one: a notification must never be able to
# change the colour of the thing it is reporting on. A run that is red for a
# reason nobody acts on teaches everyone to stop reading the colour.
name: Notify CI failure
on:
workflow_run:
workflows: ['CI']
types: [completed]
permissions:
contents: read
actions: read
jobs:
notify:
# Both conditions matter. The conclusion check stops this running at all on
# a green CI, which is what made it red on every push; the variable gate
# keeps it off entirely until the owner has actually set DISCORD_CI_WEBHOOK,
# since the reusable declares that secret `required: true` and GitHub
# validates it before the reusable's own filter runs.
#
# `continue-on-error` is NOT usable here: GitHub rejects it on a job that
# calls a reusable workflow ("Property continue-on-error is not allowed"),
# which invalidates the entire file. A repo variable is allowed in `if:`;
# a secret is not.
if: github.event.workflow_run.conclusion == 'failure' && vars.DISCORD_CI_NOTIFY == 'true'
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
permissions:
contents: read
actions: read
# Named, not `inherit`: the reusable is pinned to a moving branch, so it gets
# the one secret it declares and nothing else.
secrets:
DISCORD_CI_WEBHOOK: ${{ secrets.DISCORD_CI_WEBHOOK }}
+129
View File
@@ -0,0 +1,129 @@
# Qodana — docs/12 §2.7.
#
# A separate workflow, like SonarCloud's: a Qodana outage or opinion must never
# change the colour of CI, which is what branch protection reads. Not a
# required check.
#
# Two jobs, least privilege first:
# - `scan` runs the analysis. qodana-js resolves types through node_modules,
# so the dev dependencies are installed here (install scripts off) — which
# means they share a runner with QODANA_TOKEN. That is the documented
# exception to docs/12 §2.5's "a token job installs nothing": the token
# only uploads reports to one Qodana Cloud project (rotate it in
# qodana.cloud if a dependency is ever found compromised), and this job's
# GITHUB_TOKEN is read-only — no PR comments, no check runs from here.
# - `publish` installs and runs nothing: it takes the SARIF report from
# `scan` and uploads it to GitHub code scanning, where the findings appear
# beside CodeQL's under "Security and quality" and on pull requests.
name: Qodana
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
schedule:
- cron: '0 15 * * 1' # weekly, Monday — an hour after CodeQL
permissions:
contents: read
concurrency:
group: qodana-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
scan:
name: Qodana for JS
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
outputs:
ran: ${{ steps.token.outputs.present }}
steps:
# Dependabot and fork pull requests get no repository secrets: skip with
# a notice instead of failing, before installing anything.
- name: Check for QODANA_TOKEN
id: token
env:
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
run: |
if [ -n "$QODANA_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "::notice::Qodana skipped — QODANA_TOKEN is not available to this run (Dependabot or fork PR)."
fi
# The default ref — on a pull request, its merge commit — which is the
# commit code scanning attributes an upload from this run to.
- uses: actions/checkout@v7
if: steps.token.outputs.present == 'true'
with:
fetch-depth: 0
persist-credentials: false
- uses: actions/setup-node@v7
if: steps.token.outputs.present == 'true'
with:
node-version-file: .nvmrc
cache: npm
# --ignore-scripts: no dependency runs code at install time (docs/12 §2).
- if: steps.token.outputs.present == 'true'
run: npm ci --ignore-scripts
- if: steps.token.outputs.present == 'true'
run: npx --no-install wxt prepare
- name: Qodana scan
if: steps.token.outputs.present == 'true'
# Pinned to a commit, not the moving `v2026.2` branch the vendor's
# snippet uses: this step holds a token. v2026.2.2 rather than the
# newest tag, which is younger than the repo's 7-day cooldown.
uses: JetBrains/qodana-action@3e8d76ff0e0241618abd808682f426afe84bab3f # v2026.2.2
with:
# Whole project every time — it is small, and a PR that touches only
# docs would otherwise scan nothing.
pr-mode: false
# Both need write permissions this job deliberately does not have;
# `publish` reports the findings through code scanning instead.
post-pr-comment: false
use-annotations: false
# The SARIF report as the `qodana-report` artifact.
upload-result: true
env:
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN }}
QODANA_ENDPOINT: 'https://qodana.cloud'
publish:
name: Findings to code scanning
needs: scan
# !cancelled(), not the implicit success(): with failureConditions in
# qodana.yaml, a scan that FINDS something fails — and those are exactly
# the findings that must reach code scanning and the pull request.
if: ${{ !cancelled() && needs.scan.outputs.ran == 'true' }}
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
security-events: write
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: qodana-report
path: qodana-report
# The artifact holds one zip, qodana-report.zip, whose entries carry
# absolute names ("/qodana.sarif.json"). Take only the report, by its
# exact name, to a fixed path — nothing else is unpacked.
- name: Extract the SARIF report
run: |
set -euo pipefail
unzip -p qodana-report/qodana-report.zip /qodana.sarif.json > qodana.sarif.json
test -s qodana.sarif.json || { echo "::error::no qodana.sarif.json in the report"; exit 1; }
- uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3
with:
sarif_file: qodana.sarif.json
category: qodana
+325
View File
@@ -0,0 +1,325 @@
# Release — docs/12 §2.3.
#
# Standalone rather than the ops reusable: the reusable's `release` job only
# runs `gh release create --generate-notes`. It produces no SHA256SUMS.txt
# (required by docs/09 §5), performs no store submission, and exposes no
# `outputs:`, so a caller cannot reference the zip it built.
#
# Least privilege first. `build` installs, runs every gate and packages with a
# READ-ONLY token; only `publish`, which installs nothing and runs no
# repository code, ever holds `contents: write`. Before the split one job ran
# `npm ci` — every dependency's install script plus our own tests — while
# holding a write token that checkout had also left in .git/config.
#
# Since v1.3.0 there are three release files: the Chromium package (the Chrome
# Web Store AND Edge Add-ons take it), the Firefox package, and the sources
# archive AMO reviews (docs/08 §9, docs/13 §1c). And three store jobs, one per
# store, each off until its repo variable says otherwise (docs/12 §3).
name: Release
on:
push:
tags: ['v*']
permissions:
contents: read
jobs:
build:
name: Gate + package
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci --ignore-scripts
- run: npx --no-install wxt prepare
# The same gates as CI. A tag must never ship what a PR would have
# blocked — pushing a tag skips the CI workflow's branch triggers.
- run: npm run lint
- run: npm run check
- run: npm run knip
- run: npm run coverage
- run: npm run guard
- run: npm run check:licenses
- run: npm audit --omit=dev --audit-level=low
- run: npm run zip # → .output/<name>-<version>-chrome.zip (Chrome Web Store, Edge Add-ons)
- run: npm run zip:firefox # → …-firefox.zip and …-sources.zip (Firefox Add-ons)
# Gate the artifacts, not just the config they were built from. A tag is
# the last point at which an unintended permission can still be stopped.
- run: npm run check:manifest
- run: npm run check:manifest -- --browser firefox
- name: Verify tag matches both manifests
run: |
set -euo pipefail
TAG_VERSION="${GITHUB_REF_NAME#v}"
for target in chrome firefox; do
MANIFEST_VERSION=$(jq -r '.version' ".output/${target}-mv3/manifest.json")
test "$MANIFEST_VERSION" = "$TAG_VERSION" \
|| { echo "::error::tag $TAG_VERSION != $target manifest $MANIFEST_VERSION"; exit 1; }
done
# Staged in a plain directory: upload-artifact skips hidden paths by
# default, and `.output` is one. Each file by its exact name: a glob would
# pass with one of the three missing.
- name: Stage the release files
run: |
set -euo pipefail
VERSION="${GITHUB_REF_NAME#v}"
mkdir dist
for file in "bookmarkmagic-${VERSION}-chrome.zip" \
"bookmarkmagic-${VERSION}-firefox.zip" \
"bookmarkmagic-${VERSION}-sources.zip"; do
test -f ".output/$file" || { echo "::error::missing release file $file"; exit 1; }
cp ".output/$file" dist/
done
(cd dist && sha256sum bookmarkmagic-*.zip > SHA256SUMS.txt)
cat dist/SHA256SUMS.txt
- uses: actions/upload-artifact@v7
with:
name: release-${{ github.ref_name }}
path: dist/
if-no-files-found: error
retention-days: 90
publish:
name: GitHub Release
needs: build
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write # create the GitHub Release — the only write in this file
steps:
- uses: actions/download-artifact@v8
with:
name: release-${{ github.ref_name }}
path: dist
# The bytes about to be published are the bytes the build job hashed.
- name: Re-verify checksums
working-directory: dist
run: sha256sum -c SHA256SUMS.txt
# Idempotent on purpose. `gh release create` fails outright if a Release
# for the tag already exists, so any failure AFTER this step — a store
# job, realistically — used to strand the tag: re-running could not get
# past this line (docs/13 §7).
- name: Create or update the Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
run: |
set -euo pipefail
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
echo "Release $GITHUB_REF_NAME exists — re-uploading assets."
gh release upload "$GITHUB_REF_NAME" dist/*.zip dist/SHA256SUMS.txt --clobber
else
gh release create "$GITHUB_REF_NAME" dist/*.zip dist/SHA256SUMS.txt \
--verify-tag --generate-notes
fi
# --- Stores (docs/12 §3) -------------------------------------------------
#
# One job per store, so a store's credentials never share a runner with
# another's and one store refusing an upload does not stop the others. Each
# runs in a GitHub Environment that holds only its own secrets (give it the
# owner as required reviewer), is off until its repo VARIABLE is 'true' (a
# secret is not allowed in a job-level `if:`), and installs only
# tools/publish — publish-browser-extension and its three dependencies, from
# their own lockfile, scripts off — not the dev toolchain: a job's secrets
# are readable by everything on its runner. Never re-run a store job that
# succeeded: every store refuses a version number it has already seen.
# A sparse checkout of tools/publish still brings the repository's root files
# (cone mode), .nvmrc among them.
store-chrome:
name: Publish to Chrome Web Store
needs: publish
if: vars.CWS_AUTOPUBLISH == 'true'
runs-on: ubuntu-latest
timeout-minutes: 15
environment: chrome-web-store
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
sparse-checkout: tools/publish
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
- run: npm ci --ignore-scripts --prefix tools/publish
- uses: actions/download-artifact@v8
with:
name: release-${{ github.ref_name }}
path: dist
# Against the SHA256SUMS.txt of the published Release — not the copy that
# travelled in the same artifact — and by exact name, so a missing file
# fails here rather than passing a check that skipped it.
- name: Check against the published checksums
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
run: |
set -euo pipefail
VERSION="${GITHUB_REF_NAME#v}"
gh release download "$GITHUB_REF_NAME" --pattern SHA256SUMS.txt --dir published
cd dist
for file in "bookmarkmagic-${VERSION}-chrome.zip"; do
grep -F " $file" ../published/SHA256SUMS.txt | sha256sum -c -
done
- name: Submit
env:
# API v2: v1.1 was shut down on 2026-10-15. Set explicitly — the tool
# still defaults to v1.1.
CHROME_API_VERSION: v2
CHROME_PUBLISHER_ID: ${{ secrets.CHROME_PUBLISHER_ID }}
CHROME_EXTENSION_ID: ${{ secrets.CHROME_EXTENSION_ID }}
CHROME_SERVICE_ACCOUNT_CLIENT_EMAIL: ${{ secrets.CHROME_SERVICE_ACCOUNT_CLIENT_EMAIL }}
CHROME_SERVICE_ACCOUNT_PRIVATE_KEY: ${{ secrets.CHROME_SERVICE_ACCOUNT_PRIVATE_KEY }}
run: |
set -euo pipefail
./tools/publish/node_modules/.bin/publish-extension \
--chrome-zip "dist/bookmarkmagic-${GITHUB_REF_NAME#v}-chrome.zip"
store-firefox:
name: Publish to Firefox Add-ons
needs: publish
if: vars.AMO_AUTOPUBLISH == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
environment: firefox-add-ons
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
sparse-checkout: tools/publish
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
- run: npm ci --ignore-scripts --prefix tools/publish
- uses: actions/download-artifact@v8
with:
name: release-${{ github.ref_name }}
path: dist
# Against the SHA256SUMS.txt of the published Release — not the copy that
# travelled in the same artifact — and by exact name, so a missing file
# fails here rather than passing a check that skipped it.
- name: Check against the published checksums
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
run: |
set -euo pipefail
VERSION="${GITHUB_REF_NAME#v}"
gh release download "$GITHUB_REF_NAME" --pattern SHA256SUMS.txt --dir published
cd dist
for file in "bookmarkmagic-${VERSION}-firefox.zip" "bookmarkmagic-${VERSION}-sources.zip"; do
grep -F " $file" ../published/SHA256SUMS.txt | sha256sum -c -
done
- name: Submit
env:
FIREFOX_EXTENSION_ID: ${{ secrets.FIREFOX_EXTENSION_ID }}
FIREFOX_JWT_ISSUER: ${{ secrets.FIREFOX_JWT_ISSUER }}
FIREFOX_JWT_SECRET: ${{ secrets.FIREFOX_JWT_SECRET }}
FIREFOX_CHANNEL: listed
# Desktop only: Firefox for Android has no bookmarks API (docs/08 §9).
FIREFOX_COMPATIBILITY: firefox
run: |
set -euo pipefail
VERSION="${GITHUB_REF_NAME#v}"
./tools/publish/node_modules/.bin/publish-extension \
--firefox-zip "dist/bookmarkmagic-${VERSION}-firefox.zip" \
--firefox-sources-zip "dist/bookmarkmagic-${VERSION}-sources.zip"
store-edge:
name: Publish to Microsoft Edge Add-ons
needs: publish
if: vars.EDGE_AUTOPUBLISH == 'true'
runs-on: ubuntu-latest
timeout-minutes: 30
environment: edge-add-ons
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
sparse-checkout: tools/publish
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
- run: npm ci --ignore-scripts --prefix tools/publish
- uses: actions/download-artifact@v8
with:
name: release-${{ github.ref_name }}
path: dist
# Against the SHA256SUMS.txt of the published Release — not the copy that
# travelled in the same artifact — and by exact name, so a missing file
# fails here rather than passing a check that skipped it.
- name: Check against the published checksums
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
run: |
set -euo pipefail
VERSION="${GITHUB_REF_NAME#v}"
gh release download "$GITHUB_REF_NAME" --pattern SHA256SUMS.txt --dir published
cd dist
for file in "bookmarkmagic-${VERSION}-chrome.zip"; do
grep -F " $file" ../published/SHA256SUMS.txt | sha256sum -c -
done
- name: Submit
env:
# API v1.1 keys expire every 72 days (docs/12 §3).
EDGE_PRODUCT_ID: ${{ secrets.EDGE_PRODUCT_ID }}
EDGE_CLIENT_ID: ${{ secrets.EDGE_CLIENT_ID }}
EDGE_API_KEY: ${{ secrets.EDGE_API_KEY }}
run: |
set -euo pipefail
# Edge Add-ons takes the Chromium package unchanged (docs/08 §10).
./tools/publish/node_modules/.bin/publish-extension \
--edge-zip "dist/bookmarkmagic-${GITHUB_REF_NAME#v}-chrome.zip"
# A job INSIDE this workflow, not an `on: release: [published]` caller.
# A Release created by `gh release create` under the default GITHUB_TOKEN
# emits no event that starts new workflow runs, so an event-driven caller
# would silently never fire.
announce:
needs: publish
# A Discord notification is not part of the release, so it can never turn a
# good release red (docs/12 §2.3). Gated on a repo VARIABLE — GitHub REJECTS
# `continue-on-error` on a job that calls a reusable workflow, which makes
# the whole file a startup_failure with zero jobs and no log.
if: vars.DISCORD_ANNOUNCE == 'true'
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
with:
# REQUIRED here: the reusable resolves `TAG="${INPUT_TAG:-$EVENT_TAG}"`
# with EVENT_TAG = github.event.release.tag_name — empty under
# `on: push: tags` — so without this the job exits 1 and never announces.
tag_override: ${{ github.ref_name }}
# Named, not `inherit`: the reusable is pinned to a moving branch, so it gets
# only the two webhooks it reads — never the store or SONAR secrets. The
# names also differ: this repo stores RELEASES_WEBHOOK / REPO_WEBHOOK, while
# the reusable reads DISCORD_* — with `inherit` it received neither and would
# have failed on "No webhooks configured" the day DISCORD_ANNOUNCE was set.
secrets:
DISCORD_RELEASES_WEBHOOK: ${{ secrets.RELEASES_WEBHOOK }}
DISCORD_REPO_WEBHOOK: ${{ secrets.REPO_WEBHOOK }}
+115
View File
@@ -0,0 +1,115 @@
# SonarCloud — docs/12 §2.5.
#
# A separate workflow on purpose, not a job in ci.yml: a SonarCloud outage or a
# quality-gate opinion must never change the colour of CI, which is what branch
# protection reads ("Quality gates", "Build + package / build"). The verdict
# reaches the PR through the SonarCloud GitHub App's own check.
#
# Two jobs, so the token never shares a runner with dependency code. Secrets
# are loaded into the runner for the whole job, and a step can read them from
# the runner process whatever its own `env:` says — the shape of the March 2025
# tj-actions compromise. So `coverage` installs and runs the dev dependencies
# with no secret at all, and `scan` installs nothing: it gets the lcov report as
# an artifact.
#
# ⚠️ Prerequisite: Automatic Analysis is OFF in the SonarCloud project
# (Administration → Analysis Method). With it on, the scanner refuses to run.
name: SonarCloud
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
coverage:
name: Coverage for SonarCloud
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version-file: .nvmrc
cache: npm
# --ignore-scripts: no dependency gets to run code at install time. Our own
# postinstall (`wxt prepare`) is the one script we need, so it runs
# explicitly — from the local binary, never fetched on demand.
- run: npm ci --ignore-scripts
- run: npx --no-install wxt prepare
# lcov for Sonar; the docs/11 §1 thresholds still gate core here too.
- run: npm run coverage
# The lcov report, and the generated .wxt/ that tsconfig.json extends (it
# defines the `@/` alias), so the scan can resolve our own modules.
- uses: actions/upload-artifact@v7
with:
name: lcov
path: |
coverage/lcov.info
.wxt/
include-hidden-files: true
retention-days: 1
if-no-files-found: error
scan:
name: SonarCloud analysis
needs: coverage
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
steps:
- uses: actions/checkout@v7
with:
# Full history: Sonar's new-code detection and blame need it.
fetch-depth: 0
persist-credentials: false
- uses: actions/download-artifact@v8
with:
name: lcov
path: .
# No npm here: the runner's own Node reads one field of a JSON file.
- name: Read the package version
id: pkg
run: echo "version=$(node -p "require('./package.json').version")" >> "$GITHUB_OUTPUT"
# Dependabot and fork PRs get no repo secrets at all: they skip the scan
# with a notice instead of failing.
- name: Check for SONAR_TOKEN
id: token
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: |
if [ -n "$SONAR_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "::notice::SonarCloud scan skipped — SONAR_TOKEN is not available to this run (Dependabot or fork PR)."
fi
- name: SonarCloud scan
if: steps.token.outputs.present == 'true'
# Pinned to a commit, not a moving tag: this step holds a token. Dependabot
# proposes updates (with the repo's 7-day cooldown).
uses: SonarSource/sonarqube-scan-action@e805d875275f728fac1885b413934be6d7c63f65 # v8.4.1
env:
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
with:
args: >
-Dsonar.projectVersion=${{ steps.pkg.outputs.version }}
+94
View File
@@ -0,0 +1,94 @@
# Maintenance-mode triage — MAINTENANCE.md, docs/12 §2.6.
#
# scripts/triage.mjs decides (a pure, unit-tested function of the event); this
# file only carries the decision out with the `gh` CLI the runner ships. No
# third-party action holds the write token.
#
# Security, because `pull_request_target` runs with a write token even for a
# pull request from a fork:
# - the checkout is the DEFAULT BRANCH (what pull_request_target checks out
# unless told otherwise) — never the pull request's head, and nothing from
# the pull request is executed;
# - the payload reaches the script as the runner's event FILE; no title, body
# or label is ever interpolated into a shell line with `${{ }}`;
# - the decision the shell reads back is constants: an action from a fixed
# set, an integer, a label from a fixed list, a comment the script wrote.
name: Triage
on:
issues:
types: [opened, labeled]
pull_request_target:
types: [opened]
permissions: {}
# A new issue from the feature form fires `opened` and `labeled` together; one
# at a time per number, and the second re-reads the live state before acting.
concurrency:
group: triage-${{ github.event.issue.number || github.event.pull_request.number }}
cancel-in-progress: false
jobs:
triage:
name: Maintenance-mode triage
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
issues: write
pull-requests: write
steps:
# Pinned to commits, unlike the other workflows: these two run with a
# write token on events anyone can trigger, fork pull requests included.
# No `cache:` on setup-node — a cache written here could be read back by
# a job that trusts it.
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
- name: Decide
run: node scripts/triage.mjs > "$RUNNER_TEMP/decision.json"
- name: Act
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
run: |
set -euo pipefail
decision="$RUNNER_TEMP/decision.json"
action=$(jq -r '.action' "$decision")
echo "triage: $action — $(jq -r '.reason' "$decision")"
[ "$action" = none ] && exit 0
kind=$(jq -r '.kind' "$decision")
number=$(jq -r '.number' "$decision")
label=$(jq -r '.label' "$decision")
case "$kind" in issue|pr) ;; *) echo "::error::unexpected kind"; exit 1 ;; esac
[[ "$number" =~ ^[0-9]+$ ]] || { echo "::error::unexpected number"; exit 1; }
# Re-read the live state: the second of two events for one issue
# finds the first one's label and does nothing.
live=$(gh "$kind" view "$number" --json state,labels \
--jq '[.state] + [.labels[].name] | join(" ")')
case " $live " in
*" maintenance-mode "*|*" needs-triage "*|*" roadmap "*)
echo "already triaged: $live"; exit 0 ;;
esac
case "$live" in OPEN*) ;; *) echo "not open: $live"; exit 0 ;; esac
# Comment and close FIRST, label last: the label is what a re-run
# reads as "done", so it must not exist before the work it stands for.
if [ "$action" = close ]; then
jq -r '.comment' "$decision" > "$RUNNER_TEMP/comment.md"
gh "$kind" comment "$number" --body-file "$RUNNER_TEMP/comment.md"
if [ "$kind" = issue ]; then
gh issue close "$number" --reason "not planned"
else
gh pr close "$number"
fi
fi
gh "$kind" edit "$number" --add-label "$label"
+8 -4
View File
@@ -7,10 +7,14 @@ node_modules/
stats.html
stats-*.json
# Test / coverage
# Test / coverage (Vitest 5 writes reporter output under .vitest/)
coverage/
.vitest/
*.tsbuildinfo
# WXT runner config — holds local browser paths, never shared
web-ext.config.ts
# Editors
.idea/
.vs/
@@ -33,8 +37,8 @@ npm-debug.log*
.env.local
.env.*.local
# Generated fixtures that are too big to commit (tests/fixtures/generate-huge.ts
# writes here on demand — docs/11 §2)
# Generated fixtures that are too big to commit (scripts/gen-fixture.mjs writes
# here on demand — docs/11 §2)
tests/fixtures/generated/
.claude/
.claude/
+6
View File
@@ -0,0 +1,6 @@
# Supply-chain cooldown (docs/01 §6): resolve every install to the newest
# release that has been public for at least 7 days. Malicious versions
# published to npm have historically been caught and pulled within hours to
# days; a week of age keeps this repo out of that window. Units are DAYS.
# Dependabot applies the same rule through `cooldown` in dependabot.yml.
min-release-age=7
+1 -1
View File
@@ -1 +1 @@
24
26
+259
View File
@@ -0,0 +1,259 @@
# Accessibility
BookmarkMagic should be usable by anyone who has bookmarks to move — with a
keyboard and no mouse, with a screen reader, with a contrast theme, with the
page zoomed, or with animation switched off. This file says what that means
today: what the goal is, what has actually been tested, what is known not to
work well yet, and how to tell us about a barrier.
**Last reviewed:** 2026-11-18, for version 1.3.0.
## The goal
The target is the [Web Content Accessibility Guidelines (WCAG) 2.2](https://www.w3.org/TR/WCAG22/)
at **Level AA**.
That is a goal, not a claim. BookmarkMagic has not been audited by an
accessibility specialist, and it does not claim to conform to WCAG. It is
built and tested by one person, and the testing that has been done is listed
below so you can judge it for yourself.
The priorities, in order:
1. **Everything works from the keyboard.** No task needs a mouse.
2. **A screen reader is told what is on screen and what just happened** —
names, roles, states, and the result of an import.
3. **Nothing depends on colour, motion or a pointer's precision alone.**
4. **Every shipped language is treated the same** — English, Tiếng Việt, 日本語,
简体中文 and Română. The page's language is declared to the browser, so a
screen reader picks the right voice.
## Supported environments
| Environment | Status |
|---|---|
| Chrome 136 or later on Windows | Supported, and where the testing below was done |
| Chrome 136 or later on macOS, Linux and ChromeOS | Supported; expected to work the same, not tested for accessibility |
| Edge, Brave, Vivaldi and Opera (the same package as Chrome) | Best effort — the extension runs there, and accessibility is untested |
| Firefox 140 or later on the desktop (since 1.3.0, its own package) | Best effort — the extension runs there, and accessibility is untested |
| Chrome on Android or iOS | Not applicable: Chrome there does not run extensions |
| Firefox for Android | Not applicable: it has no bookmarks API for extensions |
## What is in place
### Keyboard
Every control is either a tab stop or has a key of its own, and every dialog
can be closed with Esc. Focus shows as a 2-pixel ring on controls; inside the
bookmark tree, the current row is marked by a highlight and a bar at its left
edge.
The bookmark tree on the **Edit** tab is a single tab stop. Inside it:
| Key | What it does |
|---|---|
| ↑ / ↓ | Move to the previous or next row |
| Home / End | Move to the first or last row |
| → | Open a closed folder, or step into an open one |
| ← | Close an open folder, or step out to its parent |
| A letter or digit | Jump to the next row whose title starts with it |
| Enter | Open a bookmark in a new tab; open or close a folder |
| F2 | Rename (Enter saves, Esc cancels) |
| Delete (Fn+Delete on a Mac laptop) | Delete, after a confirmation |
| Menu key, or Shift+F10 | **Move to…** — pick a destination folder from a filterable list |
| Alt+↑ / Alt+↓ | Move the row up or down one place inside its folder |
| Ctrl+C (⌘C on macOS) | Copy the focused bookmark's address |
| Ctrl+F (⌘F on macOS) | Go to the search box, from anywhere on the Edit tab |
The small buttons that appear on a row are shortcuts for the mouse, and are
deliberately not tab stops: Open, Copy link, Rename, Move to… and Delete each
have a key in the table above, and Sort A→Z is also a button on the toolbar.
Alt+↑ and Alt+↓ move a row past the neighbour you can see. While a search is
filtering the tree, that also carries it past any hidden items in between.
Elsewhere: the theme control is a radio group (arrow keys change the choice),
the file drop zone is a button that opens the file picker, and the folder
lists in the import preview and the export picker are ordinary lists with
buttons and checkboxes — Tab, Enter and Space.
### Screen readers
- The Edit tree is an ARIA tree: each row announces its name, its level, its
position ("3 of 12") and whether it is expanded.
- Dialogs are native `<dialog>` elements. Focus moves in when one opens and
returns when it closes; a confirmation reads its title and its body, and
opens with **Cancel** focused, so Enter never confirms a deletion.
- An import is spoken as it goes: reading the file, backing up, writing,
progress every 10 %, and the result. Failures are announced as alerts.
- Moving a row with Alt+↑ or Alt+↓ announces its new position ("Docs:
position 2 of 5"). This is new in 1.2.1 and has not yet been checked with a
screen reader — see "What has been tested".
- When an import moves to its next step, focus moves to that step's heading.
When a page change removes the control that had focus, focus moves to the
page's main content rather than back to the top of the page.
- Every icon-only button has a name. Icons themselves are hidden from
assistive technology.
- The page title names the current section, and the page's language follows
the language you chose.
### Seeing the page
- **Contrast.** Text is at least 4.5:1 against its background, and control
borders and the focus ring at least 3:1, in the light and the dark theme. A
test fails the build if a colour pair drops below that.
- **Contrast themes** (Windows "Contrast themes", `forced-colors`). Since
1.2.1, the states that were shown only by a fill or a shadow — the focused
row, where a dragged item will land, the selected theme, the current
section, the selected option cards, the progress bar, the edge of the file
drop zone — are drawn with the theme's own colours instead.
- **Zoom.** The layout reflows as the window narrows or the page is zoomed.
- **Light and dark** themes follow the system, or your choice in Settings.
- **Disabled buttons** are marked by colour and cursor, never by fading the
text until it cannot be read. (Two kinds of button are an exception; see
the limitations.)
- **Target size.** Since 1.2.1, every button is at least 24 × 24 CSS pixels,
including the small icon buttons. Checkboxes, radio buttons and links in
text keep their natural size; their labels are part of the target.
### Motion
If your system asks for reduced motion, nothing moves: no sliding, spinning or
travelling stripes. A test fails the build if an animation is added outside
that rule. Nothing flashes. An error message stays until you dismiss it;
short confirmations leave by themselves after four seconds (see the
limitations below).
## What has been tested
| Check | With | When |
|---|---|---|
| Keyboard only, mouse unplugged | Chrome on Windows 11 | November 2026, version 1.2.0 |
| Screen reader | **Narrator** with Chrome on Windows 11 | November 2026, version 1.2.0 |
| Contrast themes | Chrome with `forced-colors` emulated — not yet a real Windows theme | November 2026, version 1.2.1 |
| What 1.2.1 changed: focus, Alt+↑/↓, button sizes | A scripted keyboard run in Chrome — no screen reader | November 2026, version 1.2.1 |
| Colour contrast of the theme colours, reduced motion, the tree's key handling | Automated tests, on every change | Continuous |
**Not tested**, so we cannot tell you how well they work: anything in Firefox
or Edge; anything on macOS, Linux or ChromeOS; NVDA, JAWS, VoiceOver, ChromeVox and Orca; voice control
(Dragon, Voice Access, Voice Control); switch access; screen magnifiers; and
zoom at 200 %. Narrator has not yet been run over what 1.2.1 added.
If you use one of these, a report of what you found — good or bad — is
genuinely useful.
## Known limitations
These are known, and none of them is by design.
- **Most edits are not announced.** Alt+↑/↓ announces the result; a rename, a
move to another folder, a sort and a new folder succeed silently. Search
does not announce how many rows match. A key that cannot act — Alt+↑ on the
first item of a folder, Delete on one of the three top-level folders — does
nothing and says nothing.
- **Folders and bookmarks sound alike in the tree.** They differ by an icon a
screen reader does not read. A folder with something in it announces
"expanded" or "collapsed"; an empty folder announces neither. The lock on a
bookmark your organisation manages is also only an icon, and a folder's
item count is read as a bare number.
- **A focused row may read out its buttons** ("Open, Copy link, Rename…")
after its name. It is noisy, not broken.
- **Reordering with a pointer needs a drag.** There is a keyboard way
(Alt+↑/↓) and Sort A→Z, but no click-only way to place one item before
another.
- **Separators in Firefox are only drawn.** A line in a Firefox folder is
shown in the tree, but a screen reader is not told it is there, and the
"position n of m" counts bookmarks and folders only — so Alt+↑ or Alt+↓ past
a separator moves the row without changing the position you hear.
- **Alt+↑/↓ may not reach the page on a Chromebook**, where the system can turn
those keys into Page Up and Page Down. On a Mac there is no Menu key (use
Shift+F10), and the laptop's delete key is Backspace, which the tree does
not act on (use Fn+Delete).
- **The tree's keys are not shown inside the extension**, apart from Ctrl+F on
the search box. The table above is the list; the About tab links to this
file.
- **The toolbar above the tree is announced as a toolbar**, but its buttons are
reached with Tab, not with the arrow keys a toolbar usually offers.
- **Some hints appear only on mouse hover**: the notes in the status bar, where
a top-level folder of an imported file will go, and the reason a section is
unavailable while an import is writing.
- **A section that is unavailable while an import is writing looks the same as
one that is available**; only the cursor and the hover hint differ. The same
goes for a tree row's small buttons while a sort or a bulk delete is
running. A screen reader does announce both as unavailable.
- **Long titles are cut short with "…"** in the tree, and there is no way to
read the whole title there other than renaming (F2).
- **Headings are sparse.** Sections are landmarks, but the pages have few
headings to jump between, and there is no "skip to content" link past the
header's controls.
- **Descriptions in Settings are not tied to their controls**, so a screen
reader reads the control's name but not the sentence under it.
- **Short notices disappear after four seconds** ("Saved", "Link copied",
the name of an exported file). They are announced, but they cannot be
paused. An error stays, though a second error replaces the first.
- **Text size follows zoom, not the browser's font-size setting.** Use
Ctrl and + to enlarge the page.
- **On the Edit tab, Ctrl+F always goes to BookmarkMagic's own search box**
rather than the browser's Find.
- **The Japanese, Chinese and Romanian translations have not been reviewed by
native speakers**, which includes the text a screen reader speaks.
## Reporting a barrier
If something stops you, or just gets in your way, please say so. An
accessibility report is treated as a defect, not a feature request.
- **With a GitHub account:** open an
[accessibility report](https://github.com/poli0981/bookmarkmagic/issues/new?template=accessibility.yml).
- **Without one:** write to **accessibility@poli0981.dev**.
It helps to include:
- what you were trying to do, and what happened instead;
- the BookmarkMagic version (About tab, `chrome://extensions`, or
`about:addons` in Firefox);
- your browser and operating system;
- the assistive technology you use and its version, if any — a screen reader,
a contrast theme, zoom level, voice control;
- how badly it gets in the way: **blocked** (you could not finish),
**hard** (you finished, with a workaround), or **annoying**.
You do not need to explain why you use the tools you use, and nobody will ask.
**Please do not send your real bookmarks file**, and check a screenshot or a
recording for bookmark titles before attaching it — your bookmarks are your
browsing history. [`CONTRIBUTING.md`](CONTRIBUTING.md) explains how to
sanitize a file if a particular one is needed.
### What happens next
BookmarkMagic has one maintainer, so these are honest intentions rather than
guarantees:
- A report is acknowledged within about a week.
- A **blocking** barrier is fixed ahead of other work and shipped in its own
patch release; your browser then updates installed copies by itself,
usually within days of the store's review.
- Anything else is scheduled, and added to the list above until it is fixed,
so the next person can see it is known.
- If a fix is not possible or not planned, you will be told why.
- When a fix ships, you will be asked whether it actually works for you. Your
answer counts for more than our test.
## For contributors
A change to the interface has to keep the above true.
[`CONTRIBUTING.md`](CONTRIBUTING.md) and the pull-request checklist list what
to check: keyboard, visible focus, names and labels, no meaning carried by
colour alone, reduced motion, contrast themes, and one pass with a screen
reader. The specification behind this statement is
[`docs/06_UI.md` §5](docs/06_UI.md); if a change makes this file wrong, the
same pull request has to correct it.
## Who is responsible
The maintainer, [@poli0981](https://github.com/poli0981), triages
accessibility reports, keeps the limitations list current, and reviews this
statement at every release.
Suggestions for the statement itself are welcome the same way as any other
report.
+63
View File
@@ -0,0 +1,63 @@
# Building BookmarkMagic from source
How to rebuild the packages attached to each
[GitHub Release](https://github.com/poli0981/bookmarkmagic/releases) — for
Firefox Add-ons reviewers, who must be able to reproduce the submitted package
from its sources, and for anyone who wants to check that a store build matches
this repository.
## Requirements
| Tool | Version | Where |
|---|---|---|
| Node.js | **26** (the version in `.nvmrc`; tested with 26.13) | <https://nodejs.org/en/download> |
| npm | the one bundled with Node.js 26 (11.x) | ships with Node.js |
| OS | any — Windows 11, macOS and Ubuntu all build the same files | |
No other tool, account, network service or environment variable is needed
beyond what `npm ci` installs from `package-lock.json`.
> **The Firefox sources archive omits dotfiles**, so `.nvmrc` and `.npmrc` are
> not in it. Use Node.js 26: an older Node may install but is not what the
> package was built with, and `package.json` says `"engines": { "node": ">=26" }`.
## Steps
```bash
npm ci # exactly the versions in package-lock.json
npm run zip:firefox # the Firefox package (and a sources archive)
npm run zip # the Chromium package (Chrome Web Store, Edge Add-ons)
```
`npm ci` runs one install script of this project's own, `wxt prepare`, which
generates the TypeScript configuration the build reads. (CI installs with
`--ignore-scripts` and runs `npx --no-install wxt prepare` itself; the result
is the same.)
## Output
| Command | Unpacked build | Package |
|---|---|---|
| `npm run zip:firefox` | `.output/firefox-mv3/` | `.output/bookmarkmagic-<version>-firefox.zip` |
| `npm run zip` | `.output/chrome-mv3/` | `.output/bookmarkmagic-<version>-chrome.zip` |
Compare the **files inside** the package with the submitted one, not the
archives themselves: a zip records file times, so two builds of the same
commit hash differently while every entry is identical (`docs/09 §5`).
## What the build does
- [WXT](https://wxt.dev) bundles `src/` with Vite into plain JavaScript, CSS
and HTML. The code is **minified, not obfuscated**.
- The only third-party code compiled in is the Svelte runtime, its `clsx`
helper and WXT's one-line browser shim, all MIT
([`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md)); the build
fails if anything else would ship.
- Nothing is downloaded at build time beyond `npm ci`, and the built extension
makes no network requests at all — its content security policy forbids them
([`docs/08_MV3_COMPLIANCE.md`](docs/08_MV3_COMPLIANCE.md) §3).
To check a build the way CI does: `npm run check:manifest` (Chromium) and
`npm run check:manifest -- --browser firefox` (Firefox) verify the manifest,
the permissions, the CSP, the file inventory and that no network API is in the
bundle.
+362
View File
@@ -0,0 +1,362 @@
# Changelog
All notable changes to BookmarkMagic are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
Per `docs/12 §4`: **patch** = fixes and translation fixes · **minor** =
features, a new UI language, and any change to the permission list or the
store privacy tab · **major** = breaking format or schema changes (a BM JSON
version bump).
## [Unreleased]
Nothing yet.
## [1.3.0] — 2026-11-18
Firefox and Microsoft Edge, and maintenance mode. Permissions are unchanged
(`bookmarks` and `storage`), nothing is asked of you again, and on Chrome
there is nothing to do — your browser updates itself. This version also
carries everything listed under 1.2.1, which never reached the Chrome Web
Store on its own.
### Added
- **Firefox** (desktop, 140 or later), with a package of its own for Firefox
Add-ons — listing to come. The same features, the same two permissions and
the same no-network policy, which Firefox enforces just as Chrome does.
Firefox's **Bookmarks Menu** is a root like the others: Merge and Replace put
entries back where they came from. Whatever a file leaves loose at its top
level goes into the menu, as Firefox's own import does — the menu itself in
a Firefox export, but also Other's and Mobile's contents in Chrome's own
HTML export, which Chrome writes loose. BookmarkMagic's exports and backups
name every root and are not affected.
- **Microsoft Edge Add-ons** — the Chrome package, unchanged; listing to come.
Until then Edge installs from the Chrome Web Store.
- **Firefox separators** show in the Edit tab as lines. Nothing acts on them:
they are not focused, searched, counted, sorted across, or offered as
duplicates of each other. Sort A→Z sorts each run between two separators on
its own.
- Replace on Firefox says how many separators it will delete — no file
BookmarkMagic writes can keep one, so they do not come back with the backup.
- An import says how many separators the file held, and on Firefox skips — and
counts — any address longer than the 65,536 characters Firefox accepts,
before anything is written.
### Changed
- The About tab's store link is now **"Store listing"** and opens the store
your copy came from: the Chrome Web Store for the Chrome Web Store's copy,
Firefox Add-ons in Firefox, and otherwise the README's list of stores.
- Sentences that blamed Chrome for what every browser does now say "the
browser" — "The browser does not let an extension set a bookmark's original
date" — in all five languages; the note about skipped Firefox smart
bookmarks no longer calls them dead links.
- Copy diagnostics names the browser and its version (`"browser": "Firefox
160"`) instead of only Chrome's.
- The project is in **maintenance mode** ([`MAINTENANCE.md`](MAINTENANCE.md)):
fixes, accessibility, translations, security and dependency updates, and
features that are already on the roadmap.
### Fixed
- Since 1.1.0, in a Chrome signed in with account bookmarks (Chrome 134 or
later), Replace's confirmation counted the account's own bar, Other and
Mobile among what it would delete. Replace has never touched them; the count
now covers exactly what it deletes.
### Packages
Each GitHub Release now carries three files: `…-chrome.zip` (the Chrome Web
Store and Edge Add-ons), `…-firefox.zip` and `…-sources.zip` (what Firefox
Add-ons reviews), with `SHA256SUMS.txt` over all three. [`BUILD.md`](BUILD.md)
explains how to rebuild them.
## [1.2.1] — 2026-11-10
Accessibility. Permissions are unchanged (`bookmarks` and `storage`), nothing
is asked of you again, and there is nothing to do — Chrome updates itself.
### Added
- **An accessibility statement**,
[`ACCESSIBILITY.md`](ACCESSIBILITY.md): what works with a keyboard and a
screen reader, what was tested and with what, what is known not to work
well yet, every key the Edit tree understands, and how to report a barrier.
About links to it.
- **Reorder with the keyboard.** On the Edit tab, **Alt+↑** and **Alt+↓** move
the focused bookmark or folder one place up or down inside its folder — until
now only a drag could do that. The new position is announced for screen
readers (not yet checked with one).
- **Windows contrast themes.** The focused row, the line that shows where a
dragged item will land, the selected theme, the current section, the
selected import mode and export format, the progress bar and the drop zone's
outline are now drawn in the theme's own colours; before, they disappeared.
Checked with Chrome's emulation so far, not yet with a real theme.
### Fixed
- The theme switch showed no focus ring: it was drawn in the same colour as
the button under it.
- Keyboard focus is no longer thrown back to the top of the page after "Open
in Edit", after "Keep the first of each", or after sorting a folder from the
toolbar.
- Clicking a row's button or its arrow no longer stops the arrow keys from
working in the tree.
- Clicking a row in a long, scrolled tree no longer jumps the tree back to the
top.
- Small buttons — the ones on a tree row, the folder arrows, the close buttons
on dialogs and notices, the popup's gear, "Show more" — are at least
24 × 24 pixels to click or tap.
- The focus ring was cut off on "Show earlier / Show more" in the tree and on
the folders in "Move to…"; the selected theme lost its label on hover; and
the search box's placeholder text was fainter than the rest.
### Notes
- The goal is WCAG 2.2 AA; it is a goal, not a claim — nobody has audited the
extension. If something is hard or impossible to use, the "Something is hard
or impossible to use" form on GitHub, or accessibility@poli0981.dev, reaches
the maintainer.
- The two new pieces of text are best-effort in Japanese, Chinese and Romanian,
like the rest of those translations.
## [1.2.0] — 2026-11-06
Two new languages. Permissions are unchanged (`bookmarks` and `storage`), and
there is nothing to do — Chrome updates itself.
### Added
- **简体中文 (Simplified Chinese)** and **Română (Romanian)**, in the extension
and in its name and description in `chrome://extensions`. Pick one under
Settings → Language, or leave it on Automatic.
- Romanian counts read the way Romanian does: "1 marcaj", "5 marcaje",
"20 de marcaje".
- Sort A→Z follows the language you use: pinyin order in Chinese, and `ș`/`ț`
as letters of their own in Romanian.
### Changed
- **If your browser is set to Simplified Chinese or Romanian and the language
setting is Automatic** (the default), BookmarkMagic switches from English to
that language after this update. A browser in Traditional Chinese stays in
English; 简体中文 can still be chosen by hand.
### Notes
- Both translations are best-effort, written from Chrome's own wording in each
language but not yet read by a native speaker. If something reads wrong,
the translation form on GitHub takes a sentence — no code needed.
## [1.1.0] — 2026-10-29
New import formats, a Merge that really merges, restores that put everything
back where it was, Sort A→Z, drag to reorder, and a new look. Permissions are
unchanged (`bookmarks` and `storage`), and nothing to do — Chrome updates
itself. **Needs Chrome 136 or later.**
### Added
- Import Chrome's own `Bookmarks` file — the JSON file in your profile folder,
which has no extension — and Firefox's JSON backups
(`bookmarks-YYYY-MM-DD.json`). Both still know which bookmarks were in
"Mobile bookmarks", which the browsers' own HTML exports throw away.
- **Sort A→Z** for any folder: folders first, then bookmarks, in natural order
("Item 2" before "Item 10"). It tells you how many items will move before
doing anything.
- **Drag to reorder**: drop above or below a row to place an item exactly
there, or onto a folder to move it inside.
- A new look: clearer panels, a status bar, readable numbers, and icons that
move a little — never if your system asks for reduced motion.
- **Copy diagnostics** in the About tab: a short log of what the tab did
(error codes and counts — never titles or addresses) to paste into a bug
report. It stays on your computer unless you paste it somewhere.
- The import preview marks which folders go straight into the Bookmarks bar,
Other or Mobile bookmarks, and names the format it detected.
### Changed
- **Requires Chrome 136 or later** (was 120). Older Chrome keeps version 1.0.1.
- Chrome itself now enforces that the extension makes no network requests: a
stricter content security policy refuses any connection, remote image, font
or frame an extension page might try. Nothing it did before needed one.
- "Merge into existing folders" now really merges: a folder you already have is
reused and the new bookmarks are added at the end of it. Before, every folder
in the file was created again beside yours.
- "Replace everything" restores a file exactly, duplicate links included — the
"skip duplicates" box never applied to it, and now it really does not.
- Firefox "smart bookmarks" (saved searches, `place:` links) in browser HTML
exports are skipped and counted: in Chrome they are dead links. BookmarkMagic's
own JSON and CSV files keep them.
- A bookmark with an empty title stays untitled after import, instead of taking
its address as the title.
- The safety backup taken before "Replace everything" is compact JSON — about
half the size.
- The file picker shows every file; BookmarkMagic recognises the format from
the content.
- "Replace everything" now asks first, showing exactly how many bookmarks and
folders will be deleted and how many will be written.
- The import button counts what will really be imported (duplicates you chose
to skip are not counted), and the report lists bookmarks and folders
separately, what was skipped, which existing folders were reused, and where
everything went.
- Error messages stay on screen until you dismiss them.
- The popup opens an already-open manager on the page you clicked, and its
folder count no longer includes the three built-in root folders.
- Very large folders and trees show 500 rows at a time, with "Show more" (and
"Show earlier" in the edit tree), so expanding everything no longer freezes
the tab.
- Two manager tabs can no longer write bookmarks at the same time — the second
one is told to wait, and nothing is changed.
### Fixed
- Restoring a backup put "Other bookmarks" and "Mobile bookmarks" inside Other
Bookmarks — one level deeper on every restore. They now go back where they
were, and backups made by 1.0.x are recognised and restored correctly too.
- One address Chrome refuses no longer stops an import half-way — after
"Replace everything" had already deleted your bookmarks. Such entries are now
skipped before anything is written, and the preview says how many.
- "Replace everything" now refuses to start when your current bookmarks are too
large for a backup BookmarkMagic could read back, instead of writing that
backup and deleting everything anyway.
- Some bookmark files silently lost entries: a folder list after a loose
bookmark, everything after a title containing an unescaped `<b>`, and lists
wrapped in other markup. Anything that still cannot be read is now counted.
- A folder marked `PERSONAL_TOOLBAR_FOLDER="false"` is no longer taken for the
Bookmarks Bar.
- A CSV file with an unclosed quote is reported with its line number, instead of
one cell swallowing the rest of the file.
- CSV exports no longer contain cells a spreadsheet would run as a formula; the
guard character is removed again when the file is imported.
- Titles in Markdown exports can no longer turn into links, HTML or broken
lines.
- A link ending in a bare `?` or `#` is recognised as a duplicate of the same
link without it.
- "Replace everything" re-checks your bookmarks after the safety backup is
saved, and re-saves it if something changed meanwhile (sync, another window),
so nothing can be deleted that the backup does not hold. It never empties the
bookmarks stored in your Google Account, and restoring a backup puts Mobile
bookmarks back in "Mobile bookmarks" even when that folder was empty.
- Imports that would nest folders deeper than Chrome can reliably store are
refused up front instead of being written.
- Keyboard: "Move to…" is now a real dialog that keyboard focus enters and
leaves properly, with a filter; the menu key or Shift+F10 opens it from the
tree, and Ctrl+C copies the focused link. Cancelling a drag no longer leaves
rows highlighted. Pressing Esc while renaming no longer saves the new name.
- The edit tree no longer collapses or loses your place after a failed edit,
and focus moves to the next row after a delete.
- Renaming from the keyboard works: F2 and New folder put the cursor in the
name box, and Enter or Esc returns you to the tree. A folder created while
searching no longer disappears and locks the keyboard.
- The edit tree keeps your place when the row you were on is collapsed, moved
or deleted elsewhere — focus goes to the nearest folder still on screen —
and a folder you close during a search stays closed.
- While a sort or a duplicate clean-up runs, the other edit actions wait for
it, instead of starting and failing with misleading messages.
- End and type-ahead on a very large tree no longer freeze the tab.
- An error message no longer holds back the messages after it.
- The import preview shows its "new" and "dup" badges again. Keyboard and
screen-reader users now land on each step of an import, and hear how it
ended.
- Dialogs name their close button "Dismiss", and screen readers read the
confirmation's details with its title. After a delete, keyboard focus goes
back to the tree or the duplicate panel instead of the top of the page.
- At narrow widths the edit toolbar wraps instead of pushing the page sideways,
and titles keep their room before the domain beside them.
- Wording: an untitled item is named by its address in dialogs, plurals read
correctly ("1 extra copy", "Show 1 more row"), and the Japanese text spells
ブラウザ and フォルダ one way throughout.
- The header logo's animation stops after two pulses instead of running
forever, and the popup now switches only the Manager tab it brings forward.
- The About tab and the third-party notices now name the small MIT-licensed
pieces the build has always compiled in (the Svelte runtime with its `clsx`
helper, and WXT's browser shim), instead of saying there were none.
## [1.0.1] — 2026-08-03
Released and submitted 2026-08-03; live on the Chrome Web Store (confirmed on
the listing 2026-10-28).
Stabilization, from the first pass over the shipped extension. No new features,
no change to permissions, and nothing you have to do — Chrome updates itself.
### Fixed
- If the browser refuses part of an import, the report now says how many
bookmarks were actually created, and — after a "replace everything" — names
the safety backup so you can restore. It used to say only that something went
wrong, while the items it had already written sat in your tree uncounted.
- Cancelling a "replace everything" after the deletion had begun said only how
many items were created, on a browser that was nearly empty. It now says what
happened and points at your backup.
- The import screen no longer offers a backup filename in the cases where no
backup was written.
- Pressing the browser's Back button during an import used to leave the manager
permanently stuck — every tab disabled, and no way out but closing it.
Navigation is now refused while an import is running, with an explanation.
- Two manager tabs no longer overwrite each other's settings, and accepting the
terms in one tab now unlocks the other.
- Errors in the Edit and Export tabs appear in your own language again, with the
browser's own message kept separately for bug reports.
- Clearing the search box no longer leaves every folder it opened expanded, and
collapsing a folder while searching now stays collapsed.
- "Keep the first of each" no longer offers to delete bookmarks managed by your
organisation, which the browser always refused, and says how many copies it
removed if it stops early.
- A profile with no writable bookmark folder now says so, instead of reporting a
refused operation.
### Added
- The import screen states that imported bookmarks carry today's date — the
browser does not let an extension set the original one. Your exported files
still keep the real dates.
- A link to the Chrome Web Store listing in the About tab.
- Bug-report forms, a contributing guide, and `scripts/sanitize-bookmarks.mjs`,
which strips every address and title from a bookmark file while keeping the
structure a parsing bug depends on — so a sample can be attached to a public
issue without publishing your browsing history.
## [1.0.0] — 2026-07-26
First public release. Approved by the Chrome Web Store and available to install
from 2026-08-03.
### Added
- Import bookmark files (Netscape HTML, BookmarkMagic JSON, CSV) with a full
preview — counts, folder depth, duplicates and warnings — before anything is
written.
- Three import modes: into a new dated folder (the default), merge into
existing folders, or replace everything. Replace downloads a JSON safety
backup first and deletes nothing until that backup is proven.
- Skip bookmarks whose URL already exists in this browser.
- Export everything, or just the folders you pick, to HTML, JSON, CSV or
Markdown.
- Edit the bookmark tree: search, rename, create folders, delete, drag & drop,
a keyboard "Move to…" with full parity, and a duplicate-finder panel.
- English, Vietnamese and Japanese, switchable in Settings independently of the
browser's own language.
- Light, dark and system themes.
- A first-run legal gate covering the EULA, licence, disclaimer and privacy
policy.
### Security
- Imported URLs are never rendered as links. Opening one goes through an
`http(s)`-only allowlist, so a `javascript:` or `data:` bookmark in a crafted
file cannot be activated from the extension.
- Parsing is bounded: 25 MB per file, 100 000 nodes, 200 levels of nesting.
- No network access of any kind at runtime, enforced by a grep gate in CI.
[Unreleased]: https://github.com/poli0981/bookmarkmagic/compare/v1.3.0...HEAD
[1.3.0]: https://github.com/poli0981/bookmarkmagic/compare/v1.2.1...v1.3.0
[1.2.1]: https://github.com/poli0981/bookmarkmagic/compare/v1.2.0...v1.2.1
[1.2.0]: https://github.com/poli0981/bookmarkmagic/compare/v1.1.0...v1.2.0
[1.1.0]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.1...v1.1.0
[1.0.1]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.0...v1.0.1
[1.0.0]: https://github.com/poli0981/bookmarkmagic/releases/tag/v1.0.0
+166 -8
View File
@@ -1,9 +1,34 @@
# CLAUDE.md — Build Instructions (BookmarkMagic)
You are building a Chrome MV3 extension: offline bookmark import/export/edit.
A Chrome MV3 extension: offline bookmark import/export/edit.
This file is the entry point; the `docs/` suite is the specification.
**When code and docs disagree, docs win — or stop and ask.**
> ## ⚠️ This is shipped software
>
> **BookmarkMagic is published on the Chrome Web Store and has real users**
> (v1.0.0 live by 2026-08-03; v1.0.1 live, confirmed on the listing
> 2026-10-28; v1.1.0 live, confirmed on the listing 2026-11-06; v1.2.0 live,
> confirmed on the listing 2026-11-10; v1.2.1 released on GitHub 2026-11-10,
> ⚠️ not yet submitted).
> Phases 0–9 are complete; since 2026-11-18 the project is in **maintenance
> mode** — `/MAINTENANCE.md` is the policy (Phase 10 below).
> That changes the rules of the game:
>
> - **New work must fit `/MAINTENANCE.md`**: dependency and security updates,
> major platform upgrades, bug/UI/UX/accessibility/translation fixes, and
> features only when they are on `docs/15`'s roadmap or genuinely needed. A
> feature that is not on the roadmap needs a decision-log row before code.
> - Every change now reaches installed users through a store review. It needs a
> semver bump, a `CHANGELOG.md` entry and an update submission — `13 §1b`.
> - Breaking something is no longer a local cost. The 1.0.0 → 1.0.x **upgrade
> over an existing profile** (`11 §5`) is the one test whose failure hits
> every user at once.
> - Bumping `LEGAL_VERSION` re-shows the first-run gate to **everybody**. It is
> a deliberate, documented act (`14 §2`), never a side effect.
> - Read `docs/15`'s build-progress table and decision log before planning
> anything; `docs/00 §10` is the live open-items list.
## Doc index (read 00–02 fully before writing any code)
| Doc | Contents |
@@ -14,7 +39,7 @@ This file is the entry point; the `docs/` suite is the specification.
| docs/03_DATA_FLOW.md | Import/export/edit pipelines, state machine |
| docs/04_FILE_FORMATS.md | Netscape HTML / BM JSON / CSV / Markdown specs |
| docs/05_ALGORITHMS.md | Parser walk, normalize, dedupe, diff, write queue |
| docs/06_UI.md | Tokens, layouts per tab, component inventory, a11y |
| docs/06_UI.md | Tokens, layouts per tab, component inventory, a11y (§5 is the spec behind `/ACCESSIBILITY.md`) |
| docs/07_I18N.md | chrome.i18n vs runtime store split, EN/VI/JA rules |
| docs/08_MV3_COMPLIANCE.md | Manifest, permissions (bookmarks+storage ONLY), CWS rules |
| docs/09_SECURITY_PRIVACY.md | Threat model T1–T8, secure-coding bans |
@@ -33,11 +58,17 @@ This file is the entry point; the `docs/` suite is the specification.
The canonical gate is docs/08 §3, run as `npm run guard`.
4. `src/lib/core/` never imports browser APIs, Svelte, or `src/lib/browser`.
5. Files ≤300 lines (hard 500); functions ≤50 (hard 80).
6. Every string user-visible ⇒ i18n key in en+vi+ja (en is schema; vi/ja
`satisfies Dict`, where `Dict = typeof dict` is exported from
`locales/en.ts`). **Never `as const` on a locale file** — docs/07 §2.
6. Every string user-visible ⇒ i18n key in **every shipped locale** — `LOCALES`
in `src/lib/i18n/resolve-locale.ts`: en, vi, ja, zh-CN, ro (en is schema;
the others `satisfies Dict`, where `Dict = Localized<typeof dict>` is
exported from `locales/en.ts`). **Never `as const` on a locale file** —
docs/07 §2. Romanian plural keys carry a third form, `few` (docs/07 §5).
7. TypeScript strict; no `any`; casts need `// SAFETY:` comments.
8. Conventional Commits; `npm run verify` green before every commit.
8. Conventional Commits; `npm run verify` green before every commit — and
**`npm run verify:full` before anything release-bearing**. `verify` omits
three gates the tag run enforces (`coverage`, `build`, `check:manifest`), so
a core change that drops branch coverage passes locally and fails only after
the tag is pushed, when `gh release create` may already have run.
## Build phases (each ends with `npm run verify` green + a commit)
@@ -87,13 +118,140 @@ performance budgets docs/11 §6, CI workflows per docs/12 §2 (explicit
`permissions:` blocks on every caller — and note the ops repo has **no**
`browser-extension-*` family), CHANGELOG, README (badges, screenshots ⚠,
install, privacy summary, donate), full manual QA (docs/11 §5), `wxt zip`
clean-install test.
**Exit:** ready for the docs/13 §1 runbook (human performs store submission).
clean-install test. Also carried in from the Phase 4 review:
- ✔ About's "Changelog" link now targets `CHANGELOG.md`, pinned by
`tests/unit/links.test.ts`;
- ✔ `EditTab.svelte` split (589 → 459, under the hard limit). It grew back to
481, and in v1.1.0 its state and commands moved into three stores —
`edit-view` (181 lines), `edit-commands` (226), `edit-session` (133) — and
its key handling into `src/lib/edit/tree-keys.ts`. As of the 1.1.0 review the
component is 259 lines with a 144-line script, `TreeRow.svelte` 276,
`ImportTab.svelte` 266 and the Manager's `App.svelte` 237: every file is under
the 300 target again. Extract before adding;
- ✔ contrast tokens fixed, and `tests/unit/styles/contrast.test.ts` now fails
the build on any text pair under 4.5:1. Two blind spots to know about: it is
token-level, so it cannot see the `opacity`-on-text bypass it was written to
catch, and its pair list is hand-maintained.
**Exit:** ✔ v1.0.0 submitted and published.
### Phase 6 — Post-launch stabilization → v1.0.1
The first phase written for shipped software. In order, because the docs are
binding and three of the code changes need the spec to say the new thing first:
docs reconciliation (this suite had frozen at "in review") → user-intake
machinery (`.github/ISSUE_TEMPLATE`, `CONTRIBUTING.md`, the sanitizer — docs/15
§v1.0.x's "fixture + test per report" had no intake at all) → import failure
reporting and the routing deadlock → localized `#edit`/`#export` failures and
bounded search expansion → cross-tab settings/legal sync → dependency bumps and
CI hardening → the About store link → cut 1.0.1.
**Exit:** ✔ v1.0.1 tagged and released 2026-08-03, live on the store
(confirmed 2026-10-28).
### Phase 7 — v1.1.0: toolchain, import redesign, new formats, technical UI
Two PRs. **PR-A** (toolchain): Node 26, TypeScript 7 beside the TS 6 API,
ES2025 with Chrome ≥ 136, SonarCloud in CI, a browser-enforced zero-network
CSP, gates that cannot be talked past. **PR-B** (product): the import pipeline
redesigned — every entry a file holds read, addresses Chrome would refuse
skipped up front, Chrome's `Bookmarks` file and Firefox JSON backups imported,
root markers so restores stop nesting, a Merge that reuses folders, a Replace
that plans first and refuses an unrestorable backup; the Edit tab rebuilt
around a store, with Sort A→Z, drag to reorder and batched live sync; a
technical redesign of every surface; local diagnostics; a cross-tab write
lock; docs and legal synced (clarifications only — `LEGAL_VERSION` stays 1);
contact aliases per purpose.
**Exit:** ✔ v1.1.0 tagged and released 2026-10-29 (signed tag on `9040f84`,
checksum-verified zip). Still human-only: the docs/11 §5 manual pass on real
Chrome including the **1.0.1 → 1.1.0 upgrade over an existing profile** ⚠️,
then the zip uploaded to the store ⚠️.
### Phase 8 — v1.2.0: Simplified Chinese and Romanian
Real installs in Chinese and Romanian browsers (CWS dashboard) made two UI
languages the next minor. In order: docs first (`07` gains §6 "Adding a
locale") → one `LOCALES` list and a third plural form (`few`), with no new
language yet → `zh-CN` → `ro` → manifest `_locales`, store listings, the
translation form, the screenshot harness → visual sweep in both languages and
an adversarial review of code *and* translations → 1.2.0. Both ship
best-effort (`TODO(review-zh)`, `TODO(review-ro)`). A Traditional Chinese
browser on "Automatic" gets English.
**Exit:** ✔ v1.2.0 tagged and released 2026-11-06 (signed tag on `e2f36bc`,
checksum-verified zip). A finding worth keeping: on this Windows machine the
process-spawning script tests time out intermittently under load (`main`'s
too), so CI — whose Windows smoke job passed — was the gate.
✔ Live on the store, confirmed on the listing 2026-11-10 (5 languages).
Human-only ⚠️, still open: the native review passes, and `13 §1b` step 10 —
the published build installed on a clean profile — which has no recorded
result for any version.
### Phase 9 — v1.2.1: accessibility
The owner's keyboard-only and Narrator pass over 1.2.0 found nothing; an audit
of `src/` then found what such a pass cannot see. In order: dependency sync
after Dependabot (the `biome.json` `$schema` and `docs/01` do **not** move
with its PRs) → docs first (`06 §5`) → `ACCESSIBILITY.md` at the repository
root with its intake (issue form, PR checklist, `accessibility@`) → the fixes:
a focus ring that was drawn in the colour of the fill under it, forced-colours
support, Alt+↑/↓ to reorder (through the drag's own `planDrop`), focus that
fell to `<body>` in three places, 24 px targets, an About link to the
statement → adversarial review → 1.2.1.
Two things to carry forward. **`ACCESSIBILITY.md` is a public promise**: a UI
change that makes its key table or its known-limitations list false has to
change the file in the same PR (`11 §5` has the check). And the statement's
goal is WCAG 2.2 AA **as a goal** — never write "conforms" or "compliant"
without an audit to cite. The review found the first draft of the statement
overclaiming in nine places ("every clickable target", "nothing times out"):
check each sentence of it against the source, not against the intention.
A third: **code moved out of a component starts counting.** SonarCloud's
new-code gate (80 %) failed the first push because the live-sync wiring left
`EditTab` for a `.ts` module with no test. Extracting to stay under a size
limit is half the job; the test is the other half.
**Exit:** ✔ v1.2.1 tagged and released 2026-11-10 (signed tag on `d61318a`,
checksum-verified zip). Human-only ⚠️: the `11 §5` pass with the
**1.2.0 → 1.2.1 upgrade over an existing profile**, a real Windows contrast
theme and a screen-reader pass over Alt+↑/↓, the zip upload, and the native
review of the two new strings.
### Phase 10 — maintenance mode; Firefox and Edge → v1.3.0
The owner put the project into maintenance mode and asked for the last
roadmap item, the other two stores. In order: Dependabot #39–#41 and the
hand sync they always need → the `picomatch` advisory recorded (no fix
exists) → a licence gate over the lockfile (`check:licenses`) → the policy
(`/MAINTENANCE.md`, a feature form that asks which kind of change it is, and
`triage.yml`, which closes requests for something new) → Qodana (`qodana-js`,
Ultimate) beside SonarCloud → then Firefox (AMO) and Edge: the docs first,
then the port, then CI, review and 1.3.0.
One thing to carry forward: **`triage.yml` runs on `pull_request_target`,
with a write token, for pull requests from forks.** It checks out the base
branch and only compares event text with constants. Never add a checkout of
the pull request's head, a step that runs its code, or a `${{ }}` of a title
or body inside a `run:` line to that file.
## Working style
- Small commits per module; tests land with (or before) implementation.
- **A git worktree needs its own `npm ci` *and* `npx wxt prepare`.** With an
empty `node_modules/` packages resolve upward from the parent repo and most
things appear to work, but knip reports every devDependency unused and
`verify` fails; `tsconfig.json` extends `./.wxt/tsconfig.json`, which
`wxt prepare` generates.
**Type resolution walks up too, and it does so even after a correct `npm ci`.**
A worktree under `E:\bookmarkmagic\.claude\worktrees\` inherits
`E:\bookmarkmagic\node_modules\@types\*`, so `npm run check` can pass locally
on types the package does not declare and CI does not have. That is exactly
how a missing `@types/node` survived a green local `verify` and failed CI on
the first push. A green local type-check in a worktree is weaker evidence than
it looks.
- **TypeScript 7 runs beside the TS 6 API.** `tsc` is TS 7 (`@typescript/native`,
aliased `npm:typescript@~7`); the `typescript` package is aliased to
`@typescript/typescript6` for svelte-check, which needs the classic API TS 7
does not have yet. `npm run check` runs svelte-check (TS 6, `.svelte` files)
and then `tsc` (TS 7, `.ts` and `scripts/*.mjs`). Never "fix" one by
removing the other.
- **Installs run with `--ignore-scripts`**, in CI and locally when in doubt:
`npm ci --ignore-scripts && npx --no-install wxt prepare`. The `postinstall`
hook only runs `wxt prepare`; every other package's install script is
untrusted code.
- When a browser fixture contradicts the format spec: add the fixture, make
the parser tolerant, note the quirk in code + docs/04 §1.2, then continue.
- Do not invent features not in docs; park ideas as `docs/15` roadmap PRs.
- Anything marked ⚠️ is human-only — surface it in your summary, don't fake it.
- Every phase so far has been adversarially reviewed after implementation and
**every review found real defects**. A green test run has never once meant
"done" on this project. Budget the review.
+71
View File
@@ -0,0 +1,71 @@
# Code of Conduct
## Our pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our standards
Examples of behavior that contributes to a positive environment:
- Demonstrating empathy and kindness toward other people
- Being respectful of differing opinions, viewpoints, and experiences
- Giving and gracefully accepting constructive feedback
- Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
- Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior:
- The use of sexualized language or imagery, and sexual attention or advances of
any kind
- Trolling, insulting or derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or email address,
without their explicit permission
- Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement responsibilities
Project maintainers are responsible for clarifying and enforcing these standards
and will take appropriate and fair corrective action in response to any behavior
that they deem inappropriate, threatening, offensive, or harmful.
Maintainers have the right and responsibility to remove, edit, or reject
comments, commits, code, issues, and other contributions that are not aligned to
this Code of Conduct, and will communicate reasons for moderation decisions when
appropriate.
## Scope
This Code of Conduct applies within all community spaces — the issue tracker,
pull requests, discussions and any project communication channel — and also
applies when an individual is officially representing the project in public
spaces.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the maintainers at **code@poli0981.dev**. All complaints will be
reviewed and investigated promptly and fairly.
Maintainers are obligated to respect the privacy and security of the reporter of
any incident.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
<https://www.contributor-covenant.org/version/2/1/code_of_conduct.html>.
[homepage]: https://www.contributor-covenant.org
+207
View File
@@ -0,0 +1,207 @@
# Contributing to BookmarkMagic
Bug reports, parser samples and translation fixes are all genuinely useful, and
none of them requires you to write code. If you only want to report something,
[open an issue](https://github.com/poli0981/bookmarkmagic/issues/new/choose) and
stop reading here — the forms ask for what is needed.
Security problems go through [`SECURITY.md`](SECURITY.md), never a public issue.
**The project is in maintenance mode** ([`MAINTENANCE.md`](MAINTENANCE.md)).
What it takes: bug, UI/UX and accessibility fixes; translation fixes (wording
wrong for a language or region, misleading spelling); dependency and security
updates; major platform upgrades; and features that are already on the
roadmap or genuinely needed. A feature request for something new, or a pull
request titled `feat…` from outside the project, is closed automatically and
labelled `maintenance-mode` — read, not deleted, and reopened if it fits.
Ideas belong in
[Discussions › Ideas](https://github.com/poli0981/bookmarkmagic/discussions/categories/ideas).
If something is hard or impossible to use — with a keyboard, a screen reader, a
contrast theme, zoom — that is a defect, and it has its own form.
[`ACCESSIBILITY.md`](ACCESSIBILITY.md) says what is already known and how a
report is handled.
## Reporting a bookmark file that will not import
This is the most valuable report this project gets, because a sample becomes a
permanent test and the bug can then never come back.
**Sanitize the file first.** From a clone of this repository:
```bash
node scripts/sanitize-bookmarks.mjs your-bookmarks.html
```
It needs nothing installed — plain Node. It writes
`your-bookmarks.sanitized.html` next to the original, and prints what it found.
It reads the usual `bookmarks.html` export, a BookmarkMagic JSON file, Chrome's
profile `Bookmarks` file (also Edge, Brave and Vivaldi), a Firefox
`bookmarks-YYYY-MM-DD.json` backup, and our CSV. It refuses anything else rather
than guess, and it refuses to write if its own output still looks personal.
What it **destroys**: every hostname, path, query value and fragment; every
bookmark and folder title and description; Firefox keywords and tags; favicon
data; local `file:` paths; in JSON, every string except structural fields
(types, ids, timestamps), including Chrome's `meta_info` and sync blob.
What it **keeps**, because this is where the bug lives: the byte order mark, the
doctype, the `<META>` line, comments, line endings, indentation, tag and
attribute **case**, quoting style, attribute order, the tree's shape and depth,
every timestamp exactly as written, whether a URL had a port, how deep its path
was, whether it ended in a slash, how many query parameters it had, whether
there was a fragment, any percent-escapes, and any HTML entities in a title.
Distinct hosts stay distinct, so duplicate-detection bugs survive too.
That combination is the point: the sanitized file still reproduces the problem,
without telling us where you browse. A test in `tests/unit/scripts/` asserts
exactly that against every fixture in the repo.
Please do not send a real bookmarks file — an export is a browsing history.
Anything you attach to a GitHub issue is public and permanent; see
[`legal/PRIVACY.md`](legal/PRIVACY.md) for what happens to anything you email.
## Suggesting a translation fix
You do not need to clone anything. Use the translation issue form: the language,
where the text appears, what it says now, and what it should say. Vietnamese is
reviewed by the maintainer; **Japanese, Simplified Chinese and Romanian are
best-effort until a native pass**, so corrections in those three are especially
welcome.
One constraint if you send the change yourself: placeholders like `{n}` or
`{name}` must appear in the translation exactly as in English — same names, same
count. A build gate enforces it.
## Setting up to write code
Node **26 or newer** (see `.nvmrc`).
```bash
npm ci
npx wxt prepare
npm run verify
```
`wxt prepare` is not optional: `tsconfig.json` extends `./.wxt/tsconfig.json`,
which does not exist until it has run.
> **Using a git worktree?** It needs its own `npm ci` *and* `npx wxt prepare`.
> With an empty `node_modules/` the packages resolve upward from the parent
> checkout and almost everything appears to work — but knip then reports every
> devDependency as unused and `verify` fails in a way that looks like your
> change broke something.
Then `npm run dev` and load `.output/chrome-mv3` at `chrome://extensions` with
Developer mode on.
`npm run verify` runs lint, type-check, knip, the grep gate, the licence gate
(`npm run check:licenses`) and the tests. It
must be green before every commit. For anything release-bearing use
`npm run verify:full`, which additionally runs coverage, the build, and the gate
that inspects the *built* manifest — `verify` alone is weaker than what CI and a
release tag enforce.
## The rules that are not negotiable
These are what the extension promises in its store listing and privacy policy,
so they are not style preferences:
- **Zero runtime dependencies.** Not "few". A new one needs discussion first.
- **Exactly two permissions**, `bookmarks` and `storage`. Changing that list is
a minor-version event that also requires re-certifying the store's privacy
answers.
- **No network access of any kind** — no `fetch`, `XMLHttpRequest`, `WebSocket`,
`EventSource` or `sendBeacon`. `npm run guard` fails the build on any of them.
- **No `eval`, `{@html}` or `innerHTML`.** File content reaches the DOM as text.
- `src/lib/core/` is pure: it imports nothing from `browser/`, `stores/`, Svelte
or `chrome.*`.
- Files stay under 300 lines (hard limit 500), functions under 50 (hard 80).
- Every user-visible string is an i18n key present in **every** locale (en, vi,
ja, zh-CN, ro — `LOCALES` in `src/lib/i18n/resolve-locale.ts`).
[`CLAUDE.md`](CLAUDE.md) is the entry point and [`docs/`](docs/) is the binding
specification — **where code and docs disagree, the docs win.** A behaviour
change that skips its doc leaves the spec lying, which is why the PR checklist
asks about it.
## Changing the interface
[`ACCESSIBILITY.md`](ACCESSIBILITY.md) tells users what works; `docs/06 §5`
is the specification behind it. A change to a component has to keep both true:
- **Keyboard.** Whatever a pointer can do, a key can do. A control that is not
a tab stop on purpose (the tree's row buttons) has its key documented.
- **Focus.** Always visible — check it on a control with a filled background,
where the default ring can vanish into the fill — and never dropped: when
the focused thing goes away, focus is put somewhere deliberate
(`src/lib/components/focus-heading.ts` has the helpers).
- **Names.** Icons are decorative; the control carries the name. Anything a
screen reader speaks is an i18n key in every locale.
- **Not colour alone, not motion.** A state shown by a fill or a shadow needs
a `forced-colors` equivalent; anything that moves sits behind
`prefers-reduced-motion: no-preference`. Tests enforce the second
(`tests/unit/styles/motion.test.ts`) and hold the list for the first
(`forced-colors.test.ts`).
- **Native first.** A `<button>`, a `<dialog>`, a `<fieldset>` before an ARIA
role. A role is a promise of that role's keyboard behaviour: the previews
lost `role="tree"` because they did not have the arrow keys.
- **Try it.** Unplug the mouse, then run one screen reader over the screen you
changed. Say in the PR which one, or that you could not.
There is no component test framework here, so logic that can leave a component
does, and is tested where it lands (`src/lib/edit/`, `src/lib/stores/`).
## Turning a reported file into a regression test
The full ritual, in order, because it is easy to do four fifths of it:
1. **Commit the sanitized sample** to `tests/fixtures/` (or `weird/`, or
`malformed/`). Note that `.gitattributes` sets `tests/fixtures/** -text`, so
line-ending normalization cannot rewrite the CRLF or BOM bytes the bug may
depend on — do not "fix" that.
2. **Add the regression test** to `tests/unit/core/fixtures.test.ts`, the only
parser regression suite. A browser export goes in its `BROWSER_EXPORTS` array,
which drives a shared set of assertions; anything else gets its own case.
There is no shared fixture-loading helper — that file has its own loader.
3. **Fix the parser** in `src/lib/core/parse/`. The test and the fix land in the
**same** pull request; a fixture with no test is just a file.
4. **Write the quirk down** in the parser source *and* in `docs/04 §1.2`. The
format chapter is where the next person looks to understand why the code is
shaped oddly.
5. **Update** `docs/11 §2`'s inventory and `CHANGELOG.md`'s `[Unreleased]`.
If the fix changes what a format is able to preserve, that is a specification
change: update `docs/04` first, then `tests/helpers/tree.ts`'s `project()` — it
models each format's documented lossiness, and widening it without the doc turns
a real regression into a passing test.
## Translations, in code
`src/lib/i18n/locales/en.ts` is the schema; every other locale (`vi.ts`,
`ja.ts`, `zh-CN.ts`, `ro.ts`, each with its `-notices` and `-import` parts) is
typed `satisfies Dict` against it, so a missing key is a compile error.
**Never add `as const` to `en.ts`.** It would make `Dict` a tree of string
*literal* types, and every correct translation would become a type error — the
only way to make the build pass would be leaving every other locale in English.
The gates that run on every change:
- identical key paths across the locales;
- identical interpolation tokens per string;
- no empty leaves;
- plural keys carrying exactly the forms the language needs: `{one, other}`
everywhere, plus `few` in Romanian ("1 marcaj", "5 marcaje", "20 de
marcaje");
- language names written as endonyms, identical in every dictionary;
- for Romanian, comma-below `ș ț` only, never the cedilla look-alikes.
See `docs/07` for register and tone in each language. Adding a whole new
language has its own checklist: `docs/07 §6`.
## Commits and pull requests
Conventional Commits (`fix(import): …`, `feat(edit): …`, `docs: …`,
`chore(deps): …`). Small commits, one concern each; tests land with or before
the implementation. The PR template lists the rest.
+89
View File
@@ -0,0 +1,89 @@
# Maintenance
**Status: maintenance mode, since 2026-11-18.**
BookmarkMagic does what it set out to do: import, export and edit bookmarks
between browsers — offline, with two permissions and no network access. From
here the project is **maintained, not extended**. That is not abandonment: it
means keeping the extension correct, safe and current matters more than adding
to it, and every change still reaches people through a store review.
This file is the policy. The reasoning behind it is in the decision log of
[`docs/15_ROADMAP.md`](docs/15_ROADMAP.md).
## What is still done
1. **Dependencies, on a schedule.** Dependabot proposes updates weekly, for npm
and for the GitHub Actions the workflows use, and only for releases that
have been public for at least seven days. Each is merged after CI and the
follow-up the docs ask for ([`docs/01 §6`](docs/01_TECH_STACK.md)).
2. **Security, urgently.** An advisory rated **high or critical** against any
dependency — or a serious security problem in the toolchain itself, Node.js
for example — is fixed as soon as a fixed version exists. While none exists,
[`docs/09 §3.1`](docs/09_SECURITY_PRIVACY.md) records the advisory and why it
cannot reach a user, until the fix lands. To report a vulnerability, follow
[`SECURITY.md`](SECURITY.md).
3. **Major upgrades of the platform.** A new major of the language, runtime or
framework — Node.js 24 → 26, TypeScript 6 → 7, a major of WXT or Svelte — is
adopted on purpose, in its own pull request, with the docs updated first.
4. **Defects.** Bugs, UI/UX defects and accessibility barriers
([`ACCESSIBILITY.md`](ACCESSIBILITY.md)). A bookmark file that will not
import is the most useful report there is
([`CONTRIBUTING.md`](CONTRIBUTING.md)).
5. **Language.** Translation fixes: wording that is wrong for a language, or
for a region's culture or usage, and spelling mistakes that could mislead
someone. The translation form is the way in.
6. **Roadmap features, and necessary ones.** A feature that is already on the
roadmap ([`docs/15`](docs/15_ROADMAP.md)) can still land, and so can a change
that is genuinely needed — to fix a defect, to remove a barrier, or to keep
the extension working in a browser it is published for.
## What is not
**New features outside the roadmap.** Requests for them are closed
automatically, by [`.github/workflows/triage.yml`](.github/workflows/triage.yml):
- An issue opened with the **Suggest a feature** form whose first answer is
"Something new — not on the roadmap" is labelled `maintenance-mode`, gets a
comment that links here, and is closed as *not planned*. The form's other two
answers — on the roadmap, or needed for a fix — keep the issue open, labelled
`needs-triage`, for the maintainer to read.
- A pull request from outside the project whose title starts with `feat`
(Conventional Commits) is labelled and closed the same way. Open a feature
request first.
- The maintainer can label any issue `enhancement` to close it the same way.
Nothing is deleted. Every closed request is read, and one that fits this
policy is reopened and labelled `roadmap`, which the automation leaves alone.
**Ideas** are welcome in
[Discussions › Ideas](https://github.com/poli0981/bookmarkmagic/discussions/categories/ideas),
where they can be talked through without an issue that has to be accepted or
refused.
Out of scope permanently, maintenance mode or not: cloud sync, accounts,
analytics of any kind, and anything that would need a new browser permission —
the never list in [`docs/15`](docs/15_ROADMAP.md).
## Releases
A **patch** ships when there is something to fix: a file that will not import,
a data-integrity defect or a dead end, an accessibility barrier, a batch of
translation fixes, or a security problem that reaches what ships. (The
extension has no runtime dependencies, so an advisory against the build tools
is fixed in the repository and needs no release unless it changed the
built extension.) A **minor** carries a roadmap
feature, a new UI language or a change to the permissions
([`docs/12 §4`](docs/12_CI_CD.md)). There is no fixed schedule.
Your browser updates the extension by itself once a new version passes store
review; there is nothing to do.
## Supported versions
The latest version published on each store. See [`SECURITY.md`](SECURITY.md).
## Changing this policy
Through a pull request like any other, recorded in `docs/15`'s decision log
and announced in Discussions.
+227
View File
@@ -0,0 +1,227 @@
# BookmarkMagic
[![Status: maintenance mode](https://img.shields.io/badge/status-maintenance%20mode-yellow.svg)](MAINTENANCE.md)
[![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-blue.svg)](LICENSE)
[![CI](https://github.com/poli0981/bookmarkmagic/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/bookmarkmagic/actions/workflows/ci.yml)
[![CodeQL](https://github.com/poli0981/bookmarkmagic/actions/workflows/codeql.yml/badge.svg)](https://github.com/poli0981/bookmarkmagic/actions/workflows/codeql.yml)
[![Qodana](https://github.com/poli0981/bookmarkmagic/actions/workflows/qodana.yml/badge.svg)](https://github.com/poli0981/bookmarkmagic/actions/workflows/qodana.yml)
[![Quality gate](https://sonarcloud.io/api/project_badges/measure?project=poli0981_bookmarkmagic&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=poli0981_bookmarkmagic)
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=poli0981_bookmarkmagic&metric=coverage)](https://sonarcloud.io/summary/new_code?id=poli0981_bookmarkmagic)
[![Chrome Web Store](https://img.shields.io/chrome-web-store/v/eghnciphhegekmnofffpgbdfefckdhmg?label=Chrome%20Web%20Store)](https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg)
[![Runtime dependencies: 0](https://img.shields.io/badge/runtime%20dependencies-0-brightgreen.svg)](#privacy)
Move your bookmarks between browsers the simple way: with a file. No account,
no cloud sync, 100% offline.
A browser extension (Manifest V3) for importing, exporting and editing
bookmarks and folder trees — for Chrome and the other Chromium browsers, and,
since 1.3.0, for Firefox. English · Tiếng Việt · 日本語 · 简体中文 · Română.
## Project status
**Maintenance mode** since 2026-11-18 — see [`MAINTENANCE.md`](MAINTENANCE.md).
Bug, UI/UX, accessibility and translation fixes, dependency and security
updates, and features already on the roadmap still land; requests for new
features beyond that are closed automatically. Ideas are welcome in
[Discussions › Ideas](https://github.com/poli0981/bookmarkmagic/discussions/categories/ideas).
## Screenshots
| Import | Edit |
|---|---|
| ![The import tab's drop zone, listing the formats it reads](capture/import.png) | ![The edit tree: folders with counts, bookmarks with their domains, toolbar with search, new folder, sort and duplicates](capture/edit.png) |
| Export | Settings |
|---|---|
| ![The export tab: folder picker on the left, format cards on the right](capture/export.png) | ![Settings: language, theme, and four defaults](capture/settings.png) |
Taken with neutral sample data by `node scripts/screenshots.mjs --shoot`, never
from anyone's real profile.
## What it does
- **Import** HTML, CSV and JSON bookmark files — including Chrome's own
`Bookmarks` file from the profile folder and Firefox's JSON backups, the
copies you have when a browser will not start. A full preview comes first:
counts, folders, depth, duplicates and warnings before anything is written.
- **Choose how**: into a new dated folder (the safe default), merged into the
folders you already have (reused, not copied), or replacing everything.
Replace tells you exactly what it will delete, saves a JSON safety backup
first, and **deletes nothing until that backup is proven** — and restoring
that backup puts the Bookmarks bar, Other and Mobile bookmarks back where
they were.
- **Export** everything, or just the folders you pick, to HTML (Chrome, Edge,
Brave, Firefox, Safari, Vivaldi, Opera), JSON, CSV or Markdown.
- **Edit** the tree: search, rename, drag to move or reorder, sort a folder
A→Z, create folders, delete, and find duplicate links — every action
reachable from the keyboard.
## Accessibility
Everything works without a mouse, a screen reader is told what is on screen
and what an import did, contrast themes and reduced motion are respected, and
the page declares the language you chose. The goal is WCAG 2.2 AA; it is a
goal, not a claim — nobody has audited it.
[`ACCESSIBILITY.md`](ACCESSIBILITY.md) has the detail: the keys, what was
tested and with which screen reader, what is known not to work well yet, and
how to report a barrier.
## Privacy
This is the whole point of the project, so it is worth being precise.
- **No network access at all.** Not analytics, not telemetry, not update pings.
There is no server, and the code makes no network calls. The browser backs
that up: the extension's content security policy — the same in Chrome, Edge
and Firefox — makes the browser refuse fetch, XHR, WebSocket, EventSource and
beacon requests, and remote images, fonts, media and frames. On top of that,
`npm run check:manifest` scans both shipped packages for network APIs (WebRTC
included, which no CSP directive covers) and `npm run guard` scans the source.
- **Exactly two permissions**: `bookmarks` and `storage`. No host permissions,
no content scripts, no background worker. Two gates enforce it: a unit test
over `wxt.config.ts`, and `npm run check:manifest`, which CI runs against the
**built** `manifest.json` — because a build can add what the config never
asked for.
- **Zero runtime dependencies.** Nothing is installed at runtime; the only
third-party code in the package is what the build compiles in — the Svelte
runtime with its `clsx` helper and WXT's one-line browser shim, all MIT
([`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md)). The build
fails if anything else would ship.
- A short diagnostics log (error codes and counts, never titles or addresses)
lives in memory while a tab is open, so you can copy it into a bug report.
It never leaves your computer unless you paste it somewhere.
- Settings use `chrome.storage.local`, never `storage.sync`, so even your
preferences stay off any vendor cloud.
Full policy: [`legal/PRIVACY.md`](legal/PRIVACY.md).
## Honest limitations
- Favicons cannot be imported — the bookmarks API has no favicon field.
- Imported bookmarks get today's date. Browsers do not let an extension set a
bookmark's original creation date. Your **exported** files keep the real ones.
- **Firefox separators are not kept.** They show in the Edit tab as lines, but
no file BookmarkMagic writes can hold one: exports and backups leave them out,
imports skip the ones a file holds and say how many, and Replace — which
deletes them with everything else — tells you so before it starts.
- Firefox refuses bookmark addresses longer than 65,536 characters (they are
skipped, and counted) and shortens titles longer than 4,096.
- On Firefox, entries a file leaves loose at its top level go into the
**Bookmarks Menu**, where Firefox's own import puts them. For an HTML file
exported by Chrome itself, that means Chrome's Other and Mobile bookmarks;
BookmarkMagic's own exports name every root and land where they came from.
- CSV is a flattened view: empty folders and "which folder is the toolbar" are
not preserved. Use HTML or JSON for a faithful backup.
- Markdown is share-only — BookmarkMagic cannot read it back.
## Install
| Browser | Where | Requires |
|---|---|---|
| Chrome, Brave, Vivaldi, Opera | [Chrome Web Store](https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg) | Chrome 136 or later (April 2025), or a Chromium browser of the same vintage |
| Microsoft Edge | Edge Add-ons — **not listed yet**; until it is, Edge installs from the Chrome Web Store link above | Edge 136 or later |
| Firefox (desktop) | Firefox Add-ons — **not listed yet**; the link will be here when it is | Firefox 140 or later. Firefox for Android has no bookmarks API for extensions |
On an older browser the store keeps the version you already have and simply
stops updating it.
Each [GitHub Release](https://github.com/poli0981/bookmarkmagic/releases) carries
the exact packages sent to the stores, with `SHA256SUMS.txt`. Firefox only
installs add-ons Mozilla has signed, so its `-firefox.zip` there is for
checking the store build, not for installing.
From source (Node.js 26) — [`BUILD.md`](BUILD.md) has the details:
```bash
npm ci && npm run build # Chromium: load .output/chrome-mv3/ at chrome://extensions (Developer mode)
npm run build:firefox # Firefox: about:debugging → Load Temporary Add-on → .output/firefox-mv3/manifest.json
```
## Development
```bash
npm run dev
```
`npm run verify` is the gate everything else answers to — lint, type-check
(svelte-check on the TypeScript 6 API, then `tsc` 7), knip, the grep gate, the
licence gate and the test suite, in that order. It must be green before every commit;
`npm run verify:full` adds coverage, the build and the built-manifest check,
and must be green before anything release-bearing.
`node scripts/screenshots.mjs` serves the built extension with sample
bookmarks and a fake `chrome`, for looking at every page without loading the
extension (`--shoot` also captures the store screenshots).
The [`docs/`](docs/) directory is the binding specification, not notes: where
code and docs disagree, the docs win. Start with [`CLAUDE.md`](CLAUDE.md), then
`docs/00`–`docs/02`.
## Contributing
Bug reports and translation fixes are welcome —
[the issue forms](https://github.com/poli0981/bookmarkmagic/issues/new/choose)
ask for what is needed, and none of them requires you to write code. The
project is in maintenance mode, so a request for a feature that is not on the
roadmap is closed automatically ([`MAINTENANCE.md`](MAINTENANCE.md)).
If a bookmark file will not import, that is the most useful report there is,
because the sample becomes a permanent test. Sanitize it first:
```bash
node scripts/sanitize-bookmarks.mjs your-bookmarks.html
```
That strips every address and title but keeps the structure, encoding and
timestamps a parser bug depends on — so the sanitized file still reproduces the
problem without handing over your browsing history.
[`CONTRIBUTING.md`](CONTRIBUTING.md) has the rest: the setup, the rules that are
not negotiable, and how a reported file becomes a regression test.
Security issues: please follow [`SECURITY.md`](SECURITY.md) rather than opening
a public issue.
## Contact
| For | Write to |
|---|---|
| Security vulnerabilities (if you have no GitHub account) | security@poli0981.dev |
| Privacy questions, removing a sample you sent | privacy@poli0981.dev |
| An accessibility barrier (if you have no GitHub account) | accessibility@poli0981.dev |
| The terms (EULA, disclaimer) | legal@poli0981.dev |
| Licensing and permission questions | copyright@poli0981.dev |
| Formal copyright (DMCA) notices | dmca@poli0981.dev |
| A copy or listing pretending to be BookmarkMagic | takedown@poli0981.dev |
| Contributing and code of conduct | code@poli0981.dev |
| Sponsorship · collaboration · press | sponsor@ · collab@ · press@poli0981.dev |
Bugs are best as
[issues](https://github.com/poli0981/bookmarkmagic/issues) and ideas as
[Discussions](https://github.com/poli0981/bookmarkmagic/discussions/categories/ideas)
— they help the next person too. The extension itself never shows or uses any of these addresses.
## Support development
Entirely optional — BookmarkMagic is free software either way.
[GitHub Sponsors](https://github.com/sponsors/poli0981) ·
[Ko-fi](https://ko-fi.com/skullmute) ·
[Buy Me a Coffee](https://www.buymeacoffee.com/skullmute) ·
[Patreon](https://www.patreon.com/skullmute) ·
[PayPal](https://paypal.me/DungDang212)
## Licence
Copyright © 2026 skullmute ([poli0981](https://github.com/poli0981)).
[GPL-3.0-or-later](LICENSE). Also see [`legal/EULA.md`](legal/EULA.md),
[`legal/DISCLAIMER.md`](legal/DISCLAIMER.md) and
[`legal/THIRD_PARTY_NOTICES.md`](legal/THIRD_PARTY_NOTICES.md). Licensing
questions: copyright@poli0981.dev.
The BookmarkMagic name and icon identify this project. The GPL lets anyone fork
the code; it does not let a fork present itself as this project.
Not affiliated with or endorsed by Google, Chrome, Mozilla, Firefox,
Microsoft, Edge or any browser vendor. Browser names are trademarks of their respective owners.
+37 -3
View File
@@ -1,22 +1,56 @@
# Security Policy
## Supported versions
| Version | Supported |
|---|---|
| The latest version published on the Chrome Web Store, Firefox Add-ons or Microsoft Edge Add-ons | ✅ |
| Anything older | ❌ |
There is no back-porting, and there is nothing for you to do to stay current:
your browser updates extensions once a new version passes store review. You
can see which version you are running in the extension's **About** tab, on
`chrome://extensions`, or on `about:addons` in Firefox.
## Reporting a vulnerability
Report privately via **GitHub Security Advisories**:
<https://github.com/poli0981/bookmarkmagic/security/advisories/new>
No GitHub account? Email **security@poli0981.dev** instead. Please say up front
that it is a security report.
Please do not open a public issue for a security problem.
Include, where possible: the affected version, a description of the impact, and
a minimal reproduction. If a bookmark file triggers the issue, attach a
**sanitized** sample — replace real URLs and titles with placeholders.
a minimal reproduction. If a bookmark file triggers the issue, **sanitize it
first**:
```bash
node scripts/sanitize-bookmarks.mjs your-file.html
```
That replaces every hostname, path, query value and title while preserving the
structure, encoding and timestamp shape a parser bug actually depends on — so
the sanitized file still reproduces the problem. `CONTRIBUTING.md` explains what
it keeps and why. Please do not send us a real bookmarks file; we would rather
have a slow reproduction than your browsing history. Anything you do send by
email is kept only as long as it takes to reproduce and fix the issue, and is
then deleted.
## Response targets
| Stage | Target |
|---|---|
| Acknowledgement | 72 hours |
| Fix or mitigation for High/Critical | 14 days |
| Fix prepared for High/Critical | 14 days |
| Fix **reaching users** | the above, plus Chrome Web Store review |
That last row is the honest one: a shipped fix has to pass store review before
Chrome rolls it out, and that step is not ours to control. If a defect is severe
enough to warrant it, we will say so publicly in the advisory so users can
mitigate — for this extension, that generally means "do not import untrusted
files until the update lands".
This is a hobby project with no bounty programme. Credit is given in the
release notes unless you ask otherwise.
+13 -2
View File
@@ -1,9 +1,20 @@
{
"$schema": "https://biomejs.dev/schemas/2.5.5/schema.json",
"$schema": "https://biomejs.dev/schemas/2.6.6/schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
"files": {
"ignoreUnknown": true,
"includes": ["**", "!**/*.svelte", "!**/*.css", "!.output", "!.wxt", "!tests/fixtures"]
"includes": [
"**",
"!**/*.svelte",
"!**/*.css",
"!**/*.md",
"!**/*.yml",
"!**/*.yaml",
"!.output",
"!.wxt",
"!coverage",
"!tests/fixtures"
]
},
"formatter": {
"enabled": true,
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

+204 -15
View File
@@ -5,11 +5,45 @@
> **Owner:** poli0981 (GitHub) / SkullMute
> **Repo:** `poli0981/bookmarkmagic` ✔
> **License:** GPL-3.0-or-later
> **Status:** In development — **Phases 0–3 complete** (scaffold, core library,
> browser layer + import, export + edit). Verified working on real Chrome and
> Brave, 2026-07-25. Next: Phase 4 (i18n wiring, theming, Settings, About,
> Legal Gate). Sequencing lives in `/CLAUDE.md`.
> **Doc suite version:** 1.2 (2026-07-25 — reality pass)
> **Status:** **v1.0.0 is PUBLISHED on the Chrome Web Store and has real users.**
> Submitted 2026-07-26, approved and live by 2026-08-03 (⚠️ exact approval date
> to be recorded by the owner). Listing:
> <https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg>.
> Signed tag `v1.0.0`, GitHub Release with a checksum-verified zip. Verified
> working on real Chrome and Brave.
>
> **v1.0.1 is PUBLISHED.** Tagged, released and submitted 2026-08-03; the
> listing was observed showing **version 1.0.1** (`Updated: August 3, 2026`,
> 5 users) on 2026-10-28. ⚠️ The exact approval date was never recorded — the
> owner can read it from the dashboard. Installed users are on 1.0.1.
>
> **v1.1.0 is PUBLISHED.** Tagged and released 2026-10-29 (signed tag on
> `9040f84`, checksum-verified zip); the listing showed version 1.1.0 on
> 2026-11-06. It raised the floor to Chrome 136 (`08 §7`); permissions are
> unchanged.
>
> **v1.2.0 is PUBLISHED.** Tagged and released 2026-11-06 (signed tag on
> `e2f36bc`); the listing was observed showing **version 1.2.0** (`Updated:
> November 7, 2026`, 5 languages) on 2026-11-10. Installed users are on 1.2.0.
>
> **v1.2.1 — accessibility — is RELEASED on GitHub, not yet on the store.**
> Tagged and released 2026-11-10 (signed tag on `d61318a`, checksum-verified
> zip): an accessibility statement (`/ACCESSIBILITY.md`) and the fixes an
> audit found (`06 §5`). ⚠️ It still needs the owner's manual pass, including
> the 1.2.0 → 1.2.1 upgrade over an existing profile, and a hand upload to
> the store (`13 §1b`); until it clears review, installed users stay on 1.2.0.
>
> The project is now in **maintenance**, not construction: every change from
> here reaches installed users through a store review, so it needs a version
> bump, a CHANGELOG entry and an update submission (`13 §1b`). Sequencing lives
> in `/CLAUDE.md`; what is still open is in §10 below.
>
> **Since 2026-11-18 that is a written policy: maintenance mode**
> (`/MAINTENANCE.md`). Dependency and security updates, major platform
> upgrades, bug/UI/UX/accessibility/translation fixes, and features only when
> they are on `15`'s roadmap or genuinely needed; requests for anything else
> are closed by `triage.yml` (`12 §2.6`).
> **Doc suite version:** 1.12 (2026-11-18 — maintenance mode)
---
@@ -39,7 +73,7 @@ One extension page with three capabilities:
|---|---|
| **Import** | Validate a bookmark file → preview the tree + stats → choose merge mode + dedupe → write into the browser with progress reporting. |
| **Export** | Pick scope (all / specific folders) → pick format → download a file compatible with every major browser. |
| **Edit** | Full tree manager: search, rename, move (drag & drop), delete, create folders, find duplicates. |
| **Edit** | Full tree manager: search, rename, move and reorder (drag & drop), sort A→Z, delete, create folders, find duplicates. |
## 4. Product principles
@@ -74,6 +108,35 @@ One extension page with three capabilities:
- First-run Legal Gate (EULA, GPL-3.0, Disclaimer, Privacy Policy → GitHub links).
- About tab: version, GitHub repo, third-party list ("None"), donate links.
**v1.1.0 adds** (the list above stays as v1.0 shipped it — `15` cites it as
v1.0's scope):
- Import: Chrome's profile `Bookmarks` file and Firefox JSON backups, both
recognised by content, not extension (`04 §2a/§2b`). Backups restore into
the right roots instead of nesting them (`03 §1`).
- Merge that merges: folders the user already has are reused level by level,
and new items are appended to them (`03 §1`, `05 §5`).
- Replace asks first, with exact counts, and refuses a backup it could not
read back (`09` T4); one writer across Manager tabs (`03 §5`).
- Tree editor: Sort A→Z per folder, drag to reorder (before / after / into),
a real "Move to…" dialog, bounded rendering (`03 §3`, `05 §9–§11`).
- About: the third-party statement names the two MIT pieces the build compiles
in instead of "None"; Copy diagnostics, a local log for bug reports
(`09 §7`).
- A redesigned UI with a self-drawn icon set, all motion behind
`prefers-reduced-motion` (`06`).
**v1.3.0 adds** two stores: **Firefox Add-ons** (its own package from the same
source — the Bookmarks Menu as a fourth root, separators shown and protected,
Firefox's own move-index rule, `02 §4`, `03`) and **Microsoft Edge Add-ons**
(the Chromium package, unchanged). Release automation for all three stores,
each off until its owner switches it on (`12 §3`).
**v1.2.0 adds** two UI languages, chosen from the CWS dashboard's install and
usage figures: **Simplified Chinese (`zh-CN`) and Romanian (`ro`)** — in the
app, in the manifest and in the store listing (`07`). Traditional Chinese is
not shipped; a Traditional Chinese browser on "Automatic" gets English.
## 7. Non-goals (v1.0)
- ❌ Cloud sync, accounts, or any server component.
@@ -81,12 +144,18 @@ One extension page with three capabilities:
`ICON` attributes are tolerated on parse and dropped — documented limitation).
- ❌ Dead-link checking (requires host permissions — deferred, see Roadmap).
- ❌ Firefox/Safari *store* releases (WXT keeps the door open; see Roadmap).
*Firefox and Edge became goals on 2026-11-18 (v1.3, `15`); Safari stays
out.*
- ❌ Editing browser-native root folders themselves (Bookmarks Bar / Other
Bookmarks cannot be deleted/renamed — enforced by API anyway).
## 8. Success criteria
- Chrome Web Store approval on first or second review pass.
- ✔ Chrome Web Store approval on first or second review pass — **approved**
between 2026-07-26 and 2026-08-03, with no rejection recorded (⚠️ owner: note
which pass, since it is the only evidence that the `08 §5` privacy answers and
permission justifications landed correctly, and the baseline against which a
future *update* rejection would be judged).
- Round-trip fidelity **at the file level**: `parse(serialize(tree))` reproduces
the tree, per-format and minus each format's documented losses — verified by
the automated suite (`11 §3`). Note what the platform does *not* allow:
@@ -107,11 +176,13 @@ Derived identifiers (canonical across docs and code):
| Context | Value |
|---|---|
| Manifest / store / UI name | `BookmarkMagic` (identical in EN/VI/JA) |
| Manifest / store / UI name | `BookmarkMagic` (identical in every locale) |
| Repo slug | `poli0981/bookmarkmagic` ✔ |
| Own JSON schema | "BM JSON v1", `"format": "bookmarkmagic"` |
| Code prefix | `Bm*` (`BmParseError`, `BmAborted`) |
| Safety-backup filename | `bookmarkmagic-backup-YYYYMMDD-HHmm.json` |
| Chrome Web Store item id | `eghnciphhegekmnofffpgbdfefckdhmg` (also the value `CHROME_EXTENSION_ID` needs — `12 §3`) |
| Store listing URL | `https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg` |
## 10. Manual action items (human-only) ⚠️
@@ -119,14 +190,132 @@ Derived identifiers (canonical across docs and code):
`github.com/poli0981/bookmarkmagic`.
2. ✔ Repo created, `LICENSE` committed. Variant resolved: **GPL-3.0-or-later**,
matching `poli0981/switch-every-tab-hotkey`.
3. **Designed** icon set (16/32/48/128 px) + CWS promo images. Not blocking:
`scripts/gen-icons.mjs` (ported from the portfolio precedent, zero-dep) emits
placeholder PNGs in the accent violet so the manifest loads from Phase 0.
3. ✔ Icon set (16/32/48/128 px) — the owner adopted the `scripts/gen-icons.mjs`
output as final on 2026-07-26, so the generator is the source of truth rather
than a placeholder. Regenerate with `npm run icons` after any change.
⚠️ **Store assets are unreconciled.** The listing is live, so whatever
`13 §2` requires was supplied — but nothing in the repo records what, or
where the originals live. Since 1.1.0 the screenshot harness writes
1280×800 candidates to `store/screenshots/` (`13 §2`); there is still no
440×280 promo tile of any size. Owner: record where the submitted assets
live, or correct `13 §2`.
4. ✔ Donate URLs resolved from `.github/FUNDING.yml` (`14 §5`).
Still open: contact email in `legal/PRIVACY.md`.
5. Chrome Web Store: developer account already paid ✔ — create the item,
fill the Privacy tab per `08_MV3_COMPLIANCE.md`.
6. Repo secrets + settings per `12 §5` (incl. disabling CodeQL "Default setup").
✔ Contact addresses: since v1.1.0, one alias per purpose (`privacy@` in
`legal/PRIVACY.md`, `security@`, `legal@`, `dmca@`, `copyright@`,
`takedown@`, `code@` — README "Contact"); `contact@` is retired. ⚠️ Owner:
if the CWS dashboard's developer contact still says `contact@`, change it
to `privacy@` or `code@` there.
5. ✔ Chrome Web Store: developer account paid, item created, submitted
2026-07-26 and **approved — the listing is public and has users**. Listing
copy and the Privacy tab answers came from `13 §3` and `08 §5`. The store URL
landed in the README on 2026-07-27 (`ea246aa`) and the item id is now in the
§9 identifiers table. `store/listing.{en,vi,ja}.md` now hold the listing copy
`13 §4` always asked for — ⚠️ reconstructed from `13 §3` *after* the listing
went live, so diff them against the dashboard and correct the files.
**Still open:** the asset reconciliation in item 3.
6. Repo secrets + settings per `12 §5`. ✔ CodeQL "Default setup" is already
disabled (the advanced workflow uploads SARIF cleanly). **Still open:**
- `DISCORD_CI_WEBHOOK` is **not** optional in practice. `notify-ci-failure.yml`
calls a reusable that declares it `required: true`, so with the secret
unset that workflow fails on *every* CI completion — success or failure.
Either set it or accept the caller-side tolerance in `12 §2.4`.
- `DISCORD_RELEASES_WEBHOOK` / `DISCORD_REPO_WEBHOOK` genuinely are optional;
the announce job is skipped unless the repo variable `DISCORD_ANNOUNCE` is
`true`. (It used to say `continue-on-error`, which GitHub **rejects** on a
reusable-workflow caller — see `12 §2.3`.)
- The four `CHROME_*` secrets are now a **concrete v1.1 prerequisite**, not a
maybe: `15` lists automated CWS publishing as the first v1.1 item. One of
the four is already known — `CHROME_EXTENSION_ID` is the item id in §9. The
other three come from `npx wxt submit init` (`12 §3`). Note there is no
dry-run: the first time that step executes it makes a real submission.
7. ~~**Untested:** `npm run dev:firefox`.~~ Since v1.3.0 the Firefox package is
built and checked by CI and the release (`12 §2.1`, `12 §2.3`) and its logic
is tested against a Firefox-shaped fake (`11 §4`). Still ⚠️: nothing has run
it in a real Firefox until the owner's `11 §5` pass. Historical text: No gate exercises it (Firefox is a
non-goal, §7). The `overrides` block that used to threaten it is gone
(`09 §3.1`), but do not assume it works.
8. **Unmeasured:** the 2 s parse budget on a real browser (`11 §6`). The
recorded 2869 ms is a jsdom figure and settles nothing. `scripts/gen-fixture.mjs`
now produces the file needed to measure it.
### Post-launch (added 2026-08-03)
9. **JA native review pass.** `src/lib/i18n/locales/ja.ts` carries the repo's
only `TODO` — "owner reviews VI; JA is best-effort until a native pass". It
was acceptable pre-launch; it is now shipping to users. `15 §v1.0.x` tracks
it, and the `translation` issue form is the intake for it.
10. **The published build has never been installed from the store and smoke
tested.** `13 §1` step 8 became due at approval and no result is recorded.
It is the only check that the artifact users actually receive matches what
was tested. Now folded into `11 §5` as a standing pre/post-submission item.
11. ✔ **v1.0.1 cleared review** — the listing showed 1.0.1 when checked on
2026-10-28, and the "published" row is in `15`'s progress table. ⚠️ Still
open: the exact approval date, and `13 §1b` step 10 against the published
build (install on a clean profile, re-run the upgrade check) — no result is
recorded for either.
12. ✔ **v1.1.0 cleared review** — the listing showed 1.1.0 ("Updated October
29, 2026", 6 users, 3 languages) when checked on 2026-11-06. ⚠️ Still
open, as for 1.0.1: `13 §1b` step 10 against the published build — no
result is recorded. Also unverified outside the harness: the
account-storage roots of a signed-in profile and the hidden empty Mobile
root (`02 §4`), and the `MAX_WRITE_DEPTH` rationale against a real Chrome.
### v1.2.0 (added 2026-11-06)
13. ⚠️ **ZH-CN and RO native review passes.** Both locales ship best-effort
(`07 §4`), written from Chrome's own terminology in each language but read
by no native speaker. Each file's header carries `TODO(review-zh)` /
`TODO(review-ro)`. The `translation` issue form lists both languages.
14. ✔ **v1.2.0 to the store** — live, observed 2026-11-10 (version 1.2.0,
`Updated: November 7, 2026`, 5 listing languages). ⚠️ Still unrecorded, as
for 1.0.1 and 1.1.0: `13 §1b` step 10, the clean-profile install of the
published build and the upgrade re-check against it.
### v1.2.1 (added 2026-11-10)
15. ⚠️ **v1.2.1 to the store.** The GitHub Release exists and is verified
(`15`'s progress table). The usual `11 §5` pass plus the **1.2.0 →
1.2.1 upgrade over an existing profile**, then the Release zip uploaded in
the dashboard. No listing change: a patch (`13 §5`).
16. ⚠️ **The accessibility checks no script can run** (`11 §5`): a Windows
contrast theme over the tree, the tabs, the theme control and a running
import; a screen-reader pass over Alt+↑/↓ (does the new position get
spoken, once); 200 % zoom. The fixes were verified in a headless Chrome
with `forced-colors` emulated, which is not the same as a real theme.
17. ⚠️ **Other screen readers.** `ACCESSIBILITY.md` says Narrator with Chrome
on Windows 11 was tested and NVDA, JAWS, VoiceOver and ChromeVox were not.
Any pass with one of those moves it from the second list to the first.
18. ⚠️ **Native review of the new strings** — the About link label and the
spoken position — in JA, ZH-CN and RO, with the passes in items 9 and 13.
### v1.3.0 — maintenance mode, Firefox and Edge (added 2026-11-18)
19. ⚠️ **Pin the maintenance announcement** (Discussions #43) — the API cannot.
20. ⚠️ **v1.3.0 to the Chrome Web Store** instead of 1.2.1, which never went
up: the `11 §5` pass with the **1.2.0 → 1.3.0 upgrade over an existing
profile**, then the Chrome package from the Release (`13 §1b`). The CWS
listing text may keep its Chrome wording; it is the Chrome store.
21. ⚠️ **The first Firefox Add-ons version, by hand** (`13 §8`): the `11 §5`
Firefox section on a real Firefox 140+, then the Developer Hub upload of
the Firefox package **and** the sources archive, desktop only, with
`BUILD.md` in the notes to reviewers. AMO's upload validator report is the
first outside check of the package.
22. ⚠️ **The first Edge Add-ons submission, by hand** (`13 §9`): a Partner
Center account, the `11 §5` Edge items — above all a profile **signed in
with sync on** (`08 §10`, unverified) — then the Chrome package.
23. ⚠️ **Store automation, when wanted** (`12 §3`): the three environments,
each with a required reviewer, deployments limited to `v*` tags, and its
secrets (Chrome: API v2 service
account; AMO: JWT pair; Edge: API key + Client ID, renewed every 72 days),
then the `*_AUTOPUBLISH` variables.
24. ⚠️ **After the listings go live**: their URLs for the README and the
About link (`06 §3.5` — Edge's needs its listing id), and the AMO/Edge
badges.
25. ⚠️ **Evidence for the Firefox fake** (`11 §4`): a sanitized `getTree()`
dump from a real Firefox 140+ profile, committed as a fixture the fake is
checked against; and a Firefox column in `11 §6`'s parse timing.
26. ⚠️ **Native review** of the strings 1.3.0 added or changed (`07`) in JA,
ZH-CN and RO, and of the store-listing blocks for AMO and Edge.
## 11. Reading order
+48 -25
View File
@@ -1,6 +1,7 @@
# 01 — Tech Stack
> Versions verified against npm/official sources on **2026-07-25**.
> Versions verified against npm/official sources on **2026-11-18** (first pass
> 2026-07-25).
> Rule: latest stable or LTS only, with any deliberate exception stated inline.
> Re-verify minor/patch at scaffold time (`npm outdated`), but do NOT jump
> majors without a doc update.
@@ -9,25 +10,29 @@
| Item | Choice | Rationale |
|---|---|---|
| Browser | Chrome / Chromium, **Manifest V3** | MV2 is fully retired. Edge/Brave/Vivaldi/Opera work from the same build. |
| Min Chrome | `minimum_chrome_version: "120"` | Margin over our highest hard-floor API, `runtime.getContexts()` (116+). `scheduler.yield()` (129+) is used only behind a nullish fallback, so it does not raise the floor — see `08 §7`. |
| Runtime deps | **0 (zero)** | `DOMParser`, `Blob`, `URL`, `crypto.randomUUID` cover all needs. |
| Browser | Chrome / Chromium, **Manifest V3** — and since v1.3.0 **Firefox**, MV3 too | MV2 is fully retired. Edge/Brave/Vivaldi/Opera run the Chromium package; Edge Add-ons publishes that same package (`08 §10`). Firefox gets its own package from the same source (`wxt build -b firefox`, MV3 forced by `manifestVersion: 3`, `08 §9`). |
| Min Firefox | `strict_min_version: "140.0"` (since v1.3.0) | The first Firefox that accepts `data_collection_permissions`, which AMO requires of new extensions; every ES2025 built-in is older (134). Vite targets `firefox140` for that package. Desktop only — Firefox for Android has no `bookmarks` API. |
| Min Chrome | `minimum_chrome_version: "136"` (was `"120"` through v1.0.1) | The ES2025 floor: 136 is the first Chrome with every ES2025 built-in (`RegExp.escape` 136, `Float16Array` 135, `Promise.try` 128, iterator helpers and Set methods 122). The manifest floor, Vite's `build.target` (`chrome136`) and tsconfig's `lib: ["ES2025", …]` are one number stated three times — `wxt.config.ts` derives two of them from `CHROME_FLOOR`, and `tests/unit/manifest.test.ts` pins all three. Users on Chrome 120–135 keep the version they have and stop receiving updates; nothing is uninstalled. `scheduler.yield()` (129+) is now always present, though the write queue keeps its fallback because the test environment has no `scheduler`. |
| Runtime deps | **0 (zero)** | `DOMParser`, `Blob`, `URL`, `showSaveFilePicker` and `navigator.clipboard` cover all needs. "Zero" means no npm `dependencies`: the compiled Svelte runtime still ships inside the bundle — see `legal/THIRD_PARTY_NOTICES.md`. |
## 2. Toolchain (dev dependencies)
| Tool | Version (2026-07) | Role |
|---|---|---|
| Node.js | **24.x (Active LTS)** | Build runtime. Active LTS until Oct 2026, maintained to 2028-04-30. Node 26 is *Current*, not LTS — do not use for production tooling yet. |
| npm | bundled with Node 24 (v11) | Package manager. Commit `package-lock.json`. |
| **WXT** | **^0.20.27** | Extension framework: entrypoints, manifest generation, HMR, `wxt zip`, `wxt submit`. |
| **TypeScript** | **~6.0.3** (strict) | Deliberate exception to "latest stable": TS **7.0 went GA 2026-07-08** (7.0.2 is `dist-tags.latest`), but the Go-native compiler exposes no stable programmatic API yet and Microsoft's own GA post says Svelte/Volar toolchains "can only currently rely on TypeScript 6.0" — full support is deferred to 7.1. Since `svelte-check` is our template type authority, we hold on 6.x. Pin with `~` (patch-only). Revisit when TS 7.1 ships **and** svelte-check declares support. |
| **Svelte** | **^5.56.4** | UI, runes mode only (`$state`, `$derived`, `$effect`, `$props`). |
| @wxt-dev/module-svelte | latest at scaffold | WXT ↔ Svelte integration. |
| **Biome** | **2.5.2 (pinned exact)** | Lint + format (replaces ESLint + Prettier). Install with `npm i -D -E @biomejs/biome` per Biome guidance. |
| svelte-check | ^4.7.1 | Type/template authority for `.svelte` files. |
| **Knip** | **^6** (6.29.0 latest as of 2026-07) | Dead code: unused files, exports, dependencies. Requires Node ≥ 20.19. v6 swapped the TypeScript backend for oxc-parser — confirm `compilers.svelte` is still the supported `.svelte` hook before scaffold (`10 §4`). |
| **Vitest** | latest stable at scaffold | Unit tests for `src/lib/core`. |
| @vitest/coverage-v8 | match Vitest | Coverage reporting. |
| Node.js | **26.x (Active LTS)** (was 24.x through v1.0.1) | Build runtime. Node 26 entered Active LTS on 2026-10-28 (maintenance from 2027-10-20, end of life 2029-04-30); Node 24 moved to maintenance on 2026-10-20. `.nvmrc`, `engines` and every CI job say 26 — CI reads `.nvmrc` where it can, and passes `'26'` to the ops reusable, which takes a string input. |
| npm | bundled with Node 26 (v11.20+) | Package manager. Commit `package-lock.json`. `.npmrc` sets `min-release-age=7` (§6). |
| **WXT** | **^0.21.5** (was ^0.20.27 through v1.0.0) | Extension framework: entrypoints, manifest generation, HMR, `wxt zip`, `wxt submit`. **0.x, so a minor is semver's breaking slot** — and 0.21 was: `wxt/testing` split into `wxt/testing/fake-browser` and `wxt/testing/vitest-plugin`, and `tabs.create` is now typed as returning `void`. Both are dev-only. Never take a WXT bump without diffing the **built** manifest before and after (`12 §2.3`); `tests/unit/manifest.test.ts` reads `wxt.config.ts` and is structurally incapable of noticing. |
| **TypeScript** | **7.0 for `tsc`, 6.0 for the API** (strict) | Two packages under two names, Microsoft's documented side-by-side setup for toolchains that embed the compiler: `"@typescript/native": "npm:typescript@~7.0.2"` provides the `tsc` binary (the Go-native 7.0 compiler that type-checks every `.ts` file in `npm run check`), and `"typescript": "npm:@typescript/typescript6@~6.0.2"` keeps the TS 6.0 programmatic API under the `typescript` module name (it re-exports the real `typescript@6.0.x` and adds a `tsc6` binary). svelte-check (peer `typescript ^5 || ^6`) and Volar need that API — TS 7 has none until 7.1 — so `.svelte` files are checked by 6.0 and `.ts` files by both. `tsc --version` must say 7.x and `tsc6 --version` 6.x. Drop the alias when svelte-check declares TS 7 support. Both pinned `~` (patch-only). |
| **Svelte** | **^5.57.3** | UI, runes mode only (`$state`, `$derived`, `$effect`, `$props`). The compiled runtime ships in the bundle (MIT — `legal/THIRD_PARTY_NOTICES.md`). |
| @sveltejs/vite-plugin-svelte | ^7.3.1 | Compiles `.svelte` and the runes in `.svelte.ts` stores for Vitest (`vitest.config.ts`). Its `deepmerge` dependency carries the one advisory with no fix (`09 §3.1`). |
| @wxt-dev/module-svelte | ^2.0.5 | WXT ↔ Svelte integration. |
| **Biome** | **2.6.6 (pinned exact)** | Lint + format (replaces ESLint + Prettier). Install with `npm i -D -E @biomejs/biome` per Biome guidance. 2.6 started formatting Markdown and YAML; both are excluded in `biome.json` so docs and workflows keep their hand layout (`10 §3`). The `$schema` URL in `biome.json` names the same version and moves with the pin — Dependabot bumps the package and leaves the URL behind. |
| svelte-check | ^4.7.8 | Type/template authority for `.svelte` files. Runs on the TS 6 API (see TypeScript above). |
| **@types/node** | **^26** (matches the Node major) | Types for `node:fs`, `node:path`, `node:child_process` and `process`, which the test suite and `scripts/*.mjs` genuinely use. **Declared explicitly since 2026-08-03** — it used to arrive transitively, and WXT 0.21 stopped providing it. Types only: erased at build, so hard rule 2 (zero *runtime* dependencies) is untouched. |
| jsdom | **^31.0** (was ^30 through v1.2.1, ^29 through v1.0.0) | Test DOM. Not interchangeable — `02 §3` picks jsdom over happy-dom because the Netscape walk depends on parse5's implied-end-tag behaviour. A major bump runs `tests/unit/dom-environment.test.ts` first; if that canary fails, pin rather than loosen the test. |
| **Knip** | **^6** (6.44.2 as of 2026-11-18) | Dead code: unused files, exports, dependencies. Requires Node ≥ 20.19. v6 swapped the TypeScript backend for oxc-parser — confirm `compilers.svelte` is still the supported `.svelte` hook before scaffold (`10 §4`). |
| **Vitest** | **^5.1.0** (was ^4 through v1.0.1) | Unit tests. 5.0 changed `clearMocks` to default `true`, requires `vi.mock` at top level and fails unawaited async assertions; the suite needed no changes. Requires Node ≥ 22.12. |
| @vitest/coverage-v8 | match Vitest | Coverage reporting (`text` + `lcov` for SonarCloud, `12 §2.5`). |
## 3. Explicitly rejected
@@ -52,22 +57,29 @@
```jsonc
{
"license": "GPL-3.0-or-later",
"engines": { "node": ">=24" },
"engines": { "node": ">=26" },
"scripts": {
"postinstall": "wxt prepare", // generates .wxt/tsconfig.json — 10 §2 extends it
"dev": "wxt",
"dev:firefox": "wxt -b firefox", // build sanity only, no store release
"dev:firefox": "wxt -b firefox", // MV3 since v1.3.0 (manifestVersion: 3)
"build:firefox": "wxt build -b firefox", // .output/firefox-mv3
"zip:firefox": "wxt zip -b firefox", // the AMO package + its sources archive
"build": "wxt build",
"zip": "wxt zip",
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings && tsc --noEmit && tsc -p tsconfig.scripts.json",
// TS 6 API, the TS 7 tsc, then scripts/*.mjs via checkJs
"lint": "biome check .",
"lint:fix": "biome check --write .",
"knip": "knip",
"guard": "node scripts/guard.mjs", // canonical grep gate, 08 §3
"guard": "node scripts/guard.mjs", // the source gate, 08 §3
"check:manifest": "node scripts/check-manifest.mjs", // the built-artifact gate, 08 §3
"check:licenses": "node scripts/check-licenses.mjs", // every lockfile licence, 09 §3.2
"icons": "node scripts/gen-icons.mjs", // regenerates the shipped icons (source of truth)
"test": "vitest run",
"test:watch": "vitest",
"coverage": "vitest run --coverage",
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run test"
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run check:licenses && npm run test",
"verify:full": "npm run verify && npm run coverage && npm run build && npm run check:manifest && npm run build:firefox && npm run check:manifest -- --browser firefox"
}
}
```
@@ -77,16 +89,27 @@
`npm ci` would otherwise fail type-checking.
`npm run verify` is the local gate — it must pass before every commit that
touches `src/` (mirrors CI, see `12_CI_CD.md`). CI additionally runs
`npm run coverage` for the threshold gate (`11 §1`).
touches `src/`.
It is **not** the same gate CI and a release tag run, and the difference bites:
both additionally run `coverage` (the `11 §1` thresholds), `build` and
`check:manifest`. A change to `src/lib/core/**` that drops branch coverage below
85 therefore passes every local step and fails only *after* the tag is pushed —
by which point `release.yml` may already have created the GitHub Release, which
is not re-runnable. `verify:full` closes that gap and is what `CLAUDE.md` hard
rule 8 requires before anything release-bearing.
Also set `repository`, `homepage` and `bugs` to
`https://github.com/poli0981/bookmarkmagic` — `13`/`14` link to those URLs.
Commit `.nvmrc` containing `24`.
Commit `.nvmrc` containing `26`.
## 6. Version pinning policy
- `typescript` → `~` (patch only; TS minors can break svelte-check).
- `@typescript/native` (TS 7 `tsc`) and `typescript` (the TS 6 API alias) → `~` (patch only; TS minors can break svelte-check). Dependabot ignores majors of both — a 7→8 or 6→7 jump is a doc decision, not a weekly bump.
- `@biomejs/biome` → exact (`-E`), formatter output must be reproducible.
- Everything else → `^`, with `package-lock.json` committed as source of truth.
- Renovate/Dependabot: weekly, grouped, majors require manual review.
- **Cooldown:** `.npmrc` `min-release-age=7` — installs resolve to the newest
release that has been public for 7 days (npm counts days). Dependabot uses the
same `cooldown`. Lockfile installs (`npm ci`) are not affected (`09 §3.1`).
- Renovate/Dependabot: weekly, grouped, majors require manual review; WXT
bumps arrive in their own PR (built-manifest diff, `12 §2.3`).
+150 -34
View File
@@ -46,26 +46,40 @@ 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 / vitest.config.ts
├── .nvmrc # 24
├── scripts/
│ ├── guard.mjs # canonical grep gate (08 §3), run by npm run guard
│ └── gen-icons.mjs # zero-dep placeholder PNG writer (16/32/48/128)
├── 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}/messages.json # manifest-level strings only
│ │ ├── _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
@@ -76,23 +90,57 @@ bookmarkmagic/
│ │ │ ├── timestamps.ts
│ │ │ ├── dedupe.ts
│ │ │ ├── diff.ts
│ │ │ ├── detect-format.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
│ │ │ ├── roots.ts # getRoots: which live folders are the roots (§4)
│ │ │ ├── live-tree.ts # live → file model; separators, counts, move index (§4)
│ │ │ ├── write-queue.ts # sequential tree writer + progress + abort
│ │ │ ├── storage.ts # typed settings/legal accessors
│ │ │ ├── download.ts # Blob → <a download>
│ │ │ └── open-manager.ts # getContexts() focus-or-create
│ │ │ ├── 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
│ │ │ ├── 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
│ │ │ └── locales/{en,vi,ja}.ts
│ │ └── components/ # shared Svelte components (see 06_UI.md)
│ │ │ ├── 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
@@ -128,9 +176,13 @@ export interface BookmarkNode {
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
@@ -140,43 +192,83 @@ export interface ParseResult {
export type MergeMode = 'new-folder' | 'merge' | 'replace';
export interface PlanSegment {
rootId: string; // chrome folder id to write this subtree under
nodes: BookmarkNode[];
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;
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.** `03 §1` maps `toolbar: true` nodes to
Bookmarks Bar and everything else to Other Bookmarks, and Replace deletes the
children of both roots before writing. A single destination cannot express
that, and would leave the toolbar permanently empty after a Replace.
**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. `rootId` = Other Bookmarks; `nodes` = the single `Imported <date>` wrapper folder containing the whole parsed tree. `toolbar` is informational only (`03 §1`). |
| `merge` / `replace` | At most two. Subtrees rooted at a `toolbar: true` node → `{ rootId: <Bookmarks Bar> }`; everything else → `{ rootId: <Other Bookmarks> }`. A segment with no nodes is omitted, not emitted empty. |
| `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. |
`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`).
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`).
Chrome root mapping (Chromium ids are stable): Bookmarks Bar = `"1"`,
Other Bookmarks = `"2"`, Mobile = `"3"`. `browser/bookmarks.ts` resolves them
via `getTree()` rather than hardcoding — segment `rootId`s always come from
that resolution, never a literal — but tests may rely on these ids.
**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. The
position fallback itself never takes the Menu either: it is left out of the
candidates, so roots with unknown ids still map the bar, Other and Mobile
(tested with hand-built roots in `bookmarks.test.ts` — neither fake reaches
that path).
**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/live-tree.ts` keep them out of every bookmark count.
Chrome root mapping: `browser/roots.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 `parentId`s
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
@@ -205,13 +297,23 @@ submission (`08 §8`).
`browser/open-manager.ts`:
1. `browser.runtime.getContexts({ contextTypes: ['TAB'] })` → find an existing
manager context (requires Chrome 116+; we target 120+).
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`) via the 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
@@ -221,21 +323,35 @@ Popup may pass an intent (`#import` / `#export` / `#edit`) via the hash.
| Code | Raised when |
|---|---|
| `NOT_NETSCAPE` | No `NETSCAPE-Bookmark-file-1` doctype **and** no `<DL>` found |
| `NOT_BM_JSON` | Leading `{` parses, but `format !== "bookmarkmagic"` |
| `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 `ParseWarning`s, never errors — including
`NO_BOOKMARKS` (valid doctype, zero `<DL>`), dropped `<DD>` descriptions,
ignored `ICON` attributes, and invalid timestamps.
Non-fatal anomalies are `ParseWarning`s, 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>`), and since
v1.3.0 `SEPARATORS_SKIPPED` (separators an HTML file or a Firefox backup
holds — no format keeps one) and `URL_TOO_LONG` (an address longer than the
browser accepts, 65 536 characters in Firefox — added by the import from
the browser layer's limit, not by a parser).
- `browser/` adds `BmBackupError { code }` for the forced safety backup
(`03 §1` step 6b) and `BmAborted { done }` for a cancelled write.
(`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
+220 -52
View File
@@ -3,12 +3,12 @@
## 1. IMPORT pipeline
```
[1] Select file drag & drop or file picker (.html .htm .json .csv)
│
[2] Pre-validate extension allowlist · size ≤ MAX_FILE_BYTES (25 MB)
[1] Select file drag & drop or file picker — any file; no extension
│ filter (Chrome's `Bookmarks` file has none)
[2] Pre-validate size ≤ MAX_FILE_BYTES (25 MB)
│ fail → localized error, stop
[3] Detect format detect-format.ts (content sniffing, not extension-trust)
│
[3] Detect format parse-file.ts → detect-format.ts: content sniffing,
│ JSON parsed once and routed by shape (04 intro)
[4] Parse per-format parser → ParseResult
│ node count ≤ MAX_NODES (100 000) · collect warnings
│ fail → error + line/detail, stop
@@ -18,20 +18,26 @@
│ warnings list (e.g. "favicons will not be imported")
[6] Configure MergeMode:
│ ● New folder "Imported 2026-07-03 14:05" (DEFAULT)
│ ○ Merge (folders matched by path+title)
│ ○ Merge (existing folders reused, level by level)
│ ○ Replace all (DANGER: forces step 6b)
│ Dedupe toggle: skip URLs already in browser
│
[6b] Safety backup Replace only. Three sub-steps, see "Safety backup"
[7] Build ImportPlan from ONE Start-time read of the live tree:
│ dedupe.ts → route.ts → merge.ts → plan.ts. Built
│ BEFORE the backup, so a failure here deletes nothing.
[6b] Safety backup Replace only. Five sub-steps, see "Safety backup"
│ below. Non-skippable, and deletion never starts until
│ the backup is proven or the user explicitly overrides.
[7] Build ImportPlan core/diff.ts + dedupe.ts → final node list + counts
│
│ (Numbering kept from 1.0.x for cross-references; since
│ v1.1.0 the plan comes first.)
[8] Write browser/write-queue.ts:
│ sequential DFS create (parent → children, in order)
│ progress events every 50 ops → progress bar + path label
│ progress on the first create, then every 50 ops
│ → progress bar + path label
│ Cancel button → AbortController → partial state reported
[9] Report success card: created / skipped / warnings
[9] Report bookmarks and folders created · skipped (existing / in
file) · folders reused · where it went — also after a
cancel or failure (06 §3.1)
actions: [Open Edit tab] [Import another file]
```
@@ -39,26 +45,76 @@
- Steps 1–7 touch nothing in the browser. The first write happens at step 8.
- Replace = delete children of Bookmarks Bar + Other Bookmarks (+ Mobile if
present), then write. Roots themselves are never deleted (API forbids it).
- Merge mode folder matching: same *path of titles* from the root ⇒ reuse
folder; otherwise create. Bookmarks are never "updated" — only created or
skipped (dedupe).
- Toolbar mapping: nodes with `toolbar: true` target Bookmarks Bar; everything
else targets Other Bookmarks. This is why `ImportPlan` carries **segments**
rather than one destination (`02 §4`). In **new-folder** mode the whole tree
goes under `Other Bookmarks/Imported <date>/…` preserving structure (toolbar
flag recorded in the preview as informational).
present, + the Bookmarks Menu on Firefox), then write. Roots themselves are
never deleted (API forbids it). On Firefox the deletion includes the
**separators** in those roots, and nothing restores them — no format
BookmarkMagic writes keeps one — so the confirmation says how many will go
(`import.replaceSeparators`, shown only when there are any). The counts in
that confirmation never include separators among the bookmarks, and they
cover exactly what Replace deletes: the roots it empties, never a signed-in
Chrome account's own roots (`syncing: true`, `02 §4`), which it leaves
alone (fixed in v1.3.0 — they used to be counted).
- **Root routing** (`core/route.ts`), top-level nodes only — deeper, markers
are data. A folder that *is* a browser root is **unwrapped**: its children go
into that root and the folder itself is never written.
- `toolbar: true` folder → its children into the Bookmarks Bar (a flagged
bookmark, malformed but possible, goes there as itself);
- `root: "other"` folder → its children into Other Bookmarks, in its place in
the order;
- `root: "mobile"` folder → its children into Mobile Bookmarks; a profile
with no Mobile root keeps it as an ordinary folder under Other;
- `root: "menu"` folder (since v1.3.0) → its children into Firefox's
Bookmarks Menu; every Chromium browser, which has no menu root, keeps it
as an ordinary folder under Other;
- everything else → the **Bookmarks Menu on Firefox**, Other Bookmarks
everywhere else. Firefox's own HTML export leaves the menu's contents loose
at the top level, and Firefox's own import puts loose entries back into
the menu; doing the same is what makes a Firefox file round-trip in
Firefox. It also means a **Chrome** HTML export's Other and Mobile
contents, which Chrome writes loose (`04 §1.2`), land in the Menu in
Firefox — as they do with Firefox's own import. BookmarkMagic's exports
mark every root, so they are not affected. New-folder mode is not routing and stays the same on every
browser: `Other Bookmarks/Imported <date>/…`.
The markers come from our own exports and backups (`04 §1.1`, §2), from
Firefox's HTML export (`UNFILED_BOOKMARKS_FOLDER`), and from the two browser
JSON files (`04 §2a/§2b`). Without them — 1.0.x — every restore nested a
folder named "Other bookmarks" inside Other Bookmarks, one level deeper each
time, and Mobile never came back. In **new-folder** mode nothing is routed:
the whole tree, root folders included, goes under
`Other Bookmarks/Imported <date>/…` (markers recorded in the preview as
informational).
- **What Firefox refuses is dropped before planning** (since v1.3.0): an
address longer than 65 536 characters (`URL_TOO_LONG`, counted; the limit
comes from the browser layer, and Chromium has none). Firefox also shortens
titles past 4 096 characters on its own; that is a documented limit, not a
warning. Separators a file holds — `<HR>` in HTML, separator entries in a
Firefox JSON backup — are counted as `SEPARATORS_SKIPPED`: the file model has
no separator, on any browser.
- **Merge reuses folders** (`core/merge.ts`, `05 §5`). Below each destination
root, a file folder with the exact, case-sensitive title of a writable child
folder of the live folder its parent matched is reused — never created,
moved or renamed — and new items are **appended** to it. The first of two
same-named live folders wins; policy-managed folders never match. Bookmarks
are never "updated" — only created or skipped (dedupe). 1.0.x planned Merge
exactly like Replace and re-created every folder, so "merge" produced a
second "Dev" beside the first.
**CSV can never target the Bookmarks Bar** — the format has no `toolbar`
column, so a parsed CSV node always has `toolbar === undefined` and its first
path segment is an ordinary folder title. Re-importing our own CSV export in
merge/replace mode therefore produces `Other Bookmarks/Bookmarks bar/…`, not
the real toolbar. Documented limitation, surfaced in the Export tab (`04 §3`).
- **Dedupe is inert in Replace mode.** The browser tree is deleted before the
write, so nothing can already exist: build the plan against an *empty*
browser index and force the browser-side skip off, or a user re-importing
their own backup would have every bookmark skipped and lose everything. The
UI disables and unchecks the dedupe checkbox when Replace is selected
(`06 §3.1`). In-file duplicate collapsing still applies when the toggle is on.
- **Dedupe is off in Replace mode — both halves of it.** The browser tree is
deleted before the write, so nothing can already exist, and a Replace
restores a file *exactly*: two copies of a link in the backup are two
bookmarks after the restore. `buildImportPlan` computes the effective value
(`dedupe && mode !== 'replace'`) and stores it in `plan.dedupe`; the stored
preference is untouched. In 1.0.x the box showed unchecked while in-file
repeats were still collapsed. The UI disables and unchecks the dedupe
checkbox when Replace is selected (`06 §3.1`).
- Merge dedupes against the **Start-time** read of the tree, not the preview's
snapshot, so a link bookmarked between preview and Start is not added twice.
The preview snapshot drives only the badges.
- Import runs **only in the Manager tab**, never in the popup (popup teardown
on blur would kill the write queue).
@@ -72,21 +128,40 @@ we would then delete every bookmark they own. So:
click handler — reading the tree first burns the activation window on
exactly the largest profiles. Only the handle is acquired here; writing is
not activation-gated. Cancel ⇒ `BmBackupError { code: 'BACKUP_CANCELLED' }`.
2. **Read the live tree ONCE, and serialize from that read.** The same
`LiveNode[]` that gets serialized is the one handed to the delete step, so
the backup is provably a superset of what is removed. Serializing the
*preview-time* snapshot instead loses anything bookmarked between preview
and Start — with no copy on disk. Any serialize throw aborts with
`BACKUP_SERIALIZE_FAILED` and never reaches step 7.
The snapshot must carry `toolbar: true` on the Bookmarks Bar, or restoring
the backup nests the whole toolbar under Other Bookmarks.
3. **Attest.** Picker path: writer `close()` resolving proves the backup —
2. **Serialize from a Start-time read — and check it still holds.** The roots
Replace backs up and empties are exactly the three destinations
(`BookmarkRoots.replaceable`): never an account-storage root it does not
write back into, never a managed one. Serializing the *preview-time*
snapshot instead would lose anything bookmarked between preview and Start.
But the read also precedes the save dialog, and on the fallback path the
user's trip to the Downloads folder — time in which sync, another window or
another tab can add a bookmark inside an existing folder, which the clear
would then delete with no copy anywhere. So once the backup is on disk the
tree is **read again**: unchanged → the clear deletes exactly what was
backed up; changed → the picker path writes the fresh snapshot to the same
file (no new click) and checks again, up to three times, and the fallback
path stops with `BACKUP_STALE`. Nothing is deleted on either refusal. Any
serialize throw aborts with `BACKUP_SERIALIZE_FAILED`; a file the user
picked but that never received a backup is removed again (best effort,
`FileSystemHandle.remove`), and the suggested name carries seconds, so a
retry never offers to overwrite the previous backup.
The snapshot carries the root markers — `toolbar: true` on the Bookmarks
Bar, `root: "other"`/`"mobile"` on the other two — or restoring the backup
nests them under Other Bookmarks.
3. **Refuse a backup the import could not read back** (since v1.1.0). The
backup is compact BM JSON (no indentation, about half the bytes), and before
a single byte is written it is checked against the import's own caps — node
count, depth, then the serialized size (`core/caps.ts`). A breach raises
`BACKUP_EXCEEDS_LIMITS` and nothing is written, downloaded, confirmed or
deleted. 1.0.x wrote such a backup, deleted the tree, and the parser then
refused the backup on restore.
4. **Attest.** Picker path: writer `close()` resolving proves the backup —
proceed. Fallback `<a download>` path: **no signal exists**, so the import
enters an `attesting` state and shows a blocking confirm ("Check your
downloads folder for `bookmarkmagic-backup-….json`, then confirm") —
anything other than an explicit confirmation is treated as
`BACKUP_CANCELLED` and nothing is deleted.
4. **Delete.** Only now. The UI enters a `clearing` state that offers **no
5. **Delete.** Only now. The UI enters a `clearing` state that offers **no
Cancel button**: the deletion loop is abortable, but presenting a cancel
affordance mid-delete let a user cancel and then be told "0 items created"
after their tree was already gone. Cancel becomes available again once the
@@ -111,32 +186,100 @@ fine at our size cap (strings of a few MB).
## 3. EDIT flows (Manager → #edit)
State and commands live in `stores/edit-session.svelte.ts` (`EditSession`, one
per tab mount, with the bookmarks API injected so every command is tested
against the in-memory fake), built in three layers — `edit-view` (what the tree
shows), `edit-commands` (single-item writes), `edit-session` (duplicates and the
two bulk commands); `EditTab.svelte` is markup and wiring. Rename,
move and delete are applied to the local tree optimistically; bulk commands
update it after each call the browser accepts; the live events below confirm
both. A command the browser refuses **re-reads the tree** instead of restoring
a snapshot — a snapshot would resurrect rows an earlier step of a bulk command
legitimately deleted — and the re-read keeps whatever is still open and
focused.
**One bulk command at a time.** While Sort A→Z or "keep first in each group"
runs (`busy`), every other write — a second bulk command, rename, delete, move,
drag, new folder — is refused by the session itself, not only greyed out in the
toolbar; only the command that set `busy` clears it. 1.1.0's first cut guarded
the toolbar alone, so a row's Sort button started a second sort that failed with
two false messages and re-enabled the toolbar mid-sort.
**Focus stays on a rendered row.** When the focused row leaves the screen — a
collapse, a move into a closed folder, a search, a delete in another tab — focus
moves to its nearest visible folder (`edit/focus-repair.ts`; a row deleted
elsewhere is climbed with the tree as it was), and a rename whose row is hidden
is dropped. Without this `aria-activedescendant` pointed at nothing and every
tree key was ignored.
| Action | Path |
|---|---|
| Search | input (debounced 150 ms) → core filter on title+URL → tree shows matches with ancestors expanded |
| Rename | inline edit / F2 → `bookmarks.update(id, { title })` |
| Move | drag & drop or context-menu "Move to…" (folder picker) → `bookmarks.move(id, { parentId, index })` |
| Delete | context menu / Del key → confirm dialog (folder shows descendant count) → `removeTree` / `remove` |
| New folder | toolbar button / context menu → `bookmarks.create({ parentId, title })` → inline-edit title |
| Open bookmark | click URL → `tabs.create({ url })` (`javascript:` URLs are display-only, never opened) |
| Duplicate finder | scan tree → groups by normalized URL → panel lists groups → per-item delete, "keep first in each group" bulk action (confirm) |
| Search | input (debounced 150 ms) → core filter on title+URL → tree shows matches with ancestors expanded; a folder the user collapses during the search stays collapsed until the search text changes |
| Rename | F2 or the row button → inline input, focused with its text selected; Enter or blur commits, Esc cancels (a blur after Esc does not commit), and after Enter or Esc focus returns to the tree → trimmed; blank or unchanged → nothing; else `bookmarks.update(id, { title })` |
| Move | drag & drop onto a row — before, after or into (`planDrop`, `05 §10`) → `bookmarks.move(id, { parentId, index })`, or `{ parentId }` alone into a folder; "Move to…" (row button, menu key / Shift+F10) → modal folder list with a filter → `bookmarks.move(id, { parentId })`, appended; **Alt+↑ / Alt+↓** on the tree (since v1.2.1) → `nudgeTarget` picks the sibling shown above or below, then the same `planDrop` (before / after) and the same `moveTo` as a drag — no second write path. One move at a time. The command reports the row's new place among the siblings on screen — the same "n of m" as its `aria-posinset` — which the tab speaks (`06 §5`) |
| Delete | Del or the row button → confirm dialog (folder shows descendant count) → `removeTree` / `remove`; when the deleted row had focus, focus moves to the next row, else the previous. A copy deleted from the duplicate panel leaves the tree's focus where it was |
| New folder | toolbar button → `bookmarks.create({ parentId, title })` in the focused folder, beside a focused bookmark, else in the first writable root → inserted at once unless its live event got there first (Chrome fires `onCreated` before `create` resolves, so either may win), a search that would hide it cleared, and every folder above it opened as the user's own — so clearing the search cannot close them again → inline rename |
| Sort A→Z | toolbar (the focused folder, or the focused bookmark's folder) or a folder row's button → `planSort` (`05 §10`; on Firefox each run between two separators is sorted on its own, and separators stay where they are) → confirm stating how many items move → one awaited `bookmarks.move(id, { parentId, index })` per planned move, yielding every 25, under the write lock (§5). Refused part-way → "moved d of t" and a re-read: there is no undo |
| Open bookmark | Enter, double-click, or the row's Open button → `tabs.create({ url })` for `http:`/`https:` only (`09` T3); anything else is refused with a toast |
| Copy link | the row button, or Ctrl/⌘+C on the focused row → `navigator.clipboard.writeText` (`09` T8) |
| Duplicate finder | toolbar toggles the panel → groups by normalized URL, computed **only while the panel or its confirmation is showing**, policy-managed copies left out (the browser refuses to delete them) → per-copy delete, or "keep first in each group" (confirm with the exact count) under the write lock; stopped part-way → "deleted d of t" and a re-read |
**Live sync:** `#edit` subscribes to `bookmarks.onCreated/onRemoved/onChanged/
onMoved` and patches the in-memory tree, so external changes (or our own
import) appear without reload. Listeners attach on tab enter, detach on leave.
**Separators (Firefox, since v1.3.0)** are rows of their own in the tree: a
line at the depth of its siblings, outside the accessibility tree
(`aria-hidden`), never focused, matched, counted, opened, renamed, deleted,
dragged or dropped into — and never offered as a duplicate of each other,
which their shared `data:` address would otherwise make them. They are still
siblings, so positions stay the browser's: a drag lands where it was dropped,
and Alt+↑ above a separator moves the row past it, one place.
**The move index is the browser's own rule.** `planDrop` computes a target
twice (`05 §10`): Chromium's `bookmarks.move` counts a move to the right as if
the node were still in place (`position.api`), Firefox's counts after removing
it (`position.local`). The adapter sends the one its browser expects, and the
move's own reply (the node's new `index`) is checked against `position.local`:
a mismatch re-reads the tree rather than leave it disagreeing with the browser.
**Live sync** (`edit/live-sync.ts`, `05 §11`). `#edit` subscribes on enter and
unsubscribes on leave: `bookmarks.onCreated/onRemoved/onChanged/onMoved`, plus
`onChildrenReordered` and Chrome's own importer's `onImportBegan/onImportEnded`
where the browser has them (Firefox has neither; its own sort and import send
one `onMoved`/`onCreated` per node, which the burst rule below absorbs).
Events are queued and applied together **once per animation frame**, in arrival
order. An import running in another tab sends one `onCreated` per node — 1.0.x
patched the tree, and rescanned it for duplicates, on every one — so past 500
queued events the queue is dropped and the tree is **re-read once** instead. A
wholesale reorder (Chrome's own "Sort by name") and the end of a Chrome import
re-read too; `onCreated` is ignored while Chrome's importer runs. Each listener
is isolated (`subscribe` in `browser/bookmarks.ts`), so an exception in one can
no longer silently stop the tree following the browser.
## 4. Settings & legal flows
- Settings writes go through `stores/settings.svelte.ts` →
`chrome.storage.local` (debounced 200 ms). Shape:
`{ locale, theme, defaultExportFormat, defaultMergeMode, csvDelimiter }`.
`{ locale, theme, defaultExportFormat, defaultMergeMode, csvDelimiter,
markdownStyle }` — **six** fields, one `<SettingRow>` each (`06 §3.4`).
- `updateSettings(patch)` returns a `SaveOutcome` that resolves when the
debounced write has **settled**, and never rejects. UI feedback follows the
write; it never precedes it, or a failed save still says "Saved".
- The store object is **mutated in place**, never replaced, so a component that
reads `getSettings()` into a local cannot silently go stale. Writes pass a
plain snapshot — `chrome.storage.local.set` structured-clones its argument and
a Svelte `$state` proxy is not cloneable.
- `flushSettings()` runs on `visibilitychange` → hidden (not `beforeunload`,
which is cancellable). It shrinks the window in which an unwritten change is
lost from 200 ms to roughly nothing — not to zero.
- Legal gate: on Manager mount read `legal.acceptedVersion`; if
`< LEGAL_VERSION` render `<LegalGate>` overlay blocking **#import / #export /
#edit** — **#settings and #about stay reachable**, so a VI/JA user can switch
#edit** — **#settings and #about stay reachable**, so a non-English user can switch
language (and theme) before reading the notice and the gate needs no language
switcher of its own. Accept → write version + timestamp → unlock.
This three-route set is normative; `14 §2` states the same list.
Details: `14_LEGAL_GATE.md`.
- The gate's accept path writes **first**, awaits, and only then reflects
acceptance in state. Dismissing optimistically would leave the user accepted
in the UI and unaccepted on disk, so the gate would silently reappear next
launch. A storage read failure fails **closed** (gate shown).
## 5. State machines (informal)
@@ -147,7 +290,32 @@ unmounts the tab on every route change, so component-local state would be lost
while the session still said `parsed`, leaving a preview with no badges and a
dead Import button.
`attesting` and `clearing` occur in Replace mode only. While any of
`backing-up`/`attesting`/`clearing`/`writing` is active the other tabs are
disabled, so an in-app route change cannot orphan the queue — `beforeunload`
only covers closing or reloading the tab, not internal navigation.
`attesting` and `clearing` occur in Replace mode only. Replace's Start opens
the confirmation with exact counts first (`06 §3.1`); that dialog is
component state, not a session state, and `backing-up` begins on confirm.
Since v1.1.0 `cancelled` and `error` carry `where` (`WriteSite`: the mode, and
the new-folder wrapper's title) so the report can say where the items already
created are, and a `backupFilename` only once the backup really exists — the
name the user saved it under, reported by `onClearing`. A failure before that
point never names a file that was not written.
While any of `backing-up`/`attesting`/`clearing`/`writing` is active
(`isWriting()`) the other tabs are disabled, so an in-app route change cannot
orphan the queue — `beforeunload` only covers closing or reloading the tab, not
internal navigation. The same check refuses browser Back and, since v1.1.0, a
route the popup sends over the `BroadcastChannel` (`06 §2`); both get the busy
toast instead.
**One writer across Manager tabs** (`browser/write-lock.ts`, since v1.1.0). Two
tabs replacing at once would each back up, then delete what the other was
writing; a sort racing an import reorders a folder mid-write. So the import's
whole write phase (the Start-time read and plan, backup, clear, write), Sort
A→Z and "keep first in each group" each run inside a Web Lock,
`navigator.locks.request('bookmarkmagic-write', { ifAvailable: true }, …)`. A
second tab that tries one of them while the lock is held is refused **at once**
with `BmEnvError('WRITE_LOCKED')` — before anything is read or touched — rather
than queued behind a write the user cannot see. The import requests the lock
only after opening the save picker: waiting for it first would spend the
click's transient activation (§1 step 6b). Single edits (rename, move,
delete one item, new folder) take no lock. Where the API is missing — the test
environment — the operation simply runs.
+250 -22
View File
@@ -1,18 +1,41 @@
# 04 — File Formats
Four formats. HTML is the interoperability workhorse; JSON is our lossless
round-trip format; CSV is for spreadsheets; Markdown is share/export-only.
Six formats. HTML is the interoperability workhorse; BM JSON is our lossless
round-trip format; CSV is for spreadsheets; Markdown is share/export-only; and
since v1.1.0 two browser files are read directly — Chrome's profile `Bookmarks`
file and Firefox's JSON backup.
| Format | Import | Export | Lossless | Purpose |
|---|---|---|---|---|
| Netscape HTML | ✔ | ✔ | structure+dates | Universal browser exchange (Chrome, Edge, Brave, Firefox, Safari, Vivaldi, Opera all read/write it) |
| BM JSON v1 | ✔ | ✔ | ✔ | Backups, round-trip, safety backup before Replace |
| Chrome `Bookmarks` (§2a) | ✔ | ✖ | structure+dates | The profile file itself — the copy left when the browser no longer starts; keeps Other and Mobile |
| Firefox JSON backup (§2b) | ✔ | ✖ | structure+dates | `bookmarks-YYYY-MM-DD.json` from Library → Backup…; keeps Mobile, which Firefox's HTML export drops |
| CSV (RFC 4180) | ✔ | ✔ | flattened | Spreadsheet review/editing |
| Markdown | ✖ | ✔ | — | Human-readable sharing (blog posts, Discord, README) |
`detect-format.ts` sniffs content (never trusts the file extension):
`<!DOCTYPE NETSCAPE-Bookmark-file-1` (case-insensitive, first 512 bytes) →
HTML; leading `{` + parses with `format:"bookmarkmagic"` → JSON; else try CSV header.
**Sniffing** (`detect-format.ts`, called only through `parse-file.ts`'s
`parseBookmarkFile`) reads content and never the extension — Chrome's file has
none — after stripping a BOM:
1. Text whose first non-blank character is `{` or `[` is JSON. It is parsed
**exactly once** and routed by shape: `format: "bookmarkmagic"` → BM JSON;
an object `roots` holding `bookmark_bar`, `other` or `synced` → Chrome;
`type: "text/x-moz-place-container"` (or `root: "placesRoot"`) with a
`children` array → Firefox. Valid JSON matching none → `NOT_BM_JSON`
(meaning, since v1.1.0, "JSON, but no bookmark file we know"); invalid JSON →
`MALFORMED_JSON`. JSON is tested first so a title quoting the doctype can
never make a JSON file look like HTML.
2. `<!DOCTYPE NETSCAPE-Bookmark-file-1` (case-insensitive) as the first thing
in the file after whitespace and comments → HTML. Anchored since v1.1.0: the
old probe accepted the marker anywhere in the first 512 bytes, including
inside a CSV title.
3. The §3 header row → CSV.
4. Any `<DL` → HTML (the parser decides whether it is usable); else
`UNKNOWN_FORMAT`.
The file picker has no `accept` filter for the same reason: a filter on
`.html,.json,.csv` hid Chrome's `Bookmarks` file.
---
@@ -42,14 +65,39 @@ HTML. `DOMParser('text/html')` normalizes it fine.
```
Export rules: 4-space indent per depth (matches Chrome), attributes only when
values exist, `PERSONAL_TOOLBAR_FOLDER="true"` on the toolbar root folder,
HTML-escape `& < > "` in titles and hrefs — **and `\r` as `&#13;`**. The last
values exist, one **root marker** on each folder that stands for a browser root
(below), HTML-escape `& < > "` in titles and hrefs — **and `\r` as `&#13;`**. The last
one is not a markup hazard but a round-trip one: the HTML tokenizer normalizes
CR and CRLF to LF during input-stream preprocessing, so an unescaped `\r` in a
title comes back as `\n`. A numeric reference survives, because character
references are decoded after that normalization. `\r` reaches us from BM JSON
and from quoted CSV fields, so this is reachable, not theoretical.
**Root markers** (since v1.1.0). Our own export and the Replace safety backup
write the browser roots as top-level folders; without a marker, re-importing
them nested a folder named "Other bookmarks" *inside* Other Bookmarks, one more
level on every restore (`03 §1`). Exactly one attribute per folder, the toolbar
winning:
| Root | Attribute | Who reads it |
|---|---|---|
| Bookmarks Bar | `PERSONAL_TOOLBAR_FOLDER="true"` | every browser |
| Other Bookmarks | `UNFILED_BOOKMARKS_FOLDER="true"` | Firefox (its own exporter writes it), and us |
| Mobile Bookmarks | `MOBILE_BOOKMARKS_FOLDER="true"` | us — importers ignore attributes they do not know |
| Bookmarks Menu (Firefox) | *none* — its contents are written **loose at the top level** | every browser, the way Firefox's own exporter writes it (since v1.3.0) |
The Bookmarks Menu has no attribute of its own in Firefox's format: Firefox
exports the menu's entries as the file's top level and imports loose
top-level entries back into the menu. A BM JSON `root: "menu"` folder (§2)
is therefore written to HTML by unwrapping it — its children appear at the
top level, before the marked roots — and reading that file in Firefox puts
them back where they were (`03 §1`). Chromium has no menu root, so in Chrome
or Edge those entries land in Other Bookmarks, as they do from Firefox's own
export. The other way round, Chrome's own export writes Other's and Mobile's
contents loose (§1.2), so in Firefox they land in the Bookmarks Menu, exactly
as Firefox's own import places them; our exports mark both roots and land
where they came from.
### 1.2 Parse tolerance (import)
Must accept, with a warning where noted:
@@ -70,11 +118,56 @@ Must accept, with a warning where noted:
(Note the precise claim: Chrome's own importer *can* do this; the extension
API exposes no favicon field, so we cannot.)
- Unknown attributes ignored silently — `SHORTCUTURL`, `TAGS`, `LAST_CHARSET`,
`POST_DATA`, `UNFILED_BOOKMARKS_FOLDER` (Firefox), `FOLDED` (Safari),
`LAST_VISIT`, and the IE-era `FEED`/`FEEDURL`/`WEBSLICE`/`ISLIVEPREVIEW`/
`PREVIEWSIZE`.
- `<HR>` separator elements (Firefox) → skipped, no warning. These are
*elements*, so "unknown attributes ignored" does not cover them.
`POST_DATA`, `FOLDED` (Safari), `LAST_VISIT`, and the IE-era
`FEED`/`FEEDURL`/`WEBSLICE`/`ISLIVEPREVIEW`/`PREVIEWSIZE`.
- The three root markers (§1.1) are read **by value**: present and not
`false`/`0`/`no`. Firefox writes `UNFILED_BOOKMARKS_FOLDER="false"` on folders
that are not Other Bookmarks, and v1.0.x read `PERSONAL_TOOLBAR_FOLDER` by
presence alone, so a `="false"` made a folder the bar.
- **Addresses** (since v1.1.0, `05 §1`): blank → skipped, `MISSING_URL`; not
parseable (`URL.canParse` false — e.g. `www.example.com` with no scheme, a
space in the host) → skipped, `INVALID_URL`, because `chrome.bookmarks.create`
rejects it mid-write, after a Replace has already cleared the tree; Firefox
`place:` smart bookmarks → skipped, `PLACE_QUERIES_SKIPPED` (Chrome's own
importer drops them too; in Chrome they are dead links, and on Firefox
BookmarkMagic still does not write them — the notice says "skipped", not
"dead", since v1.3.0). On Firefox, an address longer than 65 536 characters
→ skipped before planning, `URL_TOO_LONG` (applied after parsing, with the
limit the browser layer passes in, so every format is covered by one rule). `javascript:`,
`data:` and `file:` addresses are kept verbatim (`09` T3). Fixture:
`weird/invalid-urls.html`.
- **Empty titles are kept empty** (since v1.1.0), counted as `EMPTY_TITLE`.
They used to become the address, which turned a favicon-only Bookmarks Bar
into a row of URLs after one export/import cycle; Chrome shows the address
itself wherever it needs a title.
- **A loose bookmark before a list.** With no `</DT>`, the HTML parser nests a
following `<DL>` inside a bookmark's `<DT>`; that list is read at the same
depth, after the bookmark. With an explicit `</DT>`, only a *folder* `<DT>`
consumes the next body-level list. v1.0.x dropped the list in both shapes.
Fixture: `weird/loose-first.html`.
- **An unescaped formatting tag in a title** (`C++ <b>tips</A>`): the parser
re-opens that `<b>` around every later entry (`dt > b > a`, `dl > b > dt`).
Entries are found through such wrappers — a `<DT>`'s own `<A>`/`<H3>`/`<DL>`
is any descendant whose nearest `<DT>` is that one. v1.0.x imported one
bookmark from such a file. Fixture: `weird/unclosed-format-tag.html`. A
`<DT>` that still yields nothing is counted as `UNREADABLE_ENTRIES`.
- **An unescaped `<h3>` inside a bookmark title** (`<A …>Intro <h3>Heading</h3></A>`)
is part of the title: a `<DT>`'s `<H3>` makes it a folder only when it is not
inside that entry's own `<A>`. v1.1.0 before the review read it as an empty
folder and dropped the address.
- A root list wrapped in `<div>`/`<center>`/a table cell → found as an
outermost `<DL>` when body-level collection finds nothing.
- **Real Chrome output** writes Other's and Mobile's contents loose at the top
level, after the bar, with no folder line (`bookmark_html_writer.cc`; fixture
`chrome-156-export.html`, built to that writer byte for byte, CRLF included).
The older `chrome-131-export.html` wraps them in an `Other bookmarks` folder
that Chrome itself never writes; it is kept as a third-party shape, not as a
record of Chrome.
- `<HR>` separator elements (Firefox) → skipped and **counted**,
`SEPARATORS_SKIPPED` (no warning until v1.3.0; once Firefox users could
import, a silent loss stopped being acceptable). These are *elements*, so
"unknown attributes ignored" does not cover them. The file model has no
separator: none of the four formats BookmarkMagic writes carries one.
- Empty folders → preserved.
- **Root list selection.** Do **not** pick a single root `<DL>` —
`document.querySelector('dl')` and "the outermost `<DL>`" are both lossy.
@@ -89,12 +182,14 @@ Must accept, with a warning where noted:
child `<DL>` also lands at body level, so compute each body-level `<DT>`'s
child list first and skip any `<DL>` already consumed that way, or the whole
subtree is emitted twice. Algorithm in `05 §1`.
⚠️ The exact Safari shape is still unverified against a real export — gate
the fixture on a captured one before shipping (`11 §2`).
⚠️ The exact Safari shape is still unverified against a real export (`00 §10`).
Hard failures only: no `NETSCAPE-Bookmark-file-1` doctype **and** no `<DL>`
found; or node/size/depth caps exceeded (`TOO_MANY_NODES`, `FILE_TOO_LARGE`,
`TOO_DEEP`). A file with a valid doctype and zero `<DL>` is **not** a failure —
`TOO_DEEP`). The node cap is checked on the raw text (a count of `<DT` tags)
**before** `DOMParser` runs, so a 25 MB file of 1.7 million entries is refused
without building its DOM (`09` T2). The depth cap applies to entries: an empty
list one level past it is harmless. A file with a valid doctype and zero `<DL>` is **not** a failure —
it yields an empty `ParseResult` with a `NO_BOOKMARKS` warning (`05 §1`).
### 1.3 Timestamps
@@ -137,12 +232,132 @@ not an anomaly, and must not raise a warning (`05 §4`).
- `roots` = array of `BookmarkNode` (see `02_ARCHITECTURE.md §4`). Folders may
omit `children` (⇒ empty). Unknown extra keys are ignored on import
(forward compatibility); `version > 1` → warning "newer file, best-effort".
(forward compatibility); `version > 1` → warning "newer file, best-effort";
an absent `version` is read as 1.
- `"root": "other" | "mobile" | "menu"` (since v1.1.0; `"menu"`, Firefox's
Bookmarks Menu, since v1.3.0; folders only, never beside `"toolbar"`) marks a
folder that IS that browser root — the JSON form of §1.1's markers. Additive: v1 readers ignore unknown keys, so the version stays
1, and a 1.0.x reader simply nests as before.
- **Legacy backups.** A 1.0.x safety backup has exactly the shape of a Chromium
profile — `generator` `BookmarkMagic 1.0.x`, no `root` keys, three top-level
folders, the first `toolbar` — so it is recognised and marked on read
(`[1]` other, `[2]` mobile). Fixture: `weird/bm-legacy-1.0.1-backup.json`.
Known limit: a 1.0.x **"Everything" export** (not a backup) from a profile
with policy-managed bookmarks and an empty, hidden Mobile root has the same
shape with the managed folder third, which is then read as Mobile — its
contents land in Mobile instead of a folder. Nothing is lost; the file's
contents are all imported.
- Addresses: blank or unparseable → skipped with `MISSING_URL`/`INVALID_URL`
(Chrome turns `url: ""` into a *folder*). `place:` is **kept**: this is the
restore format, and a backup must bring back what the browser held.
- Dates go through `timestamps.ts` like every other format, so milliseconds
and numeric strings are read and nonsense (`1e300`) is flagged, not stored.
- The safety backup is written **compact** (`indent: 0`, roughly half the
bytes): it must stay under the 25 MB import cap to be restorable at all
(`03 §1` step 6b). Exports stay indented.
- Validation is hand-rolled structural checking in `parse/bm-json.ts`
(no schema library — zero-dep rule). Every node: `title` string required;
`url` if present must be string; `children` only on folders.
- Chrome's internal `Bookmarks` file and Firefox `.json` backups are **not**
v1 import targets (Roadmap v1.1).
- Chrome's profile `Bookmarks` file and Firefox `.json` backups are separate
dialects with their own sections (§2a, §2b).
## 2a. Chrome profile `Bookmarks` file (import only, since v1.1.0)
The JSON file Chromium keeps in the profile folder — `User Data/Default/Bookmarks`
on Windows, `~/Library/Application Support/Google/Chrome/Default/Bookmarks` on
macOS, `~/.config/google-chrome/Default/Bookmarks` on Linux — with **no
extension**. Edge, Brave, Vivaldi and Opera keep the same file. Written by
`BookmarkCodec`, pretty-printed by `base::JSONWriter` (3-space indent, keys
sorted):
```json
{
"checksum": "…",
"roots": {
"bookmark_bar": { "children": [ … ], "date_added": "13344473600000000",
"date_modified": "…", "guid": "…", "id": "1",
"name": "Bookmarks bar", "type": "folder" },
"other": { …, "name": "Other bookmarks", "type": "folder" },
"synced": { …, "name": "Mobile bookmarks", "type": "folder" }
},
"version": 1
}
```
- Nodes are `{ "type": "url", "name", "url", "date_added" }` or
`{ "type": "folder", "name", "children", "date_added", "date_modified" }`.
`id`, `guid`, `meta_info`, `date_last_used`, `show_icon`, `source`,
`sync_metadata` and `checksum` are ignored. **The checksum is never
verified**, so a hand-repaired file still imports.
- **Dates** are decimal strings of microseconds since 1601-01-01 UTC. They are
past 2^53, so the conversion cuts the last six digits as a *string* before any
arithmetic, then subtracts 11 644 473 600 — truncating to the second, exactly
as Chrome's HTML writer (`ToTimeT`) does. `"0"` means unset. Run through
§1.3's magnitude detection instead, such a value lands in the microsecond
bucket and comes out near the year 2395 (`timestamps.ts`
`chromeTimeToSeconds`).
- **Roots.** The bar is always emitted, as a `toolbar` folder, with the file's
own `name`; Other and Mobile are emitted as `root`-marked folders only when
they hold something. A blank root name falls back to the caller's localized
title. Any other root key — Opera's `custom_root` (Speed Dial, Trash,
Unsorted), vendor additions — is skipped and its bookmarks counted as
`EXTRA_ROOTS_SKIPPED`; old profiles also keep a `sync_transaction_version`
*string* in `roots`, which is not a root and is ignored silently.
- Addresses follow §1.2: blank → `MISSING_URL`, unparseable → `INVALID_URL`,
`place:` → `PLACE_QUERIES_SKIPPED`. A node of any other `type`, or not an
object at all → `UNREADABLE_ENTRIES`. Empty names are kept (`EMPTY_TITLE`).
- **Parity rule** (the spec, tested against a Chromium-faithful pair,
`chrome-156-Bookmarks` + `chrome-156-export.html`): the tree read from the
profile file equals the tree read from Chrome's own HTML export of it, once
Other's and Mobile's contents are written loose at the top level, with no
folder line — which is what `bookmark_html_writer.cc` does. The JSON keeps
what the HTML loses: which items were in Other and which in Mobile.
## 2b. Firefox JSON backup (import only, since v1.1.0)
`bookmarks-YYYY-MM-DD.json`, written by Library → Import and Backup → Backup…
(the automatic `.jsonlz4` backups are compressed and are a separate, later
item — `15`). One line of `JSON.stringify` output:
```json
{"guid":"root________","title":"","type":"text/x-moz-place-container","root":"placesRoot","children":[
{"title":"menu","root":"bookmarksMenuFolder","type":"text/x-moz-place-container","children":[…]},
{"title":"toolbar","root":"toolbarFolder", …},
{"title":"tags","root":"tagsFolder", …},
{"title":"unfiled","root":"unfiledBookmarksFolder", …},
{"title":"mobile","root":"mobileFolder", …}]}
```
- Nodes: `type` `text/x-moz-place` (bookmark: `title`, `uri`), `…-container`
(folder: `title`, `children`), `…-separator` (skipped and counted,
`SEPARATORS_SKIPPED`, as `<HR>` is — so a backup and its HTML twin still
give the same result, which the parity rule requires).
A node with no `type` falls back to `typeCode` 1/2/3. Dates are **PRTime** —
integer microseconds since the Unix epoch — converted explicitly and
truncated, as Firefox's own HTML export does (`microsToSeconds`).
- **Roots**, emitted in the order Firefox's HTML export writes them, whatever
the file order: the menu's contents loose at the top level; then the toolbar
as a `toolbar` folder and Other Bookmarks (`unfiled`) as a `root: "other"`
folder, each only when its raw `children` list is non-empty (a toolbar holding
only a separator still yields an empty folder, matching the exporter); then
Mobile as a `root: "mobile"` folder — which Firefox's HTML export leaves out
altogether. The **tags** root is dropped silently: it is a view over bookmarks
the other roots already hold, and importing it would add every tagged
bookmark twice. Any other root → `EXTRA_ROOTS_SKIPPED`.
- **Root titles.** Firefox stores only the internal keys `toolbar`, `unfiled`,
`mobile`, and localizes them at display time. The caller passes localized
titles (`import.rootTitle.*`, `07`); with none, the file's own key is used,
never an English string from `core/`.
- `iconUri` (older files: `iconuri`) → `FAVICONS_IGNORED`; a
`bookmarkProperties/description` anno → `DESCRIPTIONS_DROPPED` (counted
where the HTML export would have written a `<DD>`); `tags`, `keyword`,
`charset`, `postData`, `guid`, `id` and `index` are ignored silently, like
their HTML attributes. Addresses follow §1.2, `place:` included.
- A container that is not the places root (a hand-made or third-party file) is
read as a plain list: its children become the top-level entries.
- **Parity rule**, tested on `firefox-bookmarks-2026-07-25.json` against
`firefox-html-export.html`: equal trees and warnings once the Mobile folder
is removed.
## 3. CSV
@@ -161,7 +376,15 @@ folder_path,title,url,add_date
from normal escaping (every literal `\` is doubled), so it is free to use.
- RFC 4180: quote fields containing `, " \n`; escape `"` as `""`. Accept both
`,` and `;` delimiters on import (sniff header); export delimiter is a
Settings option (default `,`).
Settings option (default `,`). A quoted field that never closes is
`CSV_UNCLOSED_QUOTE`, naming the line it opened on — it used to swallow the
rest of the file into one cell.
- **Formula cells.** A title or folder path starting with `= + - @`, tab or CR
(after any `'` guard quotes) is written with one extra leading `'`, and the
reader removes exactly one again — so `=HYPERLINK(…)` is never a live formula
in Excel, and the round trip stays exact.
- Import also skips blank, whitespace-only and padding (`,,,`) rows, and a
leading Excel `sep=;` line. Address rules as BM JSON (`place:` kept).
- Rows are bookmarks only; folders are reconstructed from paths. CSV is a
**flattened projection** — the full list of what it does not preserve, shown
in the Export tab and asserted by the projected round-trip (`11 §3`):
@@ -171,7 +394,9 @@ folder_path,title,url,add_date
`undefined`, so the first path segment is an ordinary folder title, never a
root reference (consequence spelled out in `03 §1`);
- sibling **order** across folders: folders materialise in row order, so two
folders' relative position is whatever the row sequence implies.
folders' relative position is whatever the row sequence implies;
- **same-named sibling folders merge** — two "New folder"s (Chrome's default
name) come back as one holding both sets of contents.
- Column order is fixed and part of the format contract — appending a column is
a breaking change (major version, `12 §4`).
- Export writes UTF-8 **with BOM** (Excel compatibility).
@@ -190,8 +415,11 @@ Nested list, one line per item:
```
Option "flat with headings": `##` per top-level folder, flat link lists under
each. Escape `[ ] ( )` in titles. Angle-bracket-wrap URLs containing `)` or
spaces.
each. In titles, backslash-escape every character CommonMark gives meaning to
(`` \ ` * _ { } [ ] ( ) < > # + - . ! | ~ & ``) and collapse line breaks to a
space — escaping only the link brackets let raw HTML such as
`<img onerror=…>` through (`09` T1) and let a newline turn the rest of the list
into a heading. Angle-bracket-wrap URLs containing `)` or spaces.
## 5. Filenames
+273 -41
View File
@@ -1,7 +1,9 @@
# 05 — Algorithms
All in `src/lib/core/` (pure, unit-tested) except the write queue
(`src/lib/browser/write-queue.ts`, tested against a mocked API).
(`src/lib/browser/write-queue.ts`, tested against a mocked API) and the #edit
algorithms of §10–§11 (`src/lib/edit/` — pure and unit-tested too, but outside
core's coverage gate, `11 §1`).
## 1. Netscape HTML parsing — `parse/netscape-html.ts`
@@ -9,36 +11,59 @@ All in `src/lib/core/` (pure, unit-tested) except the write queue
```
parseNetscapeHtml(text):
if count of '<dt' in text > MAX_NODES → BmParseError('TOO_MANY_NODES') // before any DOM
doc = new DOMParser().parseFromString(text, 'text/html')
hasDoctype = /NETSCAPE-Bookmark-file-1/i.test(text.slice(0, 512))
hasEntries = doc has any <DL>, or body has a direct <DT> child
if !hasEntries and !hasDoctype → BmParseError('NOT_NETSCAPE')
if !hasEntries → return { roots: [], stats: emptyStats, warnings: [{ code: 'NO_BOOKMARKS' }] }
roots = collectRoots(doc.body)
if roots is empty → roots = walk every outermost <DL> anywhere // wrapped in <div>/<table>
collectRoots(body): // NOT "the outermost DL" — see 04 §1.2
consumed = { nextDlFor(dt) for each direct <DT> child of body }
consumed = { nextDlFor(dt) for each direct FOLDER <DT> child of body }
roots = []
for el of body.children in document order:
if el is DT → roots.push(readEntry(el, depth 1))
if el is DT → roots.push(...readEntry(el, depth 1))
if el is DL and el not in consumed → roots.push(...walkDl(el, 1))
return roots
own(dt, tag): // dt > b > a after an unclosed <b>
return dt's direct <tag> child, else the first descendant <tag> whose closest DT is dt
walkDl(dl, depth):
if depth > MAX_DEPTH → BmParseError('TOO_DEEP')
for dt of dl children where tag == 'DT':
h3 = dt.querySelector(':scope > h3')
a = dt.querySelector(':scope > a')
if h3: // folder
node = { title: h3.textContent, toolbar: h3.hasAttribute('personal_toolbar_folder'), dates… }
childDl = nextDlFor(dt)
node.children = childDl ? walkDl(childDl, depth + 1) : []
else if a: // bookmark
node = { title: a.textContent || a.href, url: a.getAttribute('href'), dates… }
if !node.url → warning, skip
push node; nodeCount++; if nodeCount > MAX_NODES → BmParseError('TOO_MANY_NODES')
for entry of dl's <DT>/<DD>, looking THROUGH wrapper elements (dl > b > dt):
DD → warning DESCRIPTIONS_DROPPED
DT → if depth > MAX_DEPTH → BmParseError('TOO_DEEP'); out.push(...readEntry(dt, depth))
readEntry(dt, depth): // returns 0..n nodes
h3 = own(dt, 'h3')
if h3: // folder
node = { title: h3.textContent, toolbar/root markers by VALUE (04 §1.1), dates… }
childDl = nextDlFor(dt); node.children = childDl ? walkDl(childDl, depth + 1) : []
return [node]
a = own(dt, 'a')
if !a → warning UNREADABLE_ENTRIES; return []
bookmark = classify(a.href): missing/invalid/place: → warning, none // see below
else { title: a.textContent (kept, even empty → EMPTY_TITLE), url, dates… }
swallowed = own(dt, 'dl') // a loose bookmark swallowed the next list
return [bookmark?, ...(swallowed ? walkDl(swallowed, depth) : [])]
every node counts against MAX_NODES → BmParseError('TOO_MANY_NODES')
```
**Address classification (`core/href.ts`, every reader).** Blank →
`MISSING_URL`. `URL.canParse` false → `INVALID_URL`: `chrome.bookmarks.create`
rejects those with "Invalid URL." mid-write, and an extension page's
`URL.canParse` runs the same Chromium URL library. `place:` → skipped with
`PLACE_QUERIES_SKIPPED` in browser-written formats (Netscape HTML, Chrome, Firefox
JSON), **kept** in BM JSON and CSV, which are restore formats. Everything else —
`javascript:` and `data:` included — is stored verbatim (`09` T3).
**Titles are kept exactly as written** (since v1.1.0) — empty included, counted as
`EMPTY_TITLE`. The old `textContent || href` fallback replaced deliberately
cleared titles (a favicon-only bar) with full URLs. All readers share this rule
through `parse/shared.ts`.
**`walkDl(null)` must be unreachable** — a valid-doctype file with zero `<DL>`
is tolerated per `04 §1.2`, so the guard above returns an empty `ParseResult`
rather than letting a raw `TypeError` escape `core/` (`02 §7`).
@@ -59,7 +84,8 @@ rather than letting a raw `TypeError` escape `core/` (`02 §7`).
Use `textContent` (never innerHTML) → titles are inert.
**Complexity:** O(n) nodes, single pass. 100k nodes parse well under 1s.
**Complexity:** O(n) nodes, single pass. Timing: see `11 §6` (the only measured
figure is a jsdom one).
## 2. URL normalization — `normalize-url.ts`
@@ -72,14 +98,21 @@ bare-origin key from `protocol + host`, which discards `user:pass@`.
```
normalizeUrl(raw):
u = new URL(raw) // throws → return raw.trim() as-is key
u.protocol, u.hostname → lowercase
strip default ports (http:80, https:443)
u = new URL(raw.trim()) // throws → return raw.trim() as-is key
// the parser already lowercases scheme + host
// and drops default ports (http:80, https:443)
if u.search == '' → u.search = '' // a BARE ? or # is the same link without it:
if u.hash == '' → u.hash = '' // assigning '' removes the delimiter
if u.pathname == '/' and no search/hash → key without trailing slash
keep search & hash verbatim // conservative: ?q= and #section are meaningful
return u.toString()
return u.href
```
The two empty-delimiter lines are a v1.1.0 fix. Reading `search`/`hash` cannot
tell a bare `?` from none, so `https://a.example/?` passed the bare-origin test
and the slash-trim cut its `?` instead of the slash — the key never matched
`https://a.example/`, and dedupe missed the pair.
Explicitly **not** done: stripping `utm_*`, stripping `www.`, unifying
http/https — too opinionated for a dedupe default. (Roadmap: optional
"aggressive dedupe" toggle.)
@@ -87,7 +120,7 @@ http/https — too opinionated for a dedupe default. (Roadmap: optional
## 3. Dedupe — `dedupe.ts`
```
buildUrlIndex(tree) → Map<normKey, count> // O(n), from current browser tree
buildUrlIndex(tree) → Set<normKey> // O(n), iterative, from current browser tree
dedupeAgainst(nodes, index):
DFS copy of import tree
drop bookmark if index.has(key) → skippedExisting++
@@ -102,16 +135,22 @@ file" are different facts and the user sees both separately in the report
(`02 §4` `stats`). Keep them apart end to end — a single `skippedDuplicates`
made the report, the checkbox label and the StatsCard disagree.
**Replace mode: pass an empty index.** The browser tree is deleted before the
**Replace mode: no dedupe at all.** The browser tree is deleted before the
write (`§6`), so nothing can already exist. Building the plan against the live
index would skip every bookmark of a user re-importing their own backup and
leave them with nothing. In-file collapsing still applies. The UI enforces the
same thing by disabling the checkbox (`03 §1`, `06 §3.1`).
leave them with nothing. Since v1.1.0 in-file collapsing is off too —
`buildImportPlan` skips `dedupeAgainst` entirely when `mode === 'replace'`, so
two copies of a link in a backup are two bookmarks after the restore (1.0.x
still collapsed them). The UI enforces the same thing by disabling the checkbox
(`03 §1`, `06 §3.1`).
Duplicate finder (#edit) reuses the same normalized-URL keying, but over the
**live** tree — `Map<normKey, chrome.bookmarks.BookmarkTreeNode[]>`, so each
entry carries the `id` that per-item delete needs. Groups with length > 1,
ordered by group size desc.
**live** tree — `findDuplicateGroups` over the #edit nodes, so each entry
carries the `id` that per-item delete needs. Groups with length > 1, ordered by
group size desc. Since v1.1.0 it runs **only while the panel or its
confirmation is showing** (1.0.x rescanned the whole tree on every live event,
panel open or not), and policy-managed copies are left out — the browser
refuses to delete them, so offering it was a lie.
## 4. Timestamp normalization — `timestamps.ts`
@@ -140,8 +179,12 @@ Two deliberate choices:
The µs bucket is **defensive**, not a known-live case: every browser that
writes Netscape HTML emits seconds, including Firefox. Microsecond values come
only from non-browser exporters and from Firefox `.json` backups, which are out
of scope until v1.1 (`04 §2`).
from non-browser exporters — and from the two browser JSON files, which have
their own converters precisely so that they never go through magnitude
guessing: Chrome's `Bookmarks` file counts microseconds since **1601**
(`chromeTimeToSeconds`, by string slicing — the values exceed 2^53), and
Firefox's backup counts PRTime microseconds since 1970 (`microsToSeconds`). A
1971 PRTime date is about 3e13 and would read as milliseconds here (`04 §2a/§2b`).
Round to integer seconds. HTML/JSON/CSV export always writes seconds — which is
what browsers put in *files*. Do not confuse this with `chrome.bookmarks`,
@@ -161,8 +204,35 @@ diffAgainstBrowser(parsed.roots, browserIndex):
return { newCount, existsCount, perNodeStatus: WeakMap } // WeakMap feeds preview badges
```
Merge-mode folder matching: key = join of ancestor titles `['Bookmarks bar','Dev']`
(exact, case-sensitive) → existing folder id map built once from browser tree.
**Merge-mode folder matching** — `core/merge.ts` `planIntoFolder` (since
v1.1.0; 1.0.x documented this and never called it). Per destination root,
after routing (`03 §1`):
```
visit(fileNodes, liveParent, trail):
byTitle = first writable child FOLDER of liveParent per exact title // lazily, once
for node of fileNodes:
if node is a folder and byTitle has node.title:
reused++; visit(node.children, thatLiveFolder, trail + title) // never created
else:
segment(liveParent.id).nodes.push(node) // created, subtree inside
```
- Matching is **level by level**: a file folder is compared only with the
children of the live folder its parent matched — so a "Dev" below a folder
that does not exist yet is never matched against some other "Dev".
- Exact and case-sensitive; bookmarks never match folders; policy-managed
(`unmodifiable`) folders never match and are never descended into; the first
of two same-named live siblings wins.
- Two same-named folders in the *file* that both match one live folder both
write into it; when neither matches, both are created. Replace plans through
the same function against emptied roots, so it creates everything and keeps
the file's structure exactly.
- Recursion follows the file tree, which the parsers cap at 200 levels; the
live tree is only ever read one matched folder at a time.
- Properties asserted over 200 random file/live pairs (`merge.test.ts`): every
`parentId` is a writable live folder; created + reused = every file node; no
created folder has the title of a writable folder already in its parent.
## 6. Sequential write queue — `browser/write-queue.ts`
@@ -173,18 +243,20 @@ creating in order).
```
writeTree(plan, { signal, onProgress }):
total = plan.stats.toCreate; done = 0 // one counter for the WHOLE import
async dfs(nodes, parentId):
async dfs(nodes, parentId, trail):
for node of nodes:
if signal.aborted → throw BmAborted(done)
created = await bookmarks.create({ parentId, title, url? })
done++; if done % 50 == 0 or done == total → onProgress({done,total,currentPath})
if node.children → await dfs(node.children, created.id)
for (const seg of plan.segments) // 1 segment (new-folder) or ≤2 (merge/replace)
await dfs(seg.nodes, seg.rootId)
done++; if done == 1 or done % 50 == 0 or done == total → onProgress({done,total,currentPath})
if node.children → await dfs(node.children, created.id, trail + node.title)
for (const seg of plan.segments) // 1 (new-folder), or one per live folder written to
await dfs(seg.nodes, seg.parentId, seg.trail ?? [])
```
`done` and `total` are declared outside the loop, so progress, abort and the
final report stay whole-import scoped rather than resetting per segment.
final report stay whole-import scoped rather than resetting per segment. The
first create reports too (since v1.1.0): on a slow profile 50 creates can take
seconds, and a bar stuck at 0% reads as a hang.
`create()` accepts only `{ parentId, index?, title, url? }` — `dateAdded` is
output-only, so **imported nodes are stamped with the current time**. Parsed
@@ -232,7 +304,167 @@ is fine ≤ 100k nodes. No fuzzy search in v1 (zero-dep rule).
## 9. Tree rendering scale strategy
Folders render collapsed by default (depth ≥ 2) and children mount lazily on
expand — the DOM never holds the full 100k tree. If a single folder with
>5 000 direct children is expanded, render in chunks of 500 with a
"Show more" sentinel. This avoids a virtual-list dependency in v1.
**Bounded, not virtualized.** Every tree surface mounts a bounded number of
rows: 500 to start, 500 more per "Show more" ("Show n more rows · m not
shown"). There is no virtual list — no dependency for one, and none
hand-written; #edit mounts a **window** of rows around the focus instead.
1.0.x documented chunking for very wide folders and never built it: #edit
rendered every visible row in one pass, so "Expand all" on a large profile
froze the tab.
- **#edit** (`TreeList.svelte`). `visibleRows` (`edit/tree-keyboard.ts`)
flattens the tree into the rows actually showing — roots open on first load,
every other folder closed until opened — and computes each row's
`aria-posinset`/`aria-setsize` on the way. The list mounts a window of 500
rows (`edit/row-window.ts`) that always holds the focused row:
`aria-activedescendant` and scroll-into-view both need it in the DOM. When
focus leaves the window (End, type-ahead, Home), a fresh window is centred on
it; "Show earlier" and "Show more" grow it by 500 either way. 1.1.0's first
cut grew a prefix from row 0 instead, so End on 20 000 rows mounted all of
them — 3.9 s, then ~200 ms per arrow key.
- **Import preview and export picker** (`TreePreviewNode`, `FolderPickNode`):
nested lists. The top level starts open and everything deeper closed; a
folder's children mount only once it is opened, then 500 at a time with a
per-folder "Show more". The picker lists folders only.
- **What is not done.** `visibleRows` re-walks every visible node on each tree
change — O(visible) per change, acceptable at the 100k cap; a key press only
looks the focused row up. Mounting exactly what is on screen (true
virtualization) would bring a jump from 500 row mounts down to a screenful;
measured in the harness, Home/End on 3 000 rows takes ~0.4 s in a background
page and arrows 2–6 ms, so it stays in the `15` backlog.
## 10. Reordering — `edit/sort.ts`, `edit/move-target.ts`
Both write through `bookmarks.move`, whose index has one trap, and it is not
the same trap in every browser. **Chromium**: within one parent, a move to the
right counts the target index as if the node were still in place, while
`onMoved` — and `patch-tree`'s `moveNode` — count after its removal. Moving `a`
after `c` in `[a, b, c]` is `move(a, { index: 3 })`, and `onMoved` then reports
index 2. **Firefox** (since v1.3.0) counts after removal in the call too —
`move(a, { index: 2 })` — as Places stores the final position. A move to the
left is the same number in both. `planDrop` returns both numbers; the adapter
(`browser/bookmarks.ts` `move`, through `moveIndexFor` in `live-tree.ts`)
sends `api` to Chromium and `local` to Firefox and returns the index the
browser reports; `moveTo` in `stores/edit-commands.svelte.ts` compares it with
`local` and re-reads the tree on a mismatch (`03 §3`).
**Separators** (Firefox) are children like any other here: they occupy
indices, `planDrop` may place a node before or after one, and Alt+↑/↓ steps
past one as a single place. They are never a drop target *into*, and Sort A→Z
leaves them where they are and sorts each run between them on its own.
**Sort A→Z** (`planSort`), planned before anything moves so the confirmation
can state the number:
```
sortedOrder(children, locale):
collator = Intl.Collator(locale, { numeric: true, sensitivity: 'base' })
split children into runs at each separator (Firefox; Chromium has none — one run)
each run: stable sort, folders before bookmarks, then collator.compare(key), then current position
result = run₀ sorted, separator₀, run₁ sorted, separator₁, … — every separator keeps its index
key(node) = node.title — or the URL, for a bookmark whose title is blank (as Chrome shows it)
planSort(children, locale):
target = sortedOrder(children, locale); current = [...children]; moves = []
for index, wanted of target:
if current[index] is wanted → continue // already in place: never moved
take wanted out of current (it is always to the right of index), put it at index
moves.push({ id: wanted.id, index })
return moves
```
- `numeric` puts "Item 2" before "Item 10"; `sensitivity: 'base'` ignores case
and accents; the locale is the UI language. Ties keep their current order.
- Each move fills the next position from further right — a **leftward** move,
the case where Chrome's index needs no adjustment — so the indices are valid
applied in order. `sort.test.ts` applies the moves to 300 random folders with
Chrome's index rule and checks the result equals `sortedOrder`.
- A sorted folder plans zero moves (the UI says so instead of asking). The
commands that run the plan are in `03 §3`.
**Drop planning** (`planDrop`), shared by every drag; `canMoveInto` is the one
legality rule DnD and "Move to…" both use:
```
planDrop(roots, movingId, targetId, zone): // zone: before | into | after
'into' → canMoveInto(target) ? { parentId: target } : none // appended
parent = target.parentId; none if illegal (canMoveInto(parent) false) or target is the node
at = target's index among parent's children
api = zone == 'before' ? at : at + 1 // chrome.bookmarks.move's index
from = moving's index if it already lives in parent, else -1
if from != -1 and api in { from, from + 1 } → none // dropped right beside itself
local = (from != -1 and from < api) ? api - 1 : api // onMoved's / moveNode's index
return { parentId: parent, position: { api, local } }
canMoveInto(movingId, targetId):
target is a folder, not policy-managed, not the node, not inside the node's subtree
```
The optimistic patch uses `local` and the API call `api`. Permanent roots take
drops *into* only: their parent is the synthetic root, which is never a legal
destination. Asserted in `move-target.test.ts` (both index spaces, cross-folder,
into a bookmark refused, beside itself, beside a root) and, against the
in-memory fake, in `edit-session.test.ts`.
**Keyboard reorder** (Alt+↑ / Alt+↓, since v1.2.1) adds no planner. It picks a
target row and a zone, and `planDrop` does the rest:
```
nudgeTarget(rows, id, direction): // rows: the visible rows, in order; direction: -1 | +1
row = the row for id; none if absent
siblings = rows with row.parentId, in order // the VISIBLE ones: under a search, only matches
neighbour = siblings[index of row + direction]; none at either end
return neighbour.id
nudge(id, direction):
a nudge already in flight → nothing // a held key repeats faster than a move completes
target = nudgeTarget(rows, id, direction); none → nothing
plan = planDrop(roots, id, target, direction < 0 ? 'before' : 'after'); none → nothing
moveTo(id, plan); refused → nothing
row = the row for id, as it is now
return { position: row.posInSet, total: row.setSize } // among the siblings ON SCREEN
```
Visible siblings, not all of them, because that is what a drag does too: the
user places the item relative to a row they can see. Under a search that has
a consequence: the row passes its visible neighbour **and every hidden item
between them**, so down-then-up restores what is on screen but not
necessarily the hidden order. The place it reports is the visible one too —
the same "n of m" the row's `aria-posinset`/`aria-setsize` give — so what is
spoken and what the tree says cannot disagree. A permanent root has no
`parentId` that `planDrop` accepts, so it never moves.
One at a time, because each plan is made from the optimistic tree: a second
plan made before the first move has landed is made from a tree that is about
to change. A residue is known and unfixed: the first move's live event can
flush a frame after a second press's optimistic patch and roll the row back
for that frame; the tree converges once the events drain (`15`, backlog).
Asserted in `tree-keyboard.test.ts` (ends of a folder, an open neighbour's
children stepped over, a filtered list, a root's neighbour) and
`edit-session.test.ts` (Chrome's index rule in both directions, a root, a
managed node, hidden items under a search, one move at a time, while busy, a
refusal).
## 11. Live-sync batching — `edit/live-sync.ts`
```
createBatcher({ onFlush, onBurst, limit = 500, schedule = requestAnimationFrame }):
push(event): if not overflowed:
queue.push(event)
if queue.length > limit → overflowed = true; queue = []
arm() // at most one flush scheduled
resync(): overflowed = true; queue = []; arm() // reorder, end of Chrome's import
flush(): overflowed → onBurst() // re-read the tree once
else queue non-empty → onFlush(queue) // applyEvents, arrival order
dispose(): cancel the scheduled flush, drop the queue
```
- `applyEvents` folds `created`/`removed`/`changed`/`moved` into the tree with
`patch-tree`'s immutable helpers: one new tree per frame, not one per event.
- Past the limit, one re-read (`getTree`) replaces what would be thousands of
patches, and is exact by construction; the next frame batches normally again.
The re-read keeps expansion and focus where the nodes still exist (`03 §3`).
- The scheduler is injected, so `live-sync.test.ts` fires frames by hand: one
batch per frame, a burst past the limit becomes one `onBurst` and no patch,
`resync` re-reads, `dispose` cancels what is pending.
+568 -88
View File
@@ -6,119 +6,412 @@ framework.
## 1. Design tokens — `src/styles/tokens.css`
The look since v1.1.0 is "technical": a cool neutral ramp, a monospace face for
labels and readouts, a faint grid, square-ish corners and quick, small motion.
No font is bundled — both stacks are system ones.
```css
:root {
--bg: #ffffff; --bg-raised: #f6f7f9; --border: #e2e5ea;
--fg: #1b1e24; --fg-muted: #5b6472;
--accent: #6d4aff; --accent-fg: #ffffff; /* violet — "magic" identity */
--danger: #d8384a; --success: #1f9d55; --warn: #b7791f;
--radius: 10px; --radius-sm: 6px;
--font: system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
color-scheme: light; accent-color: var(--accent); /* native controls follow the theme */
--bg: #fbfbfd; --bg-raised: #f2f3f7; --bg-sunken: #eceef3; /* page · panel · well */
--border: #dde1e8; /* decorative dividers only */
--border-strong: #7b8496; /* every interactive boundary — ≥ 3:1 */
--fg: #151821; --fg-muted: #535d6e;
--accent: #6447f0; --accent-fg: #ffffff; --accent-subtle: #ece7ff; /* violet — "magic" */
--danger: #c22f3e; --danger-fg: #ffffff; --success: #15733c; --warn: #8a5a12;
--grid: rgb(21 24 33 / 4.5%);
--radius: 6px; --radius-sm: 4px;
--font: system-ui, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
--font-mono: ui-monospace, 'Cascadia Code', 'SF Mono', Menlo, Consolas, 'Liberation Mono', monospace;
--fs-0: 12px; --fs-1: 13.5px; --fs-2: 15px; --fs-3: 18px; --fs-4: 24px;
--sp-1: 4px; --sp-2: 8px; --sp-3: 12px; --sp-4: 16px; --sp-5: 24px; --sp-6: 32px;
--shadow-1: …; --shadow-2: …; /* resting raise · floating (toasts, dialogs) */
--z-dialog: 40; --z-toast: 50;
--width-page: 1040px; --width-side: 360px;
--dur-1: 120ms; --dur-2: 200ms; --dur-3: 320ms; --ease: cubic-bezier(0.2, 0.8, 0.2, 1);
}
[data-theme="dark"] {
--bg: #16181d; --bg-raised: #1e2128; --border: #2b3039;
--fg: #e8eaee; --fg-muted: #9aa3b0;
--accent: #8b6dff; --danger: #ff6b7d; --success: #3ecf8e; --warn: #e2b93b;
[data-theme='dark'] { /* repeated verbatim under prefers-color-scheme: dark */
color-scheme: dark;
--bg: #0e1015; --bg-raised: #161a22; --bg-sunken: #0a0c10;
--border: #262b35; --border-strong: #5f697c;
--fg: #e6e9f0; --fg-muted: #9aa4b5;
--accent: #9a80ff; --accent-fg: #0e1015; --accent-subtle: #241c44;
--danger: #ff6b7d; --danger-fg: #0e1015; --success: #3ecf8e; --warn: #e2b93b;
--grid: rgb(230 233 240 / 3.5%); /* plus darker --shadow-1/-2 */
}
```
Theme: `data-theme` on `<html>`; default follows `prefers-color-scheme`,
manual override persisted in Settings. Focus rings always visible
(`:focus-visible` outline in accent).
The roles matter more than the values, because the new surfaces are easy to
misuse:
## 2. Popup (~320 × auto px)
- **Three surfaces.** `--bg` is the page and the inside of lists and cards;
`--bg-raised` is a panel (callouts, dialog header and footer, the duplicate
panel, row hover); `--bg-sunken` is a well — inputs, readouts (StatsCard, the
popup counts), the TabBar track, the status bar. `--accent-subtle` tints what
is selected: the focused tree row, the chosen mode or format card, a
drop-into target.
- **Two borders.** `--border` only divides. Anything that marks an interactive
boundary — inputs, cards, the drop zone, the tree frame — uses
`--border-strong`, which clears 3:1 (WCAG 1.4.11).
- `color-scheme` makes scrollbars and native form controls follow the theme;
`accent-color` tints checkboxes and radios. `base.css` draws the 24px body
grid from `--grid` (a few percent alpha: texture, never content), and sets
machine-shaped text — counts, versions, paths, addresses (`.mono`, `code`,
`kbd`) — and the numbered step labels (`.eyebrow`, `01 · SOURCE`) in the mono
stack.
- `--z-dialog` is defined but nothing reads it: `Modal` opens with
`showModal()`, whose top layer sits above any z-index. `--z-toast` places the
toast.
- **Motion tokens** (`--dur-*`, `--ease`): anything that *moves* uses them only
inside `@media (prefers-reduced-motion: no-preference)` (§5). Colour and
opacity fades are not motion and may use them anywhere — Button's hover does.
⚠️ **`--accent-fg` and `--danger-fg` must be redefined in the dark block, in the
opposite direction to the colour they sit on.** Dark mode lightens `--accent`
and `--danger` for contrast against `--bg`, which is exactly what breaks white
ink on them — the original palette measured 3.67:1 and 2.74:1 there, against
the 4.5:1 §5 requires.
The light `--danger`/`--success`/`--warn` are darker than an eyeball would pick
because all three are rendered as **text** — StatsCard's duplicate count, the
preview badges, DuplicatePanel's "kept", the status bar's "local only" — and
every text token is held to 4.5:1 on every surface, the sunken and tinted ones
included.
None of these numbers is a matter of taste: `tests/unit/styles/contrast.test.ts`
parses `tokens.css` and, for light and for both dark blocks, fails the build if
any of the six text tokens (`--fg`, `--fg-muted`, `--accent`, `--danger`,
`--success`, `--warn`) drops below 4.5:1 on any of the four surfaces (`--bg`,
`--bg-raised`, `--bg-sunken`, `--accent-subtle`); if ink on a filled control
(`--accent-fg` on `--accent`, `--danger-fg` on `--danger`) does; if
`--border-strong` or `--accent` (the focus ring) falls under 3:1 on `--bg` or
`--bg-raised`; or if the two dark blocks drift apart. Re-run it after changing a
colour. It is token-level: an `opacity` on text, a hardcoded colour or a pair
nobody added to its list gets past it — the contrast item in `11 §5` is the
backstop.
Theme: `data-theme` on `<html>` — set for Light and Dark, **removed** for
System, so the `prefers-color-scheme` block decides (`applyTheme` in
`stores/settings.svelte.ts`); the manual override persists in Settings. Focus
rings are always visible (`:focus-visible`, a 2px `--accent` outline).
The extension icon does not read these tokens: `scripts/gen-icons.mjs`
hardcodes the 1.0 accent, `#6d4aff`, so the toolbar icon kept its violet when
the UI moved to `#6447f0`.
## 2. Popup (340 px × auto)
```
┌──────────────────────────────┐
│ ◆ BookmarkMagic v1.0 │ header: icon + name + version
├──────────────────────────────┤
│ [⬆ Import bookmarks… ] │ → manager#import
│ [⬇ Export bookmarks… ] │ → manager#export
│ [🗂 Open manager ] │ → manager#edit
├──────────────────────────────┤
│ 1 284 bookmarks · 96 folders │ footer: live count (getTree stats) + ⚙ → #settings
└──────────────────────────────┘
┌──────────────────────────────────┐
│ ◆ BookmarkMagic v1.x.y │ mark + name + version (mono)
├────────────────┬─────────────────┤
│ BOOKMARKS │ FOLDERS │ readout: what lives INSIDE the roots
│ 1 284 │ 96 │
├────────────────┴─────────────────┤
│ [⬆ Import bookmarks… ›]│ tile + one-line hint → manager#import
│ [⬇ Export bookmarks… ›]│ → manager#export
│ [✎ Open manager ›]│ → manager#edit
├──────────────────────────────────┤
│ ● local only ⚙ │ ⚙ → manager#settings
└──────────────────────────────────┘
```
Legal not yet accepted → buttons still open the Manager (the gate lives
The counts walk the tree once and **leave out the three permanent roots** —
1.0.x counted them, so an empty profile read "0 bookmarks · 3 folders". A failed
read shows `—`. Each tile hands its route to `openManager`
(`browser/open-manager.ts`): an open Manager tab is focused and asked over a
`BroadcastChannel` to switch to that route — refused, with the busy toast, while
an import is writing (`03 §5`) — and otherwise a new tab opens at the hash.
1.0.x only focused the open tab, so "Export" landed wherever it had been.
Legal not yet accepted → the tiles still open the Manager (the gate lives
there). No heavy work in the popup, ever.
## 3. Manager layout
```
┌────────────────────────────────────────────────────────────┐
│ ◆ BookmarkMagic [Import][Export][Edit] 🌐 ◐ │ header: brand · TabBar · lang · theme
├────────────────────────────────────────────────────────────┤
│ <active tab content> │
├────────────────────────────────────────────────────────────┤
│ v1.0.0 · GPL-3.0 · GitHub ↗ Settings · About │ slim footer
└────────────────────────────────────────────────────────────┘
┌──────────────────────────────────────────────────────────────────────────────────────────┐
│ ◆ BookmarkMagic ~/edit [⬆ Import][⬇ Export][✎ Edit] [◍ English ▾] [▭|☀|☾] │ header
├──────────────────────────────────────────────────────────────────────────────────────────┤
│ <active tab content> │
├──────────────────────────────────────────────────────────────────────────────────────────┤
│ ● local only │ bookmarks, storage │ v1.x.y │ GPL-3.0 │ GitHub ↗ ⚙ Settings │ ⓘ About │ status bar
└──────────────────────────────────────────────────────────────────────────────────────────┘
```
Max content width 960px, centered. Settings/About open as tabs too (footer
links = same routes). `<LegalGate>` renders as a full overlay when required.
- **Header** (sticky, translucent over the content): the brand mark (an accent
tile whose logo spark pulses), the name, and the route as a mono crumb
`~/<route>` (hidden under 640px); `TabBar` — Import/Export/Edit as icon +
label in a sunken track, with one raised pill that slides to the active tab
(labels collapse to icons under 560px; no pill on `#settings`/`#about`); then
the compact language select and theme control.
- **Status bar** (IDE-style: mono, sunken, sticky at the bottom): `local only`
(a green dot; its title says the extension cannot send anything) ·
`bookmarks, storage`, the only two permissions · `v<version>` · `GPL-3.0` ·
`GitHub ↗` · and, right-aligned, `Settings` and `About`. The page is a flex
column at least the window's height, so the bar sits at the bottom even
under a short tab.
Max content width `--width-page` (1040px), centered. The side column of
#import, #export and the duplicate panel is `--width-side` (360px); two-column
layouts stack under 820px. Settings/About open as tabs too (the status-bar
buttons = same routes, and both are disabled while an import is writing — see
`03 §5`). The version is read from the manifest at runtime
(`browser/app-info.ts`), never hardcoded. Every route sets the document title,
`<Route> · BookmarkMagic`.
The theme control is a **three-way segmented control** (System · Light · Dark —
monitor/sun/moon icons in the header, words in `#settings`), not a cycling `◐`
glyph. Rationale: one code path shared with the `#settings` row, and the
current choice is visible rather than inferred — a cycling button conflates
"what am I" with "what will I become", which fights §5.
`<LegalGate>` fills the **content region**, not the viewport. `docs/14 §2`
(echoed in `03 §4` and the `15` decision log) requires `#settings` and `#about`
to stay reachable while the gate is up, and a literal `inset: 0` scrim would
bury the status-bar links that get you there. So: a full-bleed panel inside
`<main>`, with the header and status bar still live. `TabBar`'s `blocked` prop
marks the three gated tabs with a lock icon and an "accept the terms" title,
but they stay **clickable** — the gate renders in their place, and inert
buttons stranded a first-run user who had gone to `#settings` first. A side
effect worth keeping — the Import/Export/Edit tabs never mount before
acceptance, so nothing touches `chrome.bookmarks` until the user has agreed to
the terms.
### 3.1 #import
1. **Idle:** `<DropZone>` (dashed border, accent on dragover) — "Drop a
bookmark file or *browse* — .html, .json, .csv · max 25 MB".
2. **Parsed:** two-column: left `<TreePreview>` (read-only tree, badges
`new`/`dup`); right `<StatsCard>` (bookmarks / folders / depth /
duplicates) + `<WarningList>` (collapsible) + `<ImportOptions>`:
- Merge mode radio (New folder ▸ default · Merge · Replace all).
Replace shows a danger callout: "Deletes ALL current bookmarks. A JSON
safety backup will download first."
- `[x] Skip duplicates already in this browser (n found)` — **disabled and
unchecked when Replace is selected**, with the note "Existing bookmarks
are being replaced". Skipping against a tree that is about to be deleted
would silently drop everything (`03 §1`, `05 §3`).
- Primary button `Import n bookmarks`, where n is `stats.bookmarkCount`
(bookmarks only). The progress bar uses `stats.toCreate` (folders
included) — two different numbers by design (`02 §4`).
3. **Writing:** `<ProgressBar>` (determinate) + current path line +
`Cancel` + "Keep this tab open" notice.
4. **Done:** `<ResultCard>` (created / skipped / warnings) + `[Open Edit tab]`
`[Import another file]`. Cancelled/error variants include copyable detail.
Numbered mono step labels (`01 · SOURCE` … `04 · WRITING`) head each stage.
1. **Idle — 01 · Source:** `<DropZone>`, a single button-shaped target (so the
keyboard gets the file picker for free) with a marching-ants border that
travels on hover and dragover: "Drop a bookmark file or click to browse ·
max 25 MB", and a line naming what it reads — browser HTML exports, CSV,
BookmarkMagic and Firefox JSON backups, Chrome's own `Bookmarks` file. The
picker has **no `accept` filter** (`03 §1` step 1); only the first file of a
multi-file drop is read. While reading: "Reading <name>…".
2. **Parsed:** two columns.
- Left, **02 · Preview**, with the file name and the detected format as
pills, then `<TreePreview>` (read-only nested lists, §5): `new`/`dup`
badges, a child count on every folder, and on a top-level folder the file
marks as a browser root a `→ bar` / `→ Other` / `→ Mobile` pill — where
Merge and Replace unwrap it (`03 §1`).
- Right, **03 · Options**: `<StatsCard>` readout (bookmarks · folders · max
depth · duplicates, the last in `--warn` when non-zero) + `<WarningList>`
(collapsible, one plural line per code) + `<ImportOptions>`:
- Merge mode as three cards with an icon and a one-line note (New folder ▸
default · Merge · Replace all). Replace shows a danger callout: "This
deletes ALL current bookmarks. A JSON safety backup is saved first, and
nothing is deleted until that succeeds."
- `[x] Skip duplicates already in this browser (n found)` — **disabled and
unchecked when Replace is selected**, with the note "Not applicable:
Replace deletes your current bookmarks first." Skipping against a tree
that is about to be deleted would silently drop everything (`03 §1`,
`05 §3`).
- The today's-date notice, then the primary button `Import n bookmarks`,
danger-styled for Replace. **n comes from a preview plan** —
`previewPlan` runs `buildImportPlan` against the preview-time snapshot
with the chosen mode and dedupe — so links the user chose to skip are
not counted; the write re-plans against a fresh read at Start
(`03 §1` step 7). The progress bar uses `stats.toCreate` (folders
included) — two different numbers by design (`02 §4`).
- **Replace asks first.** A danger `ConfirmDialog` (focus on Cancel) states
both sides exactly: "n bookmarks and m folders in this browser will be
deleted, after a safety backup is saved. Then n′ bookmarks and m′ folders
from <file> are written." The current counts are everything inside the
writable roots, from the preview-time read (`prepareImport`'s `current`);
the incoming ones are the preview plan's. Confirm reads "Back up and
replace" (`09` T4).
3. **Backing up → attesting → clearing** (Replace only, `03 §1` step 6b): a
warning while the save dialog is open; on the fallback path a blocking
confirmation ("I have the backup — delete and replace" / Cancel); then a
danger callout while the tree is deleted, with **no Cancel**.
4. **Writing — 04 · Writing:** striped determinate `<ProgressBar>` (the stripes
travel only when motion is allowed) + "Importing… done / total" + the
current path + "Keep this tab open" + `Cancel`. The first create already
reports, so the bar moves at once rather than after 50 items.
5. **Report** (`<ImportReport>`). Done: a success callout "Done — n bookmarks
and m folders created.", then what was skipped (already in this browser vs
repeated in the file), how many existing folders Merge reused (when any),
**where** it all went (the new folder's name under Other bookmarks /
appended to the folders it belongs in / now exactly what the file holds),
and the today's-date notice. A cancelled or failed run says how many items
were created and — when something was written outside Replace — where;
after a Replace has cleared the tree it names the backup as the user saved
it. Failures add an `<ErrorCallout>` (localized message + technical
detail). Actions: `[Open Edit tab]` (done only) · `[Import another file]`.
### 3.2 #export
Left: `<FolderPickTree>` with tri-state checkboxes under "Everything" master
toggle. Right: `<FormatSelect>` (radio cards HTML · JSON · CSV · Markdown,
one-line description each + per-format note, e.g. CSV: "empty folders not
preserved"), format options (CSV delimiter, MD style), then
`Export n bookmarks ⬇`. Success toast with filename.
Two columns, like #import.
- **01 · What to export:** `<FolderPickTree>` — an "Everything" master
checkbox, indeterminate while a partial selection exists, over nested lists
of folder checkboxes with tri-state (checked / indeterminate / unchecked,
from one `checkStates` pass over the tree — `core/select.ts`). Folders only:
a bookmark travels with its folder, and each folder shows how many bookmarks
it holds directly. The top level starts open, deeper levels closed, and
children mount 500 at a time (`05 §9`). Not `role="tree"` (§5).
- **02 · Format:** `<FormatSelect>` — radio cards HTML · JSON · CSV ·
Markdown, each with an icon, its extension and a one-line note; then the
per-format extras: Markdown says it is share-only (BookmarkMagic cannot
import it back), CSV says empty folders and the toolbar are not preserved
and offers the delimiter, Markdown offers its layout. Defaults come from
Settings.
- `Export n bookmarks`, disabled at zero. Success is a toast "Download started:
<file>" — *started*, because the anchor download gives no completion signal
and the browser may still ask where to save (`03 §2`). A failure stays on
screen as an `<ErrorCallout>` with its technical detail.
### 3.3 #edit
Toolbar: `<SearchInput>` (⌘/Ctrl-F focuses) · `New folder` ·
`Find duplicates` · `Expand all / Collapse all`.
Body: `<TreeView>` (editable) — rows: disclosure ▸, favicon placeholder
(folder/link glyph — no remote favicons), title, muted domain, hover-actions
(rename ✎, delete 🗑, ⋯ menu: Move to…, Copy URL, Open).
Interactions: drag & drop with drop-line indicator (HTML5 DnD wrapped in a
Svelte action `draggableNode`); F2 rename; Del delete (confirm shows
descendant count for folders); Enter opens bookmark; full arrow-key tree
navigation (see §5). `<DuplicatePanel>` slides in from right: groups by URL,
per-item delete + "Keep first in each group" bulk (confirm dialog).
Empty state: friendly illustration + "Import some bookmarks →".
**Toolbar** (`EditToolbar`, `role="toolbar"`): search (⌘/Ctrl-F focuses it from
anywhere in the tab) · `New folder` · `Sort A→Z` · `Find duplicates` (a
toggle, `aria-pressed`) · icon-only `Expand all` / `Collapse all`. Sort acts on
the focused folder, or the folder holding the focused bookmark, and is
disabled unless that folder has two or more children and is not
policy-managed. New folder, Sort and the duplicate panel's deletes are
disabled while a bulk command runs.
**Tree** (`TreeList` + `TreeRow`): one flat `role="tree"` list in a
fixed-height scroller, mounted 500 rows at a time with a "Show more" row
(`05 §9`); the roots start open. A row: disclosure chevron · glyph (folder,
open folder, link — a lock for a policy-managed node) · title (an untitled
bookmark shows its address, muted, in mono) · host · a child count on folders
(bookmarks and folders — a Firefox separator is not counted) ·
⚠ on an address Open refuses (`09` T3) · action buttons, shown on hover and on
the focused row: **Open** and **Copy link** (bookmarks), **Sort A→Z**
(sortable folders), **Rename**, **Move to…**, **Delete** (editable nodes only —
never the permanent roots or a policy-managed node). No remote favicons.
Search matches render bold in the accent colour.
- **Rename:** an inline input (F2 or the button), focused with its text
selected. Enter or leaving the field commits, trimmed — a blank or unchanged
title does nothing; Esc cancels. After Enter or Esc, focus is back on the
tree.
- **Delete:** a confirmation naming the item (an untitled bookmark by its
address), with the descendant count for a folder; when the deleted row had
focus, focus moves to the next row (else the previous).
- **New folder:** created in the focused folder, beside a focused bookmark,
else in the first writable root, and opened in rename with every folder above
it open; a search that would hide it is cleared.
- **While a bulk command runs** (Sort A→Z, keep-first), every row action that
writes is disabled and its keys do nothing, and drag is off.
- **Sort A→Z** (`05 §10`): planned first, so the confirmation states how many
items move and that the browser has no undo; an already sorted folder gets a
toast instead of a dialog.
- **Drag & drop**, from any editable row not being renamed: the row under the
pointer shows where the item will land — a line along its top (upper
quarter: before), along its bottom (lower quarter: after), or a dashed
outline (the middle half of a folder: into). A bookmark row splits at the
half. An illegal drop — onto itself, into its own subtree, beside a
permanent root, into a managed folder — shows nothing and does nothing; a
cancelled drag clears every highlight.
- **Alt+↑ / Alt+↓** (since v1.2.1) is the keyboard's before/after: the focused
row changes places with the sibling shown above or below it — under a search,
the nearest one the search still shows. It is the same `planDrop` a drag
resolves through (`05 §10`), so legality is one rule: nothing happens at
either end of a folder, on a permanent root, on a policy-managed node or
while a bulk command runs. Focus stays on the row, and the new position is
spoken (§5).
- **Move to…** (`MoveToDialog`, built on `Modal`): a filter box over every
folder the item may move into, each as its full path, indented — the item
itself, its subtree, its current parent and managed folders left out.
Picking one appends the item there. The list renders only while the dialog
is open.
- **`<DuplicatePanel>`**, in the side column: "n duplicated links · m extra
copies" (each count pluralized on its own), then each group under its
normalized URL, largest first. Every copy
shows its title and the folder it lives in; the first is marked "kept", the
others get a delete button; "Keep the first of each, delete m copies" sits
behind a danger confirmation with that number.
A failed command shows above the tree as an `<ErrorCallout>` (localized
message, technical detail), plus "moved / deleted d of t" when a bulk command
stopped part-way; the tree is then re-read. Empty states are text only:
"Reading your bookmarks…", "No bookmarks yet — import some to get started.",
"Nothing matches that search."
### 3.4 #settings
Single column of `<SettingRow>`s: Language (EN/VI/JA select) · Theme
Single column of **six** `<SettingRow>`s: Language · Theme
(System/Light/Dark segmented) · Default export format · Default import mode ·
CSV delimiter. Auto-save + saved toast. Footer: "Reset to defaults".
CSV delimiter · Markdown layout.
- The Language select offers **six** options — one per shipped locale plus
"Automatic": `Settings.locale` is `'auto' | Locale` (`en`, `vi`, `ja`,
`zh-CN`, `ro` — `07 §2`) and `DEFAULT_SETTINGS.locale === 'auto'`, so
"Automatic (follow the browser)" has to be selectable or the default is
unreachable. The options are built from `LOCALES`, in that order. The
language labels are **endonyms**, identical in every dictionary — a Japanese
user hunting for Vietnamese looks for "Tiếng Việt", a Romanian one for
"Română" — and `dictionaries.test.ts` enforces that they match.
- Romanian runs roughly a third longer than English, and Chinese far shorter.
Neither may truncate a control, wrap a tab label or push the popup past its
340 px width — the visual sweep (`11 §5`) photographs every route in both,
and that sweep, not a test, is where overflow is caught.
- Markdown layout is the sixth row because `markdownStyle` is a persisted
field; without it the only place to change it was a transient `#export`
control that never wrote back.
- Four of the six rows reuse the Export/Import tabs' own i18n keys rather than
inventing parallel wording, so the two surfaces cannot describe the same
choice differently.
Auto-save + saved toast — the toast reports the resolved `SaveOutcome`, so a
failed write says so rather than claiming success. Footer: "Reset to defaults",
behind a `<ConfirmDialog>` (six preferences is enough to be worth a confirm).
### 3.5 #about
`<AboutCard>`: logo, name, version (from manifest at runtime), tagline;
links: **GitHub repo ↗** · Report an issue ↗ · Changelog ↗;
**Third-party dependencies: None 🎉** (statement, satisfies the requirement);
Donate: GitHub Sponsors (`poli0981`) ↗ · Ko-fi (`skullmute`) ↗ — full handle
list in `14 §5`, sourced from `.github/FUNDING.yml`;
links: **GitHub repo ↗** · Report an issue ↗ · Changelog ↗ · Accessibility ↗ ·
Store listing ↗;
**Third-party code:** no runtime dependencies are installed, and the two
MIT-licensed pieces the build compiles in are named — the Svelte runtime and
WXT's one-line browser shim — with their notices shipped in the package as
`THIRD_PARTY_NOTICES.txt` (since v1.1.0; it used to say "Third-party
dependencies: None", which was never true of the bundle);
Donate: **all five** handles from `14 §5` / `.github/FUNDING.yml` — GitHub
Sponsors · Ko-fi · Buy Me a Coffee · Patreon · PayPal (platform names are brand
names and stay untranslated, `07 §4`);
Legal block: EULA · License (GPL-3.0) · Disclaimer · Privacy Policy — each →
GitHub `legal/` file; "Legal terms accepted on <date> · version n".
GitHub `legal/` file; "Legal terms accepted on <date> · version n" — where `n`
is the version the user **accepted**, from the stored record, not the current
`LEGAL_VERSION` constant. Reachable before acceptance (`14 §2`), so it also has
a not-yet-accepted state, and a dateless variant for a stored record whose
timestamp is missing or unparseable;
Diagnostics: a one-line note and **Copy diagnostics**, which puts this tab's
local event log on the clipboard on an explicit click (`09 §7`).
"Changelog" points at `CHANGELOG.md` on `main`. (It pointed at the repo's
releases page until Phase 5 wrote that file — an empty releases page beats a 404
opened from a legal surface. `tests/unit/links.test.ts` now pins both the URL
shape and the file's existence, so the fallback cannot silently return.)
"Accessibility" (since v1.2.1) points at `ACCESSIBILITY.md` on `main` — the
statement, the full key list and how to report a barrier. Someone who cannot
use a screen has no other route from inside the product to either, and the
tree's keys are shown nowhere in the UI. The same test pins its URL and the
file's existence.
"Store listing" points at the listing the running copy came from — it is the
only route a user has from inside the product to rate or review it, which
`13 §6` depends on. Since v1.3.0 one package serves the Chrome Web Store and
Edge Add-ons, so the link is chosen at run time (`links.ts` `storeUrlFor`):
the Firefox build → the AMO listing, addressed by the gecko id; a Chromium
copy whose `runtime.id` is the Chrome Web Store item id (`00 §9`) → that
listing; anything else — an Edge Add-ons install, an unpacked build → the
README's install section, which lists every store. The label was "Chrome Web
Store" until then.
**No email address appears anywhere in the product.** Since v1.1.0 the
project's addresses are per purpose (`security@` in `SECURITY.md`, `privacy@` in
`legal/PRIVACY.md`, `accessibility@` in `ACCESSIBILITY.md`, the rest in the
legal files and the README's contact table; `contact@` is retired), and none of them is inside the extension. An address on
an in-product surface invites users to mail their real bookmark file, and
receiving unsanitized personal URLs is exactly what `09` and the privacy policy
are written to avoid (`15` decision log, 2026-08-03). `tests/unit/links.test.ts`
fails on a `mailto:` or an `@poli0981.dev` address anywhere under `src/` —
widened in v1.1.0 from `links.ts` alone.
## 4. Component inventory (`src/lib/components/`)
@@ -126,23 +419,210 @@ GitHub `legal/` file; "Legal terms accepted on <date> · version n".
`TreeView` · `TreeNode` (recursive, `{#await}`-free, lazy children) ·
`FolderPickTree` · `StatsCard` · `WarningList` · `ImportOptions` ·
`FormatSelect` · `ProgressBar` · `ResultCard` · `SearchInput` ·
`DuplicatePanel` · `ConfirmDialog` (native `<dialog>`) · `Toast` (queue,
auto-dismiss 4s, ARIA `status`) · `SettingRow` · `AboutCard` · `LegalGate` ·
`Button` · `Callout`.
`DuplicatePanel` · `Modal` (native `<dialog>`; every dialog is built on it) ·
`ConfirmDialog` · `Toast` (info and success one at a time, up to three queued,
auto-dismissed after 4 s; **the latest failure pinned above them until
dismissed**; polite and assertive live regions) · `SettingRow` · `AboutCard` · `LegalGate` · `Button` ·
`Callout` · `ErrorCallout` (localized message + technical detail) · `Icon`
(§6).
Rule: components ≤ 300 lines; recursive tree logic isolated in `TreeNode`.
Rule: components follow `10 §1` (300 lines soft, 500 hard); recursive tree
logic stays in the node components.
As built, some inventory names map differently — recorded so the list is not
read as a list of missing files:
| Inventory name | Realized as |
|---|---|
| `AboutCard` | `AboutTab.svelte`, for symmetry with the other four tab shells |
| `TreeView` | `TreeList.svelte` (the `role="tree"` list, a window of rows around the focus) + `TreeRow.svelte` (one row) with `RowActions.svelte` and `RenameInput.svelte`. State and commands live in `stores/edit-{view,commands,session}.svelte.ts`, the flattening in `edit/tree-keyboard.ts`, the key handling in `edit/tree-keys.ts`; `EditTab.svelte` is markup and wiring |
| `TreeNode` | `TreePreviewNode.svelte` (import preview) + `FolderPickNode.svelte` (export picker) |
| `ResultCard` | `ImportReport.svelte` (step 05, with its actions); step 04 is `ImportProgress.svelte`, and `ImportAnnouncer.svelte` is the import's one live region |
| `SearchInput` | inside `EditToolbar.svelte` |
| `Icon` | `icons/Icon.svelte` |
| — | plus `SettingsTab.svelte` (the fifth tab shell), `EditToolbar.svelte`, `MoveToDialog.svelte` and `StatusBar.svelte` (the Manager's footer) |
`Toast`'s queue and timers live in `stores/toast.svelte.ts`, not the component:
one `<Toast>` mounts at the App root while the route chain below it unmounts on
every navigation, so component-owned timers would leak by construction. A
`danger` toast has a slot of its own, above the queue, and no timer (since
v1.1.0): four seconds is too short to read a failure, let alone act on it. A
newer failure replaces it; a repeat of the same one keeps it. 1.1.0's first cut
held failures at the head of the one queue instead, and every later toast —
"Link copied", "Saved" — waited unseen behind it.
## 5. Accessibility & keyboard
- Tree uses `role="tree"/"treeitem"`, `aria-expanded`, `aria-level`; arrow
keys per WAI-ARIA tree pattern (↑↓ move, → expand/first child, ← collapse/
parent, Home/End, type-ahead by first letter).
- All actions reachable without a mouse; DnD has menu-based "Move to…" parity.
- Dialogs: native `<dialog>` + focus trap + `Esc`.
- Progress announced via `aria-live="polite"` every 10%.
- Contrast ≥ 4.5:1 in both themes (tokens chosen accordingly).
- **#edit is the one ARIA tree** (`TreeList`): `role="tree"` on a focusable
`<ul>` — one tab stop — with roving focus through `aria-activedescendant`.
Rows are `treeitem`s with `aria-level`, `aria-expanded` (expandable rows
only), `aria-selected` and explicit **`aria-setsize`/`aria-posinset`**: the
rows render flat, so the browser cannot count siblings, and without them a
screen reader said "1 of 1" on every row. `aria-busy` while a bulk command
runs. Tabbing in with nothing focused focuses the first row.
- Keys on the tree (`edit/tree-keyboard.ts`): ↑/↓ move; → opens a closed folder
or steps into an open one; ← closes it or steps out to the parent;
Home/End; type-ahead by first letter, wrapping. → on an empty folder does
nothing, even after "Expand all" put it in the open set. Enter opens a
bookmark or toggles a folder; F2 renames; Del asks to delete; the **menu key or
Shift+F10** opens "Move to…"; **Alt+↑ / Alt+↓** moves the row one place up
or down among its siblings (§3.3); **Ctrl/⌘+C** copies the focused
bookmark's link. Ctrl/⌘+F focuses search from anywhere in the tab. Keys
typed into the rename input belong to it. `ACCESSIBILITY.md` carries the
same list for users, and the About tab links to it — apart from "Ctrl F" on
the search box, nothing in the UI shows these keys yet. Tabbing in with
nothing focused focuses the first row; a **mouse** press does not (since
v1.2.1): the press focuses the list too, and choosing the first row then
scrolled a long tree to the top under the pointer.
- **Focus never dangles.** A focused row that leaves the screen hands focus to
its nearest visible folder (`03 §3`). After a delete, focus goes back where
the delete was asked for — the tree, or in the duplicate panel the next
copy's delete button, else the panel's close button — because the dialog
cannot return it to a button that went with what it deleted. A step that
replaces another (the import's preview, progress and result) moves focus to
its own heading (`components/focus-heading.ts`) — only when focus was lost or
already inside that tab, never stolen from elsewhere; inside step 04, a phase
change that removes the focused control (confirming the backup) hands focus
to the step's heading again. The import's outcome is spoken by one
always-present live region (`ImportAnnouncer`).
Since v1.2.1 three more places that dropped focus on `<body>` are closed. A
**route change** whose control went with the old route ("Open in Edit" on
the import report) moves focus to `<main>` — only when focus was lost, and
never on the first load. After **"Keep the first of each"** focus lands on
the panel's close button, the delete buttons having gone with the copies.
After a confirmed **Sort A→Z** from the toolbar — whose button is disabled
while the sort runs, which is what dropped it — focus goes to the tree.
- **Separators (Firefox, since v1.3.0)** render as a line inside an
`aria-hidden` list item between the `treeitem`s — outside the accessibility
tree, so the tree still owns only tree items, and with no `role`, which a
hidden element does not need. They take no focus, so ↑/↓, Home/End and
type-ahead pass over them, and `aria-posinset`/`aria-setsize` count the
items around them, not the separators. Alt+↑/↓ does step past one, one place
at a time, as a drag would — and since the separator is not counted, the
spoken "position n of m" does not change on that step. A known limitation
(`ACCESSIBILITY.md`): a screen reader is not told where the separators are.
- **The tree says what Alt+↑/↓ did.** One always-present polite live region in
the tab speaks "<title>: position n of m" after each move — n and m being
the row's own `aria-posinset` and `aria-setsize`, so under a search they
count the siblings on screen, as the tree does. The attributes change too,
but a screen reader does not re-read the active descendant for an attribute
change, so without the region the move is silent. The region is emptied
before each message: set to the text it already holds, it would say nothing.
- **Dialogs** (`Modal`): the × is named "Dismiss" — it was named after the
dialog, so a screen reader announced the cancel button as "Delete this
item?" — and a confirmation's body is its `aria-describedby`, so the counts
are read with the title.
- **Row buttons are not tab stops** (`tabindex="-1"`; the disclosure is
`aria-hidden`). They are mouse shortcuts, and each has a key above — Open
(Enter), Copy link (Ctrl+C), Rename (F2), Move to… (menu key), Delete (Del);
Sort A→Z is also on the toolbar. **A click on one, or on the chevron, hands
focus back to the tree** (since v1.2.1, `focusOwningTree`): Chrome focuses a
`tabindex="-1"` button on click, the tree's key handler ignores keys aimed at
a row's own control, and so one click used to switch the arrow keys off
until the next click on a row. It also means "Move to…" opened from the row
button returns focus to the tree, not to a button on a row that has moved.
With no row focused yet, the clicked control's row becomes the focused one,
so the keys start from where the click was.
- Drag & drop has keyboard parity: **into a folder** is "Move to…", and
**before/after a sibling** is Alt+↑ / Alt+↓, one place at a time (since
v1.2.1; through 1.2.0 Sort A→Z was the only keyboard reorder). What is still
missing is a **pointer** route that is not a drag — a click-only way to
place an item (WCAG 2.5.7); `ACCESSIBILITY.md` lists it as a known
limitation.
- **Read-only previews are lists, not trees.** The import preview and the
export picker are nested `<ul>`s with disclosure buttons (`aria-expanded`,
named "Expand folder: <title>") and, in the picker, checkboxes; plain Tab,
Enter and Space are their whole keyboard interface. Both used to carry `role="tree"`
without the arrow keys it promises, announcing a widget that ignored the
keyboard.
- Dialogs: every one is built on `Modal.svelte` — a native `<dialog>` opened
with `showModal()`, which brings the focus trap, the inert page, Esc and the
top layer. Focus moves in on open (the first control; **Cancel** in a
`ConfirmDialog`, so Enter never confirms a destructive action) and returns
to the opener on close; Esc, the backdrop and × cancel, and confirming never
also fires the cancel handler.
- Progress announced via `aria-live="polite"` every 10%. Toasts use two
always-present live regions: polite for info and success, assertive for
failures. The popup readout is `aria-live="polite"`.
- The theme control is a real radiogroup: arrow keys and Home/End move the
choice, one tab stop.
- **Reduced motion:** every animation, and every transition that moves
something, sits inside `@media (prefers-reduced-motion: no-preference)`.
`tests/unit/styles/motion.test.ts` parses every `.svelte` and `.css` file
under `src/` and fails on one outside it; colour, opacity and shadow fades
are not motion and are exempt. State that must show either way — an open
folder's turned chevron — is a static transform, not a transition.
- **Contrast:** text ≥ 4.5:1; interactive boundaries and the focus ring ≥ 3:1 —
in light and both dark variants (§1, enforced by `contrast.test.ts` at token
level). Disabled controls say so with colour and the cursor, never opacity,
which would drop text under the floor while it still has to be read.
- **A ring drawn inside a filled control takes the fill's text colour.** The
global ring is `--accent`, outside the control (`outline-offset: 2px`), where
it sits on the page. The theme control insets it (`-2px`) to stay inside the
group's border — and its selected segment is filled with `--accent`, so
through 1.2.0 the ring was accent on accent: invisible, on the one segment
roving focus ever lands on. An inset ring on an accent fill is `--accent-fg`
(≥ 4.5:1 on `--accent`, already a tested pair), 4px in rather than 2, so
the fill shows on both sides of it — at the very edge, a ring in the page's
colour only made the segment look smaller. `styles/focus-ring.test.ts` fails
on a component that insets a ring over an accent fill without the switch.
- **Forced colours** (Windows contrast themes; since v1.2.1). The browser
replaces every colour and removes `box-shadow` and background images, so
state shown only by a fill or a shadow vanishes. Each such state gets a
system-colour equivalent inside `@media (forced-colors: active)`: the tree's
focused row and its drop lines, the selected theme segment, the current tab
and status-bar entry, the selected import-mode and export-format cards, the
progress fill, and the drop zone's edge (drawn with background gradients,
which are images). **A border or an outline in `Highlight` wherever the
state has a label**: Chrome paints a backplate in the page colour behind
forced text, so a label on a `Highlight` fill became a box that hid it — the
first cut of this did exactly that to the current tab. The one fill with a
label on it, the selected theme segment, sets `forced-color-adjust: none`
with `Highlight` / `HighlightText`, because its outline is already the focus
ring's.
`styles/forced-colors.test.ts` holds the list of components that must carry
the block; like the contrast pair list it is hand-maintained, so a new
filled state has to be added to it.
- **Target size:** every pointer target is at least 24 × 24 CSS px (WCAG 2.2,
2.5.8) — since v1.2.1 the row buttons (were 22), the three disclosure
chevrons (16), the toast and dialog dismiss buttons, the popup's gear and
"Show more" in the export picker and the import preview. The glyphs keep
their size; the hit area grows. "Every target" means every button: native
checkboxes and radios keep the browser's size inside a label that is the
target, and links in running text are exempt by the criterion itself.
- **A ring that would be clipped is drawn inside.** The tree's frame and the
"Move to…" list clip their overflow, and the global ring sits 2px outside
the control: on "Show earlier / Show more" and on the folder buttons it was
cut off. Those use `outline-offset: -2px`.
- **Placeholders use `--fg-muted`**, set once in `base.css`. The browser's
default placeholder grey is not a token, so `contrast.test.ts` never saw it
— about 4:1 on `--bg-sunken`.
- **The selected theme segment keeps its label on hover.** `button:hover`
outranks `.selected`, and `--fg` on the accent fill is under 3:1.
- **The public statement is `ACCESSIBILITY.md`** at the repository root: the
goal (WCAG 2.2 AA — a goal, not a conformance claim), what was tested and
with what, the known limitations, and how to report a barrier. This section
is the specification; the statement is what users are told, and a change
here that makes the statement false has to change it too (`11 §5`).
## 6. Iconography
Inline SVG only (16/20px, `currentColor`), stored as tiny Svelte components in
`components/icons/`. No icon-font, no external icon package.
One component, `components/icons/Icon.svelte`: 34 named glyphs drawn for this
project on a 24-unit grid — 1.75 stroke, round caps, `currentColor`, so every
icon takes its colour and theme from the control around it. Props: `name`,
`size` (default 16), `motion`, `turned` (a quarter turn — the open disclosure
chevron). Decorative by contract (`aria-hidden`, `focusable="false"`): the
control carries the accessible name, which is why an icon-only `Button` takes a
`label`. No icon font, no icon package, and no emoji — 1.0.x's emoji rendered
differently on every OS and could not follow the theme.
Motion variants, all defined inside the reduced-motion guard (§5), so asking
for one is always safe:
| `motion` | What moves | Used on |
|---|---|---|
| `spin` | gear and sun turn a quarter while the enclosing button or link is hovered or focused | status-bar and popup Settings, the Light theme choice |
| `bob` | the arrow bobs, looping, while hovered — or while a `.dragging` ancestor is (a file over the drop zone, a row being dragged) | tab icons, popup tiles, the drop zone, Start and Export buttons, Sort and Move to… |
| `tilt` | the trash lid lifts on hover or focus | every delete |
| `draw` | the check draws itself once, on appearing | success callouts and toasts |
| `pulse` | the logo's spark breathes | the Manager header mark |
+283 -45
View File
@@ -1,7 +1,9 @@
# 07 — Internationalization (EN / VI / JA)
# 07 — Internationalization (EN / VI / JA / ZH-CN / RO)
Baseline matches the portfolio standard: **English (default), Vietnamese,
Japanese**. Two mechanisms with a strict split:
Japanese**. v1.2.0 adds **Simplified Chinese (`zh-CN`) and Romanian (`ro`)** —
the two languages the CWS dashboard showed real installs and active users in
after the first three. Two mechanisms with a strict split:
| Layer | Mechanism | Why |
|---|---|---|
@@ -11,9 +13,11 @@ Japanese**. Two mechanisms with a strict split:
## 1. `_locales/` (manifest-level only)
```
public/_locales/en/messages.json ← default_locale
public/_locales/vi/messages.json
public/_locales/ja/messages.json
src/public/_locales/en/messages.json ← default_locale
src/public/_locales/vi/messages.json
src/public/_locales/ja/messages.json
src/public/_locales/zh_CN/messages.json ← Chrome's directory name, underscore
src/public/_locales/ro/messages.json
```
```json
@@ -25,91 +29,325 @@ public/_locales/ja/messages.json
`wxt.config.ts` manifest: `name: "__MSG_appName__"`,
`description: "__MSG_appDesc__"`, `default_locale: "en"`.
Keep `appName` identical in all three locales (brand name is not translated);
`appDesc` is translated.
Keep `appName` identical in every locale (brand name is not translated);
`appDesc` is translated and stays ≤ 132 characters (the manifest limit, enforced
by `manifest.test.ts`).
Directory names are **Chrome's**, not BCP 47: `zh_CN`, with an underscore. The
runtime locale id is the BCP 47 tag `zh-CN` (§2). The two are mapped in `CHROME_LOCALE_DIRS` in `tests/helpers/locales.ts`; `manifest.test.ts`
uses it to fail on a missing `messages.json` and on a `_locales/` directory no
locale owns.
Chrome resolves a manifest string by trying the full UI locale, then its
language, then `default_locale` — so a Traditional Chinese browser (`zh_TW`)
falls back to **English**, never to `zh_CN`. §2's runtime rule deliberately
matches it, so the name in `chrome://extensions` and the UI agree.
## 2. Runtime i18n — `src/lib/i18n/`
```ts
// locales/en.ts (vi.ts, ja.ts mirror the exact same shape)
// resolve-locale.ts — the single list of shipped locales
export const LOCALES = ['en', 'vi', 'ja', 'zh-CN', 'ro'] as const;
export type Locale = (typeof LOCALES)[number];
```
`as const` is correct **here** — this is a list of ids, not a dictionary (the
ban below is about dictionaries). Every table keyed by locale is a
`Record<Locale, …>`, so a locale added to `LOCALES` and missing anywhere else is
a compile error rather than a silent English fallback: `dicts` in
`index.svelte.ts`, `TAGS` in `format.ts`. `storage.ts`'s allow-list is
`['auto', ...LOCALES]` and the Settings choices are built from the same array.
```ts
// locales/en.ts (every other locale mirrors the exact same shape)
import { importTab } from './en-import';
import { errors, warnings } from './en-notices';
const dict = {
common: { import: 'Import', export: 'Export', edit: 'Edit',
settings: 'Settings', about: 'About', cancel: 'Cancel', /* … */ },
import: {
dropHint: 'Drop a bookmark file or {browse} — .html, .json, .csv · max {size}',
stats: { bookmarks: '{n} bookmarks', duplicates: '{n} duplicates found' },
mode: { newFolder: 'Into a new folder (recommended)', merge: 'Merge into existing folders',
replace: 'Replace everything' },
replaceWarning: 'This deletes ALL current bookmarks. A JSON safety backup will download first.',
progress: 'Importing… {done} / {total}',
},
/* export, edit, settings, about, legal, errors … */
import: importTab, // en-import.ts: dropHint, mode, stats, progress …
/* popup, status, export, edit, settings, about, legal … */
warnings, // en-notices.ts
errors,
};
export default dict;
export type Dict = typeof dict; // widened: string, NOT the literal 'Import'
/** Widened (string, NOT the literal 'Import'); plural branches may add `few` (§5). */
export type Dict = Localized<typeof dict>;
```
```ts
// locales/vi.ts (ja.ts identical in shape)
// locales/vi.ts (ja.ts, zh-CN.ts, ro.ts identical in shape)
import type { Dict } from './en';
export default { /* … */ } satisfies Dict;
import { importTab } from './vi-import';
import { errors, warnings } from './vi-notices';
export default { /* …, */ import: importTab, warnings, errors } satisfies Dict;
// locales/vi-import.ts — each part is checked on its own
export const importTab = { /* … */ } satisfies Dict['import'];
```
**Each locale is three files** (since v1.1.0): `<lang>.ts`, `<lang>-notices.ts`
(`warnings` and `errors`) and `<lang>-import.ts` (the Import tab). `<lang>.ts`
re-assembles them, so the runtime shape and every key path are unchanged — the
split exists only to keep each file under the `10 §1` size limit as codes and
Import strings are added. In the non-English locales the parts are typed
`satisfies Dict['warnings']`, `Dict['errors']` and `Dict['import']`, so a
missing key fails `tsc` in the very file that lacks it. A new string goes in
whichever file holds its branch.
```ts
// index.svelte.ts
import en from './locales/en'; import vi from './locales/vi'; import ja from './locales/ja';
export type Locale = 'en' | 'vi' | 'ja';
const dicts = { en, vi, ja };
const dicts: Record<Locale, Dict> = { en, vi, ja, 'zh-CN': zhCN, ro };
let locale = $state<Locale>('en'); // hydrated from settings store
export function t(path: string, params?: Record<string, string | number>): string
// resolves dotted path in dicts[locale], falls back to en, interpolates {tokens}
export function setLocale(l: Locale) { locale = l; } // settings store persists
```
- `en.ts` is the **schema source of truth**; `vi`/`ja` are typed
- `en.ts` is the **schema source of truth**; every other locale is typed
`satisfies Dict` → missing keys fail `tsc` (compile-time completeness check,
no i18n framework needed).
- ⚠️ **Do not write `as const` on `en.ts`.** It would make `typeof dict` a tree
of *string literal* types, so `satisfies Dict` would demand
`vi.common.import === 'Import'` — every correct translation becomes a compile
error and the only way to make VI/JA build is to leave them in English.
- ⚠️ **Do not write `as const` on `en.ts`** (or any dictionary). It would make
`typeof dict` a tree of *string literal* types, so `satisfies Dict` would
demand `vi.common.import === 'Import'` — every correct translation becomes a
compile error and the only way to make a locale build is to leave it in
English.
- `Dict` is `Localized<typeof dict>`: `typeof dict` with every plural branch
(`{ one, other }`) widened to `{ one, other, few? }`. That optional `few` is
the only thing it adds — it lets Romanian carry its third form (§5) without
every other locale writing a dead one. Whether a locale carries `few` is
checked at runtime, not by the type.
- `Dict` is exported from `locales/en.ts` (a leaf module), **not** from
`index.svelte.ts`. That module imports vi/ja and holds runtime `$state`, so
having vi/ja import a type back from it forms a cycle that is only harmless
while the import stays type-only — fragile under `verbatimModuleSyntax`.
`index.svelte.ts`. That module imports every locale and holds runtime
`$state`, so having a locale import a type back from it forms a cycle that is
only harmless while the import stays type-only — fragile under
`verbatimModuleSyntax`.
- Interpolation is `{token}` replacement only. **No string concatenation of
sentence fragments** — full sentences per key, so VI/JA word order works.
- Initial locale resolution: saved setting → else map
`chrome.i18n.getUILanguage()` prefix (`vi*`→vi, `ja*`→ja) → else `en`.
sentence fragments** — full sentences per key, so word order works in every
language.
- The document language follows the resolved locale: `<html lang>` is set to the
locale id (`vi`, `zh-CN`, …). For `zh-CN` that is load-bearing — Chinese and
Japanese share code points, and `lang` is what makes Chrome pick a Simplified
Chinese font and glyph forms instead of Japanese ones.
**Initial locale resolution:** saved setting → else map
`chrome.i18n.getUILanguage()` → else `en`. The mapping (`resolveLocale`):
| Browser UI language | Resolves to |
|---|---|
| `vi`, `vi-*` | `vi` |
| `ja`, `ja-*` | `ja` |
| `zh-Hant*` (any region) | **`en`** — matches Chrome's own manifest fallback (§1); the user can still pick 简体中文 by hand |
| `zh-Hans*` (any region) | `zh-CN` |
| `zh-TW`, `zh-HK`, `zh-MO` (no script subtag) | **`en`**, as above |
| `zh`, `zh-CN`, `zh-SG` and every other `zh-*` region | `zh-CN` |
| `ro`, `ro-*` (incl. `ro-MD`) | `ro` |
| anything else | `en` |
The rows are checked top to bottom, so an explicit script wins over the region
(`zh-Hans-TW` is Simplified). Only whole subtags match: `vic` or `jav` (Javanese)
start with `vi`/`ja` but are not our locales. Extension and private-use subtags
(`-u-…`, `-x-…`) are ignored. `-` and `_` both separate subtags.
The `<option>` for each language carries its own `lang`, so the endonyms are
voiced and drawn in their own language whatever the UI language is.
## 3. Formatting rules
- Dates in UI: `new Intl.DateTimeFormat(localeTag, { dateStyle:'medium', timeStyle:'short' })`
with tags `en-US` / `vi-VN` / `ja-JP`.
- Numbers (counts): `Intl.NumberFormat(localeTag)` — VI uses `.` thousands.
with tags `en-US` / `vi-VN` / `ja-JP` / `zh-CN` / `ro-RO`.
- Numbers (counts): `Intl.NumberFormat(localeTag)` — VI and RO use `.`
thousands, EN, JA and ZH `,`.
Where these live: pure `localeTag` / `formatCount` / `formatDateTime` in
`src/lib/i18n/format.ts` (formatters cached per tag — `StatsCard` alone formats
four counts per paint), plus reactive `num()` / `dateTime()` wrappers in
`index.svelte.ts` that read the current locale. `formatDateTime` returns
`undefined` rather than a string on an unparseable input: `readLegal` coerces a
missing `acceptedAt` to `''`, and `Intl.format(new Date(''))` throws a
`RangeError` *inside a render*, which would blank the About tab.
Three rendered numbers deliberately do **not** go through `num()`, each with a
comment at the site so the next reader does not "finish the job":
| Site | Why |
|---|---|
| `ProgressBar`'s `{n}%` | 0–100; no shipped locale groups two digits, and it is the hottest render path in the app |
| `import.folderName`'s date | this bullet list already pins it to the localized *word* + an **ISO** date; localizing it would rename folders written into the user's browser |
| Export filenames and file contents | locale-independent so a file means the same thing whoever opens it |
ARIA numeric attributes (`aria-level`, `aria-valuenow`) are not display text and
stay raw.
- File names & file contents stay locale-independent (ISO dates, English
"Imported" folder prefix? **No** — the auto-folder title uses the localized
word + ISO date, e.g. `Đã nhập 2026-07-03`, key `import.folderName`).
- **Sort A→Z** collates with the UI locale (`Intl.Collator(getLocale())`), so a
Chinese user's folders sort by pinyin and a Romanian user's put `ș` after `s`.
## 4. Translation workflow & tone
- New strings land in `en.ts` first (PR fails type-check until vi/ja follow).
- New strings land in English first — in `en.ts`, `en-notices.ts` or
`en-import.ts`, whichever holds the branch (PR fails type-check until every
locale follows).
- **Terminology follows the browser.** Where Chrome (or, for Firefox's root
names, Firefox) already has a word in that language — bookmark, bookmarks
bar, folder, import — use the browser's own word, so the extension and the
browser around it never disagree.
- VI: neutral–friendly register, "bạn"; keep established loanwords
(bookmark, import/export may stay English in UI where natural — decide per
string, be consistent; folder = "thư mục").
- JA: です/ます form; katakana loanwords (ブックマーク, インポート,
エクスポート, フォルダ).
- No machine-translated commits without human review (owner reviews VI;
JA reviewed best-effort — mark `// TODO(review-ja)` where unsure).
- ZH-CN (Simplified only):
- Chrome's zh-CN terms: 书签 · 书签栏 · 其他书签 · 移动设备书签 · 文件夹 ·
导入 · 导出 · 编辑 · 设置 · 关于 · 重复 · 合并 · 替换 · 备份 · 主题.
- Polite but sparing: 您 where a pronoun is needed. Most strings need none.
- Full-width punctuation (,。:;?!“”()). The ellipsis is `…`, as in the
English source.
- One half-width space between Han characters and Latin text, numbers or a
`{token}`: "导出 {n} 个书签", "HTML 文件". No space next to full-width
punctuation.
- Measure words with counts: 个书签, 个文件夹, 项 for mixed items.
- RO:
- Chrome's ro terms: marcaj / marcaje · Bara de marcaje · Alte marcaje ·
Marcaje mobile · dosar / dosare · a importa / a exporta · setări · despre ·
copie de rezervă · temă.
- Polite plural address, as Chrome and Windows use: "Selectați", "Importați",
"dumneavoastră" where a pronoun is needed.
- **Comma-below `ș ț Ș Ț` (U+0219/021B/0218/021A), never cedilla `ş ţ`**. They
are different letters to a search box and a sort. `dictionaries.test.ts`
fails on a cedilla anywhere in the Romanian files.
- Quotation marks „…”.
- Counts take a third plural form (§5): "1 marcaj", "5 marcaje", "20 de
marcaje".
- **Review policy.** Commit no machine translation unless someone has reviewed
it. The owner reviews VI. JA, ZH-CN and RO are **best-effort** until a native
pass, and each file says so in its header: `TODO(review-ja)`,
`TODO(review-zh)`, `TODO(review-ro)`, with the same marker on any single
string that is especially uncertain. Native passes are open ⚠️ items
(`00 §10`), and translation reports arrive through
`.github/ISSUE_TEMPLATE/translation.yml`.
### Browser-neutral wording (since v1.3.0)
Since the same strings run in Chrome, Edge and Firefox, a sentence may name a
browser only when it is about that browser's own thing — "Chrome's Bookmarks
file", "Firefox JSON backups", "Firefox smart bookmarks". A sentence about what
"the browser" does or allows says "the browser". v1.3.0 reworded the three
that were not true everywhere, in all five languages:
| Key | Was | Is |
|---|---|---|
| `import.dateNotice` | "Chrome does not let an extension set…" | "The browser does not let an extension set…" |
| `about.store` | "Chrome Web Store listing" | "Store listing" (the URL follows the install, `06 §3.5`) |
| `warnings.PLACE_QUERIES_SKIPPED` | "…skipped — here they would be dead links." | "…skipped." (on Firefox they are not dead links; BookmarkMagic still does not write them) |
and added, with Romanian's `few` form where a count is involved (§5):
`warnings.URL_TOO_LONG`, `warnings.SEPARATORS_SKIPPED`,
`import.replaceSeparators` and `import.target.menu`. The JA, ZH-CN and RO versions are best-effort and
carry the usual `TODO(review-…)` marker.
## 5. Locale-sensitive edge cases
- Pluralization: plural keys are objects `{ one, other }` in **every** locale —
a tiny helper selects by locale. VI/JA have one grammatical form, so they set
`one` and `other` to the same string. They must still carry both keys, or the
`satisfies Dict` shape check that §2 relies on for completeness fails.
- **Pluralization.** A plural key is an object of CLDR plural forms. Every
locale carries `{ one, other }`. **Romanian also carries `few`.** The rule is
mechanical: a locale carries `few` exactly when
`Intl.PluralRules(tag).resolvedOptions().pluralCategories` includes it.
- VI, JA and ZH have one grammatical form, so they set `one` and `other` to
the same string. They must still carry both keys, or the `satisfies Dict`
shape check that §2 relies on for completeness fails.
- EN has `one` (1) and `other`.
- RO has `one` (1), `few` (0, 2–19, and any number ending in 01–19, such as
101 or 119) and `other` (20–100, 120…). `other` is the form with "de":
"{n} de marcaje".
- A count-less noun label — the popup's eyebrows above a big number — is not
a sentence. There the bare plural noun serves both `few` and `other`
("marcaje").
Implemented as `selectPluralForm(count, tag)` in `i18n/format.ts`. It is
backed by `Intl.PluralRules` and narrowed to `one`/`few`/`other`; `zero`,
`two` and `many` fold into `other`, and no shipped locale produces them.
`tPlural(path, count, params?)` in `index.svelte.ts` supplies `{n}` already
grouped for the locale, so callers pass a raw count. It falls back from the
selected form to `other`, then to English.
`tests/unit/i18n/dictionaries.test.ts` enforces the shape:
- every plural key carries exactly the forms its locale's rules need, and
nothing else;
- `few` is compared against English `other` for interpolation tokens;
- **every shipped locale's `pluralCategories` ⊆ {one, few, other}**. A future
locale that needs `two` or `many` (Arabic, Polish, Russian…) fails there
first, before anyone ships a grammar the helper cannot select.
The plural keys are **every** `warnings.*` code. That includes the two that
interpolate no count: `ParseWarning` always carries one, and a uniform shape
lets `WarningList` call `tPlural` unconditionally instead of keeping a list
of which codes count things. Beyond those come `import.warnings.title` and,
since v1.1.0, eighteen more:
- `popup.bookmarks`/`folders`;
- `export.start`;
- `import.start`, `countBookmarks`/`countFolders`, `reused`,
`cancelledSummary`, `partialCreated`/`partialCleared`;
- `edit.deleteFolderBody`, `keepFirst`/`keepFirstBody`, `sortBody`,
`showMore`/`showEarlier` and `duplicateLinks`/`extraCopies`. The duplicate
summary was one string with two counts, so it read "1 duplicated links · 1
extra copies".
Anything else stays a plain string.
⚠️ **No non-plural key may be named `one`, `few` or `other`.** The test reads
any branch holding one of those keys as a plural and fails it unless its keys
are exactly the plural forms. That is why the Firefox root names are
`import.rootTitle.{toolbar, unfiled, mobile}`: a third key named `other` made
the branch a malformed "plural".
- **Language labels are endonyms, identical in every dictionary.** A Japanese
user hunting for Romanian looks for "Română", not "ルーマニア語".
`dictionaries.test.ts` asserts `settings.lang` is the same in all of them.
- **Every code needs a message, in every locale.** A code with no key renders
as its own dotted path (`warnings.INVALID_URL`) and no union type can see it,
so `dictionaries.test.ts` walks three runtime lists:
- `PARSE_WARNING_CODES` (eleven since v1.1.0, each a plural under
`warnings.*`);
- `BM_PARSE_ERROR_CODES`;
- since v1.1.0, `BM_BACKUP_ERROR_CODES` (`browser/errors.ts`, now including
`BACKUP_EXCEEDS_LIMITS`).
The last two are plain strings under `errors.*`. A new code goes into its
list, or the test cannot see it. `BmEnvError`'s codes are covered by
`BM_ENV_ERROR_CODES`.
- Legal Gate: the four legal documents are **English-only** (canonical), with
a localized one-line note: "The legally binding documents are in English."
- Store listing: EN required; VI + JA listings via CWS dashboard localized
fields (copy lives in `13_RELEASE_PUBLISHING.md`).
- Store listing: EN required; every other locale's listing goes into the CWS
dashboard's localized fields (copy lives in `store/listing.*.md`, `13 §3`).
## 6. Adding a locale
Written while adding `zh-CN` and `ro`, so the next language is a checklist and
not an investigation. Each step names what fails when it is skipped.
1. **Plural forms first.** Check
`new Intl.PluralRules(tag).resolvedOptions().pluralCategories`. If it holds
anything besides `one`, `few` and `other`, stop: `format.ts`, `Localized`
and the dictionary tests need a new form before any translation can be
correct. The guard test fails here anyway.
2. `LOCALES` in `resolve-locale.ts`, plus a `resolveLocale` row and its tests.
`tsc` then demands the `dicts` entry (`index.svelte.ts`) and the `TAGS`
entry (`format.ts`).
3. Three dictionary files modelled on `ja.ts` / `ja-notices.ts` /
`ja-import.ts`, with a tone header and the `TODO(review-xx)` marker.
4. The endonym in `settings.lang` of **every** dictionary (the endonym test
fails otherwise).
5. `src/public/_locales/<chrome dir>/messages.json`. Also add it to
`CHROME_LOCALE_DIRS` (`tests/helpers/locales.ts`), to `REQUIRED_FILES`
(`scripts/check-manifest.mjs`) and to that script's test fixture.
6. `store/listing.<chrome dir>.md` plus its row in `store/README.md`.
7. The language dropdown in `.github/ISSUE_TEMPLATE/translation.yml`, and the
`LANGS` list in `scripts/screenshots.mjs`. Then run the visual sweep
(`11 §5`) in both themes for overflow and glyphs.
`tests/unit/i18n/touch-points.test.ts` fails on any of steps 5–7 left out,
and on a `LANGUAGES` line in a listing or the README that does not name
every language.
8. This chapter's tone section, `06 §3.4`, `11 §5`, `README.md`, `CHANGELOG.md`.
A new UI language is a **minor** release (`12 §4`).
+190 -37
View File
@@ -1,6 +1,9 @@
# 08 — Manifest V3 & Chrome Web Store Compliance
# 08 — Manifest V3 & Store Compliance
Goal: pass review fast and stay listed. Every item here is a hard requirement.
Goal: pass review fast and stay listed — on the Chrome Web Store, Firefox
Add-ons (AMO) and Microsoft Edge Add-ons. Every item here is a hard
requirement. §1–§8 were written for Chrome and still hold for every store;
§9 (Firefox) and §10 (Edge) add what differs.
## 1. Manifest (generated by WXT from `wxt.config.ts`)
@@ -11,7 +14,7 @@ export default defineConfig({
name: '__MSG_appName__',
description: '__MSG_appDesc__',
default_locale: 'en',
minimum_chrome_version: '120',
minimum_chrome_version: String(CHROME_FLOOR), // 136 — the ES2025 floor, 01 §1
permissions: ['bookmarks', 'storage'], // ← the complete list, forever (v1)
action: { default_popup: 'popup.html' }, // WXT wires this automatically
options_ui: { page: 'manager.html#settings', open_in_tab: true },
@@ -20,6 +23,18 @@ export default defineConfig({
});
```
Since v1.3.0 the manifest is a function of the target browser (`wxt.config.ts`,
`manifestVersion: 3` for every target — WXT would otherwise build Firefox as
MV2). Two packages are built from one source:
| Package | For | Differs from the above |
|---|---|---|
| `bookmarkmagic-X.Y.Z-chrome.zip` (`.output/chrome-mv3`) | Chrome Web Store **and Microsoft Edge Add-ons** | nothing — this is the manifest above (§10) |
| `bookmarkmagic-X.Y.Z-firefox.zip` (`.output/firefox-mv3`) + `…-sources.zip` | Firefox Add-ons | no `minimum_chrome_version`; adds `browser_specific_settings.gecko` (§9) |
Permissions, CSP, pages and icons are **identical** in both; `check:manifest`
holds each package to its own exact key set (§3, layer 2).
## 2. Permissions — justification table (paste into CWS review notes)
| Permission | Justification (single purpose) |
@@ -31,35 +46,93 @@ export default defineConfig({
`host_permissions`, `activeTab`, `scripting`, `alarms`. The design
deliberately avoids each (see `01_TECH_STACK.md §3`, `02_ARCHITECTURE.md §6`).
**What v1.1.0 adds needs no permission, and none of it is a network path.**
Each uses only web-platform APIs that any extension page has, scoped to this
extension's own origin inside the browser, and all long available below the
Chrome 136 floor (§7):
| Feature | API | Why no permission |
|---|---|---|
| The popup routes an open Manager (`browser/open-manager.ts`, `03 §5`) | `BroadcastChannel` | Messages go only to other documents of the same origin — the extension's own pages |
| One bookmark writer across Manager tabs (`browser/write-lock.ts`, `03 §5`) | Web Locks (`navigator.locks`) | A lock name shared by the extension's own pages; nothing leaves the browser |
| Copy diagnostics (`browser/diagnostics.ts`, `09 §7`) | Module memory + `navigator.clipboard.writeText` | Kept in the page's memory, never in `storage`; copied only on the user's click, like Copy link |
Finding the open Manager still uses `runtime.getContexts()`, `tabs.update` and
`windows.update`, and a Manager learns its own tab id from `tabs.getCurrent()` —
none of which needs `tabs`, because nothing reads a tab's URL or title
(`02 §6`). Nothing here touches what §5 certifies: the extension
transmits none of it, and the diagnostics log leaves the device only if the
user pastes it somewhere.
## 3. Code integrity rules
- **No remotely hosted code.** All JS/CSS ships in the package. No CDN
`<script>`, no `import()` of URLs, no `eval`, no `new Function`,
no string `setTimeout`. MV3's default extension CSP —
`script-src 'self' 'wasm-unsafe-eval'; object-src 'self';` — enforces this,
and Chrome rejects any manifest that loosens it. Never add a custom
`content_security_policy`.
- **No runtime network requests at all** (stronger than required): no
`fetch`, no remote favicons, no update pings. ⚠️ The default CSP does **not**
help here — it has no `connect-src`/`img-src` at all and restricts code
execution only, not network egress. The *only* thing enforcing the
zero-network promise is the grep gate below.
`<script>`, no `import()` of URLs, no `eval`, no `new Function`, no string
`setTimeout`. The extension-page CSP (below) enforces this, and Chrome
rejects any manifest that loosens the MV3 minimum.
- **No runtime network requests at all** (stronger than required): no network
calls, no remote favicons, no update pings. Three layers enforce it since
v1.1.0 — the browser, a build gate and a source gate:
#### The canonical grep gate
#### Layer 1 — the extension-page CSP (browser-enforced)
One pattern, defined **here and nowhere else**. `09 §1`, `09 §3`, `12 §2.1`
and §8 below all reference this block rather than restating it — four
divergent copies is exactly how a gate ends up weaker than the promise it
guards.
MV3's default extension CSP (`script-src 'self' 'wasm-unsafe-eval';
object-src 'self';`) restricts code execution only; it has no `connect-src` or
`img-src` at all. Until v1.0.1 that left a grep gate as the *only* thing between
the product and its zero-network claim. The production manifest now declares:
```
fetch\(|XMLHttpRequest|WebSocket|EventSource|sendBeacon|\beval\(|new Function|\{@html\}|(inner|outer)HTML\s*=|insertAdjacentHTML|import\s*\(
default-src 'none'; script-src 'self'; object-src 'none'; connect-src 'none';
img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self';
media-src 'none'; frame-src 'none'; worker-src 'self'; form-action 'none'; base-uri 'none'
```
must return nothing across `src/` (which contains `entrypoints/` — `02 §2`
sets `srcDir: 'src'`), excluding `*.test.ts`. Implemented as
`scripts/guard.mjs` and run by `npm run guard`, so the same gate runs locally
(in `npm run verify`) and in CI — it cannot drift between them.
`connect-src 'none'` makes Chrome refuse every fetch, XHR, WebSocket,
EventSource and beacon from an extension page; the rest closes remote images,
stylesheets, fonts, media, frames and form posts, and `default-src 'none'`
closes everything left unlisted (web app manifests, prefetches). Every directive
the pages use is listed explicitly, so `default-src` changes nothing for them.
`style-src` keeps `'unsafe-inline'` because Svelte sets `style` attributes.
**WebRTC is not governed by any CSP directive Chrome enforces**, so it is held
by the other two layers: both scan for `RTCPeerConnection`, prefixed aliases
(`webkitRTCPeerConnection`, which Chrome still ships) included. User-initiated
navigation — an About link, or "Open" on a bookmark via `tabs.create` — is not
governed by a page CSP and is not a request the extension makes (`09 §1`).
- **The rule is: only ever tighten.** Adding `'unsafe-*'`, a remote source, or
removing a directive is a security regression, and `check:manifest` fails on
any string other than the exact one above.
- **Production builds only.** `wxt.config.ts` emits it when the command is
`build` (so `npm run build` and `npm run zip`), because the dev server reloads
the extension over a localhost websocket that `connect-src 'none'` blocks.
- Vite's modulepreload polyfill is disabled (`modulePreload.polyfill: false`):
it was the one network call in the shipped bundle, dead code for every Chrome
at the floor.
#### Layer 2 — the built-artifact gate
`npm run check:manifest` (`scripts/check-manifest.mjs`) scans every `.js` file
in `.output/chrome-mv3` — and, with `--browser firefox`, in `.output/firefox-mv3`
(since v1.3.0, each against its own key set, §1) — for the network identifiers the source gate bans, as
bare words — including code that arrived through a dependency, which no source
gate can see — and pins the manifest: MV3, the permission list, the exact key
set, the Chrome floor, the exact CSP, that every file the manifest and the
built pages reference exists, and that no page loads anything from outside the
package.
#### Layer 3 — the source gate
`npm run guard` (`scripts/guard.mjs`). **The rule set lives in that file, not
here** — this section used to restate it, and the copy drifted (its `\{@html\}`
matched only the literal `{@html}`). The script header explains each rule and
`tests/unit/scripts/guard.test.ts` holds a passing and a failing case for every
one, including the bypasses an audit found against the old line-by-line regexes
(aliases, computed global access, multi-line calls, `+=`, `{ @html }`, remote
`url()` in CSS, resource hints). It scans `src/**` — `.ts`, `.svelte`, `.html`,
`.css` and friends — with no exemptions, matches across line breaks, and fails
if it scanned nothing. Because identifiers are banned outright, the bare API
names cannot appear in `src/` comments either; write "network call".
- **Minification: yes. Obfuscation: NO.** CWS has prohibited obfuscated code
since 2018; WXT/Vite default minify (whitespace/identifier shortening) is
allowed and sufficient. Never add an obfuscator plugin. Open-source repo +
@@ -88,7 +161,7 @@ data-usage checkboxes. That is *not* the same as being exempt from disclosure:
CWS requires extensions to describe how they handle user data **even when the
handling is entirely local**, which is why the privacy-policy URL above is
mandatory and why `legal/PRIVACY.md` spells out the local bookmark reads/writes
and the `chrome.storage.local` settings explicitly (`14 §3.1`).
and the `chrome.storage.local` settings explicitly (`14 §3`).
The single-purpose text (§4) and the per-permission justifications (§2) are
also submitted on this tab — keep all three in sync, and re-certify whenever
@@ -112,13 +185,21 @@ any of them changes (`09 §4`).
- No background service worker is registered at all (§02). If one ever
becomes necessary, it must be an ES module (`type: 'module'`) and
event-driven only.
- Extension pages (popup/manager) may use `DOMParser`, `Blob`, `<a download>`
freely — these need no permissions.
- `browser.runtime.getContexts()` (Chrome 116+) is our highest **hard**-floor
API → `minimum_chrome_version: 120` gives margin. `scheduler.yield()`
(Chrome 129+) is used only behind the nullish fallback in `05 §6`, so it does
not raise the floor — but that fallback only works if it is written with
explicit parentheses; see the warning there.
- Extension pages (popup/manager) may use `DOMParser`, `Blob`, `<a download>`,
`BroadcastChannel` and Web Locks freely — these need no permissions (§2).
- **The floor is Chrome 136** (`minimum_chrome_version: "136"`, since v1.1.0;
120 before). It is set by the language, not by an extension API: 136 is the
first Chrome with every ES2025 built-in, and tsconfig's `lib` is ES2025
(`01 §1`). The highest extension-API floors are far below it —
`browser.runtime.getContexts()` needs 116 and `scheduler.yield()` 129 — so
`scheduler.yield()` is in fact always present. The write queue still keeps
its nullish fallback (`05 §6`) because the test environment has no
`scheduler`; it only works if written with explicit parentheses, see the
warning there.
- Raising the floor is a **user-visible** event even though it is not a
permission change: a user below it keeps the installed version and simply
stops receiving updates. Say so in the CHANGELOG, and never raise it in a
patch release.
## 8. Review-readiness checklist (before every submission)
@@ -126,14 +207,86 @@ any of them changes (`09 §4`).
"Load unpacked" on a fresh profile.
- [ ] Manifest diff reviewed — permission list unchanged (`bookmarks`,
`storage` only).
- [ ] `npm run guard` passes (the canonical grep gate, §3). Note `{@html}` is
**not** catchable by Biome — no such rule exists for Svelte — so this
gate plus review is the whole enforcement.
- [ ] `npm run guard` and `npm run check:manifest` pass (§3: the source gate,
and the built-artifact gate that pins the CSP and scans the bundle). Note
`{@html}` is **not** catchable by Biome — no such rule exists for Svelte —
so the source gate plus review is its whole enforcement.
- [ ] Right-click → Options lands on `#settings` both on a fresh profile and
with a Manager tab already open on another route (§1 uses an undocumented
URL fragment; `02 §5`).
- [ ] All three `_locales` load (chrome://extensions shows localized name
when browser language switched).
- [ ] All five `_locales` load (chrome://extensions shows the localized
description when the browser language is switched — and a `zh_TW`
browser shows English, `07 §1`).
- [ ] Version bumped (semver) in `package.json` (WXT propagates to manifest).
- [ ] Privacy tab answers unchanged, or updated + re-certified.
- [ ] Store listing screenshots regenerated if the UI changed.
- [ ] Store listing screenshots regenerated if the UI changed
(`scripts/screenshots.mjs --shoot` — `13 §2`).
- [ ] Firefox: `check:manifest --browser firefox` passes; the gecko id is
still `bookmarkmagic@poli0981.dev`; the sources zip and `BUILD.md`
rebuild the package (§9).
- [ ] Edge: the package uploaded is the Chrome Release asset (§10).
## 9. Firefox Add-ons (AMO) — since v1.3.0
```ts
browser_specific_settings: {
gecko: {
id: 'bookmarkmagic@poli0981.dev', // permanent after the first AMO upload
strict_min_version: '140.0',
data_collection_permissions: { required: ['none'] },
},
},
```
- **The id is permanent.** AMO requires one for MV3 and never lets it change;
every installed copy and every update is tied to it. It is an id, not a
mailbox, and no page of the extension shows it (`15`, 2026-11-18).
- **`data_collection_permissions: { required: ['none'] }`** is Firefox's own
consent system, mandatory for new extensions since 2025-11-03. "None" is the
accurate answer for the same reason §5's privacy answers are "No": nothing is
collected or transmitted. Changing it is the Firefox equivalent of changing
the CWS privacy tab — a minor-version event (`09 §4`).
- **Floor: Firefox 140** — the first release that understands
`data_collection_permissions` (older ones reject the key), and above every
ES2025 built-in the code relies on (`RegExp.escape` and `Promise.try` are
134). Vite's `build.target` for this package is `firefox140`, the
counterpart of `chrome136`. Like the Chrome floor, never raise it in a patch.
- **Desktop only.** Firefox for Android has no `bookmarks` API, so the
manifest declares no `gecko_android` and the listing and every API upload
declare Firefox desktop compatibility only.
- **The extension-page CSP is the same string**, in MV3's object form, and
Firefox enforces it the same way; `check:manifest` pins it in both packages.
- **No background script** on Firefox either, so Firefox's MV3 event-page
model never comes into it.
- **Options can open a second Manager tab.** Chrome reuses an open Manager
for `options_ui` whatever its route, ignoring the `#settings` fragment
(`02 §5`); Firefox matches the whole address, fragment included (its
about:addons and `open_in_tab` code never pass `ignoreFragment`), so with a
Manager open on `#edit` it opens another one on `#settings`. Cosmetic: both
tabs work, and the write lock keeps them from writing at once (`03 §5`).
- **Source code is part of every submission.** The bundle is minified, so AMO
requires the sources and instructions that rebuild the same files. `wxt zip
-b firefox` writes `…-sources.zip` beside the package (dotfiles excluded —
`.nvmrc` among them, so the instructions state Node 26 explicitly), and
`/BUILD.md` is those instructions. AMO's reviewers build on their own
machine and diff the result against the uploaded package.
- **Obfuscation is prohibited** on AMO too; minification is allowed.
- What the code does differently on Firefox — the roots, the separators, the
move index — is `02 §4`, `03 §1` and `05 §10`; none of it is a manifest
matter.
## 10. Microsoft Edge Add-ons — since v1.3.0
- **The Chrome package, unchanged.** Edge accepts Chrome's MV3 manifest keys,
`minimum_chrome_version` included (Edge versions follow Chromium's, so
136 means Edge 136). The zip uploaded to Edge is the same Release asset as
the Chrome one, with the same checksum.
- Partner Center rejects a listing whose name or description sells it as a
Chrome extension; the Edge listing copy (`13 §3`) is reworded to name
Chromium-based browsers where it has to mention Chrome's file format.
- Edge's bookmarks API is Chromium's: the same roots ("Favorites bar", "Other
favorites"), `folderType` included. Whether Edge marks the roots of a
signed-in, syncing profile with `syncing: true` — which would leave no
writable root (`NO_WRITABLE_ROOTS`) — is **unverified**; `11 §5` checks it
on a real Edge with sync on before the first submission.
- Privacy answers in Partner Center are §5's.
+215 -19
View File
@@ -3,10 +3,16 @@
## 1. Privacy guarantees (product-level, non-negotiable)
1. **Zero data collection.** No analytics, no telemetry, no crash reporting,
no update pings. There is no server.
2. **Zero network activity at runtime.** Enforced by the canonical grep gate
defined in `08_MV3 §3` — that block is the single source of truth for the
pattern; do not restate it here.
no update pings. There is no server. The local diagnostics log (§7) is not
an exception: it lives in the page's memory and leaves it only when the user
copies it and pastes it somewhere themselves.
2. **Zero network activity at runtime.** Enforced in three layers, all in
`08 §3`: the production CSP (`connect-src 'none'` — the browser itself
refuses), `check:manifest`'s scan of the shipped bundle, and the source gate
`scripts/guard.mjs`. Do not restate their rules here. Links the user
chooses to open (About, the legal documents, "Open" on a bookmark) load in a
browser tab; that is navigation the user asked for, not a request the
extension makes.
3. **Everything on-device.** Bookmarks are read/written via `chrome.bookmarks`
locally; files are parsed in-page and downloaded via Blob URLs. `chrome.
storage.local` holds only settings + legal flag (no `storage.sync` — even
@@ -18,21 +24,76 @@
| # | Threat | Vector | Mitigation |
|---|---|---|---|
| T1 | **Malicious import file — markup injection** | Crafted `<script>`/`onerror` payloads in a .html bookmark file | `DOMParser('text/html')` produces an **inert** document (scripts never execute). We read `textContent`/`getAttribute` only. Rendering uses Svelte text interpolation — **`{@html}` is banned repo-wide**. |
| T2 | Malicious file — resource exhaustion (huge/deep/zip-bomb-style) | 500 MB file, 1M nodes, 10k-deep nesting | Pre-parse size cap 25 MB; node cap 100 000; depth cap 200 — typed errors, parse aborts early. Lazy tree rendering (§05 §9) bounds DOM size. |
| T3 | Dangerous URLs in imported bookmarks (`javascript:`, `data:`) | Clicking them in #edit | Never rendered as `<a href>`; "Open" uses `tabs.create`, which refuses `javascript:`. UI marks non-http(s)/ftp/file/about/chrome schemes with a ⚠ badge; they are display-only. Imported URLs are stored verbatim (user's data, not ours to censor) — the browser's own bookmark UI applies its own rules. |
| T4 | Data loss from destructive import | User picks "Replace all" casually | Non-skippable auto safety-backup (BM JSON download) *before* deletion; danger-styled confirm with exact counts; default mode is non-destructive new-folder. |
| T5 | Supply-chain compromise | Malicious transitive dep | **Zero runtime deps**; dev deps pinned via lockfile; Dependabot + `npm audit` in CI; Biome installed exact-pinned. |
| T2 | Malicious file — resource exhaustion (huge/deep/zip-bomb-style) | 500 MB file, 1M nodes, 10k-deep nesting | Pre-parse size cap 25 MB; node cap 100 000 — for HTML counted on the raw text before `DOMParser` builds anything (since v1.1.0; before, 1.7 M entries were materialised first); depth cap 200 — typed errors, parse aborts early. Replace's safety backup is held to the same caps before a byte is written (`BACKUP_EXCEEDS_LIMITS`, `core/caps.ts`), so a profile too large to restore is never deleted on the strength of a backup the parser would refuse. Bounded rendering (`05 §9`) caps what mounts at once. |
| T3 | Dangerous URLs in imported bookmarks (`javascript:`, `data:`) | Clicking them in #edit | Never rendered as `<a href>`; "Open" passes only `http:`/`https:` to `tabs.create` (`browser/open-url.ts` — our allowlist, not the browser's refusal, is the control). UI marks every other scheme with a ⚠ badge; those are display-only. Imported URLs are stored verbatim (user's data, not ours to censor) — the browser's own bookmark UI applies its own rules. |
| T4 | Data loss from destructive import | User picks "Replace all" casually; two Manager tabs write at once | Non-skippable auto safety-backup (BM JSON download) *before* deletion, refused outright when the import could not read it back; danger-styled confirm with exact counts; default mode is non-destructive new-folder; one bookmark writer across tabs (`03 §5`). |
| T5 | Supply-chain compromise | Malicious transitive dep | **Zero runtime deps**; dev deps pinned via lockfile; Dependabot with a 7-day cooldown + `min-release-age=7`; `npm audit --omit=dev` in CI; Biome installed exact-pinned. See §3.1. |
| T6 | Store-listing impersonation / trademark issues | — | Unique name + linked GitHub; report via CWS if cloned. |
| T7 | XSS via filenames/titles echoed into UI (result cards, toasts) | Weird characters in file name | Same as T1 — text interpolation only; filenames additionally sanitized for the *download* name (`[\\/:*?"<>|]` → `_`). |
| T8 | Clipboard abuse | "Copy URL" action | Uses `navigator.clipboard.writeText` on explicit user click only; never reads the clipboard. |
### Pass performed 2026-07-26 (Phase 5)
| # | Now enforced by |
|---|---|
| T1 | `tests/unit/core/fixtures.test.ts` parses `malformed/script-injection.html` and asserts the payloads survive as inert text. `DOMParser('text/html')` never executes scripts, and `{@html}` is barred by `npm run guard`. |
| T2 | `tests/unit/core/limits.test.ts` plus the caps in `core/limits.ts`. Measured: a 100k-node file parses without exhausting anything (`11 §6`). |
| T3 | `malformed/js-url.html` at parse level, `tests/unit/browser/open-url.test.ts` at the point of use — `javascript:`, `data:`, `file:`, `chrome:`, `vbscript:` and case-shouted variants are refused before `tabs.create` — and the ⚠ badge this row has always specified, which `isBlockedUrl` now drives in `TreeRow`. A refused open also raises a toast; it used to do nothing at all, which read as a broken button rather than a deliberate refusal. |
| T4 | `tests/unit/import/safety-backup.test.ts`. |
| T5 | `npm audit --omit=dev` reports **0** — every open Dependabot alert is `development` scope. |
| T6 | Human; nothing in code. |
| T7 | `sanitizeFilename` (`tests/unit/browser/download.test.ts`); everything else reaches the DOM through Svelte text interpolation. |
| T8 | `browser/clipboard.ts` — write-only, click-only, never reads. Implemented in Phase 5; it had been specified in `06 §3.3` and here since the start but never built. |
Three gaps this pass closed, all of which had gone unnoticed because nothing
mechanical was watching:
- **The permission list had no gate at all.** Two now exist, and both are
needed. `tests/unit/manifest.test.ts` asserts `['bookmarks', 'storage']`
against `wxt.config.ts` — what we *ask* for. `scripts/check-manifest.mjs`
asserts the **built** artifact, which is not the same thing: a dev build of
this identical config emits
`"permissions": ["bookmarks","storage","tabs","scripting"]` and
`"host_permissions": ["http://localhost/*"]`, because WXT injects them.
Production is clean today, but that is WXT's behaviour, not our enforcement.
Both were verified to fail — one by adding `'tabs'` to the config, the other
by editing the built manifest.
- **"Copy URL" did not exist**, so T8 described the mitigation for a feature
that was never shipped.
- **T3's ⚠ badge did not exist either.** The blocking half was real and tested;
the "mark dangerous schemes in the UI" half was not, so a `javascript:`
bookmark titled "Your bank" rendered exactly like a safe one and its Open
button silently did nothing.
### v1.1.0 — what changed against the model
- **T4's confirmation did not exist until v1.1.0.** The row has always promised
a "danger-styled confirm with exact counts"; 1.0.x had only a danger-styled
button. Replace now opens a `ConfirmDialog` — focus on Cancel — stating how
many bookmarks and folders will be deleted (everything inside the writable
roots, from the preview read) and how many will be written (a preview plan
with the chosen mode and dedupe), `06 §3.1`. Checked by hand (`11 §5`); the
counts come from tested pieces (`prepareImport`, `buildImportPlan`).
- **T2 met T4 in the backup.** A profile past the node, depth or size cap got a
backup that the parser then refused — after the tree had been deleted. The
backup is now compact BM JSON, checked against the import's own caps before
anything is written, downloaded or deleted (`03 §1` step 6b;
`safety-backup.test.ts`, `caps.test.ts`).
- **A second tab was an unmodelled writer.** Two Manager tabs replacing at once
would each back up, then delete what the other was writing. The import, Sort
A→Z and keep-first now hold a Web Lock, and a second writer is refused before
it touches anything (`03 §5`, `write-lock.test.ts`).
- **Diagnostics are new data, kept local** — what may and may not be recorded
is §7.
## 3. Secure coding rules (enforced)
- `{@html}` — **forbidden**. Enforced by the canonical grep gate (`08 §3`) and
review. Biome has no rule for this: `noDangerouslySetInnerHtml` is a React
- `{@html}` — **forbidden**. Enforced by the source gate (`scripts/guard.mjs`,
`08 §3`) and review. Biome has no rule for this: `noDangerouslySetInnerHtml` is a React
rule and does not see Svelte templates.
- `innerHTML`, `outerHTML`, `insertAdjacentHTML` assignment — forbidden (same
gate).
- `innerHTML`, `outerHTML`, `insertAdjacentHTML`, `setHTMLUnsafe`,
`createContextualFragment`, `srcdoc`, `document.write` — forbidden outright,
reads included (same gate).
- All user/file-derived strings cross into the DOM only via Svelte text
bindings or `textContent`.
- `URL` constructor for any URL handling; no string-splitting of URLs.
@@ -44,6 +105,67 @@
≤120-char excerpt of the offending line (avoids log-injection weirdness in
screenshots/issues).
### 3.1 Dev-dependency advisories
**There is no `overrides` block any more** (removed 2026-10-28). The six pins
added on 2026-07-26 (`shell-quote`, `adm-zip`, `tmp`, `uuid`, `esbuild`,
`brace-expansion`) had all become dead: WXT 0.21 dropped `web-ext-run`, which
four of them sat under, and Vite 8 bundles with rolldown rather than esbuild.
None of the six packages was in the lockfile — and a stale override is worse
than none, because the day the package returns it silently pins it.
State on 2026-11-18 (Node 26, Vitest 5.1, Vite 8.3, WXT 0.21.5):
| Check | Result |
|---|---|
| `npm audit --omit=dev` | **0** — nothing third-party is a runtime dependency (CI runs this, `12 §2.1`) |
| `npm audit` (dev included) | **14 high, one root cause: `picomatch`** — GHSA-fc5q-39xc-vjpf (CVE-2026-112366), a ReDoS through single-branch repeated extglobs. **Every version up to 4.0.7 is affected and no fixed version exists**, so there is nothing to upgrade or override to. It is the glob engine of the whole toolchain (WXT, Vite, Vitest, knip, svelte-check, unplugin, tinyglobby, fdir — the other 13 entries are those parents), and it matches patterns this repository writes into its own config files, at build and test time only: never user data, never in the shipped extension. Recorded rather than worked around. Dependabot opens a security PR the day a fixed release exists, and `MAINTENANCE.md` makes that PR urgent. |
| Retired | The `deepmerge` advisory recorded here until v1.2.1 (GHSA-gcqx-w48m-w2h4, low, via `@sveltejs/vite-plugin-svelte`) was **withdrawn** by GitHub on 2026-11-16. `deepmerge` 4.3.1 is still in the tree; nothing else needs doing. |
The maintenance policy's rule for advisories (`MAINTENANCE.md`): a **high or
critical** one is fixed as soon as a fixed version exists — through the
Dependabot security PR, or a lockfile update when a parent's range already
allows the fix. When no fix exists, the advisory goes in the table above with
why it cannot reach a user, and the row stays until the fix lands.
How new advisories are kept out:
- `.npmrc` sets `min-release-age=7`, and Dependabot's `cooldown` is 7 days:
a release must have been public for a week before this repo installs it. The
2025 npm compromises were caught and pulled within hours to days, so that
window is the point (`01 §6`).
- `npm ci` installs exactly what the lockfile pins and is unaffected by the
age rule — verified, not assumed.
- Dependabot *security* PRs bypass `cooldown`; one for a version younger than
a week may fail to resolve until it ages. That is the intended trade-off.
### 3.2 Licence gate — `npm run check:licenses`
Added 2026-11-18. `scripts/check-licenses.mjs` reads every entry of
`package-lock.json` (lockfile v3 records each package's `license` field, and every
entry carries one) and fails the run on any licence outside two lists:
| Packages | Accepted | Why |
|---|---|---|
| What the build compiles into the extension — `CREDITED_PACKAGES` in `scripts/credited-packages.mjs`, the same list the build gate and the notices test read (`14 §5`) | `MIT`, `ISC`, `BSD-2-Clause`, `BSD-3-Clause`, `Apache-2.0`, `0BSD`, `MIT-0` | This code travels inside a GPL-3.0-or-later extension; only permissive licences that combine with it cleanly |
| Everything else — all of it build and test tooling, since there are no runtime dependencies | the above, plus `MPL-2.0`, `BlueOak-1.0.0`, `CC0-1.0`, `CC-BY-4.0`, `Python-2.0`, `Unlicense`, `Zlib` | Tools never ship. File-level copyleft (MPL-2.0 — `lightningcss`, under Vite) is fine for a tool; network copyleft, source-available terms and missing or custom licences are not |
SPDX expressions are evaluated (`OR` needs either side, `AND` both). An entry
with no `license`, `UNLICENSED` or `SEE LICENSE IN …` fails. A new licence
enters the tree through a reviewed change to the lists — or one `EXCEPTIONS`
entry with its reason and a `15` decision-log row — never unnoticed inside a
Dependabot bump. The gate trusts each package's own declaration, as any
lockfile-based check must, and needs neither `node_modules` nor the network.
It runs in `verify`, in CI's `quality` job and in the release build, over the
root lockfile and, since v1.3.0, `tools/publish/package-lock.json` — the
store-upload tool, which ships nothing, so it is held to the toolchain list
(`12 §3`).
Considered and not used: `actions/dependency-review-action`. It sees only
what a pull request changes, reads licences from ClearlyDefined rather than
the lockfile, checks only runtime-scoped packages unless told otherwise, and
cannot run locally — a second, weaker opinion beside this one.
## 4. Permissions posture
`bookmarks` + `storage`, nothing else (justifications in `08 §2`). Any PR
@@ -52,14 +174,88 @@ a **minor-version** event at minimum.
## 5. Release integrity
- Builds are reproducible from a clean checkout: `npm ci && npm run zip`.
- GitHub Releases attach the exact zip uploaded to CWS + `SHA256SUMS.txt`
so users can verify store build ↔ source correspondence.
- Builds are **content**-reproducible from a clean checkout: `npm ci && npm run
zip`. Verified 2026-07-26 by building the same commit in a fresh clone and in
the working tree — every entry in the two zips has an identical name and
CRC32. The archives' SHA-256 hashes still differ, because `wxt zip` records
file mtimes and nothing normalizes them (there is no `SOURCE_DATE_EPOCH`
support). Do not claim byte-identical rebuilds.
- GitHub Releases attach the exact zips uploaded to the stores + `SHA256SUMS.txt`
(since v1.3.0: the Chrome package, which is also what Edge Add-ons receives,
the Firefox package and its sources archive) so users can verify store build
↔ source correspondence. The stores re-sign or repackage what they receive
(Chrome and Edge into a signed CRX, AMO signs the XPI), so a file installed
from a store does not hash like the Release asset; the checksum vouches for
what was uploaded. That works on the
released artifact itself, which is the same file in both places — it is not a
claim that a third party can rebuild the same hash.
- Tags are signed (GPG) — consistent with the tracker-repo signing practice.
## 6. Vulnerability reporting
`SECURITY.md` in repo root (⚠️ create at scaffold): report privately via
GitHub Security Advisories; acknowledgment target 72h; fix-or-mitigate target
14 days for High/Critical. No bounty (hobby project) — credit given in
release notes.
`SECURITY.md` in the repo root is the policy in force. Summary:
- **Supported: the latest version published on the Chrome Web Store, only.** No
back-porting — Chrome auto-updates every installed copy once a release passes
review, so there is no population left behind to back-port for.
- Report privately via GitHub Security Advisories, or `security@poli0981.dev`
for reporters without a GitHub account (`contact@` is retired since v1.1.0;
each purpose has its own address). Never a public issue.
- Acknowledgement 72 h; fix **prepared** within 14 days for High/Critical. Time
to *users* is that plus store review, which is outside our control — the
policy says so rather than implying a delivery guarantee we cannot make.
- No bounty (hobby project); credit in the release notes.
**Sample files from reporters.** A bookmark file is a browsing history, so the
policy asks reporters to run `scripts/sanitize-bookmarks.mjs` first — it rewrites
every hostname, path, query value, title, note, keyword and tag while preserving
the structure, encoding, and timestamps a parser bug depends on, so the sanitized
file still reproduces. It reads Netscape HTML, BookmarkMagic JSON, Chrome's
profile `Bookmarks` file, Firefox `.json` backups and our CSV, and refuses
anything else. JSON is rewritten default-deny (every string value except a short
list of structural keys). Before writing, it checks its own output — no host but
its `*.example` aliases, and for HTML no text left that is not a placeholder —
and writes nothing if that check fails. Until 2026-10-28 it accepted any JSON
and rewrote only `url`/`title`, so Chrome's profile file (titles under `name`)
came out with every title intact. Anything received by email is kept only as long as needed to
reproduce and fix, then deleted; `legal/PRIVACY.md` states the same to users.
This is the receiving-side counterpart to §3's rule that error messages never
echo more than a 120-character excerpt of file content.
## 7. Local diagnostics — `browser/diagnostics.ts`
A bug report needs more than "it failed", and §1 rules out sending anything.
So since v1.1.0 each page keeps its last **200** events in a ring buffer in
module memory, and About → **Copy diagnostics** puts them on the clipboard as
JSON — on an explicit click, write-only, like Copy link (T8). The user decides
whether to paste it anywhere.
**Recorded:** import phases — `parsed` (with the detected format and node
count), `planned:<mode>`, `backup-proven`, `cleared`, `written`; every failure
the UI shows, by its i18n code and the error's class name, logged inside
`describeError` — the one place failures are described; bulk edits (`sort`,
`keep-first`) with their counts; storage read and decode failures, by a fixed
issue name; uncaught errors and unhandled rejections, by error **name**
(`installCrashHooks`, in the popup and the Manager).
**Never recorded:** titles, addresses, file names, folder paths; a failure's
`detail` text, which can quote a URL or a line of the file; error messages and
stacks; stored values; wall-clock time — entries carry milliseconds since the
page loaded.
- `DiagEvent` is a closed union with no field for a title, an address or a
path — adding one is a type change under review, not a call site — and every
string field is itself a **union of fixed values**: the import phases,
`FileFormat`, the `ErrorKey`s `describeError` can return, the two edit
actions, the three storage issues, and an allowlist of error names (anything
else is logged as `'other'`, since a name is just a string property). 1.1.0's
first cut typed them all `string`; the test file now carries
`@ts-expect-error` cases, so a title stops compiling, not just reviewing. The copied report adds only the extension version, the language and
theme *preferences*, and Chrome's major version from the user agent.
- Never written to `storage`, never sent (the CSP would refuse it anyway,
`08 §3`), gone when the tab closes. The log is per page: the popup installs
the crash hooks too, but has no Copy button, so nothing can read its log.
- `tests/unit/browser/diagnostics.test.ts`: the 200-entry cap and order, the
report's exact keys, a failure logged by code with its URL-bearing detail
absent, crash hooks by name with the message absent.
- `legal/PRIVACY.md` describes the same log to users; the two must agree.
+23 -6
View File
@@ -4,7 +4,7 @@
| Unit | Soft limit | Hard limit |
|---|---|---|
| File (.ts / .svelte) | **300 lines** | **500 lines** — split before merging |
| File (.ts / .svelte / .mjs) | **300 lines** | **500 lines** — split before merging |
| Function / method | 50 lines | 80 lines |
| Svelte component script block | 150 lines | move logic to a `.svelte.ts` store or `core/` |
| Nesting depth | 3 | 4 |
@@ -46,14 +46,18 @@ rather than assign `undefined`. Build nodes with conditional spreads
- Discriminated unions over boolean flags for state
(`{ kind: 'parsed', … } | { kind: 'error', … }`).
## 3. Biome — `biome.json` (2.5.x)
## 3. Biome — `biome.json` (2.6.x)
```jsonc
{
"$schema": "https://biomejs.dev/schemas/2.5.2/schema.json",
"$schema": "https://biomejs.dev/schemas/2.6.6/schema.json",
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
// Svelte and CSS are excluded on purpose — see the note below.
"files": { "includes": ["src/**", "tests/**", "*.ts", "!**/*.svelte", "!**/*.css"] },
// Svelte, CSS, Markdown and YAML are excluded on purpose — see the notes below.
"files": {
"ignoreUnknown": true,
"includes": ["**", "!**/*.svelte", "!**/*.css", "!**/*.md", "!**/*.yml", "!**/*.yaml",
"!.output", "!.wxt", "!coverage", "!tests/fixtures"]
},
"formatter": { "enabled": true, "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 },
"javascript": { "formatter": { "quoteStyle": "single", "semicolons": "always", "trailingCommas": "all" } },
"linter": {
@@ -74,9 +78,22 @@ rather than assign `undefined`. Build nodes with conditional spreads
(`switch-every-tab-hotkey`) excludes `.svelte` and `.css` instead, and we
follow it rather than putting the build on an experimental flag.
**`svelte-check` is the authority** for everything inside `.svelte`.
Since v1.2.1 it runs with **`--fail-on-warnings`**: the Svelte compiler's
accessibility warnings (`a11y_*` — a click handler with no key handler, a
control with no label) are warnings, and through 1.2.0 a warning never
failed anything. It is the only lint that reads the markup. A deliberate
exception takes a `<!-- svelte-ignore a11y_… -->` with its reason in the
same comment; there are two, on `Modal`'s backdrop click and on the tree's
`<ul>`. (`TreeRow`'s row `<div>` avoids the same warning differently — an
empty `onkeydown` and `role="presentation"` — because the keys are the
tree's, not the row's.)
- **Markdown and YAML are excluded since Biome 2.6**, which started formatting
both. The docs and workflow files are laid out by hand (long explanatory
comments, deliberate wrapping); letting a formatter own them would turn every
doc edit into a reflow diff.
- There is **no Biome rule that catches `{@html}`.** `noDangerouslySetInnerHtml`
is a React rule and does not apply to Svelte. The ban in `09 §3` is enforced
by the canonical grep gate (`08 §3`, run as `npm run guard`) and by review —
by the source gate (`scripts/guard.mjs`, `08 §3`, run as `npm run guard`) and by review —
not by the linter.
- `overrides` block: `noDefaultExport` must be relaxed for **`**/*.svelte`**,
not just `entrypoints/**` — every Svelte component is a default export,
+450 -36
View File
@@ -9,10 +9,13 @@
| Components/UI | Manual QA checklist (§5) | No component-test framework in v1 (cost/benefit) |
| End-to-end | Out of scope v1 (Roadmap: Playwright + `--load-extension`) | — |
`vitest.config.ts`: `plugins: [WxtVitest()]` (WXT aliases/auto-imports resolve
in tests), `environment: 'jsdom'`, `coverage.provider: 'v8'`,
`coverage.thresholds: { lines: 90, functions: 90, branches: 85 }` scoped to
`src/lib/core/**`.
`vitest.config.ts`: `plugins: [svelte(), WxtVitest()]` (the svelte plugin
compiles runes in `.svelte.ts` stores; WXT's resolves aliases and auto-imports),
`environment: 'jsdom'`, `coverage.provider: 'v8'`. Coverage **measures** every
`src/**/*.ts` module and writes `text` + `lcov` (SonarCloud reads the lcov,
`12 §2.5`), but only core is **gated**: a glob threshold
`'src/lib/core/**': { lines: 90, functions: 90, branches: 85 }`, so widening
what is measured cannot change what is enforced.
**Environment canary.** Add one test asserting that a Chrome fixture parses to
a `<DL>` nested *inside* its `<DT>` (`dl.querySelector('dt').querySelector(':scope > dl') !== null`).
@@ -28,23 +31,50 @@ Real-world exports (committed, small, anonymized):
chrome-131-export.html edge-export.html firefox-html-export.html
safari-export.html vivaldi-export.html
bm-v1-sample.json csv-comma.csv csv-semicolon.csv
chrome-156-export.html # built to bookmark_html_writer.cc byte for byte (CRLF) (v1.1.0)
chrome-156-Bookmarks # the SAME profile as Chrome's JSON file — no extension (v1.1.0)
firefox-bookmarks-2026-07-25.json # Firefox backup of firefox-html-export.html's profile,
# plus tags root, separator, iconUri, keyword, description, Mobile
malformed/no-doctype.html malformed/truncated.html
malformed/doctype-only.html # valid doctype, zero <DL> → NO_BOOKMARKS warning
malformed/script-injection.html # <script> + onerror payloads (T1)
malformed/js-url.html # javascript: bookmark (T3)
weird/deep-nesting.html # depth 150 (under the 200 cap — tolerance)
weird/over-depth.html # depth 201 → TOO_DEEP (the cap itself)
weird/folder-with-dd.html # <DT><H3>/<DD>/<DL> — subtree must survive (04 §1.2)
weird/explicit-close-dt.html # literal </DT> → sibling-DL branch (05 §1)
weird/hr-separator.html # Firefox <HR> between entries → skipped
weird/add-date-zero.html # ADD_DATE="0" → omitted, NO warning
weird/mixed-wrapper.html # some roots wrapped, some not → root-list selection rule (04 §1.2)
weird/safari-no-wrapper.html # no wrapper <DL> at all → same rule, other branch
weird/emoji-rtl-titles.html # 🌸, RTL, CJK titles; & < > " entities
weird/microsecond-dates.html # Firefox-style timestamps
generate-huge.ts # script: emits 100k+1 node file on demand (not committed output)
weird/loose-first.html # loose bookmark before the wrapper list, no </DT> (v1.1.0)
weird/unclosed-format-tag.html # unescaped <b> in a title re-opened around every entry (v1.1.0)
weird/invalid-urls.html # addresses Chrome rejects, place:, bookmarklet, blank (v1.1.0)
weird/bm-legacy-1.0.1-backup.json # a 1.0.x Replace backup, read with root markers (v1.1.0)
```
Generated on demand, never committed: `scripts/gen-fixture.mjs` writes
arbitrarily large Netscape files into `tests/fixtures/generated/` (git-ignored)
for the 10k responsiveness item in §5 and the 100k parse measurement in §6.
Three behaviours have **no dedicated fixture** because a real browser export
already covers them, and a second file would only be a second thing to maintain:
| Behaviour | Covered by |
|---|---|
| `<HR>` separators skipped | `firefox-html-export.html` (`fixtures.test.ts` "firefox: DD does not eat the subtree, HR is skipped") |
| `ADD_DATE="0"` → omitted, **no** warning | `chrome-131-export.html` (same suite, asserted explicitly) |
| Depth past the cap → `TOO_DEEP` | built synthetically in `parse/netscape-html.test.ts` — cheaper and clearer than committing a 201-level file |
The two browser JSON fixtures are **pairs**: each describes the same profile
as an HTML fixture written by that browser's own exporter, and the parity rule
of `04 §2a/§2b` is asserted on them — equal trees and warnings once the JSON's
extra knowledge (where Other and Mobile were) is projected away. Neither is a
capture from a real profile yet; capturing one is a `15` backlog item.
**Rule:** every browser-specific parser quirk discovered later gets a fixture
+ regression test in the same PR.
+ regression test in the same PR. `CONTRIBUTING.md` documents the full ritual
end to end; note `.gitattributes` sets `tests/fixtures/** -text` so EOL
normalization cannot rewrite the CRLF/BOM bytes a bug may depend on.
## 3. Core test suites (one file per module, mirrored paths)
@@ -53,16 +83,30 @@ generate-huge.ts # script: emits 100k+1 node file on demand
aggregated warning; entity unescaping; injection fixture yields inert text
titles (assert no `<` execution possible — title equals literal string);
caps: node/depth/size errors with correct codes.
- **`serialize/netscape-html.test.ts`** — golden-file comparison; escaping;
toolbar attribute placement; 4-space indentation.
- **`serialize/netscape-html.test.ts`** — golden-file comparison (4-space
indentation, attributes only when present); exactly one root marker per
folder, the toolbar winning; markers round-trip through our parser; escaping
of the four markup characters and CR. ⚠️ Written in v1.1.0: this bullet
described it from Phase 1, but the file did not exist until then.
- **`serialize/bm-json.test.ts`** (v1.1.0) — stable field order with the root
markers, `root` never beside `toolbar`, compact backup vs indented export,
markers round-tripped through the parser.
- **Round-trip (the flagship suite):** the assertion is
`parse(serialize(tree)).roots deepEquals project(tree, format)` — note
`.roots`, since `parse` returns a `ParseResult` (`02 §4`) — plus
`warnings.length === 0`, so a parser that silently degrades cannot "pass".
Run across all three corpora: sample trees, every parsed browser fixture, and
a property-style randomized generator (500 random trees, seeded) with titles
from a nasty-string pool (quotes, commas, newlines, emoji, `</a>`, path
slashes).
a property-style randomized generator (200 random trees per format, seeded)
with titles from a nasty-string pool (quotes, commas, newlines, emoji, `</a>`,
path slashes).
⚠️ **Until v1.1.0 the seeded corpus was empty.** `makeRng` seeded xorshift32
straight with the integers 1–200, whose first draws are all near zero, so
`generateTree` drew a child count of 0 every time and the suite compared 200
empty trees. The seed is now scrambled first, and the suite asserts the
corpus holds more than 1 000 nodes before it asserts anything else. Any new
seeded suite carries the same guard (`merge.test.ts` checks that more than a
quarter of its seeds actually reuse a folder).
`project(tree, format)` is a documented pure helper in the test utils that
models each format's declared lossiness. **A strict identity round-trip is
@@ -81,63 +125,433 @@ generate-huge.ts # script: emits 100k+1 node file on demand
and user-facing (`04 §3`, `06 §3.2`, `13 §3`); the fix is to bend the test to
the documented format, never the format to the test.
- **`normalize-url.test.ts`** — case, default ports, root-slash, preserved
query/hash, invalid-URL passthrough.
query/hash, invalid-URL passthrough; since v1.1.0 a bare `?` or `#` keys like
the URL without it (`05 §2`).
- **`timestamps.test.ts`** — s/ms/µs magnitude table, invalid → undefined.
- **`dedupe.test.ts` / `diff.test.ts`** — index building, in-file dupes,
`skippedExisting` vs `skippedInFile` kept distinct, folder preservation,
merge path-matching. **Replace-mode guard:** a Replace plan built from a file
whose URLs all exist in the browser must yield `toCreate === <all file
bookmarks>` and `skippedExisting === 0` — otherwise a user re-importing their
own backup loses everything (`05 §3`).
preview badges.
- **`plan.test.ts` / `route.test.ts` / `merge.test.ts` / `caps.test.ts`**
(v1.1.0) — root routing and unwrapping; Merge reusing live folders level by
level, case-sensitively, never into managed folders; the 200-seed merge
properties (`05 §5`); the backup caps. **Replace-mode guard:** a Replace plan
never dedupes — not against the browser, not within the file — and plans
against emptied roots, otherwise a user re-importing their own backup loses
part of it (`03 §1`).
- **`import/run-import.test.ts`** (v1.1.0) — the whole pipeline against the
in-memory `chrome.bookmarks` (`tests/helpers/fake-bookmarks.ts`, which now
rejects unparseable URLs and turns `url: ''` into a folder, as Chrome does):
Merge reuses `Bookmarks bar/Dev`; a second Merge with dedupe creates nothing;
a Replace restore of its own backup, run twice, gives the original tree with
Mobile back in Mobile; a 1.0.x backup restores into the roots; in-file
duplicates survive a Replace; the invalid-URL fixture completes; the backup
is written before the first removal.
- **`import/safety-backup.test.ts`** — the picker/anchor gates, and the three
cap breaches (nodes, depth, bytes) where nothing is written, downloaded or
confirmed.
- **`csv` state machine** — RFC 4180 torture cases: `""` escapes, CRLF inside
quotes, delimiter sniffing, BOM tolerance, `\/` path escapes.
- **`detect-format.test.ts`** — sniffing matrix incl. wrong extensions.
- **`detect-format.test.ts` / `parse-file.test.ts`** — sniffing matrix
incl. wrong extensions, the anchored doctype, JSON dialect routing, and
`JSON.parse` called exactly once per file.
- **`parse/chrome-json.test.ts` / `parse/firefox-json.test.ts`** (v1.1.0) —
roots, vendor roots, localized-title fallback, date units, skipped
addresses, caps.
- **`parse/netscape-tolerance.test.ts`, `parse/bm-json.v11.test.ts`,
`parse/csv.v11.test.ts`, `parse/shared.test.ts`, `href.test.ts`** (v1.1.0) —
the reader rules of `05 §1`: a list after a loose bookmark, every entry after
an unescaped `<b>`, root markers read by value, a list wrapped in a `<div>`,
the node cap counted before the DOM is built; addresses Chrome would reject
skipped and counted, `place:` kept only in the restore formats; empty titles
kept; a 1.0.x backup's roots recognised; a CSV quote left open reported with
its line, formula cells neutralised on export and restored on import.
## 4. Browser-layer tests
`tests/unit/browser/write-queue.test.ts` with a mock implementing
`create/removeTree` + failure injection:
- Order preservation (DFS, parent-before-child, sibling order).
- Progress cadence (every 50 + final).
- Order preservation (DFS, parent-before-child, sibling order); a Merge
segment writes into the existing folder it names, after what is there.
- Progress cadence (the first create, every 50, and the final one), one
denominator across segments, the path prefixed with the segment's trail.
- Abort mid-tree → `BmAborted` carries exact `done` count; no further calls.
- API error on node k → typed failure, k−1 successes reported.
- Replace pre-step calls `removeTree` only on root children.
Also in `tests/unit/browser/` (v1.1.0):
- **`write-lock.test.ts`** (`03 §5`) — a free lock runs the operation and is
requested `{ ifAvailable: true }`; a held lock refuses at once with
`WRITE_LOCKED` and never runs it; with no Web Locks API it simply runs.
- **`diagnostics.test.ts`** (`09 §7`) — the newest 200 kept, oldest first, with
page-relative times; the report's exact keys; a described failure logged by
code with its URL-bearing detail absent; crash hooks record names only, and
stop after teardown.
**Firefox flavour (since v1.3.0).** There is no Firefox in CI, so
`tests/helpers/fake-bookmarks.ts` takes `{ flavour: 'firefox' }` and then
behaves the way Firefox's source says its API does
(`browser/components/extensions/parent/ext-bookmarks.js`, Places'
`Bookmarks.sys.mjs`): GUID roots in the order Menu, Toolbar, Other, Mobile,
all four always present; no `folderType`; separators as
`{ type: 'separator', url: 'data:' }`; a same-folder `move` that takes the
final position; no `onChildrenReordered` or `onImport*`; `get('3')`
rejected; addresses over 65 536 characters refused. Firefox has suites of its own rather than
a second pass of the Chromium ones: `firefox-import.test.ts` (roots by GUID;
Merge, New-folder and Replace — all four roots emptied, the backup restored
twice; export), `edit-firefox.test.ts` (the edit model, keyboard positions,
Sort A→Z around separators, drops and Alt+↑/↓ at Firefox's index, the re-read
when the browser reports another landing place), `live-tree.test.ts`
(separators, counts, the Menu marker, each browser's move index) and the pure
`firefox-menu.test.ts`. The position fallback in `getRoots`, which neither
fake reaches — both have known ids — is tested in `bookmarks.test.ts` with
hand-built roots of unknown ids, including a Menu listed first. ⚠️ The fake is built from reading Firefox's source;
a sanitized `getTree()` dump from a real Firefox 140+ profile, committed as a
fixture the fake is checked against, would turn that reading into evidence
(`00 §10`).
### #edit logic, stores, styles and scripts
The components have no test framework (§1), so everything that can move out of
them is tested where it lives:
- **`stores/edit-session.test.ts`** (v1.1.0) — the #edit commands (`03 §3`)
against the in-memory fake, which now models Chrome's `move` (the same-parent
index rule), `update` and `remove` (refusing a non-empty folder): a re-read
keeps expansion and focus; Sort plans, then puts the folder in order,
declines a sorted folder, and on a refusal part-way reports `done`/`total`
and re-reads; a drag reorders by Chrome's index rule; a rename is trimmed and
a blank or unchanged one makes no call; focus moves to the next row after a
delete; a new folder clears a search that would hide it; duplicates are
scanned only while shown.
- **`edit/sort.test.ts`** (v1.1.0) — folders first, natural order, case and
accents ignored, ties stable, untitled bookmarks by address; only
out-of-place children move; 300 seeded random folders end sorted when the
moves are applied with Chrome's index rule (`05 §10`).
- **`edit/move-target.test.ts`** — since v1.1.0 also `planDrop`: both index
spaces, across folders, into a bookmark, beside itself, beside a root.
- **`edit/live-sync.test.ts`** (v1.1.0) — with a hand-fired scheduler: one
batch per frame, a burst past the limit becomes one re-read and no patch,
`resync`, `dispose` (`05 §11`).
- **`stores/toast.test.ts`** — since v1.1.0 also: a danger toast never
auto-dismisses, and the queue moves on once it is dismissed.
- **`styles/contrast.test.ts`** (widened in v1.1.0 to four surfaces and the
3:1 boundary pairs) and **`styles/motion.test.ts`** (v1.1.0) — the token
contrast pairs (`06 §1`) and the reduced-motion guard (`06 §5`), both parsed
from the real stylesheets, so a new component cannot opt out by forgetting.
`motion.test.ts` first checks that it found more than 20 styled files to
police.
- **`styles/focus-ring.test.ts`** and **`styles/forced-colors.test.ts`**
(v1.2.1) — the two `06 §5` rules 1.2.0 broke without a test noticing. The
first fails on a component that insets a focus ring (`outline-offset` below
zero) while filling a state with `--accent`, unless that ring is
`--accent-fg`: the theme control's ring was accent on accent. The second
holds the list of components that show state by a fill or a shadow and
requires each to carry a `@media (forced-colors: active)` block naming a
system colour. Both read the real `.svelte` files; the second's list is
hand-maintained, like the contrast pairs.
- **`edit/tree-keyboard.test.ts`**, **`edit/tree-keys.test.ts`** and
**`stores/edit-session.test.ts`** — since v1.2.1 also Alt+↑/↓ (`05 §10`):
`nudgeTarget` at both ends of a folder, stepping over an open neighbour's
children, in a filtered list; the key reaching the command only with Alt
alone; the move itself by Chrome's index rule, refused for a root, a managed
node and while busy, one at a time, and returning the row's place among the
siblings on screen — under a search too, where it passes hidden items.
- **`stores/edit-live.test.ts`** (v1.2.1) — the wiring that used to sit
untested in `EditTab`'s `onMount`, with `wxt/browser` mocked to seven
hand-fired event emitters and a hand-fired frame: a frame's events land as
one patch; a created node with no parent is ignored; nothing is patched
during Chrome's own import, and its end re-reads once; a wholesale reorder
re-reads; teardown detaches every listener and drops what was queued.
SonarCloud's new-code gate is what asked for it — moving code out of a
component makes it count.
- **`components/focus-heading.test.ts`** — since v1.2.1 also
`focusOwningTree`: a click on a row's control hands focus to the tree it
sits in, and does nothing outside one.
- **`links.test.ts`** — since v1.2.1 also `ACCESSIBILITY.md`: the file exists
and the About link ends at it.
- **`accessibility-statement.test.ts`** (v1.2.1) — the statement is a public
promise nothing in the build reads, so its routes and its key table are
pinned: the README links to it; the issue form exists and carries the
`accessibility` label; the address is the same in the statement, the README
and the issue chooser; every key `tree-keyboard.ts` switches on has a row;
it states a goal and an untested list, and it is dated. It cannot tell
whether a sentence is *true* — that is `§5`'s last item.
- **`tests/unit/scripts/`** — the repo's own gates, tested like code. New in
v1.1.0: `guard.test.ts` (`08 §3`), `check-manifest.test.ts` (a correct build
passes, one without the CSP fails) and `sanitize-formats.test.ts` (the
browser JSON formats and the audit's HTML leaks, beside the older
`sanitize-bookmarks.test.ts` — `09 §6`). New in Phase 10:
`check-licenses.test.ts` (SPDX expressions, the shipped list held stricter
than the toolchain's, a missing or custom licence refused, the repository's
own lockfile passing — `09 §3.2`) and `triage.test.ts` (every branch of the
maintenance-mode decision, the feature form's dropdown wording, and no event
text interpolated into the workflow's shell — `12 §2.6`).
## 5. Manual QA checklist (run before every store submission)
**A visual sweep first, without loading the extension** (since v1.1.0).
`scripts/screenshots.mjs` serves the **built** extension — `npm run build`
first — on `http://localhost:4318` with a fake `chrome`: neutral sample
bookmarks, so no real profile ever appears, and in-memory storage. Every HTML
page is served with the production CSP as a `<meta>`, so a violation shows in
the console exactly as it would in the extension. Pages take
`?theme=light|dark&lang=en|vi|ja|zh-CN|ro&legal=0|1` and the route as the hash —
`manager.html?theme=dark&lang=vi#edit`; `legal=0` shows the gate. `--shoot`
photographs every route × theme × language at 1280×800 and the popup per theme
× language at 360×420 with a local headless Chrome (`CHROME_PATH`, or the usual
install paths), plus the README and store sets (`13 §2`). It does not shoot
the gate (`legal=0`) — open that by hand in each language. Use it to sweep layout, translation overflow and both themes in
minutes. It is **not** the pass below: each page has its own fake tree and
storage, nothing written survives a reload, and the popup's tiles open nothing.
**Fresh profile, Load unpacked:**
- [ ] Legal Gate appears once; declines block #import/#export/#edit; accept
persists across restart; **#settings and #about reachable pre-accept**
(switch language before accepting and confirm the gate re-renders in it).
- [ ] Import each browser fixture via drag-drop *and* picker; preview stats
sane; default mode creates `Imported <date>` folder correctly.
- [ ] Merge mode reuses existing same-path folders; Replace forces the backup
and blocks deletion until it is confirmed (cancel the save dialog → the
import must abort with nothing deleted); then result matches the file,
with toolbar entries landing in the Bookmarks Bar.
- [ ] **Chrome's `Bookmarks` file** — a copy of a real profile's, or
`tests/fixtures/chrome-156-Bookmarks`. The picker lists it although it
has no extension; the preview names the format "Chrome Bookmarks file"
and marks the bar/Other/Mobile folders with their `→` pills; a Merge puts
their contents back into the real roots, not into folders named after
them.
- [ ] **A Firefox JSON backup** (`bookmarks-YYYY-MM-DD.json`, or
`tests/fixtures/firefox-bookmarks-2026-07-25.json`): format pill "Firefox
backup"; in new-folder mode its roots arrive under localized names (check
every non-English locale too); `place:` smart bookmarks are skipped and
counted.
- [ ] **Merge reuses folders:** import a file holding `Bookmarks bar/Dev/…`
into a profile that already has `Dev` — no second `Dev`; the new items
land at the end of the existing one, and the report says how many
folders were reused. Import it again with dedupe on → nothing created.
- [ ] **Replace:** the confirmation states how many bookmarks and folders will
be deleted and written — check both against the profile and the preview
(Cancel is focused; Enter must not confirm). Cancel the save dialog → the
import aborts with nothing deleted. Then a real Replace: the result
matches the file, toolbar entries in the Bookmarks Bar. Then restore the
safety backup with Replace **twice in a row**: the original tree both
times, Other and Mobile contents back in their own roots, never nested
one level deeper.
- [ ] Dedupe toggle: re-import same file → all skipped. With **Replace**
selected the checkbox is disabled and unchecked; re-importing your own
backup restores everything.
- [ ] 10k-node generated file: UI stays responsive, progress moves, Cancel
stops within ~1s, report counts correct.
backup restores everything, duplicate links included.
- [ ] 10k-node generated file: UI stays responsive, progress moves from the
first create, Cancel stops within ~1s, report counts correct.
- [ ] Export all 4 formats; re-import HTML/JSON → tree equivalent; re-import
CSV → equivalent **modulo the documented CSV losses** (`04 §3`: empty
folders gone, top-level "Bookmarks bar" arrives as an ordinary folder,
no `lastModified`); Excel opens CSV (BOM ✔); filenames correct.
- [ ] Edit: rename (F2), delete w/ descendant count, new folder, drag-drop
reorder + reparent, Move-to menu, search expands ancestors, duplicate
panel bulk-keep-first.
- [ ] Keyboard-only pass of the tree (WAI-ARIA pattern) + dialogs.
- [ ] Language switch EN→VI→JA live-updates all tabs; dates/numbers
localized; restart persists.
- [ ] Theme: system/light/dark; contrast spot-check.
- [ ] Edit: rename (F2; Esc cancels, leaving the field commits), delete w/
descendant count (focus moves to the next row), new folder (also with a
search active), search expands ancestors, duplicate panel shows each
copy's folder, bulk-keep-first.
- [ ] **Sort A→Z** on a mixed folder: folders first, then "Item 2" before
"Item 10", case ignored; the confirmation states how many items move; an
already sorted folder says so instead of asking. From the toolbar with a
bookmark focused it sorts that bookmark's folder.
- [ ] **Drag to reorder:** the upper edge of a row drops before it, the lower
edge after it (a line shows where), the middle of a folder inside it (a
dashed outline). Dropping beside itself or into its own subfolder does
nothing; Esc mid-drag leaves no row highlighted.
- [ ] Keyboard-only pass: Tab reaches the tree in one stop (row buttons are not
tab stops); arrows, Home/End, type-ahead, Enter, F2, Del. The menu key
**and** Shift+F10 open **Move to…** with focus in its filter — type to
narrow, Tab to a folder, Enter moves the item there; Esc closes it and
focus returns to the tree. Ctrl+C copies the focused link. Every dialog
opens with focus inside and returns it on close. **Alt+↑ / Alt+↓** moves
the focused row one place among its siblings and stops at either end;
a permanent root does not move. After clicking a row button or a
chevron with the mouse, the arrow keys still work.
- [ ] **Focus is never lost:** Tab to the theme control — the ring is visible
on the selected segment, in the header and in `#settings`, in both
themes. After "Keep the first of each" and after a toolbar Sort A→Z,
focus is on something visible. After "Open in Edit" from an import
report it is on the page's main region, which shows no ring: the test is
that the next Tab goes into the tab's content, not back to the header.
- [ ] **Screen reader** (Narrator on Windows, or NVDA; VoiceOver on macOS):
the tree announces each row's name, level and "n of m"; a dialog reads
its title and body; the import's steps and outcome are spoken; Alt+↓
speaks the row's new position, once. Record the reader and its version
in `ACCESSIBILITY.md`'s "What has been tested".
- [ ] **Contrast themes** (Windows: Settings → Accessibility → Contrast
themes; or DevTools → Rendering → `forced-colors: active`): the tree's
focused row, the drop line of a drag, the selected theme segment, the
current tab, the selected import-mode and export-format cards and the
progress bar's fill are all still distinguishable.
- [ ] **Zoom and narrow windows:** at 200 % zoom and at a 400 px-wide window,
every route still works without a horizontal scrollbar on the page, and
no control is clipped or covered.
- [ ] **`ACCESSIBILITY.md` is still true:** its key table matches `06 §5`, its
known limitations still exist (and nothing new belongs there), and its
"last reviewed" date is this release's.
- [ ] Language switch EN→VI→JA→简体中文→Română live-updates all tabs;
dates/numbers localized; restart persists. Header switcher and the
`#settings` row agree at all times (one state, two views).
- [ ] **Romanian plurals read right** at all three forms: import or select 1,
then 2–19, then 20 or more items and read the counts — "1 marcaj",
"5 marcaje", "20 de marcaje" — in the import stats, the Start button and
the popup tiles.
- [ ] **Chinese renders as Chinese**: with 简体中文 selected, `<html lang>` is
`zh-CN` and characters such as 设置 / 导入 use Simplified Chinese glyphs,
not Japanese ones. With the browser in Traditional Chinese (`zh-TW`)
and the setting on Automatic, the UI is English, and so is the name in
chrome://extensions (`07 §1`).
- [ ] Romanian and Chinese in the popup, the tab bar, the status bar and
every button: nothing truncated, wrapped mid-word or overlapping. The
sweep photographs each route at 1280×800 and the popup at 360×420; this
item covers what it cannot — narrower windows, open dialogs, the import
preview, a running import and the Legal Gate.
- [ ] Theme: system/light/dark. In **both** light and dark, read text on every
surface — page, panels, inputs and the status bar, a selected row or
card — and check the focus ring, control borders and disabled controls
(readable, not faded). `contrast.test.ts` checks tokens only; an
`opacity` on text or a hardcoded colour shows up only here.
- [ ] **Reduced motion** (DevTools → Rendering → `prefers-reduced-motion:
reduce`, or the OS setting): nothing moves — no sliding tab indicator,
toast slide, dialog rise, marching ants, travelling progress stripes,
icon bob/spin/tilt/draw/pulse — yet an open folder's chevron still turns.
Back to no preference: the motion returns.
- [ ] Settings auto-save: change a value, close the tab immediately, reopen —
the value stuck. The "Saved" toast appears only *after* the write
confirms, and a failure says so instead.
- [ ] Legal Gate "Close tab" either closes the tab or shows the
manual-close message — never appears to do nothing.
- [ ] Two Manager tabs open: changing a setting in one **is** reflected in the
other, and accepting the gate in one drops the gate in the other. Also:
clearing storage in one must **not** re-raise the gate in the other —
acceptance is adopted in one direction only, by design (`03 §4`).
- [ ] **Two Manager tabs, one writer** (`03 §5`): start a Replace or a large
import in one; while it writes, try an import, Sort A→Z and "keep first"
in the other — each is refused at once ("Another BookmarkMagic tab is
writing…") and nothing changes. The second tab's #edit keeps up with the
import without freezing (events land once per frame, `05 §11`); once the
first finishes, both work normally.
- [ ] **Popup with a Manager tab already open** on another route: Import,
Export and Open manager each switch that tab to their route; while it is
writing, the tab stays put and shows the busy toast. The popup's counts
leave out the three roots — an empty profile reads 0 and 0.
- [ ] About → **Copy diagnostics** after a failed import: the pasted log holds
phases, error codes and counts — no title, address or file name
(`09 §7`).
- [ ] Browser **Back** during a write: stays on `#import`, progress and Cancel
remain reachable, and a "busy" toast explains the refusal.
- [ ] Browser **Back** while the backup attestation is on screen: same. This is
the path that used to deadlock the Manager until the tab was closed.
- [ ] Right-click → Options **while a write is running**, with a Manager tab
already open. The deep-link is refused by the same guard; confirm it
behaves as `02 §5` describes rather than appearing to do nothing.
- [ ] The import report states that imported bookmarks carry today's date — in
every locale.
- [ ] chrome://extensions → no errors logged during the whole pass.
- [ ] Edge (or Brave): smoke test install + import/export.
**Upgrade + published-build pass (every submission after the first):**
These have no equivalent in a first submission, and the upgrade item is the only
failure mode that would hit every installed user at once.
- [ ] Install the **currently published** version from the store on a clean
profile. Accept the gate, change two settings, import a fixture. This is
the prior state the upgrade test needs.
- [ ] Update that profile to the new build (load unpacked over it, or wait for
the store rollout). Then: the legal gate does **not** reappear
(`legal.acceptedVersion` survived), both settings survived, bookmarks are
untouched, and chrome://extensions logs nothing.
⚠️ If `LEGAL_VERSION` was bumped the gate *will* reappear for everyone —
that is `14 §2` working as designed, and it must be a deliberate decision
recorded in `15`, never a surprise found here.
- [ ] After the update goes live: install from the store on a clean profile and
smoke it. This is the only check that the artifact users receive is the
artifact that was tested (`13 §1b` step 10).
### Firefox and Edge (since v1.3.0) — before the first submission to each
Firefox (140 or later; about:debugging → Load Temporary Add-on →
`.output/firefox-mv3/manifest.json`, on a profile you can afford to lose):
- [ ] The four roots are where they belong: an import in Merge mode of a
BookmarkMagic HTML export puts the bar's entries in the **Bookmarks
Toolbar**, Other's in **Other Bookmarks**, loose entries in the
**Bookmarks Menu**; New-folder mode puts `Imported <date>` under Other
Bookmarks.
- [ ] **Replace, then restore the safety backup with Replace twice**: menu,
toolbar, Other and Mobile come back in their own roots, never nested; the
confirmation counted the separators it was about to delete and said they
would not come back.
- [ ] Export all four formats: no `data:` entry where a separator was; HTML
re-imports into Firefox with the menu restored; an import of Firefox's
own HTML export reports the separators it skipped.
- [ ] #edit: separators are lines that ↑/↓ and type-ahead skip; Alt+↑/↓ steps
past one; a drag before/after a row lands exactly there (the move-index
rule, `05 §10`); Sort A→Z leaves separators where they are; the
duplicate panel never lists separators.
- [ ] Replace's backup on Firefox goes through the **anchor download and the
"I have the backup" confirmation** (no `showSaveFilePicker`).
- [ ] About → "Store listing" opens the AMO listing; right-click → Options
lands on #settings (a second Manager tab here is expected, `08 §9`).
- [ ] The Manager in every language; Firefox's own locale fallback.
Edge (the Chrome package, Load unpacked from `.output/chrome-mv3`):
- [ ] **Signed in with sync on**: #edit loads and Merge writes — no
`NO_WRITABLE_ROOTS` (`08 §10`, unverified until this item is done).
- [ ] The Chrome items above that touch roots: Favorites bar / Other
favorites receive what Bookmarks bar / Other bookmarks would.
- [ ] About → "Store listing" opens the README's install section (the Edge
listing's address is not known until it exists).
## 6. Performance budgets (checked manually in v1)
- Parse 25 MB / 100k HTML file: < 2 s.
- Preview render after parse: < 500 ms (lazy tree).
- Manager cold open: interactive < 1 s.
- Import 10k nodes: progress visible ≤ 500 ms after start; cancel ≤ 1 s.
### Measured 2026-07-26 — Phase 5
A generated 100 000-node Netscape file (11.2 MB, 99 000 bookmarks in 1 000
folders), timed under jsdom — one column per jsdom major, never overwritten:
| Stage | jsdom 29 (2026-07-26) | jsdom 31 (2026-11-18) |
|---|---|---|
| `detectFormat` (now `sniffFormat`) | 0 ms | 0 ms |
| `parseNetscapeHtml` | **2 869 ms** | **2 484 ms** (median of 3 runs, 2 416–2 733) |
| `buildUrlIndex` | 42 ms | not re-run (pure JS) |
| `diffAgainstBrowser` | 53 ms | not re-run (pure JS) |
| `serializeNetscapeHtml` | 72 ms | not re-run (pure JS) |
The jsdom 31 column: Node 26.13, Windows 11, Intel i7-14700KF, the file from
`gen-fixture.mjs --nodes 100000`. The jsdom 30 bump (2026-08-03) added no
column, so there is no jsdom 30 figure.
⚠️ **This does not settle the 2 s budget either way.** Everything except the
parse is pure JS and comfortably fast; the parse is dominated by `DOMParser`,
and jsdom's parse5 implementation is roughly an order of magnitude slower than
Chrome's native parser. The budget is about the real browser, so the honest
reading is "≤ 2.9 s in the slowest environment we can measure from a test".
The number that decides it has to come from Chrome. ⚠️ Still unmeasured
(`00 §10.8`) — but no longer unmeasurable: the generator the original entry
assumed now exists.
**Procedure (reproducible, ~5 minutes):**
```bash
node scripts/gen-fixture.mjs --nodes 100000 --out tests/fixtures/generated/huge.html
npm run build # load .output/chrome-mv3 unpacked, fresh profile
```
Then in the Manager: open DevTools → Performance, drop the file on `#import`,
and time **drop → preview rendered**. Record the number, the Chrome version and
the machine below; a figure without those three is not comparable to anything.
| Date | Chrome | Machine | Drop → preview |
|---|---|---|---|
| ⚠️ | | | |
Re-measure whenever the jsdom major changes, since the table above is jsdom's
parse5 and not Chrome's parser — a jsdom bump invalidates the 2 869 ms row
rather than updating it. Add a column; do not overwrite.
+358 -195
View File
@@ -27,224 +27,329 @@ workflows use the `reusable-*` naming family. There is **no
## 2. Workflows (caller stubs in this repo)
### 2.1 `.github/workflows/ci.yml` — every push/PR to `main`
**This chapter no longer copies the workflow YAML** (decided 2026-10-28). It
used to, and the copies drifted three times: a Dependabot bump moved
`actions/setup-node` v6 → v7 in `.github/workflows/` and never touched this doc,
the `check:manifest` step added to the release job in `674ac34` was missing
here, and a copy kept `continue-on-error` after the file had dropped it.
Because docs win over code in this project, a stale copy is a standing
invitation to "reconcile" a pinned action backwards or delete a security gate.
**The workflow files are the ground truth about themselves.** What follows is
what a YAML file cannot say: why each job exists, what it must keep doing, and
the traps already stepped in.
The local `quality` job exists because the ops reusable workflow performs none
of it (§1). The `build` job delegates packaging.
Common to every job since v1.1.0:
```yaml
name: CI
- `actions/checkout` with `persist-credentials: false` — no job pushes, so no
job leaves a token in `.git/config`.
- `actions/setup-node` with `node-version-file: .nvmrc` (Node 26, `01 §2`).
The ops reusable takes a string input and cannot read the file, so `ci.yml`
passes it `'26'` — keep the two equal by hand.
- `npm ci --ignore-scripts`, then `npx --no-install wxt prepare`. No dependency
gets to run code at install time (SonarCloud S6505); our own `postinstall` is
the one script we need, so it runs explicitly, from the local binary, never
fetched. A local `npm ci` still runs `postinstall` normally. **One exception
we do not control:** the `build` job delegates to the ops reusable, which runs
a plain `npm ci`, so install scripts do run there. That job holds a read-only
token and no secrets; an ops-repo input to skip install scripts is on the
`15` backlog.
- Reusable workflows get **named** secrets, never `secrets: inherit`: they are
pinned to the ops repo's moving `main`, so each one receives only what it
declares.
on:
push: { branches: [main] }
pull_request:
### 2.1 `ci.yml` — every push/PR to `main`
permissions:
contents: read
Three jobs. The two whose names branch protection requires (§5) are
`Quality gates` and `Build + package / build`.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
- **`quality` — "Quality gates".** Local, because the ops reusable runs no
quality gates at all (§1). In order: `lint`, `check` (svelte-check on the
TS 6 API — failing on warnings too since v1.2.1, which is what makes Svelte's
`a11y_*` checks a gate, `10 §3` — then the TS 7 `tsc`), `knip`, `coverage` (`11 §1` thresholds),
`guard` (`08 §3`), `check:licenses` (every licence in the lockfile, `09 §3.2`),
`npm audit --omit=dev --audit-level=low` (the
zero-runtime-dependencies claim, `09 T5`), `build`, `check:manifest`, and since
v1.3.0 `build:firefox` + `check:manifest -- --browser firefox` — the second
package, held to its own key set (`08 §1`, `08 §9`). The build/check pairs
exist because the unit test over `wxt.config.ts` proves what we *asked*
for and only the built manifest proves what WXT *emitted* — a dev build of
the same config carries `tabs`/`scripting`/`host_permissions`.
- **`windows` — "Windows smoke (guard + unit tests)".** Not required. The owner
develops on Windows, and the failures that only happen there — drive letters
and percent-encoding in script paths, CRLF checkouts — had no CI coverage.
- **`build` — "Build + package".** Delegates packaging to
`reusable-chrome-extension.yml` with `package-manager: 'npm'`,
`node-version: '26'`, `build-command: 'npm run build'`,
`source-dir: '.output/chrome-mv3'`, `release: false`. All four are required in
practice: leaving `package-manager` at its `'none'` default skips install and
build, then fails on `test -f ./manifest.json`, a file WXT never writes to the
repo root.
jobs:
quality:
name: Quality gates
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v6
with: { node-version: '24', cache: npm }
- run: npm ci
- run: npm run lint # biome check .
- run: npm run check # svelte-check + tsc --noEmit
- run: npm run knip
- run: npm run coverage # vitest --coverage, thresholds per 11 §1
- run: npm run guard # canonical grep gate, 08_MV3 §3
build:
name: Build + package
needs: quality
uses: poli0981/.github/.github/workflows/reusable-chrome-extension.yml@main
permissions:
contents: read
with:
package-manager: 'npm' # 01 §6 commits package-lock.json
node-version: '24'
build-command: 'npm run build'
source-dir: '.output/chrome-mv3' # WXT emits the manifest here
release: false
```
All four `with:` values are required. Omitting `package-manager` defaults it to
`'none'`, which skips install/build entirely and then fails on
`test -f ./manifest.json` — a file WXT never writes to the repo root.
⚠️ **`contents: write` on the `build` job is not a mistake.** The reusable
declares two mutually exclusive jobs — `build` (`contents: read`,
`if: !inputs.release`) and `release` (`contents: write`, `if: inputs.release`).
GitHub validates the caller's grant against **every job the reusable declares,
before evaluating any `if:`**, so `release: false` does not exempt the caller
from the release job's requirement. Granting `contents: read` makes the entire
run fail with `startup_failure`: no jobs, no log, and only the generic "this run
likely failed because of a workflow file issue" in the UI. Verified 2026-07-26
on the first real run of this workflow.
`npm run guard` runs the same script locally and in CI, so the gate cannot
drift between the two (`10 §3`). It is the single canonical pattern defined in
`08_MV3_COMPLIANCE.md §3`; do not restate the pattern here or anywhere else.
drift between the two (`10 §3`).
### 2.2 `.github/workflows/codeql.yml`
### 2.2 `codeql.yml`
Use the current reusable (`reusable-codeql.yml`, CodeQL Action v4). Its input is
`languages` — a **JSON array encoded as a string**, not the singular `language`
of the older `codeql.yml`.
```yaml
name: CodeQL
on:
push: { branches: [main] }
pull_request: { branches: [main] }
schedule:
- cron: '0 14 * * 1' # weekly, Monday
permissions:
security-events: write
actions: read
contents: read
packages: read
jobs:
analyze:
uses: poli0981/.github/.github/workflows/reusable-codeql.yml@main
permissions:
security-events: write
actions: read
contents: read
packages: read
with:
languages: '["javascript-typescript"]'
```
Calls the current reusable, `reusable-codeql.yml` (CodeQL Action v4). Its input
is `languages` — a **JSON array encoded as a string**
(`'["javascript-typescript"]'`), not the singular `language` of the older
`codeql.yml`. Weekly schedule plus push/PR to `main`; the permission block
(`security-events: write`, `actions: read`, `contents: read`, `packages: read`)
is repeated on the job because reusable workflows do not inherit it.
⚠️ **Prerequisite:** repo Settings → Advanced Security → CodeQL **"Default
setup" must be DISABLED**, or this advanced-setup workflow is rejected at SARIF
upload time.
### 2.3 `.github/workflows/release.yml` — on tag `v*`
### 2.3 `release.yml` — on tag `v*`
Standalone, **not** the ops reusable: the reusable's `release` job only does
`gh release create --generate-notes`. It produces no `SHA256SUMS.txt`
(required by `09 §5`), performs no store submission, and exposes no `outputs:`,
so a caller cannot reference the zip it built.
`gh release create --generate-notes`. It produces no `SHA256SUMS.txt` (required
by `09 §5`), performs no store submission, and exposes no `outputs:`, so a
caller cannot reference the zip it built.
```yaml
name: Release
Jobs, least privilege first (split 2026-10-28; the store job became three in
v1.3.0):
on:
push:
tags: ['v*']
| Job | Token | Does |
|---|---|---|
| `build` "Gate + package" | `contents: read` | install, **every CI gate again** (a tag skips the branch triggers, and must never ship what a PR would have blocked), `zip` and (since v1.3.0) `zip:firefox` — the Chrome/Edge package, the Firefox package and its sources archive — `check:manifest` on both packages, the tag ↔ manifest version check on both, `SHA256SUMS.txt` over all three files, each staged by its exact name so a missing one fails the run (a glob would pass with one of three); copies the three files and `SHA256SUMS.txt` into a plain `dist/` and uploads that as the artifact `release-<tag>` — `upload-artifact` skips hidden paths such as `.output/` by default, which failed the first v1.1.0 tag run before any Release existed |
| `publish` "GitHub Release" | `contents: write` | downloads the artifact, `sha256sum -c` it, creates the Release with `--verify-tag` (or re-uploads to an existing one). Installs nothing and runs no repository code — the only job that ever holds a write token |
| `store-chrome`, `store-firefox`, `store-edge` | `contents: read` | since v1.3.0, one job per store, each only when its own repo variable is `'true'` (`CWS_AUTOPUBLISH`, `AMO_AUTOPUBLISH`, `EDGE_AUTOPUBLISH`) and each in its own GitHub **Environment** holding only that store's secrets (§3). They install `tools/publish/` — `publish-browser-extension` and its three dependencies, from their own lockfile, scripts off — instead of the whole dev toolchain, check the downloaded files by exact name against the `SHA256SUMS.txt` of the **published Release** (not the artifact's own copy), and run its `publish-extension` binary. Before v1.3.0 a single `store` job ran `wxt submit` after a full `npm ci`: four Chrome secrets shared a runner with ~320 packages |
| `announce` | `contents: read` | Discord, only when `DISCORD_ANNOUNCE` is `'true'` |
permissions:
contents: read
Before the split, one job ran `npm ci` — every dependency's install script plus
our own tests — while holding `contents: write`, with the token also left in
`.git/config` by checkout.
jobs:
release:
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: write # create the GitHub Release
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v6
with: { node-version: '24', cache: npm }
- run: npm ci
**The Release step is idempotent deliberately.** `gh release create` fails
outright when a Release for the tag already exists, so any failure *after* it —
realistically the store job, once `CWS_AUTOPUBLISH` is on — stranded the tag: a
re-run could not get past that line, and recovery meant deleting the Release
and the tag by hand. `docs/13 §7` documents the manual escape; this removes the
need for it in the common case.
# Same gates as CI — a tag must never ship what a PR would have blocked.
- run: npm run lint
- run: npm run check
- run: npm run knip
- run: npm run coverage
- run: npm run guard
The announcement is gated because the reusable exits 1 on "No webhooks
configured". On the real v1.0.0 run the Release, the zip and `SHA256SUMS.txt`
all published correctly and the run still showed red. A red run on a good
release trains you to ignore the colour, so the notification must not be able
to fail the release.
- run: npm run zip # wxt zip → .output/<name>-<version>-chrome.zip
⚠️ **It is gated with `if:` on a repo VARIABLE, not with `continue-on-error`.**
GitHub **rejects** `continue-on-error` on a job that calls a reusable workflow
(`Property continue-on-error is not allowed`), and a rejected file does not
fail one job — the whole run is a `startup_failure` with zero jobs and no log.
That sat undetected from `5f4c6e7` until 2026-08-03 because the commit landed
after the `v1.0.0` tag and no tag was pushed in between. A variable and not a
secret: secrets cannot be referenced in a job-level `if:`.
- name: Verify tag matches manifest version
run: |
set -euo pipefail
MANIFEST_VERSION=$(jq -r '.version' .output/chrome-mv3/manifest.json)
TAG_VERSION="${GITHUB_REF_NAME#v}"
test "$MANIFEST_VERSION" = "$TAG_VERSION" \
|| { echo "::error::tag $TAG_VERSION != manifest $MANIFEST_VERSION"; exit 1; }
⚠️ **The webhook secrets are mapped by name.** This repo stores
`RELEASES_WEBHOOK` and `REPO_WEBHOOK`; the reusable reads
`DISCORD_RELEASES_WEBHOOK` and `DISCORD_REPO_WEBHOOK`. Under the old
`secrets: inherit` the reusable received neither, so the day `DISCORD_ANNOUNCE`
was set the job would have failed on "No webhooks configured". It now passes
each one explicitly under the name the reusable reads — found 2026-10-28 by
comparing the repo's secret list with the reusable's `workflow_call` block.
- name: SHA256SUMS
working-directory: .output
run: sha256sum *-chrome.zip > SHA256SUMS.txt
`tag_override` is **required**: the reusable resolves
`TAG="${INPUT_TAG:-$EVENT_TAG}"` with `EVENT_TAG = github.event.release.tag_name`,
which is empty under `on: push: tags`, so without it the job exits 1 on "No
release tag available". The announcement is a **job inside this workflow**, not
a separate `on: release: [published]` caller, because a Release created by
`gh release create` under the default `GITHUB_TOKEN` emits no event that starts
new workflow runs.
- name: GitHub Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
### 2.4 `notify-ci-failure.yml`
- name: Publish to Chrome Web Store
if: vars.CWS_AUTOPUBLISH == 'true'
env:
CHROME_EXTENSION_ID: ${{ secrets.CHROME_EXTENSION_ID }}
CHROME_CLIENT_ID: ${{ secrets.CHROME_CLIENT_ID }}
CHROME_CLIENT_SECRET: ${{ secrets.CHROME_CLIENT_SECRET }}
CHROME_REFRESH_TOKEN: ${{ secrets.CHROME_REFRESH_TOKEN }}
run: npx wxt submit --chrome-zip .output/*-chrome.zip
Runs on `workflow_run` of CI, gated on
`conclusion == 'failure' && vars.DISCORD_CI_NOTIFY == 'true'`, and passes the
one secret the reusable declares (`DISCORD_CI_WEBHOOK`) by name. The reusable
declares that secret `required: true` and GitHub validates it before any of the
reusable's own logic, so without the gate this caller failed on **every** CI
completion, success included. `DISCORD_CI_WEBHOOK` exists (set 2026-07-26); the
variable is still unset, so notifications stay off until the owner opts in. A
notification must never be able to change the colour of the thing it reports
on.
announce:
needs: release
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
secrets: inherit
```
### 2.5 `sonarcloud.yml` — SonarCloud CI analysis
The announcement is a **job inside this workflow**, not a separate
`on: release: [published]` caller. A Release created by `gh release create`
under the default `GITHUB_TOKEN` does not emit an event that starts new
workflow runs, so an event-driven caller would silently never fire.
Added 2026-10-28, replacing SonarCloud's Automatic Analysis so the project gets
**coverage** and a scan of exactly what CI builds. Project
`poli0981_bookmarkmagic`, organisation `poli0981`; settings live in
`sonar-project.properties`.
### 2.4 `.github/workflows/notify-ci-failure.yml`
- **A separate workflow, not a job in `ci.yml`:** a Sonar outage or a
quality-gate opinion must never turn CI red. The verdict reaches PRs as the
SonarCloud GitHub App's own check. It is not a required check.
- **Two jobs, so the token never shares a runner with dependency code.** A
job's secrets are loaded into its runner for the whole job, and any step can
read them from the runner process whatever its own `env:` says (the shape of
the March 2025 tj-actions compromise). `coverage` does the common install and
`npm run coverage` with **no secret**, and uploads `coverage/lcov.info` and
the generated `.wxt/` (which `tsconfig.json` extends, and which defines the
`@/` alias) as a one-day artifact; `scan` installs nothing — full-history checkout
(`fetch-depth: 0`, for new-code detection), the artifact, then the scan with
`-Dsonar.projectVersion=<package.json version>`, so "new code" means "since
the last release".
- The price of that isolation: the scan job has no `node_modules`, so Sonar's
type-aware rules resolve our own modules (through `.wxt/`) but not the
dependencies' types.
- The scan action is **pinned to a commit** (`v8.4.1`): it is the step that
holds `SONAR_TOKEN`. Dependabot and fork PRs get no repository secrets, so the
scan is skipped with a notice instead of failing.
- Coverage: `vitest.config.ts` measures every `src/**/*.ts` module and reports
`text` + `lcov`; the CI *gate* is still the core-only glob threshold of
`11 §1`. `sonar.coverage.exclusions` drops components, entrypoints and
scripts — the same split as `11 §1`, where those are covered by the manual
pass and the script tests. The three locale files are excluded from
duplication detection: they are parallel by design.
- No `sonar.qualitygate.wait`: an unreviewed Security Hotspot can only be
cleared by a person in the Sonar UI, and a CI step that waits on a human is a
step that is red for a reason nobody can fix from the repo.
```yaml
name: Notify CI failure
⚠️ **Prerequisite:** Automatic Analysis must be **off** in the SonarCloud project
(Administration → Analysis Method). With it on, the scanner refuses to run.
on:
workflow_run:
workflows: ['CI']
types: [completed]
Snyk is connected only as a GitHub App (the `security/snyk (poli0981)` PR
check); there is no `SNYK_TOKEN` and no Snyk step in any workflow.
permissions:
contents: read
actions: read
### 2.6 `triage.yml` — maintenance-mode triage
jobs:
notify:
uses: poli0981/.github/.github/workflows/notify-ci-failure.yml@main
permissions:
contents: read
actions: read
secrets: inherit
```
Added 2026-11-18 with `/MAINTENANCE.md`. On `issues: [opened, labeled]` and
`pull_request_target: [opened]` it runs `scripts/triage.mjs`, which reads the
runner's event file and prints a decision, then carries it out with the `gh`
CLI the runner ships — no third-party action ever holds its write token
(`issues: write`, `pull-requests: write`, `contents: read`).
The reusable already filters to `conclusion == 'failure'` on the default
branch, so the caller needs no `if:`.
- **The decision is code with tests**, not shell: `decide()` is a pure
function (`tests/unit/scripts/triage.test.ts`) — a feature-form issue
answering "Something new" is labelled `maintenance-mode`, commented and
closed *not planned*; the two in-policy answers get `needs-triage`; an
`enhancement` label the owner adds by hand closes the issue the same way; an outside
pull request titled `feat…` is closed. The owner's own issues, members,
collaborators, bots and anything labelled `roadmap` are exempt. The test also
pins the dropdown's wording against `feature_request.yml`, which is the only
thing the decision parses.
- ⚠️ **`pull_request_target` holds a write token for fork pull requests.** The
checkout is the base branch — the event's default — and nothing from the
pull request runs. Titles and bodies reach the script as the event file and
are only compared with constants; the shell reads back an action from a fixed
set, an integer, a label from a fixed list and a comment the script wrote, and
validates the first two before using them.
- **Idempotent.** The feature form fires `opened` and `labeled` for one new
issue. `concurrency` runs them one at a time per number and the second
re-reads the live labels and state before acting.
- The labels must exist (`§5`); `gh … --add-label` fails on a missing one.
- **Order: comment and close first, label last.** The label is what a re-run
reads as "done", so it must not exist before the work it stands for.
- **A hand label closes only when the owner adds it.** An `enhancement` issue
with no answer to the form's question is the owner's one-touch close when
the owner labelled it; from anyone else, or on `opened`, it goes to
`needs-triage` instead of being closed on a guess.
- `actions/checkout` and `actions/setup-node` are **pinned to commits here**,
unlike the other workflows, because this one runs them with a write token
on events anyone can trigger; and setup-node has no `cache:`.
## 3. Chrome Web Store publishing automation
### 2.7 `qodana.yml` — Qodana for JS
WXT ships publishing built-in: **`wxt submit`** (wrapping
`publish-browser-extension`). One-time local setup: `npx wxt submit init`
→ walks through creating the Google Cloud OAuth client + refresh token →
produces the four values above → store as **repo Actions secrets**.
Added 2026-11-18. `qodana-js` (JetBrains' JavaScript/TypeScript linter,
which needs the Ultimate licence `QODANA_TOKEN` carries) on push to `main`,
pull requests, a weekly schedule and `workflow_dispatch`. Configuration is
`qodana.yaml`: native mode (`withinDocker: false`), profile
`qodana.recommended`, fixtures and generated output excluded.
**Gating policy:**
- **Its own workflow, never required**, for the reason Sonar has one (§2.5).
- **Two jobs.** `scan` has a read-only `GITHUB_TOKEN`, installs the dev
dependencies (install scripts off) because `qodana-js` resolves types
through `node_modules`, runs the action with PR comments and annotations
off, and keeps the SARIF report as the `qodana-report` artifact.
`publish` installs and runs nothing: it uploads that SARIF to code
scanning (`category: qodana`), so the findings sit beside CodeQL's under
Security and quality and on pull requests.
- ⚠️ **The documented exception to §2.5.** Sonar's token never shares a
runner with dependency code; Qodana's cannot avoid it, since the analysis
needs the dependencies. The token only uploads reports to one Qodana
Cloud project. If a dependency is ever found compromised, rotate it in
qodana.cloud.
- The action is **pinned to the commit of v2026.2.2**, not the vendor's
moving `v2026.2` branch: it holds a token, and the newest tag was younger
than the 7-day cooldown when it was added. Dependabot proposes updates.
- `pr-mode: false`: the whole project every time. It is small, and a pull
request that touches only docs would otherwise scan nothing.
- Dependabot and fork pull requests have no secrets; the scan is skipped
with a notice and `publish` does not run.
- The report artifact is a zip inside the artifact, with absolute entry
names; `publish` extracts the one entry `/qodana.sarif.json` by name. A
glob for the file found nothing on the first run.
- **First run (2026-11-18): 27 findings, none a defect.** Three regular
expressions that could be simpler — fixed — and 24 that contradict a rule
of this repository, switched off in `qodana.yaml` with the reason beside
each: JSDoc completeness (doc comments here are prose, `10 §6`), bitwise
operators in the PNG CRC-32 of `gen-icons.mjs`, and the deliberately
doubled dark palette in `tokens.css`. A finding is fixed when it is a
defect and switched off, with its reason, when it is a convention; it is
never left standing to be ignored.
## 3. Store publishing automation (Chrome Web Store, Firefox Add-ons, Edge Add-ons)
Since v1.3.0 the release workflow can submit to all three stores, each step
**off until its owner switches it on** with a repo variable. Uploaded builds
still go through each store's review; automation removes the clicking, not the
review.
| Job | Gate (repo variable) | Environment | Secrets in that environment | Uploads |
|---|---|---|---|---|
| `store-chrome` | `CWS_AUTOPUBLISH=true` | `chrome-web-store` | `CHROME_PUBLISHER_ID`, `CHROME_EXTENSION_ID` (= the item id, `00 §9`), `CHROME_SERVICE_ACCOUNT_CLIENT_EMAIL`, `CHROME_SERVICE_ACCOUNT_PRIVATE_KEY` | the Chrome package |
| `store-firefox` | `AMO_AUTOPUBLISH=true` | `firefox-add-ons` | `FIREFOX_EXTENSION_ID` (= the gecko id), `FIREFOX_JWT_ISSUER`, `FIREFOX_JWT_SECRET` | the Firefox package and its sources, `listed`, Firefox desktop only |
| `store-edge` | `EDGE_AUTOPUBLISH=true` | `edge-add-ons` | `EDGE_PRODUCT_ID`, `EDGE_CLIENT_ID`, `EDGE_API_KEY` | the Chrome package |
- **The tool is `publish-browser-extension`** (6.2.0 — what `wxt submit`
wraps), installed from `tools/publish/`'s own lockfile: four packages, not
the dev toolchain. A job's secrets are readable by everything on its runner
for the whole job (§2.5), and these can push an update to every user.
- **One job per store**, so a store's credentials never share a runner with
another's, and one store refusing an upload does not stop the others.
- **Environments** carry the secrets, not the repository, so nothing else in
any workflow can read them. Give each one a required reviewer (the owner) to
approve every upload, **and** restrict its deployment branches and tags to
the tag pattern `v*`: an environment GitHub creates on first use has no
rule at all, so any branch with a workflow that names it — a pushed branch,
not only a release — could reach its secrets. The reviewer is the second
lock, not the only one.
- **Chrome Web Store API v2.** v1.1 — what the old `store` job's
client-id/secret/refresh-token secrets used — was shut down on 2026-10-15;
that job would have failed the day `CWS_AUTOPUBLISH` was set. v2 takes a
publisher id and a Google Cloud **service account** (`CHROME_API_VERSION=v2`
is set by the job, never left to the tool's default).
- **AMO: the first version must be created by hand.** The API (and the tool)
can add a version to an add-on that exists, not create one; `13 §8`. AMO
JWT credentials come from addons.mozilla.org/developers/addon/api/key/.
- **Edge: the first submission is made in Partner Center**, by hand (`13 §9`).
API keys (v1.1, with a Client ID) **expire every 72 days** — a scheduled
chore, not an incident; until rotated, `store-edge` fails and the others do
not.
- **No re-run of a store job that succeeded**: every store refuses a version
number it has seen. Re-run only the failed job (`13 §7`).
| Version | Method |
|---|---|
| v1.0.x (first listing + first reviews) | **Manual**: download the zip from the GitHub Release (not the CI artifact — the Release asset is the one `SHA256SUMS.txt` covers) → Dashboard upload → fill listing/privacy → submit. First reviews often ask questions; keep a human in the loop. |
| v1.1+ | **Automated**: the `Publish to Chrome Web Store` step in §2.3 runs after the Release succeeds, gated on the repo variable `CWS_AUTOPUBLISH=true` so it can be flipped off instantly if a review dispute is ongoing. |
| v1.0.x–v1.2.x | Chrome Web Store by hand (`13 §1b`) — the `CHROME_*` secrets never existed. |
| v1.3.0 | The first AMO and Edge versions **must** be uploaded by hand (`13 §8`, `13 §9`); the Chrome one by hand until the owner sets up §3's environment. |
| later | Each store automated once its environment has its secrets and its variable is `true`; switch a variable off to stop submitting there instantly (a review dispute, a rollout to watch). |
Notes: uploaded builds still go through CWS review before rollout (automation
removes the clicking, not the review). Consider Dashboard "staged rollout"
manually for risky releases.
Consider a staged (percentage) rollout on the Chrome Web Store for anything
touching the write paths — `CHROME_DEPLOY_PERCENTAGE` for the automated job,
the dashboard otherwise.
## 4. Branch/version flow
@@ -254,25 +359,83 @@ release: bump package.json (semver) → CHANGELOG.md (Keep a Changelog) →
git tag -s vX.Y.Z → push tag → release.yml
```
- Patch = fixes/translations · Minor = features / any permission or
privacy-tab change (per `09 §4`) · Major = breaking format/schema changes
(BM JSON version bump).
- Patch = fixes / translation fixes / **accessibility fixes** — including a
keyboard or assistive-technology route to something the product could
already do (v1.2.1's Alt+↑/↓ beside drag-to-reorder): it closes a barrier, it
does not add a capability · Minor = features, **a new UI language**
(it changes the listing and what the switcher offers — `07 §6`) / any
permission or privacy-tab change (per `09 §4`) · Major = breaking
format/schema changes (BM JSON version bump).
## 5. Repo settings checklist (one-time ⚠️)
- [ ] Branch protection on `main`: require CI, require review, linear history.
Required checks are the **job** names — `Quality gates` and
`Build + package` — not the workflow name.
- [ ] CodeQL **Default setup DISABLED** (Settings → Advanced Security),
otherwise `codeql.yml` fails at SARIF upload (§2.2).
- [ ] Actions secrets: the four `CHROME_*` values (after `wxt submit init`).
- [ ] Actions secrets for Discord notifications (all optional — the reusables
skip cleanly when unset, except `DISCORD_CI_WEBHOOK` which
`notify-ci-failure.yml` declares `required: true`):
`DISCORD_CI_WEBHOOK`, `DISCORD_RELEASES_WEBHOOK`, `DISCORD_REPO_WEBHOOK`,
`DISCORD_PING_ROLE_ID`.
- [ ] Repo variable `CWS_AUTOPUBLISH=false` initially.
- [ ] Dependabot: npm weekly, grouped minors; `github-actions` ecosystem too.
- [ ] Issue templates: bug (asks for browser + a sanitized sample file),
feature, translation.
- [ ] GPG signing required for tags (matches tracker-repo practice).
Only the repo-visible items can be verified from a checkout; the rest live in
GitHub settings and stay ⚠️ until the owner confirms them. An unticked box here
means "unknown", not "not done".
- [x] Branch protection on `main` — configured 2026-08-03. Two corrections to
what this line used to say, both learned by applying it:
- **Required checks are `Quality gates` and `Build + package / build`.**
The old text said `Build + package`, the job name in `ci.yml`. That is
not what gets reported: a job that *calls a reusable workflow* publishes
its check as `<caller job> / <reusable job>`. Requiring the caller's
name alone matches nothing, so every PR waits forever on a check that
can never arrive — `main` becomes permanently unmergeable.
- **`required_approving_review_count: 0`, not 1.** "Require review" is
right for a team and a lockout for one maintainer, who cannot approve
their own pull request. Zero still forces every change through a PR and
through the checks above; it only drops the second pair of eyes that
does not exist. Raise it the day a second maintainer does.
Also set: linear history (matches the rebase-merge practice), no force
pushes, no branch deletion, conversation resolution required. **Admins are
deliberately NOT enforced** — with a single maintainer, an escape hatch
from your own protection rules is the difference between a safety net and
a locked door.
- [x] CodeQL **Default setup DISABLED** (Settings → Advanced Security) —
confirmed 2026-07-26; `codeql.yml` uploads SARIF cleanly, which is only
possible with it off (§2.2).
- [ ] ⚠️ Store environments (§3), each with the owner as required reviewer,
deployments limited to tags matching `v*`, and only its own secrets: `chrome-web-store` (the four API v2 values;
`CHROME_EXTENSION_ID` is the item id in `00 §9`), `firefox-add-ons`
(`FIREFOX_EXTENSION_ID` = `bookmarkmagic@poli0981.dev` and the AMO JWT
pair), `edge-add-ons` (product id, Client ID, API key — rotate every 72
days). GitHub creates an environment the first time a job names it, with
no protection; add the reviewer, the `v*` tag rule and the secrets in
Settings → Environments.
- [x] Actions secrets for Discord notifications — **present as of 2026-10-28:**
`DISCORD_CI_WEBHOOK`, `RELEASES_WEBHOOK`, `REPO_WEBHOOK` (the last two under
names the reusable does not read; `release.yml` maps them, §2.3).
`DISCORD_PING_ROLE_ID` is optional and unset.
- [x] `SONAR_TOKEN` — set 2026-10-28, used only by `sonarcloud.yml` (§2.5).
- [x] `QODANA_TOKEN` — set by the owner 2026-11-18 (the Qodana Cloud project
token, Ultimate), used only by `qodana.yml`'s `scan` job (§2.7).
- [ ] ⚠️ SonarCloud **Automatic Analysis OFF** (SonarCloud → bookmarkmagic →
Administration → Analysis Method). Required for §2.5; with it on, the CI
scan errors out. The owner agreed to switch it off on 2026-10-28.
- [x] Private vulnerability reporting **enabled** (verified 2026-10-28 via the
API) — `SECURITY.md` and the issue chooser send reporters there first.
- [ ] ⚠️ Repo variables `CWS_AUTOPUBLISH`, `AMO_AUTOPUBLISH`,
`EDGE_AUTOPUBLISH` — unset, so no store job runs. Note that when a
variable does not exist the expression is simply false, so "not configured"
and "configured off" are indistinguishable from a run's output.
- [ ] ⚠️ Repo variables `DISCORD_ANNOUNCE` and `DISCORD_CI_NOTIFY` — both still
unset (2026-10-28), so no notification fires. The webhook secrets now
exist, so either can be flipped to `true` whenever the owner wants the
posts. Unset means skipped; a reusable-workflow caller cannot use
`continue-on-error` to absorb a failure (§2.3).
- [x] Dependabot: npm weekly, grouped dev minor+patch, `github-actions` too —
`.github/dependabot.yml` — and since v1.3.0 `tools/publish/` (the
store-upload tool's own lockfile, §3) as a third ecosystem entry. Both ecosystems have a 7-day `cooldown`
(matching `.npmrc` `min-release-age=7`, `09 §3.1`); WXT is excluded from
the group so every WXT bump arrives alone and gets its built-manifest
diff; majors of the TypeScript pair and `@types/node` are ignored.
- [x] Labels the forms and `triage.yml` apply — `maintenance-mode`,
`needs-triage`, `roadmap` (new with `MAINTENANCE.md`) and `parser`, `i18n`
(named by the parser and translation forms since 2026-08-03, and missing
until 2026-11-18: a form silently drops a label that does not exist).
- [x] Issue templates: `.github/ISSUE_TEMPLATE/` — bug, parser report (requires
a sanitized sample), translation, feature, plus a `config.yml` chooser.
Landed 2026-08-03; `13 §6` had asserted they existed since before launch.
- [ ] ⚠️ GPG signing required for tags (matches tracker-repo practice). The
`v1.0.0` tag object is in fact PGP-signed, so the practice held once.
+295 -57
View File
@@ -1,8 +1,17 @@
# 13 — Release & Store Publishing
Developer account: registered & fee paid ✔.
Chrome Web Store developer account: registered & fee paid ✔. Since v1.3.0
there are two more stores — Firefox Add-ons (§8) and Microsoft Edge Add-ons
(§9) — and §1b is still the procedure for every release; §8 and §9 add what
is different there.
## 1. First-submission runbook (v1.0.0)
## 1. First-submission runbook (v1.0.0) — ✔ completed 2026-07-26
**Historical.** Kept because it is the record of how the listing was created and
what was answered where. For every release after v1.0.0 use §1b instead — the
steps below are all first-listing shaped ("New item", filling the listing and
privacy tabs, setting distribution) and none of them is what a second submission
does.
1. `npm run verify` + full manual QA pass (`11 §5`) on a fresh profile.
2. Tag `v1.0.0` → CI produces the zip artifact (or `npm run zip` locally from
@@ -22,71 +31,153 @@ Developer account: registered & fee paid ✔.
community channels — posted automatically by the `announce` job in
`release.yml`, which calls the ops repo's `announce-release.yml`
(script: `.github/scripts/discord_notify.py`), see `12 §2.3`).
⚠️ **Never recorded as performed.** The approval landed and no result was
written down, so the one check that the *published* artifact matches what was
tested has not demonstrably happened. It is now a standing item in `11 §5`
rather than a one-off step here.
## 2. Asset checklist ⚠️ (create before submission)
## 1b. Update-submission runbook (v1.0.1 and every release after)
This is the procedure for shipping to an **existing** listing. The listing,
privacy and distribution tabs are already filled; you are replacing the package.
1. `npm run verify:full` + the full manual QA pass (`11 §5`) on a fresh profile,
**including the upgrade test over an existing profile** — that is the item
that has no equivalent in a first submission and the one whose failure hits
every installed user simultaneously.
2. Bump the version. Exactly **two** files change:
- `package.json` `version` (semver per `12 §4`);
- `CHANGELOG.md` — a new dated section **and** the link references at the
bottom of the file (`[Unreleased]` must compare against the new tag, and a
new `[X.Y.Z]` line must be added). Forgetting the link refs is the easy
half to miss.
A third when the interface changed, or a new check was run:
- `ACCESSIBILITY.md` — its "Last reviewed" line (date and version) and its
"What has been tested" table, once `11 §5`'s last item has been done.
`wxt.config.ts` declares no `version` key — WXT derives it from
`package.json` (`08 §5`). If it appears in your diff, something is wrong.
3. PR → CI green → merge to `main`. **The bump must be on `main` before the
tag**: `release.yml` reads the built `manifest.json` at the tagged commit and
fails the run when it does not equal the tag minus `v`.
4. ⚠️ Human: `git tag -s vX.Y.Z && git push origin vX.Y.Z`. Signed, per `09 §5`.
`release.yml` re-runs every gate, builds, zips, verifies tag↔manifest, writes
`SHA256SUMS.txt`, and creates the GitHub Release.
5. Download the **Release asset**, not the CI artifact — `SHA256SUMS.txt` covers
the Release assets only (`12 §3`). Verify with `sha256sum -c --ignore-missing
SHA256SUMS.txt` (since v1.3.0 it lists three files; `--ignore-missing` lets
you check only the one you downloaded).
6. Dashboard → the existing item → **Package → Upload new package** → the zip.
Do *not* create a new item.
7. Fill the "why this update" / what-changed note. Listing text and the privacy
answers stay as they are unless something actually changed — and if the
permission list or the data-handling answers did change, that is a
minor-version event which requires re-certifying the Privacy tab first
(`09 §4`, `08 §5`).
8. Consider a staged (percentage) rollout for anything touching the write paths.
There is no undo once a version is live, only a higher version (§7).
9. Submit. Review for a `bookmarks`+`storage`-only item is typically hours–days.
10. After it goes live: confirm the dashboard shows the new version, then
install/update on a clean profile and re-run the upgrade check from step 1
against the *published* build. Record the result in `15`'s progress table.
Chrome auto-updates installed extensions once the new version passes review;
users do nothing and, notably, get no prompt. That is why the upgrade test
matters more than any other single check here.
## 1c. Which file goes where (since v1.3.0)
| Store | Upload | Notes |
|---|---|---|
| Chrome Web Store | `bookmarkmagic-X.Y.Z-chrome.zip` | §1b |
| Microsoft Edge Add-ons | the **same** `…-chrome.zip` | §9 |
| Firefox Add-ons | `bookmarkmagic-X.Y.Z-firefox.zip` **and** `…-sources.zip` | §8 |
A store that re-signs or repackages what it receives (all three do, in some
form) serves users a file whose hash is not the Release asset's. What
`SHA256SUMS.txt` vouches for is that the uploaded file is the Release asset
(`09 §5`).
## 2. Asset checklist ⚠️
### Store assets (submitted — source of truth is the CWS dashboard)
| Asset | Spec |
|---|---|
| Icon | 128×128 PNG (also 16/32/48 in-package). Flat glyph: bookmark + swap arrows, violet `#6d4aff` on transparent. |
| Screenshots ×5 | 1280×800 PNG, real UI, EN locale, light theme: 1) Import preview+stats 2) Merge options+progress 3) Export format cards 4) Edit tree + duplicate panel 5) Dark theme overview |
| Small promo tile | 440×280 (required) |
| Marquee (optional) | 1400×560 — skip for v1.0 |
| Icon | 128×128 PNG (also 16/32/48 in-package). Flat glyph: bookmark + swap arrows, violet `#6d4aff` on transparent. Generated by `scripts/gen-icons.mjs`, which is the source of truth (`00 §10.3`). |
| Screenshots | 1280×800 PNG, real UI, EN locale. Since v1.1.0 generated, not hand-made: `npm run build && node scripts/screenshots.mjs --shoot` writes the store set — `#import`, `#edit`, `#export` — to `store/screenshots/`. |
| Small promo tile | 440×280 (required by the dashboard) |
| Marquee (optional) | 1400×560 — skipped |
**Screenshots come from the harness** (`scripts/screenshots.mjs`, `11 §5`). It
photographs the built extension over a fake `chrome` with neutral sample
bookmarks, so no real profile can appear in a store image, and one command
reproduces the set after any UI change (`08 §8`). Each route is captured as it
first renders — the import shot is the drop zone (no file is loaded), the edit
shot the tree with the duplicate panel closed. That is narrower than the five
subjects first planned (import preview + stats, Merge options + progress,
export format cards, edit tree + duplicate panel, dark overview); a preview, a
running import or an open panel still needs a hand-staged capture.
⚠️ Human, with the v1.1.0 submission: the redesign changed every surface, so
images of the 1.0 UI no longer show the product (`08 §6`). Upload the
regenerated set in the dashboard alongside the package (§1b step 6).
⚠️ **The submitted v1.0 assets are unreconciled.** The listing is live, so the
dashboard has whatever was actually uploaded — but the repo does not, and
nothing records where those originals live. The screenshots are now
reproducible; the 440×280 promo tile still is not — nothing generates it.
Owner: record where the submitted assets live, or correct this table to match
what the dashboard really required.
### README screenshots (not store assets — do not confuse them)
`capture/` holds the README set — `import`, `export`, `edit`, `settings`,
`about` (light, English, 1280×800) and `popup` (360×420) — regenerated for
1.1.0 by `node scripts/screenshots.mjs --shoot` from neutral sample data. The
1.0.0 shots (2512×1440, a real profile) are gone. `store/screenshots/` holds
the dark 1280×800 store candidates (`edit`, `export`, `import`); which of them
to upload, alongside or instead of what the listing has now, is the owner's
call (⚠️ `13 §1b`).
## 3. Store listing — EN (canonical)
**Name:** `BookmarkMagic` ✔ (final — `00 §9`)
**The listing copy lives in `store/listing.*.md`** — one file per locale
(`en`, `vi`, `ja`, `zh_CN`, `ro`, named by Chrome's locale code) — name, summary,
description, category and the privacy-policy URL, exactly as pasted into the
dashboard. This section used to carry a second copy of the English text, and
for v1.1.0 the two had already diverged (the store files gained the Chrome and
Firefox imports, Merge reuse, the Replace confirmation and Sort A→Z; the copy
here still described v1.0). A copy in two places is a copy that drifts.
**Summary (≤132 chars):**
`Import, export & edit bookmarks between browsers — offline, no account, no cloud. Your data never leaves your device.`
**Description:**
```
Move your bookmarks between browsers the simple way: with a file. No account.
No cloud sync. 100% offline.
WHAT IT DOES
• Import bookmark files (HTML, JSON, CSV) with a full preview before anything
is written — see counts, folders, and duplicates first.
• Choose how to import: into a new dated folder (safe default), merge into
your existing folders, or replace everything (with an automatic safety
backup downloaded first).
• Skip duplicates automatically.
• Export everything — or just the folders you pick — to HTML (works with
Chrome, Edge, Brave, Firefox, Safari, Vivaldi, Opera), JSON, CSV, or
Markdown.
• Edit your bookmark tree: search, rename, drag & drop, create folders,
delete, and find duplicate links.
PRIVACY BY DESIGN
• Works entirely on your device. No servers, no analytics, no tracking.
• Only two permissions: "bookmarks" (the whole point) and "storage" (your
settings). Nothing else.
• Free & open source (GPL-3.0) — read the code on GitHub.
LANGUAGES
English · Tiếng Việt · 日本語
LIMITATIONS (HONESTY CORNER)
• Favicons can't be imported — the extensions API for bookmarks has no
favicon field.
• Imported bookmarks get today's date — Chrome doesn't let extensions set a
bookmark's original creation date. Your exported files keep the real dates.
• CSV is a flattened view: empty folders and "which folder is the toolbar"
aren't preserved. Use HTML or JSON for a faithful backup.
Source code, issue tracker & privacy policy:
https://github.com/poli0981/bookmarkmagic
```
**Category:** Productivity → Tools · **Language:** English + VI/JA localized.
When the description changes: edit every `store/listing.*.md` in the same
pull request as the feature, keep claims to what the CHANGELOG says shipped,
and paste them into the dashboard as part of `§1b`. The summary must stay ≤132
characters in every language.
## 4. Localized listing snippets
**VI summary:** `Nhập, xuất & chỉnh sửa bookmark giữa các trình duyệt — offline, không tài khoản, không cloud. Dữ liệu không rời khỏi máy bạn.`
**JA summary:** `ブラウザ間でブックマークをインポート・エクスポート・編集。オフライン、アカウント不要、クラウド不要。データは端末から出ません。`
(Full VI/JA descriptions: translate §3 keeping structure; store in
`store/listing.{vi,ja}.md` in-repo so listing text is version-controlled ⚠️.)
**ZH-CN summary:** `在浏览器之间导入、导出和编辑书签——离线运行,无需账户,无需云端。您的数据绝不会离开您的设备。`
**RO summary:** `Import, export și editare de marcaje între browsere — offline, fără cont, fără cloud. Datele nu vă părăsesc dispozitivul.`
Full descriptions: translate `store/listing.en.md` keeping its structure. The
canonical copy lives in `store/listing.*.md` so listing text is
version-controlled and reviewable — a listing edit made straight into the
dashboard has no diff and no history.
**Adding a listing language** (v1.2.0 did two): in the dashboard, Store listing
→ the language selector → add the language, then paste name, summary and
description from its file. The "Languages" line in the public listing is not
typed by anyone — CWS derives it from the package's `_locales/`, so it changes
only when the new package is live. The `LANGUAGES` paragraph inside every
description *is* typed, so a new locale means re-pasting the description of
every existing language too.
⚠️ Those files were written from §3 **after** the listing went live, so they are
a reconstruction, not a transcript. Owner: diff them against what the dashboard
actually shows and correct the files, not the dashboard.
## 5. Update cadence & versioning
@@ -103,7 +194,154 @@ https://github.com/poli0981/bookmarkmagic
## 6. Post-launch monitoring (no telemetry ⇒ these channels only)
- CWS dashboard: user counts, ratings, review replies (reply within a week;
link issues to GitHub).
- GitHub issues — templates route bug reports with sample files.
link issues to GitHub). A store review is not a bug report — if it describes a
reproducible defect, open the GitHub issue yourself and reply with the link.
- GitHub issues — `.github/ISSUE_TEMPLATE/` routes them. `parser_report.yml`
requires a sanitized sample (`scripts/sanitize-bookmarks.mjs`) plus explicit
consent to commit it as a GPL-3.0 fixture, because that is what turns a report
into a regression test (`11 §2`, `15 §v1.0.x`).
- Accessibility reports — their own form (`accessibility.yml`, label
`accessibility`) and `accessibility@poli0981.dev` for people without a
GitHub account. `ACCESSIBILITY.md` promises an acknowledgement within about
a week and a patch for a blocking barrier (`15`, release trigger); a report
that is not fixed at once goes into its Known limitations.
- Discord servers (`#support` in the OSS server) — pin an FAQ post.
- Review flow for feature requests: label → roadmap doc PR → milestone.
⚠️ The invite URL is not recorded anywhere in the repo.
- Feature requests, in maintenance mode (`/MAINTENANCE.md`): `triage.yml`
closes a request for something new and labels the two in-policy answers
`needs-triage` (`12 §2.6`). Read every `needs-triage` issue and every closed
one; one that fits goes into `15` by pull request and gets the `roadmap`
label, which the automation leaves alone. Ideas live in Discussions › Ideas.
The three recurring questions are already answered in prose and make the FAQ
seed: favicons cannot be imported; imported bookmarks carry today's date (the
import report now says so itself); CSV is a flattened view. See §3's honesty
corner and README's "Honest limitations".
## 7. When something goes wrong after launch
None of this existed before v1.0.0 was live, and all of it is now reachable.
### An update is rejected
**The published version stays live.** An update rejection is not a takedown —
users keep running the previous version, so nothing is on fire and there is time
to read carefully.
1. Read the exact policy citation. Never argue past it (same rule as §1 step 7).
2. Fix, and bump the patch **again**. The store refuses a version string it has
already seen, so a rejected 1.0.1 comes back as 1.0.2 — not as a re-upload.
3. Never delete or move the tag of a rejected version. It is a real, published
GitHub Release and moving it invalidates its checksum. Leave it and move on.
The one exception is a tag whose run failed **before** any Release existed —
nothing was published, so fix the workflow on `main` and re-point the tag,
as `v1.1.0` was (`15` decision log, 2026-10-29).
4. Note the rejection and its resolution in `15`'s decision log — it is the only
memory the project has of what the reviewers actually object to.
### Rollback
There is no "revert to the previous version" in the Chrome Web Store. The only
rollback is **forward**: ship a higher version containing the revert. Plan
accordingly — a bad release cannot be recalled, only superseded, and the
superseding version has to pass review too.
### Takedown / unpublish / appeal
- **Unpublished** (by you or by Google): the listing disappears from search and
no one can install it. **Existing users keep the version they have** and it
keeps working; it simply stops receiving updates. GitHub Releases become the
only distribution channel, and the README install section should say so.
- Appeal through the developer support form, citing the specific policy. Attach
the permission justifications from `08 §5` — a `bookmarks`+`storage`-only,
zero-network extension has an unusually short defence to make, and `09`'s
threat model exists partly to make it.
- If a takedown is about data handling, `legal/PRIVACY.md` and the privacy-tab
answers must agree with the code exactly. `npm run guard` and
`npm run check:manifest` are the evidence that they do.
### A store job failed after the Release was published (since v1.3.0)
Re-run **only the failed job** from the run page. Every store refuses a
version number it has already accepted, so re-running the whole workflow would
turn the stores that succeeded red; and nothing before the store jobs needs
redoing — the Release and its checksums are already published. The usual
causes: an expired Edge API key (72 days, `12 §3`), a review hold, a token
revoked in a store dashboard.
### A tag was pushed and the release run failed
`release.yml` runs `gh release create` with no existence check, so a failure
*after* that step (realistically the CWS publish step, once `CWS_AUTOPUBLISH` is
on) leaves a published Release that a re-run cannot recreate.
- If the Release and its two assets published correctly, the failure is
downstream — fix it and do the affected step by hand. Do **not** re-run the
workflow.
- If the Release is broken or incomplete: `gh release delete vX.Y.Z`, then
`git push --delete origin vX.Y.Z`, then re-tag. Only safe while nothing has
consumed the assets.
- Never move a tag that has already been announced or submitted.
## 8. Firefox Add-ons (AMO) — runbook (since v1.3.0)
**First version — by hand, once** (the API and `publish-browser-extension`
can only add versions to an add-on that exists):
1. The `11 §5` pass on a **real Firefox** (140 or later): about:debugging →
This Firefox → Load Temporary Add-on → `.output/firefox-mv3/manifest.json`
(or the Release's `…-firefox.zip`). Its Firefox section covers the
Bookmarks Menu, separators and Alt+↑/↓.
2. addons.mozilla.org/developers → **Submit a New Add-on** → *On this site*
(listed) → upload `bookmarkmagic-X.Y.Z-firefox.zip` from the Release.
3. **Compatibility: Firefox only** — untick Firefox for Android (no
`bookmarks` API there, `08 §9`).
4. **Source code: yes** → upload `bookmarkmagic-X.Y.Z-sources.zip` from the same
Release. In *Notes to reviewer* paste the short version of `/BUILD.md`:
Node.js 26 and npm 11 (the sources archive drops `.nvmrc`), `npm ci`,
`npm run zip:firefox`, the package lands in `.output/`. Reviewers diff their
build against the upload, file by file.
Checked 2026-11-18: the sources archive, unpacked into an empty folder,
`npm ci --ignore-scripts`, `wxt prepare`, `npm run build:firefox`, rebuilt
every one of the package's 19 files byte for byte.
5. Listing: from `store/listing.<lang>.md`'s **AMO** block — name, summary
(≤ 250 characters), description, category *Bookmarks*, licence *GNU General
Public License v3.0* (the code is GPL-3.0-or-later), privacy policy
`https://github.com/poli0981/bookmarkmagic/blob/main/legal/PRIVACY.md`,
homepage the repository, support site the repository's issues. No support
email (`09 §6`).
6. Submit, and record the review's outcome in `15`. The add-on's page is
`https://addons.mozilla.org/firefox/addon/bookmarkmagic@poli0981.dev/`
(AMO resolves the gecko id; the slug it picks works too).
**Later versions:** by hand, the same way (*Upload New Version*), or
automatically from `release.yml`'s `store-firefox` job once
`firefox-add-ons` has its secrets and `AMO_AUTOPUBLISH` is `true`
(`12 §3`) — the job uploads the package and the sources together.
**Rollback:** AMO can disable a version in the Developer Hub, which sends
users back to the previous approved one — a recall Chrome does not offer.
Still ship the fix forward.
## 9. Microsoft Edge Add-ons — runbook (since v1.3.0)
**First submission — by hand, once:**
1. A Partner Center developer account (no fee) — ⚠️ owner.
2. The `11 §5` pass on a real **Edge**, including a profile **signed in with
sync on** — the case `08 §10` could not verify (`NO_WRITABLE_ROOTS` if
Edge marks syncing roots).
3. Partner Center → Edge → **Create new extension** → upload the Release's
`bookmarkmagic-X.Y.Z-chrome.zip` — the Chrome package, unchanged.
4. Listing from `store/listing.<lang>.md`'s **Edge** block (it avoids selling
the extension as a Chrome one, `08 §10`); category *Productivity*; privacy
answers as `08 §5`; privacy policy URL as above; screenshots from
`store/screenshots/`.
5. Submit; record the outcome in `15`. Note the **Product ID** on the
extension's overview page — `EDGE_PRODUCT_ID` — and the listing URL, which
the About link and the README can then use (`06 §3.5`).
**Later versions:** by hand (*Update* → upload the new package), or from
`release.yml`'s `store-edge` job once `edge-add-ons` has its secrets and
`EDGE_AUTOPUBLISH` is `true`. The API key expires every **72 days**; put the
renewal in a calendar.
+70 -74
View File
@@ -15,7 +15,7 @@ the user accepts, once, with links to canonical documents on GitHub.
`<LegalGate>` overlay.
- **Blocks:** `#import`, `#export`, `#edit`. **`#settings` and `#about` stay
reachable** — `#about` so users can read the linked documents before
accepting, `#settings` so a VI/JA user can switch language and theme first
accepting, `#settings` so a non-English user can switch language and theme first
(which is why `<LegalGate>` needs no language switcher of its own). Popup is
never blocked (it only launches the Manager). Same list in `03 §4` and the
`11 §5` QA checklist.
@@ -38,89 +38,75 @@ Storage keys are namespaced `legal.*` / `settings.*` (single
## 3. Repo `legal/` files (English canonical)
Linked from the gate, About tab, README, and the CWS privacy-policy URL.
Drafts below are ready to commit ⚠️ — fill placeholders, have a final human
read-through (docs are provided as-is, not legal advice).
Filenames follow the portfolio precedent: `legal/PRIVACY.md`,
`legal/DISCLAIMER.md`, `legal/EULA.md`, `legal/THIRD_PARTY_NOTICES.md` (the
notices file lives in `legal/`, not the repo root).
### 3.1 `legal/PRIVACY.md` (draft)
**The committed files are the canonical text — read them, not a copy here.**
This section used to embed drafts carrying `Last updated: 2026-⚠️` and
`⚠️ contact email` placeholders. Those were filled in Phase 0 and Phase 4, and
real users have now accepted the published wording in-product; a spec still
showing the unfilled draft was describing a document nobody has ever agreed to.
```markdown
# Privacy Policy — BookmarkMagic
Last updated: 2026-⚠️
### 3.1 Changing a legal document after launch
BookmarkMagic ("the Extension") is designed to work entirely on your
device.
The gate reappears for **every installed user** when `LEGAL_VERSION`
(`src/lib/core/limits.ts`) increases. That is the mechanism working correctly,
and it is also the most disruptive thing this project can do to its users
without shipping a bug. So the bump is a decision, never a side effect:
## What we collect
Nothing. The Extension has no servers, performs no network requests, and
contains no analytics, telemetry, or crash reporting.
| Change | Bump? |
|---|---|
| A new obligation, permission, or data flow — anything a user could reasonably object to | **Yes.** Bump, and say so in the CHANGELOG, so the reappearing gate is explicable rather than alarming. |
| Wording that narrows or clarifies something already true | No. Record the reasoning in the `15` decision log so the judgement stays auditable. |
| Typos, formatting, dead links | No. |
| Contact details — a new address, a different alias for a purpose | No. It changes how to reach us, not what anyone agreed to. Log it in `15`. |
## What the Extension accesses, and why
- Bookmarks (permission: "bookmarks"): read to display/export your bookmark
tree; written when you import or edit. This data never leaves your device.
- Local settings (permission: "storage"): your language, theme, preferences,
and the date you accepted these terms are stored locally via
chrome.storage.local. They are not transmitted anywhere and are removed by
Chrome when you uninstall the Extension.
Procedure for a bump: edit `legal/*.md` → bump `LEGAL_VERSION` → update the CWS
Privacy tab if the privacy text changed at all (`08 §5`, `09 §4`; a privacy-tab
change is a **minor**-version event per `12 §4`) → add a `15` decision-log row →
confirm with the `11 §5` upgrade item that the gate does reappear and that
settings and bookmarks survive it.
## Files you import or export
Files are read and generated locally in your browser. They are never
uploaded. Exported files are saved through your browser's normal download
mechanism to a location you control.
**Precedent (2026-08-03):** `legal/PRIVACY.md` gained an "If you contact us"
paragraph — do not send your real bookmarks file, sanitize it first, GitHub
attachments are public, emailed material is deleted once the issue is fixed.
Deliberately **not** a bump: it describes what happens to data a user chooses to
send us, which was never inside "what the Extension collects", and re-gating
every installed user over a clarification is the worse of the two outcomes.
## Third parties
No data is shared with anyone, because no data is collected.
**Precedent (2026-10-29, v1.1.0):** all four documents gained a version/date
header ("Terms version 1 · Effective 2026-07-26 · Last updated …"), a copyright
line, and per-purpose contact aliases (`legal@`, `dmca@`, `privacy@`,
`takedown@`, `copyright@`; `contact@` retired). EULA clause 3 — worded as an
obligation, which a GPL program cannot impose (§10) — became a note.
DISCLAIMER now describes Replace as it really behaves (confirmation with exact
counts, refusal when no restorable backup is possible). PRIVACY now describes
the in-memory diagnostics log, the Chrome Web Store's own role, what happens
when a user opens a bookmark (the browser's request, not the Extension's), and
what the build compiles in. THIRD_PARTY_NOTICES now lists the Svelte runtime,
its `clsx` helper and WXT's browser shim, which the build always compiled in. **Not a bump:**
every change clarifies or corrects a description of what was already true, or
removes an obligation; none adds one or a data flow.
## Changes
Material changes will be published here and re-acceptance will be requested
inside the Extension.
**Precedent (2026-11-18, v1.3.0):** Firefox Add-ons and Microsoft Edge Add-ons
become distribution channels. EULA clause 5 says updates come "through the
store you installed the Extension from"; PRIVACY names all three stores and
Firefox's data-consent declaration ("none"), and calls the settings store by
both browsers' names; DISCLAIMER's note on dates no longer blames Chrome alone,
and the non-affiliation line adds Microsoft and Edge. THIRD_PARTY_NOTICES (same
day, Phase 10) corrected its description of the build tooling's licences.
**Not a bump:** a new channel to receive the same software is not a new data
flow from the Extension, and nothing asks more of the user.
## Contact
⚠️ contact email / GitHub issues link
```
**What each `LEGAL_VERSION` means** — the text a user who accepted that number
agreed to:
### 3.2 `legal/DISCLAIMER.md` (draft)
| `LEGAL_VERSION` | Accepted text | Notes |
|---|---|---|
| 1 | The four `legal/` files as published 2026-07-26, with the clarifications of 2026-08-03, 2026-10-29 and 2026-11-18 | The clarifications are listed above; git history has each wording |
```markdown
# Disclaimer — BookmarkMagic
- Provided "AS IS", without warranty of any kind (see LICENSE §15–16).
- Bookmark operations modify your browser's bookmark data. The "Replace
everything" mode DELETES all existing bookmarks after downloading an
automatic safety backup. You are responsible for keeping backups of data
you care about.
- Import files come from outside this Extension; verify you trust their
source. Bookmarked URLs are stored as-is and are not vetted by the
Extension.
- This project is not affiliated with or endorsed by Google, Chrome, or any
browser vendor. Browser names are trademarks of their respective owners.
```
### 3.3 `legal/EULA.md` (draft)
```markdown
# End User License Agreement — BookmarkMagic
1. License. The software is free software licensed under the GNU General
Public License v3.0 (see LICENSE). You may use, study, share, and modify
it under those terms. This EULA adds no restrictions beyond the GPL; if
anything here conflicts with the GPL, the GPL prevails.
2. No warranty; limitation of liability. As stated in GPL-3.0 §15 and §16,
the software is provided without warranty, and authors are not liable for
damages, including loss of bookmark data.
3. Acceptable use. You agree not to use the software to violate applicable
law or third-party rights.
4. Your data. The software processes bookmark data locally on your device
only (see PRIVACY.md).
5. Updates. Updates are delivered via the Chrome Web Store and may change
functionality. Material legal changes trigger re-acceptance in-app.
```
### 3.4 `LICENSE`
### 3.2 `LICENSE`
Full GPL-3.0 text at **repo root** (already committed). Variant resolved:
**`GPL-3.0-or-later`**, matching `poli0981/switch-every-tab-hotkey`. Set the
@@ -131,15 +117,25 @@ same value in `package.json#license` (`01 §5`).
| Surface | Shows |
|---|---|
| First-run gate | Summary + 4 links + accept |
| About tab | 4 links + accepted date/version + "Third-party dependencies: None" |
| About tab | 4 links + accepted date/version + "Third-party code" (the Svelte runtime with clsx, and WXT's browser shim — MIT, as compiled in) + Copy diagnostics |
| Store listing | GitHub link; privacy-policy URL in Privacy tab |
| README | License badge, links to `legal/` |
## 5. Third-party & donations note
- v1 ships **zero runtime dependencies** → About states "None". If `fflate`
lands in v1.1, About must render its name + MIT license text (add
`THIRD_PARTY_NOTICES.md` generated at build time — keep the rule ready).
- **Zero runtime dependencies are installed**, but the build compiles a few
MIT-licensed pieces into the package: the Svelte runtime, `clsx` (which the
Svelte runtime imports) and WXT's one-line `browser` shim (`wxt` +
`@wxt-dev/browser`). `wxt.config.ts` fails the build when any other package
would ship (`CREDITED_PACKAGES` — since 2026-11-18 in
`scripts/credited-packages.mjs`, the one list the build gate, the notices
test and the licence gate of `09 §3.2` all read). Through v1.0.x the About tab said "None"
and THIRD_PARTY_NOTICES said "no third-party code" — both wrong, corrected in
v1.1.0. The notices ship as `THIRD_PARTY_NOTICES.txt` (from `src/public/`),
which `check:manifest` requires in every build; `legal/THIRD_PARTY_NOTICES.md`
is the same list for readers of the repository. A new runtime dependency
(`fflate`, if ever) adds its name and license text to both files in the same
pull request, and the About tab names it.
- Donate links live in About + README only — outbound links are fine on CWS;
no payment functionality inside the extension. Handles are resolved (from the
portfolio's `.github/FUNDING.yml`, which this repo copies verbatim):
+354 -27
View File
@@ -1,10 +1,16 @@
# 15 — Roadmap
## v1.0 — MVP (store launch) — target: ~1–2 week build
> **Maintenance mode since 2026-11-18.** What the project still takes, and how
> requests outside that are handled, is [`/MAINTENANCE.md`](../MAINTENANCE.md) —
> the policy, not restated here. Every feature that can still land is on this
> page; anything not on it needs a decision-log row first.
Everything in `00_PROJECT_OVERVIEW.md §6`. Definition of done =
## v1.0 — MVP (store launch) — ✔ SHIPPED
Everything in `00_PROJECT_OVERVIEW.md §6`. Definition of done was
`CLAUDE.md` Phase 5 exit criteria + manual QA checklist green + store
approval.
approval — **all three met; published by 2026-08-03.** This section is now a
record rather than a plan.
Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
@@ -16,43 +22,249 @@ Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
| 1 — Core library | ✔ 2026-07-25 | 3 parsers, 4 serializers, dedupe/diff/plan; 600 seeded round-trips |
| 2 — Browser layer + #import | ✔ 2026-07-25 | adapter, write queue, stores, full import flow incl. forced backup |
| 3 — #export + #edit | ✔ 2026-07-25 | tri-state picker, tree CRUD, search, duplicates, DnD + keyboard parity |
| 4 — i18n, theming, Settings, About, Legal Gate | next | dictionaries already exist in EN/VI/JA; the switcher UI does not |
| 5 — Hardening + release prep | pending | CI stubs per `12 §2`, CHANGELOG, README, full QA, `wxt zip` clean install |
| 4 — i18n, theming, Settings, About, Legal Gate | ✔ 2026-07-26 | switcher + theme controls, six-row `#settings`, `#about`, first-run gate; Intl retrofit; store-backed Toast |
| 5 — Hardening + release prep | ✔ 2026-07-26 | contrast tokens + a test that enforces them, `EditTab` split under the hard limit, CHANGELOG + README, four CI callers, T1–T8 pass, clean-room `wxt zip` |
| **v1.0.0 released** | ✔ 2026-07-26 | signed tag, GitHub Release with a `sha256sum -c`-verified zip, submitted to the Chrome Web Store |
| **v1.0.0 published** | ✔ by 2026-08-03 | approved by CWS review with no rejection recorded; listing public, item id `eghnciphhegekmnofffpgbdfefckdhmg`, **real users installed** |
| 6 — Post-launch stabilization | ✔ 2026-08-03 | doc reconciliation, user-intake machinery, the defects below, dependency bumps → v1.0.1 |
| **v1.0.1 released** | ✔ 2026-08-03 | signed tag on `4654086`, GitHub Release with a `sha256sum -c`-verified zip; shipped manifest `1.0.1`, permissions unchanged. `announce` skipped (no `DISCORD_ANNOUNCE`), store publish skipped (no `CWS_AUTOPUBLISH`) |
| **v1.0.1 submitted** | ✔ 2026-08-03 | uploaded to the CWS dashboard by hand (`13 §1b` step 6) |
| **v1.0.1 published** | ✔ observed 2026-10-28 | listing shows version 1.0.1 (`Updated: August 3, 2026`), 5 users. ⚠️ Exact approval date not recorded; `13 §1b` step 10 (clean-profile install of the published build + upgrade re-check) has no recorded result |
| 7 — v1.1.0 | ✔ 2026-10-29 | PR-A toolchain/CI/Sonar (#26); PR-B import redesign, Chrome/Firefox formats, Merge reuse, Edit store + Sort A→Z + reorder, technical UI, diagnostics, docs/legal (#27); the second review's fixes, which missed the #27 merge (#28); the release workflow's artifact fix (#29) |
| **v1.1.0 released** | ✔ 2026-10-29 | signed tag on `9040f84`, GitHub Release with a `sha256sum -c`-verified zip (`104f020c…2dd6c94`, 94 091 bytes). Its manifest differs from 1.0.1's only in `version`, `minimum_chrome_version` (120 → 136) and the new CSP; permissions unchanged. The first tag run failed before publishing anything (`12 §2.3`); fixed in #29 and the tag moved while no Release existed. `announce` and store publish skipped (variables unset) |
| **v1.1.0 submitted** | ✔ by 2026-11-06 | uploaded to the CWS dashboard by hand (`13 §1b` step 6) |
| **v1.1.0 published** | ✔ observed 2026-11-06 | owner reported the review passed; the listing shows version 1.1.0 (`Updated: October 29, 2026`), 6 users, "3 languages". ⚠️ As for 1.0.1, `13 §1b` step 10 (clean-profile install of the published build + upgrade re-check) has no recorded result |
| 8 — v1.2.0 languages | ✔ 2026-11-06 | Simplified Chinese (`zh-CN`) and Romanian (`ro`): one `LOCALES` list, a third plural form for Romanian, manifest `_locales`, store listings, intake form (`07`). One PR (#33); a code review and a native-style translation review before the bump, every finding fixed — the worst a Romanian CSV note saying the bookmarks-bar folder itself is lost on export |
| **v1.2.0 released** | ✔ 2026-11-06 | signed tag on `e2f36bc`, GitHub Release with a `sha256sum -c`-verified zip (`0b4a268c…f8617b`, 105 284 bytes). Its manifest differs from 1.1.0's only in `version`; the package gains `_locales/zh_CN` and `_locales/ro`. `announce` and store publish skipped (variables unset) |
| **v1.2.0 submitted** | ✔ by 2026-11-07 | uploaded to the CWS dashboard by hand, with the 简体中文 and Română listing languages (`13 §1b` step 6, `13 §4`) |
| **v1.2.0 published** | ✔ observed 2026-11-10 | the listing shows version 1.2.0 (`Updated: November 7, 2026`), 3 users, "5 languages" — English, Tiếng Việt, română, 中文(中国), 日本語. ⚠️ As for 1.0.1 and 1.1.0, `13 §1b` step 10 (clean-profile install of the published build + upgrade re-check) has no recorded result |
| 9 — v1.2.1 accessibility | ✔ 2026-11-10 | `ACCESSIBILITY.md` and its intake (issue form, PR checklist, `accessibility@`); the defects an audit of `src/` found that a keyboard-and-Narrator pass had not — an invisible focus ring on the theme control, no forced-colours support, drag-only reordering (Alt+↑/↓), focus dropped on `<body>` in three places, targets under 24 px; dependency sync after Dependabot #31/#32/#35/#36 (`06 §5`) |
| **v1.2.1 released** | ✔ 2026-11-10 | PR #37, merged at the head that was reviewed. Signed tag on `d61318a`, GitHub Release with a `sha256sum -c`-verified zip (`4975b5df…ca13254`, 106 290 bytes). Its manifest differs from 1.2.0's only in `version`, and the file inventory is the same. SonarCloud's new-code gate failed the first push at 73.6 % — the live-sync wiring moved out of `EditTab` had no test — and passed once it had one. `announce` and store publish skipped (variables unset) |
| **v1.2.1 submitted** | ⚠️ pending — or skipped | owner: the `11 §5` pass incl. the **1.2.0 → 1.2.1 upgrade over an existing profile**, a Windows contrast theme and a screen-reader pass over Alt+↑/↓, then the zip upload (`13 §1b`). 1.3.0 contains all of 1.2.1, so uploading 1.3.0 instead is the shorter path (`00 §10` item 20) |
| 10 — maintenance mode, Firefox + Edge | ✔ 2026-11-18 | PR #42: Dependabot #39–#41 and their hand sync, the unfixable `picomatch` advisory recorded, a lockfile licence gate, `MAINTENANCE.md` with a feature form that classifies and `triage.yml` that closes out-of-policy requests, Qodana (`qodana-js`) beside SonarCloud — 27 first-run findings, none a defect. PR #44: Firefox and Edge Add-ons — Firefox's roots by GUID and the Bookmarks Menu as a fourth root, separators recognised by type, each browser's move index, Firefox's address limit, a second (Firefox) package with its own manifest gate, three store jobs in their own environments (CWS API v2), `BUILD.md` (the sources archive rebuilt the package byte for byte) |
**Verified on real browsers 2026-07-25:** Chrome and Brave, unpacked build.
Until that point every phase had been tested only against a hand-rolled
`chrome.bookmarks` mock, because WXT's `fakeBrowser` stubs that API with
"not implemented" throws (`11 §4`).
Each of phases 1–3 was adversarially reviewed after implementation and each
review found real defects (7, 13 and 14 respectively) — several in the paths
that delete bookmarks. Budget that review into the remaining phases; a green
test run has not once meant "done" on this project.
**Phase 4 verified on a real browser 2026-07-26**, after the review fixes
landed. Covered: the Legal Gate (appears once, blocks the three routes, leaves
`#settings`/`#about` reachable pre-accept, re-renders in the language chosen
before accepting, and persists across a restart); EN→VI→JA live switching with
localized numbers and dates, and the header and `#settings` controls staying in
agreement; theme system/light/dark; settings surviving an immediate tab close —
the path the `$state`-proxy `DataCloneError` would have broken; and the Phase
2–3 import/export/edit flows still working after Phase 4 touched their tabs and
the settings store.
## v1.0.x — stabilization
Every phase was adversarially reviewed after implementation and **every review
found real defects** — 7, 13 and 14 in phases 1–3, 19-of-33-filed in phase 4,
8-of-20 in phase 5 — several in the paths that delete bookmarks. Budget that
review into any future work; a green test run has not once meant "done" on this
project.
- Parser-tolerance fixes from real user files (fixture + test per report).
- Translation polish (JA review pass).
- Listing copy tweaks from early reviews.
Phase 5's own lesson is worth keeping: its three worst findings were defects in
work added **earlier in the same branch** — a release workflow that would have
failed on the first tag, a contrast test blind to its own bypass (`opacity` on
text, which a token-level check cannot see), and a README claiming a test
asserted the *built* manifest when it only read the config source. Review new
work as hard as old work.
And three defects reached `main` that no automated gate could ever have caught,
all found by a human looking at the running extension or at a real CI run: the
footer's missing space, a moon glyph that renders as a capital "C", and a
reusable-workflow permission grant that produced a `startup_failure` with no
jobs and no log.
Phase 4's own review filed 33 findings across six lenses; 19 survived
adversarial verification. The most serious was a first-run dead-end: the gate
rendered only on the three routes it blocked, and those three tabs were the
only in-app navigation to them — so a user who reached `#settings` (via the
popup's new gear, which opens a fresh tab with no history) could never get
back to the accept UI.
Phase 4 also found three latent defects in code that 338 green tests had
already signed off, all unreachable until Phase 4 gave them a caller:
`writeSettings` handed a `$state` proxy to `chrome.storage.local.set` (would
throw `DataCloneError` in a real browser — `fakeBrowser` stores the reference
without cloning, so the suite could not see it); `updateSettings` replaced the
settings object rather than mutating it, which would strand any component that
captured it; and footer navigation during `attesting` stranded the import's
attestation resolver, deadlocking it until reload.
## v1.0.x — stabilization (**the live workstream since 2026-08-03**)
This was speculative when written. It is now the actual next work, because real
users and a public listing exist.
### Intake — how a report becomes a fix
There is exactly one path, and every step has an owner in the repo:
1. A user files `.github/ISSUE_TEMPLATE/parser_report.yml`, which **requires** a
sanitized sample (`scripts/sanitize-bookmarks.mjs`) and an explicit consent
checkbox that the sample may be committed as a GPL-3.0 test fixture.
2. The sample lands in `tests/fixtures/`. Note `.gitattributes` sets
`tests/fixtures/** -text`, so EOL normalization cannot destroy the CRLF/BOM
bytes the bug may depend on.
3. A regression test lands in `tests/unit/core/fixtures.test.ts` — the only
parser regression suite — **in the same PR** as the parser fix (`11 §2`). The
sanitizer suite (`tests/unit/scripts/sanitize-bookmarks.test.ts`) also walks
every fixture automatically, so the new file is covered there too.
4. The quirk is noted in the parser source and in `04 §1.2` (`CLAUDE.md`
working style makes this mandatory, not optional).
5. `11 §2`'s inventory and `CHANGELOG.md [Unreleased]` are updated.
Translation fixes use `.github/ISSUE_TEMPLATE/translation.yml` and follow
`07 §4`. The native review passes are the outstanding ones, and all of them are
user-facing: JA (`TODO(review-ja)`) since launch, and ZH-CN and RO
(`TODO(review-zh)`, `TODO(review-ro)`) since v1.2.0.
### Release trigger
Cut a patch when **any** of these is true, rather than on a schedule:
- a parser-tolerance fix exists (a user is currently unable to import a file);
- a data-integrity or dead-end defect is fixed;
- an accessibility barrier is fixed — something a keyboard, screen-reader or
contrast-theme user could not do or could not perceive (`ACCESSIBILITY.md`
promises exactly this);
- a batch of translation fixes has accumulated;
- a dependency fix is needed for a real advisory.
Listing copy tweaks alone do **not** need a patch — the store listing is edited
independently of the package (`13 §5`), though the copy should still go through
`store/listing.*.md` first so it is reviewable. A **new** UI language is not a
patch: it is a minor (`12 §4`).
## v1.1 — quality of life
| Feature | Notes |
|---|---|
| Automated CWS publishing | Flip `CWS_AUTOPUBLISH=true`; `wxt submit` in release workflow (`12 §3`). |
| Import Chrome's internal `Bookmarks` JSON file | New parser (`roots.bookmark_bar/other/synced` shape); users often have this file from profile backups. |
| Import Firefox `.json` backup | GUID/typeCode schema → BookmarkNode mapping. |
| "Export all formats as .zip" | First runtime dep decision: `fflate` (gated, `01 §4`; About/THIRD_PARTY updates per `14 §5`). |
| ✔ Import Chrome's internal `Bookmarks` JSON file | **Shipped in v1.1.0** (`04 §2a`). |
| ✔ Import Firefox `.json` backup | **Shipped in v1.1.0** (`04 §2b`). The compressed automatic backups (`.jsonlz4`) are a separate item: a ~80-line pure-TS LZ4 block decoder, no dependency. |
| "Export all formats as .zip" | First runtime dep decision: `fflate` (gated, `01 §4`; About/THIRD_PARTY updates per `14 §5`). **Not planned in maintenance mode** (2026-11-18): it would end "zero runtime dependencies" for a convenience. |
| Aggressive-dedupe toggle | Optional `www.`/`utm_*` stripping in normalize (off by default). |
| Sort folder A→Z action | In #edit context menu (bulk `move` with index). |
| ✔ Sort folder A→Z action | **Shipped in v1.1.0** — a row action and a toolbar button, planned first and confirmed with a count (`03 §3`). |
## v1.2 — resilience
### Next direction (written 2026-10-29, ordered by value per risk)
- **Scheduled local snapshots**: periodic JSON backup. ⚠️ Requires `alarms`
permission + a background service worker + `downloads` (or OPFS storage)
→ permission-story change ⇒ minor version, docs 08/09 update, privacy tab
re-review. Decide deliberately; OPFS-based silent snapshots may avoid
`downloads`.
1. **v1.1.x — automate the upgrade test.** An end-to-end run with Playwright's
bundled Chromium (`--load-extension` still works there; branded Chrome
dropped it in 137) that installs 1.0.1, upgrades over the same profile and
runs the `11 §5` smoke in CI. Needs a dev-dependency approval (`01 §4`).
2. **v1.1.x — Firefox automatic backups** (`.jsonlz4`): a ~80-line pure-TS LZ4
block decoder, no dependency. Also: capture a real Chrome HTML + `Bookmarks`
pair to sit beside the hand-built `chrome-156-*` fixtures, and the JA native
review.
3. **v1.4 — the aggressive-dedupe toggle** (deferred this round), a
session-scoped import undo, Biome linting of `.svelte` files, and true
virtualization of the edit tree if 500-row chunks prove too coarse. These
were the v1.2 plan until 2026-11-06, when real installs in Chinese and
Romanian made two languages the next minor instead (see below), and the
v1.3 plan until 2026-11-18, when Firefox and Edge took that number.
4. **v1.3 — Firefox (AMO) and Edge Add-ons, and automated publishing to all
three stores** — **GO 2026-11-18** (decision log; the section below).
### Backlog carried from the v1.1.0 audit
Items found by the 2026-10-28 audit and not closed in v1.1.0, with their IDs:
cL6 non-UTF-8 charsets in HTML imports; cL9 an extension allowlist on drop
(content sniffing is the gate, so not planned); cL13 a newline inside a title
for Chrome's line-based importer; sA8.1 Biome does not lint `.svelte`. From
the post-implementation review: ~~a keyboard way to place an item before or
after a sibling~~ (✔ v1.2.1, Alt+↑/↓); true virtualization of the
edit tree (a 500-row window around the focus shipped — `05 §9`); a
`require-trusted-types-for 'script'` CSP, which would make Chrome itself
enforce the raw-HTML ban (the Svelte runtime already creates the policy;
untested in extension pages); an input on the ops repo's reusable workflow to
skip install scripts in the `Build + package` job (`12 §2`); whether a
screen reader reads a focused row's button labels with its name (the owner's
Narrator pass on 1.2.0 found nothing blocking, 2026-11; the verbosity itself
was not measured, and NVDA, JAWS and VoiceOver remain untested).
### Accessibility backlog (from the 2026-11-10 audit, not closed in v1.2.1)
`ACCESSIBILITY.md` lists the user-facing ones as known limitations; this is
where they are scheduled. None blocks a task; each is a patch when it lands
(`12 §4`).
- **Spoken results for the other edit commands.** Only Alt+↑/↓ announces what
it did. A move, a sort, a rename, "keep first" and a new folder are silent
on success, and so is a search (no result count, and "Nothing matches" is
not a live region).
- **Row semantics.** A folder and a bookmark differ only by an `aria-hidden`
icon (an empty folder has no `aria-expanded`, so it sounds like a
bookmark); the policy-managed lock and the child count are an icon and a
bare number.
- **A pointer route to reorder that is not a drag** (WCAG 2.5.7): drag and
Alt+↑/↓ exist; a click-only one does not.
- **The tree's keys are shown nowhere in the UI.** `ACCESSIBILITY.md` lists
them and About links to it; an in-product key list would need a dialog.
- **`role="toolbar"` without arrow keys** on the edit toolbar — the mismatch
the previews' `role="tree"` was removed for.
- **Hover-only hints** (`title` on elements that cannot take focus): the
status bar's notes, the import target note, the busy reason on a disabled
tab.
- **Headings and a skip link.** Only the legal gate has an `<h1>`, `#edit` has
no headings, and the header's five tab stops cannot be skipped. Landmarks
exist.
- **Settings descriptions** are not tied to their controls
(`aria-describedby`), nor is the "dedupe is off under Replace" note.
- **Info toasts leave after four seconds** with no pause on hover or focus.
- **Font sizes are in px**, so Chrome's font-size setting does not scale the
UI (zoom does).
- **Ctrl/⌘+F always goes to the search box** on `#edit`, even with a dialog
open.
- **No automated check of the rendered markup** — no axe pass, no role
queries; the harness photographs but does not inspect. (A process gap, so
not in the statement.) The forced-colours and focus-ring tests are
file-level text checks: they cannot see specificity, which is how three of
the 1.2.1 review's findings got past them.
- **Disabled without a visual cue.** The section tabs during a write, and a
row's buttons during a bulk command, change only the cursor.
- **Keys that cannot act are silent** — Alt+↑ at the top of a folder, Delete on
a root. And on a Mac laptop the delete key is Backspace, which the tree
does not handle; on ChromeOS Alt+↑/↓ may arrive as Page Up/Down.
- **Truncated titles** have no way to be read in full in the tree.
- **A held Alt+↑/↓ can flicker.** Moves run one at a time, but the live event
of one can flush a frame after the next press's optimistic patch and roll
the row back for that frame (`05 §10`). It converges; the fix is to drain
the batcher before planning.
## v1.2 — languages (planned 2026-11-06)
The CWS dashboard showed installs and active users in Chinese and Romanian
browsers, which the three shipped languages did not cover. v1.2.0 adds:
| Locale | Notes |
|---|---|
| **简体中文 (`zh-CN`)** | Simplified only. A Traditional Chinese browser (`zh-TW`/`HK`/`MO`) on "Automatic" gets English, matching Chrome's own manifest fallback (`07 §1–2`). A `zh-TW` dictionary is a separate, later decision; the `zh-CN` id leaves room for it. |
| **Română (`ro`)** | The first locale with **three** plural forms (`07 §5`), so the plural machinery grows a `few` form first. Comma-below `ș ț` enforced by a test. |
Both are best-effort translations awaiting a native pass (`07 §4`, `00 §10`).
The other candidates (Traditional Chinese, Russian, Polish, Arabic…) wait for
the same dashboard evidence. Russian, Polish and Arabic also need plural forms
beyond `few`; the guard test in `dictionaries.test.ts` fails first if one is
attempted.
## v1.3 — Firefox and Edge (GO 2026-11-18)
The last "reach" item, taken out of the v2.0 table below on the owner's
decision the day maintenance mode began (decision log). The roadmap's own
wording was right: it is not "the same zip" for Firefox — the bookmark roots,
separators and the move index all differ — so it is a minor, built docs-first.
Edge takes the Chromium package unchanged. Scope and status live in the
decision log and `CLAUDE.md` Phase 10.
## v1.4 — resilience (was v1.3 until 2026-11-18, v1.2 until 2026-11-06)
- ~~**Scheduled local snapshots**~~ — **not planned in maintenance mode**
(2026-11-18). It needs the `alarms` permission and a background service
worker, and `/MAINTENANCE.md` puts anything that needs a new permission out
of scope, as `CLAUDE.md` hard rule 1 always did.
- Import "undo" (session-scoped): remember created ids → one-click revert.
- Virtualized tree rendering if >100k real-world demand appears.
@@ -60,11 +272,11 @@ test run has not once meant "done" on this project.
| Candidate | Consideration |
|---|---|
| Firefox Add-ons (AMO) release | WXT multi-target already builds it (`wxt -b firefox`); needs AMO listing, `browser_specific_settings.gecko.id`, separate signing flow. |
| Edge Add-ons store | Same zip usually passes; Partner Center account needed. |
| ~~Firefox Add-ons (AMO) release~~ | **GO 2026-11-18 → v1.3** (above). |
| ~~Edge Add-ons store~~ | **GO 2026-11-18 → v1.3** (above). |
| Dead-link checker | Needs `host_permissions: <all_urls>` → destroys the minimal-permission story. If ever done: **separate companion extension**, not this one. |
| Duplicate auto-merge assistant | Merge metadata (keep oldest addDate) + folder-aware suggestions. |
| Bookmarklet/notes fields | Only if a lossless place exists in Chrome's model (likely not — avoid schema lies). |
| Duplicate auto-merge assistant | Merge metadata (keep oldest addDate) + folder-aware suggestions. **Not planned in maintenance mode.** |
| Bookmarklet/notes fields | Only if a lossless place exists in Chrome's model (likely not — avoid schema lies). **Not planned in maintenance mode.** |
## Explicit "never" list (re-affirm before any pivot)
@@ -73,6 +285,9 @@ test run has not once meant "done" on this project.
- Analytics/telemetry of any kind.
- Ads, sponsored bookmarks, affiliate link rewriting.
- Collecting or transmitting bookmark content.
- Any permission beyond `bookmarks` and `storage` (`CLAUDE.md` hard rule 1),
which is what keeps the dead-link checker a separate extension and the
scheduled snapshots off the roadmap.
## Decision log
@@ -93,3 +308,115 @@ test run has not once meant "done" on this project.
| 2026-07-25 | CI: ops repo has no `browser-extension-*` family; callers use `reusable-chrome-extension.yml` + a local quality job, release is standalone | 12 §2 |
| 2026-07-25 | Replace deletes nothing until the backup is **proven** — picker `close()` resolving, or an explicit user attestation on the anchor fallback | 03 §1 6b |
| 2026-07-25 | Every `#edit` mutation resyncs from the browser on rejection; roots and `unmodifiable` nodes offer no destructive affordance at all | 03 §3 |
| 2026-07-26 | Legal Gate renders **inside the content region**, not as a viewport overlay — `06 §3`'s "full overlay" reconciled in favour of `14 §2`'s reachable `#settings`/`#about` | 06 §3 |
| 2026-07-26 | Settings state mutates **in place**; every storage write passes a plain snapshot (a `$state` proxy is not structured-cloneable, so the old code would have thrown `DataCloneError` in a real browser) | 03 §4 |
| 2026-07-26 | `updateSettings` / `acceptLegal` return non-rejecting outcomes; UI feedback follows the write, never precedes it | 03 §4 |
| 2026-07-26 | Toast queue + timers live in a store, so they survive the route chain unmounting | 06 §4 |
| 2026-07-26 | Static outbound links use `<a target="_blank" rel="noopener noreferrer">`; imported bookmark URLs keep `tabs.create` (`09` T3 unchanged). Two mechanisms for two trust classes — do not harmonize | 09 T3 |
| 2026-07-26 | `#settings` has **six** rows: `markdownStyle` was persisted but only editable as a transient `#export` control | 06 §3.4 |
| 2026-07-26 | `locale: 'auto'` is a first-class fourth option in the switcher — it is the default, so it must be selectable | 06 §3.4 |
| 2026-07-26 | Language labels are endonyms, duplicated identically across the three dicts (the `common.appName` precedent) | 07 §4 |
| 2026-07-26 | Theme control is a three-way segmented control in both header and `#settings`, not a cycling `◐` | 06 §3 |
| 2026-07-26 | Version comes from the manifest at runtime; three hardcoded `0.1.0` literals removed (footer, `run-export`, `run-import`) | 06 §3.5 |
| 2026-07-26 | ~~About's "Changelog" points at GitHub Releases until `CHANGELOG.md` exists in Phase 5~~ — **resolved in Phase 5**: `links.ts` targets `CHANGELOG.md` and `tests/unit/links.test.ts` asserts both the URL shape and that the file exists | 06 §3.5 |
| 2026-07-26 | The gate's acceptance checkbox deliberately resets if the user navigates away and back — an un-submitted legal affirmation is not worth persisting | 14 §2 |
| 2026-07-26 | Both entrypoints await settings (Manager also legal) **before** `mount()`, trading a blank frame for no locale/theme/gate flicker | 02 §2 |
| 2026-07-26 | ~~**Known limitation:** two open Manager tabs do not sync settings or acceptance to each other; last write wins. No `storage.onChanged` listener in v1~~ — **superseded 2026-08-03**, see the Phase 6 rows below | 03 §4 |
| 2026-07-26 | Transitive dev-dep CVEs fixed with a `package.json` `overrides` block rather than by waiting on parents — every parent pinned a vulnerable range, which is why Dependabot's own PRs all failed | 09 §3.1 |
| 2026-07-26 | The release announcement is `continue-on-error`. A missing Discord webhook made the real v1.0.0 run red on a release whose zip and checksums had published correctly; a red run on a good release trains you to ignore the colour | 12 §2.3 |
| 2026-07-26 | Gate-blocked tabs stay **clickable**; what blocks a route is the gate replacing the tab body, not an inert button. Disabling them removed the only in-app path back to the accept UI | 06 §3 |
| 2026-07-26 | Failure UI shows the localized sentence and puts the raw browser error in a separate detail block — `detail ?? t(key)` made every translation dead code | 02 §7 |
| 2026-07-26 | `--accent-fg` is redefined in the dark blocks alongside `--accent`; white on the lightened violet measured 3.67:1 | 06 §5 |
| 2026-07-26 | Plural keys implemented per `07 §5` (`selectPluralForm` + `tPlural`); `import.warnings.title` and all seven `warnings.*` codes converted | 07 §5 |
| 2026-07-26 | The import session stores an i18n **key**, not a resolved string — `t()` is only reactive where it is called, so a stored sentence never follows a language switch | 03 §5 |
| 2026-08-03 | **Every destructive step reports what already landed.** `writeTree` and `clearRoots` wrap their failing `chrome.*` call in `BmPartialWrite{phase, done}`, matching the contract `BmAborted` already had. A failure that says only "the browser refused" tells a user whose tree was half-replaced nothing they can act on | 02 §7, 03 §1 |
| 2026-08-03 | **`BmAborted` is re-thrown before the partial-write wrap.** Wrapping it would relabel every user cancellation as a failure and make `import.cancelledSummary` dead code — the same defect class as `detail ?? t(key)` | 03 §1 |
| 2026-08-03 | **The import report states that imported bookmarks carry today's date.** `05 §6` and `00 §8` both required this and no string ever said it. Shown in the `parsed` state too — telling someone before they commit beats telling them after | 03 §1, 05 §6 |
| 2026-08-03 | **Routing is guarded while a write or attestation is in flight**, via an injected predicate rather than a store import, so `route` stays uncoupled. Browser Back during `attesting` previously deadlocked the Manager permanently: the same hole Phase 4 closed for the footer and TabBar, left open on `hashchange` | 02 §5 |
| 2026-08-03 | **The attestation resolver lives in the import store, not in `ImportTab`.** A component-local resolver dies with the component; a remounted tab then renders inert buttons. A stale or reset resolver settles **`false`** — an unanswered backup attestation must never read as consent | 03 §1 6b |
| 2026-08-03 | **Two Manager tabs now converge.** Settings adopt external changes under two rules: ignore anything arriving while this context has an unflushed write (last-write-wins, as before), else adopt only when a field actually differs. Field equality makes self-echo suppression fall out for free — no snapshot to go stale | 03 §4 |
| 2026-08-03 | **Legal acceptance is adopted in one direction only — toward accepted.** The gate replaces the tab body, so an externally-raised gate would unmount `ImportTab` mid-write and recreate the attestation deadlock through a third door. One-way makes that unreachable by construction | 03 §4, 14 §2 |
| 2026-08-03 | **One `ErrorCallout` owns the localized-sentence-plus-detail-block contract.** Three sites still rendered a raw English Chrome string as the whole message after `LegalGate` had already been fixed for exactly that | 02 §7 |
| 2026-08-03 | **`NO_WRITABLE_ROOTS` is its own error, not `BROWSER`.** A profile with no writable root is an absence, not a refusal; reporting "the browser refused" sends the user looking for the wrong thing | 02 §7 |
| 2026-08-03 | **Search-driven expansion is undone when the search clears**, tracked separately from folders the user opened by hand. Merging into `expanded` was deliberate (a render-time union broke the disclosure button) — the missing half was the un-merge | 03 §3, 06 §3.3 |
| 2026-08-03 | **The "if you contact us" paragraph in `legal/PRIVACY.md` is a clarification, not a material change** — it describes what happens to data a user chooses to send, which was never inside "what the extension collects". `LEGAL_VERSION` deliberately **not** bumped: re-showing the gate to every installed user over a patch is a worse outcome than the ambiguity it fixes | 14 §2, 14 §3 |
| 2026-08-03 | **A WXT bump is accepted only after diffing the BUILT manifest**, not on a green test run. `tests/unit/manifest.test.ts` reads `wxt.config.ts`, which a WXT upgrade cannot change, so it stays green no matter what WXT emits. 0.21.3 was verified byte-identical in manifest, file inventory and bundle size; it did break `wxt/testing` into two subpaths and retype `tabs.create` as `void`, both dev-only. `check-manifest.mjs` now asserts the exact top-level key set so the next one is caught by CI rather than by hand | 01 §2, 12 §2.3 |
| 2026-08-03 | **jsdom 30 accepted after running `dom-environment.test.ts` first.** The canary exists because the Netscape walk depends on parse5's implied-end-tag behaviour; the rule is that a failing canary pins the dependency, never loosens the test. The 2 869 ms figure in `11 §6` is a jsdom **29** number and a major bump adds a column rather than overwriting it | 01 §2, 11 §6 |
| 2026-08-03 | **`continue-on-error` is invalid on a job that calls a reusable workflow** — GitHub rejects the file with "Property continue-on-error is not allowed", and a rejected file is a `startup_failure` with zero jobs and no log, not a failed job. `release.yml`'s announce job had carried it since `5f4c6e7`; that commit landed *after* the `v1.0.0` tag and no tag was pushed since, so **the first v1.0.1 tag would have been its first execution**. Both notification jobs are now gated with `if:` on a repo variable — allowed there, unlike a secret — defaulting to skipped | 12 §2.3, 12 §2.4 |
| 2026-08-03 | **A notification must never change the colour of the thing it reports on.** `notify-ci-failure.yml` had been failing on *every* CI completion, success included, because the reusable declares a secret that does not exist and GitHub validates that before the reusable's own success filter runs. Same lesson as `5f4c6e7`, learned twice | 12 §2.4 |
| 2026-08-03 | **No support email on any in-product surface.** About links to the store listing, the repo, issues and the changelog. Publishing an address inside the extension invites unsanitized bookmark files by mail, which is the exact receipt-of-personal-data problem the privacy clause exists to bound. The address stays in `SECURITY.md`, `CONTRIBUTING.md` and the privacy policy | 06 §3.5, 09 §6 |
| 2026-10-28 | **Node 26 LTS for the whole toolchain.** Node 26 entered Active LTS that day and Node 24 had gone to maintenance on 2026-10-20 — the "latest stable or LTS" rule of `01` moves with it | 01 §2 |
| 2026-10-28 | **TypeScript 7 runs beside the TS 6 API instead of replacing it.** `@typescript/native` (`npm:typescript@~7.0.2`) owns `tsc`; `typescript` is aliased to `@typescript/typescript6`, which re-exports TS 6.0.3 for svelte-check and Volar. TS 7 has no programmatic API until 7.1, and svelte-check peers `^5 \|\| ^6`, so this is the only way to adopt 7 without losing template type-checking | 01 §2 |
| 2026-10-28 | **ES2025, and the Chrome floor that makes it honest: 120 → 136.** A lib newer than the floor lets the compiler accept APIs the oldest allowed Chrome lacks (`RegExp.escape` is 136). `CHROME_FLOOR` in `wxt.config.ts` drives both `minimum_chrome_version` and Vite's `build.target`; `manifest.test.ts` pins those and tsconfig's `lib` together. A floor raise strands nobody — users below it keep their version and stop updating — but it is user-visible, so never in a patch | 01 §1, 08 §7 |
| 2026-10-28 | **7-day supply-chain cooldown:** `.npmrc` `min-release-age=7` + Dependabot `cooldown: 7`. Verified that `npm ci` still installs whatever the lockfile pins, so the rule only shapes *what gets locked* | 01 §6, 09 §3.1 |
| 2026-10-28 | **The `overrides` block is deleted.** All six pinned packages had left the tree (WXT 0.21 dropped `web-ext-run`; Vite 8 uses rolldown, not esbuild). `npm audit` 13 → 3 low, all one unfixable `deepmerge` advisory inside vite-plugin-svelte, accepted and documented; `--omit=dev` stays 0 | 09 §3.1 |
| 2026-10-28 | **WXT 0.21.3 → 0.21.4 accepted after the built-manifest diff** the 2026-08-03 rule requires: identical key set and values (only the deliberate `minimum_chrome_version`), identical file inventory, chunk sizes within ±1.1 kB from the Svelte 5.57 runtime. Vitest 4 → 5 and jsdom 30.0 → 30.1 passed the whole suite unchanged, the `dom-environment` canary first | 01 §2 |
| 2026-10-28 | **Biome ignores Markdown and YAML.** 2.6 began formatting both and flagged 35 hand-laid docs and workflows; formatting prose is not what the gate is for | 10 §3 |
| 2026-10-28 | **SonarCloud moves from Automatic Analysis to a CI scan** (`sonarcloud.yml`, `sonar-project.properties`): coverage at last, and a scan of what CI actually builds. Its own workflow so it never colours CI; the scan action pinned to a commit because it holds `SONAR_TOKEN`; skipped, not failed, where secrets are absent | 12 §2.5 |
| 2026-10-28 | **Coverage measures all of `src/**/*.ts`, but the gate stays core-only** via a glob threshold — verified to still fail a run below `src/lib/core/**`'s numbers, so widening what is measured cannot loosen what is enforced | 11 §1, 12 §2.5 |
| 2026-10-28 | **CI installs with `--ignore-scripts` and runs `wxt prepare` explicitly; reusables get named secrets; checkouts drop credentials; the release's write token moves to a job that installs nothing.** The old release job ran every dependency's install script and our tests while holding `contents: write`. The announce job's `secrets: inherit` also passed nothing it could use — this repo's webhook secrets have different names than the reusable reads | 12 §2 |
| 2026-10-28 | **docs/12 stops copying workflow YAML.** The copies drifted three times; with docs-win, a stale copy invites reverting a pinned action or deleting a gate. The chapter now records why each job exists and the traps already hit; the files are the ground truth about themselves | 12 §2 |
| 2026-10-28 | **The zero-network promise becomes browser-enforced.** The production manifest gains an extension-page CSP that keeps the MV3 minimum and adds `connect-src 'none'` plus closed image/font/media/frame/form sources — no `default-src`, so styles are untouched; dev builds omit it so HMR works. Reverses `08 §3`'s old "never add a custom CSP", whose reason was that MV3 forbids *loosening*; tightening was always allowed. The rule now: only ever tighten, and `check:manifest` pins the exact string | 08 §3 |
| 2026-10-28 | **Three gates instead of one grep:** the CSP (runtime), `check:manifest` scanning the shipped JS for network APIs (catches dependency code), and a rewritten `guard.mjs` — whole-file matching, identifiers banned outright, computed global access banned, `.html/.css` scanned, no test exemption, fails on zero files. The old one let all 28 audited bypasses through and printed "clean" for a checkout path with a space or diacritic. Vite's modulepreload polyfill (the one network call in the bundle) is off | 08 §3 |
| 2026-10-28 | **The guard's rule list lives in `scripts/guard.mjs` only.** `08 §3` restating it was the "single source" that had already diverged (`\{@html\}` matched only the literal text) | 08 §3 |
| 2026-10-28 | **The sanitizer reads the browser JSON formats and is default-deny for JSON.** It accepted any JSON and rewrote only `url`/`title`, so Chrome's profile `Bookmarks` file — titles under `name`, plus `meta_info` and a base64 sync blob — came out with every title intact and passed its own host check. JSON dialects are now recognised by shape (anything else refused), every string value is rewritten except structural keys, Firefox root GUIDs and the timestamps survive | 09 §6 |
| 2026-10-28 | **The sanitizer's backstop reads the output's text, not just its hosts.** For HTML it strips markup and refuses on any word that is not a placeholder — independent of the rewriting rules, unlike the old check (and its test), which shared their blind spots. It also stopped overwriting the input when the output path equalled it, checks size before reading, decodes attributes once (CodeQL double-escaping) and finds `<DD>` notes in linear time (Sonar S8786), attributes included | 09 §6 |
| 2026-10-28 | **`scripts/` obeys the size rule and is type-checked.** `docs/10 §1` now names `.mjs`; the 627-line sanitizer is split into `scripts/sanitize/` modules; every script carries `// @ts-check` and `tsconfig.scripts.json` runs them through the TS 7 `tsc` in `npm run check`. The sanitizer stays plain `.mjs` on purpose — reporters run it on whatever Node they have | 10 §1 |
| 2026-10-28 | **Every reader skips what `chrome.bookmarks.create` would reject — before anything is written.** One `core/href.ts` verdict for all formats: blank → `MISSING_URL`, unparseable → `INVALID_URL`, Firefox `place:` → `PLACE_QUERIES_SKIPPED` in browser-written formats only (BM JSON/CSV are restore formats and keep it). v1.0.x let an invalid address reach the write, which failed part-way — after a Replace had cleared the tree | 04 §1.2, 05 §1 |
| 2026-10-28 | **Empty titles stay empty.** `textContent \|\| href` turned a deliberately favicon-only Bookmarks Bar into a row of URLs after one export/import cycle; Chrome shows the address itself when it needs a title. `EMPTY_TITLE` now just counts them | 05 §1 |
| 2026-10-28 | **The Netscape walk reads every entry the file holds**: lists swallowed by a loose bookmark, entries hidden inside a re-opened `<b>`, root lists wrapped in `<div>`. Root markers are read by value (`="false"` is not the bar). The node cap is counted on the raw text before `DOMParser` runs. Each was a silent loss in v1.0.x — a smaller tree and no warning — so `UNREADABLE_ENTRIES` now counts what still cannot be read | 04 §1.2 |
| 2026-10-28 | **Other and Mobile get root markers, like the bar always had**: `UNFILED_BOOKMARKS_FOLDER` (Firefox's own attribute) / `MOBILE_BOOKMARKS_FOLDER` in HTML, `"root"` in BM JSON (additive, version stays 1). A 1.0.x full-tree backup is recognised by its exact shape and marked on read, so existing backups stop nesting too | 04 §1.1, §2 |
| 2026-10-28 | **CSV neutralizes formula cells** with one guard `'` that its own reader removes again — reversible, so the round trip stays exact. An unclosed quote is now `CSV_UNCLOSED_QUOTE` with the opening line instead of one cell swallowing the rest of the file. Same-named sibling folders merging is documented as a CSV loss | 04 §3 |
| 2026-10-28 | **Markdown escapes every CommonMark-active character and collapses line breaks in titles.** Escaping only `[ ] ( )` let raw HTML through into the renderers a share format lands in | 04 §4 |
| 2026-10-28 | **`warnings`/`errors` live in `locales/<lang>-notices.ts`**, re-assembled by each locale file, so all six stay under the size limit as codes are added | 07 §2 |
| 2026-10-29 | **Chrome's profile `Bookmarks` file and Firefox's JSON backup are imported directly** — the copies people have when a browser will not start or a profile is gone, and the only ones that still say which bookmarks were in Mobile. Neither ever writes: export stays HTML/BM JSON/CSV/Markdown. Each reader is held to a **parity rule** against its browser's own HTML exporter (`chrome-156-*`, `firefox-*` fixture pairs), so the two paths into BookmarkMagic cannot disagree about the same profile | 04 §2a, §2b |
| 2026-10-29 | **One read entry point, JSON first and parsed once.** `parseBookmarkFile` sniffs, parses and routes JSON by shape; `NOT_BM_JSON` widens to "JSON, but no bookmark file we know" rather than adding a code. The doctype probe is anchored to the start of the file, and the file picker loses its `accept` filter, which hid the extensionless `Bookmarks` file | 04 intro, 02 §7 |
| 2026-10-29 | **Firefox's internal root names are localized by the caller** (`import.rootTitle.*`), and fall back to the file's own key — never an English string from `core/`. The i18n key is `unfiled`, not `other`: a branch with an `other` key reads as a plural to `dictionaries.test.ts` | 04 §2b, 07 |
| 2026-10-29 | **Merge finally merges** (`core/merge.ts`): file folders reuse writable live folders with the same title, level by level, and new items are appended. 1.0.x documented path matching and planned Merge exactly like Replace, re-creating every folder. Same-named file siblings that both match share the live folder; when neither matches both are created — Merge never invents structure | 03 §1, 05 §5 |
| 2026-10-29 | **Root folders are unwrapped by marker, not title** (`core/route.ts`): toolbar → bar, `root: other` → Other in place, `root: mobile` → Mobile (a folder under Other when the profile has none). Replace plans through the same code against emptied roots, so a restore run twice gives the same tree — 1.0.x nested Other and Mobile one level deeper per restore | 03 §1, 02 §4 |
| 2026-10-29 | **Replace never dedupes, and the plan says so** (`plan.dedupe` is the effective value). In-file repeats are part of a backup; 1.0.x collapsed them while the box showed unchecked. Merge dedupes against the Start-time read, not the preview snapshot | 03 §1 |
| 2026-10-29 | **The plan is built before the backup, and the backup is refused if the import could not read it back.** Compact BM JSON, checked against the node, depth and byte caps before anything is written, downloaded or deleted (`BACKUP_EXCEEDS_LIMITS`). The still-open save dialog's rejection is marked handled, so a later Cancel cannot surface as an unhandled rejection | 03 §1 step 6b, 02 §7 |
| 2026-10-29 | **The seeded round-trip suite had been testing 200 empty trees since Phase 1.** xorshift32 seeded with 1–200 draws near-zero values first, so every generated tree had 0 children. `makeRng` now scrambles the seed, and every seeded suite asserts its corpus is non-trivial before asserting anything else. Found by the new merge property suite's own non-vacuity check | 11 §3 |
| 2026-10-29 | **Sort A→Z is planned before it runs and moves only what is out of place.** Folders first, `Intl.Collator` numeric and accent/case-insensitive, stable; left-to-right moves, each taking a child from further right, so the target index needs no correction for `chrome.bookmarks.move`'s same-parent rule. The confirmation states the count; a refusal part-way says how far it got and re-reads | 03 §3 |
| 2026-10-29 | **Drag to reorder, with before/after/into zones.** `planDrop` converts once between Chrome's pre-removal move index and `onMoved`'s post-removal one; dropping a node beside itself is no move; the permanent roots take drops into only | 03 §3, 06 §3.3 |
| 2026-10-29 | **Live sync is batched per animation frame and re-reads on bursts** (more than 500 queued events), after a wholesale reorder and after Chrome's own import. Each listener is isolated in try/catch. 1.0.x patched the whole tree — and rescanned it for duplicates — once per event | 03 §3 |
| 2026-10-29 | **Bounded rendering ships as 500-row chunks, not windowing.** The edit tree, the import preview and the export picker mount 500 rows at a time with "Show more"; the focused row is always mounted. Windowing was the plan; chunking gives the same bound with none of the keyboard/DnD risk, and windowing moves to the backlog | 05 §9 |
| 2026-10-29 | **One modal for every dialog** (`Modal.svelte`, native `<dialog>`): focus in, Esc, focus returned, and no cancel callback after a confirm. Move-to was a positioned `<div>` that focus never entered | 06 §5 |
| 2026-10-29 | **The v1.1 look is "technical"**: cool neutrals, a mono stack for labels and numbers, a faint grid, 6/4 px radii, a self-drawn SVG icon set, an IDE-style status bar. No font is bundled. Every animation and moving transition sits inside `prefers-reduced-motion: no-preference`, enforced by `motion.test.ts`; text clears 4.5:1 and control boundaries 3:1 on every surface, enforced by `contrast.test.ts` | 06 §1 |
| 2026-10-29 | **Replace asks first, with numbers.** The confirmation states how many bookmarks and folders will be deleted and how many written; the Start button counts what a preview plan will really import, not what the file holds | 03 §1, 09 T4 |
| 2026-10-29 | **One writer across Manager tabs** (Web Locks, `ifAvailable`): a second tab's import, sort or duplicate clean-up is refused at once with `WRITE_LOCKED`. The import takes the lock after opening the save picker, so the click's activation still holds | 03 §5, 08 §2 |
| 2026-10-29 | **The popup routes an open Manager** over a `BroadcastChannel` instead of only focusing it; the Manager refuses while an import writes | 02 §6 |
| 2026-10-29 | **A local diagnostics log, copied by the user.** In memory, 200 allowlisted events (phases, codes, counts, error names), recorded at the one place failures are described — by code, never detail text. No storage, no network, no new permission. A PRIVACY clarification, not a bump | 09 §7, 14 §3.1 |
| 2026-10-29 | **Failure toasts stay until dismissed**; success and info still leave after 4 s | 06 §4 |
| 2026-10-29 | **About and THIRD_PARTY_NOTICES stop saying "no third-party code"** — the build always compiled in the Svelte runtime, its `clsx` helper and WXT's browser shim (all MIT; `clsx` was found by the review, not by the first fix). The notices now ship as `THIRD_PARTY_NOTICES.txt`, required by `check:manifest`, and `wxt.config.ts` fails the build when an uncredited package would ship | 14 §5 |
| 2026-10-29 | **Contact aliases per purpose**: security@ (SECURITY.md), privacy@ (PRIVACY), legal@ and dmca@ (EULA, DISCLAIMER), copyright@ (licensing), takedown@ (impersonating copies), code@ (CoC, contributing, issue chooser), sponsor@/collab@/press@ (README); contact@ retired. Still none inside the product — `links.test.ts` now scans all of `src/` | 14 §3.1, 09 §6 |
| 2026-10-29 | **Legal clarifications, no `LEGAL_VERSION` bump**: version/date headers, a copyright line, EULA clause 3 as a non-binding note (GPL §10), DISCLAIMER's Replace description, PRIVACY on diagnostics, the Web Store and opening a bookmark | 14 §3.1 |
| 2026-10-29 | **`scripts/screenshots.mjs`** serves the built extension with a fake `chrome`, neutral sample data and the production CSP as a meta tag; `--shoot` drives headless Chrome for `capture/` and the store set. Visual QA and listing screenshots stop depending on anyone's real profile. It listens on 127.0.0.1 only, and runs Chrome asynchronously — `execFileSync` blocked the very server Chrome was waiting on | 11 §5, 13 |
| 2026-10-29 | **Review of the 1.1.0 UI, acted on before release**: the edit tree keeps focus on a rendered row and returns it from the rename box; a bulk command locks every other write in the session, not just the toolbar; a folder closed during a search stays closed; #edit mounts a 500-row window around the focus instead of a growing prefix; failures get a pinned toast slot so later toasts still show; the import moves focus to each step's heading and announces its outcome; dialogs name their × "Dismiss"; the import preview's new/dup badges show again (a deep `$state` proxy broke their WeakMap lookups — already broken in 1.0.x) | 03 §3, 05 §9, 06 §4–§5 |
| 2026-10-29 | **The extension-page CSP gains `default-src 'none'`** — reversing the earlier "deliberately no default-src". Every directive the pages use is listed, so it changes nothing for them, and it closes what was left open (manifests, prefetch). WebRTC, which no CSP directive Chrome enforces governs, stays covered by the bundle and source scans | 08 §3 |
| 2026-10-29 | **Diagnostics allowlist enforced by types**: every `DiagEvent` string field is a union of fixed values, error names pass through an allowlist (`'other'` otherwise), and `@ts-expect-error` tests keep a title from compiling | 09 §7 |
| 2026-10-29 | **SonarCloud runs in two jobs**: coverage with no secret, then a scan that installs nothing and gets the lcov report as an artifact — a job's secrets are readable by every step on its runner | 12 §2.5 |
| 2026-10-29 | **The first `v1.1.0` tag run failed before publishing, and the tag was moved.** `upload-artifact` skips hidden paths, so the build job's `.output/*` matched nothing. Fixed in #29; since no Release or asset existed yet, `v1.1.0` was re-pointed at the fixed `main` (`9040f84`) rather than burning a version. `13 §7`'s rule — never move the tag of a published Release — is unchanged | 12 §2.3, 13 §7 |
| 2026-11-06 | **v1.1.0 is live; v1.2.0 is two languages, not the dedupe toggle.** The dashboard showed real installs in Chinese and Romanian browsers. A new UI language is a **minor** release — it changes what the switcher offers and what the listing says — while translation *fixes* stay patches (`12 §4`). The old v1.2 items move to v1.3 unchanged | 12 §4, 15 |
| 2026-11-06 | **Simplified Chinese only, and a Traditional Chinese browser on "Automatic" gets English.** Chrome's manifest fallback goes `zh_TW → zh → en`, never to `zh_CN`, so mapping Traditional to Simplified in the UI would make the extension's name and its UI disagree. A user can still pick 简体中文 by hand | 07 §1–2 |
| 2026-11-06 | **The locale id is `zh-CN`, not `zh`.** It is a persisted setting value: a bare `zh` would have to be migrated the day a `zh-TW` dictionary exists. The id doubles as the `<html lang>` value, which is what makes Chrome draw Simplified glyphs rather than Japanese ones | 07 §2 |
| 2026-11-06 | **One `LOCALES` list.** Every table keyed by locale is a `Record<Locale, …>` and every allow-list spreads `LOCALES`, so a new locale missing anywhere is a compile error. Before, adding a language meant finding six hand-written `['en', 'vi', 'ja']` lists, and missing one degraded silently to English | 07 §2, §6 |
| 2026-11-06 | **A third plural form, only where a locale needs it.** `Dict` widens each plural branch to `{ one, other, few? }`. Whether a locale carries `few` is decided by its own `Intl.PluralRules` categories and enforced at runtime, so en/vi/ja/zh write no dead `few`. A guard fails on any shipped locale needing `two`/`many`/`zero` before a grammar the helper cannot select can ship | 07 §5 |
| 2026-11-06 | **Romanian uses comma-below `ș ț`, enforced by a test.** The cedilla forms `ş ţ` look alike and are different letters to search and sort — the classic Romanian localization defect | 07 §4 |
| 2026-11-06 | **ZH-CN and RO ship best-effort, like JA.** Written from Chrome's own terminology in each language and marked `TODO(review-zh)` / `TODO(review-ro)`; the translation form lists both. Waiting for native reviewers would have left users who already installed the extension on English indefinitely | 07 §4, 00 §10 |
| 2026-11-10 | **v1.2.0 is live; v1.2.1 is accessibility.** The owner's keyboard-only and Narrator pass over 1.2.0 found nothing, and an audit of `src/` then found five things such a pass cannot see or did not reach: a focus ring drawn in the colour of the fill under it, no forced-colours support, reordering that only a drag could do, focus dropped on `<body>` in three places, and targets under 24 px. A pass by one person with one screen reader is evidence, not a verdict — which is also why the statement says what was tested and what was not | 06 §5, 11 §5 |
| 2026-11-10 | **An accessibility statement, at the repository root.** `ACCESSIBILITY.md`, beside `SECURITY.md` and `CONTRIBUTING.md`, linked from the README and from About. It states **WCAG 2.2 AA as the goal, not as a conformance claim**: nobody has audited the product, and a claim would be the kind of sentence `14` exists to keep out of the project. Known limitations are listed in it rather than left in this backlog, because a user deciding whether the product will work for them reads that file, not this one | 06 §5, 15 |
| 2026-11-10 | **`accessibility@poli0981.dev` for barrier reports**, the eleventh per-purpose alias (created and tested by the owner). It appears in `ACCESSIBILITY.md`, the README's contact table and the issue chooser — never in `src/`, by the 2026-08-03 rule, which the About link respects by pointing at the file instead. Reports have their own issue form and an `accessibility` label, because a barrier report needs the assistive technology and its version, which the bug form does not ask for | 06 §3.5, 13 §6 |
| 2026-11-10 | **Svelte's accessibility warnings fail the build.** `svelte-check --fail-on-warnings`: the `a11y_*` checks are compiler warnings, a warning never failed anything, and Biome does not read `.svelte` — so nothing linted the markup. The suite was at zero warnings, which is the only cheap moment to turn it on | 10 §3, 12 §2 |
| 2026-11-10 | **The review of 1.2.1 found what the tests could not, again.** Twelve code findings and seventeen in the docs — among them a tree that jumped to the top on the first click of a row button (the fix for one focus defect causing another), three forced-colours rules that lost to more specific ones, and an accessibility statement that promised more than the code did: "every clickable target is 24 px", "nothing times out", "focus is always a 2-pixel ring". The statement was rewritten to what the source supports, and its untested list grew. A statement written by the author of the code needs the same adversarial read as the code | 11 §5 |
| 2026-11-10 | **Alt+↑ / Alt+↓ reorders, and it is a patch.** It reuses `planDrop` and `moveTo`, so a keyboard move and a drag cannot disagree about what is legal, and there is no second write path to test. One place at a time, among the siblings on screen, like a drag. It ships in a patch because it closes a barrier to something the product already did rather than adding a capability; `12 §4` now says so. Rejected: "Move up / Move down" row buttons (two more on a row that already hides up to five), and a position field in "Move to…" (a new dialog flow for the same result) — though a click-only route is still owed (WCAG 2.5.7, backlog) | 05 §10, 12 §4 |
| 2026-11-10 | **Focus after a route change goes to `<main>`, not to the tree.** "Open in Edit" removes the button that was clicked. Focusing the tree when `#edit` mounts would also have fired on every first load, highlighting a row nobody chose and changing every screenshot; a route change with focus lost is the narrower condition and covers every tab | 06 §5 |
| 2026-11-10 | **Dependabot's bumps are not the whole bump.** #31 and #36 moved Biome twice and left `biome.json`'s `$schema` behind both times, and left `vitest`'s declared range a minor behind the coverage plugin's, which must match it (the lockfile had both at 5.1.0); `01 §2` drifted with them. The sync is a human step after each Dependabot merge, and WXT still gets the built-manifest diff — 0.21.5 produced a manifest byte-identical to the 1.2.0 release asset | 01 §2, §6 |
| 2026-11-18 | **Maintenance mode, as a written policy.** The project had been "in maintenance" since launch in the loose sense; the owner made it explicit: dependency updates on a schedule, high/critical advisories fixed as soon as a fix exists, major platform upgrades, bug/UI/UX/accessibility/translation fixes, and features only when on this roadmap or genuinely needed. **`/MAINTENANCE.md` is the policy and this file does not restate it** — the lesson of `12 §2`: a copy in two places drifts. The roadmap below stays valid; it is now the whole list of features that can still land | `MAINTENANCE.md` |
| 2026-11-18 | **Out-of-policy requests are closed by a workflow, not by hand.** The feature form asks one required question (on the roadmap / needed for a fix / something new); `scripts/triage.mjs` decides, as a pure and unit-tested function, and `triage.yml` acts with `gh` only — labelled `maintenance-mode` and closed *not planned*, or labelled `needs-triage`. `pull_request_target` checks out the base branch only and never interpolates a title or body into a shell line. Outside `feat…` pull requests are closed the same way; the owner, members, collaborators, bots and anything labelled `roadmap` are exempt. Rejected: removing the feature form (requests would arrive through the bug form, where nothing can detect them) and closing every request unread (the two in-policy answers deserve a human) | `12 §2.6`, `MAINTENANCE.md` |
| 2026-11-18 | **A high advisory with no fix is recorded, not worked around.** `npm audit` reports 14 high findings, all `picomatch` GHSA-fc5q-39xc-vjpf, every version affected, nothing to upgrade to. It is the toolchain's glob engine, matching patterns this repository writes, and never ships. The `deepmerge` row left: GitHub withdrew that advisory on 2026-11-16 | `09 §3.1` |
| 2026-11-18 | **A licence gate over the whole lockfile** (`scripts/check-licenses.mjs`): shipped packages must be permissive and GPL-3.0-compatible, tooling may also be MPL-2.0 and a few other non-copyleft licences; anything else fails until a person adds it on purpose. One shared `CREDITED_PACKAGES` list (`scripts/credited-packages.mjs`) now feeds the build gate, the notices test and this gate. `dependency-review-action` was considered and not used: PR-only, ClearlyDefined rather than the lockfile, runtime scope by default, not runnable locally. `legal/THIRD_PARTY_NOTICES.md` had called the tooling all MIT/Apache-2.0/ISC; corrected, **not a `LEGAL_VERSION` bump** — it describes tooling that never ships | `09 §3.2`, `14 §3.1` |
| 2026-11-18 | **Dependabot #39–#41 merged and synced by hand**, as the 2026-11-10 row requires: `biome.json`'s `$schema` to 2.6.6, `01 §2`, the scan action's pin in `12 §2.5`, and for the jsdom 31 major a new column in `11 §6` (2 484 ms median) beside the jsdom 29 figure | `01 §2`, `11 §6` |
| 2026-11-18 | **GO for Firefox (AMO) and Microsoft Edge Add-ons, as v1.3.** The owner's decision, recorded here before any code because the maintenance announcement names it. Settled with the owner: gecko id `bookmarkmagic@poli0981.dev` — permanent after the first AMO upload, an id and not a mailbox, shown nowhere in the UI; desktop only, because Firefox for Android has no `bookmarks` API; MV3 everywhere (WXT defaults Firefox to MV2); and Firefox separators shown, protected and warned about rather than written into any file format. An audit found why it is a minor and not a CI change: Firefox's roots are GUIDs with a fourth (Bookmarks Menu) root, so `getRoots`' position fallback maps the Menu to the toolbar; separators come back as `data:` bookmarks; and a same-folder `move` counts its index after removal | `00 §7`, `15 §v1.3` |
| 2026-11-18 | **Qodana beside SonarCloud**, at the owner's request (Ultimate licence, `QODANA_TOKEN`). Its own, never-required workflow, in two jobs: `scan` installs the dev dependencies — `qodana-js` needs them — with a read-only `GITHUB_TOKEN`; `publish` installs nothing and uploads the SARIF to code scanning, instead of the PR comments and annotations the vendor's snippet asks `contents: write` for. Sharing a runner with dependency code is a recorded exception to the Sonar rule, accepted because the token can only upload reports | `12 §2.7` |
| 2026-11-18 | **The roadmap pruned to what maintenance mode allows.** Scheduled snapshots need `alarms` and are off the roadmap; the permission rule joins the never list, where the feature form had already put it. The `fflate` zip export (a runtime dependency), the duplicate auto-merge assistant and bookmarklet notes are not planned. The old v1.3 "resilience" becomes v1.4 | `15` |
+20 -8
View File
@@ -1,15 +1,27 @@
# Disclaimer — BookmarkMagic
Terms version 1 · Effective 2026-07-26 · Last updated 2026-11-18
- Provided "AS IS", without warranty of any kind (see LICENSE §15–16).
- Bookmark operations modify your browser's bookmark data. The "Replace
everything" mode DELETES all existing bookmarks after saving an automatic
safety backup. You are responsible for keeping backups of data you care
about.
- Imported bookmarks are created with the current date and time. Chrome's
extension API does not allow an extension to set a bookmark's original
creation date, so original dates are preserved in your exported *files* but
everything" mode DELETES all existing bookmarks. Before it does, it saves a
safety backup and asks you to confirm with the exact numbers it will delete
and write; it does not start if your bookmarks are larger than a backup the
Extension could read back. If the browser stops part-way, what was already
deleted can be restored by importing that backup. You remain responsible for
keeping backups of data you care about.
- Imported bookmarks are created with the current date and time. The
browsers' extension APIs do not allow an extension to set a bookmark's
original creation date, so original dates are preserved in your exported *files* but
not when writing back into the browser.
- Import files come from outside this Extension; verify you trust their source.
Bookmarked URLs are stored as-is and are not vetted by the Extension.
- This project is not affiliated with or endorsed by Google, Chrome, or any
browser vendor. Browser names are trademarks of their respective owners.
- This project is not affiliated with or endorsed by Google, Chrome, Mozilla,
Firefox, Microsoft, Edge or any browser vendor. Browser names are trademarks of their
respective owners.
- The BookmarkMagic name and icon identify this project, published by skullmute
(poli0981). The GPL lets anyone fork the code; it does not let a fork present
itself as this project. Report a copy that does to **takedown@poli0981.dev**,
and formal copyright notices to **dmca@poli0981.dev**.
Questions about this disclaimer: **legal@poli0981.dev**.
+20 -5
View File
@@ -1,5 +1,9 @@
# End User License Agreement — BookmarkMagic
Terms version 1 · Effective 2026-07-26 · Last updated 2026-11-18
Copyright © 2026 skullmute ([poli0981](https://github.com/poli0981)).
1. **License.** The software is free software licensed under the GNU General
Public License v3.0 or later (see LICENSE). You may use, study, share, and
modify it under those terms. This EULA adds no restrictions beyond the GPL;
@@ -7,9 +11,20 @@
2. **No warranty; limitation of liability.** As stated in GPL-3.0 §15 and §16,
the software is provided without warranty, and authors are not liable for
damages, including loss of bookmark data.
3. **Acceptable use.** You agree not to use the software to violate applicable
law or third-party rights.
3. **A note on use — not a condition.** Please do not use the software to break
the law or to infringe anyone's rights. This restates what the law already
requires; it is not an additional license term, because GPL-3.0 §10 does not
allow one, and your rights under the GPL do not depend on it.
4. **Your data.** The software processes bookmark data locally on your device
only (see PRIVACY.md).
5. **Updates.** Updates are delivered via the Chrome Web Store and may change
functionality. Material legal changes trigger re-acceptance in-app.
only, and sends nothing anywhere (see PRIVACY.md).
5. **Updates.** Updates are delivered through the store you installed the
Extension from — the Chrome Web Store, Firefox Add-ons or Microsoft Edge
Add-ons — and may change functionality. Material legal changes trigger re-acceptance in-app.
6. **Contact.** Questions about these terms: **legal@poli0981.dev**. Formal
copyright infringement (DMCA) notices: **dmca@poli0981.dev**.
---
*Clarified on 2026-10-29: clause 3 was worded as an obligation, which a GPL
program cannot impose; it is now a note, and clause 6 gives contacts. Nothing
you agreed to changed, so no re-acceptance is requested (`docs/14 §3.1`).*
+66 -7
View File
@@ -1,6 +1,6 @@
# Privacy Policy — BookmarkMagic
Last updated: 2026-07-25
Terms version 1 · Effective 2026-07-26 · Last updated 2026-11-18
BookmarkMagic ("the Extension") is designed to work entirely on your device.
@@ -16,12 +16,23 @@ contains no analytics, telemetry, or crash reporting.
device.
- **Local settings** (permission: `storage`): your language, theme,
preferences, and the date you accepted these terms are stored locally via
`chrome.storage.local`. They are not transmitted anywhere and are removed by
Chrome when you uninstall the Extension. The Extension does not use
`chrome.storage.sync`, so even your settings stay off any vendor cloud.
`chrome.storage.local` (Firefox calls the same store `browser.storage.local`).
They are not transmitted anywhere and are removed by the browser when you
uninstall the Extension. The Extension does not use `storage.sync`, so even
your settings stay off any vendor cloud.
The Extension requests no other permissions. It has no host permissions, no
content scripts, and no background service worker.
content scripts, and no background service worker. It contains no code that
makes network requests, and its Content-Security-Policy additionally makes the
browser refuse fetch, XHR, WebSocket, EventSource and beacon requests and
remote images, fonts, media and frames from its pages.
- **Diagnostics** (no permission needed): while a BookmarkMagic tab is open,
it keeps a short log of what it did — import steps, error codes, counts —
in memory, so that you can copy it into a bug report from the About tab. It
never contains titles, addresses or file names, is never written to storage,
disappears when the tab closes, and leaves your computer only if you paste
it somewhere yourself.
## Files you import or export
@@ -32,14 +43,62 @@ location you control.
## Third parties
No data is shared with anyone, because no data is collected. The Extension
ships with zero runtime dependencies.
installs no runtime dependencies; the few small MIT-licensed pieces its build
compiles in (the Svelte runtime with its clsx helper, and WXT's browser shim —
see THIRD_PARTY_NOTICES.md) contain no network code.
Two things happen outside the Extension and are worth knowing:
- **The store you install it from** — the Chrome Web Store (Google), Firefox
Add-ons (Mozilla) or Microsoft Edge Add-ons (Microsoft) — distributes the
Extension and its updates. Installing and updating it are governed by that
store's own privacy policy, not this one, and each gives the developer only
aggregate counts such as the number of users. On Firefox the Extension
declares that it collects no data, in Firefox's own data-consent system.
- **Opening a bookmark.** When you open a bookmark from the Edit tab, your
browser loads that page exactly as when you click any link: the request is
the browser's, made on your instruction, to the site you chose. The
Extension itself still sends nothing.
## If you contact us
Everything above describes the Extension, which sends us nothing. This section
describes what happens if *you* choose to send us something — reporting a bug,
for example.
- **Please do not send us your real bookmarks file.** A bookmarks export is a
browsing history. Run `scripts/sanitize-bookmarks.mjs` from the repository
first: it replaces every address and title while keeping the file structure
that a bug depends on, so the sanitized version still reproduces the problem.
- **Anything you attach to a GitHub issue is public** and stays in the issue
history. Attach only a sanitized sample. If you agree, a sample may be
committed to the repository as a permanent test fixture under GPL-3.0 — the
bug report form asks you explicitly, and never assumes it.
- **Anything you email us is kept only as long as it takes to reproduce and fix
the issue, and is then deleted.** It is not shared with anyone, and it is
never added to the repository unless you agreed to that.
## Changes
Material changes will be published here and re-acceptance will be requested
inside the Extension.
*The section above was added on 2026-08-03. It is a clarification, not a change
of practice: it describes handling of material you choose to send us, which was
never part of what the Extension itself collects — which remains nothing. No
re-acceptance was requested.*
*Clarified on 2026-11-18: the Extension is also distributed through Firefox
Add-ons and Microsoft Edge Add-ons. That adds no data flow — the Extension
still collects nothing — so no re-acceptance is requested (`docs/14 §3.1`).*
*Clarified on 2026-10-29: the diagnostics log, the Chrome Web Store, opening a
bookmark, and what the build compiles in are now described, and the contact
address changed. None of it changes what the Extension collects — still
nothing — so no re-acceptance is requested (`docs/14 §3.1`).*
## Contact
⚠️ contact email — or open an issue at
Privacy questions, and requests to remove a sample you sent:
**privacy@poli0981.dev** — or open an issue at
<https://github.com/poli0981/bookmarkmagic/issues>
+91 -10
View File
@@ -1,15 +1,96 @@
# Third-Party Notices — BookmarkMagic
**Runtime dependencies: None.**
Last updated: 2026-11-18
The shipped extension bundles no third-party code. Parsing, serializing and
downloading use platform APIs only (`DOMParser`, `Blob`, `URL`,
`crypto.randomUUID`).
**No runtime dependencies are installed** — `package.json` has an empty
`dependencies` list (`docs/01 §4`). A few small MIT-licensed pieces are,
however, **compiled into** the shipped extension by the build, and their
notices travel with it in `THIRD_PARTY_NOTICES.txt` at the root of the package:
Build-time tooling (WXT, Vite, Svelte, TypeScript, Biome, Knip, Vitest) is not
distributed with the extension and is not listed here. All of it is
MIT/Apache-2.0/ISC licensed and compatible with GPL-3.0-or-later.
| Package | What ships | License |
|---|---|---|
| [svelte](https://github.com/sveltejs/svelte) 5 | The runtime the compiler emits into each page (reactivity, DOM updates) | MIT |
| [clsx](https://github.com/lukeed/clsx) 2 | A class-name helper the Svelte runtime uses | MIT |
| [wxt](https://github.com/wxt-dev/wxt) + [@wxt-dev/browser](https://github.com/wxt-dev/wxt) | The one-line `browser` export: `globalThis.browser` when it exists, else `globalThis.chrome` | MIT |
If a runtime dependency is ever added — see `docs/01_TECH_STACK.md §4` for the
gated list — its name and full license text must be added to this file in the
same pull request, and the About tab must render it (`docs/14 §5`).
The build enforces this list: `wxt.config.ts` fails the build when code from any
other npm package would ship (`CREDITED_PACKAGES`, kept in
`scripts/credited-packages.mjs`), `tests/unit/third-party.test.ts` checks that
this file and the shipped `.txt` name every package on it, and
`npm run check:licenses` holds each of them to a permissive licence. None of these contains network code; the
extension's Content-Security-Policy forbids it anyway (`docs/08 §3`).
Build-time tooling (WXT's CLI, Vite, TypeScript, Biome, Knip, Vitest,
svelte-check and what they depend on) is not distributed with the extension and
is not listed here. Its licences are checked on every build by
`npm run check:licenses`: permissive (MIT, Apache-2.0, ISC, BSD, 0BSD, MIT-0,
BlueOak, CC0) or, for one CSS tool under Vite (`lightningcss`), the
file-level copyleft MPL-2.0 — none of which reaches the extension.
Licensing questions: **copyright@poli0981.dev**.
## svelte — MIT
Copyright (c) 2016-2025 Svelte Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## clsx — MIT
Copyright (c) Luke Edwards (lukeed.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## wxt and @wxt-dev/browser — MIT
Copyright (c) Aaron Klinker
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1301 -4495
View File
File diff suppressed because it is too large. Load diff
+21 -14
View File
@@ -1,7 +1,7 @@
{
"name": "bookmarkmagic",
"private": true,
"version": "0.1.0",
"version": "1.3.0",
"type": "module",
"description": "Import, export & edit bookmarks between browsers — offline, no account, no cloud.",
"license": "GPL-3.0-or-later",
@@ -15,36 +15,43 @@
"url": "https://github.com/poli0981/bookmarkmagic/issues"
},
"engines": {
"node": ">=24"
"node": ">=26"
},
"scripts": {
"postinstall": "wxt prepare",
"dev": "wxt",
"dev:firefox": "wxt -b firefox",
"build": "wxt build",
"build:firefox": "wxt build -b firefox",
"zip": "wxt zip",
"check": "svelte-check --tsconfig ./tsconfig.json && tsc --noEmit",
"zip:firefox": "wxt zip -b firefox",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings && tsc --noEmit && tsc -p tsconfig.scripts.json",
"lint": "biome check .",
"lint:fix": "biome check --write .",
"knip": "knip",
"guard": "node scripts/guard.mjs",
"check:manifest": "node scripts/check-manifest.mjs",
"check:licenses": "node scripts/check-licenses.mjs",
"icons": "node scripts/gen-icons.mjs",
"test": "vitest run",
"test:watch": "vitest",
"coverage": "vitest run --coverage",
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run test"
"verify": "npm run lint && npm run check && npm run knip && npm run guard && npm run check:licenses && npm run test",
"verify:full": "npm run verify && npm run coverage && npm run build && npm run check:manifest && npm run build:firefox && npm run check:manifest -- --browser firefox"
},
"devDependencies": {
"@biomejs/biome": "2.5.5",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"@vitest/coverage-v8": "^4.1.10",
"@biomejs/biome": "2.6.6",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
"@types/node": "^26.6.6",
"@typescript/native": "npm:typescript@~7.0.2",
"@vitest/coverage-v8": "^5.1.0",
"@wxt-dev/module-svelte": "^2.0.5",
"jsdom": "^29.1.1",
"knip": "^6.29.0",
"svelte": "^5.56.8",
"svelte-check": "^4.7.3",
"typescript": "~6.0.3",
"vitest": "^4.1.10",
"wxt": "^0.20.27"
"jsdom": "^31.0.0",
"knip": "^6.44.2",
"svelte": "^5.57.3",
"svelte-check": "^4.7.8",
"typescript": "npm:@typescript/typescript6@~6.0.2",
"vitest": "^5.1.0",
"wxt": "^0.21.5"
}
}
+49
View File
@@ -0,0 +1,49 @@
# Qodana — docs/12 §2.7. Read by .github/workflows/qodana.yml.
#
# qodana-js is JetBrains' JavaScript/TypeScript linter; it needs the Ultimate
# licence that QODANA_TOKEN carries. Native mode (no Docker image): the
# workflow installs node_modules on the runner first, with install scripts
# off, and the analysis reads them from there.
version: "1.0"
linter: qodana-js
withinDocker: false
profile:
name: qodana.recommended
# What is not code, or not ours: byte-exact browser samples (malformed on
# purpose), build and coverage output, screenshots, store copy, prose.
exclude:
- name: All
paths:
- tests/fixtures
- .output
- .wxt
- coverage
- capture
- store
- docs
- legal
# Inspections switched off after the first run (2026-11-18), each because it
# contradicts a rule of this repository rather than finding a defect:
#
# Doc comments here are prose (docs/10 §6). `@param` tags appear only where a
# `// @ts-check` script needs a type, so "every parameter described" is not
# the convention — 22 of the first run's 27 findings.
- name: JSCommentMatchesSignature
# A CRC-32 table for PNG chunks is bitwise by definition.
- name: JSBitwiseOperatorUsage
paths:
- scripts/gen-icons.mjs
# The dark palette is declared twice on purpose: once under the
# prefers-color-scheme query, once for the explicit theme switch (docs/06 §1).
- name: DuplicatedCode
paths:
- src/styles/tokens.css
# Clean since 2026-11-18 (docs/12 §2.7): any new finding turns this workflow
# red, so it is fixed or switched off here with its reason — never left
# standing to be ignored. Not a required check.
failureConditions:
severityThresholds:
any: 0
+17
View File
@@ -0,0 +1,17 @@
/**
* Types for scripts/check-licenses.mjs, so its tests can call it directly.
* The script itself is plain JavaScript checked with `// @ts-check`.
*/
export const SHIPPED_LICENSES: readonly string[];
export const TOOLCHAIN_LICENSES: readonly string[];
export const EXCEPTIONS: Readonly<Record<string, string>>;
export function satisfies(expression: string, allowed: readonly string[]): boolean;
export function packageNameOf(key: string): string;
export function checkLockfile(
lock: unknown,
options?: { shipsCode?: boolean },
): {
problems: string[];
checked: number;
counts: Map<string, number>;
};
+248
View File
@@ -0,0 +1,248 @@
// @ts-check
/**
* Licence gate — docs/09 §3.2, docs/12 §2.1.
*
* Reads `package-lock.json` (lockfile v3), where npm records each installed
* package's `license` field, and checks every entry against one of two lists:
*
* - SHIPPED — the packages the build compiles into the extension
* (`CREDITED_PACKAGES`, scripts/credited-packages.mjs). Their code travels
* inside a GPL-3.0-or-later extension, so only permissive licences that
* combine with it cleanly are accepted.
* - TOOLCHAIN — everything else. The extension has no runtime dependencies,
* so all of these are build and test tools that never ship. Permissive
* licences and weak, file-level copyleft (MPL-2.0) are fine; network
* copyleft (AGPL), source-available terms (SSPL, BUSL, Commons Clause),
* a missing or custom licence (`UNLICENSED`, `SEE LICENSE IN …`) are not.
*
* Anything outside the lists fails the run until a person looks at it — the
* point is that a new licence enters the tree through a reviewed change to
* this file, never unnoticed through a Dependabot bump. `EXCEPTIONS` is that
* reviewed change for one package, with its reason.
*
* The `license` value is self-declared by each package and copied verbatim by
* npm; this gate trusts it, as every lockfile-based checker must. It needs no
* `node_modules` and no network, so it runs before anything is installed.
*
* Usage: node scripts/check-licenses.mjs — reads <repo>/package-lock.json and
* <repo>/tools/publish/package-lock.json (the store-upload tool, docs/12 §3),
* resolved from this file. Its tests call `checkLockfile(lock)` directly.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { CREDITED_PACKAGES } from './credited-packages.mjs';
/** Permissive licences that may ship inside a GPL-3.0-or-later extension. */
export const SHIPPED_LICENSES = Object.freeze([
'0BSD',
'Apache-2.0',
'BSD-2-Clause',
'BSD-3-Clause',
'ISC',
'MIT',
'MIT-0',
]);
/** Licences accepted for build and test tooling, which never ships. */
export const TOOLCHAIN_LICENSES = Object.freeze([
...SHIPPED_LICENSES,
'BlueOak-1.0.0',
'CC-BY-4.0',
'CC0-1.0',
'MPL-2.0',
'Python-2.0',
'Unlicense',
'Zlib',
]);
/**
* Packages accepted despite the lists above: `name → reason`. Empty on
* purpose; an entry is a decision, recorded in docs/15's decision log.
* @type {Readonly<Record<string, string>>}
*/
export const EXCEPTIONS = Object.freeze({});
/**
* Whether an SPDX licence expression is satisfied by the allowed identifiers.
* `A OR B` needs either side, `A AND B` both; parentheses group; `A WITH X`
* (a licence exception) is judged by `A`. Anything unparseable is refused.
*
* @param {string} expression
* @param {readonly string[]} allowed
* @returns {boolean}
*/
export function satisfies(expression, allowed) {
const tokens = expression.match(/\(|\)|[^\s()]+/g) ?? [];
let at = 0;
/** @returns {boolean} */
const parseOr = () => {
let ok = parseAnd();
while (tokens[at] === 'OR') {
at++;
const right = parseAnd();
ok = ok || right;
}
return ok;
};
/** @returns {boolean} */
const parseAnd = () => {
let ok = parseTerm();
while (tokens[at] === 'AND') {
at++;
const right = parseTerm();
ok = ok && right;
}
return ok;
};
/** @returns {boolean} */
const parseTerm = () => {
const token = tokens[at++];
if (token === '(') {
const ok = parseOr();
if (tokens[at++] !== ')') throw new SyntaxError('unbalanced parentheses');
return ok;
}
if (token === undefined || token === ')' || token === 'AND' || token === 'OR') {
throw new SyntaxError('expected a licence identifier');
}
if (tokens[at] === 'WITH') at += 2;
return allowed.includes(token);
};
try {
const ok = parseOr();
return at === tokens.length && tokens.length > 0 && ok;
} catch {
return false;
}
}
/**
* The package name a lockfile key installs: the part after the last
* `node_modules/`, scope included.
* @param {string} key
*/
export function packageNameOf(key) {
const at = key.lastIndexOf('node_modules/');
return at === -1 ? key : key.slice(at + 'node_modules/'.length);
}
/**
* Lockfile text is our own committed file, but it is still file content: keep
* what reaches the log to the characters package names and SPDX ids use.
* @param {unknown} value
*/
function printable(value) {
return String(value)
.replaceAll(/[^\w@/.+() -]/g, '?')
.slice(0, 120);
}
/**
* Check every installed package of a v2/v3 lockfile.
*
* @param {unknown} lock - the parsed `package-lock.json`
* @param {{ shipsCode?: boolean }} [options] - `shipsCode: false` for a lockfile
* that builds nothing into the extension (tools/publish), where the credited
* packages are not expected
* @returns {{ problems: string[], checked: number, counts: Map<string, number> }}
*/
export function checkLockfile(lock, options = {}) {
const shipsCode = options.shipsCode ?? true;
/** @type {string[]} */
const problems = [];
/** @type {Map<string, number>} */
const counts = new Map();
const packages =
typeof lock === 'object' && lock !== null && 'packages' in lock ? lock.packages : undefined;
if (typeof packages !== 'object' || packages === null) {
return { problems: ['no "packages" map — lockfile v2 or v3 expected'], checked: 0, counts };
}
const shippedSeen = new Set();
let checked = 0;
for (const [key, raw] of Object.entries(packages)) {
// The root project (key "") and workspace links carry no install of their own.
if (key === '' || !key.includes('node_modules/')) continue;
if (typeof raw === 'object' && raw !== null && 'link' in raw && raw.link === true) continue;
checked++;
const name = packageNameOf(key);
const license =
typeof raw === 'object' && raw !== null && 'license' in raw ? raw.license : undefined;
const label = typeof license === 'string' ? license : '(none)';
counts.set(label, (counts.get(label) ?? 0) + 1);
const shipped = CREDITED_PACKAGES.includes(name);
if (shipped) shippedSeen.add(name);
if (Object.hasOwn(EXCEPTIONS, name)) continue;
const allowed = shipped ? SHIPPED_LICENSES : TOOLCHAIN_LICENSES;
if (typeof license !== 'string' || !satisfies(license, allowed)) {
problems.push(
`${printable(key)}: licence "${printable(label)}" is not accepted for ` +
(shipped ? 'code that ships in the extension' : 'build tooling'),
);
}
}
for (const name of shipsCode ? CREDITED_PACKAGES : []) {
if (!shippedSeen.has(name)) {
problems.push(`${printable(name)}: credited as shipping, but not in the lockfile`);
}
}
return { problems, checked, counts };
}
/** The lockfiles this repository installs from, and whether each builds the extension. */
const LOCKFILES = [
{ path: 'package-lock.json', shipsCode: true },
{ path: 'tools/publish/package-lock.json', shipsCode: false },
];
/** @returns {number} exit code */
function main() {
const repo = resolve(fileURLToPath(import.meta.url), '..', '..');
/** @type {string[]} */
const problems = [];
let checked = 0;
/** @type {Map<string, number>} */
const counts = new Map();
for (const { path, shipsCode } of LOCKFILES) {
/** @type {unknown} */
let lock;
try {
lock = JSON.parse(readFileSync(resolve(repo, path), 'utf8'));
} catch (cause) {
console.error(`::error::check-licenses: cannot read ${path} (${String(cause)})`);
return 1;
}
const result = checkLockfile(lock, { shipsCode });
for (const problem of result.problems) problems.push(`${path}: ${problem}`);
checked += result.checked;
for (const [license, n] of result.counts) counts.set(license, (counts.get(license) ?? 0) + n);
}
if (problems.length > 0) {
for (const problem of problems) console.error(`::error::check-licenses: ${problem}`);
console.error(
'\nSee docs/09 §3.2: add the licence to a list, or an EXCEPTIONS entry, on purpose.',
);
return 1;
}
const summary = [...counts]
.sort((a, b) => b[1] - a[1])
.map(([license, n]) => `${printable(license)} ${n}`)
.join(', ');
console.warn(`check-licenses: clean — ${checked} packages (${summary}).`);
return 0;
}
// Run only as the entry point (same guard as check-manifest.mjs).
const isEntry =
import.meta.url.startsWith('file:') &&
process.argv[1] !== undefined &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isEntry) {
// exitCode, not exit(): exit() can cut off piped stderr before CI reads it.
process.exitCode = main();
}
+9
View File
@@ -0,0 +1,9 @@
/**
* Types for scripts/check-manifest.mjs, so its tests can call it directly.
* The script itself is plain JavaScript checked with `// @ts-check`.
*/
export const TARGETS: Record<string, { dir: string; keys: string[]; label: string }>;
export function checkExtension(
outDir: string,
target?: string,
): { problems: string[]; readError?: string };
+355
View File
@@ -0,0 +1,355 @@
// @ts-check
/**
* Assert the BUILT extension — CLAUDE.md hard rule 1, docs/08 §2–§3.
*
* `tests/unit/manifest.test.ts` reads `wxt.config.ts`, which proves what we
* ASKED for. It cannot prove what WXT emitted, and those differ: a dev build of
* this exact config produces
* "permissions": ["bookmarks","storage","tabs","scripting"]
* "host_permissions": ["http://localhost/*"]
* because WXT injects them for its dev server. So the shipped artifact gets its
* own gate, run after `npm run build` (or `npm run zip`):
*
* 1. the manifest: MV3, the exact permission list, the exact top-level key
* set, the Chrome floor, and the exact extension-page CSP;
* 2. the file inventory: every file the manifest or the pages point at exists
* (WXT drops `_locales/` and `icon/` silently when publicDir is wrong),
* and no page points anywhere but inside the package;
* 3. the bundle: none of the network identifiers `npm run guard` bans in the
* source, anywhere in the shipped JavaScript.
*
* Usage: node scripts/check-manifest.mjs [--browser chrome|firefox] — checks
* <repo>/.output/chrome-mv3 (the default) or <repo>/.output/firefox-mv3 (since
* v1.3.0, docs/08 §9), resolved from this file, not the cwd. It takes no path:
* one from the command line flowed straight into file reads (SonarCloud
* S8707), so `--browser` only picks an entry of a fixed table. Its tests call
* `checkExtension(dir, target)` directly instead.
*/
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
/** Exactly this, in any order. Adding one is a minor-version event (docs/09 §4). */
const ALLOWED_PERMISSIONS = ['bookmarks', 'storage'];
/** The ES2025 floor (docs/01 §1). Must equal CHROME_FLOOR in wxt.config.ts. */
const CHROME_FLOOR = '136';
/**
* The production extension-page CSP (docs/08 §3), character for character.
* It may only ever get stricter. Never add 'unsafe-eval' or a remote source.
*/
const EXPECTED_CSP =
"default-src 'none'; script-src 'self'; object-src 'none'; connect-src 'none'; " +
"img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self'; " +
"media-src 'none'; frame-src 'none'; worker-src 'self'; form-action 'none'; base-uri 'none'";
/**
* The exact top-level key set the build is expected to emit.
*
* The forbidden list below can only catch reach-widening keys someone thought
* to enumerate. This catches the other direction — a build tool that starts
* emitting a key nobody asked for, or stops emitting one the store requires.
* WXT is a 0.x dependency, so a routine minor bump is exactly when that
* happens. `version_name` would appear if package.json ever carried a
* prerelease version (WXT splits it out); release versions never do.
*
* Adding a key here is a deliberate act. Check docs/08 §1 first.
*/
/** @param {string} a @param {string} b */
const byName = (a, b) => a.localeCompare(b, 'en');
const COMMON_KEYS = [
'action',
'content_security_policy',
'default_locale',
'description',
'homepage_url',
'icons',
'manifest_version',
'name',
'options_ui',
'permissions',
'version',
];
/**
* Firefox's block, exactly (docs/08 §9). The id is permanent once on AMO; the
* floor is the first Firefox that accepts `data_collection_permissions`.
*/
const FIREFOX_SETTINGS = {
gecko: {
id: 'bookmarkmagic@poli0981.dev',
strict_min_version: '140.0',
data_collection_permissions: { required: ['none'] },
},
};
/**
* The two packages (docs/08 §1): where each is built, its exact key set, and
* how its floor reads in the log. Edge Add-ons takes the Chrome package.
*
* @type {Record<string, { dir: string, keys: string[], label: string }>}
*/
export const TARGETS = {
chrome: {
dir: 'chrome-mv3',
keys: [...COMMON_KEYS, 'minimum_chrome_version'].sort(byName),
label: `Chrome ≥${CHROME_FLOOR}`,
},
firefox: {
dir: 'firefox-mv3',
keys: [...COMMON_KEYS, 'browser_specific_settings'].sort(byName),
label: 'Firefox ≥140, gecko id pinned',
},
};
/**
* A value's JSON with object keys sorted, so key order never decides equality.
* @param {unknown} value
* @returns {string}
*/
function canonical(value) {
if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;
if (value !== null && typeof value === 'object') {
const entries = Object.entries(value).sort(([a], [b]) => byName(a, b));
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;
}
return JSON.stringify(value) ?? 'undefined';
}
/** Keys that would widen the extension's reach. None may be present. */
const FORBIDDEN_KEYS = [
'host_permissions',
'optional_permissions',
'optional_host_permissions',
'content_scripts',
'background',
'web_accessible_resources',
'externally_connectable',
'declarative_net_request',
'devtools_page',
'chrome_url_overrides',
];
/** Files every build must contain besides what the manifest references. */
const REQUIRED_FILES = [
'manager.html',
'popup.html',
// The MIT notices for the code the build compiles in (legal/THIRD_PARTY_NOTICES.md).
'THIRD_PARTY_NOTICES.txt',
'_locales/en/messages.json',
'_locales/vi/messages.json',
'_locales/ja/messages.json',
'_locales/zh_CN/messages.json',
'_locales/ro/messages.json',
];
/**
* Network APIs that must not appear in the shipped JavaScript — including code
* that arrived through a dependency, which `npm run guard` (source only) never
* sees. The same identifiers the source gate bans, matched as bare words: until
* v1.1.0 only `fetch(` counted, so `fetch.call(…)`, an alias, WebRTC and
* `importScripts` shipped unseen. WebRTC matters most — no CSP directive Chrome
* enforces governs it.
*/
const NETWORK_IN_BUNDLE =
/\b(?:fetch|XMLHttpRequest|WebSocket|WebTransport|EventSource|sendBeacon|(?:webkit|moz)?RTCPeerConnection|importScripts)\b/;
/** `src`/`href` values in a built page. Vite writes them double-quoted. */
const PAGE_REFS = /\b(?:src|href)="([^"]*)"/g;
/** @param {string} dir @returns {string[]} */
function listFiles(dir) {
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const full = join(dir, entry.name);
return entry.isDirectory() ? listFiles(full) : [full];
});
}
/**
* @param {string} outDir
* @returns {Record<string, unknown> | string} the manifest, or why it could not be read
*/
function readManifest(outDir) {
try {
return JSON.parse(readFileSync(join(outDir, 'manifest.json'), 'utf8'));
} catch (cause) {
return `cannot read manifest.json (${cause instanceof Error ? cause.message : cause})`;
}
}
/**
* @param {Record<string, unknown>} manifest
* @param {string[]} problems
* @param {string} target - a key of TARGETS
*/
function checkManifest(manifest, problems, target) {
const expectedKeys = TARGETS[target]?.keys ?? [];
if (manifest.manifest_version !== 3) {
problems.push(`manifest_version is ${manifest.manifest_version}, expected 3`);
}
const permissions = Array.isArray(manifest.permissions) ? manifest.permissions : [];
const actualPermissions = [...permissions].sort(byName).join(',');
if (actualPermissions !== [...ALLOWED_PERMISSIONS].sort(byName).join(',')) {
problems.push(
`permissions are ${JSON.stringify(manifest.permissions)}, expected ${JSON.stringify(ALLOWED_PERMISSIONS)}`,
);
}
for (const key of FORBIDDEN_KEYS) {
if (key in manifest) problems.push(`declares "${key}": ${JSON.stringify(manifest[key])}`);
}
const actualKeys = Object.keys(manifest);
const unexpected = actualKeys.filter((key) => !expectedKeys.includes(key)).sort(byName);
const missing = expectedKeys.filter((key) => !actualKeys.includes(key));
if (unexpected.length > 0) {
problems.push(`unexpected top-level key(s): ${unexpected.join(', ')} — see docs/08 §1`);
}
if (missing.length > 0) problems.push(`missing expected top-level key(s): ${missing.join(', ')}`);
if (target === 'firefox') {
if (canonical(manifest.browser_specific_settings) !== canonical(FIREFOX_SETTINGS)) {
problems.push(
`browser_specific_settings is ${JSON.stringify(manifest.browser_specific_settings)}, expected exactly ${JSON.stringify(FIREFOX_SETTINGS)} (docs/08 §9)`,
);
}
} else if (manifest.minimum_chrome_version !== CHROME_FLOOR) {
problems.push(
`minimum_chrome_version is ${JSON.stringify(manifest.minimum_chrome_version)}, expected "${CHROME_FLOOR}" (docs/01 §1)`,
);
}
const csp = /** @type {{ extension_pages?: unknown } | undefined} */ (
manifest.content_security_policy
);
if (csp?.extension_pages !== EXPECTED_CSP || Object.keys(csp).length !== 1) {
problems.push(
`content_security_policy is ${JSON.stringify(csp)}, expected exactly { extension_pages: "${EXPECTED_CSP}" } (docs/08 §3)`,
);
}
}
/** @param {Record<string, unknown>} manifest @returns {string[]} */
function referencedFiles(manifest) {
const icons = /** @type {Record<string, string>} */ (manifest.icons ?? {});
const action = /** @type {{ default_popup?: string }} */ (manifest.action ?? {});
const options = /** @type {{ page?: string }} */ (manifest.options_ui ?? {});
return [...Object.values(icons), action.default_popup, options.page?.split('#')[0]].filter(
(p) => typeof p === 'string',
);
}
/**
* What the built pages load: every `src`/`href` must be a path inside the
* package. A page pointing outside it would be a remote load (which the CSP
* refuses at runtime) or a file the build forgot (a blank page).
*
* @param {string} outDir @param {string[]} problems @returns {string[]}
*/
function pageReferences(outDir, problems) {
const refs = [];
for (const page of listFiles(outDir).filter((f) => f.endsWith('.html'))) {
const rel = relative(outDir, page).replace(/\\/g, '/');
for (const [, ref = ''] of readFileSync(page, 'utf8').matchAll(PAGE_REFS)) {
if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(ref)) {
problems.push(`${rel} loads "${ref}" from outside the package (docs/08 §3)`);
} else if (ref !== '' && !ref.startsWith('#')) {
refs.push(ref.split(/[?#]/)[0] ?? '');
}
}
}
return refs;
}
/** @param {string} outDir @param {Record<string, unknown>} manifest @param {string[]} problems */
function checkInventory(outDir, manifest, problems) {
const files = [
...REQUIRED_FILES,
...referencedFiles(manifest),
...pageReferences(outDir, problems),
];
for (const file of new Set(files)) {
const path = join(outDir, file.replace(/^\//, ''));
if (!existsSync(path)) problems.push(`missing file in the build: ${file}`);
}
}
/** @param {string} outDir @param {string[]} problems */
function checkBundle(outDir, problems) {
for (const file of listFiles(outDir).filter((f) => f.endsWith('.js'))) {
const match = readFileSync(file, 'utf8').match(NETWORK_IN_BUNDLE);
if (match) {
const rel = relative(outDir, file).replace(/\\/g, '/');
problems.push(`network API "${match[0]}" in the shipped bundle: ${rel} (docs/08 §3)`);
}
}
}
/**
* Check one built extension directory.
*
* @param {string} outDir
* @param {string} [target] - a key of TARGETS; `chrome` when omitted
* @returns {{ problems: string[], readError?: string }} no problems and no read
* error means the build is clean
*/
export function checkExtension(outDir, target = 'chrome') {
if (!Object.hasOwn(TARGETS, target)) {
return { problems: [], readError: `unknown target "${target}"` };
}
const manifest = readManifest(outDir);
if (typeof manifest === 'string') return { problems: [], readError: manifest };
/** @type {string[]} */
const problems = [];
checkManifest(manifest, problems, target);
checkInventory(outDir, manifest, problems);
checkBundle(outDir, problems);
return { problems };
}
/** @returns {number} the exit code */
function main() {
const flag = process.argv.indexOf('--browser');
const target = flag === -1 ? 'chrome' : (process.argv[flag + 1] ?? '');
const profile = Object.hasOwn(TARGETS, target) ? TARGETS[target] : undefined;
if (profile === undefined) {
console.error(`check-manifest: --browser must be one of ${Object.keys(TARGETS).join(', ')}`);
return 1;
}
const repo = resolve(fileURLToPath(new URL('..', import.meta.url)));
// The directory comes from the table, never from the command line.
const { problems, readError } = checkExtension(join(repo, '.output', profile.dir), target);
if (readError !== undefined) {
const build = target === 'chrome' ? 'npm run build' : `npm run build:${target}`;
console.error(`check-manifest: ${readError} — run \`${build}\` first.`);
return 1;
}
if (problems.length > 0) {
for (const problem of problems) {
console.error(`::error::check-manifest: ${problem}`);
console.error(` ${problem}`);
}
console.error('\nSee CLAUDE.md hard rule 1 and docs/09 §4 before changing this.');
return 1;
}
// Constants only: the manifest has just passed every check, so its values ARE
// these — and nothing read from a file is echoed into the log.
console.warn(
`check-manifest: clean (${target}) — MV3, permissions exactly ${ALLOWED_PERMISSIONS.join(' + ')}, ${profile.label}, CSP pinned, inventory complete, no network API in the bundle.`,
);
return 0;
}
// Run only as the entry point. Under a test runner `import.meta.url` may not
// even be a file: URL, so it is not resolved until it is known to be one.
const isEntry =
import.meta.url.startsWith('file:') &&
process.argv[1] !== undefined &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isEntry) {
// exitCode, not exit(): exit() can cut off piped stderr before CI reads it.
process.exitCode = main();
}
+5
View File
@@ -0,0 +1,5 @@
/**
* Types for scripts/credited-packages.mjs, so `wxt.config.ts` and the tests can
* import the list. The script itself is plain JavaScript checked with `// @ts-check`.
*/
export const CREDITED_PACKAGES: readonly string[];
+17
View File
@@ -0,0 +1,17 @@
// @ts-check
/**
* The npm packages whose code the build compiles into the extension — docs/14 §5.
*
* One list behind three gates, so none of them can drift from the others:
* - `wxt.config.ts` fails the build when code from any other package ships;
* - `tests/unit/third-party.test.ts` requires both notices files to credit
* every package named here;
* - `scripts/check-licenses.mjs` holds each of them to the licences that may
* travel inside a GPL-3.0-or-later extension.
*
* Through v1.0.x the notices said "none" while three of these shipped. Adding
* a name here is the first step of shipping a new package, never the last:
* its licence text goes into `legal/THIRD_PARTY_NOTICES.md` and
* `src/public/THIRD_PARTY_NOTICES.txt` in the same pull request.
*/
export const CREDITED_PACKAGES = Object.freeze(['svelte', 'clsx', '@wxt-dev/browser', 'wxt']);
+165
View File
@@ -0,0 +1,165 @@
#!/usr/bin/env node
// @ts-check
/**
* Generate a large Netscape bookmark file on demand.
*
* Purpose: make the two measurements docs/11 asks for actually runnable — the
* 10 000-node responsiveness item in §5, and the 100 000-node parse budget in
* §6 that has only ever been measured under jsdom.
* Inputs: a node count and an output path.
* Guarantees: exactly `--nodes` nodes (folders + bookmarks), valid Netscape
* HTML, deterministic for a given seed — so two runs are comparable.
*
* docs/11 §2 named a `generate-huge.ts` for this and `.gitignore` has always
* reserved `tests/fixtures/generated/` for its output, but the script itself was
* never written, which is why the 2 s budget stayed unmeasured (docs/00 §10.8).
*
* Usage:
* node scripts/gen-fixture.mjs --nodes 10000 --out tests/fixtures/generated/big.html
* node scripts/gen-fixture.mjs --nodes 100000 --per-folder 100 --seed 7 --out …
*/
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
/**
* Mulberry32 — small, seeded, and good enough for shaping test data.
* @param {number} seed
*/
function rng(seed) {
let a = seed >>> 0;
return () => {
a = (a + 0x6d2b79f5) >>> 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const USAGE =
'usage: node scripts/gen-fixture.mjs --nodes <n> --out <path> [--per-folder <n>] [--seed <n>]';
/**
* Strict flags: whole numbers >= 1, every flag needs a value, no unknown flags.
* The old reader took arguments in blind pairs, so `--nodes 1.5` wrote 2 nodes,
* `--per-folder abc` silently wrote no bookmarks, and one missing value shifted
* every flag after it.
*
* @param {string[]} argv
* @returns {{ nodes: number, perFolder: number, seed: number, out: string } | string}
* the options, or an error message
*/
function parseArgs(argv) {
const out = { nodes: 10_000, perFolder: 50, seed: 1, out: '' };
/** @type {Record<string, 'nodes' | 'perFolder' | 'seed'>} */
const numeric = { '--nodes': 'nodes', '--per-folder': 'perFolder', '--seed': 'seed' };
for (let i = 0; i < argv.length; i += 2) {
const flag = argv[i] ?? '';
const value = argv[i + 1];
if (value === undefined || value.startsWith('--')) return `${flag} needs a value`;
if (flag === '--out') {
out.out = value;
continue;
}
const key = numeric[flag];
if (key === undefined) return `unknown flag ${flag}`;
const n = Number(value);
if (!Number.isInteger(n) || n < 1) return `${flag} must be a whole number >= 1, got "${value}"`;
out[key] = n;
}
return out.out === '' ? '--out is required' : out;
}
/**
* Titles that exercise the escaping path, not just ASCII.
*
* A 100k file of `Bookmark 1..n` would measure string concatenation and nothing
* else; entities, CJK and emoji are what the parser actually spends time on.
*/
const TITLE_POOL = [
'Example bookmark',
'Quotes &quot;here&quot;',
'Ampersand &amp; more',
'Angle &lt;brackets&gt;',
'ブックマーク',
'Thư mục quan trọng',
'🌸 emoji title',
'A rather long bookmark title that wraps in most reasonable window widths',
];
/**
* @param {{ nodes: number, perFolder: number, seed: number }} options
* @returns {string}
*/
function build({ nodes, perFolder, seed }) {
const rand = rng(seed);
const lines = [
'<!DOCTYPE NETSCAPE-Bookmark-file-1>',
'<!-- Generated by scripts/gen-fixture.mjs — not a real export. -->',
'<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">',
'<TITLE>Bookmarks</TITLE>',
'<H1>Bookmarks</H1>',
'<DL><p>',
];
let folderIndex = 0;
/** @param {number} depth */
const indent = (depth) => ' '.repeat(depth);
/**
* Write one folder (and, below depth 3, one nested folder chain) using at
* most `budget` nodes. Returns how many it wrote — always at least 1, so the
* caller's loop provably makes progress.
*
* @param {number} depth
* @param {number} written nodes written before this call
* @param {number} budget nodes this call may write
* @returns {number}
*/
const emitFolder = (depth, written, budget) => {
folderIndex++;
const stamp = 1700000000 + folderIndex;
lines.push(
`${indent(depth)}<DT><H3 ADD_DATE="${stamp}" LAST_MODIFIED="${stamp + 1}"${
folderIndex === 1 ? ' PERSONAL_TOOLBAR_FOLDER="true"' : ''
}>Folder ${folderIndex}</H3>`,
`${indent(depth)}<DL><p>`,
);
let used = 1;
const count = Math.min(perFolder, budget - used);
for (let i = 0; i < count; i++) {
const n = written + used;
const title = TITLE_POOL[Math.floor(rand() * TITLE_POOL.length)];
lines.push(
`${indent(depth + 1)}<DT><A HREF="https://host${n % 997}.example/p${n}?q=${n}" ` +
`ADD_DATE="${1700000000 + n}">${title}</A>`,
);
used++;
}
// Depth 3 so the walk is exercised, but nowhere near the 200 cap — this
// file is for measuring the common case, not the limit.
if (depth < 3 && used < budget) used += emitFolder(depth + 1, written + used, budget - used);
lines.push(`${indent(depth)}</DL><p>`);
return used;
};
let written = 0;
while (written < nodes) written += emitFolder(1, written, nodes - written);
lines.push('</DL><p>', '');
return lines.join('\n');
}
const options = parseArgs(process.argv.slice(2));
if (typeof options === 'string') {
console.error(`gen-fixture: ${options}
${USAGE}`);
process.exitCode = 1;
} else {
const html = build(options);
mkdirSync(dirname(options.out), { recursive: true });
writeFileSync(options.out, html);
const mb = (Buffer.byteLength(html) / 1024 / 1024).toFixed(1);
console.error(`wrote ${options.out} — ${options.nodes} nodes, ${mb} MB`);
}
+29 -10
View File
@@ -1,20 +1,28 @@
// @ts-check
/**
* Generate placeholder extension icons — a rounded violet square with a white
* bookmark ribbon — at the four sizes Chrome needs. Zero dependencies: PNG is
* written by hand (zlib deflate + a CRC32 table), so no image library enters
* the tree.
* Generate the extension icons — a rounded violet square with a white bookmark
* ribbon — at the four sizes Chrome needs. Zero dependencies: PNG is written by
* hand (zlib deflate + a CRC32 table), so no image library enters the tree.
*
* These are functional placeholders so the manifest loads from Phase 0.
* Replace with the designed icon before a store release (docs/00 §10 item 3,
* docs/13 §2). Run: `npm run icons`.
* THIS SCRIPT IS THE SOURCE OF TRUTH for the shipped icons: the owner adopted
* its output as final on 2026-07-26 (docs/00 §10 item 3). There is no other
* master file. `npm run icons` overwrites src/public/icon/*.png — review the
* diff before committing, because those PNGs are what the store listing shows.
*/
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { deflateSync } from 'node:zlib';
const ACCENT = [0x6d, 0x4a, 0xff, 255]; // --accent, docs/06 §1
/** @typedef {readonly [number, number, number, number]} Rgba */
/** @type {Rgba} */
// The 1.0 brand violet. Deliberately NOT re-derived from --accent (now #6447f0,
// docs/06 §1): the toolbar and store icon stay the one users already know.
const ACCENT = [0x6d, 0x4a, 0xff, 255];
/** @type {Rgba} */
const WHITE = [255, 255, 255, 255];
/** @type {Rgba} */
const TRANSPARENT = [0, 0, 0, 0];
const CRC_TABLE = (() => {
@@ -27,12 +35,14 @@ const CRC_TABLE = (() => {
return table;
})();
/** @param {Uint8Array} buf */
function crc32(buf) {
let c = 0xffffffff;
for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
for (const byte of buf) c = (CRC_TABLE[(c ^ byte) & 0xff] ?? 0) ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
/** @param {string} type @param {Buffer} data */
function chunk(type, data) {
const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
const len = Buffer.alloc(4);
@@ -42,6 +52,7 @@ function chunk(type, data) {
return Buffer.concat([len, body, crc]);
}
/** @param {number} x @param {number} y @param {number} size @param {number} radius */
function insideRounded(x, y, size, radius) {
const px = x + 0.5;
const py = y + 0.5;
@@ -50,7 +61,10 @@ function insideRounded(x, y, size, radius) {
return dx * dx + dy * dy <= radius * radius;
}
/** Bookmark ribbon: a tall rectangle with a triangular notch cut from the bottom. */
/**
* Bookmark ribbon: a tall rectangle with a triangular notch cut from the bottom.
* @param {number} x @param {number} y @param {number} size
*/
function insideBookmark(x, y, size) {
const u = (x + 0.5) / size;
const v = (y + 0.5) / size;
@@ -64,12 +78,17 @@ function insideBookmark(x, y, size) {
return true;
}
/**
* @param {number} x @param {number} y @param {number} size
* @returns {Rgba}
*/
function colorAt(x, y, size) {
if (!insideRounded(x, y, size, size * 0.2)) return TRANSPARENT;
if (insideBookmark(x, y, size)) return WHITE;
return ACCENT;
}
/** @param {number} size */
function makePng(size) {
const stride = size * 4;
const raw = Buffer.alloc((stride + 1) * size);
+222 -51
View File
@@ -1,51 +1,167 @@
// @ts-check
/**
* The canonical grep gate — docs/08_MV3_COMPLIANCE.md §3.
* The zero-network / no-raw-HTML gate — docs/08 §3.
*
* This file is the single implementation of that pattern. It runs both locally
* (`npm run verify`) and in CI (`npm run guard`), so the gate cannot drift
* between the two. Zero dependencies, Node stdlib only.
* This file IS the rule set; docs/08 §3 points here instead of restating it,
* because two copies of a security pattern drift (they did: the doc's
* `\{@html\}` matched only the literal `{@html}`, never `{@html x}`).
*
* Why a grep and not a lint rule: MV3's default CSP blocks remote code, but it
* has no connect-src at all and does not restrict network egress. And no Biome
* rule sees Svelte's {@html} — noDangerouslySetInnerHtml is a React rule. This
* script plus review is the entire enforcement of the zero-network and
* no-raw-HTML promises.
* It runs locally (`npm run verify`) and in CI (`npm run guard`), so the gate
* cannot differ between the two. Zero dependencies, Node stdlib only.
*
* It is no longer the ONLY enforcement: since v1.1.0 the production manifest
* declares a CSP with `connect-src 'none'` (docs/08 §3), so the browser itself
* refuses fetch/XHR/WebSocket/EventSource/beacons. This gate catches the rest —
* raw HTML sinks, code execution, remote resources in markup and CSS — and
* keeps network code out of review in the first place.
*
* Matching runs over the WHOLE file, not line by line, so `\s*` spans newlines
* and splitting a call across two lines no longer gets past a rule. Identifiers
* are banned outright where an alias would otherwise slip through
* (`const go = fetch; go(u)`), which means the bare words are banned in
* comments too — write "network call", not the API name, in prose.
*
* Usage: node scripts/guard.mjs [--root <dir>] (--root is for its own tests)
*/
import { readFileSync } from 'node:fs';
import { readdir } from 'node:fs/promises';
import { extname, join, relative } from 'node:path';
import { extname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* fileURLToPath, never `new URL(...).pathname`: the pathname stays
* percent-encoded, so a checkout under `C:\Users\Nguyễn\…` or `my dir` became a
* path that does not exist — and the walker reported "clean" after scanning
* nothing.
*/
const DEFAULT_ROOT = fileURLToPath(new URL('..', import.meta.url));
const ROOT = new URL('..', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1');
const SCAN_DIRS = ['src'];
const SCAN_EXTS = new Set(['.ts', '.js', '.mjs', '.svelte']);
const SCAN_EXTS = new Set([
'.ts',
'.mts',
'.cts',
'.js',
'.mjs',
'.cjs',
'.svelte',
'.html',
'.css',
]);
const SKIP_DIRS = new Set(['node_modules', '.output', '.wxt', '.git']);
/** Each entry: [human-readable name, pattern]. Keep in sync with docs/08 §3. */
const BANNED = [
['network: fetch', /\bfetch\s*\(/],
['network: XMLHttpRequest', /\bXMLHttpRequest\b/],
['network: WebSocket', /\bWebSocket\b/],
['network: EventSource', /\bEventSource\b/],
['network: sendBeacon', /\bsendBeacon\b/],
['remote code: eval', /\beval\s*\(/],
['remote code: new Function', /\bnew\s+Function\s*\(/],
['remote code: dynamic import', /(^|[^.\w])import\s*\(/],
['raw HTML: {@html}', /\{@html\b/],
['raw HTML: innerHTML assignment', /\b(?:inner|outer)HTML\s*=/],
['raw HTML: insertAdjacentHTML', /\binsertAdjacentHTML\b/],
/** A URL that leaves the extension: `https://`, `http://` or protocol-relative `//`. */
const REMOTE = String.raw`(?:https?:)?\/\/`;
/**
* [category, name, pattern, refine?]. Every pattern carries the `g` flag and is
* run over the whole file; when `refine` is present, a match only counts if
* `refine` also matches the matched text. Each rule has a positive and a
* negative case in tests/unit/scripts/guard.test.ts — add both when adding one.
*
* No pattern may let two quantifiers compete for the same characters (a
* `\s*` beside an optional quote beside another `\s*`): that backtracks
* polynomially (SonarCloud S8786), and this script scans whatever lands in src/.
*/
const RULES = [
// Network. Identifiers, not call shapes: aliasing, tagged templates and
// `.call()` all start with the bare name.
['network', 'fetch', /\bfetch\b/g],
['network', 'XMLHttpRequest', /\bXMLHttpRequest\b/g],
['network', 'WebSocket', /\bWebSocket\b/g],
['network', 'WebTransport', /\bWebTransport\b/g],
['network', 'EventSource', /\bEventSource\b/g],
['network', 'sendBeacon', /\bsendBeacon\b/g],
// Prefixed aliases too: no word boundary separates `webkit` from `RTC`, and
// Chrome still ships `webkitRTCPeerConnection` as the same constructor.
['network', 'RTCPeerConnection', /\b(?:webkit|moz)?RTCPeerConnection\b/g],
['network', 'importScripts', /\bimportScripts\b/g],
// `globalThis['fe' + 'tch']` — computed access on a global is how every
// identifier rule above is evaded, so it is banned as a shape, optional
// chaining included (`globalThis?.['fe' + 'tch']` got through until v1.1.0).
[
'network',
'computed global access',
/\b(?:globalThis|window|self|navigator|document)(?:\s*\?\.)?\s*\[/g,
],
// Resource hints fetch ahead of time. These words have no use in this
// extension, so they are banned outright; `preload` is ordinary English, so
// only as a rel value.
[
'network',
'resource hint',
/\b(?:prefetch|preconnect|prerender|dns-prefetch|modulepreload)\b|\brel\s*=\s*["'`]?preload\b/gi,
],
// Two linear steps: find a resource-loading tag, then look inside it.
[
'network',
'remote resource in markup',
/<(?:img|script|iframe|frame|link|source|video|audio|embed|object|track|image)\b[^>]*>/gi,
new RegExp(String.raw`\b(?:src|href|srcset|data|poster)\s*=\s*(?:["'{]\s*)?` + REMOTE, 'i'),
],
['network', 'remote url() in CSS', new RegExp(String.raw`url\(\s*(?:["']\s*)?` + REMOTE, 'gi')],
[
'network',
'remote @import',
new RegExp(String.raw`@import\s+(?:url\(\s*)?(?:["']\s*)?` + REMOTE, 'gi'),
],
// Remote code.
['remote code', 'eval', /\beval\b/g],
['remote code', 'Function constructor', /\bFunction\s*\(/g],
['remote code', 'string timer', /\bset(?:Timeout|Interval)\s*\(\s*["'`]/g],
// `[ \t]*`, not `\s*`: prose that ends a line with "import" and opens the
// next with "(" is common in comments, and the MV3 CSP already refuses any
// remote script, so this rule is a second line of defence, not the only one.
['remote code', 'dynamic import', /(?:^|[^.\w$])import[ \t]*\(/g],
[
'remote code',
'import from URL',
new RegExp(String.raw`\b(?:from|import)\s+["']` + REMOTE, 'g'),
],
// Raw HTML sinks.
['raw HTML', '{@html}', /\{\s*@html\b/g],
['raw HTML', 'innerHTML / outerHTML', /\b(?:inner|outer)HTML\b/g],
['raw HTML', 'insertAdjacentHTML', /\binsertAdjacentHTML\b/g],
['raw HTML', 'setHTMLUnsafe / parseHTMLUnsafe', /\b(?:set|parse)HTMLUnsafe\b/g],
['raw HTML', 'createContextualFragment', /\bcreateContextualFragment\b/g],
['raw HTML', 'srcdoc', /\bsrcdoc\b/gi],
['raw HTML', 'document.write', /\bdocument\s*\.\s*write(?:ln)?\b/g],
// Evasion. Every rule above matches a NAME; these catch the common ways of
// using a member without writing it. Not all of them — `el[['inner',
// 'HTML'].join('')]` still gets past any pattern — which is why the CSP and
// the built-bundle scan stand behind this gate. `Reflect.get(globalThis, 'fe' + 'tch')`
// and `Reflect.set(el, 'outer' + 'HTML', h)` reach anything, and nothing
// here needs Reflect at all.
['evasion', 'Reflect', /\bReflect\b/g],
// `el['inner' + 'HTML']`, `el?.[`inner${x}`]`: a member name assembled at
// runtime is only ever written to hide it. Only after something a member
// access can follow (an identifier, `)`, `]`, `?.`), so array literals such
// as `[`.${ext}`]` stay allowed.
[
'evasion',
'assembled member name',
/[\w$)\].]\s*\[\s*(?:(?:'[^'\n]*'|"[^"\n]*"|`[^`\n]*`)\s*\+|`[^`\n]*\$\{)/g,
],
];
/** Test files may reference banned identifiers when asserting they are absent. */
const isExempt = (path) => /\.(test|spec)\.ts$/.test(path);
async function* walk(dir) {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return; // directory not created yet — nothing to scan
/** @param {string[]} argv */
function rootFrom(argv) {
const at = argv.indexOf('--root');
if (at === -1) return DEFAULT_ROOT;
const value = argv[at + 1];
if (value === undefined || value.startsWith('--')) {
console.error('guard: --root needs a directory');
process.exit(2);
}
for (const entry of entries) {
return resolve(value);
}
/**
* @param {string} dir
* @returns {AsyncGenerator<string>}
*/
async function* walk(dir) {
for (const entry of await readdir(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
if (!SKIP_DIRS.has(entry.name)) yield* walk(full);
@@ -55,30 +171,85 @@ async function* walk(dir) {
}
}
/**
* Every rule over one file's text.
* @param {string} text
* @returns {{ line: number, name: string, category: string, excerpt: string }[]}
*/
function scan(text) {
const lines = text.split('\n');
const lineStarts = [0];
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) === 0x0a) lineStarts.push(i + 1);
/** @param {number} index */
const lineOf = (index) => {
let lo = 0;
let hi = lineStarts.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if ((lineStarts[mid] ?? 0) <= index) lo = mid;
else hi = mid - 1;
}
return lo + 1;
};
const found = [];
const seen = new Set();
for (const [category, name, pattern, refine] of RULES) {
for (const match of text.matchAll(/** @type {RegExp} */ (pattern))) {
if (refine instanceof RegExp && !refine.test(match[0])) continue;
const line = lineOf(match.index ?? 0);
const key = `${line}\u0000${name}`;
if (seen.has(key)) continue;
seen.add(key);
const excerpt = (lines[line - 1] ?? '').trim().slice(0, 120);
found.push({
line,
name: /** @type {string} */ (name),
category: /** @type {string} */ (category),
excerpt,
});
}
}
return found;
}
const root = rootFrom(process.argv.slice(2));
const violations = [];
let scanned = 0;
for (const dir of SCAN_DIRS) {
for await (const file of walk(join(ROOT, dir))) {
const rel = relative(ROOT, file).replace(/\\/g, '/');
if (isExempt(rel)) continue;
const lines = readFileSync(file, 'utf8').split(/\r?\n/);
lines.forEach((line, i) => {
for (const [name, pattern] of BANNED) {
if (pattern.test(line)) violations.push({ rel, line: i + 1, name, text: line.trim() });
}
});
const base = join(root, dir);
try {
for await (const file of walk(base)) {
scanned++;
const rel = relative(root, file).replace(/\\/g, '/');
const text = readFileSync(file, 'utf8').replace(/\r\n?/g, '\n');
for (const hit of scan(text)) violations.push({ rel, ...hit });
}
} catch (cause) {
// A missing src/ used to be "nothing to scan" and printed clean. A gate
// that cannot see the code has not passed it.
console.error(`guard: cannot scan ${base} — ${cause instanceof Error ? cause.message : cause}`);
process.exitCode = 1;
}
}
if (process.exitCode !== 1 && scanned === 0) {
console.error(`guard: scanned 0 files under ${root} — refusing to report clean.`);
process.exitCode = 1;
}
if (violations.length > 0) {
for (const v of violations) {
console.error(`::error file=${v.rel},line=${v.line}::[${v.name}] ${v.text}`);
console.error(` ${v.rel}:${v.line} ${v.name}\n ${v.text}`);
console.error(`::error file=${v.rel},line=${v.line}::[${v.category}: ${v.name}] ${v.excerpt}`);
console.error(` ${v.rel}:${v.line} ${v.category}: ${v.name}\n ${v.excerpt}`);
}
console.error(
`\nguard: ${violations.length} banned pattern(s) found. See docs/08_MV3_COMPLIANCE.md §3.`,
);
process.exit(1);
console.error(`\nguard: ${violations.length} banned pattern(s). See docs/08 §3.`);
process.exitCode = 1;
}
console.warn(`guard: clean — no banned patterns in ${SCAN_DIRS.join(', ')}`);
if (process.exitCode !== 1) {
console.warn(
`guard: clean — ${scanned} files under ${SCAN_DIRS.join(', ')}, ${RULES.length} rules`,
);
}
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env node
// @ts-check
/**
* Strip personal data from a bookmark file, keeping the bug.
*
* Purpose: make "attach a sanitized sample" (SECURITY.md, the parser issue
* form) something a reporter can actually do, instead of an instruction they
* have to interpret.
* Inputs: a Netscape HTML export, BookmarkMagic JSON, Chrome's profile
* `Bookmarks` file (also Edge/Brave/Vivaldi), a Firefox `.json` backup, or a
* docs/04 §3 CSV.
* Guarantees: every byte outside a replaced address, title or note is untouched
* — the BOM, the doctype, line endings, tag and attribute case, quoting style,
* indentation, JSON key order and escapes, and every timestamp. Replacements
* are stable per distinct input value, so "how many distinct hosts" and
* "which two bookmarks are duplicates" survive. When the output still looks
* personal, nothing is written at all.
*
* Zero dependencies, Node stdlib only, no network, plain JavaScript: it has to
* run from a fresh clone with nothing installed, on whatever Node the reporter
* has. The format modules live in scripts/sanitize/.
*
* Usage:
* node scripts/sanitize-bookmarks.mjs <input> [output]
* node scripts/sanitize-bookmarks.mjs <input> --stdout
* node scripts/sanitize-bookmarks.mjs <input> --check # report, write nothing
*/
import { readFileSync, statSync, writeFileSync } from 'node:fs';
import { basename, extname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { csvValues, sanitizeCsv } from './sanitize/csv.mjs';
import { detectKind } from './sanitize/detect.mjs';
import { attributeValues, sanitizeHtml } from './sanitize/html.mjs';
import { STRUCTURAL, sanitizeJson, stringValues } from './sanitize/json.mjs';
import { findLeakedHosts, findLeakedValueWords, findLeakedWords } from './sanitize/leaks.mjs';
import { makeTitleMapper, makeUrlMapper } from './sanitize/mappers.mjs';
export { detectKind } from './sanitize/detect.mjs';
export { findLeakedHosts, findLeakedWords } from './sanitize/leaks.mjs';
/** Matches docs/09's parse cap. A 25 MB attachment helps nobody anyway. */
const MAX_BYTES = 25 * 1024 * 1024;
/**
* Sanitize a bookmark file's text.
*
* @param {string} text
* @returns {{ text: string | null, kind: import('./sanitize/detect.mjs').Kind | null, leaked: string[] }}
* `text` is null when the format was not recognised, or when the output
* failed its own leak check. Both mean: write nothing.
*/
export function sanitize(text) {
const kind = detectKind(text);
if (kind === null) return { text: null, kind: null, leaked: [] };
const mapUrl = makeUrlMapper();
const mapTitle = makeTitleMapper();
let out;
if (kind === 'html') out = sanitizeHtml(text, mapUrl, mapTitle);
else if (kind === 'csv') out = sanitizeCsv(text, mapUrl, mapTitle);
else out = sanitizeJson(text, mapUrl, mapTitle);
const leaked = [
...findLeakedHosts(out).map(() => 'host'),
...(kind === 'html' ? findLeakedWords(out).map(() => 'text') : []),
...findLeakedValueWords(valuesOf(kind, out)).map(() => 'value'),
];
return { text: leaked.length > 0 ? null : out, kind, leaked };
}
/**
* The values of a sanitized file that a person could have written — every one
* of them must be a placeholder by now.
*
* @param {import('./sanitize/detect.mjs').Kind} kind
* @param {string} out
* @returns {string[]}
*/
function valuesOf(kind, out) {
if (kind === 'html') return attributeValues(out);
if (kind === 'csv') return csvValues(out);
return stringValues(out)
.filter((t) => !STRUCTURAL.has(t.key ?? '') && !(t.parentKey === 'annos' && t.key === 'name'))
.map((t) => /** @type {string} */ (JSON.parse(`"${t.raw}"`)));
}
/** @param {string} input */
function refuseUnknown(input) {
console.error(
`${basename(input)} is not a bookmark file this tool recognises, so NOTHING WAS WRITTEN.\n` +
' Expected one of: a Netscape HTML export (the usual bookmarks.html), a BookmarkMagic\n' +
' JSON export, Chrome\'s profile "Bookmarks" file, a Firefox bookmarks-*.json backup,\n' +
' or a CSV whose header is exactly "folder_path,title,url,add_date".\n' +
' Refusing to hand you a file it cannot promise is clean. Please attach the export\n' +
' exactly as your browser wrote it, or describe the problem in the issue instead.',
);
return 1;
}
/**
* Counts and categories only — never the strings. The old message printed what
* had leaked ("text \"Nguyen\", text \"payroll\"") and then asked for it in a
* public issue, which published exactly what the refusal had just withheld.
*
* @param {string} input @param {string[]} leaked categories, one per finding
*/
function refuseLeak(input, leaked) {
/** @type {Record<string, number>} */
const counts = {};
for (const category of leaked) counts[category] = (counts[category] ?? 0) + 1;
const summary = Object.entries(counts)
.map(([category, n]) => `${n} ${category}${n === 1 ? '' : 's'}`)
.join(', ');
console.error(
`${basename(input)}: NOTHING WAS WRITTEN — the result still contained ${summary} that look ` +
'personal, so this file is not safe to attach.\n' +
' This is a bug in the sanitizer, not in your file. Please report it at\n' +
' https://github.com/poli0981/bookmarkmagic/issues with only the counts above and the\n' +
' browser that wrote the file. Do not attach the file, and do not paste any of its contents.',
);
return 1;
}
/** @param {string[]} argv */
function main(argv) {
const flags = argv.filter((a) => a.startsWith('--'));
const [input, maybeOutput] = argv.filter((a) => !a.startsWith('--'));
if (input === undefined) {
console.error('usage: node scripts/sanitize-bookmarks.mjs <input> [output] [--stdout|--check]');
return 1;
}
// Size first, from the file system: reading a 2 GB file to learn it is too
// big is how the old version ran out of memory before its own check.
const size = statSync(input).size;
if (size > MAX_BYTES) {
console.error(
`${input} is ${(size / 1024 / 1024).toFixed(1)} MB. The extension itself refuses ` +
'anything over 25 MB, and a smaller file that still reproduces the bug is more useful. ' +
'Please trim it first.',
);
return 1;
}
const text = readFileSync(input).toString('utf8');
const { text: out, kind, leaked } = sanitize(text);
if (kind === null) return refuseUnknown(input);
if (out === null) return refuseLeak(input, leaked);
const eol = text.includes('\r\n') ? 'CRLF' : 'LF';
const bom = text.charCodeAt(0) === 0xfeff ? ', BOM' : '';
console.error(
`${basename(input)}: ${kind}, ${eol}${bom} — ${Buffer.byteLength(out)} bytes out, no leaks`,
);
if (flags.includes('--check')) return 0;
if (flags.includes('--stdout')) {
process.stdout.write(out);
return 0;
}
const ext = extname(input);
const target = maybeOutput ?? `${input.slice(0, input.length - ext.length)}.sanitized${ext}`;
// Never over the original: an output path equal to the input used to replace
// the user's only copy of their real bookmarks with the placeholder version.
if (resolve(target) === resolve(input)) {
console.error(
`refusing to overwrite ${input} with its sanitized copy — pick another output path.`,
);
return 1;
}
writeFileSync(target, out);
console.error(`wrote ${target}`);
return 0;
}
if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
process.exitCode = main(process.argv.slice(2));
}
+154
View File
@@ -0,0 +1,154 @@
// @ts-check
/**
* CSV (docs/04 §3): a minimal RFC 4180 reader that records the span of each
* field's *content* (inside the quotes, when quoted). Replacements never
* contain a delimiter, quote or newline, so the original quoting survives —
* which matters, because CSV quoting is itself a common bug.
*/
import { replaceSpans } from './spans.mjs';
/** @typedef {import('./spans.mjs').Span} Span */
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
/** @typedef {{ row: number, col: number, start: number, end: number }} Field */
/**
* @param {string} text
* @param {string} delimiter
* @returns {Field[]}
*/
export function readFields(text, delimiter) {
/** @type {Field[]} */
const fields = [];
let row = 0;
let col = 0;
let i = 0;
while (i < text.length) {
const quoted = text[i] === '"';
if (quoted) i++;
const start = i;
while (i < text.length) {
const ch = text[i];
if (quoted) {
if (ch === '"' && text[i + 1] === '"') i += 2;
else if (ch === '"') break;
else i++;
} else if (ch === delimiter || ch === '\n' || ch === '\r') {
break;
} else {
i++;
}
}
fields.push({ row, col, start, end: i });
if (quoted && text[i] === '"') i++;
if (text[i] === delimiter) {
col++;
i++;
} else {
if (text[i] === '\r') i++;
if (text[i] === '\n') i++;
row++;
col = 0;
}
}
return fields;
}
/**
* Map each path segment separately so `\/` and `\\` escapes keep their meaning.
* A segment that contained a literal slash or backslash keeps one, so the
* escape branch of the CSV path parser — a real reason someone files a report —
* is still exercised by the sample.
*
* @param {string} path
* @param {Mapper} mapTitle
*/
function mapFolderPath(path, mapTitle) {
const segments = [];
let current = '';
for (let i = 0; i < path.length; i++) {
const ch = path[i];
if (ch === '\\' && (path[i + 1] === '/' || path[i + 1] === '\\')) {
current += path[i + 1];
i++;
} else if (ch === '/') {
segments.push(current);
current = '';
} else {
current += ch;
}
}
segments.push(current);
return segments
.map((s) => {
if (s === '') return '';
const kept = `${s.includes('/') ? '/' : ''}${s.includes('\\') ? '\\' : ''}`;
return `${mapTitle(s)}${kept}`.replace(/\\/g, '\\\\').replace(/\//g, '\\/');
})
.join('/');
}
/** @param {string} text */
export function csvDelimiter(text) {
return (text.split('\n', 1)[0] ?? '').includes(';') ? ';' : ',';
}
/**
* Default-deny: every field is rewritten except a date (digits only). The
* old rules rewrote only the folder, title and url columns — and a title with
* an unquoted comma, the very row that makes the extension report
* CSV_ROW_MISMATCH, shifts every later field one column right, so the url
* landed in `add_date` and was copied out verbatim. A row of the wrong width is
* judged by value shape instead of by column.
*
* @param {string} text
* @param {Mapper} mapUrl
* @param {Mapper} mapTitle
*/
export function sanitizeCsv(text, mapUrl, mapTitle) {
const fields = readFields(text, csvDelimiter(text));
// Column names per docs/04 §3 — `folder_path`, not `folder`.
const header = fields.filter((f) => f.row === 0).map((f) => text.slice(f.start, f.end).trim());
/** @param {string} name */
const at = (name) => header.findIndex((h) => h.toLowerCase().replace(/^\uFEFF/, '') === name);
const [folderCol, titleCol, urlCol, dateCol] = [
at('folder_path'),
at('title'),
at('url'),
at('add_date'),
];
/** @type {Map<number, number>} */
const width = new Map();
for (const f of fields) width.set(f.row, (width.get(f.row) ?? 0) + 1);
/** @type {Span[]} */
const spans = [];
for (const f of fields) {
if (f.row === 0 || f.start === f.end) continue;
const value = text.slice(f.start, f.end).replace(/""/g, '"');
const aligned = width.get(f.row) === header.length;
// A number says nothing about anyone, and dates are what parsers branch on.
// trim() first: `^\s*\d*\s*$` let two `\s*` compete for the same blanks,
// which backtracks quadratically on a long run of them (S8786).
if (/^\d*$/.test(value.trim()) && (f.col === dateCol || !aligned)) continue;
let mapped;
if (f.col === folderCol) mapped = mapFolderPath(value, mapTitle);
else if (aligned && f.col === urlCol) mapped = mapUrl(value);
else if (aligned && f.col === titleCol) mapped = mapTitle(value);
else mapped = /^[a-z][a-z0-9+.-]*:/i.test(value) ? mapUrl(value) : mapTitle(value);
spans.push({ start: f.start, end: f.end, value: mapped.replace(/"/g, '""') });
}
return replaceSpans(text, spans);
}
/**
* Every field below the header, unescaped — what the leak check reads.
*
* @param {string} text
* @returns {string[]}
*/
export function csvValues(text) {
return readFields(text, csvDelimiter(text))
.filter((f) => f.row > 0)
.map((f) => text.slice(f.start, f.end).replace(/""/g, '"'));
}
+80
View File
@@ -0,0 +1,80 @@
// @ts-check
/**
* Format sniffing for the sanitizer — refuse anything not positively known.
*
* Returning `null` rather than guessing is load-bearing. Every sanitizer finds
* what it must destroy *by format*, so a wrong guess destroys nothing and emits
* the input verbatim — and the file would still be handed over as "sanitized".
* The old `return 'csv'` fallback did exactly that for a truncated JSON export.
*
* The same goes for JSON: the old check accepted ANY object, and the JSON
* rewriter only knew BookmarkMagic's `title`/`url` keys — so Chrome's profile
* `Bookmarks` file, which keeps titles under `name`, "sanitized" with every
* title intact and passed the host check. Each JSON dialect is now recognised
* by shape, and anything else is refused.
*
* Re-implemented rather than imported from `src/lib/core/detect-format.ts`:
* this script must run from a fresh clone with nothing installed.
*/
/** The docs/04 §3 CSV header, in order. A file is CSV only if it says so. */
const CSV_HEADER = ['folder_path', 'title', 'url', 'add_date'];
/** @typedef {'html' | 'json' | 'chrome-json' | 'firefox-json' | 'csv'} Kind */
/**
* @param {unknown} doc
* @returns {'json' | 'chrome-json' | 'firefox-json' | null}
*/
export function jsonDialect(doc) {
if (typeof doc !== 'object' || doc === null || Array.isArray(doc)) return null;
const record = /** @type {Record<string, unknown>} */ (doc);
if (record.format === 'bookmarkmagic') return 'json';
const roots = record.roots;
if (
typeof roots === 'object' &&
roots !== null &&
!Array.isArray(roots) &&
['bookmark_bar', 'other', 'synced'].some((key) => key in roots)
) {
return 'chrome-json';
}
const isPlacesRoot = record.type === 'text/x-moz-place-container' || record.root === 'placesRoot';
if (isPlacesRoot && Array.isArray(record.children)) return 'firefox-json';
return null;
}
/**
* Identify the format, or refuse with `null`.
*
* The people who run this tool are, by definition, the ones whose file did not
* import — so a malformed or hand-trimmed file is the typical input here.
*
* @param {string} text
* @returns {Kind | null}
*/
export function detectKind(text) {
const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
const trimmed = body.trimStart();
// JSON first: a JSON title may legitimately contain the Netscape doctype
// string, and nothing that starts with `{` is HTML or CSV.
if (trimmed.startsWith('{')) {
try {
return jsonDialect(JSON.parse(trimmed));
} catch {
return null;
}
}
if (/NETSCAPE-Bookmark-file-1/i.test(body.slice(0, 512))) return 'html';
const firstLine = body.split(/\r?\n/, 1)[0] ?? '';
for (const delimiter of [',', ';']) {
const columns = firstLine
.split(delimiter)
.map((h) => h.trim().replace(/^"|"$/g, '').toLowerCase());
if (columns.length === CSV_HEADER.length && CSV_HEADER.every((c, i) => columns[i] === c)) {
return 'csv';
}
}
if (/<\s*dl[\s>]/i.test(body)) return 'html';
return null;
}
+160
View File
@@ -0,0 +1,160 @@
// @ts-check
/**
* Netscape HTML: rewrite addresses, titles, descriptions and user-authored
* attributes by span, leaving every other byte exactly as the browser wrote it.
*/
import { isAddressLike } from './mappers.mjs';
import {
ANY_ATTR,
attrRewriter,
attrSpans,
replaceSpans,
spansFrom,
TAG_INNARDS,
} from './spans.mjs';
/** @typedef {import('./spans.mjs').Span} Span */
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
/** 1×1 transparent PNG. Keeps ICON= present, which is what the parser reacts to. */
const BLANK_ICON =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
/** Attributes handled explicitly; the generic sweep must not touch them. */
const HANDLED_ATTRS = new Set(['href', 'icon', 'shortcuturl', 'tags']);
/**
* Attributes whose values are structure — dates, root markers, the charset
* line — and are kept as written. Exported for the leak check.
*/
export const STRUCTURAL_ATTRS = new Set([
'add_date',
'last_modified',
'last_visit',
'personal_toolbar_folder',
'unfiled_bookmarks_folder',
'mobile_bookmarks_folder',
'last_charset',
'folded',
'http-equiv',
'content',
'charset',
]);
/**
* Every OTHER attribute, default-deny: an address is mapped as one, a number
* or boolean is kept, anything else becomes `attrN`. The old sweep touched
* only address-shaped values, so Firefox's `POST_DATA="…&user=jane.doe"` on a
* keyword bookmark — and any exporter's `DATA-NOTE` — went out verbatim.
* `file:` counts as an address: `ICON_URI="file:///C:/Users/<name>/…"`.
*
* @param {string} text
* @param {Mapper} mapUrl
* @returns {Span[]}
*/
function otherAttrSpans(text, mapUrl) {
/** @type {Span[]} */
const spans = [];
const rewrite = attrRewriter(mapUrl);
let others = 0;
for (const m of text.matchAll(ANY_ATTR)) {
const name = (m[1] ?? '').toLowerCase();
const value = m[2] ?? m[3] ?? m[4] ?? '';
if (HANDLED_ATTRS.has(name) || STRUCTURAL_ATTRS.has(name) || value === '') continue;
if (/^(?:-?\d+(?:\.\d+)?|true|false)$/i.test(value)) continue;
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
if (at === undefined) continue;
const mapped = isAddressLike(value) ? rewrite(value) : `attr${++others}`;
spans.push({ start: at[0], end: at[1], value: mapped });
}
return spans;
}
/**
* Every attribute value outside the structural set — what the leak check reads.
*
* @param {string} html
* @returns {string[]}
*/
export function attributeValues(html) {
/** @type {string[]} */
const values = [];
for (const m of html.matchAll(ANY_ATTR)) {
if (STRUCTURAL_ATTRS.has((m[1] ?? '').toLowerCase())) continue;
values.push(m[2] ?? m[3] ?? m[4] ?? '');
}
return values;
}
/** The next element that ends a description: `<DT>`, `<DD>`, `<DL>` or a close. */
const DESCRIPTION_END = /<\s*(?:\/\s*)?(?:dt|dd|dl)\b/gi;
/**
* `<DD>` descriptions, found in one linear pass.
*
* The description runs to the next `<DT>/<DD>/<DL>` (or a closing one), not to
* the end of the line — a wrapped description used to leak its second line —
* and trailing whitespace stays outside the span, because the newline and
* indentation before the next tag are byte-level shape this tool keeps.
*
* Replaces `/<dd>([\s\S]*?)(?=\s*<…>|\s*$)/`, which backtracked polynomially
* (SonarCloud S8786) and matched only a bare `<dd>` — `<DD class=n>Private
* note` passed through untouched.
*
* @param {string} text
* @param {() => string} next
* @returns {Span[]}
*/
function descriptionSpans(text, next) {
/** @type {Span[]} */
const spans = [];
for (const open of text.matchAll(/<dd\b[^>]*>/gi)) {
const start = (open.index ?? 0) + open[0].length;
DESCRIPTION_END.lastIndex = start;
const close = DESCRIPTION_END.exec(text);
let end = close === null ? text.length : close.index;
while (end > start && /\s/.test(text.charAt(end - 1))) end--;
if (end > start) spans.push({ start, end, value: next() });
}
return spans;
}
/** A document heading that says nothing about its owner stays as it is. */
const GENERIC_HEADING = /^\s*bookmarks(?:\s+menu)?\s*$/i;
/**
* @param {string} text
* @param {Mapper} mapUrl
* @param {Mapper} mapTitle
*/
export function sanitizeHtml(text, mapUrl, mapTitle) {
let descriptions = 0;
let keywords = 0;
/** @param {string} heading */
const mapHeading = (heading) => (GENERIC_HEADING.test(heading) ? heading : mapTitle(heading));
const spans = [
// HREF and ICON, at any quoting — attribute name case is left as found.
...attrSpans(text, /^href$/, attrRewriter(mapUrl)),
...attrSpans(text, /^icon$/, () => BLANK_ICON),
...otherAttrSpans(text, mapUrl),
// Firefox keywords and tags are user-authored text, so they are personal
// too. Tag count is preserved because it is the only part a parser sees.
...attrSpans(text, /^shortcuturl$/, () => `kw${++keywords}`),
...attrSpans(text, /^tags$/, (v) =>
v
.split(',')
.map((_, i) => `tag${i + 1}`)
.join(','),
),
// Bookmark and folder titles. `[\s\S]*?`, not `[^<]*`: a title holding a
// raw `<` made the whole match fail and stay in the output.
...spansFrom(text, new RegExp(`<a\\b${TAG_INNARDS}>([\\s\\S]*?)</a>`, 'gi'), mapTitle),
...spansFrom(text, new RegExp(`<h3\\b${TAG_INNARDS}>([\\s\\S]*?)</h3>`, 'gi'), mapTitle),
// `<TITLE>` / `<H1>` — usually "Bookmarks", but an exporter can write the
// owner's name there ("Jane Doe's bookmarks").
...spansFrom(text, /<title\b[^>]*>([^<]*)<\/title>/gi, mapHeading),
...spansFrom(text, /<h1\b[^>]*>([^<]*)<\/h1>/gi, mapHeading),
...descriptionSpans(text, () => `Description ${++descriptions}`),
];
return replaceSpans(text, spans);
}
+159
View File
@@ -0,0 +1,159 @@
// @ts-check
/**
* JSON bookmark files — BookmarkMagic JSON, Chrome's profile `Bookmarks` file,
* and Firefox's `bookmarks-YYYY-MM-DD.json` backup.
*
* Default-deny: every string VALUE is replaced unless its key is on the short
* structural list below. The old rewriter was default-allow — it rewrote only
* `"url"` and `"title"`, so Chrome's titles (under `"name"`), Firefox's `uri`,
* `iconUri` and keywords, Chrome's `meta_info` and the base64 `sync_metadata`
* blob all went through untouched, and the host check could not see a title.
*
* Values are rewritten by span over the raw text (a small tokenizer tracks
* which key each string belongs to), so indentation, key order, escapes and
* line endings stay byte-for-byte as the browser wrote them.
*/
import { isAddressLike, makeGuidMapper } from './mappers.mjs';
import { replaceSpans } from './spans.mjs';
/** @typedef {import('./spans.mjs').Span} Span */
/** @typedef {import('./mappers.mjs').Mapper} Mapper */
/**
* Keys whose string values are structure, not content, and are kept verbatim:
* format markers, type tags, root identifiers, numeric ids and every timestamp
* (Chrome stores dates as decimal strings). Nothing a person typed lives here.
*/
export const STRUCTURAL = new Set([
'format',
'generator',
'exportedAt',
'version',
'type',
'root',
'id',
'date_added',
'date_modified',
'date_last_used',
'charset',
'source',
]);
/** Keys whose value is an address, mapped even when it does not parse. */
const ADDRESS = new Set(['url', 'uri', 'iconuri']);
/**
* @typedef {{ kind: 'object' | 'array', key: string | null, expectKey: boolean, current: string | null }} Frame
* @typedef {{ start: number, end: number, raw: string, key: string | null, parentKey: string | null }} StringToken
*/
/**
* Every string VALUE in a JSON text, with the key it sits under and the key of
* the object that holds it (`annos[].value` → key "value", parentKey "annos").
* The input has already passed `JSON.parse`, so it is well-formed.
*
* @param {string} text
* @returns {StringToken[]}
*/
export function stringValues(text) {
/** @type {Frame[]} */
const stack = [];
/** @type {StringToken[]} */
const out = [];
// The key a new child sits under. Array elements inherit the array's key, so
// every object inside `"annos": [...]` reports "annos" as its parent.
const keyFor = () => {
const top = stack.at(-1);
return (top?.kind === 'object' ? top.current : top?.key) ?? null;
};
let i = 0;
while (i < text.length) {
const ch = text[i];
if (ch === '"') {
i = readString(text, i, stack, out, keyFor);
continue;
}
if (ch === '{' || ch === '[') {
stack.push({
kind: ch === '{' ? 'object' : 'array',
key: keyFor(),
expectKey: ch === '{',
current: null,
});
} else if (ch === '}' || ch === ']') {
stack.pop();
} else if (ch === ',') {
const top = stack.at(-1);
if (top?.kind === 'object') top.expectKey = true;
} else if (ch === ':') {
const top = stack.at(-1);
if (top !== undefined) top.expectKey = false;
}
i++;
}
return out;
}
/**
* One string token starting at the quote at `start`: a key updates its object
* frame, a value is recorded. Returns the index just past the closing quote.
*
* @param {string} text
* @param {number} start
* @param {Frame[]} stack
* @param {StringToken[]} out
* @param {() => string | null} keyFor
*/
function readString(text, start, stack, out, keyFor) {
let end = start + 1;
while (end < text.length && text[end] !== '"') end += text[end] === '\\' ? 2 : 1;
const raw = text.slice(start + 1, end);
const top = stack.at(-1);
if (top?.kind === 'object' && top.expectKey) {
top.current = JSON.parse(`"${raw}"`);
} else {
const holder = top?.kind === 'object' ? top : stack.at(-2);
out.push({ start: start + 1, end, raw, key: keyFor(), parentKey: holder?.key ?? null });
}
return end + 1;
}
/**
* @param {string} text
* @param {Mapper} mapUrl
* @param {Mapper} mapTitle
*/
export function sanitizeJson(text, mapUrl, mapTitle) {
const mapGuid = makeGuidMapper();
let keywords = 0;
/** @type {Span[]} */
const spans = [];
for (const token of stringValues(text)) {
const key = token.key ?? '';
const lower = key.toLowerCase();
if (STRUCTURAL.has(key)) continue;
// An anno's `name` is a schema id (bookmarkProperties/description); its
// `value` is what the person wrote.
if (token.parentKey === 'annos' && key === 'name') continue;
const value = /** @type {string} */ (JSON.parse(`"${token.raw}"`));
let mapped;
if (lower === 'guid') mapped = mapGuid(value);
else if (lower === 'checksum' || lower === 'checksum_sha256') mapped = '0'.repeat(value.length);
else if (lower === 'sync_metadata') mapped = '';
else if (lower === 'keyword') mapped = value === '' ? '' : `kw${++keywords}`;
else if (lower === 'tags')
mapped =
value === ''
? ''
: value
.split(',')
.map((_, i) => `tag${i + 1}`)
.join(',');
else if (ADDRESS.has(lower) || isAddressLike(value)) mapped = mapUrl(value);
else mapped = mapTitle(value);
spans.push({ start: token.start, end: token.end, value: JSON.stringify(mapped).slice(1, -1) });
}
return replaceSpans(text, spans);
}
+106
View File
@@ -0,0 +1,106 @@
// @ts-check
/**
* The backstop: check the OUTPUT, not the rules that produced it.
*
* The rewriting rules are patterns over untrusted markup, so each one has a
* shape it does not match — a single-quoted attribute, a title containing `<`,
* a JSON key nobody enumerated, a `<DD class=…>`. Every one of those is a silent
* leak, and nobody can honestly claim to have thought of every shape. So the
* output is inspected independently, and anything that still looks personal
* makes the tool refuse instead of handing the file over. A rule this misses
* degrades into a refusal — annoying — instead of a published browsing history.
*/
import { TAG_INNARDS } from './spans.mjs';
/**
* Hosts in the output that are not one of our own `*.example` aliases.
*
* @param {string} text sanitized output
* @returns {string[]} distinct suspicious hosts, empty when clean
*/
export function findLeakedHosts(text) {
const leaked = new Set();
for (const m of text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\/([^\s"'<>)\]}\\]+)/gi)) {
const authority = (m[1] ?? '').split(/[/?#]/, 1)[0] ?? '';
// Strip credentials and port; what remains is the host.
const host = authority.split('@').pop()?.replace(/:\d+$/, '').toLowerCase() ?? '';
if (host === '' || /^[a-z]\d*\.example$/.test(host)) continue;
leaked.add(host);
}
return [...leaked];
}
/**
* Words the sanitized TEXT of a Netscape file may legitimately contain: our
* placeholders, the default heading, and the script samples the title mapper
* adds so an encoding bug still reproduces.
*/
const ALLOWED_WORDS = new Set(['title', 'description', 'bookmarks', 'bookmark', 'menu', 'شيء']);
/**
* Words in the document's text content — everything outside tags and comments —
* that are not placeholders.
*
* Independent of the rewriting rules on purpose: it does not look for `<A>` or
* `<H3>` at all, it strips markup and reads whatever text is left. The old
* backstop matched only `scheme://host`, so an unsanitized title, a `<DD>` note
* or an `<H1>Jane Doe's bookmarks</H1>` passed it, and the test that guarded it
* reused the same pattern and could never notice.
*
* @param {string} html sanitized Netscape output
* @returns {string[]} distinct offending words, empty when clean
*/
export function findLeakedWords(html) {
const text = html
.replace(/<!--[\s\S]*?-->/g, ' ')
// Script and style bodies are code. A browser export never contains them;
// the T1 injection fixtures do, and their payload is the point of the file.
.replace(/<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, ' ')
.replace(new RegExp(`<${TAG_INNARDS}>`, 'g'), ' ')
.replace(/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi, ' ');
const leaked = new Set();
for (const [word] of text.matchAll(/\p{L}{3,}/gu)) {
if (!ALLOWED_WORDS.has(word.toLowerCase())) leaked.add(word);
}
return [...leaked];
}
/**
* Everything the mappers emit in place of a value, as patterns. What is left of
* a value once these are removed was not written by this tool.
*/
const PLACEHOLDERS = [
// A mapped address, query and `#frag` included — `&amp;` too, so its `;`
// must not end the match.
/\b[a-z][a-z0-9+.-]*:\/\/[a-z]\d*\.example(?::\d+)?[^\s"',]*/gi,
// Firefox's fixed root GUIDs, which the mapper keeps on purpose.
/\b(?:root|menu|toolbar|unfiled|mobile|tags)_{2,}/g,
/\b[a-z][a-z0-9+.-]*:sanitized-\d+/gi,
/\bnot-a-url-\d+/g,
/\b(?:Title|Description) \d+/g,
/\b(?:kw|tag|attr|g)\d+\b/g,
/\b0{8}-0{4}-4000-8000-\d{12}\b/g,
/data:image\/png;base64,[A-Za-z0-9+/=]+/g,
/&(?:#\d+|#x[0-9a-f]+|[a-z]+);/gi,
];
/**
* Words left in VALUES — CSV fields, attribute values, JSON strings — once every
* placeholder shape is removed. The value-level twin of `findLeakedWords`: a
* misaligned CSV row put a payslip path and a phone note in columns the CSV
* rules never looked at, and the host-only check let both through.
*
* @param {Iterable<string>} values sanitized values
* @returns {string[]} distinct offending words, empty when clean
*/
export function findLeakedValueWords(values) {
const leaked = new Set();
for (const value of values) {
let rest = value;
for (const re of PLACEHOLDERS) rest = rest.replace(re, ' ');
for (const [word] of rest.matchAll(/\p{L}{3,}/gu)) {
if (!ALLOWED_WORDS.has(word.toLowerCase())) leaked.add(word);
}
}
return [...leaked];
}
+167
View File
@@ -0,0 +1,167 @@
// @ts-check
/**
* Value mappers: deterministic placeholders that keep what parsers branch on.
*
* Replacements are stable per distinct input value, so "how many distinct
* hosts" and "which two bookmarks are duplicates" survive sanitizing.
*/
/** @typedef {(raw: string) => string} Mapper */
/**
* Replace addresses while preserving everything a parser branches on: the
* scheme, whether there is a port, how deep the path is, whether it ends in a
* slash, how many query parameters there are and in what order, and whether
* there is a fragment. Percent-escapes are carried across literally, so a
* decoding bug still reproduces.
*
* @returns {Mapper}
*/
export function makeUrlMapper() {
/** @type {Map<string, string>} */
const seen = new Map();
/** @type {Map<string, string>} */
const hosts = new Map();
/** @param {string} host */
const hostAlias = (host) => {
let alias = hosts.get(host);
if (alias === undefined) {
const n = hosts.size;
// a.example … z.example, then a1.example, a2.example …
const letter = String.fromCharCode(97 + (n % 26));
const round = Math.floor(n / 26);
alias = round === 0 ? `${letter}.example` : `${letter}${round}.example`;
hosts.set(host, alias);
}
return alias;
};
/** @param {string} segment */
const escapesIn = (segment) => (segment.match(/%[0-9a-fA-F]{2}/g) ?? []).join('');
/** @param {string} pathname */
const mapPath = (pathname) => {
if (pathname === '' || pathname === '/') return pathname;
const trailing = pathname.endsWith('/');
const parts = pathname.replace(/^\//, '').replace(/\/$/, '').split('/');
const mapped = parts.map((p, i) => (p === '' ? '' : `p${i + 1}${escapesIn(p)}`));
return `/${mapped.join('/')}${trailing ? '/' : ''}`;
};
/** @param {string} search */
const mapQuery = (search) => {
if (search === '') return '';
return `?${search
.slice(1)
.split('&')
.map((pair, i) => (pair.includes('=') ? `q${i + 1}=v${i + 1}` : `q${i + 1}`))
.join('&')}`;
};
return (raw) => {
if (raw === '') return raw;
const cached = seen.get(raw);
if (cached !== undefined) return cached;
let out;
let url;
try {
url = new URL(raw);
} catch {
url = undefined;
}
if (url === undefined) {
// Keep it unparseable, and keep distinct values distinct — the dedupe
// path treats an unparseable URL as its own trimmed self.
out = `not-a-url-${seen.size + 1}`;
} else if (url.host === '') {
// Opaque or hostless scheme (javascript:, data:, mailto:, file:, place:).
// The scheme is the whole point for the T1/T3 threat cases; the payload —
// which for file: is a local path with a user name in it — is not ours.
out = `${url.protocol}sanitized-${seen.size + 1}`;
} else {
// Credentials are never round-tripped, not even as placeholders.
const port = url.port === '' ? '' : `:${url.port}`;
const hash = url.hash === '' ? '' : '#frag';
out = `${url.protocol}//${hostAlias(url.host.replace(/:\d+$/, ''))}${port}${mapPath(url.pathname)}${mapQuery(url.search)}${hash}`;
}
seen.set(raw, out);
return out;
};
}
/**
* Replace titles while preserving what encoding bugs live in: emptiness, the
* scripts present (so a CJK or RTL or emoji bug still reproduces), and any HTML
* entity references, which are carried across verbatim.
*
* @returns {Mapper}
*/
export function makeTitleMapper() {
/** @type {Map<string, string>} */
const seen = new Map();
/** @type {[RegExp, string][]} */
const SCRIPTS = [
[/[一-鿿぀-ヿ]/, '文字'],
[/[֐-ࣿ]/, 'شيء'],
[/\p{Extended_Pictographic}/u, '🌸'],
];
return (raw) => {
if (raw.trim() === '') return raw;
const cached = seen.get(raw);
if (cached !== undefined) return cached;
const entities = (raw.match(/&(?:#\d+|#x[0-9a-fA-F]+|[a-zA-Z]+);/g) ?? []).join('');
const extras = SCRIPTS.filter(([re]) => re.test(raw))
.map(([, sample]) => sample)
.join('');
const out = `Title ${seen.size + 1}${extras === '' ? '' : ` ${extras}`}${entities}`;
seen.set(raw, out);
return out;
};
}
/** Firefox's fixed root GUIDs — structural, and the parser keys off them. */
const RESERVED_GUID = /^(?:root|menu|toolbar|unfiled|mobile|tags)_+$/;
/**
* Replace bookmark GUIDs with stable fakes of the same shape. They are random,
* but they are also the identifier sync uses, so they could tie a public sample
* to an account; the root GUIDs are kept because they carry meaning.
*
* @returns {Mapper}
*/
export function makeGuidMapper() {
/** @type {Map<string, string>} */
const seen = new Map();
return (raw) => {
if (raw === '' || RESERVED_GUID.test(raw)) return raw;
const cached = seen.get(raw);
if (cached !== undefined) return cached;
const n = String(seen.size + 1);
const out = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw)
? `00000000-0000-4000-8000-${n.padStart(12, '0')}`
: `g${n.padStart(Math.max(raw.length - 1, n.length), '0')}`;
seen.set(raw, out);
return out;
};
}
/**
* True when a value is a URL whose payload could identify someone: it has a
* host, or it is a `file:` path (`file:///C:/Users/<name>/…` has no host).
*
* @param {string} value
*/
export function isAddressLike(value) {
try {
const url = new URL(value);
return url.host !== '' || url.protocol === 'file:';
} catch {
return false;
}
}
+125
View File
@@ -0,0 +1,125 @@
// @ts-check
/**
* Span rewriting: every change is a [start, end) → value replacement, so the
* bytes between spans are provably untouched. Rebuilding the file from a parsed
* model would quietly normalize them, and the byte-level shape is often the bug.
*/
/** @typedef {{ start: number, end: number, value: string }} Span */
/**
* Apply replacements right to left by character span.
*
* Overlaps are dropped, outermost first. Two patterns can legitimately claim
* the same bytes — an <A> title containing `x="http://…"` matches both the
* title rule and the generic attribute sweep — and applying both would splice
* already-rewritten text using an `end` measured against the original. The
* widest span sanitizes the most.
*
* @param {string} text
* @param {Span[]} spans
*/
export function replaceSpans(text, spans) {
const ordered = [...spans].sort((a, b) => a.start - b.start || b.end - a.end);
const out = [];
let cursor = 0;
for (const span of ordered) {
if (span.start < cursor) continue;
out.push(text.slice(cursor, span.start), span.value);
cursor = span.end;
}
out.push(text.slice(cursor));
// Joined once rather than spliced per span: splicing is O(spans × file),
// which took minutes on a large export.
return out.join('');
}
/**
* Spans for one capture group of a global regex; `map` receives the captured
* text. The `d` flag gives exact per-group offsets — searching the match for
* the captured substring lands on the wrong copy whenever the capture also
* appears earlier in the match (a title equal to part of its own URL).
*
* @param {string} text
* @param {RegExp} re
* @param {(captured: string) => string} map
* @param {number} [group]
* @returns {Span[]}
*/
export function spansFrom(text, re, map, group = 1) {
const indexed = new RegExp(re.source, re.flags.includes('d') ? re.flags : `${re.flags}d`);
/** @type {Span[]} */
const spans = [];
for (const m of text.matchAll(indexed)) {
const captured = m[group] ?? '';
const at = m.indices?.[group];
if (captured === '' || at === undefined) continue;
spans.push({ start: at[0], end: at[1], value: map(captured) });
}
return spans;
}
/**
* The inside of an opening tag, tolerating `>` within quoted attribute values.
* `data:text/html,<h1>hi</h1>` is a legal HREF in the T1/T3 fixtures, and a
* naive `[^>]*` stopped inside it, leaving that bookmark's title unsanitized.
*/
export const TAG_INNARDS = '(?:"[^"]*"|\'[^\']*\'|[^>"\'])*';
/** The four entities Netscape exporters write inside attribute values. */
const ATTR_ENTITY = /&(amp|lt|gt|quot);/gi;
/** @type {Record<string, string>} */
const ATTR_DECODE = { amp: '&', lt: '<', gt: '>', quot: '"' };
/**
* Decode an HTML attribute value, map it, then re-encode it the way the source
* file encoded it.
*
* Decoding is ONE pass. Chained `.replace()` calls (`&amp;` first, then `&lt;`)
* turned `&amp;lt;` into `<` — a double unescape (CodeQL js/double-escaping).
* Netscape exports write `&amp;` inside HREF but not all of them do, and
* emitting a bare `&` where the source had `&amp;` would silently repair the
* file being reported.
*
* @param {(value: string) => string} map
* @returns {(captured: string) => string}
*/
export function attrRewriter(map) {
return (captured) => {
const decoded = captured.replace(
ATTR_ENTITY,
(_m, name) => ATTR_DECODE[name.toLowerCase()] ?? _m,
);
const mapped = map(decoded);
const escapesAmp = /&amp;/i.test(captured) || !captured.includes('&');
return escapesAmp ? mapped.replace(/&/g, '&amp;') : mapped;
};
}
/**
* `name = value`, where the value is double-quoted, single-quoted or bare.
* Group 2/3/4 is the value, whichever quoting was used — matching only `"…"`
* left `HREF='https://…'` completely untouched.
*/
export const ANY_ATTR = /\b([a-z_][a-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+))/dgi;
/**
* Spans for every attribute whose (lower-cased) name matches, at any quoting.
*
* @param {string} text
* @param {RegExp} nameRe
* @param {(value: string) => string} map
* @returns {Span[]}
*/
export function attrSpans(text, nameRe, map) {
/** @type {Span[]} */
const spans = [];
for (const m of text.matchAll(ANY_ATTR)) {
if (!nameRe.test((m[1] ?? '').toLowerCase())) continue;
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
const value = m[2] ?? m[3] ?? m[4] ?? '';
if (at === undefined || value === '') continue;
spans.push({ start: at[0], end: at[1], value: map(value) });
}
return spans;
}
+298
View File
@@ -0,0 +1,298 @@
#!/usr/bin/env node
// @ts-check
/**
* Screenshot harness — docs/13 §2, docs/11 §5.
*
* Serves the BUILT extension (`.output/chrome-mv3`) over localhost with a fake
* `chrome` object and neutral sample bookmarks, so every page can be looked at
* — and photographed for the store listing — without loading the extension or
* exposing anyone's real bookmarks. Each HTML response also carries the
* production CSP as a meta tag, so a violation shows up in the console here
* exactly as it would in the extension.
*
* npm run build && node scripts/screenshots.mjs # serve on :4318
* node scripts/screenshots.mjs --shoot # also capture PNGs
*
* Page URLs take `?theme=light|dark&lang=en|vi|ja|zh-CN|ro&legal=0|1`, and the
* route as the hash: http://localhost:4318/manager.html?theme=dark&lang=vi#edit
*
* `--shoot` drives a locally installed Chrome (CHROME_PATH, or the usual
* install paths) headless, on a throwaway profile — never the user's own:
* every route × theme × language at 1280×800, plus the popup per theme ×
* language at 360×420, into `.output/qa-screens/` (for review, git-ignored),
* the README set into `capture/`, and the store set into
* `store/screenshots/`. Dev tool only: nothing here ships, the server listens
* on 127.0.0.1 alone, and it never touches the network beyond it.
*/
import { execFile } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { extname, join, relative, resolve, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
const run = promisify(execFile);
const ROOT = resolve(fileURLToPath(new URL('..', import.meta.url)));
const OUT = join(ROOT, '.output', 'chrome-mv3');
const PORT = Number(process.env.PORT ?? 4318);
/** Loopback only: the harness serves the build and a fake API to this machine, nobody else. */
const HOST = '127.0.0.1';
const TYPES = /** @type {Record<string, string>} */ ({
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.txt': 'text/plain; charset=utf-8',
});
/** The CSP the production manifest declares, read from the build itself. */
function productionCsp() {
const manifest = JSON.parse(readFileSync(join(OUT, 'manifest.json'), 'utf8'));
return String(manifest.content_security_policy?.extension_pages ?? "script-src 'self'");
}
/** The fake `chrome`, as a classic script that runs before the page's modules. */
function shim() {
const manifest = readFileSync(join(OUT, 'manifest.json'), 'utf8');
return `(() => {
const q = new URLSearchParams(location.search);
const manifest = ${manifest};
const listeners = () => { const set = new Set(); return { addListener: (f) => set.add(f), removeListener: (f) => set.delete(f), fire: (...a) => set.forEach((f) => f(...a)) }; };
let next = 100;
const day = 86400000, base = Date.UTC(2026, 6, 1);
const b = (title, url, age = 1) => ({ id: String(next++), title, url, dateAdded: base - age * day });
const f = (title, children, age = 30) => ({ id: String(next++), title, dateAdded: base - age * day, dateGroupModified: base, children });
const tree = [{ id: '0', title: '', children: [
{ id: '1', title: 'Bookmarks bar', children: [
b('Docs', 'https://docs.example.org/'), b('Calendar', 'https://calendar.example.com/'),
f('Dev', [b('Repository', 'https://code.example.dev/project'), b('CI dashboard', 'https://ci.example.dev/'),
f('Reference', [b('Language spec', 'https://spec.example.org/latest'), b('Style guide', 'https://style.example.org/'), b('Repository', 'https://code.example.dev/project')])]),
f('Reading', [b('Long read about distributed systems and the people who keep them running', 'https://essays.example.net/systems'), b('Weekly notes', 'https://notes.example.net/week-27')]),
b('', 'https://untitled.example.com/'),
] },
{ id: '2', title: 'Other bookmarks', children: [
f('Recipes', [b('Bread', 'https://kitchen.example.com/bread'), b('Soup', 'https://kitchen.example.com/soup')]),
f('Travel', [b('Rail map', 'https://rail.example.org/map'), b('Hostels', 'https://stay.example.org/')]),
b('Bookmarklet', 'javascript:void(0)'), b('Docs', 'https://docs.example.org/'),
] },
{ id: '3', title: 'Mobile bookmarks', children: [b('Read later', 'https://later.example.com/')] },
] }];
// Chrome gives every node but the root a parentId, and the product relies on
// it: without one, nothing can be placed beside a sibling (drag, Alt+↑/↓) and
// the toolbar's Sort has no folder to act on.
const adopt = (nodes, parentId) => { for (const n of nodes) { if (parentId !== undefined) n.parentId = parentId; if (n.children) adopt(n.children, n.id); } };
adopt(tree);
const byId = (id, nodes = tree) => { for (const n of nodes) { if (n.id === id) return n; const hit = n.children && byId(id, n.children); if (hit) return hit; } };
const parentOf = (id, nodes = tree) => { for (const n of nodes) { if (n.children?.some((c) => c.id === id)) return n; const hit = n.children && parentOf(id, n.children); if (hit) return hit; } };
const clone = (v) => structuredClone(v);
const events = { onCreated: listeners(), onRemoved: listeners(), onChanged: listeners(), onMoved: listeners(), onChildrenReordered: listeners(), onImportBegan: listeners(), onImportEnded: listeners() };
const bookmarks = { ...events,
getTree: async () => clone(tree),
create: async ({ parentId, title, url, index }) => { const p = byId(parentId); const n = url ? { id: String(next++), parentId, title, url, dateAdded: Date.now() } : { id: String(next++), parentId, title, dateAdded: Date.now(), children: [] }; const at = index ?? p.children.length; p.children.splice(at, 0, n); events.onCreated.fire(n.id, clone({ ...n, index: at })); return clone(n); },
update: async (id, changes) => { Object.assign(byId(id), changes); events.onChanged.fire(id, changes); },
move: async (id, { parentId, index }) => { const from = parentOf(id); const n = byId(id); const old = from.children.indexOf(n); from.children.splice(old, 1); const to = byId(parentId ?? from.id); let at = index ?? to.children.length; if (to === from && at > old) at--; to.children.splice(at, 0, n); n.parentId = to.id; events.onMoved.fire(id, { parentId: to.id, index: at, oldParentId: from.id, oldIndex: old }); },
remove: async (id) => { const p = parentOf(id); p.children = p.children.filter((c) => c.id !== id); events.onRemoved.fire(id, {}); },
};
bookmarks.removeTree = bookmarks.remove;
const area = (seed = {}) => { const data = { ...seed }; const changed = listeners(); return { data, changed,
get: async (keys) => { if (keys == null) return clone(data); const list = typeof keys === 'string' ? [keys] : Array.isArray(keys) ? keys : Object.keys(keys); return Object.fromEntries(list.filter((k) => k in data).map((k) => [k, clone(data[k])])); },
set: async (items) => { Object.assign(data, clone(items)); }, remove: async (keys) => { for (const k of [].concat(keys)) delete data[k]; }, clear: async () => { for (const k of Object.keys(data)) delete data[k]; } }; };
const lang = q.get('lang') ?? 'en';
const local = area({
settings: { theme: q.get('theme') ?? 'light', locale: lang, defaultExportFormat: 'netscape-html', defaultMergeMode: 'new-folder', csvDelimiter: ',', markdownStyle: 'nested' },
...(q.get('legal') === '0' ? {} : { legal: { acceptedVersion: 1, acceptedAt: '2026-07-26T09:00:00.000Z' } }),
});
const storage = { local, sync: area(), session: area(), onChanged: listeners() };
globalThis.chrome = {
bookmarks, storage,
runtime: { id: 'harness', getManifest: () => manifest, getURL: (p) => location.origin + (p.startsWith('/') ? p : '/' + p), getContexts: async () => [], lastError: undefined },
i18n: { getUILanguage: () => lang, getMessage: (k) => k },
tabs: { create: async () => ({}), update: async () => ({}), getCurrent: async () => ({ id: 1 }) },
windows: { update: async () => ({}) },
};
})();`;
}
/**
* Every file of the build, by the URL path that serves it. A request is looked
* up here and never joined onto a directory, so no request can name a file
* outside the build — `..`, encoded separators and prefix tricks included.
* (A prefix check after `join` did the same job, but SonarCloud's taint
* analysis, S2083, cannot see it; an allowlist it can.)
*
* @returns {Map<string, string>}
*/
function buildIndex() {
const index = new Map();
/** @param {string} dir */
const walk = (dir) => {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) walk(full);
else index.set(`/${relative(OUT, full).split(sep).join('/')}`, full);
}
};
walk(OUT);
return index;
}
function serve() {
const csp = productionCsp();
let files = buildIndex();
/**
* A rebuild while the harness runs renames the hashed chunks, so a miss
* re-lists once. `wxt build` empties the directory first; listing it then
* throws, and an uncaught throw in the handler ended the whole process.
* @param {string} urlPath @returns {string | undefined}
*/
const lookup = (urlPath) => {
if (files.has(urlPath)) return files.get(urlPath);
try {
files = buildIndex();
} catch {
return undefined;
}
return files.get(urlPath);
};
const server = createServer((req, res) => {
const url = new URL(req.url ?? '/', `http://${HOST}:${PORT}`);
if (url.pathname === '/__shim.js') {
res.writeHead(200, { 'content-type': TYPES['.js'] ?? '' }).end(shim());
return;
}
let decoded;
try {
decoded = decodeURIComponent(url.pathname);
} catch {
// A malformed escape (`%E0%A4%A`) used to throw out of the handler.
res.writeHead(400).end('bad request');
return;
}
const path = lookup(decoded);
if (path === undefined) {
res.writeHead(404).end('not found');
return;
}
const type = TYPES[extname(path)] ?? 'application/octet-stream';
let body;
try {
body = readFileSync(path);
} catch {
// Listed, then deleted: a build is rewriting .output under us.
res.writeHead(503).end('build in progress');
return;
}
if (type.startsWith('text/html')) {
const tags = `<meta http-equiv="Content-Security-Policy" content="${csp}"><script src="/__shim.js"></script>`;
body = Buffer.from(body.toString('utf8').replace('<head>', `<head>${tags}`));
}
res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }).end(body);
});
server.listen(PORT, HOST, () =>
console.log(`harness: http://${HOST}:${PORT}/manager.html#import`),
);
return server;
}
function findChrome() {
const candidates = [
process.env.CHROME_PATH,
'C:/Program Files/Google/Chrome/Application/chrome.exe',
'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe',
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
];
return candidates.find((path) => path !== undefined && existsSync(path));
}
/**
* One headless screenshot. Asynchronous on purpose: the server answering
* Chrome's requests runs in this same process, and 1.1.0's first cut used
* `execFileSync`, which blocked the event loop — Chrome waited for a page the
* blocked server could never send, and `--shoot` hung forever.
*
* @param {string} chrome @param {string} profile @param {string} url
* @param {string} file @param {string} size
*/
async function shoot(chrome, profile, url, file, size) {
const flags = ['--headless=new', '--no-first-run', '--disable-gpu', '--hide-scrollbars'];
const page = [`--window-size=${size}`, '--virtual-time-budget=4000', `--screenshot=${file}`];
await run(chrome, [...flags, `--user-data-dir=${profile}`, ...page, url], { timeout: 60_000 });
}
/** `LOCALES` (resolve-locale.ts), which .mjs cannot import — touch-points.test.ts pins it. */
const LANGS = ['en', 'vi', 'ja', 'zh-CN', 'ro'];
/**
* Every screenshot `--shoot` takes, as [url, file, window size] (docs/11 §5):
* the QA sweep — each route × theme × locale, plus the popup, the narrowest
* surface (340 px) and where a long translation overflows first — then the
* README set and the store set, both English.
*
* @param {{ qa: string, capture: string, store: string }} dirs
* @returns {[url: string, file: string, size: string][]}
*/
function shotList({ qa, capture, store }) {
const origin = `http://${HOST}:${PORT}`;
const page = (/** @type {string} */ query, /** @type {string} */ route) =>
`${origin}/manager.html?${query}#${route}`;
const routes = ['import', 'export', 'edit', 'settings', 'about'];
/** @type {[string, string, string][]} */
const jobs = [];
for (const lang of LANGS) {
for (const theme of ['light', 'dark']) {
const query = `theme=${theme}&lang=${lang}`;
for (const route of routes) {
jobs.push([page(query, route), join(qa, `${route}-${theme}-${lang}.png`), '1280,800']);
}
jobs.push([
`${origin}/popup.html?${query}`,
join(qa, `popup-${theme}-${lang}.png`),
'360,420',
]);
}
}
for (const route of routes) {
jobs.push([page('theme=light&lang=en', route), join(capture, `${route}.png`), '1280,800']);
}
for (const route of ['edit', 'export', 'import']) {
jobs.push([page('theme=dark&lang=en', route), join(store, `${route}.png`), '1280,800']);
}
jobs.push([`${origin}/popup.html?theme=light&lang=en`, join(capture, 'popup.png'), '360,420']);
return jobs;
}
if (!existsSync(join(OUT, 'manifest.json'))) {
console.error('harness: no build found — run `npm run build` first.');
process.exitCode = 1;
} else {
const server = serve();
if (process.argv.includes('--shoot')) {
const chrome = findChrome();
if (chrome === undefined) {
console.error('harness: no Chrome found — set CHROME_PATH.');
process.exitCode = 1;
server.close();
} else {
const qa = join(OUT, '..', 'qa-screens');
const capture = join(ROOT, 'capture');
const store = join(ROOT, 'store', 'screenshots');
for (const dir of [qa, capture, store]) mkdirSync(dir, { recursive: true });
const profile = mkdtempSync(join(tmpdir(), 'bookmarkmagic-harness-'));
try {
for (const [url, file, size] of shotList({ qa, capture, store })) {
await shoot(chrome, profile, url, file, size);
}
} finally {
rmSync(profile, { recursive: true, force: true });
server.close();
}
console.log(`harness: screenshots in ${qa}, ${capture} and ${store}`);
}
}
}
+22
View File
@@ -0,0 +1,22 @@
/**
* Types for scripts/triage.mjs, so its tests can call it directly.
* The script itself is plain JavaScript checked with `// @ts-check`.
*/
export interface Decision {
action: 'close' | 'label' | 'none';
reason: string;
kind?: 'issue' | 'pr';
number?: number;
label?: string;
comment?: string;
}
export const POLICY_URL: string;
export const IDEAS_URL: string;
export const KIND_QUESTION: string;
export const KIND: Readonly<{ roadmap: string; needed: string; fresh: string }>;
export const LABEL: Readonly<{ feature: string; closed: string; triage: string; exempt: string }>;
export const ISSUE_COMMENT: string;
export const PR_COMMENT: string;
export function kindOf(body: unknown): string | undefined;
export function decide(eventName: string | undefined, payload: unknown): Decision;
+261
View File
@@ -0,0 +1,261 @@
// @ts-check
/**
* Maintenance-mode triage — MAINTENANCE.md, docs/12 §2.6.
*
* Decides what `.github/workflows/triage.yml` does with a new issue or pull
* request; the workflow then carries the decision out with `gh`. The decision
* is a pure function of the event payload, so every branch is unit-tested
* (tests/unit/scripts/triage.test.ts) instead of living in shell `if`s.
*
* - An issue labelled `enhancement` (the feature form applies it) whose
* "kind of change" answer is "something new" — or that has no answer at
* all, i.e. the maintainer labelled it by hand — is labelled
* `maintenance-mode`, gets a comment and is closed as not planned.
* - The other two answers (on the roadmap; needed for a fix) keep it open,
* labelled `needs-triage`, for the maintainer to read.
* - A pull request from outside the project titled `feat…` (Conventional
* Commits) is labelled and closed the same way.
* - Exempt: the owner's own issues, project members and collaborators, bots
* (Dependabot), anything labelled `roadmap`, anything already triaged.
*
* Nothing here runs code from the event: titles and bodies are only compared
* with constants, and the workflow passes the payload by file, never through
* shell interpolation.
*
* Usage (in CI): node scripts/triage.mjs — reads GITHUB_EVENT_NAME and
* GITHUB_EVENT_PATH from the environment the runner sets, prints a JSON
* decision on stdout. It takes no arguments.
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const REPO = 'https://github.com/poli0981/bookmarkmagic';
export const POLICY_URL = `${REPO}/blob/main/MAINTENANCE.md`;
export const IDEAS_URL = `${REPO}/discussions/categories/ideas`;
/** The feature form's dropdown, word for word (`.github/ISSUE_TEMPLATE/feature_request.yml`). */
export const KIND_QUESTION = 'Which kind of change is this?';
export const KIND = Object.freeze({
roadmap: 'Something already on the roadmap (docs/15)',
needed: 'Needed to fix a bug, a UI/UX defect or an accessibility barrier',
fresh: 'Something new — not on the roadmap',
});
export const LABEL = Object.freeze({
feature: 'enhancement',
closed: 'maintenance-mode',
triage: 'needs-triage',
exempt: 'roadmap',
});
/** Associations that mean "part of the project", per GitHub's author_association. */
const INSIDERS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']);
const BOT_NOTE = '<sub>Posted automatically by the triage workflow.</sub>';
export const ISSUE_COMMENT = [
'Thank you for the suggestion.',
'',
`BookmarkMagic is in **maintenance mode** ([MAINTENANCE.md](${POLICY_URL})): it takes bug, UI/UX and accessibility fixes, translation fixes, dependency and security updates, and features that are already on the roadmap. This request is for something new, so it has been labelled \`${LABEL.closed}\` and closed.`,
'',
'It has not been deleted, and it will be read. If it is on the roadmap, or it is needed to fix a defect or remove a barrier, it will be reopened. Ideas are welcome in [Discussions › Ideas](' +
`${IDEAS_URL}).`,
'',
BOT_NOTE,
].join('\n');
export const PR_COMMENT = [
'Thank you for the pull request.',
'',
`BookmarkMagic is in **maintenance mode** ([MAINTENANCE.md](${POLICY_URL})). A pull request that adds a feature — its title starts with \`feat\` — is closed automatically unless the feature is already on the roadmap, so this one has been labelled \`${LABEL.closed}\` and closed.`,
'',
'Please open a feature request first; if it is accepted (label `roadmap`), this pull request will be reopened. If it is a fix rather than a feature, say so in a comment — a `fix:` title is what the maintainer expects.',
'',
BOT_NOTE,
].join('\n');
/**
* @typedef {{
* action: 'close' | 'label' | 'none',
* reason: string,
* kind?: 'issue' | 'pr',
* number?: number,
* label?: string,
* comment?: string,
* }} Decision
*/
/**
* The answer to the feature form's dropdown, or undefined when the body has
* none (an issue from another form, labelled by hand). Issue forms render each
* field as `### <label>` followed by the answer.
* @param {unknown} body
* @returns {string | undefined}
*/
export function kindOf(body) {
if (typeof body !== 'string') return undefined;
const lines = body.split(/\r?\n/);
const at = lines.findIndex((line) => line.trim() === `### ${KIND_QUESTION}`);
if (at === -1) return undefined;
for (const line of lines.slice(at + 1)) {
const text = line.trim();
if (text.startsWith('### ')) return undefined;
if (text !== '') return text;
}
return undefined;
}
/** @param {unknown} value @returns {Record<string, unknown>} */
function record(value) {
return typeof value === 'object' && value !== null
? /** @type {Record<string, unknown>} */ (value)
: {};
}
/** @param {unknown} labels @returns {string[]} */
function labelNames(labels) {
if (!Array.isArray(labels)) return [];
return labels.map((label) => record(label).name).filter((name) => typeof name === 'string');
}
/** @param {unknown} value @returns {number | undefined} */
function positiveInt(value) {
return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;
}
/**
* Whether this event is the repository owner adding a label by hand.
* @param {Record<string, unknown>} payload
*/
function addedByOwner(payload) {
const sender = record(payload.sender).login;
const owner = record(record(payload.repository).owner).login;
return (
payload.action === 'labeled' && typeof sender === 'string' && sender !== '' && sender === owner
);
}
/**
* @param {Record<string, unknown>} payload
* @returns {Decision}
*/
function decideIssue(payload) {
const issue = record(payload.issue);
const number = positiveInt(issue.number);
if (number === undefined) return { action: 'none', reason: 'no issue number' };
if (payload.action !== 'opened' && payload.action !== 'labeled') {
return { action: 'none', reason: `issue action ${String(payload.action)}` };
}
if (payload.action === 'labeled' && record(payload.label).name !== LABEL.feature) {
return { action: 'none', reason: 'a different label was added' };
}
if (issue.state !== 'open') return { action: 'none', reason: 'issue is not open' };
const labels = labelNames(issue.labels);
if (!labels.includes(LABEL.feature)) return { action: 'none', reason: 'not a feature request' };
for (const done of [LABEL.exempt, LABEL.closed, LABEL.triage]) {
if (labels.includes(done)) return { action: 'none', reason: `already labelled ${done}` };
}
if (issue.author_association === 'OWNER')
return { action: 'none', reason: "the owner's own issue" };
const kind = kindOf(issue.body);
const forTriage = /** @type {Decision} */ ({
action: 'label',
reason: 'in policy — for the maintainer',
kind: 'issue',
number,
label: LABEL.triage,
});
if (kind === KIND.roadmap || kind === KIND.needed) return forTriage;
// No answer at all means the form was not used. Closing on that is the
// owner's one-touch close, so it needs the owner's own `enhancement` label;
// anything else (an edited body, an answer the form never offered) goes to
// a human rather than being closed on a guess.
if (kind !== KIND.fresh && !addedByOwner(payload)) {
return { ...forTriage, reason: 'no answer to the form, not labelled by the owner' };
}
return {
action: 'close',
reason:
kind === KIND.fresh ? 'a new feature outside the roadmap' : 'labelled enhancement by hand',
kind: 'issue',
number,
label: LABEL.closed,
comment: ISSUE_COMMENT,
};
}
/** Conventional Commits `feat`, with an optional scope and breaking-change mark. */
const FEAT_TITLE = /^feat(\([^)]*\))?!?:/i;
/**
* @param {Record<string, unknown>} payload
* @returns {Decision}
*/
function decidePullRequest(payload) {
const pr = record(payload.pull_request);
const number = positiveInt(pr.number);
if (number === undefined) return { action: 'none', reason: 'no pull request number' };
if (payload.action !== 'opened')
return { action: 'none', reason: `pull request action ${String(payload.action)}` };
if (pr.state !== 'open') return { action: 'none', reason: 'pull request is not open' };
if (record(pr.user).type === 'Bot') return { action: 'none', reason: 'opened by a bot' };
if (INSIDERS.has(String(pr.author_association)))
return { action: 'none', reason: 'opened from inside the project' };
if (labelNames(pr.labels).includes(LABEL.exempt))
return { action: 'none', reason: 'labelled roadmap' };
if (typeof pr.title !== 'string' || !FEAT_TITLE.test(pr.title.trim())) {
return { action: 'none', reason: 'not a feature pull request' };
}
return {
action: 'close',
reason: 'a feature pull request from outside the project',
kind: 'pr',
number,
label: LABEL.closed,
comment: PR_COMMENT,
};
}
/**
* What to do with one event.
* @param {string | undefined} eventName — GITHUB_EVENT_NAME
* @param {unknown} payload — the parsed GITHUB_EVENT_PATH file
* @returns {Decision}
*/
export function decide(eventName, payload) {
const event = record(payload);
if (eventName === 'issues') return decideIssue(event);
if (eventName === 'pull_request_target') return decidePullRequest(event);
return { action: 'none', reason: `event ${String(eventName)} is not triaged` };
}
/** @returns {number} exit code */
function main() {
const eventPath = process.env.GITHUB_EVENT_PATH;
if (eventPath === undefined || eventPath === '') {
console.error('triage: GITHUB_EVENT_PATH is not set — this runs inside GitHub Actions only');
return 1;
}
/** @type {unknown} */
let payload;
try {
payload = JSON.parse(readFileSync(eventPath, 'utf8'));
} catch (cause) {
console.error(`triage: cannot read the event payload (${String(cause)})`);
return 1;
}
process.stdout.write(`${JSON.stringify(decide(process.env.GITHUB_EVENT_NAME, payload))}\n`);
return 0;
}
// Run only as the entry point (same guard as check-manifest.mjs).
const isEntry =
import.meta.url.startsWith('file:') &&
process.argv[1] !== undefined &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isEntry) {
// exitCode, not exit(): exit() can cut off piped output before CI reads it.
process.exitCode = main();
}
+28
View File
@@ -0,0 +1,28 @@
# SonarCloud — CI-based analysis (docs/12 §2.5). Read by
# .github/workflows/sonarcloud.yml; Automatic Analysis must stay OFF in the
# SonarCloud project (Administration → Analysis Method), or the scan errors out.
sonar.projectKey=poli0981_bookmarkmagic
sonar.organization=poli0981
sonar.projectName=BookmarkMagic
sonar.sourceEncoding=UTF-8
# What ships, plus the repo tooling that guards it.
sonar.sources=src,scripts
# Icons and the _locales message catalogues are data, not code.
sonar.exclusions=src/public/**
sonar.tests=tests
sonar.test.inclusions=tests/**/*.ts
# Fixtures are byte-exact samples of what browsers emit — malformed on purpose
# (a no-doctype HTML file is a test case, not a bug), never something to "fix".
sonar.test.exclusions=tests/fixtures/**
# Coverage scope mirrors docs/11 §1: components, entrypoints and repo scripts
# are verified by the manual QA pass and their own script tests, not by line
# coverage. Everything else in src/ is unit-tested and counted.
sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.coverage.exclusions=src/entrypoints/**,src/lib/components/**,**/*.svelte,scripts/**
# The three locale dictionaries are parallel by design (en is the schema, vi/ja
# `satisfies Dict`); their "duplication" is the i18n contract working.
sonar.cpd.exclusions=src/lib/i18n/locales/**
+192 -55
View File
@@ -1,119 +1,256 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, tick } from 'svelte';
import AboutTab from '@/lib/components/AboutTab.svelte';
import EditTab from '@/lib/components/EditTab.svelte';
import ExportTab from '@/lib/components/ExportTab.svelte';
import ImportTab from '@/lib/components/ImportTab.svelte';
import LanguageSwitcher from '@/lib/components/LanguageSwitcher.svelte';
import LegalGate from '@/lib/components/LegalGate.svelte';
import SettingsTab from '@/lib/components/SettingsTab.svelte';
import StatusBar from '@/lib/components/StatusBar.svelte';
import TabBar from '@/lib/components/TabBar.svelte';
import ThemeToggle from '@/lib/components/ThemeToggle.svelte';
import Toast from '@/lib/components/Toast.svelte';
import { focusIfLost } from '@/lib/components/focus-heading';
import Icon from '@/lib/components/icons/Icon.svelte';
import { t } from '@/lib/i18n/index.svelte';
import { isWriting } from '@/lib/stores/import-session.svelte';
import { getRoute, navigate, startRouting } from '@/lib/stores/route.svelte';
import { loadSettings } from '@/lib/stores/settings.svelte';
import {
getBlockedRoutes,
getLegalStatus,
isGatedRoute,
isGateRequired,
} from '@/lib/stores/legal.svelte';
import { getRoute, isRoute, navigate, startRouting } from '@/lib/stores/route.svelte';
import { subscribeStorage } from '@/lib/browser/storage';
import { onNavigateRequest } from '@/lib/browser/open-manager';
import { adoptExternalLegal } from '@/lib/stores/legal.svelte';
import {
adoptExternalSettings,
flushSettings,
getSettings,
updateSettings,
} from '@/lib/stores/settings.svelte';
import { pushToast } from '@/lib/stores/toast.svelte';
// Settings are loaded and awaited in main.ts, before this ever mounts.
const settings = $derived(getSettings());
const legal = $derived(getLegalStatus());
const gated = $derived(isGateRequired() && isGatedRoute(getRoute()));
let mainEl: HTMLElement | undefined = $state();
const ROUTE_KEYS = {
import: 'common.import',
export: 'common.export',
edit: 'common.edit',
settings: 'common.settings',
about: 'common.about',
} as const;
// Each route names its own tab in the browser's tab strip and history (uL16).
$effect(() => {
document.title = `${t(ROUTE_KEYS[getRoute()])} · ${t('common.appName')}`;
});
// A route change can take the focused control with it — "Open in Edit" on
// the import report unmounts the button that was clicked — and focus then
// falls to <body>, back at the top of the page. It goes to <main> instead.
// Only when it was lost — the tab and status-bar buttons keep theirs — and
// never while the page is loading: `startRouting` reads the hash on mount,
// which is a route change to this effect and not to the user, and a fresh
// load must not move focus by itself.
let routeSettled = false;
$effect(() => {
void getRoute();
if (!routeSettled) return;
void tick().then(() => focusIfLost(mainEl));
});
onMount(() => {
void loadSettings();
const stopRouting = startRouting();
// The tab bar and the footer already refuse to navigate mid-write. This
// closes the third door: browser Back, which fires `hashchange` directly
// and — during the backup attestation — used to unmount ImportTab and leave
// the Manager permanently locked.
const stopRouting = startRouting({
isBlocked: isWriting,
onBlocked: () => pushToast(t('common.busy'), 'info'),
});
// After the route the hash named has rendered (see the effect above).
void tick().then(() => {
routeSettled = true;
});
// Leaving mid-write would kill the queue with the tab (docs/03 §5).
const onBeforeUnload = (event: BeforeUnloadEvent): void => {
if (!isWriting()) return;
event.preventDefault();
};
// Fires on tab close, navigation and backgrounding — unlike beforeunload it
// cannot be cancelled, so it is the right place to shorten the 200 ms
// window in which a just-changed setting is still unwritten.
const onVisibilityChange = (): void => {
if (globalThis.document?.visibilityState === 'hidden') void flushSettings();
};
// Two Manager tabs used to overwrite each other silently: `save()` writes
// the whole settings object, so a tab holding a stale locale reverted the
// other tab's language change the moment its own theme toggle fired.
// Registered here rather than in main.ts because this is the only place
// with a teardown path.
const stopStorage = subscribeStorage((change) => {
if (change.settings !== undefined) adoptExternalSettings(change.settings);
if ('legal' in change) adoptExternalLegal(change.legal ?? null);
});
// The popup asks an open Manager to switch route (uM12). Refused while an
// import is writing, exactly like the tab bar and browser Back.
const stopNavigate = onNavigateRequest((hash) => {
if (isWriting()) {
pushToast(t('common.busy'), 'info');
return;
}
const route = hash.slice(1);
if (isRoute(route)) navigate(route);
});
globalThis.addEventListener('beforeunload', onBeforeUnload);
globalThis.document?.addEventListener('visibilitychange', onVisibilityChange);
return () => {
stopRouting();
stopStorage();
stopNavigate();
globalThis.removeEventListener('beforeunload', onBeforeUnload);
globalThis.document?.removeEventListener('visibilitychange', onVisibilityChange);
};
});
/**
* Shared by the header controls so a silent failure there is impossible.
*
* The toast carries the LOCALIZED sentence, never the raw browser error —
* `detail` is essentially always present for a storage rejection, so putting
* it first made every translation of settings.saveFailed unreachable. The
* header has no room for a detail block; #settings shows one.
*/
function save(patch: Parameters<typeof updateSettings>[0]): void {
void updateSettings(patch).then((outcome) => {
pushToast(t(outcome.ok ? 'settings.saved' : 'settings.saveFailed'), outcome.ok ? 'success' : 'danger');
});
}
</script>
<header>
<div class="brand">
<span class="mark" aria-hidden="true">◆</span>
<span class="mark"><Icon name="logo" size={20} motion="pulse" /></span>
<strong>{t('common.appName')}</strong>
<span class="crumb mono" aria-hidden="true">~/{getRoute()}</span>
</div>
<TabBar blocked={getBlockedRoutes()} />
<div class="controls">
<LanguageSwitcher compact value={settings.locale} onchange={(locale) => save({ locale })} />
<ThemeToggle compact value={settings.theme} onchange={(theme) => save({ theme })} />
</div>
<TabBar />
</header>
<main>
{#if getRoute() === 'import'}
<main bind:this={mainEl} tabindex="-1">
{#if gated && legal.kind === 'required'}
<!-- Fills the content region rather than covering the viewport: docs/14 §2
requires #settings and #about to stay reachable while it is up, and a
literal inset:0 scrim would bury the status-bar links that get you
there. The three blocked tabs never mount before acceptance, so
nothing touches chrome.bookmarks until the user has agreed. -->
<LegalGate status={legal} onaccepted={() => mainEl?.focus()} />
{:else if getRoute() === 'import'}
<ImportTab />
{:else if getRoute() === 'export'}
<ExportTab />
{:else if getRoute() === 'edit'}
<EditTab />
{:else if getRoute() === 'settings'}
<SettingsTab />
{:else}
<!-- Phases 3-4 fill these in; the routes exist now so the shell is real. -->
<p class="placeholder">{t('common.comingSoon', { tab: t(`common.${getRoute()}`) })}</p>
<AboutTab />
{/if}
</main>
<footer>
<span>v0.1.0 · GPL-3.0</span>
<nav>
<button onclick={() => navigate('settings')}>{t('common.settings')}</button>
<button onclick={() => navigate('about')}>{t('common.about')}</button>
</nav>
</footer>
<StatusBar />
<!-- Mounted once, outside <main>, so the route chain below cannot unmount it
mid-dismiss and strand a timer (docs/06 §4). -->
<Toast />
<style>
header,
footer {
header {
position: sticky;
top: 0;
z-index: 10;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--sp-4);
max-width: 960px;
margin: 0 auto;
padding: var(--sp-3) var(--sp-4);
}
header {
gap: var(--sp-3) var(--sp-4);
padding: var(--sp-2) max(var(--sp-4), calc((100% - var(--width-page)) / 2));
border-bottom: 1px solid var(--border);
}
footer {
border-top: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-0);
background: color-mix(in srgb, var(--bg) 88%, transparent);
backdrop-filter: blur(8px);
}
.brand {
display: flex;
align-items: center;
gap: var(--sp-2);
min-width: 0;
}
.mark {
color: var(--accent);
display: inline-flex;
padding: 5px;
border-radius: var(--radius-sm);
background: var(--accent);
color: var(--accent-fg);
}
.crumb {
color: var(--fg-muted);
font-size: var(--fs-0);
padding: 1px 6px;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-sunken);
}
.controls {
display: flex;
align-items: center;
gap: var(--sp-2);
}
/* The page is a column: header, content, status bar — the bar sits at the
bottom of the window even when the content is short. */
:global(#app) {
display: flex;
flex-direction: column;
min-height: 100dvh;
}
main {
max-width: 960px;
flex: 1;
width: 100%;
max-width: var(--width-page);
margin: 0 auto;
padding: var(--sp-5) var(--sp-4);
min-height: 60vh;
padding: var(--sp-5) var(--sp-4) var(--sp-6);
}
.placeholder {
color: var(--fg-muted);
main:focus {
outline: none;
}
footer nav {
display: flex;
gap: var(--sp-3);
}
footer button {
font: inherit;
background: none;
border: none;
color: var(--fg-muted);
cursor: pointer;
padding: 0;
}
footer button:hover {
color: var(--accent);
@media (max-width: 640px) {
.crumb {
display: none;
}
}
</style>
+19 -6
View File
@@ -1,16 +1,29 @@
import { mount } from 'svelte';
import { browser } from 'wxt/browser';
import { setLocale } from '@/lib/i18n/index.svelte';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
import { installCrashHooks } from '@/lib/browser/diagnostics';
import { loadLegal } from '@/lib/stores/legal.svelte';
import { loadSettings } from '@/lib/stores/settings.svelte';
import '@/styles/base.css';
import App from './App.svelte';
// Phase 0: browser UI language only. Phase 4 hydrates from the persisted
// Settings value first, falling back to this (docs/07 §2).
setLocale(resolveLocale(browser.i18n.getUILanguage()));
// Uncaught errors reach the local diagnostics log (by name only) instead of
// vanishing into a console nobody opens.
installCrashHooks(window);
// SAFETY: the element is declared in this entrypoint's own index.html, so it
// always exists by the time this module runs.
const target = document.getElementById('app') as HTMLElement;
// Both reads happen BEFORE the first render, on purpose. The alternative --
// mount, then hydrate -- paints one frame in the browser's UI language and the
// system theme, then flips to the persisted ones, and flashes the legal gate at
// users who accepted it long ago. Awaiting means that frame holds an empty #app
// instead: a blank moment rather than visible EN->VI, light->dark or gate
// flicker.
//
// Neither loader can throw: readSettings and readLegal both swallow storage
// failures (browser/storage.ts) and applyLocale guards the i18n lookup. No
// timeout race either — storage.local.get always settles, and racing it would
// just re-introduce the wrong-locale render this exists to prevent.
await Promise.all([loadSettings(), loadLegal()]);
export default mount(App, { target });
+169 -41
View File
@@ -1,33 +1,37 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getAppVersion } from '@/lib/browser/app-info';
import { getRootChildren } from '@/lib/browser/bookmarks';
import { openManager } from '@/lib/browser/open-manager';
import { t } from '@/lib/i18n/index.svelte';
import { loadSettings } from '@/lib/stores/settings.svelte';
import { countLive } from '@/lib/browser/live-tree';
import { type ManagerRoute, openManager } from '@/lib/browser/open-manager';
import Icon, { type IconName } from '@/lib/components/icons/Icon.svelte';
import { num, t, tPlural } from '@/lib/i18n/index.svelte';
let counts = $state<{ bookmarks: number; folders: number } | undefined>();
const version = getAppVersion();
const TILES: { hash: ManagerRoute; icon: IconName; label: string; hint: string }[] = [
{ hash: '#import', icon: 'upload', label: 'popup.import', hint: 'popup.importHint' },
{ hash: '#export', icon: 'download', label: 'popup.export', hint: 'popup.exportHint' },
{ hash: '#edit', icon: 'edit', label: 'popup.manage', hint: 'popup.manageHint' },
];
// Settings are loaded and awaited in main.ts, before this ever mounts.
onMount(() => {
void loadSettings();
void countTree();
});
/** Cheap stats for the footer. No heavy work ever runs here (docs/06 §2). */
/**
* Cheap stats for the readout. No heavy work ever runs here (docs/06 §2).
* Counts what lives INSIDE the roots: 1.0.x counted the three permanent root
* folders too, so an empty profile reported "0 bookmarks · 3 folders".
*/
async function countTree(): Promise<void> {
try {
const roots = await getRootChildren();
let bookmarks = 0;
let folders = 0;
const walk = (nodes: readonly { url?: string; children?: unknown[] }[]): void => {
for (const node of nodes) {
if (node.url === undefined) folders++;
else bookmarks++;
if (node.children !== undefined) {
walk(node.children as { url?: string; children?: unknown[] }[]);
}
}
};
walk(roots);
// Inside the roots, separators (Firefox) apart: a separator's url is
// "data:", and counting by url called every one a bookmark.
const inside = (await getRootChildren()).flatMap((root) => root.children ?? []);
const { bookmarks, folders } = countLive(inside);
counts = { bookmarks, folders };
} catch {
counts = undefined;
@@ -37,68 +41,192 @@
<main>
<header>
<span class="mark" aria-hidden="true">◆</span>
<span class="mark"><Icon name="logo" size={16} /></span>
<strong>{t('common.appName')}</strong>
{#if version !== ''}<span class="version mono">v{version}</span>{/if}
</header>
<div class="actions">
<button onclick={() => void openManager('#import')}>⬆ {t('popup.import')}</button>
<button onclick={() => void openManager('#export')}>⬇ {t('popup.export')}</button>
<button onclick={() => void openManager('#edit')}>🗂 {t('popup.manage')}</button>
<dl class="readout" aria-live="polite">
<div>
<dt class="eyebrow">{tPlural('popup.bookmarks', counts?.bookmarks ?? 0)}</dt>
<dd class="mono">{counts === undefined ? '—' : num(counts.bookmarks)}</dd>
</div>
<div>
<dt class="eyebrow">{tPlural('popup.folders', counts?.folders ?? 0)}</dt>
<dd class="mono">{counts === undefined ? '—' : num(counts.folders)}</dd>
</div>
</dl>
<div class="tiles">
{#each TILES as tile (tile.hash)}
<button class="tile" onclick={() => void openManager(tile.hash)}>
<span class="icon"><Icon name={tile.icon} size={18} motion="bob" /></span>
<span class="text">
<span class="label">{t(tile.label)}</span>
<span class="hint">{t(tile.hint)}</span>
</span>
<Icon name="chevron" size={12} />
</button>
{/each}
</div>
<footer>
{#if counts !== undefined}
{t('popup.counts', { bookmarks: counts.bookmarks, folders: counts.folders })}
{/if}
<footer class="mono">
<span class="local"><span class="dot" aria-hidden="true"></span>{t('status.local')}</span>
<button
class="settings"
aria-label={t('common.settings')}
title={t('common.settings')}
onclick={() => void openManager('#settings')}
>
<Icon name="gear" size={15} motion="spin" />
</button>
</footer>
</main>
<style>
main {
width: 320px;
width: 340px;
padding: var(--sp-3);
display: flex;
flex-direction: column;
gap: var(--sp-3);
}
header {
display: flex;
align-items: center;
gap: var(--sp-2);
padding-bottom: var(--sp-3);
border-bottom: 1px solid var(--border);
}
.mark {
color: var(--accent);
display: inline-flex;
padding: 4px;
border-radius: var(--radius-sm);
background: var(--accent);
color: var(--accent-fg);
}
.actions {
.version {
margin-left: auto;
color: var(--fg-muted);
font-size: var(--fs-0);
}
.readout {
display: grid;
grid-template-columns: 1fr 1fr;
margin: 0;
border: 1px solid var(--border-strong);
border-radius: var(--radius);
background: var(--bg-sunken);
}
.readout div {
padding: var(--sp-2) var(--sp-3);
}
.readout div + div {
border-left: 1px solid var(--border);
}
dt {
margin: 0;
}
dd {
margin: 0;
font-size: var(--fs-4);
font-weight: 600;
font-variant-numeric: tabular-nums;
line-height: 1.2;
}
.tiles {
display: flex;
flex-direction: column;
gap: var(--sp-2);
padding: var(--sp-3) 0;
}
.actions button {
.tile {
display: flex;
align-items: center;
gap: var(--sp-3);
font: inherit;
text-align: left;
padding: var(--sp-2) var(--sp-3);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-raised);
color: var(--fg);
border: 1px solid var(--border-strong);
border-radius: var(--radius);
background: var(--bg);
color: var(--fg-muted);
cursor: pointer;
}
.actions button:hover {
.tile:hover {
border-color: var(--accent);
color: var(--accent);
}
.icon {
display: inline-flex;
padding: 6px;
border-radius: var(--radius-sm);
background: var(--accent-subtle);
color: var(--accent);
}
.text {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
}
.label {
color: var(--fg);
font-size: var(--fs-1);
font-weight: 600;
}
.hint {
font-size: var(--fs-0);
color: var(--fg-muted);
}
footer {
display: flex;
align-items: center;
justify-content: space-between;
padding-top: var(--sp-2);
border-top: 1px solid var(--border);
color: var(--fg-muted);
font-size: var(--fs-0);
min-height: 1.5em;
}
.local {
display: inline-flex;
align-items: center;
gap: 5px;
color: var(--success);
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
}
.settings {
display: inline-flex;
padding: 4px;
border: 1px solid transparent;
border-radius: var(--radius-sm);
background: none;
color: var(--fg-muted);
cursor: pointer;
}
.settings:hover {
color: var(--accent);
border-color: var(--border);
}
</style>
+6 -7
View File
@@ -1,16 +1,15 @@
import { mount } from 'svelte';
import { browser } from 'wxt/browser';
import { setLocale } from '@/lib/i18n/index.svelte';
import { resolveLocale } from '@/lib/i18n/resolve-locale';
import { loadSettings } from '@/lib/stores/settings.svelte';
import '@/styles/base.css';
import App from './App.svelte';
// Phase 0: browser UI language only. Phase 4 hydrates from the persisted
// Settings value first, falling back to this (docs/07 §2).
setLocale(resolveLocale(browser.i18n.getUILanguage()));
// SAFETY: the element is declared in this entrypoint's own index.html, so it
// always exists by the time this module runs.
const target = document.getElementById('app') as HTMLElement;
// Awaited before mount for the same reason as the Manager: the popup is small
// and fast, so a locale or theme flip here is proportionally more visible.
// The popup is never gated (docs/14 §2), so there is no legal read to make.
await loadSettings();
export default mount(App, { target });
+61
View File
@@ -0,0 +1,61 @@
/**
* Runtime metadata about the built extension.
*
* Purpose: the ONE place the displayed version comes from (docs/06 §3.5). It
* used to be hardcoded in three files, which is three chances to ship a
* number that disagrees with the manifest.
* Inputs: none — reads the packaged manifest.
* Guarantees: synchronous, so there is no version race and no loading state;
* never throws.
*/
import { browser } from 'wxt/browser';
/**
* The manifest version, or `''` when it cannot be read.
*
* Empty rather than a plausible fallback like `'0.0.0'`: callers hide the line
* entirely, and no version at all is better than a wrong one in a footer users
* quote in bug reports.
*/
export function getAppVersion(): string {
try {
return browser.runtime.getManifest().version;
} catch {
return '';
}
}
/** This install's extension id, or `''` when it cannot be read. Never throws. */
export function getExtensionId(): string {
try {
return browser.runtime.id;
} catch {
return '';
}
}
/**
* The `generator` string written into exported and backup BM JSON.
*
* Separate from `getAppVersion` because the UI and a file want different
* fallbacks: the UI hides an unknown version, but a file field cannot be
* hidden, and `"BookmarkMagic "` with a trailing space is a worse artifact
* than the bare product name.
*/
export function getGeneratorVersion(): string {
const version = getAppVersion();
return version === '' ? 'unknown' : version;
}
/**
* The browser's UI language tag, e.g. "vi" or "ja-JP" — `'en'` when it cannot
* be read. Here rather than in the settings store, so `stores/` reaches the
* browser only through `browser/` (docs/02 §3, uM15).
*/
export function getUiLanguage(): string {
try {
return browser.i18n.getUILanguage();
} catch {
return 'en';
}
}
+91 -136
View File
@@ -3,40 +3,20 @@
*
* Purpose: the single audited surface where the extension talks to the
* bookmarks API. Components never call `chrome.*` directly.
* Inputs / guarantees: raw rejections are mapped to `BmBrowserError`; the live
* tree is converted into the pure `BookmarkNode` file model here, including
* the millisecond→second conversion (`chrome.bookmarks` reports `dateAdded`
* in ms; `BookmarkNode.addDate` is seconds — docs/05 §4).
* Inputs / guarantees: raw rejections are mapped to `BmBrowserError`. The
* pure half — the node shape, separators, counts and the conversion into the
* `BookmarkNode` file model — is `live-tree.ts`; which folders are the roots
* is `roots.ts`. Firefox's API differs from Chromium's in ways this file
* absorbs (docs/02 §4): its move index (below) and its missing events.
*/
import { browser } from 'wxt/browser';
import type { BookmarkNode } from '../core/model';
import { millisToSeconds } from '../core/timestamps';
import { BmAborted, BmBrowserError } from './errors';
import { BmAborted, BmBrowserError, BmPartialWrite } from './errors';
import { type LiveNode, type MoveDestination, type MoveIndexRule, moveIndexFor } from './live-tree';
/** The live-tree node. Unlike `BookmarkNode` it carries browser identity. */
export interface LiveNode {
id: string;
parentId?: string;
index?: number;
title: string;
url?: string;
dateAdded?: number;
dateGroupModified?: number;
/** Set by Chrome on policy-managed nodes; such nodes reject writes. */
unmodifiable?: string;
children?: LiveNode[];
}
export interface BookmarkRoots {
/** Bookmarks Bar. */
toolbarId: string;
/** Other Bookmarks. */
otherId: string;
/** Mobile Bookmarks, when the profile has one. */
mobileId: string | undefined;
/** Writable top-level folders, in tree order, excluding managed ones. */
writable: LiveNode[];
}
// The node shape and the move-index rule live with the pure helpers
// (live-tree.ts); re-exported so the adapter stays the one import for code
// that talks to the browser.
export type { LiveNode, MoveDestination } from './live-tree';
async function guard<T>(operation: string, run: () => Promise<T>): Promise<T> {
try {
@@ -52,75 +32,11 @@ export async function getRootChildren(): Promise<LiveNode[]> {
return (tree[0]?.children ?? []) as LiveNode[];
}
/**
* Resolve the destination roots.
*
* Ids "1"/"2"/"3" are stable in Chromium but resolving through `getTree()`
* keeps a future Firefox target working, where roots are named ids. Nodes
* carrying `unmodifiable` (the enterprise/supervised "Managed bookmarks"
* folder) are excluded everywhere — writing to or removing them rejects.
*/
export async function getRoots(): Promise<BookmarkRoots> {
const children = await getRootChildren();
const writable = children.filter((node) => node.unmodifiable === undefined);
const byId = (id: string): LiveNode | undefined => writable.find((node) => node.id === id);
const toolbar = byId('1') ?? writable[0];
const other = byId('2') ?? writable.find((node) => node !== toolbar);
const mobile = byId('3') ?? writable.find((node) => node !== toolbar && node !== other);
if (toolbar === undefined || other === undefined) {
throw new BmBrowserError('bookmarks.getTree', 'no writable bookmark roots found');
}
return {
toolbarId: toolbar.id,
otherId: other.id,
mobileId: mobile?.id,
writable,
};
}
export interface ToNodesOptions {
/**
* Id of the Bookmarks Bar. The matching node is marked `toolbar: true`.
*
* Without this the marker is lost, and re-importing the file (including the
* Replace safety backup) lands the entire toolbar under Other Bookmarks —
* `03 §1` routes purely on that flag.
*/
toolbarId?: string;
}
/** Convert the live tree into the pure file model (ms → s, ids dropped). */
export function toBookmarkNodes(
nodes: readonly LiveNode[],
options: ToNodesOptions = {},
): BookmarkNode[] {
return nodes.map((node) => {
const addDate = millisToSeconds(node.dateAdded);
const isFolderNode = node.url === undefined;
// dateGroupModified is a FOLDER field — Chrome does not set it on
// bookmarks, and our HTML serializer only emits LAST_MODIFIED on <H3>.
const lastModified = isFolderNode ? millisToSeconds(node.dateGroupModified) : undefined;
return {
title: node.title,
...(!isFolderNode && { url: node.url as string }),
...(addDate !== undefined && { addDate }),
...(lastModified !== undefined && { lastModified }),
...(options.toolbarId !== undefined && node.id === options.toolbarId && { toolbar: true }),
...(isFolderNode && { children: toBookmarkNodes(node.children ?? [], options) }),
};
});
}
/** Flatten a live tree, parents before children. Used by dedupe and #edit. */
export function flattenLive(nodes: readonly LiveNode[], into: LiveNode[] = []): LiveNode[] {
for (const node of nodes) {
into.push(node);
if (node.children !== undefined) flattenLive(node.children, into);
}
return into;
/** The current children of one folder — what a bulk command re-plans from. */
export async function getChildren(id: string): Promise<LiveNode[]> {
return (await guard('bookmarks.getChildren', () =>
browser.bookmarks.getChildren(id),
)) as LiveNode[];
}
export async function create(details: {
@@ -137,11 +53,33 @@ export async function update(id: string, changes: { title?: string; url?: string
await guard('bookmarks.update', () => browser.bookmarks.update(id, changes));
}
const MOVE_INDEX_RULE: MoveIndexRule = import.meta.env.FIREFOX ? 'firefox' : 'chromium';
/**
* The longest address this browser accepts in a bookmark, or `undefined` for
* none. Firefox refuses anything over 65 536 characters (Places'
* `MAX_URL_LENGTH`) — mid-write, so the import drops such addresses up front
* (docs/04 §1.2); Chromium has no limit an import can reach.
*/
export const MAX_URL_LENGTH: number | undefined = import.meta.env.FIREFOX ? 65_536 : undefined;
/**
* Move a node. Resolves to the index the browser says the node now has, which
* the caller compares with `position.local` — a disagreement means the tree on
* screen no longer matches the browser's, and it is re-read (docs/03 §3).
*/
export async function move(
id: string,
destination: { parentId?: string; index?: number },
): Promise<void> {
await guard('bookmarks.move', () => browser.bookmarks.move(id, destination));
destination: MoveDestination,
rule: MoveIndexRule = MOVE_INDEX_RULE,
): Promise<number | undefined> {
const { parentId, position } = destination;
const details = {
...(parentId !== undefined && { parentId }),
...(position !== undefined && { index: moveIndexFor(position, rule) }),
};
const moved = await guard('bookmarks.move', () => browser.bookmarks.move(id, details));
return (moved as { index?: number } | undefined)?.index;
}
/** Remove a single bookmark. Folders need `removeTree`. */
@@ -159,6 +97,11 @@ export interface BookmarkEvents {
onRemoved: (id: string) => void;
onChanged: (id: string, changes: { title?: string; url?: string }) => void;
onMoved: (id: string, info: { parentId: string; index: number }) => void;
/** A folder's children were reordered wholesale (Chrome's own "Sort by name"). */
onChildrenReordered?: (id: string) => void;
/** Chrome's own importer is running; it sends no per-node events meanwhile. */
onImportBegan?: () => void;
onImportEnded?: () => void;
}
type Listenable<T extends unknown[]> = {
@@ -169,47 +112,55 @@ type Listenable<T extends unknown[]> = {
/**
* Subscribe to bookmark changes; returns an unsubscribe function.
*
* Listeners attach on tab enter and detach on leave (docs/03 §3) — an #edit
* tab left subscribed while an import runs would otherwise take one event per
* created node.
* Listeners attach on tab enter and detach on leave (docs/03 §3). Each handler
* is isolated: an exception in one used to escape into Chrome's event
* dispatch, and the tree silently stopped following the browser.
*/
export function subscribe(handlers: BookmarkEvents): () => void {
const api = browser.bookmarks as unknown as {
onCreated: Listenable<[string, LiveNode]>;
onRemoved: Listenable<[string, unknown]>;
onChanged: Listenable<[string, { title?: string; url?: string }]>;
onMoved: Listenable<[string, { parentId: string; index: number }]>;
};
export function subscribe(
handlers: BookmarkEvents,
onError?: (error: unknown) => void,
): () => void {
// SAFETY: every name looked up below is a `chrome.bookmarks` event object;
// the record type only erases their argument lists so one loop wires them.
const api = browser.bookmarks as unknown as Record<string, Listenable<unknown[]> | undefined>;
const safe =
<T extends unknown[]>(fn: ((...args: T) => void) | undefined) =>
(...args: T): void => {
try {
fn?.(...args);
} catch (error) {
onError?.(error);
}
};
const onCreated = (id: string, node: LiveNode): void => {
handlers.onCreated(id, node);
};
const onRemoved = (id: string): void => {
handlers.onRemoved(id);
};
const onChanged = (id: string, changes: { title?: string; url?: string }): void => {
handlers.onChanged(id, changes);
};
const onMoved = (id: string, info: { parentId: string; index: number }): void => {
handlers.onMoved(id, info);
};
api.onCreated.addListener(onCreated);
api.onRemoved.addListener(onRemoved);
api.onChanged.addListener(onChanged);
api.onMoved.addListener(onMoved);
const wired: [string, (...args: never[]) => void][] = [
['onCreated', safe(handlers.onCreated)],
['onRemoved', safe(handlers.onRemoved)],
['onChanged', safe(handlers.onChanged)],
['onMoved', safe(handlers.onMoved)],
['onChildrenReordered', safe(handlers.onChildrenReordered)],
['onImportBegan', safe(handlers.onImportBegan)],
['onImportEnded', safe(handlers.onImportEnded)],
];
// Not every Chromium build has every event (Firefox lacks the import pair).
// SAFETY: each listener is registered on the event whose arguments it was
// typed for in `BookmarkEvents`; the cast only matches the erased record.
const erased = wired as unknown as [string, (...args: unknown[]) => void][];
for (const [name, fn] of erased) api[name]?.addListener(fn);
return () => {
api.onCreated.removeListener(onCreated);
api.onRemoved.removeListener(onRemoved);
api.onChanged.removeListener(onChanged);
api.onMoved.removeListener(onMoved);
for (const [name, fn] of erased) api[name]?.removeListener(fn);
};
}
/**
* Delete the CHILDREN of the given roots, never the roots themselves (the API
* forbids that anyway). Managed nodes are skipped — docs/05 §6.
*
* @throws {BmAborted} on cancellation, carrying how many were already removed.
* @throws {BmPartialWrite} when a removal rejects, carrying the same count.
* This is the one path that destroys data, so "how much is gone" is the
* single most useful thing the failure can say.
*/
export async function clearRoots(
roots: readonly LiveNode[],
@@ -222,8 +173,12 @@ export async function clearRoots(
if (child.unmodifiable !== undefined) continue;
// Checked per node so a cancel arriving mid-deletion stops promptly
// rather than running the whole tree to completion.
if (signal?.aborted === true) throw new BmAborted(0);
await removeTree(child.id);
if (signal?.aborted === true) throw new BmAborted(removed);
try {
await removeTree(child.id);
} catch (cause) {
throw new BmPartialWrite('clearing', removed, cause);
}
removed++;
}
}
+23
View File
@@ -0,0 +1,23 @@
/**
* Copying a bookmark's URL — the docs/09 T8 surface.
*
* Purpose: the only place this extension touches the clipboard.
* Inputs: a URL string, from an explicit user click.
* Guarantees: **write only**. Nothing here ever reads the clipboard, and the
* write is never triggered by anything but a click, so no permission is
* needed — `clipboard-write` is granted to a transient user activation.
* Never throws; returns whether the copy landed.
*/
export async function copyToClipboard(text: string): Promise<boolean> {
const clipboard = globalThis.navigator?.clipboard;
// Absent in a non-secure context and in jsdom. A missing clipboard is a
// "could not copy", not a crash.
if (clipboard === undefined) return false;
try {
await clipboard.writeText(text);
return true;
} catch {
return false;
}
}
+92
View File
@@ -0,0 +1,92 @@
/**
* Map a thrown value onto an i18n key plus the raw technical detail —
* docs/02 §7.
*
* Purpose: one place that decides how a failure is described, so the
* "localized sentence + separate detail block" contract cannot be got wrong
* in one tab and right in another.
* Inputs: anything thrown by the core, browser or import layers.
* Guarantees: returns a **key**, never a resolved sentence, and never throws.
*
* Two rules this encodes, both learned from real defects:
*
* - The key is not resolved here. The import session store outlives the
* component that wrote to it, and `t()` is only reactive where it is called,
* so a sentence stored at throw time would never follow a language switch.
* - `detail` is a *separate* field, never a substitute for the message.
* Rendering `detail ?? t(key)` makes every translation dead code, because the
* raw browser string is almost always present.
*
* Lives in `browser/` because that is where the error taxonomy lives;
* `browser/` may import `core/`, not the reverse (docs/02 §3).
*/
import { BmParseError, type BmParseErrorCode } from '../core/model';
import { errorName, record } from './diagnostics';
import {
BmBackupError,
type BmBackupErrorCode,
BmBrowserError,
type BmEnvCode,
BmEnvError,
BmPartialWrite,
} from './errors';
/** Every key `describeError` can return — and so every code the diagnostics log can hold. */
export type ErrorKey = `errors.${
| BmParseErrorCode
| BmBackupErrorCode
| BmEnvCode
| 'PARTIAL_CLEAR'
| 'PARTIAL_WRITE'
| 'BROWSER'
| 'UNKNOWN'}`;
export interface DescribedError {
/** Dotted i18n path, e.g. `errors.TOO_DEEP`. */
messageKey: ErrorKey;
/** Raw, untranslated technical text for the copyable detail block. */
detail?: string | undefined;
/** Nodes written before a partial failure, when the failure knows. */
created?: number;
/** Root children deleted before a partial failure, when the failure knows. */
removed?: number;
}
export function describeError(err: unknown): DescribedError {
const described = describe(err);
// Every failure the UI shows passes through here, so this is where the
// diagnostics log learns of it — by code, never by its detail text.
record({ kind: 'failure', where: errorName(err), code: described.messageKey });
return described;
}
function describe(err: unknown): DescribedError {
if (err instanceof BmParseError) {
return { messageKey: `errors.${err.code}`, detail: err.detail };
}
if (err instanceof BmBackupError) {
return { messageKey: `errors.${err.code}`, detail: err.message };
}
if (err instanceof BmEnvError) {
return {
messageKey: `errors.${err.code}`,
...(err.detail !== undefined && { detail: err.detail }),
};
}
if (err instanceof BmPartialWrite) {
// The phase decides the sentence, because "nothing was deleted, some items
// were added" and "part of your tree is gone" need different advice.
return {
messageKey: err.phase === 'clearing' ? 'errors.PARTIAL_CLEAR' : 'errors.PARTIAL_WRITE',
...(err.detail !== undefined && { detail: err.detail }),
...(err.phase === 'clearing' ? { removed: err.done } : { created: err.done }),
};
}
if (err instanceof BmBrowserError) {
return { messageKey: 'errors.BROWSER', detail: err.detail };
}
return {
messageKey: 'errors.UNKNOWN',
detail: err instanceof Error ? err.message : undefined,
};
}
+153
View File
@@ -0,0 +1,153 @@
/**
* Local-only diagnostics — docs/09 §7, legal/PRIVACY.md.
*
* Purpose: when something goes wrong, a bug report needs more than "it failed"
* — which phase, which error code, in what order. This is a small ring
* buffer the user can copy from About → "Copy diagnostics" and paste into an
* issue themselves.
* Guarantees: in memory only, never written to storage, never sent anywhere
* (there is no network). Entries are an allowlist of codes, counts and
* phase names, and the TYPES enforce it: every string field is a union of
* fixed values, so a title, an address or a file path does not compile —
* 1.1.0's first cut typed them all `string` and only promised it (v1.1.0
* review). Free-text `detail` strings from the browser are never recorded;
* they can quote a URL.
*/
import type { FileFormat, MergeMode } from '../core/model';
import type { ErrorKey } from './describe-error';
/** The import pipeline's milestones (`import/run-import.ts`). */
type ImportPhase = 'parsed' | `planned:${MergeMode}` | 'backup-proven' | 'cleared' | 'written';
type EditAction = 'keep-first' | 'sort';
type StorageIssue = 'settings-read-failed' | 'legal-read-failed' | 'change-decode-failed';
/**
* Error names worth telling apart. Any other is recorded as `'other'`: a
* name is an ordinary string property, and nothing stops code from putting
* data in it.
*/
const KNOWN_ERROR_NAMES = [
'Error',
'TypeError',
'RangeError',
'SyntaxError',
'ReferenceError',
'URIError',
'AggregateError',
'AbortError',
'NotAllowedError',
'NotFoundError',
'SecurityError',
'QuotaExceededError',
'InvalidStateError',
'DataCloneError',
'BmParseError',
'BmBackupError',
'BmBrowserError',
'BmEnvError',
'BmPartialWrite',
'BmAborted',
] as const;
const KNOWN: ReadonlySet<string> = new Set(KNOWN_ERROR_NAMES);
/** An allowlisted error name, `'other'`, or — for a non-Error throw — its `typeof`. */
export type ErrorName =
| (typeof KNOWN_ERROR_NAMES)[number]
| 'other'
| 'string'
| 'number'
| 'bigint'
| 'boolean'
| 'symbol'
| 'undefined'
| 'object'
| 'function';
function isKnownName(name: string): name is (typeof KNOWN_ERROR_NAMES)[number] {
return KNOWN.has(name);
}
/** What a thrown value is called in the log — never its message. */
export function errorName(err: unknown): ErrorName {
if (err instanceof Error) return isKnownName(err.name) ? err.name : 'other';
return typeof err;
}
/** What may be recorded — nothing else type-checks. */
export type DiagEvent =
| { kind: 'import'; phase: ImportPhase; format?: FileFormat; nodes?: number }
| { kind: 'failure'; where: ErrorName; code: ErrorKey }
| { kind: 'edit'; action: EditAction; count?: number }
| { kind: 'storage'; issue: StorageIssue }
| { kind: 'crash'; name: ErrorName };
interface Entry {
/** Milliseconds since the page loaded — no wall-clock time is kept. */
t: number;
event: DiagEvent;
}
const CAPACITY = 200;
const entries: Entry[] = [];
/** Record one event; the oldest drops off past 200. Never throws. */
export function record(event: DiagEvent): void {
entries.push({ t: Math.round(globalThis.performance?.now() ?? 0), event });
if (entries.length > CAPACITY) entries.shift();
}
export interface DiagnosticsContext {
version: string;
locale: string;
theme: string;
}
/**
* The browser and its major version from the user agent: "Firefox 160",
* "Edge 142", "Chrome 142", or "unknown". Edge's agent also says Chrome, so it
* is read first. Since v1.3.0 — until then the report carried `chromeMajor`,
* which said "unknown" on Firefox.
*/
export function browserOf(userAgent: string): string {
for (const [name, pattern] of [
['Firefox', /Firefox\/(\d+)/],
['Edge', /Edg\/(\d+)/],
['Chrome', /Chrome\/(\d+)/],
] as const) {
const major = pattern.exec(userAgent)?.[1];
if (major !== undefined) return `${name} ${major}`;
}
return 'unknown';
}
/** The report the About tab copies: context first, then the events, oldest first. */
export function snapshot(context: DiagnosticsContext): string {
const browser = browserOf(globalThis.navigator?.userAgent ?? '');
return JSON.stringify({ app: 'BookmarkMagic', ...context, browser, events: entries }, null, 2);
}
/** Test teardown — module state outlives a single `it()`. */
export function clearDiagnostics(): void {
entries.length = 0;
}
/**
* Record uncaught errors and unhandled rejections — by NAME only: a message
* can quote whatever the code was looking at. Returns a teardown.
*/
export function installCrashHooks(
target: Pick<Window, 'addEventListener' | 'removeEventListener'>,
): () => void {
const onError = (event: ErrorEvent): void => {
record({ kind: 'crash', name: event.error === undefined ? 'Error' : errorName(event.error) });
};
const onRejection = (event: PromiseRejectionEvent): void => {
record({ kind: 'crash', name: errorName(event.reason) });
};
target.addEventListener('error', onError);
target.addEventListener('unhandledrejection', onRejection);
return () => {
target.removeEventListener('error', onError);
target.removeEventListener('unhandledrejection', onRejection);
};
}
+31 -5
View File
@@ -46,7 +46,11 @@ interface FileSystemWritable {
close: () => Promise<void>;
}
interface FileSystemHandle {
/** The name the user saved under — they may have changed the suggested one. */
name?: string;
createWritable: () => Promise<FileSystemWritable>;
/** Chrome's `FileSystemHandle.remove()`: deletes a file we picked but never wrote. */
remove?: () => Promise<void>;
}
type SaveFilePicker = (options: {
suggestedName?: string;
@@ -69,7 +73,12 @@ export type SaveTarget = FileSystemHandle;
*
* @throws {BmBackupError} `BACKUP_CANCELLED` when the dialog is dismissed.
*/
export async function openSaveTarget(filename: string, mimeType: string): Promise<SaveTarget> {
export async function openSaveTarget(
filename: string,
mimeType: string,
/** The file-type label the dialog shows, localized by the caller (it was hardcoded English). */
description: string,
): Promise<SaveTarget> {
const picker = (globalThis as { showSaveFilePicker?: SaveFilePicker }).showSaveFilePicker;
if (picker === undefined) {
throw new BmBackupError('BACKUP_WRITE_FAILED', 'showSaveFilePicker unavailable');
@@ -78,9 +87,7 @@ export async function openSaveTarget(filename: string, mimeType: string): Promis
try {
return await picker({
suggestedName: sanitizeFilename(filename),
types: [
{ description: 'Bookmark backup', accept: { [mimeType]: [`.${extensionOf(filename)}`] } },
],
types: [{ description, accept: { [mimeType]: [`.${extensionOf(filename)}`] } }],
});
} catch (cause) {
if (cause instanceof Error && cause.name === 'AbortError') {
@@ -112,8 +119,27 @@ function extensionOf(filename: string): string {
return dot === -1 ? 'json' : filename.slice(dot + 1);
}
/** `bookmarks-<scope>-YYYYMMDD-HHmm.<ext>` / backup name — docs/04 §5. */
/** `bookmarks-<scope>-YYYYMMDD-HHmm.<ext>` — docs/04 §5. */
export function timestampSuffix(now: Date): string {
const pad = (n: number): string => String(n).padStart(2, '0');
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}`;
}
/**
* The safety backup's suggested name, to the SECOND. To the minute, a retry
* after a failed Replace suggested the same name, and accepting "replace the
* existing file?" overwrote the complete backup with the half-deleted tree.
*/
export function backupFilename(now: Date): string {
const seconds = String(now.getSeconds()).padStart(2, '0');
return `bookmarkmagic-backup-${timestampSuffix(now)}${seconds}.json`;
}
/**
* Best-effort removal of a file the user picked in the save dialog but that
* never received the backup (the import stopped before writing it). Leaves
* nothing behind, and never throws.
*/
export function discardTarget(pending: Promise<SaveTarget> | undefined): void {
void pending?.then((target) => target.remove?.()).catch(() => undefined);
}
+68 -4
View File
@@ -16,10 +16,16 @@ export class BmAborted extends Error {
}
}
export type BmBackupErrorCode =
| 'BACKUP_SERIALIZE_FAILED'
| 'BACKUP_CANCELLED'
| 'BACKUP_WRITE_FAILED';
/** A runtime list, so `dictionaries.test.ts` can require a message for each. */
export const BM_BACKUP_ERROR_CODES = [
'BACKUP_SERIALIZE_FAILED',
'BACKUP_EXCEEDS_LIMITS',
'BACKUP_STALE',
'BACKUP_CANCELLED',
'BACKUP_WRITE_FAILED',
] as const;
export type BmBackupErrorCode = (typeof BM_BACKUP_ERROR_CODES)[number];
/**
* Thrown when the forced safety backup could not be produced or proven
@@ -46,3 +52,61 @@ export class BmBrowserError extends Error {
this.detail = detail;
}
}
/** A runtime list, so `dictionaries.test.ts` can require a message for each. */
export const BM_ENV_ERROR_CODES = ['NO_WRITABLE_ROOTS', 'WRITE_LOCKED'] as const;
export type BmEnvCode = (typeof BM_ENV_ERROR_CODES)[number];
/**
* Thrown when the environment cannot support the operation at all.
*
* Distinct from `BmBrowserError` on purpose: an absence is not a refusal.
* Reporting "the browser refused a bookmark operation" to someone whose profile
* simply has no writable root sends them looking for the wrong thing.
*/
export class BmEnvError extends Error {
readonly code: BmEnvCode;
readonly detail: string | undefined;
constructor(code: BmEnvCode, detail?: string) {
super(detail === undefined ? code : `${code}: ${detail}`);
this.name = 'BmEnvError';
this.code = code;
this.detail = detail;
}
}
/** Which destructive step was interrupted. */
export type BmWritePhase = 'clearing' | 'writing';
/**
* Thrown when a destructive step failed part-way through.
*
* Carries exactly what already landed, for the same reason `BmAborted` carries
* `done`: a user whose tree was half-replaced needs a number and the name of
* their backup, not "the browser refused a bookmark operation".
*
* `cause` is deliberately not used — `noImplicitOverride` complicates
* redeclaring it, and the detail is flattened here anyway so the UI never has
* to unwrap a chain.
*/
export class BmPartialWrite extends Error {
readonly phase: BmWritePhase;
readonly done: number;
readonly detail: string | undefined;
constructor(phase: BmWritePhase, done: number, cause: unknown) {
const detail =
cause instanceof BmBrowserError
? cause.detail
: cause instanceof Error
? cause.message
: String(cause);
super(`${phase} failed after ${done} item(s): ${detail}`);
this.name = 'BmPartialWrite';
this.phase = phase;
this.done = done;
this.detail = detail;
}
}
+173
View File
@@ -0,0 +1,173 @@
/**
* The live bookmark tree as the browser reports it — docs/02 §4.
*
* Purpose: the pure half of the bookmarks adapter — the node shape, Firefox's
* separators, the counts, and the conversion into the file model. No
* browser call lives here, so every line is tested directly.
* Guarantees: separators are recognised by `type` alone. Firefox gives them
* `url: "data:"`, so every "has a url, so it is a bookmark" test in the code
* would otherwise count, export, dedupe and open them as bookmarks.
*/
import type { BookmarkNode } from '../core/model';
import { millisToSeconds } from '../core/timestamps';
/** The live-tree node. Unlike `BookmarkNode` it carries browser identity. */
export interface LiveNode {
id: string;
parentId?: string;
index?: number;
title: string;
url?: string;
dateAdded?: number;
dateGroupModified?: number;
/** Set by Chrome on policy-managed nodes; such nodes reject writes. */
unmodifiable?: string;
/**
* Chrome 134+: which permanent folder a root is ('bookmarks-bar', 'other',
* 'mobile', 'managed'), and whether it is in the signed-in account's storage
* rather than this device's. Both exist from the 136 floor up; Firefox has
* neither.
*/
folderType?: string;
syncing?: boolean;
/** Firefox: 'bookmark', 'folder' or 'separator'. Chromium does not send it. */
type?: string;
children?: LiveNode[];
}
/** A Firefox separator. By `type`, never by url: a separator's url is "data:". */
export function isSeparator(node: { type?: string }): boolean {
return node.type === 'separator';
}
/**
* The forest without its separators — for everything that reads bookmarks as
* bookmarks (the dedupe index, Merge's folder matching). Untouched branches
* are returned as they are.
*/
export function withoutSeparators(nodes: readonly LiveNode[]): LiveNode[] {
const out: LiveNode[] = [];
for (const node of nodes) {
if (isSeparator(node)) continue;
out.push(
node.children === undefined ? node : { ...node, children: withoutSeparators(node.children) },
);
}
return out;
}
export interface LiveCounts {
bookmarks: number;
folders: number;
/** Firefox only; always 0 in a Chromium browser. */
separators: number;
}
/**
* Count what a forest holds, separators apart. Iterative: Other Bookmarks can
* hold 100k children, and the live tree has no depth cap.
*/
export function countLive(nodes: readonly LiveNode[]): LiveCounts {
const counts: LiveCounts = { bookmarks: 0, folders: 0, separators: 0 };
const stack: LiveNode[] = [];
for (const node of nodes) stack.push(node);
while (stack.length > 0) {
const node = stack.pop();
if (node === undefined) break;
if (isSeparator(node)) counts.separators++;
else if (node.url === undefined) counts.folders++;
else counts.bookmarks++;
for (const child of node.children ?? []) stack.push(child);
}
return counts;
}
export interface ToNodesOptions {
/**
* Id of the Bookmarks Bar. The matching node is marked `toolbar: true`.
*
* Without this the marker is lost, and re-importing the file (including the
* Replace safety backup) lands the entire toolbar under Other Bookmarks —
* `03 §1` routes purely on that flag.
*/
toolbarId?: string;
/**
* Ids of Other and Mobile Bookmarks, and of Firefox's Bookmarks Menu,
* marked `root: 'other'`/`'mobile'`/`'menu'` for the same reason: without
* them a restore nested each one level too deep.
*/
otherId?: string;
mobileId?: string;
menuId?: string;
}
function markerOf(id: string, options: ToNodesOptions): Pick<BookmarkNode, 'toolbar' | 'root'> {
if (id === options.toolbarId) return { toolbar: true };
if (id === options.otherId) return { root: 'other' };
if (id === options.mobileId) return { root: 'mobile' };
if (id === options.menuId) return { root: 'menu' };
return {};
}
/**
* Convert the live tree into the pure file model (ms → s, ids dropped).
* Separators are left out: no format BookmarkMagic writes can hold one
* (docs/04).
*/
export function toBookmarkNodes(
nodes: readonly LiveNode[],
options: ToNodesOptions = {},
): BookmarkNode[] {
const out: BookmarkNode[] = [];
for (const node of nodes) {
if (isSeparator(node)) continue;
const addDate = millisToSeconds(node.dateAdded);
const isFolderNode = node.url === undefined;
// dateGroupModified is a FOLDER field — Chrome does not set it on
// bookmarks, and our HTML serializer only emits LAST_MODIFIED on <H3>.
const lastModified = isFolderNode ? millisToSeconds(node.dateGroupModified) : undefined;
out.push({
title: node.title,
...(node.url !== undefined && { url: node.url }),
...(addDate !== undefined && { addDate }),
...(lastModified !== undefined && { lastModified }),
...(isFolderNode && markerOf(node.id, options)),
...(isFolderNode && { children: toBookmarkNodes(node.children ?? [], options) }),
});
}
return out;
}
/**
* How a browser counts `bookmarks.move`'s index for a move inside one folder
* (docs/05 §10). Chromium counts as if the node were still in place; Firefox
* counts after removing it, because Places stores the final position. Moving
* `a` after `c` in `[a, b, c]` is index 3 in Chrome and 2 in Firefox — and
* sending Chrome's number to Firefox made every rightward drag land one place
* too far and Alt+↓ move two places.
*/
export type MoveIndexRule = 'chromium' | 'firefox';
/** Where a node goes: a folder, and optionally a place in it counted both ways (`planDrop`). */
export interface MoveDestination {
parentId?: string;
/** `api` counted before the node's removal (Chromium's rule), `local` after it. */
position?: { api: number; local: number };
}
/** The index to send under a browser's rule. */
export function moveIndexFor(
position: { api: number; local: number },
rule: MoveIndexRule,
): number {
return rule === 'firefox' ? position.local : position.api;
}
/** Flatten a live tree, parents before children. Used by dedupe and #edit. */
export function flattenLive(nodes: readonly LiveNode[], into: LiveNode[] = []): LiveNode[] {
for (const node of nodes) {
into.push(node);
if (node.children !== undefined) flattenLive(node.children, into);
}
return into;
}
+65 -4
View File
@@ -20,18 +20,79 @@ interface ManagerContext {
windowId?: number;
}
/**
* The channel an open Manager listens on for "go to this route". Same-origin
* and in-browser only: no permission, no network.
*/
export const MANAGER_CHANNEL = 'bookmarkmagic-manager';
interface NavigateMessage {
kind: 'navigate';
route: ManagerRoute;
/** The Manager tab the popup is about to focus; every other one ignores it. */
tabId?: number;
}
const ROUTES: ReadonlySet<string> = new Set(['#import', '#export', '#edit', '#settings', '#about']);
function isNavigateMessage(data: unknown): data is NavigateMessage {
if (typeof data !== 'object' || data === null) return false;
// SAFETY: a non-null object, and every field read is checked below.
const { kind, route, tabId } = data as Record<string, unknown>;
return (
kind === 'navigate' &&
typeof route === 'string' &&
ROUTES.has(route) &&
(tabId === undefined || typeof tabId === 'number')
);
}
/**
* In the Manager: act on the popup's "go to this route". A message addressed
* to another Manager tab is ignored — with two open, the popup's choice used to
* switch every one of them, not just the one it focused (v1.1.0 review).
* `tabs.getCurrent` needs no permission and is not used for anything else.
*
* @returns the unsubscribe.
*/
export function onNavigateRequest(handle: (route: ManagerRoute) => void): () => void {
const channel = new BroadcastChannel(MANAGER_CHANNEL);
const own = browser.tabs
.getCurrent()
.then((tab) => tab?.id)
.catch(() => undefined);
channel.onmessage = (event: MessageEvent<unknown>) => {
const data = event.data;
if (!isNavigateMessage(data)) return;
void own.then((tabId) => {
// Unknown on either side → the 1.1.0-first-cut behaviour: everyone moves.
if (data.tabId !== undefined && tabId !== undefined && data.tabId !== tabId) return;
handle(data.route);
});
};
return () => channel.close();
}
/**
* Focus an existing Manager tab or open a new one at `route`.
*
* Note the asymmetry: a NEW tab lands on the requested route, but an existing
* tab is only focused — its hash is left alone rather than forced, so an
* in-progress import is never navigated away from (docs/03 §5).
* An existing tab is asked — not forced — to switch route over a
* BroadcastChannel; it refuses while an import is writing (docs/03 §5). 1.0.x
* only focused it, so the popup's "Export" landed wherever the tab had been.
*/
export async function openManager(route: ManagerRoute = '#import'): Promise<void> {
const managerUrl = browser.runtime.getURL(MANAGER_PAGE);
const existing = await findManagerContext(managerUrl);
if (existing?.tabId !== undefined) {
// Posted before focusing: the popup closes as soon as the tab takes focus.
const channel = new BroadcastChannel(MANAGER_CHANNEL);
channel.postMessage({
kind: 'navigate',
route,
tabId: existing.tabId,
} satisfies NavigateMessage);
channel.close();
await browser.tabs.update(existing.tabId, { active: true });
if (existing.windowId !== undefined) {
await browser.windows.update(existing.windowId, { focused: true });
@@ -43,7 +104,7 @@ export async function openManager(route: ManagerRoute = '#import'): Promise<void
}
async function findManagerContext(managerUrl: string): Promise<ManagerContext | undefined> {
// getContexts is Chrome 116+; our floor is 120. Guard anyway so a future
// getContexts is Chrome 116+; our floor is 136. Guard anyway so a future
// Firefox target degrades to "always open a new tab" rather than throwing.
const getContexts = (
browser.runtime as {
+54
View File
@@ -0,0 +1,54 @@
/**
* Opening a bookmarked URL — the docs/09 T3 control.
*
* Purpose: the single gate between a URL that came out of someone's import file
* and the browser actually navigating to it.
* Inputs: a URL string from untrusted file data.
* Guarantees: only `http:` and `https:` ever reach `tabs.create`. Nothing is
* opened for an unparseable URL, and nothing throws.
*/
import { browser } from 'wxt/browser';
/** Schemes allowed to reach the browser. Everything else is display-only. */
const ALLOWED_SCHEMES = new Set(['http:', 'https:']);
/**
* Whether this URL would be refused — so the row can warn BEFORE the click.
*
* docs/09 T3 asks for both halves: block the navigation, and mark the bookmark
* so a `javascript:` entry titled "Your bank" does not look like an ordinary
* link that simply does nothing.
*/
export function isBlockedUrl(url: string | undefined): boolean {
if (url === undefined) return false;
try {
return !ALLOWED_SCHEMES.has(new URL(url).protocol);
} catch {
return true;
}
}
/**
* Open `url` in a new tab if its scheme is allowed.
*
* Returns whether it was opened, so callers and tests can tell "blocked" from
* "opened" rather than inferring it.
*
* Chromium also refuses `javascript:` from `tabs.create`, but this allowlist is
* the authoritative control: it is ours, it is testable, and it does not move
* when a browser changes its mind. `data:`, `file:` and `chrome:` are blocked
* here even though some are navigable, because a bookmark file is untrusted
* input and none of them are worth the surface.
*/
export async function openBookmarkUrl(url: string): Promise<boolean> {
let scheme: string;
try {
scheme = new URL(url).protocol;
} catch {
return false;
}
if (!ALLOWED_SCHEMES.has(scheme)) return false;
await browser.tabs.create({ url });
return true;
}
+139
View File
@@ -0,0 +1,139 @@
/**
* Which live folders are the browser's permanent roots — docs/02 §4.
*
* Purpose: find the import's destinations — the bar, Other, Mobile, and on
* Firefox the Bookmarks Menu — in whatever browser this runs in.
* Guarantees: this device's roots only (a signed-in Chrome account's own roots
* are listed but never written to or emptied); policy-managed roots never;
* and on Firefox the Menu is never mistaken for the bar.
*/
import { browser } from 'wxt/browser';
import { getRootChildren } from './bookmarks';
import { BmEnvError } from './errors';
import type { LiveNode, ToNodesOptions } from './live-tree';
export interface BookmarkRoots {
/** Bookmarks Bar. */
toolbarId: string;
/** Other Bookmarks. */
otherId: string;
/** Mobile Bookmarks, when the profile has one. */
mobileId: string | undefined;
/** Firefox's Bookmarks Menu. No Chromium browser has one. */
menuId: string | undefined;
/** The same roots as nodes, children included — Merge matches inside them. */
toolbar: LiveNode;
other: LiveNode;
mobile: LiveNode | undefined;
menu: LiveNode | undefined;
/** Writable top-level folders, in tree order, excluding managed ones. */
writable: LiveNode[];
/**
* The roots Replace backs up and empties: exactly the destinations above.
* Never an account-storage root this import does not write back into —
* deleting one would sync the deletion to every device, and the restore
* would land its bookmarks in local storage.
*/
replaceable: LiveNode[];
/** Every top-level folder, managed ones included — what "already in this browser" means. */
all: LiveNode[];
}
/** Chromium's stable ids for the three permanent folders. */
const CHROMIUM_IDS = { 'bookmarks-bar': '1', other: '2', mobile: '3' } as const;
/** Firefox's permanent folders — Places GUIDs, the same in every profile. */
const FIREFOX_IDS = {
'bookmarks-bar': 'toolbar_____',
other: 'unfiled_____',
mobile: 'mobile______',
} as const;
const FIREFOX_MENU_ID = 'menu________';
/**
* Desktop Chrome leaves an EMPTY Mobile root out of `getTree()`, so a restore
* into a fresh profile found no Mobile root and nested those bookmarks under
* Other. The node still exists, and accepts writes; ask for it by id. (Firefox
* always lists its Mobile root, and rejects the id "3" — caught here.)
*/
async function hiddenMobileRoot(): Promise<LiveNode | undefined> {
try {
const [node] = (await browser.bookmarks.get(CHROMIUM_IDS.mobile)) as LiveNode[];
const usable =
node !== undefined &&
node.url === undefined &&
node.unmodifiable === undefined &&
node.syncing !== true &&
(node.folderType === undefined || node.folderType === 'mobile');
return usable ? { ...node, children: node.children ?? [] } : undefined;
} catch {
return undefined;
}
}
/**
* Resolve the destination roots.
*
* By `folderType` first — Chrome 134+ can list a signed-in account's own bar,
* Other and Mobile beside this device's, and the old by-id-then-by-position
* rule mixed the two sets up. Then the stable Chromium ids, then Firefox's
* GUIDs, and position last. The Bookmarks Menu is never a candidate for a
* position: Firefox lists it first, and until v1.3.0 the position fallback
* took it for the bar — Replace would have emptied the Menu and the toolbar
* and restored the bar's bookmarks into the Menu. Nodes carrying
* `unmodifiable` (the enterprise "Managed bookmarks" folder) are excluded
* everywhere — writing to or removing them rejects.
*/
export async function getRoots(): Promise<BookmarkRoots> {
const children = await getRootChildren();
const writable = children.filter((node) => node.unmodifiable === undefined);
const local = writable.filter((node) => node.syncing !== true);
const typed = local.some((node) => node.folderType !== undefined);
const menu = local.find((node) => node.id === FIREFOX_MENU_ID);
const positional = local.filter((node) => node !== menu);
const pick = (type: keyof typeof CHROMIUM_IDS): LiveNode | undefined =>
local.find((node) => node.folderType === type) ??
local.find((node) => node.id === CHROMIUM_IDS[type]) ??
local.find((node) => node.id === FIREFOX_IDS[type]);
const toolbar = pick('bookmarks-bar') ?? (typed ? undefined : positional[0]);
const other = pick('other') ?? (typed ? undefined : positional.find((n) => n !== toolbar));
const mobile =
pick('mobile') ??
(typed ? undefined : positional.find((n) => n !== toolbar && n !== other)) ??
(await hiddenMobileRoot());
if (toolbar === undefined || other === undefined) {
// Not a BmBrowserError: nothing refused anything. Every root this profile
// has is policy-managed, so there is nowhere an extension may write, and
// "the browser refused a bookmark operation" would be actively misleading.
throw new BmEnvError('NO_WRITABLE_ROOTS', `${children.length} root(s), none writable`);
}
const replaceable = [toolbar, other];
if (mobile !== undefined) replaceable.push(mobile);
if (menu !== undefined) replaceable.push(menu);
return {
toolbarId: toolbar.id,
otherId: other.id,
mobileId: mobile?.id,
menuId: menu?.id,
toolbar,
other,
mobile,
menu,
writable,
replaceable,
all: children,
};
}
/** The marker ids for a whole-tree conversion — what an export or backup passes. */
export function rootMarkersOf(roots: BookmarkRoots): ToNodesOptions {
return {
toolbarId: roots.toolbarId,
otherId: roots.otherId,
...(roots.mobileId !== undefined && { mobileId: roots.mobileId }),
...(roots.menuId !== undefined && { menuId: roots.menuId }),
};
}
+60 -9
View File
@@ -8,9 +8,10 @@
* defaults, because a corrupt settings blob must not brick the Manager.
*/
import { browser } from 'wxt/browser';
import type { CsvDelimiter } from '../core/serialize/csv';
import type { CsvDelimiter } from '../core/csv-dialect';
import type { MarkdownStyle } from '../core/serialize/markdown';
import type { Locale } from '../i18n/resolve-locale';
import { LOCALES, type Locale } from '../i18n/resolve-locale';
import { record } from './diagnostics';
export type ThemePreference = 'system' | 'light' | 'dark';
export type ExportFormat = 'netscape-html' | 'bm-json' | 'csv' | 'markdown';
@@ -54,7 +55,7 @@ function coerceSettings(raw: unknown): Settings {
allowed.includes(raw[key] as Settings[K]) ? (raw[key] as Settings[K]) : DEFAULT_SETTINGS[key];
return {
locale: pick('locale', ['auto', 'en', 'vi', 'ja']),
locale: pick('locale', ['auto', ...LOCALES]),
theme: pick('theme', ['system', 'light', 'dark']),
defaultExportFormat: pick('defaultExportFormat', [
'netscape-html',
@@ -73,6 +74,7 @@ export async function readSettings(): Promise<Settings> {
const stored = await browser.storage.local.get(SETTINGS_KEY);
return coerceSettings(stored[SETTINGS_KEY]);
} catch {
record({ kind: 'storage', issue: 'settings-read-failed' });
return { ...DEFAULT_SETTINGS };
}
}
@@ -81,16 +83,23 @@ export async function writeSettings(settings: Settings): Promise<void> {
await browser.storage.local.set({ [SETTINGS_KEY]: settings });
}
/** Keep only a well-formed acceptance record; anything else is "never accepted". */
function coerceLegal(raw: unknown): LegalAcceptance | null {
if (!isRecord(raw) || typeof raw.acceptedVersion !== 'number') return null;
return {
acceptedVersion: raw.acceptedVersion,
// Coerced rather than left missing: `Intl.format(new Date(''))` throws a
// RangeError inside a render, which would blank the About tab.
acceptedAt: typeof raw.acceptedAt === 'string' ? raw.acceptedAt : '',
};
}
export async function readLegal(): Promise<LegalAcceptance | null> {
try {
const stored = await browser.storage.local.get(LEGAL_KEY);
const raw = stored[LEGAL_KEY];
if (!isRecord(raw) || typeof raw.acceptedVersion !== 'number') return null;
return {
acceptedVersion: raw.acceptedVersion,
acceptedAt: typeof raw.acceptedAt === 'string' ? raw.acceptedAt : '',
};
return coerceLegal(stored[LEGAL_KEY]);
} catch {
record({ kind: 'storage', issue: 'legal-read-failed' });
return null;
}
}
@@ -106,3 +115,45 @@ export async function writeLegal(acceptedVersion: number, nowIso: string): Promi
[LEGAL_KEY]: { acceptedVersion, acceptedAt: nowIso } satisfies LegalAcceptance,
});
}
/** What changed, already coerced. A key absent from the event stays absent. */
export interface StorageChange {
settings?: Settings;
legal?: LegalAcceptance | null;
}
/**
* Watch for writes made by another extension context — a second Manager tab.
*
* The event fires in *every* context including the one that wrote, so the
* caller has to decide what is an echo of its own write; this layer only
* decodes and hands over. Values are coerced through the same functions the
* read path uses, because a second tab is not a more trustworthy source than
* disk — it is the same disk.
*
* @returns an unsubscribe function.
*/
export function subscribeStorage(handler: (change: StorageChange) => void): () => void {
const onChanged = (changes: Record<string, { newValue?: unknown }>, areaName: string): void => {
// Everything this extension stores is in `local`; `sync` is never used
// (docs/09 §1.3) and a write there is not ours to react to.
if (areaName !== 'local') return;
try {
const change: StorageChange = {};
if (SETTINGS_KEY in changes)
change.settings = coerceSettings(changes[SETTINGS_KEY]?.newValue);
if (LEGAL_KEY in changes) change.legal = coerceLegal(changes[LEGAL_KEY]?.newValue);
if (change.settings !== undefined || 'legal' in change) handler(change);
} catch {
record({ kind: 'storage', issue: 'change-decode-failed' });
// A throw inside a chrome.* listener surfaces as an extension error in
// chrome://extensions, which the QA pass treats as a failure. Nothing
// here is worth that: the next read will pick up the same value.
}
};
browser.storage.onChanged.addListener(onChanged);
return () => {
browser.storage.onChanged.removeListener(onChanged);
};
}
+34
View File
@@ -0,0 +1,34 @@
/**
* One writer at a time, across every Manager tab — docs/03 §5.
*
* Purpose: two tabs replacing at once would each back up, then delete what the
* other was writing; a sort racing an import reorders a folder mid-write.
* Inputs: the bulk operation to run.
* Guarantees: uses the Web Locks API (in-browser, same-origin, no permission).
* The lock is taken only if it is free — a second writer is refused at once
* with `BmEnvError('WRITE_LOCKED')`, never queued behind a write the user
* cannot see. Where the API is missing (tests), the operation simply runs.
*/
import { BmEnvError } from './errors';
const LOCK_NAME = 'bookmarkmagic-write';
interface LockManagerLike {
request: <T>(
name: string,
options: { ifAvailable: boolean },
run: (lock: unknown) => Promise<T>,
) => Promise<T>;
}
/** @throws {BmEnvError} `WRITE_LOCKED` when another tab holds the lock. */
export async function withWriteLock<T>(run: () => Promise<T>): Promise<T> {
const locks = (globalThis.navigator as { locks?: LockManagerLike } | undefined)?.locks;
if (locks === undefined) return run();
return locks.request(LOCK_NAME, { ifAvailable: true }, async (lock) => {
if (lock === null) {
throw new BmEnvError('WRITE_LOCKED', 'another BookmarkMagic tab is writing bookmarks');
}
return run();
});
}
+25 -10
View File
@@ -2,7 +2,8 @@
* Sequential tree writer — docs/05 §6.
*
* Purpose: create an `ImportPlan`'s nodes in order, with live progress and a
* working cancel button.
* working cancel button. A segment's parent is a root or, in Merge, a folder
* the user already has; either way it exists before the first create.
* Inputs: a plan, an AbortSignal, a progress callback.
* Guarantees: parents before children, siblings in order, one `done` counter
* across all segments, and an abort that stops before the next create.
@@ -12,9 +13,9 @@
*/
import type { BookmarkNode, ImportPlan } from '../core/model';
import { create as createNode, type LiveNode } from './bookmarks';
import { BmAborted } from './errors';
import { BmAborted, BmPartialWrite } from './errors';
/** Emitted every PROGRESS_EVERY creates and once at the end. */
/** Emitted after the first create, every PROGRESS_EVERY creates, and once at the end. */
export interface WriteProgress {
done: number;
total: number;
@@ -55,6 +56,9 @@ export interface WriteResult {
*
* @throws {BmAborted} when the signal fires — carrying the exact number of
* nodes already created, so the report can tell the user what landed.
* @throws {BmPartialWrite} when a create rejects, carrying the same count. A
* rejection half-way through leaves real bookmarks in the user's tree; a bare
* "the browser refused" gives them no way to know how many.
*/
export async function writeTree(
plan: ImportPlan,
@@ -81,15 +85,26 @@ export async function writeTree(
for (const node of nodes) {
if (signal?.aborted === true) throw new BmAborted(done);
const created = await create({
parentId,
title: node.title,
...(node.url !== undefined && { url: node.url }),
});
let created: LiveNode;
try {
created = await create({
parentId,
title: node.title,
...(node.url !== undefined && { url: node.url }),
});
} catch (cause) {
// Order matters. The abort check above throws from inside this same
// loop, and wrapping it would relabel every user cancellation as a
// failure — making `cancelled` unreachable and its copy dead.
if (cause instanceof BmAborted) throw cause;
throw new BmPartialWrite('writing', done, cause);
}
done++;
sinceYield++;
if (done % PROGRESS_EVERY === 0 || done === total) report(trail.join(' / '));
// The first create reports too: on a slow profile, 50 creates can take
// seconds, and a bar stuck at 0% reads as a hang (uL9).
if (done === 1 || done % PROGRESS_EVERY === 0 || done === total) report(trail.join(' / '));
if (sinceYield >= YIELD_EVERY) {
sinceYield = 0;
await yieldToEventLoop();
@@ -102,7 +117,7 @@ export async function writeTree(
};
for (const segment of plan.segments) {
await dfs(segment.nodes, segment.rootId, []);
await dfs(segment.nodes, segment.parentId, segment.trail ?? []);
}
// Guarantee a final event even when the total was not a multiple of 50 and
+187
View File
@@ -0,0 +1,187 @@
<script lang="ts">
import { getAppVersion, getExtensionId } from '../browser/app-info';
import { dateTime, t } from '../i18n/index.svelte';
import {
ACCESSIBILITY_URL,
CHANGELOG_URL,
DONATE_LINKS,
ISSUES_URL,
LEGAL_URLS,
REPO_URL,
storeUrlFor,
} from '../links';
import { copyToClipboard } from '../browser/clipboard';
import { snapshot } from '../browser/diagnostics';
import { getAcceptance } from '../stores/legal.svelte';
import { getSettings } from '../stores/settings.svelte';
import { pushToast } from '../stores/toast.svelte';
import Button from './Button.svelte';
import Icon from './icons/Icon.svelte';
const version = getAppVersion();
// The listing this copy came from (docs/06 §3.5): AMO for the Firefox build,
// the Chrome Web Store for its own id, the install page for anything else.
const storeUrl = storeUrlFor({ firefox: import.meta.env.FIREFOX, extensionId: getExtensionId() });
const acceptance = $derived(getAcceptance());
// undefined when acceptedAt is missing or unparseable — storage coerces a
// missing timestamp to '', and formatting that would throw inside the render.
const acceptedOn = $derived(
acceptance === undefined ? undefined : dateTime(acceptance.acceptedAt),
);
/** Write-only, on an explicit click (docs/09 T8): the user pastes it into an issue. */
async function copyDiagnostics(): Promise<void> {
const settings = getSettings();
const report = snapshot({ version, locale: settings.locale, theme: settings.theme });
const copied = await copyToClipboard(report);
pushToast(t(copied ? 'about.diagnosticsCopied' : 'about.diagnosticsCopyFailed'), copied ? 'success' : 'danger');
}
</script>
<section aria-label={t('common.about')}>
<header>
<img src="/icon/48.png" alt="" width="48" height="48" />
<div>
<strong>{t('common.appName')}</strong>
{#if version !== ''}<span class="version mono">{t('about.version', { version })}</span>{/if}
</div>
</header>
<p class="tagline">{t('about.tagline')}</p>
<h2 class="eyebrow">{t('about.links')}</h2>
<ul class="links">
<li><a href={REPO_URL} target="_blank" rel="noopener noreferrer">{t('about.repo')}<Icon name="external" size={12} /></a></li>
<li><a href={ISSUES_URL} target="_blank" rel="noopener noreferrer">{t('about.issues')}<Icon name="external" size={12} /></a></li>
<li>
<a href={CHANGELOG_URL} target="_blank" rel="noopener noreferrer">
{t('about.changelog')}<Icon name="external" size={12} />
</a>
</li>
<li>
<a href={ACCESSIBILITY_URL} target="_blank" rel="noopener noreferrer">
{t('about.accessibility')}<Icon name="external" size={12} />
</a>
</li>
<li><a href={storeUrl} target="_blank" rel="noopener noreferrer">{t('about.store')}<Icon name="external" size={12} /></a></li>
</ul>
<h2 class="eyebrow">{t('about.thirdParty')}</h2>
<p class="muted">{t('about.thirdPartyNote')}</p>
<h2 class="eyebrow">{t('about.donate')}</h2>
<p class="muted">{t('about.donateNote')}</p>
<ul class="links">
{#each DONATE_LINKS as link (link.url)}
<li><a href={link.url} target="_blank" rel="noopener noreferrer">{link.label}<Icon name="external" size={12} /></a></li>
{/each}
</ul>
<h2 class="eyebrow">{t('about.legal')}</h2>
<ul class="links">
{#each LEGAL_URLS as link (link.url)}
<li>
<a href={link.url} target="_blank" rel="noopener noreferrer">{t(link.labelKey)}<Icon name="external" size={12} /></a>
</li>
{/each}
</ul>
<p class="muted">{t('legal.englishNote')}</p>
<p class="muted">
<!-- The version the user ACCEPTED, not LEGAL_VERSION: if they differ the
gate is up anyway, and showing the current constant here would claim
consent that was never given (docs/06 §3.5). -->
{#if acceptance === undefined}
{t('about.notAccepted')}
{:else if acceptedOn === undefined}
{t('about.acceptedUndated', { version: acceptance.acceptedVersion })}
{:else}
{t('about.accepted', {
date: acceptedOn,
version: acceptance.acceptedVersion,
})}
{/if}
</p>
<h2 class="eyebrow">{t('about.diagnostics')}</h2>
<p class="muted">{t('about.diagnosticsNote')}</p>
<div>
<Button size="sm" icon="copy" onclick={() => void copyDiagnostics()}>
{t('about.copyDiagnostics')}
</Button>
</div>
</section>
<style>
section {
max-width: 720px;
display: flex;
flex-direction: column;
gap: var(--sp-2);
}
header {
display: flex;
align-items: center;
gap: var(--sp-3);
padding: var(--sp-4);
border: 1px solid var(--border-strong);
border-radius: var(--radius);
background: var(--bg-raised);
}
header div {
display: flex;
flex-direction: column;
}
header strong {
font-size: var(--fs-3);
}
.version {
font-size: var(--fs-0);
color: var(--fg-muted);
}
.tagline {
margin: var(--sp-2) 0 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
h2 {
margin: var(--sp-4) 0 0;
}
.muted {
margin: 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
.links {
display: flex;
flex-wrap: wrap;
gap: var(--sp-2);
margin: 0;
padding: 0;
list-style: none;
font-size: var(--fs-1);
}
.links a {
display: inline-flex;
align-items: center;
gap: var(--sp-1);
padding: 4px var(--sp-2);
border: 1px solid var(--border-strong);
border-radius: var(--radius-sm);
background: var(--bg);
text-decoration: none;
}
.links a:hover {
border-color: var(--accent);
background: var(--accent-subtle);
}
</style>
+95 -17
View File
@@ -1,38 +1,93 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import type { HTMLButtonAttributes } from 'svelte/elements';
import Icon, { type IconMotion, type IconName } from './icons/Icon.svelte';
interface Props {
variant?: 'primary' | 'secondary' | 'danger';
disabled?: boolean;
type?: 'button' | 'submit';
onclick?: () => void;
children: Snippet;
interface Props extends Omit<HTMLButtonAttributes, 'children' | 'class'> {
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
size?: 'sm' | 'md';
icon?: IconName;
iconMotion?: IconMotion;
/**
* Accessible name for an icon-only button. Required in practice: with no
* children and no label, the button would be announced as just "button".
*/
label?: string;
children?: Snippet;
}
let { variant = 'secondary', disabled = false, type = 'button', onclick, children }: Props =
$props();
let {
variant = 'secondary',
size = 'md',
type = 'button',
icon,
iconMotion = 'none',
label,
children,
...rest
}: Props = $props();
</script>
<button class={variant} {type} {disabled} {onclick}>{@render children()}</button>
<button
class="btn {variant} {size}"
class:icon-only={children === undefined}
{type}
aria-label={label}
title={rest.title ?? label}
{...rest}
>
{#if icon !== undefined}<Icon name={icon} motion={iconMotion} size={size === 'sm' ? 14 : 16} />{/if}
{#if children !== undefined}<span>{@render children()}</span>{/if}
</button>
<style>
button {
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: var(--sp-2);
font: inherit;
padding: var(--sp-2) var(--sp-4);
font-size: var(--fs-1);
font-weight: 500;
line-height: 1.2;
padding: 7px var(--sp-3);
border-radius: var(--radius-sm);
border: 1px solid var(--border);
background: var(--bg-raised);
border: 1px solid var(--border-strong);
background: var(--bg);
color: var(--fg);
cursor: pointer;
white-space: nowrap;
transition:
background-color var(--dur-1) linear,
border-color var(--dur-1) linear,
color var(--dur-1) linear;
}
button:hover:not(:disabled) {
.sm {
padding: 4px var(--sp-2);
font-size: var(--fs-0);
}
.icon-only {
padding: 6px;
}
.sm.icon-only {
padding: 4px;
}
.btn:hover:not(:disabled) {
border-color: var(--accent);
color: var(--accent);
}
button:disabled {
opacity: 0.5;
/* Disabled is said with colour and the cursor, not opacity: dimmed text drops
under the contrast floor while it is still meant to be read. */
.btn:disabled {
cursor: not-allowed;
background: var(--bg-sunken);
border-color: var(--border);
color: var(--fg-muted);
}
.primary {
@@ -41,9 +96,32 @@
color: var(--accent-fg);
}
.primary:hover:not(:disabled) {
color: var(--accent-fg);
background: color-mix(in srgb, var(--accent) 88%, var(--fg));
}
.danger {
background: var(--danger);
border-color: var(--danger);
color: #fff;
/* Not #fff: dark mode lightens --danger, where white ink fails 4.5:1. */
color: var(--danger-fg);
}
.danger:hover:not(:disabled) {
color: var(--danger-fg);
border-color: var(--danger);
background: color-mix(in srgb, var(--danger) 88%, var(--fg));
}
.ghost {
background: transparent;
border-color: transparent;
color: var(--fg-muted);
}
.ghost:hover:not(:disabled) {
background: var(--bg-raised);
border-color: var(--border);
}
</style>
+39 -2
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import Icon, { type IconName } from './icons/Icon.svelte';
interface Props {
tone?: 'info' | 'warn' | 'danger' | 'success';
@@ -7,30 +8,66 @@
}
let { tone = 'info', children }: Props = $props();
const ICONS: Record<NonNullable<Props['tone']>, IconName> = {
info: 'info',
warn: 'warning',
danger: 'error',
success: 'check',
};
</script>
<div class="callout {tone}" role={tone === 'danger' ? 'alert' : undefined}>
{@render children()}
<span class="glyph">
<Icon name={ICONS[tone]} motion={tone === 'success' ? 'draw' : 'none'} size={16} />
</span>
<div class="text">{@render children()}</div>
</div>
<style>
.callout {
display: flex;
gap: var(--sp-3);
align-items: flex-start;
padding: var(--sp-3);
border-radius: var(--radius-sm);
border: 1px solid var(--border);
border-left: 3px solid var(--fg-muted);
border-radius: var(--radius-sm);
background: var(--bg-raised);
font-size: var(--fs-1);
}
.glyph {
display: flex;
padding-top: 1px;
color: var(--fg-muted);
}
.text {
min-width: 0;
}
.warn {
border-left-color: var(--warn);
}
.warn .glyph {
color: var(--warn);
}
.danger {
border-left-color: var(--danger);
}
.danger .glyph {
color: var(--danger);
}
.success {
border-left-color: var(--success);
}
.success .glyph {
color: var(--success);
}
</style>
Loaded 100 of 318 files, more files were not shown because too many files have changed in this diff. Show more