Compare commits

...
10 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5 ad96b4f0f9 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:16:57 +07:00
poli0981andClaude Opus 5 253e7782d0 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:04:53 +07:00
poli0981andClaude Opus 5 cf0435e7b7 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:02:36 +07:00
poli0981andClaude Opus 5 6c4c307a25 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 19:27:43 +07:00
poli0981andClaude Opus 5 a2c5dc947c 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 19:22:25 +07:00
poli0981andClaude Opus 5 b1698aca0b 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 19:16:12 +07:00
poli0981andClaude Opus 5 8882be03cb 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 19:13:56 +07:00
poli0981andClaude Opus 5 121a5a6957 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 19:11:32 +07:00
poli0981andClaude Opus 5 36c39f3185 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 19:00:27 +07:00
poli0981andClaude Opus 5 5ce1abe744 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 18:51:12 +07:00
50 changed files with 2508 additions and 3607 deletions

No files matched your search

+21 -4
View File
@@ -1,10 +1,16 @@
# Caller stub — docs/12 §2.4.
#
# The reusable already filters to `conclusion == 'failure'` on the default
# branch, so this caller needs no `if:`.
# 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.
#
# ⚠️ It declares `DISCORD_CI_WEBHOOK` as `required: true`, so this workflow
# fails until that repo secret exists (docs/12 §5).
# 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:
@@ -18,6 +24,17 @@ permissions:
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
+28 -7
View File
@@ -53,12 +53,24 @@ jobs:
working-directory: .output
run: sha256sum *-chrome.zip > SHA256SUMS.txt
# Idempotent on purpose. `gh release create` fails outright if a Release
# for the tag already exists, so any failure AFTER this step — realistically
# the CWS publish below, once CWS_AUTOPUBLISH is on — used to strand the
# tag: re-running the workflow could not get past this line, and the only
# recovery was deleting the Release and the tag by hand (docs/13 §7).
- name: GitHub Release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
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" \
.output/*-chrome.zip .output/SHA256SUMS.txt --clobber
else
gh release create "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
fi
# v1.0.x is published by hand (docs/12 §3) — first store reviews often
# ask questions and want a human in the loop. Flipping the repo variable
@@ -78,13 +90,22 @@ jobs:
# would silently never fire.
announce:
needs: release
# A Discord notification is not part of the release. The reusable exits 1
# on "No webhooks configured" when DISCORD_RELEASES_WEBHOOK and
# A Discord notification is not part of the release. The reusable exits 1 on
# "No webhooks configured" when DISCORD_RELEASES_WEBHOOK and
# DISCORD_REPO_WEBHOOK are both unset (docs/12 §5 lists them as optional),
# which turned the v1.0.0 run red even though the Release, the zip and
# SHA256SUMS.txt had all published correctly. A red run on a good release
# is worse than a missing announcement: it trains you to ignore the colour.
continue-on-error: true
# SHA256SUMS.txt had all published correctly. A red run on a good release is
# worse than a missing announcement: it trains you to ignore the colour.
#
# ⚠️ This used to say `continue-on-error: true`, which GitHub REJECTS on a
# job that calls a reusable workflow — "Property continue-on-error is not
# allowed". The whole file is then invalid and the run is a startup_failure
# with zero jobs and no log, exactly like the `contents: write` mistake in
# 2c8fba9. It was never caught because that fix landed after the v1.0.0 tag
# and no tag has been pushed since, so the first v1.0.1 tag would have been
# its first execution. Gate on a repo VARIABLE instead — allowed in `if:`,
# unlike a secret, and the same idiom as CWS_AUTOPUBLISH above.
if: vars.DISCORD_ANNOUNCE == 'true'
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
+46 -2
View File
@@ -13,9 +13,52 @@ breaking format or schema changes (a BM JSON version bump).
Nothing yet.
## [1.0.1] — 2026-08-03
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.
First public release. Approved by the Chrome Web Store and available to install
from 2026-08-03.
### Added
@@ -44,5 +87,6 @@ First public release.
- 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.0.0...HEAD
[Unreleased]: https://github.com/poli0981/bookmarkmagic/compare/v1.0.1...HEAD
[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
+7
View File
@@ -141,6 +141,13 @@ the tag and performs the store update per docs/13 §1b.
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.
- 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.
+7 -4
View File
@@ -148,9 +148,10 @@ Derived identifiers (canonical across docs and code):
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. **Still open:** the asset reconciliation in item 3, and
`store/listing.{en,vi,ja}.md` — `13 §4` promises the listing copy is
version-controlled in-repo, and it is not.
§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`
@@ -158,7 +159,9 @@ Derived identifiers (canonical across docs and code):
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 `continue-on-error` since `5f4c6e7`.
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
+4 -2
View File
@@ -19,12 +19,14 @@
|---|---|---|
| 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`. |
| **WXT** | **^0.21.3** (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** | **~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. |
| svelte-check | ^4.7.4 | Type/template authority for `.svelte` files. |
| **@types/node** | **^24** (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 | **^30** (was ^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.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. |
+1 -1
View File
@@ -196,7 +196,7 @@ failure mode that would hit every installed user at once.
### 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**:
folders), timed **under jsdom 29**:
| Stage | Time |
|---|---|
+52 -18
View File
@@ -196,12 +196,18 @@ jobs:
working-directory: .output
run: sha256sum *-chrome.zip > SHA256SUMS.txt
- name: GitHub Release
- name: GitHub Release # idempotent — see below
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release create "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
set -euo pipefail
if gh release view "$GITHUB_REF_NAME" >/dev/null 2>&1; then
gh release upload "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --clobber
else
gh release create "$GITHUB_REF_NAME" \
.output/*-chrome.zip .output/SHA256SUMS.txt --generate-notes
fi
- name: Publish to Chrome Web Store
if: vars.CWS_AUTOPUBLISH == 'true'
@@ -214,7 +220,7 @@ jobs:
announce:
needs: release
continue-on-error: true # see below
if: vars.DISCORD_ANNOUNCE == 'true' # see below — NOT continue-on-error
uses: poli0981/.github/.github/workflows/announce-release.yml@main
permissions:
contents: read
@@ -223,11 +229,32 @@ jobs:
secrets: inherit
```
`continue-on-error` because the reusable exits 1 on "No webhooks configured"
when both Discord secrets are unset — which §5 lists as optional. 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.
**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 CWS publish step, 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.
The announcement is gated because the reusable exits 1 on "No webhooks
configured" when both Discord secrets are unset — which §5 lists as optional. 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.
⚠️ **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, it makes the whole run a `startup_failure` with zero jobs and no log.
That is the same silent shape as the `contents: write` mistake in §2.1, and it
sat undetected in this repo from `5f4c6e7` until 2026-08-03 precisely because
that commit landed *after* the `v1.0.0` tag and no tag was pushed in between —
the first v1.0.1 tag would have been its first execution.
A **variable** and not a secret: secrets cannot be referenced in a job-level
`if:`. `vars.DISCORD_ANNOUNCE` defaults to unset, so the announcement is skipped
and the release stays green until the owner opts in — the same idiom as
`CWS_AUTOPUBLISH`. Set the variable only once the webhook secrets exist.
`tag_override` is **required here**, and for the same reason the announcement
is a job rather than a caller. The reusable resolves
@@ -256,8 +283,7 @@ permissions:
jobs:
notify:
if: github.event.workflow_run.conclusion == 'failure'
continue-on-error: true
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
@@ -272,14 +298,17 @@ cost, and not for the failure below.
⚠️ **The reusable declares `DISCORD_CI_WEBHOOK` as `required: true`**, which
GitHub validates before any of the reusable's own logic runs. With the secret
unset (`00 §10.6`), the caller therefore failed on **every** CI completion —
success or failure — from the first push after this file landed. The `if:` stops
it being called on green runs at all, and `continue-on-error` keeps a missing
optional webhook from turning a genuine CI *failure* into two failures.
success or failure — from the first push after this file landed.
This is the same reasoning as `2.3`'s `continue-on-error` on `announce`, learned
the same way: a notification must never be able to change the colour of the
thing it is reporting on, because a run that is red for a reason nobody acts on
teaches everyone to stop reading the colour.
Both halves of the condition earn their place: the conclusion check stops it
running on green CI at all, and `vars.DISCORD_CI_NOTIFY` keeps it off entirely
until the secret actually exists. **Not `continue-on-error`** — see §2.3: GitHub
rejects that keyword on a reusable-workflow caller and invalidates the file.
Same reasoning as §2.3's announce gate, learned the same way: a notification
must never be able to change the colour of the thing it is reporting on, because
a run that is red for a reason nobody acts on teaches everyone to stop reading
the colour.
## 3. Chrome Web Store publishing automation
@@ -332,6 +361,11 @@ means "unknown", not "not done".
- [ ] ⚠️ Repo variable `CWS_AUTOPUBLISH=false` initially. Note that when the
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`. Leave both
unset until the matching webhook secrets exist — the reusables declare
those secrets required, so calling them without one fails the job, and a
reusable-workflow caller cannot use `continue-on-error` to absorb it
(§2.3). Unset means skipped, which is the safe default.
- [x] Dependabot: npm weekly, grouped dev minor+patch, `github-actions` too —
`.github/dependabot.yml`. Note it has no awareness of the `package.json`
`overrides` block, so those six pins must be reviewed by hand (`09 §3.1`).
+5 -1
View File
@@ -21,7 +21,7 @@ Build-phase breakdown lives in `CLAUDE.md` (single source for sequencing).
| 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 | in progress 2026-08-03 | doc reconciliation, user-intake machinery, the defects below, dependency bumps → v1.0.1 |
| 6 — Post-launch stabilization | ✔ 2026-08-03 | doc reconciliation, user-intake machinery, the defects below, dependency bumps → v1.0.1 |
**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
@@ -201,4 +201,8 @@ independently of the package (`13 §5`), though the copy should still go through
| 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 |
+135 -3259
View File
File diff suppressed because it is too large. Load diff
+5 -4
View File
@@ -1,7 +1,7 @@
{
"name": "bookmarkmagic",
"private": true,
"version": "1.0.0",
"version": "1.0.1",
"type": "module",
"description": "Import, export & edit bookmarks between browsers — offline, no account, no cloud.",
"license": "GPL-3.0-or-later",
@@ -39,15 +39,16 @@
"devDependencies": {
"@biomejs/biome": "2.5.5",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"@types/node": "^24.13.3",
"@vitest/coverage-v8": "^4.1.10",
"@wxt-dev/module-svelte": "^2.0.5",
"jsdom": "^29.1.1",
"jsdom": "^30.0.1",
"knip": "^6.29.0",
"svelte": "^5.56.8",
"svelte-check": "^4.7.3",
"svelte-check": "^4.7.4",
"typescript": "~6.0.3",
"vitest": "^4.1.10",
"wxt": "^0.20.27"
"wxt": "^0.21.3"
},
"overrides": {
"shell-quote": "^1.9.0",
+37
View File
@@ -20,6 +20,32 @@ const MANIFEST = join(process.cwd(), '.output', 'chrome-mv3', 'manifest.json');
/** Exactly this, in any order. Adding one is a minor-version event (docs/09 §4). */
const ALLOWED_PERMISSIONS = ['bookmarks', 'storage'];
/**
* 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, and the unit test over `wxt.config.ts` is structurally blind to it:
* a WXT upgrade cannot change that file.
*
* Adding a key here is a deliberate act. Check docs/08 §1 first.
*/
const EXPECTED_KEYS = [
'action',
'default_locale',
'description',
'homepage_url',
'icons',
'manifest_version',
'minimum_chrome_version',
'name',
'options_ui',
'permissions',
'version',
];
/** Keys that would widen the extension's reach. None may be present. */
const FORBIDDEN_KEYS = [
'host_permissions',
@@ -60,6 +86,17 @@ for (const key of FORBIDDEN_KEYS) {
if (key in manifest) problems.push(`declares "${key}": ${JSON.stringify(manifest[key])}`);
}
const actualKeys = Object.keys(manifest).sort();
const expectedKeys = [...EXPECTED_KEYS].sort();
const unexpected = actualKeys.filter((key) => !expectedKeys.includes(key));
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 (problems.length > 0) {
for (const problem of problems) {
console.error(`::error::check-manifest: ${problem}`);
+179 -28
View File
@@ -34,7 +34,27 @@ const BLANK_ICON =
// ---------------------------------------------------------------- format sniff
/** @param {string} text */
/** 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'];
/**
* Identify the format, or refuse.
*
* @param {string} text
* @returns {'html' | 'json' | 'csv' | null} `null` when nothing matched.
*
* Returning `null` rather than guessing is load-bearing. Every sanitizer below
* 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 to the user as
* "sanitized". The old `return 'csv'` fallback did exactly that for a truncated
* JSON export, an HTML excerpt with no doctype, or a CSV with foreign headers:
* byte-identical output, exit code 0, real hostnames intact.
*
* 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, not
* an edge case. `src/lib/core/detect-format.ts` refuses these same inputs with
* `UNKNOWN_FORMAT`; this must not be weaker than the parser it fronts.
*/
export function detectKind(text) {
const body = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
if (/NETSCAPE-Bookmark-file-1/i.test(body.slice(0, 512))) return 'html';
@@ -47,8 +67,17 @@ export function detectKind(text) {
// Not JSON after all; fall through.
}
}
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 'csv';
return null;
}
// ------------------------------------------------------------------- mappers
@@ -170,11 +199,24 @@ function makeTitleMapper() {
* @param {{start: number, end: number, value: string}[]} spans
*/
function replaceSpans(text, spans) {
let out = text;
for (const span of [...spans].sort((a, b) => b.start - a.start)) {
out = out.slice(0, span.start) + span.value + out.slice(span.end);
// 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,
// silently eating or stranding bytes. The widest span sanitizes the most.
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;
}
return out;
out.push(text.slice(cursor));
// Joined once rather than spliced per span: the old loop rebuilt the whole
// string for every replacement, which is O(spans x file) and takes minutes on
// a large export.
return out.join('');
}
/**
@@ -191,12 +233,17 @@ function replaceSpans(text, spans) {
* @param {number} [group]
*/
function spansFrom(text, re, map, group = 1) {
// The `d` flag gives exact per-group offsets. The previous version searched
// the match text for the captured substring, which lands on the wrong copy
// whenever the capture also appears earlier in the match — e.g. a bookmark
// whose title equals part of its own URL.
const indexed = new RegExp(re.source, re.flags.includes('d') ? re.flags : `${re.flags}d`);
const spans = [];
for (const m of text.matchAll(re)) {
for (const m of text.matchAll(indexed)) {
const captured = m[group] ?? '';
if (captured === '') continue;
const start = m.index + m[0].lastIndexOf(captured);
spans.push({ start, end: start + captured.length, value: map(captured) });
const at = m.indices?.[group];
if (captured === '' || at === undefined) continue;
spans.push({ start: at[0], end: at[1], value: map(captured) });
}
return spans;
}
@@ -234,6 +281,34 @@ function attrRewriter(map) {
};
}
/**
* `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 — real exports in the wild use
* single quotes, and that one is a straight leak.
*/
const ANY_ATTR = /\b([a-z_][a-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'<>=`]+))/dgi;
/**
* Spans for every attribute whose name matches, at any quoting.
*
* @param {string} text
* @param {RegExp} nameRe tested against the lower-cased attribute name
* @param {(value: string) => string} map
*/
function attrSpans(text, nameRe, map) {
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;
}
/** Attributes handled explicitly; the generic URL sweep must not touch them. */
const HANDLED_ATTRS = new Set(['href', 'icon']);
@@ -248,17 +323,18 @@ const HANDLED_ATTRS = new Set(['href', 'icon']);
function urlAttrSpans(text, mapUrl) {
const spans = [];
const rewrite = attrRewriter(mapUrl);
for (const m of text.matchAll(/\b([a-z_][a-z0-9_-]*)\s*=\s*"([^"]*)"/gi)) {
for (const m of text.matchAll(ANY_ATTR)) {
const name = (m[1] ?? '').toLowerCase();
const value = m[2] ?? '';
const value = m[2] ?? m[3] ?? m[4] ?? '';
if (HANDLED_ATTRS.has(name) || value === '') continue;
try {
if (new URL(value).host === '') continue;
} catch {
continue;
}
const start = m.index + m[0].lastIndexOf(value);
spans.push({ start, end: start + value.length, value: rewrite(value) });
const at = m.indices?.[2] ?? m.indices?.[3] ?? m.indices?.[4];
if (at === undefined) continue;
spans.push({ start: at[0], end: at[1], value: rewrite(value) });
}
return spans;
}
@@ -267,25 +343,37 @@ function sanitizeHtml(text, mapUrl, mapTitle) {
let descriptions = 0;
let keywords = 0;
const spans = [
// HREF="…" and ICON="…" — attribute name case is left exactly as found.
...spansFrom(text, /\bhref\s*=\s*"([^"]*)"/gi, attrRewriter(mapUrl)),
...spansFrom(text, /\bicon\s*=\s*"([^"]*)"/gi, () => BLANK_ICON),
// HREF and ICON, at any quoting — attribute name case is left as found.
...attrSpans(text, /^href$/, attrRewriter(mapUrl)),
...attrSpans(text, /^icon$/, () => BLANK_ICON),
...urlAttrSpans(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.
...spansFrom(text, /\bshortcuturl\s*=\s*"([^"]*)"/gi, () => `kw${++keywords}`),
...spansFrom(text, /\btags\s*=\s*"([^"]*)"/gi, (v) =>
...attrSpans(text, /^shortcuturl$/, () => `kw${++keywords}`),
...attrSpans(text, /^tags$/, (v) =>
v
.split(',')
.map((_, i) => `tag${i + 1}`)
.join(','),
),
// Bookmark titles: the text between <A …> and </A>.
...spansFrom(text, new RegExp(`<a\\b${TAG_INNARDS}>([^<]*)</a>`, 'gi'), mapTitle),
// `[\s\S]*?` and not `[^<]*`: a title containing a raw `<` made the whole
// match fail, so that bookmark's title was left in the output untouched.
...spansFrom(text, new RegExp(`<a\\b${TAG_INNARDS}>([\\s\\S]*?)</a>`, 'gi'), mapTitle),
// Folder titles.
...spansFrom(text, new RegExp(`<h3\\b${TAG_INNARDS}>([^<]*)</h3>`, 'gi'), mapTitle),
...spansFrom(text, new RegExp(`<h3\\b${TAG_INNARDS}>([\\s\\S]*?)</h3>`, 'gi'), mapTitle),
// Folder/bookmark descriptions.
...spansFrom(text, /<dd>([^\n<]*)/gi, () => `Description ${++descriptions}`),
// Runs to the next element, not to the end of the line: a description that
// wrapped onto a second line left everything after the first newline in
// place, and a `<DD>` is exactly where someone writes a private note.
...spansFrom(
text,
// The `\s*` belongs in the lookahead, not the capture: leaving it inside
// eats the newline and indentation before the next tag, which is exactly
// the byte-level shape this tool promises not to touch.
/<dd>([\s\S]*?)(?=\s*<\s*(?:dt|dd|dl|\/dl)\b|\s*$)/gi,
() => `Description ${++descriptions}`,
),
];
return replaceSpans(text, spans);
}
@@ -418,19 +506,59 @@ function mapFolderPath(path, mapTitle) {
// -------------------------------------------------------------- entry points
/**
* Everything in the OUTPUT that still looks like a real address.
*
* This is the backstop, and it is the only reason the rules above can be
* trusted. They are regexes 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>` that wraps onto a second line. Every one of
* those is a silent leak, and the only way to find them all by inspection is to
* be sure you have thought of every one, which nobody is.
*
* So instead of trusting the rules, the output is checked: any host that is not
* one of our own `*.example` aliases means something got through, and the file
* is refused rather than handed over. A rule this misses degrades into a
* refusal — annoying — instead of into a published browsing history.
*
* @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];
}
/**
* Sanitize a bookmark file's text.
*
* @param {string} text
* @returns {{ text: string, kind: 'html' | 'json' | 'csv' }}
* @returns {{ text: string | null, kind: 'html' | 'json' | 'csv' | 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();
if (kind === 'html') return { text: sanitizeHtml(text, mapUrl, mapTitle), kind };
if (kind === 'json') return { text: sanitizeJson(text, mapUrl, mapTitle), kind };
return { text: sanitizeCsv(text, mapUrl, mapTitle), kind };
const out =
kind === 'html'
? sanitizeHtml(text, mapUrl, mapTitle)
: kind === 'json'
? sanitizeJson(text, mapUrl, mapTitle)
: sanitizeCsv(text, mapUrl, mapTitle);
const leaked = findLeakedHosts(out);
return { text: leaked.length > 0 ? null : out, kind, leaked };
}
function main(argv) {
@@ -453,10 +581,33 @@ function main(argv) {
}
const text = raw.toString('utf8');
const { text: out, kind } = sanitize(text);
const { text: out, kind, leaked } = sanitize(text);
if (kind === null) {
console.error(
`${basename(input)} is not a bookmark file this tool recognises, so NOTHING WAS WRITTEN.\n` +
' Expected: a Netscape HTML export (the usual bookmarks.html), a BookmarkMagic JSON\n' +
' export, 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;
}
if (out === null) {
console.error(
`${basename(input)}: NOTHING WAS WRITTEN — the result still contained ${leaked.length} real ` +
`address(es), so this file is not safe to attach.\n Leaked: ${leaked.slice(0, 5).join(', ')}` +
`${leaked.length > 5 ? `, and ${leaked.length - 5} more` : ''}\n` +
' This is a bug in the sanitizer, not in your file. Please report it (without the file)\n' +
' at https://github.com/poli0981/bookmarkmagic/issues — the address above is enough.',
);
return 1;
}
const eol = text.includes('\r\n') ? 'CRLF' : 'LF';
const bom = text.charCodeAt(0) === 0xfeff ? ', BOM' : '';
console.error(`${basename(input)}: ${kind}, ${eol}${bom} — ${out.length} bytes out`);
console.error(`${basename(input)}: ${kind}, ${eol}${bom} — ${out.length} bytes out, no leaks`);
if (flags.includes('--check')) return 0;
if (flags.includes('--stdout')) {
+27 -2
View File
@@ -21,7 +21,14 @@
isGateRequired,
} from '@/lib/stores/legal.svelte';
import { getRoute, navigate, startRouting } from '@/lib/stores/route.svelte';
import { flushSettings, getSettings, updateSettings } from '@/lib/stores/settings.svelte';
import { subscribeStorage } from '@/lib/browser/storage';
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.
@@ -33,7 +40,14 @@
let mainEl: HTMLElement | undefined = $state();
onMount(() => {
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'),
});
// Leaving mid-write would kill the queue with the tab (docs/03 §5).
const onBeforeUnload = (event: BeforeUnloadEvent): void => {
@@ -48,11 +62,22 @@
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);
});
globalThis.addEventListener('beforeunload', onBeforeUnload);
globalThis.document?.addEventListener('visibilitychange', onVisibilityChange);
return () => {
stopRouting();
stopStorage();
globalThis.removeEventListener('beforeunload', onBeforeUnload);
globalThis.document?.removeEventListener('visibilitychange', onVisibilityChange);
};
+16 -4
View File
@@ -11,7 +11,7 @@
import { browser } from 'wxt/browser';
import type { BookmarkNode } from '../core/model';
import { millisToSeconds } from '../core/timestamps';
import { BmAborted, BmBrowserError } from './errors';
import { BmAborted, BmBrowserError, BmEnvError, BmPartialWrite } from './errors';
/** The live-tree node. Unlike `BookmarkNode` it carries browser identity. */
export interface LiveNode {
@@ -70,7 +70,10 @@ export async function getRoots(): Promise<BookmarkRoots> {
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');
// 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`);
}
return {
@@ -210,6 +213,11 @@ export function subscribe(handlers: BookmarkEvents): () => void {
/**
* 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 +230,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++;
}
}
+66
View File
@@ -0,0 +1,66 @@
/**
* 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 } from '../core/model';
import { BmBackupError, BmBrowserError, BmEnvError, BmPartialWrite } from './errors';
export interface DescribedError {
/** Dotted i18n path, e.g. `errors.TOO_DEEP`. */
messageKey: string;
/** 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 {
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,
};
}
+55
View File
@@ -46,3 +46,58 @@ export class BmBrowserError extends Error {
this.detail = detail;
}
}
export type BmEnvCode = 'NO_WRITABLE_ROOTS';
/**
* 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;
}
}
+53 -6
View File
@@ -81,15 +81,21 @@ 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 {
return null;
}
@@ -106,3 +112,44 @@ 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 {
// 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);
};
}
+18 -6
View File
@@ -12,7 +12,7 @@
*/
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. */
export interface WriteProgress {
@@ -55,6 +55,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,11 +84,20 @@ 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++;
+2 -1
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import { getAppVersion } from '../browser/app-info';
import { dateTime, t } from '../i18n/index.svelte';
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL } from '../links';
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL, STORE_URL } from '../links';
import { getAcceptance } from '../stores/legal.svelte';
const version = getAppVersion();
@@ -33,6 +33,7 @@
{t('about.changelog')} ↗
</a>
</li>
<li><a href={STORE_URL} target="_blank" rel="noopener noreferrer">{t('about.store')} ↗</a></li>
</ul>
<h2>{t('about.thirdParty')}</h2>
+107 -112
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, untrack } from 'svelte';
import {
create,
getRootChildren,
@@ -10,7 +10,7 @@
update,
} from '../browser/bookmarks';
import { copyToClipboard } from '../browser/clipboard';
import { BmBrowserError } from '../browser/errors';
import { type DescribedError, describeError } from '../browser/describe-error';
import { openBookmarkUrl } from '../browser/open-url';
import { findDuplicateGroups } from '../core/dedupe';
import { searchTree } from '../core/search';
@@ -30,31 +30,41 @@
moveNode,
removeNode,
} from '../edit/patch-tree';
import { deleteEach } from '../edit/bulk-delete';
import { canMoveInto, moveTargets } from '../edit/move-target';
import {
collapseSearchExpansion,
forgetSearchExpansion,
mergeSearchExpansion,
} from '../edit/search-expansion';
import { resolveKey, visibleRows } from '../edit/tree-keyboard';
import { num, t } from '../i18n/index.svelte';
import { pushToast } from '../stores/toast.svelte';
import Callout from './Callout.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import DuplicatePanel from './DuplicatePanel.svelte';
import EditToolbar from './EditToolbar.svelte';
import MoveToDialog from './MoveToDialog.svelte';
import TreeRow from './TreeRow.svelte';
import TreeList from './TreeList.svelte';
let roots = $state<EditNode[]>([]);
let expanded = $state<Set<string>>(new Set());
let expanded = $state<ReadonlySet<string>>(new Set());
let focusedId = $state<string | undefined>();
let renamingId = $state<string | undefined>();
let query = $state('');
let debounced = $state('');
let showDuplicates = $state(false);
let loadError = $state<string | undefined>();
let loadError = $state<DescribedError | undefined>();
let pendingDelete = $state<EditNode | undefined>();
let pendingKeepFirst = $state(false);
let draggingId = $state<string | undefined>();
let movingNode = $state<EditNode | undefined>();
/** Per-operation failure, shown ABOVE the tree rather than replacing it. */
let actionError = $state<{ message: string; detail: string | undefined } | undefined>();
let actionError = $state<
(DescribedError & { partial?: { done: number; total: number } }) | undefined
>();
/** Folders the search opened, so clearing the search can close them again. */
let searchOpened = $state<ReadonlySet<string>>(new Set());
let searchInput = $state<HTMLInputElement | undefined>();
let treeEl = $state<HTMLElement | undefined>();
@@ -96,7 +106,9 @@
roots = (await getRootChildren()).map(toEditNode);
expanded = new Set(roots.map((root) => root.id));
} catch (err) {
loadError = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
// Was `err.detail` alone: a raw English Chrome string as the entire
// screen, in every language (docs/02 §7).
loadError = describeError(err);
}
}
@@ -114,16 +126,53 @@
// Search-opened ancestors are merged INTO `expanded` rather than unioned at
// render time. Reading from a union that toggle() cannot write to made the
// disclosure button and ArrowLeft dead keys on every search-expanded folder.
//
// The merge is remembered so it can be undone: a one-character query expands
// most of a large tree, and clearing the box used to render every one of
// those rows at once, in a single synchronous pass, with no virtualization.
$effect(() => {
if (search.expand.size === 0) return;
const missing = [...search.expand].filter((id) => !expanded.has(id));
if (missing.length > 0) expanded = new Set([...expanded, ...missing]);
// Depend on the SEARCH only. `expanded` and `searchOpened` are read and
// written here, so tracking them makes the effect its own dependency: every
// write re-invalidates it, and it re-runs against a `search.expand` that has
// not changed. Collapsing a search-opened folder then immediately re-opened
// it — the disclosure arrow looked broken, which is the same class of defect
// the merge-into-`expanded` design was introduced to fix.
const wanted = search.expand;
const active = filtering;
untrack(() => {
if (!active) {
if (searchOpened.size === 0) return;
expanded = collapseSearchExpansion(expanded, searchOpened);
searchOpened = new Set();
return;
}
const merged = mergeSearchExpansion(expanded, wanted, searchOpened);
if (merged.expanded === expanded) return;
expanded = merged.expanded;
searchOpened = merged.opened;
});
});
const rows = $derived(visibleRows(roots, expanded, filtering ? search.visible : undefined));
const partialNote = $derived(
actionError?.partial === undefined
? undefined
: t('edit.keepFirstPartial', {
done: num(actionError.partial.done),
total: num(actionError.partial.total),
}),
);
// `isEditable` matters as much as the url check: without it, duplicates
// inside a policy-managed subtree were offered for bulk deletion, and the
// browser rejects every one of them. The single-delete path has always
// filtered; docs/15 makes it normative that unmodifiable nodes offer no
// destructive affordance at all.
const duplicateGroups = $derived(
findDuplicateGroups(flattenTree(roots).filter((node) => node.url !== undefined)),
findDuplicateGroups(
flattenTree(roots).filter((node) => node.url !== undefined && isEditable(node)),
),
);
/**
@@ -136,10 +185,7 @@
try {
await run();
} catch (err) {
actionError =
err instanceof BmBrowserError
? { message: t('errors.BROWSER'), detail: err.detail }
: { message: t('errors.UNKNOWN'), detail: err instanceof Error ? err.message : undefined };
actionError = describeError(err);
await load();
}
}
@@ -149,6 +195,9 @@
if (next.has(id)) next.delete(id);
else next.add(id);
expanded = next;
// Touching a folder makes it the user's, so clearing the search must not
// close it again.
searchOpened = forgetSearchExpansion(searchOpened, id);
}
function onKeydown(event: KeyboardEvent): void {
@@ -251,12 +300,21 @@
// Snapshot the ids first: duplicateGroups is $derived from `roots`, so
// reading it inside the loop would recompute mid-iteration.
const doomed = extraCopyIds(duplicateGroups);
await guardEdit(async () => {
for (const id of doomed) {
roots = removeNode(roots, id);
await remove(id);
}
actionError = undefined;
const outcome = await deleteEach(doomed, remove, (id) => {
roots = removeNode(roots, id);
});
if (outcome.error === undefined) return;
// The dialog promised an exact number. Saying only "the browser refused"
// after deleting some of them leaves the user unable to tell how many
// copies are left, on an action that cannot be undone.
actionError = {
...describeError(outcome.error),
partial: { done: outcome.deleted, total: outcome.total },
};
await load();
}
/** Shared by the drag path and the keyboard "Move to…" path. */
@@ -300,7 +358,7 @@
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
{:else}
<EditToolbar
bind:input={searchInput}
@@ -313,65 +371,37 @@
/>
{#if actionError !== undefined}
<div class="action-error">
<Callout tone="danger">{actionError.message}</Callout>
{#if actionError.detail !== undefined}
<pre>{actionError.detail}</pre>
{/if}
</div>
<ErrorCallout
messageKey={actionError.messageKey}
detail={actionError.detail}
note={partialNote}
/>
{/if}
<div class="split" class:with-panel={showDuplicates}>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<ul
bind:this={treeEl}
class="tree"
role="tree"
aria-label={t('common.edit')}
tabindex="0"
aria-activedescendant={focusedId === undefined ? undefined : `node-${focusedId}`}
<TreeList
bind:element={treeEl}
{rows}
{focusedId}
{renamingId}
{filtering}
{draggingId}
matched={search.matched}
editable={isEditable}
canDropInto={(id) => draggingId !== undefined && canMoveInto(roots, draggingId, id)}
onkeydown={onKeydown}
>
{#each rows as row (row.node.id)}
<li
id="node-{row.node.id}"
data-node-id={row.node.id}
role="treeitem"
aria-level={row.depth}
aria-expanded={row.expandable ? row.expanded : undefined}
aria-selected={focusedId === row.node.id}
>
<TreeRow
node={row.node}
depth={row.depth}
expandable={row.expandable}
expanded={row.expanded}
focused={focusedId === row.node.id}
matched={search.matched.has(row.node.id)}
renaming={renamingId === row.node.id}
ontoggle={() => toggle(row.node.id)}
onfocus={() => (focusedId = row.node.id)}
onstartRename={() => (renamingId = row.node.id)}
onrename={(title) => void commitRename(row.node.id, title)}
oncancelRename={() => (renamingId = undefined)}
ondelete={() => (pendingDelete = row.node)}
onopen={() => void openUrl(row.node.url ?? '')}
oncopyUrl={() => void copyUrl(row.node.url ?? '')}
onmoveTo={() => (movingNode = row.node)}
ondragstart={() => (draggingId = row.node.id)}
ondropinto={() => onDrop(row.node.id)}
dropTarget={draggingId !== undefined &&
canMoveInto(roots, draggingId, row.node.id)}
draggable={isEditable(row.node)}
editable={isEditable(row.node)}
/>
</li>
{/each}
{#if rows.length === 0}
<li class="empty">{filtering ? t('edit.noMatches') : t('edit.empty')}</li>
{/if}
</ul>
ontoggle={toggle}
onfocusRow={(id) => (focusedId = id)}
onstartRename={(id) => (renamingId = id)}
onrename={(id, title) => void commitRename(id, title)}
oncancelRename={() => (renamingId = undefined)}
ondelete={(node) => (pendingDelete = node)}
onopen={(node) => void openUrl(node.url ?? "")}
oncopyUrl={(node) => void copyUrl(node.url ?? "")}
onmoveTo={(node) => (movingNode = node)}
ondragstart={(id) => (draggingId = id)}
ondropinto={(id) => onDrop(id)}
/>
{#if showDuplicates}
<DuplicatePanel
@@ -441,41 +471,6 @@
}
}
.tree {
list-style: none;
margin: 0;
padding: 0;
font-size: var(--fs-1);
max-height: 560px;
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
}
.tree:focus-visible {
outline: 2px solid var(--accent);
}
.action-error {
margin-bottom: var(--sp-3);
}
.action-error pre {
margin: var(--sp-2) 0 0;
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
.empty {
color: var(--fg-muted);
padding: var(--sp-4);
text-align: center;
}
</style>
+66
View File
@@ -0,0 +1,66 @@
<script lang="ts">
/**
* A failure, shown the way docs/02 §7 requires: a localized sentence, and the
* raw browser string in a separate, copyable block.
*
* One component owns this because there is one specific way to get it wrong
* and it has been got wrong three times. Writing `detail ?? t(key)` looks
* like a sensible fallback, but the raw string is almost always present — so
* the translation becomes dead code and a Vietnamese or Japanese user sees an
* untranslated Chrome message as the entire explanation. LegalGate carries a
* comment recording that exact defect; #edit and #export still had it.
*
* The detail is `user-select: all` so a reporter can grab it in one click for
* an issue — it is the only part worth pasting.
*/
import { t } from '../i18n/index.svelte';
import Callout from './Callout.svelte';
interface Props {
/** Dotted i18n path. Never a resolved string. */
messageKey: string;
/** Raw, untranslated technical text. Omitted when there is none. */
detail?: string | undefined;
/**
* An already-localized sentence adding what the failure left behind — how
* many of a promised batch actually completed, for instance. Resolved by
* the caller because it interpolates counts they hold.
*/
note?: string | undefined;
}
let { messageKey, detail, note }: Props = $props();
</script>
<div class="error">
<Callout tone="danger">{t(messageKey)}</Callout>
{#if note !== undefined}
<p class="note">{note}</p>
{/if}
{#if detail !== undefined}
<pre>{detail}</pre>
{/if}
</div>
<style>
.error {
margin-bottom: var(--sp-3);
}
.note {
margin: var(--sp-2) 0 0;
color: var(--fg-muted);
font-size: var(--fs-1);
}
pre {
margin: var(--sp-2) 0 0;
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
</style>
+11 -6
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import { getRootChildren, type LiveNode } from '../browser/bookmarks';
import { BmBrowserError } from '../browser/errors';
import { type DescribedError, describeError } from '../browser/describe-error';
import type { ExportFormat } from '../browser/storage';
import type { CsvDelimiter } from '../core/serialize/csv';
import type { MarkdownStyle } from '../core/serialize/markdown';
@@ -16,13 +16,14 @@
import { pushToast } from '../stores/toast.svelte';
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import FolderPickTree from './FolderPickTree.svelte';
import FormatSelect from './FormatSelect.svelte';
let roots = $state<LiveNode[]>([]);
let selection = $state<ReadonlySet<string> | undefined>(undefined);
let format = $state<ExportFormat>('netscape-html');
let loadError = $state<string | undefined>();
let loadError = $state<DescribedError | undefined>();
let csvDelimiter = $state<CsvDelimiter>(',');
let markdownStyle = $state<MarkdownStyle>('nested');
@@ -39,7 +40,9 @@
csvDelimiter = settings.csvDelimiter;
markdownStyle = settings.markdownStyle;
} catch (err) {
loadError = err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN');
// Was `err.detail` alone — a raw English Chrome string as the entire
// screen, in all three languages (docs/02 §7).
loadError = describeError(err);
}
}
@@ -63,15 +66,17 @@
pushToast(t('export.saved', { name: result.filename }), 'success');
} catch (err) {
// Tone matters: this used to share a variable with the success message
// and rendered failures in success-green.
pushToast(err instanceof BmBrowserError ? err.detail : t('errors.UNKNOWN'), 'danger');
// and rendered failures in success-green. The message is the localized
// sentence — a toast has no room for a detail block, which is the same
// reasoning the header's save-failure toast records.
pushToast(t(describeError(err).messageKey), 'danger');
}
})();
}
</script>
{#if loadError !== undefined}
<Callout tone="danger">{loadError}</Callout>
<ErrorCallout messageKey={loadError.messageKey} detail={loadError.detail} />
{:else}
<div class="split">
<section aria-label={t('export.scope')}>
+52 -51
View File
@@ -1,11 +1,13 @@
<script lang="ts">
import { describeError } from '../browser/describe-error';
import { timestampSuffix } from '../browser/download';
import { BmAborted, BmBackupError, BmBrowserError } from '../browser/errors';
import { BmParseError } from '../core/model';
import { BmAborted } from '../browser/errors';
import { num, t } from '../i18n/index.svelte';
import { prepareImport, runImport } from '../import/run-import';
import { getSettings } from '../stores/settings.svelte';
import {
answerAttestation,
awaitAttestation,
beginWrite,
cancelWrite,
getImportOptions,
@@ -20,6 +22,7 @@
import Button from './Button.svelte';
import Callout from './Callout.svelte';
import DropZone from './DropZone.svelte';
import ErrorCallout from './ErrorCallout.svelte';
import ImportOptions from './ImportOptions.svelte';
import ProgressBar from './ProgressBar.svelte';
import StatsCard from './StatsCard.svelte';
@@ -33,36 +36,6 @@
const session = $derived(getImportState());
const options = $derived(getImportOptions());
/** Resolver for the fallback-backup attestation dialog. */
let attestResolve: ((confirmed: boolean) => void) | undefined;
function answerAttest(confirmed: boolean): void {
attestResolve?.(confirmed);
attestResolve = undefined;
}
/**
* Map an error onto an i18n KEY plus a raw detail — never a resolved string.
* The session store outlives this component, and `t()` only re-runs where it
* is called, so a translated sentence stored here would never follow a
* language switch.
*/
function describeError(err: unknown): { messageKey: string; detail: string | undefined } {
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 BmBrowserError) {
return { messageKey: 'errors.BROWSER', detail: err.detail };
}
return {
messageKey: 'errors.UNKNOWN',
detail: err instanceof Error ? err.message : undefined,
};
}
async function onFile(file: File): Promise<void> {
setImportState({ kind: 'validating', filename: file.name });
try {
@@ -87,6 +60,8 @@
const signal = beginWrite();
const now = new Date();
const backupFilename = `bookmarkmagic-backup-${timestampSuffix(now)}.json`;
/** Set once the backup is on disk. Nothing may point at the file before. */
let backupProven = false;
// runImport opens the save picker as its first statement, so the transient
// activation from this click still holds when the dialog appears.
@@ -111,23 +86,43 @@
// Backup proven; deletion starts now. No Cancel is offered here — the
// button used to stay live through the whole delete, letting a user
// cancel and be told "0 items created" after their tree was wiped.
//
// This callback is also the ONLY signal that the backup exists: it runs
// immediately after `proveBackup` returned, and nothing else does.
onClearing: () => {
backupProven = true;
setImportState({ kind: 'clearing', filename });
},
confirmUnprovenBackup: () => {
setImportState({ kind: 'attesting', filename, backupFilename });
return new Promise<boolean>((resolve) => {
attestResolve = resolve;
});
return awaitAttestation();
},
});
setImportState({ kind: 'done', filename, created: outcome.created, plan: outcome.plan });
} catch (err) {
if (err instanceof BmAborted) {
setImportState({ kind: 'cancelled', filename, created: err.done });
setImportState({
kind: 'cancelled',
filename,
created: err.done,
// A cancel AFTER the clear is not "nothing happened": the tree is
// gone and only `created` of it has been rebuilt. Saying "N items
// created" alone reads as a harmless no-op on an empty browser.
...(backupProven ? { backupFilename } : {}),
});
return;
}
setImportState({ kind: 'error', filename, ...describeError(err) });
setImportState({
kind: 'error',
filename,
...describeError(err),
// `backupProven`, not "mode was replace and this is not a BmBackupError".
// `runImport` resolves the roots BEFORE proving the backup, so a failure
// there — a policy-managed profile raising NO_WRITABLE_ROOTS, say —
// reaches this catch with no file on disk. Telling a frightened user to
// restore a backup that was never written is worse than saying nothing.
...(backupProven ? { backupFilename } : {}),
});
}
}
@@ -164,6 +159,7 @@
duplicates={session.duplicates}
onchange={(patch) => setImportOptions(patch)}
/>
<p class="muted">{t('import.dateNotice')}</p>
<Button
variant={options.mode === 'replace' ? 'danger' : 'primary'}
onclick={() => void start(session.filename)}
@@ -179,8 +175,10 @@
thing standing between the user and an unbacked-up deletion. -->
<Callout tone="danger">{t('import.attest', { name: session.backupFilename })}</Callout>
<div class="actions">
<Button variant="danger" onclick={() => answerAttest(true)}>{t('import.attestConfirm')}</Button>
<Button onclick={() => answerAttest(false)}>{t('common.cancel')}</Button>
<Button variant="danger" onclick={() => answerAttestation(true)}>
{t('import.attestConfirm')}
</Button>
<Button onclick={() => answerAttestation(false)}>{t('common.cancel')}</Button>
</div>
{:else if session.kind === 'clearing'}
<Callout tone="danger">{t('import.clearing')}</Callout>
@@ -206,6 +204,7 @@
inFile: num(session.plan.stats.skippedInFile),
})}
</p>
<p class="muted">{t('import.dateNotice')}</p>
<div class="actions">
<Button variant="primary" onclick={() => navigate('edit')}>{t('import.openEdit')}</Button>
<Button
@@ -214,13 +213,24 @@
</div>
{:else if session.kind === 'cancelled'}
<Callout tone="warn">{t('import.cancelledSummary', { created: num(session.created) })}</Callout>
{#if session.backupFilename !== undefined}
<Callout tone="danger">{t('import.cancelledAfterClear')}</Callout>
<p class="muted">{t('import.backupHint', { name: session.backupFilename })}</p>
{/if}
<p class="muted">{t('import.dateNotice')}</p>
<Button
onclick={resetImport}>{t('import.another')}</Button
>
{:else if session.kind === 'error'}
<Callout tone="danger">{t(session.messageKey)}</Callout>
{#if session.detail !== undefined}
<pre class="detail">{session.detail}</pre>
<ErrorCallout messageKey={session.messageKey} detail={session.detail} />
{#if session.created !== undefined && session.created > 0}
<p class="muted">{t('import.partialCreated', { created: num(session.created) })}</p>
{/if}
{#if session.removed !== undefined && session.removed > 0}
<Callout tone="danger">{t('import.partialCleared', { removed: num(session.removed) })}</Callout>
{/if}
{#if session.backupFilename !== undefined}
<p class="muted">{t('import.backupHint', { name: session.backupFilename })}</p>
{/if}
<Button
onclick={resetImport}>{t('import.another')}</Button
@@ -272,13 +282,4 @@
margin-top: var(--sp-3);
}
.detail {
font-size: var(--fs-0);
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: var(--sp-2);
overflow: auto;
user-select: all;
}
</style>
+142
View File
@@ -0,0 +1,142 @@
<script lang="ts">
/**
* The `role="tree"` container and its rows — docs/06 §3.3.
*
* Split out of `EditTab` so the ARIA structure lives in one place rather than
* inside a component that also owns loading, searching, mutation and five
* dialogs. The WAI-ARIA tree pattern is exacting — roving focus expressed
* through `aria-activedescendant`, `aria-level` starting at 1, `aria-expanded`
* present only on expandable rows — and it is easier to keep right when it is
* not surrounded by unrelated state.
*
* The keydown handler lives on this `<ul>`, not on a wrapper: a keydown
* handler on a non-focusable container never fires, and svelte-check flags it.
*/
import type { EditNode } from '../edit/patch-tree';
import type { VisibleRow } from '../edit/tree-keyboard';
import { t } from '../i18n/index.svelte';
import TreeRow from './TreeRow.svelte';
interface Props {
rows: readonly VisibleRow[];
focusedId: string | undefined;
renamingId: string | undefined;
/** Ids matching the current search, highlighted rather than filtered. */
matched: ReadonlySet<string>;
/** True while a search is narrowing the tree — picks the empty message. */
filtering: boolean;
draggingId: string | undefined;
editable: (node: EditNode) => boolean;
canDropInto: (id: string) => boolean;
element?: HTMLElement | undefined;
onkeydown: (event: KeyboardEvent) => void;
ontoggle: (id: string) => void;
onfocusRow: (id: string) => void;
onstartRename: (id: string) => void;
onrename: (id: string, title: string) => void;
oncancelRename: () => void;
ondelete: (node: EditNode) => void;
onopen: (node: EditNode) => void;
oncopyUrl: (node: EditNode) => void;
onmoveTo: (node: EditNode) => void;
ondragstart: (id: string) => void;
ondropinto: (id: string) => void;
}
let {
rows,
focusedId,
renamingId,
matched,
filtering,
draggingId,
editable,
canDropInto,
element = $bindable(),
onkeydown,
ontoggle,
onfocusRow,
onstartRename,
onrename,
oncancelRename,
ondelete,
onopen,
oncopyUrl,
onmoveTo,
ondragstart,
ondropinto,
}: Props = $props();
</script>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
<ul
bind:this={element}
class="tree"
role="tree"
aria-label={t('common.edit')}
tabindex="0"
aria-activedescendant={focusedId === undefined ? undefined : `node-${focusedId}`}
{onkeydown}
>
{#each rows as row (row.node.id)}
<li
id="node-{row.node.id}"
data-node-id={row.node.id}
role="treeitem"
aria-level={row.depth}
aria-expanded={row.expandable ? row.expanded : undefined}
aria-selected={focusedId === row.node.id}
>
<TreeRow
node={row.node}
depth={row.depth}
expandable={row.expandable}
expanded={row.expanded}
focused={focusedId === row.node.id}
matched={matched.has(row.node.id)}
renaming={renamingId === row.node.id}
ontoggle={() => ontoggle(row.node.id)}
onfocus={() => onfocusRow(row.node.id)}
onstartRename={() => onstartRename(row.node.id)}
onrename={(title) => onrename(row.node.id, title)}
{oncancelRename}
ondelete={() => ondelete(row.node)}
onopen={() => onopen(row.node)}
oncopyUrl={() => oncopyUrl(row.node)}
onmoveTo={() => onmoveTo(row.node)}
ondragstart={() => ondragstart(row.node.id)}
ondropinto={() => ondropinto(row.node.id)}
dropTarget={draggingId !== undefined && canDropInto(row.node.id)}
draggable={editable(row.node)}
editable={editable(row.node)}
/>
</li>
{/each}
{#if rows.length === 0}
<li class="empty">{filtering ? t('edit.noMatches') : t('edit.empty')}</li>
{/if}
</ul>
<style>
.tree {
list-style: none;
margin: 0;
padding: var(--sp-2);
font-size: var(--fs-1);
max-height: 560px;
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
}
.tree:focus-visible {
outline: 2px solid var(--accent);
}
.empty {
color: var(--fg-muted);
padding: var(--sp-4);
text-align: center;
}
</style>
+47
View File
@@ -0,0 +1,47 @@
/**
* Delete many nodes, one awaited call at a time, and report what happened —
* docs/03 §3.
*
* Purpose: give the "keep the first of each" bulk delete an outcome the caller
* cannot forget to handle.
* Inputs: the ids to remove, an injected remove, and a per-success callback for
* the optimistic local update.
* Guarantees: **never throws.** It stops at the first rejection and returns how
* far it got.
*
* Not throwing is the point. This is the project's recurring defect shape —
* mutate local state optimistically, await a `chrome.*` call that can reject,
* never handle the rejection — and it lived here in its purest form: the loop
* removed each node locally, awaited the browser, and on the first rejection
* abandoned the rest, leaving the user with a partial delete measured against a
* confirmation dialog that had promised an exact number.
*/
export interface BulkDeleteOutcome {
/** How many the browser actually accepted. */
deleted: number;
/** How many were asked for. */
total: number;
/** The rejection that stopped it, if one did. */
error?: unknown;
}
export async function deleteEach(
ids: readonly string[],
remove: (id: string) => Promise<void>,
onDeleted: (id: string) => void,
): Promise<BulkDeleteOutcome> {
let deleted = 0;
for (const id of ids) {
try {
await remove(id);
} catch (error) {
return { deleted, total: ids.length, error };
}
// Only after the browser has confirmed it. Updating first would leave the
// tree disagreeing with the browser for every id after a failure.
onDeleted(id);
deleted++;
}
return { deleted, total: ids.length };
}
+75
View File
@@ -0,0 +1,75 @@
/**
* Track which folders a *search* opened, separately from the ones the user
* opened — docs/03 §3.
*
* Purpose: let the tree collapse back when the search box is cleared, without
* closing anything the user opened by hand.
* Inputs: the current expanded set, the ids a search wants open, and the ids
* this module opened last time.
* Guarantees: pure, and never returns a new Set when nothing changed, so the
* `$effect` driving it does not thrash.
*
* Why the search merges into `expanded` at all: a render-time union of the two
* sets made the disclosure button and ArrowLeft dead on every search-expanded
* folder, because `toggle()` had nothing it could write to. The merge is
* deliberate; what was missing was the un-merge, so one character typed into
* the search box permanently expanded most of a large tree — and clearing the
* box then rendered every one of those rows at once, with no virtualization.
*/
export interface MergeResult {
expanded: ReadonlySet<string>;
/** Ids this module opened, to be closed again when the search clears. */
opened: ReadonlySet<string>;
}
/**
* Open everything the search needs, remembering what was not already open.
*
* @param expanded ids currently expanded
* @param wanted ids the search needs expanded
* @param opened ids a previous merge opened and has not yet collapsed
*/
export function mergeSearchExpansion(
expanded: ReadonlySet<string>,
wanted: ReadonlySet<string>,
opened: ReadonlySet<string>,
): MergeResult {
const missing = [...wanted].filter((id) => !expanded.has(id));
// Identity is preserved when there is nothing to do — the caller stores these
// in `$state`, and reassigning an equal Set would re-run every dependent.
if (missing.length === 0) return { expanded, opened };
return {
expanded: new Set([...expanded, ...missing]),
opened: new Set([...opened, ...missing]),
};
}
/**
* Close only what the search opened.
*
* A folder the user expanded themselves stays open even if the search also
* needed it — `forget` removes it from the search-owned set the moment they
* touch it, so ownership is decided at the point of interaction rather than
* guessed at collapse time.
*/
export function collapseSearchExpansion(
expanded: ReadonlySet<string>,
opened: ReadonlySet<string>,
): ReadonlySet<string> {
if (opened.size === 0) return expanded;
const next = new Set(expanded);
for (const id of opened) next.delete(id);
return next;
}
/** The user toggled this folder, so the search no longer owns it. */
export function forgetSearchExpansion(
opened: ReadonlySet<string>,
id: string,
): ReadonlySet<string> {
if (!opened.has(id)) return opened;
const next = new Set(opened);
next.delete(id);
return next;
}
+22
View File
@@ -45,6 +45,19 @@ const dict = {
doneSummary: 'Done — {created} items created.',
skipped: 'Skipped {existing} already in this browser and {inFile} repeated in the file.',
cancelledSummary: 'Cancelled — {created} items were already created and were left in place.',
// docs/05 §6 and docs/00 §8 both require saying this, and nothing did.
// chrome.bookmarks.create takes no dateAdded, so every imported bookmark is
// stamped with the import time — indistinguishable from corruption to
// someone migrating a decade-old archive.
cancelledAfterClear:
'You cancelled after your existing bookmarks had already been deleted, so what is left is only the part that was rebuilt.',
dateNotice:
'Imported bookmarks are dated today. Chrome does not let an extension set a bookmark’s original date — your exported files keep the real ones.',
partialCreated:
'{created} items had already been created before this failed, and were left in place.',
partialCleared:
'{removed} top-level items had already been deleted before this failed. Restore them from your backup.',
backupHint: 'Your safety backup was saved as {name}. Restore it by importing that JSON file.',
openEdit: 'Open Edit tab',
another: 'Import another file',
dedupe: 'Skip duplicates already in this browser ({n} found)',
@@ -131,6 +144,10 @@ const dict = {
keepFirstTitle: 'Delete duplicate copies?',
keepFirstBody:
'Keep the first copy of each link and delete the other {n}? This cannot be undone.',
// The dialog promises an exact number, so a partial delete has to reconcile
// against it — the action cannot be undone.
keepFirstPartial:
'Deleted {done} of {total} copies before this failed. Nothing else was removed.',
},
settings: {
autosave: 'Changes are saved as you make them.',
@@ -175,6 +192,7 @@ const dict = {
repo: 'GitHub repository',
issues: 'Report an issue',
changelog: 'Releases and changelog',
store: 'Chrome Web Store listing',
thirdParty: 'Third-party dependencies: None',
thirdPartyNote: 'BookmarkMagic ships no runtime libraries at all.',
donate: 'Support development',
@@ -256,6 +274,10 @@ const dict = {
BACKUP_CANCELLED: 'You cancelled the safety backup, so nothing was deleted.',
BACKUP_WRITE_FAILED: 'The safety backup could not be saved, so nothing was deleted.',
BROWSER: 'The browser refused a bookmark operation.',
NO_WRITABLE_ROOTS:
'This browser profile has no bookmark folder BookmarkMagic is allowed to write to. Bookmarks managed by an organisation cannot be changed.',
PARTIAL_WRITE: 'The browser stopped accepting bookmarks part-way through the import.',
PARTIAL_CLEAR: 'The browser stopped part-way through replacing your bookmarks.',
UNKNOWN: 'Something went wrong.',
},
};
+16
View File
@@ -38,6 +38,15 @@ export default {
skipped:
'このブラウザに既にある {existing} 件と、ファイル内で重複する {inFile} 件をスキップしました。',
cancelledSummary: 'キャンセルしました — 既に作成された {created} 件はそのまま残されています。',
cancelledAfterClear:
'既存のブックマークが削除された後にキャンセルされたため、残っているのは再作成された分だけです。',
dateNotice:
'インポートしたブックマークの日付は本日になります。拡張機能がブックマークの元の作成日を設定することを Chrome が許可していないためです。エクスポートしたファイルには本来の日付が残ります。',
partialCreated: 'エラーが発生する前に作成された {created} 件はそのまま残されています。',
partialCleared:
'エラーが発生する前に、最上位の {removed} 件が既に削除されています。バックアップから復元してください。',
backupHint:
'安全のためのバックアップは {name} として保存されています。その JSON ファイルをインポートすると復元できます。',
openEdit: '編集タブを開く',
another: '別のファイルをインポート',
dedupe: 'このブラウザに既にあるものをスキップする({n} 件見つかりました)',
@@ -123,6 +132,8 @@ export default {
keeps: '保持',
keepFirstTitle: '重複したコピーを削除しますか?',
keepFirstBody: '各リンクの最初のコピーを残し、他の {n} 件を削除しますか?元に戻せません。',
keepFirstPartial:
'エラーが発生する前に {total} 件中 {done} 件を削除しました。それ以外は削除されていません。',
},
settings: {
autosave: '変更は自動的に保存されます。',
@@ -166,6 +177,7 @@ export default {
repo: 'GitHub リポジトリ',
issues: '問題を報告',
changelog: 'リリースと変更履歴',
store: 'Chrome ウェブストアのページ',
thirdParty: 'サードパーティ依存: なし',
thirdPartyNote: 'BookmarkMagic は実行時ライブラリを一切同梱していません。',
donate: '開発を支援する',
@@ -241,6 +253,10 @@ export default {
BACKUP_CANCELLED: 'バックアップがキャンセルされたため、何も削除していません。',
BACKUP_WRITE_FAILED: 'バックアップを保存できなかったため、何も削除していません。',
BROWSER: 'ブラウザがブックマークの操作を拒否しました。',
NO_WRITABLE_ROOTS:
'このブラウザプロファイルには、BookmarkMagic が書き込みを許可されているブックマークフォルダがありません。組織によって管理されているブックマークは変更できません。',
PARTIAL_WRITE: 'インポートの途中で、ブラウザがブックマークの受け付けを停止しました。',
PARTIAL_CLEAR: 'ブックマークを置き換えている途中で、ブラウザが停止しました。',
UNKNOWN: '問題が発生しました。',
},
} satisfies Dict;
+16
View File
@@ -33,6 +33,15 @@ export default {
doneSummary: 'Hoàn tất — đã tạo {created} mục.',
skipped: 'Đã bỏ qua {existing} mục đã có trong trình duyệt và {inFile} mục lặp trong tệp.',
cancelledSummary: 'Đã hủy — {created} mục đã được tạo trước đó và vẫn được giữ lại.',
cancelledAfterClear:
'Bạn đã hủy sau khi bookmark cũ đã bị xóa, nên những gì còn lại chỉ là phần đã được tạo lại.',
dateNotice:
'Bookmark được nhập vào sẽ mang ngày hôm nay. Chrome không cho phép tiện ích đặt lại ngày tạo gốc của bookmark — các tệp bạn xuất ra vẫn giữ ngày thật.',
partialCreated: '{created} mục đã được tạo trước khi lỗi xảy ra và vẫn được giữ lại.',
partialCleared:
'{removed} mục ở cấp cao nhất đã bị xóa trước khi lỗi xảy ra. Hãy khôi phục chúng từ tệp sao lưu của bạn.',
backupHint:
'Tệp sao lưu an toàn đã được lưu với tên {name}. Nhập lại tệp JSON đó để khôi phục.',
openEdit: 'Mở thẻ Chỉnh sửa',
another: 'Nhập tệp khác',
dedupe: 'Bỏ qua mục đã có trong trình duyệt này (tìm thấy {n})',
@@ -122,6 +131,8 @@ export default {
keeps: 'giữ lại',
keepFirstTitle: 'Xóa các bản trùng?',
keepFirstBody: 'Giữ bản đầu tiên của mỗi liên kết và xóa {n} bản còn lại? Không thể hoàn tác.',
keepFirstPartial:
'Đã xóa {done} trong số {total} bản trước khi lỗi xảy ra. Không có gì khác bị xóa.',
},
settings: {
autosave: 'Thay đổi được lưu ngay khi bạn chỉnh.',
@@ -165,6 +176,7 @@ export default {
repo: 'Kho mã trên GitHub',
issues: 'Báo lỗi',
changelog: 'Bản phát hành và nhật ký thay đổi',
store: 'Trang trên Chrome Web Store',
thirdParty: 'Thư viện bên thứ ba: Không có',
thirdPartyNote: 'BookmarkMagic không đi kèm bất kỳ thư viện chạy nào.',
donate: 'Ủng hộ dự án',
@@ -239,6 +251,10 @@ export default {
BACKUP_CANCELLED: 'Bạn đã hủy bản sao lưu, nên không có gì bị xóa.',
BACKUP_WRITE_FAILED: 'Không thể lưu bản sao lưu, nên không có gì bị xóa.',
BROWSER: 'Trình duyệt đã từ chối một thao tác bookmark.',
NO_WRITABLE_ROOTS:
'Hồ sơ trình duyệt này không có thư mục bookmark nào mà BookmarkMagic được phép ghi vào. Bookmark do tổ chức quản lý thì không thể thay đổi.',
PARTIAL_WRITE: 'Trình duyệt đã ngừng nhận bookmark khi quá trình nhập đang diễn ra.',
PARTIAL_CLEAR: 'Trình duyệt đã dừng lại giữa chừng khi đang thay thế bookmark của bạn.',
UNKNOWN: 'Đã xảy ra lỗi.',
},
} satisfies Dict;
+16
View File
@@ -19,6 +19,22 @@ export const ISSUES_URL = `${REPO_URL}/issues`;
export const CHANGELOG_URL = `${REPO_URL}/blob/main/CHANGELOG.md`;
/**
* The published Chrome Web Store listing (item id — docs/00 §9).
*
* The only route from inside the product to rating or reviewing it, which
* docs/13 §6 lists as a post-launch channel.
*
* There is deliberately **no support email here.** Putting an address on an
* in-product surface invites users to mail their real bookmarks file, which is
* a browsing history and exactly the receipt of personal data that
* `legal/PRIVACY.md` and docs/09 §6 are written to bound. The address lives in
* SECURITY.md, CONTRIBUTING.md and the privacy policy, where it arrives with
* the instruction to sanitize first (docs/15 decision log, 2026-08-03).
*/
export const STORE_URL =
'https://chromewebstore.google.com/detail/bookmarkmagic/eghnciphhegekmnofffpgbdfefckdhmg';
export interface LabelledLink {
labelKey: string;
url: string;
+65 -2
View File
@@ -31,7 +31,12 @@ export type ImportState =
// begun, and nothing in the progress UI needs it.
| { kind: 'writing'; filename: string; progress: WriteProgress }
| { kind: 'done'; filename: string; created: number; plan: ImportPlan }
| { kind: 'cancelled'; filename: string; created: number }
/**
* `backupFilename` is present only when the cancel landed AFTER the Replace
* clear, i.e. the tree really was deleted and only `created` of it rebuilt.
* Without it the report reads as a harmless no-op on an empty browser.
*/
| { kind: 'cancelled'; filename: string; created: number; backupFilename?: string }
/**
* `messageKey` is a dotted i18n path, NOT a resolved string.
*
@@ -40,7 +45,31 @@ export type ImportState =
* was active when the error happened, so switching language left the error
* message behind in the old one.
*/
| { kind: 'error'; filename: string; messageKey: string; detail: string | undefined };
| {
kind: 'error';
filename: string;
messageKey: string;
/**
* Raw technical text, absent when there is none.
*
* Optional rather than `string | undefined` so it matches `DescribedError`
* exactly — under `exactOptionalPropertyTypes` those are different types,
* and a spread of one into the other is a compile error.
*/
detail?: string | undefined;
/** Nodes created before a partial failure, when the failure knows. */
created?: number;
/** Root children deleted before a partial failure, when it knows. */
removed?: number;
/**
* The safety backup's filename, on a Replace that got past the backup.
*
* Carried onto the failure deliberately: `attesting` knew it and `error`
* used to throw it away, so the one string that lets a user restore a
* half-deleted tree was the one thing not on screen.
*/
backupFilename?: string;
};
let state = $state<ImportState>({ kind: 'idle' });
let options = $state<ImportOptionsState>({ mode: 'new-folder', dedupe: true });
@@ -102,7 +131,41 @@ export function cancelWrite(): void {
controller?.abort();
}
/**
* Resolver for the fallback-backup attestation — held HERE, not in `ImportTab`.
*
* As a component-local `let` it died with the component. Pressing Back during
* `attesting` unmounted the tab, 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.
*/
let attestResolve: ((confirmed: boolean) => void) | undefined;
/** Wait for the user to confirm they have the fallback backup. */
export function awaitAttestation(): Promise<boolean> {
// A resolver that is still live fails CLOSED. An unanswered attestation is
// not consent, and this is the gate in front of deleting every bookmark.
attestResolve?.(false);
return new Promise<boolean>((resolve) => {
attestResolve = resolve;
});
}
export function answerAttestation(confirmed: boolean): void {
attestResolve?.(confirmed);
attestResolve = undefined;
}
export function hasPendingAttestation(): boolean {
return attestResolve !== undefined;
}
export function resetImport(): void {
// Before clearing state, not after: otherwise "Import another file" during an
// attestation moves the deadlock out of a component and into this store,
// where nothing renders it and nobody would find it.
answerAttestation(false);
controller = undefined;
prepared = undefined;
state = { kind: 'idle' };
+22
View File
@@ -94,6 +94,28 @@ export async function loadLegal(): Promise<void> {
status = decideLegalStatus(await readLegal(), LEGAL_VERSION);
}
/**
* Adopt an acceptance recorded by another Manager tab — **one way only**.
*
* Accepting in one tab drops the gate in the other. The reverse is deliberately
* unreachable: `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, exactly the
* deadlock the routing guard and the store-held attestation resolver exist to
* close. Clearing storage in another tab therefore does nothing here; a reload
* is what re-evaluates the gate downward, and that is a fresh page with no
* in-flight work to strand.
*
* @returns whether the gate was dropped.
*/
export function adoptExternalLegal(acceptance: LegalAcceptance | null): boolean {
if (status.kind === 'accepted') return false;
const next = decideLegalStatus(acceptance, LEGAL_VERSION);
if (next.kind !== 'accepted') return false;
status = next;
return true;
}
/**
* Record acceptance.
*
+48 -6
View File
@@ -22,19 +22,61 @@ export function getRoute(): Route {
return current;
}
export function navigate(route: Route): void {
current = route;
if (globalThis.location !== undefined) globalThis.location.hash = `#${route}`;
/**
* Refuses to leave while work would be orphaned. Injected rather than imported,
* so this module keeps knowing nothing about the import session.
*/
export interface RoutingOptions {
/** True while leaving the current route would strand in-flight work. */
isBlocked?: () => boolean;
/** Called when a navigation was refused, so the UI can explain itself. */
onBlocked?: () => void;
}
/** Sync from the URL and follow it. Returns a cleanup function. */
export function startRouting(): () => void {
let blocked: (() => boolean) | undefined;
/**
* Navigate, unless a write is in flight.
*
* @returns whether the navigation actually happened. Callers that ignore this
* turn a refusal into a button that appears to do nothing.
*/
export function navigate(route: Route): boolean {
if (route !== current && blocked?.() === true) return false;
current = route;
if (globalThis.location !== undefined) globalThis.location.hash = `#${route}`;
return true;
}
/**
* Sync from the URL and follow it. Returns a cleanup function.
*
* The `hashchange` listener is also the thing that made Back dangerous. Every
* `navigate()` writes a history entry, so during an import the user could press
* Back, unmount `ImportTab`, and strand the write it was driving — the same
* dead end Phase 4 closed for the footer and the tab bar, reachable through a
* door nobody had guarded.
*/
export function startRouting(options: RoutingOptions = {}): () => void {
current = parse(globalThis.location?.hash ?? '');
blocked = options.isBlocked;
const onHashChange = (): void => {
current = parse(globalThis.location.hash);
const next = parse(globalThis.location.hash);
// Terminates the restore below: putting the hash back fires this handler a
// second time, and that time the parsed route already equals `current`.
if (next === current) return;
if (options.isBlocked?.() === true) {
globalThis.location.hash = `#${current}`;
options.onBlocked?.();
return;
}
current = next;
};
globalThis.addEventListener('hashchange', onHashChange);
return () => {
globalThis.removeEventListener('hashchange', onHashChange);
blocked = undefined;
};
}
+37
View File
@@ -50,6 +50,43 @@ export async function loadSettings(): Promise<void> {
loaded = true;
}
/**
* Adopt settings written by another Manager tab.
*
* Two rules, and between them they solve the echo problem and the debounce
* problem at once:
*
* 1. **If this context has an unflushed write, ignore the change entirely.**
* `save()` writes the whole object, not a patch, so this tab is about to
* overwrite the incoming value anyway — and adopting it first would clobber
* the choice the user just made, in the UI *and* in what gets persisted 200
* ms later. Ignoring is last-write-wins, which is the semantic docs/15
* already documented, and it converges because our write fires this 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 `{...proxy}` and `coerceSettings` do not
* agree on anyway.
*
* Deliberately does not schedule a save: adopting a value that is already on
* disk and writing it straight back would make two tabs ping-pong forever.
*
* @returns whether anything changed.
*/
export function adoptExternalSettings(next: Settings): boolean {
if (saveTimer !== undefined || pending !== undefined) return false;
const keys = Object.keys(DEFAULT_SETTINGS) as (keyof Settings)[];
if (keys.every((key) => settings[key] === next[key])) return false;
// In place, never replaced — see updateSettings.
Object.assign(settings, next);
applyLocale();
applyTheme(settings.theme);
return true;
}
/**
* Apply a patch now, persist it shortly.
*
+7
View File
@@ -11,6 +11,8 @@ import type { LiveNode } from '@/lib/browser/bookmarks';
export interface FakeBookmarksOptions {
/** Throw on the Nth create (1-based), to test partial-failure reporting. */
failOnCreate?: number;
/** Throw on the Nth removeTree (1-based) — the Replace path's equivalent. */
failOnRemoveTree?: number;
}
export class FakeBookmarks {
@@ -18,6 +20,7 @@ export class FakeBookmarks {
private readonly nodes = new Map<string, LiveNode>();
private nextId = 100;
private createCount = 0;
private removeCount = 0;
// An explicit field, not a constructor parameter property: the latter emits
// runtime code and is rejected by `erasableSyntaxOnly` (docs/10 §2).
private readonly options: FakeBookmarksOptions;
@@ -110,7 +113,11 @@ export class FakeBookmarks {
};
removeTree = async (id: string): Promise<void> => {
this.removeCount++;
this.calls.push(`removeTree:${id}`);
if (this.options.failOnRemoveTree === this.removeCount) {
throw new Error(`injected failure on removeTree #${this.removeCount}`);
}
const node = this.nodes.get(id);
if (node === undefined) throw new Error(`no such node: ${id}`);
if (node.unmodifiable !== undefined) throw new Error("Can't modify managed bookmarks");
+33
View File
@@ -151,4 +151,37 @@ describe('clearRoots', () => {
});
expect(current.countCalls('removeTree')).toBe(0);
});
it('reports how much was already deleted when a removal rejects', async () => {
// This is the only path in the product that destroys data. A failure that
// says nothing but "the browser refused" leaves the user unable to tell
// whether they lost two bookmarks or all of them.
current = new FakeBookmarks({ failOnRemoveTree: 3 });
for (let i = 0; i < 5; i++) {
current.seed('2', { title: `b${i}`, url: `https://e${i}.example/` });
}
const roots = await getRoots();
const err = await clearRoots(roots.writable).catch((e: unknown) => e);
expect(err).toMatchObject({ name: 'BmPartialWrite', phase: 'clearing', done: 2 });
});
it('carries the removed count on an abort too, not a hardcoded zero', async () => {
for (let i = 0; i < 4; i++) {
current.seed('2', { title: `b${i}`, url: `https://e${i}.example/` });
}
const controller = new AbortController();
let seen = 0;
const roots = await getRoots();
const original = current.removeTree;
current.removeTree = async (id: string): Promise<void> => {
await original(id);
if (++seen === 2) controller.abort();
};
const err = await clearRoots(roots.writable, controller.signal).catch((e: unknown) => e);
expect(err).toMatchObject({ name: 'BmAborted', done: 2 });
});
});
+98
View File
@@ -0,0 +1,98 @@
import { describe, expect, it } from 'vitest';
import { describeError } from '@/lib/browser/describe-error';
import {
BmAborted,
BmBackupError,
BmBrowserError,
BmEnvError,
BmPartialWrite,
} from '@/lib/browser/errors';
import { BmParseError } from '@/lib/core/model';
/**
* `describeError` — docs/02 §7.
*
* Two properties matter more than the individual mappings, and both have been
* defects in this codebase before:
*
* - the result is a **key**, never a resolved sentence, because the import
* session outlives the component and `t()` is only reactive where it is
* called;
* - `detail` is *absent* when there is none, not `undefined`. Under
* `exactOptionalPropertyTypes` those are different types, and only a runtime
* `'detail' in result` check catches the difference.
*/
describe('describeError', () => {
it('maps a parse error to its own code', () => {
const result = describeError(new BmParseError('TOO_DEEP', 'nesting deeper than 200 levels'));
expect(result.messageKey).toBe('errors.TOO_DEEP');
expect(result.detail).toBe('nesting deeper than 200 levels');
});
it('maps a backup error to its own code', () => {
const result = describeError(new BmBackupError('BACKUP_CANCELLED'));
expect(result.messageKey).toBe('errors.BACKUP_CANCELLED');
});
it('maps a missing writable root to its own key, not to BROWSER', () => {
// The browser refused nothing — every root is policy-managed. Reporting a
// refusal sends the user looking for a permission problem that is not there.
const result = describeError(new BmEnvError('NO_WRITABLE_ROOTS', '1 root(s), none writable'));
expect(result.messageKey).toBe('errors.NO_WRITABLE_ROOTS');
expect(result.detail).toBe('1 root(s), none writable');
});
it('carries the created count off a partial write', () => {
const result = describeError(new BmPartialWrite('writing', 42, new Error('quota')));
expect(result.messageKey).toBe('errors.PARTIAL_WRITE');
expect(result.created).toBe(42);
expect(result.removed).toBeUndefined();
expect(result.detail).toBe('quota');
});
it('carries the removed count off a partial clear, and says something different', () => {
// "some items were added" and "part of your tree is gone" need different
// advice, so the phase picks the sentence rather than a shared one.
const result = describeError(new BmPartialWrite('clearing', 7, new Error('boom')));
expect(result.messageKey).toBe('errors.PARTIAL_CLEAR');
expect(result.removed).toBe(7);
expect(result.created).toBeUndefined();
});
it('unwraps a BmBrowserError cause rather than nesting the message', () => {
const cause = new BmBrowserError('bookmarks.create', new Error('Invalid URL'));
const result = describeError(new BmPartialWrite('writing', 1, cause));
expect(result.detail).toBe('Invalid URL');
});
it('maps a raw browser rejection to BROWSER', () => {
const result = describeError(new BmBrowserError('bookmarks.move', new Error('nope')));
expect(result.messageKey).toBe('errors.BROWSER');
expect(result.detail).toBe('nope');
});
it('falls back to UNKNOWN for anything else, including non-Errors', () => {
expect(describeError(new Error('plain')).messageKey).toBe('errors.UNKNOWN');
expect(describeError('a string').messageKey).toBe('errors.UNKNOWN');
expect(describeError(undefined).messageKey).toBe('errors.UNKNOWN');
});
it('omits detail entirely rather than setting it to undefined', () => {
const result = describeError('not an Error');
expect('detail' in result).toBe(true);
expect(result.detail).toBeUndefined();
// The env-error path uses a conditional spread, so the key is genuinely
// absent — this is the assertion that catches a regression to
// `detail: undefined`, which the type system alone would let through.
const env = describeError(new BmEnvError('NO_WRITABLE_ROOTS'));
expect('detail' in env).toBe(false);
});
it('does not claim to describe an abort — cancellation is not a failure', () => {
// BmAborted is handled by the caller before it ever reaches here. If that
// ever changed, the user's own cancellation would be reported as an error.
const result = describeError(new BmAborted(5));
expect(result.messageKey).toBe('errors.UNKNOWN');
});
});
+12 -6
View File
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { fakeBrowser } from 'wxt/testing/fake-browser';
import { openBookmarkUrl } from '@/lib/browser/open-url';
/**
@@ -8,18 +8,24 @@ import { openBookmarkUrl } from '@/lib/browser/open-url';
* `javascript:` bookmark and the browser acting on it. It had no test.
*/
let created: { url?: string }[] = [];
/**
* Recorded `tabs.create` calls.
*
* `url?: string | undefined` rather than `url?: string`: the API's own
* `CreateProperties` declares it that way, and under
* `exactOptionalPropertyTypes` the two are different types.
*/
let created: { url?: string | undefined }[] = [];
beforeEach(() => {
fakeBrowser.reset();
vi.restoreAllMocks();
created = [];
// fakeBrowser stubs tabs.* with "not implemented" throws.
// fakeBrowser stubs tabs.* with "not implemented" throws. The mock resolves
// with nothing because the API's return type is void — the caller ignores it,
// and only the recorded call matters.
vi.spyOn(fakeBrowser.tabs, 'create').mockImplementation(async (props) => {
created.push(props);
// SAFETY: the caller ignores the return value; only the recorded call
// matters, and building a full Tab here would assert nothing.
return {} as Awaited<ReturnType<typeof fakeBrowser.tabs.create>>;
});
});
+94 -4
View File
@@ -1,19 +1,28 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing/fake-browser';
import {
DEFAULT_SETTINGS,
readLegal,
readSettings,
type StorageChange,
subscribeStorage,
writeLegal,
writeSettings,
} from '@/lib/browser/storage';
// fakeBrowser DOES implement storage.local, so no hand-rolled mock is needed
// here (unlike bookmarks — docs/11 §4).
// fakeBrowser DOES implement storage.local — and, verified before this suite
// was written, storage.onChanged too. No hand-rolled mock is needed here
// (unlike bookmarks — docs/11 §4).
beforeEach(() => {
fakeBrowser.reset();
// reset() clears stored data but leaves spies in place, so one test that
// mocks a storage call would otherwise leak into every later test.
vi.restoreAllMocks();
});
/** Let the storage event dispatch. */
const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve));
describe('settings', () => {
it('returns the documented defaults on a fresh profile', async () => {
expect(await readSettings()).toEqual(DEFAULT_SETTINGS);
@@ -80,3 +89,84 @@ describe('legal acceptance', () => {
expect(Object.keys(all).sort()).toEqual(['legal', 'settings']);
});
});
/**
* `subscribeStorage` — docs/03 §4.
*
* The event fires in every extension context including the one that wrote, so
* this layer only decodes and hands over; deciding what is an echo belongs to
* the store, which is the only thing that knows what it was about to write.
*/
describe('subscribeStorage', () => {
it('reports a settings write made elsewhere, already coerced', async () => {
const seen: StorageChange[] = [];
const stop = subscribeStorage((change) => seen.push(change));
await fakeBrowser.storage.local.set({ settings: { ...DEFAULT_SETTINGS, theme: 'dark' } });
await settle();
expect(seen).toHaveLength(1);
expect(seen[0]?.settings?.theme).toBe('dark');
stop();
});
it('coerces a malformed value field by field rather than passing it through', async () => {
// A second tab is not a more trustworthy source than disk. It is the disk.
const seen: StorageChange[] = [];
const stop = subscribeStorage((change) => seen.push(change));
await fakeBrowser.storage.local.set({ settings: { theme: 'chartreuse', locale: 'vi' } });
await settle();
expect(seen[0]?.settings).toEqual({ ...DEFAULT_SETTINGS, locale: 'vi' });
stop();
});
it('reports a legal acceptance, and a cleared one as null', async () => {
const seen: StorageChange[] = [];
const stop = subscribeStorage((change) => seen.push(change));
await writeLegal(1, '2026-08-03T00:00:00.000Z');
await settle();
expect(seen.at(-1)?.legal?.acceptedVersion).toBe(1);
await fakeBrowser.storage.local.remove('legal');
await settle();
expect(seen.at(-1)?.legal).toBeNull();
stop();
});
it('ignores keys this extension does not own', async () => {
const seen: StorageChange[] = [];
const stop = subscribeStorage((change) => seen.push(change));
await fakeBrowser.storage.local.set({ somethingElse: 1 });
await settle();
expect(seen).toHaveLength(0);
stop();
});
it('stops delivering once unsubscribed', async () => {
const seen: StorageChange[] = [];
const stop = subscribeStorage((change) => seen.push(change));
stop();
await writeSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
await settle();
expect(seen).toHaveLength(0);
});
it('swallows a throwing handler', async () => {
// An exception inside a chrome.* listener surfaces as an extension error in
// chrome://extensions, which docs/11 §5 treats as a failed QA pass.
const stop = subscribeStorage(() => {
throw new Error('handler blew up');
});
await expect(writeSettings({ ...DEFAULT_SETTINGS })).resolves.toBeUndefined();
await settle();
stop();
});
});
+42 -6
View File
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
import { BmAborted } from '@/lib/browser/errors';
import { BmAborted, BmPartialWrite } from '@/lib/browser/errors';
import { type WriteProgress, writeTree } from '@/lib/browser/write-queue';
import type { BookmarkNode, ImportPlan } from '@/lib/core/model';
import { FakeBookmarks } from '../../helpers/fake-bookmarks';
@@ -196,19 +196,55 @@ describe('writeTree — abort', () => {
});
describe('writeTree — API failure', () => {
const sixNodes = (): { title: string; url: string }[] =>
Array.from({ length: 6 }, (_, i) => ({ title: `b${i}`, url: `https://e${i}.example/` }));
it('propagates a create failure with the earlier successes already written', async () => {
const fake = new FakeBookmarks({ failOnCreate: 4 });
const nodes = Array.from({ length: 6 }, (_, i) => ({
title: `b${i}`,
url: `https://e${i}.example/`,
}));
await expect(
writeTree(planOf([{ rootId: '2', nodes }]), { create: fake.create }),
writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), { create: fake.create }),
).rejects.toThrow(/injected failure/);
expect(fake.childTitles('2')).toEqual(['b0', 'b1', 'b2']);
});
it('reports how many nodes landed, because they are still in the user tree', async () => {
// Without this the report says only "the browser refused a bookmark
// operation" — while three real bookmarks sit in the tree, and the user has
// no way to learn how many. BmAborted has always carried this; a failure
// needs it at least as much, because nobody chose it.
const fake = new FakeBookmarks({ failOnCreate: 4 });
const err = await writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), {
create: fake.create,
}).catch((e: unknown) => e);
expect(err).toBeInstanceOf(BmPartialWrite);
const partial = err as BmPartialWrite;
expect(partial.phase).toBe('writing');
expect(partial.done).toBe(3);
expect(partial.detail).toMatch(/injected failure/);
});
it('lets a cancellation stay a cancellation', async () => {
// The abort check throws from inside the same loop as the create. Wrapping
// it would relabel every user cancellation as a failure and make the
// `cancelled` state — and its copy in three languages — unreachable.
const fake = new FakeBookmarks();
const controller = new AbortController();
const err = await writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), {
create: async (details) => {
controller.abort();
return fake.create(details);
},
signal: controller.signal,
}).catch((e: unknown) => e);
expect(err).toBeInstanceOf(BmAborted);
expect(err).not.toBeInstanceOf(BmPartialWrite);
});
});
describe('writeTree — responsiveness', () => {
+81
View File
@@ -0,0 +1,81 @@
import { describe, expect, it, vi } from 'vitest';
import { deleteEach } from '@/lib/edit/bulk-delete';
/**
* Bulk delete — docs/03 §3.
*
* `deleteEach` exists to make the project's recurring defect shape impossible
* here: mutate local state optimistically, await a `chrome.*` call that can
* reject, never handle the rejection. It never throws, so the caller cannot
* forget the failure case, and it reports how far it got — the confirmation
* dialog promised an exact number and the action cannot be undone.
*/
describe('deleteEach', () => {
it('deletes every id and reports a clean run', async () => {
const removed: string[] = [];
const outcome = await deleteEach(
['a', 'b', 'c'],
async () => {},
(id) => removed.push(id),
);
expect(outcome).toEqual({ deleted: 3, total: 3 });
expect(removed).toEqual(['a', 'b', 'c']);
});
it('stops at the first rejection and says how many landed', async () => {
const remove = vi.fn(async (id: string) => {
if (id === 'c') throw new Error('nope');
});
const outcome = await deleteEach(['a', 'b', 'c', 'd'], remove, () => {});
expect(outcome.deleted).toBe(2);
expect(outcome.total).toBe(4);
expect(outcome.error).toBeInstanceOf(Error);
// 'd' is never attempted — one refusal usually means the rest will refuse
// too, and hammering the API would just lengthen a frozen tab.
expect(remove).toHaveBeenCalledTimes(3);
});
it('never throws, whatever the remove does', async () => {
await expect(
deleteEach(
['a'],
() => Promise.reject(new Error('boom')),
() => {},
),
).resolves.toMatchObject({ deleted: 0 });
await expect(
deleteEach(
['a'],
() => Promise.reject('a string'),
() => {},
),
).resolves.toMatchObject({ deleted: 0, error: 'a string' });
});
it('confirms locally only after the browser accepted', async () => {
// The other order is the defect: updating first leaves the tree claiming a
// node is gone that the browser still has, for every id after a failure.
const confirmed: string[] = [];
await deleteEach(
['a', 'b'],
async (id) => {
if (id === 'a') throw new Error('refused');
},
(id) => confirmed.push(id),
);
expect(confirmed).toEqual([]);
});
it('handles an empty list', async () => {
expect(
await deleteEach(
[],
async () => {},
() => {},
),
).toEqual({ deleted: 0, total: 0 });
});
});
+91
View File
@@ -0,0 +1,91 @@
import { describe, expect, it } from 'vitest';
import {
collapseSearchExpansion,
forgetSearchExpansion,
mergeSearchExpansion,
} from '@/lib/edit/search-expansion';
/**
* Search-driven expansion — docs/03 §3.
*
* The bug this closes: a one-character query expands most of a large tree, and
* clearing the box then rendered every one of those rows at once in a single
* synchronous pass, with no virtualization behind it. The 150 ms debounce
* delayed that; it never bounded it.
*/
const set = (...ids: string[]): ReadonlySet<string> => new Set(ids);
describe('mergeSearchExpansion', () => {
it('opens what the search needs and remembers only what it opened', () => {
const result = mergeSearchExpansion(set('a'), set('a', 'b', 'c'), set());
expect([...result.expanded].sort()).toEqual(['a', 'b', 'c']);
// 'a' was already open, so the search does not own it and must not close it.
expect([...result.opened].sort()).toEqual(['b', 'c']);
});
it('accumulates across successive queries', () => {
const first = mergeSearchExpansion(set(), set('a'), set());
const second = mergeSearchExpansion(first.expanded, set('b'), first.opened);
expect([...second.opened].sort()).toEqual(['a', 'b']);
});
it('returns the SAME set objects when nothing is missing', () => {
// Identity, not equality: the caller stores these in `$state`, so returning
// an equal-but-new Set would re-run every dependent on every keystroke.
const expanded = set('a', 'b');
const opened = set('b');
const result = mergeSearchExpansion(expanded, set('a'), opened);
expect(result.expanded).toBe(expanded);
expect(result.opened).toBe(opened);
});
it('is a no-op for an empty search', () => {
const expanded = set('a');
expect(mergeSearchExpansion(expanded, set(), set()).expanded).toBe(expanded);
});
});
describe('collapseSearchExpansion', () => {
it('closes only what the search opened', () => {
const result = collapseSearchExpansion(set('a', 'b', 'c'), set('b', 'c'));
expect([...result]).toEqual(['a']);
});
it('leaves a folder the user opened themselves alone', () => {
// The whole point: a user who expanded a folder while searching keeps it.
const merged = mergeSearchExpansion(set(), set('a', 'b'), set());
const owned = forgetSearchExpansion(merged.opened, 'a');
expect([...collapseSearchExpansion(merged.expanded, owned)]).toEqual(['a']);
});
it('returns the same set when the search opened nothing', () => {
const expanded = set('a');
expect(collapseSearchExpansion(expanded, set())).toBe(expanded);
});
it('tolerates an id that is no longer expanded', () => {
expect([...collapseSearchExpansion(set('a'), set('gone'))]).toEqual(['a']);
});
});
describe('forgetSearchExpansion', () => {
it('drops the id, transferring ownership to the user', () => {
expect([...forgetSearchExpansion(set('a', 'b'), 'a')]).toEqual(['b']);
});
it('returns the same set for an id it never owned', () => {
const opened = set('a');
expect(forgetSearchExpansion(opened, 'zzz')).toBe(opened);
});
});
describe('the whole cycle', () => {
it('search, then clear, returns exactly to the starting state', () => {
const start = set('root');
const merged = mergeSearchExpansion(start, set('root', 'x', 'y', 'z'), set());
expect(merged.expanded.size).toBe(4);
const cleared = collapseSearchExpansion(merged.expanded, merged.opened);
expect([...cleared]).toEqual(['root']);
});
});
+32 -2
View File
@@ -1,10 +1,17 @@
import { existsSync } from 'node:fs';
import { existsSync, readFileSync } from 'node:fs';
import { basename, join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { getAppVersion } from '@/lib/browser/app-info';
import { setLocale, t } from '@/lib/i18n/index.svelte';
import type { Locale } from '@/lib/i18n/resolve-locale';
import { CHANGELOG_URL, DONATE_LINKS, ISSUES_URL, LEGAL_URLS, REPO_URL } from '@/lib/links';
import {
CHANGELOG_URL,
DONATE_LINKS,
ISSUES_URL,
LEGAL_URLS,
REPO_URL,
STORE_URL,
} from '@/lib/links';
const LOCALES: Locale[] = ['en', 'vi', 'ja'];
/** Vitest runs with cwd at the project root, which is where `legal/` lives. */
@@ -83,6 +90,29 @@ describe('outbound links', () => {
});
});
describe('store listing', () => {
it('is the published item, and is the only in-product route to a review', () => {
// docs/13 §6 counts store ratings as a post-launch channel; before this
// there was no way to reach the listing from inside the extension at all.
expect(STORE_URL.startsWith('https://chromewebstore.google.com/detail/')).toBe(true);
// The item id doubles as the CHROME_EXTENSION_ID secret (docs/00 §9), so a
// typo here is a typo in two places.
expect(STORE_URL).toContain('eghnciphhegekmnofffpgbdfefckdhmg');
});
it('puts no email address on any in-product surface', () => {
// Deliberate — docs/15 decision log, 2026-08-03. An address inside the
// extension invites users to mail their real bookmarks file, which is the
// receipt of personal data legal/PRIVACY.md exists to bound. The address
// belongs in SECURITY.md and CONTRIBUTING.md, where it arrives alongside
// the instruction to sanitize first.
const source = readFileSync(join(REPO_ROOT, 'src', 'lib', 'links.ts'), 'utf8');
const code = source.replace(/\/\*\*[\s\S]*?\*\//g, '');
expect(code).not.toMatch(/mailto:/);
expect(code).not.toMatch(/@poli0981\.dev/);
});
});
describe('getAppVersion', () => {
it('returns an empty string rather than throwing when the manifest is unreadable', () => {
// fakeBrowser has no packaged manifest, so this exercises the fallback.
+150 -60
View File
@@ -1,5 +1,5 @@
import { execFileSync } from 'node:child_process';
import { readdirSync, readFileSync } from 'node:fs';
import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join, relative } from 'node:path';
import { describe, expect, it } from 'vitest';
import { detectFormat } from '@/lib/core/detect-format';
@@ -25,11 +25,35 @@ const root = process.cwd();
const script = join(root, 'scripts', 'sanitize-bookmarks.mjs');
const fixtures = join(root, 'tests', 'fixtures');
const sanitize = (absPath: string): string =>
execFileSync(process.execPath, [script, absPath, '--stdout'], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
});
/**
* Run the CLI. `text` is null when it refused — which is a supported outcome,
* not a failure: refusing is what it does with anything it cannot positively
* identify, or whose output still contains a real address.
*/
function sanitize(absPath: string): { text: string | null; status: number } {
try {
const text = execFileSync(process.execPath, [script, absPath, '--stdout'], {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
maxBuffer: 64 * 1024 * 1024,
});
return { text, status: 0 };
} catch (err) {
const status = (err as { status?: number }).status ?? 1;
return { text: null, status };
}
}
/** Hosts that appear anywhere in the raw text, however the file is structured. */
function hostsInText(text: string): string[] {
const out = new Set<string>();
for (const m of text.matchAll(/\b[a-z][a-z0-9+.-]*:\/\/([^\s"'<>)\]}\\]+)/gi)) {
const authority = (m[1] ?? '').split(/[/?#]/, 1)[0] ?? '';
const host = authority.split('@').pop()?.replace(/:\d+$/, '').toLowerCase() ?? '';
if (host !== '') out.add(host);
}
return [...out];
}
/**
* Every committed fixture file, as paths relative to `tests/fixtures/`.
@@ -70,52 +94,51 @@ function topology(roots: readonly BookmarkNode[]): string {
return render(roots);
}
const hostsIn = (roots: readonly BookmarkNode[]): string[] => {
const out: string[] = [];
for (const { node } of walkTree(roots)) {
if (node.url === undefined) continue;
try {
const { host } = new URL(node.url);
if (host !== '') out.push(host);
} catch {
// Unparseable URLs carry no host to leak.
}
}
return out;
};
it('the corpus is non-empty, so a broken walk cannot pass vacuously', () => {
expect(FIXTURES.length).toBeGreaterThan(10);
});
describe.each(FIXTURES)('sanitize %s', (name) => {
const original = readFileSync(join(fixtures, name), 'utf8');
const cleaned = sanitize(join(fixtures, name));
const { text: cleaned, status } = sanitize(join(fixtures, name));
it('keeps the file recognisable as the same format', () => {
let before: string;
it('either sanitizes, or refuses — and refuses exactly what the parser rejects', () => {
// The two must agree. A file the extension itself cannot read is one this
// tool cannot promise to have cleaned, and the old fallback guessed "csv",
// matched no columns, and emitted the input verbatim while reporting
// success — publishing a real bookmark set to a public issue.
let parserAccepts = true;
try {
before = detectFormat(original);
detectFormat(original);
} catch {
// A fixture that is deliberately unrecognisable must stay unrecognisable.
expect(() => detectFormat(cleaned)).toThrow();
return;
parserAccepts = false;
}
if (parserAccepts) {
expect(status).toBe(0);
expect(cleaned).not.toBeNull();
} else {
expect(status).toBe(1);
expect(cleaned).toBeNull();
}
expect(detectFormat(cleaned)).toBe(before);
});
it('parses to the same stats, warnings and structure — or fails the same way', () => {
let before: ParseResult;
try {
before = parseAny(original);
} catch (err) {
// The interesting half: a fixture that reproduces a parse *failure* must
// still reproduce it, with the same code, after sanitizing.
const code = (err as { code?: string }).code;
expect(() => parseAny(cleaned)).toThrowError(expect.objectContaining({ code }));
return;
}
it('leaks no hostname from the original', () => {
// Asserted on the raw TEXT, not on a parse. The previous version returned
// early whenever the original failed to parse, so it passed vacuously on
// precisely the inputs that leaked.
if (cleaned === null) return;
const before = hostsInText(original);
expect(before.filter((host) => cleaned.includes(host))).toEqual([]);
});
it('keeps the file recognisable as the same format', () => {
if (cleaned === null) return;
expect(detectFormat(cleaned)).toBe(detectFormat(original));
});
it('parses to the same stats, warnings and structure', () => {
if (cleaned === null) return;
const before = parseAny(original);
const after = parseAny(cleaned);
expect(after.stats).toEqual(before.stats);
expect(computeStats(after.roots)).toEqual(computeStats(before.roots));
@@ -125,41 +148,108 @@ describe.each(FIXTURES)('sanitize %s', (name) => {
);
});
it('preserves byte-level shape: BOM, line endings and length of the untouched parts', () => {
it('preserves byte-level shape: BOM, line endings and line count', () => {
if (cleaned === null) return;
expect(cleaned.charCodeAt(0) === 0xfeff).toBe(original.charCodeAt(0) === 0xfeff);
expect(cleaned.includes('\r\n')).toBe(original.includes('\r\n'));
expect(cleaned.split('\n').length).toBe(original.split('\n').length);
});
it('preserves every timestamp exactly', () => {
if (cleaned === null) return;
const stamps = (text: string): string[] =>
(text.match(/(?:ADD_DATE|LAST_MODIFIED)="(\d*)"/gi) ?? []).sort();
expect(stamps(cleaned)).toEqual(stamps(original));
});
it('leaks no hostname from the original', () => {
let before: ParseResult;
try {
before = parseAny(original);
} catch {
return;
}
const leaked = hostsIn(before.roots).filter((h) => cleaned.includes(h));
expect(leaked).toEqual([]);
});
it('keeps distinct URLs distinct, so dedupe behaviour is unchanged', () => {
let before: ParseResult;
try {
before = parseAny(original);
} catch {
return;
}
const urls = (r: ParseResult): number => {
if (cleaned === null) return;
const urls = (text: string): number => {
const set = new Set<string>();
for (const { node } of walkTree(r.roots)) if (node.url !== undefined) set.add(node.url);
for (const { node } of walkTree(parseAny(text).roots)) {
if (node.url !== undefined) set.add(node.url);
}
return set.size;
};
expect(urls(parseAny(cleaned))).toBe(urls(before));
expect(urls(cleaned)).toBe(urls(original));
});
});
/**
* The refusal paths — every one of these was a silent leak found by review.
*
* The shared property: when a rule does not reach some byte, the tool must
* refuse rather than hand over a file the user has been told is clean. The
* rules are regexes over untrusted markup, so "we thought of every shape" is
* not a claim anyone can make honestly; the output check is what makes that
* survivable.
*/
describe('refuses rather than leaking', () => {
const tmp = join(root, 'tests', 'fixtures', 'generated');
const run = (name: string, content: string): { text: string | null; status: number } => {
mkdirSync(tmp, { recursive: true });
const path = join(tmp, name);
writeFileSync(path, content);
try {
return sanitize(path);
} finally {
rmSync(path, { force: true });
}
};
it.each([
[
'a truncated JSON export',
'broken.json',
'{"format":"bookmarkmagic","roots":[{"title":"x","url":"https://clinic.internal/a"',
],
[
'an HTML excerpt with no doctype and no <DL>',
'excerpt.html',
'<DT><A HREF="https://clinic.internal/a">Appointment</A>',
],
[
'a CSV with foreign headers',
'foreign.csv',
'folder,name,link\n"m","x","https://clinic.internal/a"\n',
],
])('refuses %s', (_label, name, content) => {
const { text, status } = run(name, content);
expect(status).toBe(1);
expect(text).toBeNull();
});
it('catches a leak the rewriting rules missed, instead of emitting it', () => {
// Single-quoted attributes were not matched at all. The rule is fixed, but
// the point of this test is the backstop: even with the rule removed, the
// output check would refuse rather than publish `clinic.internal`.
const { text, status } = run(
'quoted.html',
"<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p>\n<DT><A HREF='https://clinic.internal/a'>x</A>\n</DL><p>\n",
);
expect(status).toBe(0);
expect(text).not.toBeNull();
expect(text).not.toContain('clinic.internal');
});
it('sanitizes a bookmark whose title contains a raw <', () => {
// `[^<]*` made the whole match fail, so the title was left in place.
const { text } = run(
'angle.html',
'<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p>\n<DT><A HREF="https://a.invalid/">Dr Smith < oncology</A>\n</DL><p>\n',
);
expect(text).not.toBeNull();
expect(text).not.toContain('oncology');
});
it('sanitizes a <DD> description that wraps onto a second line', () => {
// The capture stopped at the first newline, publishing the rest.
const { text } = run(
'dd.html',
'<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p>\n<DT><H3>F</H3>\n<DD>first line\nsecond line with dr-smith\n<DL><p></DL><p>\n</DL><p>\n',
);
expect(text).not.toBeNull();
expect(text).not.toContain('dr-smith');
});
});
+148
View File
@@ -0,0 +1,148 @@
import { beforeEach, describe, expect, it } from 'vitest';
import {
answerAttestation,
awaitAttestation,
beginWrite,
cancelWrite,
getImportState,
hasPendingAttestation,
isWriting,
resetImport,
setImportState,
} from '@/lib/stores/import-session.svelte';
/**
* Import session store — docs/03 §5.
*
* The attestation half of this file exists because of a real dead end: the
* resolver used to be a component-local `let`, so pressing browser Back during
* `attesting` 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. Closing the tab was the only way out.
*/
beforeEach(() => {
resetImport();
});
describe('isWriting', () => {
it.each([
['backing-up', true],
['attesting', true],
['clearing', true],
['writing', true],
['idle', false],
['validating', false],
['parsed', false],
['done', false],
['cancelled', false],
['error', false],
])('%s → %s', (kind, expected) => {
// Only the shape of `kind` is under test; the rest of each variant is
// filled with whatever satisfies the union.
const states: Record<string, Parameters<typeof setImportState>[0]> = {
idle: { kind: 'idle' },
validating: { kind: 'validating', filename: 'f' },
parsed: {
kind: 'parsed',
filename: 'f',
result: { roots: [], warnings: [], stats: { bookmarks: 0, folders: 0, maxDepth: 0 } },
duplicates: 0,
},
'backing-up': { kind: 'backing-up', filename: 'f' },
attesting: { kind: 'attesting', filename: 'f', backupFilename: 'b.json' },
clearing: { kind: 'clearing', filename: 'f' },
writing: {
kind: 'writing',
filename: 'f',
progress: { done: 0, total: 1, currentPath: '' },
},
done: {
kind: 'done',
filename: 'f',
created: 1,
plan: {
mode: 'new-folder',
dedupe: false,
segments: [],
stats: { toCreate: 0, bookmarkCount: 0, skippedExisting: 0, skippedInFile: 0 },
},
},
cancelled: { kind: 'cancelled', filename: 'f', created: 1 },
error: { kind: 'error', filename: 'f', messageKey: 'errors.UNKNOWN' },
};
const state = states[kind];
if (state === undefined) throw new Error(`unmapped kind: ${kind}`);
setImportState(state);
expect(isWriting()).toBe(expected);
});
});
describe('attestation', () => {
it('settles true when the user confirms', async () => {
const pending = awaitAttestation();
expect(hasPendingAttestation()).toBe(true);
answerAttestation(true);
await expect(pending).resolves.toBe(true);
expect(hasPendingAttestation()).toBe(false);
});
it('settles false when the user cancels', async () => {
const pending = awaitAttestation();
answerAttestation(false);
await expect(pending).resolves.toBe(false);
});
it('survives the component that started it — the deadlock this replaced', async () => {
// The resolver lives in the store, so an unmount and remount of ImportTab
// leaves the promise settleable. As a component-local `let` this hung.
const pending = awaitAttestation();
// …component unmounts and remounts here; nothing in the store changes…
expect(hasPendingAttestation()).toBe(true);
answerAttestation(true);
await expect(pending).resolves.toBe(true);
});
it('resetImport settles a pending attestation as NOT confirmed', async () => {
// "Import another file" pressed mid-attestation must not leave a resolver
// behind — that would move the deadlock from a component, where it is
// visible, into a store, where nothing renders it.
const pending = awaitAttestation();
resetImport();
await expect(pending).resolves.toBe(false);
expect(hasPendingAttestation()).toBe(false);
expect(getImportState().kind).toBe('idle');
});
it('a second attestation settles the first as NOT confirmed, never drops it', async () => {
// Failing closed matters here more than anywhere: this promise is the last
// gate before deleting every bookmark the user has.
const first = awaitAttestation();
const second = awaitAttestation();
await expect(first).resolves.toBe(false);
answerAttestation(true);
await expect(second).resolves.toBe(true);
});
it('answering with nothing pending is a no-op, not a throw', () => {
expect(() => answerAttestation(true)).not.toThrow();
});
});
describe('write control', () => {
it('beginWrite hands out a signal that cancelWrite aborts', () => {
const signal = beginWrite();
expect(signal.aborted).toBe(false);
cancelWrite();
expect(signal.aborted).toBe(true);
});
it('each write gets a fresh signal, so a past cancel cannot poison the next', () => {
const first = beginWrite();
cancelWrite();
const second = beginWrite();
expect(first.aborted).toBe(true);
expect(second.aborted).toBe(false);
});
});
+53 -1
View File
@@ -1,8 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { fakeBrowser } from 'wxt/testing/fake-browser';
import { LEGAL_VERSION } from '@/lib/core/limits';
import {
acceptLegal,
adoptExternalLegal,
decideLegalStatus,
getAcceptance,
getBlockedRoutes,
@@ -159,3 +160,54 @@ describe('acceptLegal', () => {
expect(Object.keys(all)).not.toContain('legal');
});
});
/**
* Cross-tab adoption — docs/03 §4, docs/14 §2.
*
* Deliberately one-way. `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 — the same deadlock the routing guard and
* the store-held attestation resolver exist to close, reached through a third
* door. These tests exist so a future "simplification" that makes it
* symmetrical fails loudly rather than shipping.
*/
describe('adoptExternalLegal', () => {
it('drops the gate when another tab accepts', async () => {
await loadLegal();
expect(isGateRequired()).toBe(true);
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' })).toBe(true);
expect(isGateRequired()).toBe(false);
});
it('does NOT re-gate when another tab clears the acceptance', async () => {
await fakeBrowser.storage.local.set({
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' },
});
await loadLegal();
expect(isGateRequired()).toBe(false);
expect(adoptExternalLegal(null)).toBe(false);
expect(isGateRequired()).toBe(false);
});
it('does NOT re-gate on a superseded record either', async () => {
await fakeBrowser.storage.local.set({
legal: { acceptedVersion: LEGAL_VERSION, acceptedAt: 'x' },
});
await loadLegal();
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION - 1, acceptedAt: 'old' })).toBe(
false,
);
expect(isGateRequired()).toBe(false);
});
it('ignores a stale record while the gate is up, rather than accepting it', async () => {
await loadLegal();
expect(adoptExternalLegal({ acceptedVersion: LEGAL_VERSION - 1, acceptedAt: 'old' })).toBe(
false,
);
expect(isGateRequired()).toBe(true);
});
});
+89
View File
@@ -52,3 +52,92 @@ describe('route store', () => {
expect(getRoute()).toBe('about');
});
});
/**
* The guard exists because browser Back was the one route out of #import that
* nothing checked. During the backup attestation it unmounted `ImportTab` and
* stranded the promise `runImport` was awaiting — a Manager that could only be
* escaped by closing the tab.
*/
describe('route store — blocked while a write is in flight', () => {
const settle = (): Promise<void> =>
new Promise((resolve) => {
setTimeout(() => setTimeout(() => resolve()));
});
it('refuses an external hashchange and puts the hash back', async () => {
const stop = startRouting({ isBlocked: () => true });
globalThis.location.hash = '#export';
await settle();
expect(getRoute()).toBe('import');
expect(globalThis.location.hash).toBe('#import');
stop();
});
it('restoring the hash does not recurse', async () => {
// Putting the hash back fires `hashchange` a second time. Without the
// `next === current` early return that is an infinite loop, in a released
// extension, on the one path a panicking user is most likely to take.
let blockedCalls = 0;
const stop = startRouting({
isBlocked: () => {
blockedCalls++;
return true;
},
});
globalThis.location.hash = '#edit';
await settle();
expect(blockedCalls).toBe(1);
stop();
});
it('reports the refusal exactly once, so the UI can explain itself', async () => {
let notified = 0;
const stop = startRouting({ isBlocked: () => true, onBlocked: () => notified++ });
globalThis.location.hash = '#about';
await settle();
expect(notified).toBe(1);
stop();
});
it('navigate() returns false and writes nothing while blocked', () => {
const stop = startRouting({ isBlocked: () => true });
expect(navigate('export')).toBe(false);
expect(getRoute()).toBe('import');
expect(globalThis.location.hash === '#export').toBe(false);
stop();
});
it('navigating to the route you are already on is never refused', () => {
// Otherwise ImportTab could not re-assert its own route mid-write.
const stop = startRouting({ isBlocked: () => true });
expect(navigate('import')).toBe(true);
stop();
});
it('follows again as soon as the write finishes', async () => {
let writing = true;
const stop = startRouting({ isBlocked: () => writing });
globalThis.location.hash = '#edit';
await settle();
expect(getRoute()).toBe('import');
writing = false;
globalThis.location.hash = '#edit';
await settle();
expect(getRoute()).toBe('edit');
stop();
});
it('leaves the guard behind on cleanup, so a stale predicate cannot lock the app', () => {
const stop = startRouting({ isBlocked: () => true });
stop();
expect(navigate('export')).toBe(true);
});
});
+71 -1
View File
@@ -1,8 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fakeBrowser } from 'wxt/testing';
import { fakeBrowser } from 'wxt/testing/fake-browser';
import { DEFAULT_SETTINGS } from '@/lib/browser/storage';
import { getLocale } from '@/lib/i18n/index.svelte';
import {
adoptExternalSettings,
applyTheme,
flushSettings,
getSettings,
@@ -200,3 +201,72 @@ describe('settings store', () => {
}
});
});
/**
* Cross-tab adoption — docs/03 §4.
*
* Two Manager tabs used to silently overwrite each other, because `save()`
* writes the whole settings object rather than a patch: a tab holding a stale
* locale reverted the other tab's language change the moment its own theme
* toggle fired. From the user's side that is "I changed it and it didn't
* stick", which is unfalsifiable and reads as a bug in the extension.
*/
describe('adoptExternalSettings', () => {
it('applies a change from another tab, including locale and theme', async () => {
await updateSettings({ theme: 'light' });
const changed = adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark', locale: 'vi' });
expect(changed).toBe(true);
expect(getSettings().theme).toBe('dark');
expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
expect(getLocale()).toBe('vi');
});
it('mutates in place, so a component that captured the object still sees it', () => {
const captured = getSettings();
adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
expect(getSettings()).toBe(captured);
expect(captured.theme).toBe('dark');
});
it('ignores an identical value — which is what our own write looks like', () => {
// Echo suppression falls out of field equality: no snapshot to keep in step,
// and no dependence on key order.
expect(adoptExternalSettings({ ...getSettings() })).toBe(false);
});
it('does NOT clobber an edit this tab has not persisted yet', async () => {
// The hazard the whole design exists for. Writes are debounced 200 ms; a
// change arriving inside that window must lose, because this tab is about
// to write its entire object over it anyway — adopting first would revert
// the user's choice in the UI *and* in what gets saved.
vi.useFakeTimers();
try {
void updateSettings({ theme: 'dark' });
const changed = adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'light' });
expect(changed).toBe(false);
expect(getSettings().theme).toBe('dark');
await vi.advanceTimersByTimeAsync(250);
const stored = await fakeBrowser.storage.local.get('settings');
expect((stored.settings as { theme: string }).theme).toBe('dark');
} finally {
vi.useRealTimers();
}
});
it('adopts again once the pending write has flushed', async () => {
await updateSettings({ theme: 'dark' });
await flushSettings();
expect(adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'light' })).toBe(true);
});
it('does not write back what it just adopted', async () => {
// Otherwise two tabs ping-pong the same value forever.
const spy = vi.spyOn(fakeBrowser.storage.local, 'set');
adoptExternalSettings({ ...DEFAULT_SETTINGS, theme: 'dark' });
await flushSettings();
expect(spy).not.toHaveBeenCalled();
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vitest/config';
import { WxtVitest } from 'wxt/testing';
import { WxtVitest } from 'wxt/testing/vitest-plugin';
/**
* jsdom, not happy-dom (docs/02 §3). The Netscape parser walk depends on