feat(core): implement the pure core library with fixtures and tests (Phase 1)
Implements src/lib/core/ per docs/04 and docs/05: model, timestamps, normalize-url, csv-path, detect-format, three parsers, four serializers, dedupe and diff. 175 tests, 97% statements / 91% branches on core, well over the 90/90/85 gate. `npm run verify` green. The flagship round-trip suite asserts `parse(serialize(t)).roots deepEquals project(t, format)` with zero warnings, across sample trees, every browser fixture and 200 seeded random trees per format — 600 round-trips, with a nasty-title pool covering quotes, commas, CR/LF, emoji, RTL, `</a>` and path slashes. Seven defects found by an adversarial review pass and fixed here, each with a regression test: - normalize-url rebuilt a bare-origin key from protocol+host, discarding userinfo — https://alice@host/ and https://bob@host/ collapsed to one key, so one of them would be silently dropped on import. - The Netscape walk picked a single root <DL>. Against the real Safari shape (top-level <DT><H3> with no wrapper, Mozilla bug 801450) that returns the first folder's INNER list and reports a clean parse having dropped every other top-level folder. Replaced with a document-order pass over <body> that accepts both entry-point kinds, skipping child lists already consumed via an explicit </DT> so subtrees are not emitted twice. The old test named this case but its fixture had a wrapper, so the branch was never exercised. - escapeHtml emitted CR verbatim; the HTML tokenizer normalizes CR/CRLF to LF before character references are decoded, so any title carrying \r from BM JSON or a quoted CSV field was mutated by an HTML round trip. - joinPath(['']) collapsed to '', indistinguishable from "no path", so a folder with an empty title dissolved on CSV re-import. - parseCsv counted only bookmark rows against MAX_NODES, so folders synthesized from deep paths bypassed the cap entirely. - detect-format required a literal unquoted `folder_path` prefix and so rejected fully quoted headers that parseCsv itself accepts; both now share one matcher. - Markdown formatUrl encoded `>` but not `<` or line endings, producing an angle-bracket destination CommonMark rejects. docs/04 §1.2 is corrected too: its stated fallback ("walk the top-level <DT> children of body") is itself lossy on files that mix a wrapper with loose <DT>s. Also adds .gitattributes so fixture CRLF survives a clone — EOL normalization would otherwise make a fresh checkout test different bytes. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ea9573a12e
commit
6879558a97
51 files changed
+3474
-15
No files matched your search
@@ -0,0 +1,8 @@
|
||||
# Default: normalize to LF in the repo, check out native.
|
||||
* text=auto
|
||||
|
||||
# Fixtures are byte-exact samples of what real browsers and spreadsheets emit.
|
||||
# EOL normalization would rewrite the CRLF records in the CSV exports, so a
|
||||
# fresh clone would test a different file than the one that was committed.
|
||||
# NOTE: last matching rule wins, so this block must stay BELOW the `*` line.
|
||||
tests/fixtures/** -text
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
|
||||
"files": {
|
||||
"ignoreUnknown": true,
|
||||
"includes": ["**", "!**/*.svelte", "!**/*.css", "!.output", "!.wxt"]
|
||||
"includes": ["**", "!**/*.svelte", "!**/*.css", "!.output", "!.wxt", "!tests/fixtures"]
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
|
||||
+25
-10
@@ -43,7 +43,12 @@ HTML. `DOMParser('text/html')` normalizes it fine.
|
||||
|
||||
Export rules: 4-space indent per depth (matches Chrome), attributes only when
|
||||
values exist, `PERSONAL_TOOLBAR_FOLDER="true"` on the toolbar root folder,
|
||||
HTML-escape `& < > "` in titles and hrefs.
|
||||
HTML-escape `& < > "` in titles and hrefs — **and `\r` as ` `**. The last
|
||||
one is not a markup hazard but a round-trip one: the HTML tokenizer normalizes
|
||||
CR and CRLF to LF during input-stream preprocessing, so an unescaped `\r` in a
|
||||
title comes back as `\n`. A numeric reference survives, because character
|
||||
references are decoded after that normalization. `\r` reaches us from BM JSON
|
||||
and from quoted CSV fields, so this is reachable, not theoretical.
|
||||
|
||||
### 1.2 Parse tolerance (import)
|
||||
|
||||
@@ -71,14 +76,21 @@ Must accept, with a warning where noted:
|
||||
- `<HR>` separator elements (Firefox) → skipped, no warning. These are
|
||||
*elements*, so "unknown attributes ignored" does not cover them.
|
||||
- Empty folders → preserved.
|
||||
- **Root list selection.** Take the **outermost** `<DL>` (one with no `<DL>`
|
||||
ancestor), not `document.querySelector('dl')`. Safari has been reported
|
||||
(Mozilla bug 801450) to emit top-level `<DT><H3>` folders with no outer
|
||||
`<DL>` wrapper; against that shape "first DL" grabs the *first folder's
|
||||
inner* list and every later top-level folder is silently discarded. If any
|
||||
`DT > H3` sits outside the chosen `<DL>`, fall back to walking the top-level
|
||||
`<DT>` children of `<body>`. ⚠️ The exact Safari shape is unverified — gate
|
||||
this on a captured Safari export before shipping (`11 §2`).
|
||||
- **Root list selection.** Do **not** pick a single root `<DL>` —
|
||||
`document.querySelector('dl')` and "the outermost `<DL>`" are both lossy.
|
||||
Safari has been reported (Mozilla bug 801450) to emit top-level `<DT><H3>`
|
||||
folders with no outer wrapper, and real files can mix the two: one wrapped
|
||||
root list followed by loose `<DT>`s. Either single-root rule silently drops
|
||||
whichever half it did not pick, with no warning.
|
||||
|
||||
Instead walk `<body>`'s children **in document order** and accept both kinds
|
||||
of entry point — a `<DT>` is read as a root entry, a `<DL>` is walked as a
|
||||
root list. One caveat: when a file emits an explicit `</DT>`, a folder's
|
||||
child `<DL>` also lands at body level, so compute each body-level `<DT>`'s
|
||||
child list first and skip any `<DL>` already consumed that way, or the whole
|
||||
subtree is emitted twice. Algorithm in `05 §1`.
|
||||
⚠️ The exact Safari shape is still unverified against a real export — gate
|
||||
the fixture on a captured one before shipping (`11 §2`).
|
||||
|
||||
Hard failures only: no `NETSCAPE-Bookmark-file-1` doctype **and** no `<DL>`
|
||||
found; or node/size/depth caps exceeded (`TOO_MANY_NODES`, `FILE_TOO_LARGE`,
|
||||
@@ -143,7 +155,10 @@ folder_path,title,url,add_date
|
||||
```
|
||||
|
||||
- Separator `/` in `folder_path`; literal `/` inside a folder name escaped as
|
||||
`\/` (and `\` as `\\`). Empty path ⇒ top level.
|
||||
`\/` (and `\` as `\\`). Empty path ⇒ top level. A single folder whose title
|
||||
is empty is written as a lone `\` — otherwise it is indistinguishable from
|
||||
"no path" and the folder dissolves on re-import. A lone `\` is unreachable
|
||||
from normal escaping (every literal `\` is doubled), so it is free to use.
|
||||
- RFC 4180: quote fields containing `, " \n`; escape `"` as `""`. Accept both
|
||||
`,` and `;` delimiters on import (sniff header); export delimiter is a
|
||||
Settings option (default `,`).
|
||||
|
||||
+17
-4
@@ -11,10 +11,18 @@ All in `src/lib/core/` (pure, unit-tested) except the write queue
|
||||
parseNetscapeHtml(text):
|
||||
doc = new DOMParser().parseFromString(text, 'text/html')
|
||||
hasDoctype = /NETSCAPE-Bookmark-file-1/i.test(text.slice(0, 512))
|
||||
dl = outermostDl(doc) // DL with no DL ancestor — NOT querySelector('dl')
|
||||
if !dl and !hasDoctype → BmParseError('NOT_NETSCAPE')
|
||||
if !dl → return { roots: [], stats: emptyStats, warnings: [{ code: 'NO_BOOKMARKS' }] }
|
||||
roots = walkDl(dl, 0)
|
||||
hasEntries = doc has any <DL>, or body has a direct <DT> child
|
||||
if !hasEntries and !hasDoctype → BmParseError('NOT_NETSCAPE')
|
||||
if !hasEntries → return { roots: [], stats: emptyStats, warnings: [{ code: 'NO_BOOKMARKS' }] }
|
||||
roots = collectRoots(doc.body)
|
||||
|
||||
collectRoots(body): // NOT "the outermost DL" — see 04 §1.2
|
||||
consumed = { nextDlFor(dt) for each direct <DT> child of body }
|
||||
roots = []
|
||||
for el of body.children in document order:
|
||||
if el is DT → roots.push(readEntry(el, depth 1))
|
||||
if el is DL and el not in consumed → roots.push(...walkDl(el, 1))
|
||||
return roots
|
||||
|
||||
walkDl(dl, depth):
|
||||
if depth > MAX_DEPTH → BmParseError('TOO_DEEP')
|
||||
@@ -57,6 +65,11 @@ Use `textContent` (never innerHTML) → titles are inert.
|
||||
|
||||
Purpose: dedupe/diff keys only — **never rewrites stored URLs**.
|
||||
|
||||
The failure mode to guard against is a **false positive**: two different URLs
|
||||
producing the same key means one of them is silently dropped on import. Keep
|
||||
userinfo, port, host and path all in the key — in particular, do not rebuild a
|
||||
bare-origin key from `protocol + host`, which discards `user:pass@`.
|
||||
|
||||
```
|
||||
normalizeUrl(raw):
|
||||
u = new URL(raw) // throws → return raw.trim() as-is key
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* folder_path encoding for CSV — docs/04 §3.
|
||||
*
|
||||
* Purpose: `/` separates folders, so a literal `/` inside a folder NAME must
|
||||
* be escaped, and the escape character with it.
|
||||
* Inputs / guarantees: `splitPath(joinPath(x))` deep-equals `x` for any
|
||||
* segment content, including backslashes and slashes.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A single empty segment cannot be written as `''` — that is indistinguishable
|
||||
* from "no path at all", so a folder with an empty title would be dissolved by
|
||||
* an export/import cycle. A lone backslash is unreachable from normal escaping
|
||||
* (every literal `\` is doubled), so it is free to use as the marker.
|
||||
*/
|
||||
const EMPTY_SEGMENT = '\\';
|
||||
|
||||
/** Join folder titles into a single path field, escaping `\` then `/`. */
|
||||
export function joinPath(segments: readonly string[]): string {
|
||||
if (segments.length === 1 && segments[0] === '') return EMPTY_SEGMENT;
|
||||
return segments.map((s) => s.replace(/\\/g, '\\\\').replace(/\//g, '\\/')).join('/');
|
||||
}
|
||||
|
||||
/** Split a path field back into folder titles, honouring `\\` and `\/`. */
|
||||
export function splitPath(path: string): string[] {
|
||||
if (path === '') return [];
|
||||
if (path === EMPTY_SEGMENT) return [''];
|
||||
|
||||
const segments: string[] = [];
|
||||
let current = '';
|
||||
let escaped = false;
|
||||
|
||||
for (const ch of path) {
|
||||
if (escaped) {
|
||||
// Only `\` and `/` are meaningful escapes; anything else keeps the
|
||||
// backslash so unknown sequences survive a round trip unchanged.
|
||||
current += ch === '\\' || ch === '/' ? ch : `\\${ch}`;
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
if (ch === '\\') {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
if (ch === '/') {
|
||||
segments.push(current);
|
||||
current = '';
|
||||
continue;
|
||||
}
|
||||
current += ch;
|
||||
}
|
||||
|
||||
if (escaped) current += '\\'; // trailing lone backslash
|
||||
segments.push(current);
|
||||
return segments;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Duplicate handling — docs/05 §3.
|
||||
*
|
||||
* Purpose: drop bookmarks the user already has, and collapse repeats within
|
||||
* one file, keeping the two causes countable separately.
|
||||
* Inputs: a parsed tree plus an index built from the current browser tree.
|
||||
* Guarantees: pure; folders are preserved even when every child is dropped.
|
||||
*/
|
||||
import { type BookmarkNode, isFolder } from './model';
|
||||
import { normalizeUrl } from './normalize-url';
|
||||
|
||||
export type UrlIndex = ReadonlySet<string>;
|
||||
|
||||
/** Build the comparison index from a tree (normally the live browser tree). */
|
||||
export function buildUrlIndex(roots: readonly BookmarkNode[]): Set<string> {
|
||||
const index = new Set<string>();
|
||||
const walk = (nodes: readonly BookmarkNode[]): void => {
|
||||
for (const node of nodes) {
|
||||
if (node.url !== undefined) index.add(normalizeUrl(node.url));
|
||||
if (node.children !== undefined) walk(node.children);
|
||||
}
|
||||
};
|
||||
walk(roots);
|
||||
return index;
|
||||
}
|
||||
|
||||
export interface DedupeResult {
|
||||
nodes: BookmarkNode[];
|
||||
/** Dropped because the URL is already in the browser. */
|
||||
skippedExisting: number;
|
||||
/** Dropped because the URL repeats within this file. */
|
||||
skippedInFile: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter an import tree against the browser index.
|
||||
*
|
||||
* Pass an EMPTY index for Replace mode: the browser tree is deleted before the
|
||||
* write, so nothing can already exist, and using the live index would skip
|
||||
* every bookmark of a user restoring their own backup (docs/05 §3).
|
||||
*
|
||||
* Folders that become empty are KEPT — the user's folder structure is the
|
||||
* point, and the report states how many bookmarks were skipped.
|
||||
*/
|
||||
export function dedupeAgainst(roots: readonly BookmarkNode[], index: UrlIndex): DedupeResult {
|
||||
const seenInFile = new Set<string>();
|
||||
let skippedExisting = 0;
|
||||
let skippedInFile = 0;
|
||||
|
||||
const copy = (nodes: readonly BookmarkNode[]): BookmarkNode[] => {
|
||||
const out: BookmarkNode[] = [];
|
||||
for (const node of nodes) {
|
||||
if (isFolder(node)) {
|
||||
out.push({ ...node, children: copy(node.children ?? []) });
|
||||
continue;
|
||||
}
|
||||
const key = normalizeUrl(node.url as string);
|
||||
if (index.has(key)) {
|
||||
skippedExisting++;
|
||||
continue;
|
||||
}
|
||||
if (seenInFile.has(key)) {
|
||||
skippedInFile++;
|
||||
continue;
|
||||
}
|
||||
seenInFile.add(key);
|
||||
out.push({ ...node });
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
return { nodes: copy(roots), skippedExisting, skippedInFile };
|
||||
}
|
||||
|
||||
export interface DuplicateGroup<T> {
|
||||
key: string;
|
||||
nodes: T[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Group nodes sharing a normalized URL, largest group first. Used by the
|
||||
* #edit duplicate panel over the LIVE tree, so `T` carries an `id` there.
|
||||
*/
|
||||
export function findDuplicateGroups<T extends { url?: string }>(
|
||||
nodes: readonly T[],
|
||||
): DuplicateGroup<T>[] {
|
||||
const groups = new Map<string, T[]>();
|
||||
for (const node of nodes) {
|
||||
if (node.url === undefined) continue;
|
||||
const key = normalizeUrl(node.url);
|
||||
const bucket = groups.get(key);
|
||||
if (bucket === undefined) groups.set(key, [node]);
|
||||
else bucket.push(node);
|
||||
}
|
||||
return [...groups]
|
||||
.filter(([, bucket]) => bucket.length > 1)
|
||||
.map(([key, bucket]) => ({ key, nodes: bucket }))
|
||||
.sort((a, b) => b.nodes.length - a.nodes.length);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Format sniffing — docs/04 intro.
|
||||
*
|
||||
* Purpose: decide which parser to run from the CONTENT, never the extension.
|
||||
* Inputs: decoded file text.
|
||||
* Guarantees: never throws for a recognised format; throws `UNKNOWN_FORMAT`
|
||||
* when nothing matches.
|
||||
*
|
||||
* A leading BOM is stripped before sniffing. The UTF-8 decode at the read
|
||||
* boundary normally removes it, but a caller that decodes with
|
||||
* `ignoreBOM: true` would otherwise fail the `{` and header probes.
|
||||
*/
|
||||
import { BmParseError, type FileFormat } from './model';
|
||||
import { BM_JSON_FORMAT } from './parse/bm-json';
|
||||
import { matchCsvHeader } from './parse/csv';
|
||||
|
||||
const DOCTYPE_PROBE_BYTES = 512;
|
||||
|
||||
export function stripBom(text: string): string {
|
||||
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegate to the parser's own header matcher rather than substring-matching
|
||||
* the raw line: header fields may be quoted, and a sniffer stricter than the
|
||||
* parser would reject files the parser handles fine.
|
||||
*/
|
||||
function looksLikeCsvHeader(text: string): boolean {
|
||||
const firstBreak = text.search(/\r\n|\r|\n/);
|
||||
return matchCsvHeader(firstBreak === -1 ? text : text.slice(0, firstBreak)) !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify the format of a bookmark file.
|
||||
*
|
||||
* @throws {BmParseError} `UNKNOWN_FORMAT` when the content matches nothing.
|
||||
*/
|
||||
export function detectFormat(rawText: string): FileFormat {
|
||||
const text = stripBom(rawText);
|
||||
|
||||
if (/NETSCAPE-Bookmark-file-1/i.test(text.slice(0, DOCTYPE_PROBE_BYTES))) return 'netscape-html';
|
||||
|
||||
const trimmed = text.trimStart();
|
||||
if (trimmed.startsWith('{')) {
|
||||
try {
|
||||
const doc: unknown = JSON.parse(trimmed);
|
||||
if (
|
||||
typeof doc === 'object' &&
|
||||
doc !== null &&
|
||||
(doc as { format?: unknown }).format === BM_JSON_FORMAT
|
||||
) {
|
||||
return 'bm-json';
|
||||
}
|
||||
} catch {
|
||||
// Not valid JSON — fall through to the CSV probe.
|
||||
}
|
||||
}
|
||||
|
||||
if (looksLikeCsvHeader(text)) return 'csv';
|
||||
|
||||
// A <DL> with no doctype is still Netscape HTML in practice; the parser
|
||||
// decides whether it is usable.
|
||||
if (/<\s*dl[\s>]/i.test(text)) return 'netscape-html';
|
||||
|
||||
throw new BmParseError('UNKNOWN_FORMAT', 'not Netscape HTML, BM JSON or CSV');
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Preview diff — docs/05 §5.
|
||||
*
|
||||
* Purpose: tell the user, before anything is written, which bookmarks in the
|
||||
* file they already have.
|
||||
* Inputs: a parsed tree and an index of the current browser tree.
|
||||
* Guarantees: pure; path-insensitive, matching the question users actually
|
||||
* ask ("do I already have this link?").
|
||||
*/
|
||||
import type { UrlIndex } from './dedupe';
|
||||
import { type BookmarkNode, isFolder } from './model';
|
||||
import { normalizeUrl } from './normalize-url';
|
||||
|
||||
export type NodeStatus = 'new' | 'exists';
|
||||
|
||||
export interface DiffResult {
|
||||
/** Distinct-per-node counts: a URL appearing 3x in the file counts 3 times. */
|
||||
newCount: number;
|
||||
existsCount: number;
|
||||
/** Per-node badge source for the preview tree. */
|
||||
status: WeakMap<BookmarkNode, NodeStatus>;
|
||||
}
|
||||
|
||||
export function diffAgainstBrowser(roots: readonly BookmarkNode[], index: UrlIndex): DiffResult {
|
||||
const status = new WeakMap<BookmarkNode, NodeStatus>();
|
||||
let newCount = 0;
|
||||
let existsCount = 0;
|
||||
|
||||
const walk = (nodes: readonly BookmarkNode[]): void => {
|
||||
for (const node of nodes) {
|
||||
if (isFolder(node)) {
|
||||
walk(node.children ?? []);
|
||||
continue;
|
||||
}
|
||||
const exists = index.has(normalizeUrl(node.url as string));
|
||||
status.set(node, exists ? 'exists' : 'new');
|
||||
if (exists) existsCount++;
|
||||
else newCount++;
|
||||
}
|
||||
};
|
||||
|
||||
walk(roots);
|
||||
return { newCount, existsCount, status };
|
||||
}
|
||||
|
||||
/**
|
||||
* Map every folder in a tree to its ancestor-title path, for merge-mode folder
|
||||
* matching. Keys are exact and case-sensitive (docs/05 §5); the path is built
|
||||
* from titles only, so it is comparable across a file and the browser tree.
|
||||
*/
|
||||
export function buildFolderPathIndex<T extends { title: string; children?: T[]; url?: string }>(
|
||||
roots: readonly T[],
|
||||
): Map<string, T> {
|
||||
const index = new Map<string, T>();
|
||||
const walk = (nodes: readonly T[], trail: readonly string[]): void => {
|
||||
for (const node of nodes) {
|
||||
if (node.url !== undefined) continue;
|
||||
const path = [...trail, node.title];
|
||||
const key = JSON.stringify(path);
|
||||
// First occurrence wins — a tree with two identically-named siblings is
|
||||
// degenerate, and reusing the first is what a user expects on merge.
|
||||
if (!index.has(key)) index.set(key, node);
|
||||
walk(node.children ?? [], path);
|
||||
}
|
||||
};
|
||||
walk(roots, []);
|
||||
return index;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Core data model — the shapes every parser, serializer and planner speaks.
|
||||
*
|
||||
* Purpose: one definition of a bookmark tree, independent of any browser API.
|
||||
* Inputs: none (types + error classes only).
|
||||
* Guarantees: `BookmarkNode` is the FILE model and carries no ids. Anything
|
||||
* touching the live browser tree uses `chrome.bookmarks.BookmarkTreeNode`,
|
||||
* which already has `id`/`parentId`/`index` (docs/02 §4).
|
||||
*
|
||||
* Note `exactOptionalPropertyTypes` is on (docs/10 §2): build nodes by
|
||||
* OMITTING absent keys, never by assigning `undefined`.
|
||||
*/
|
||||
|
||||
export interface BookmarkNode {
|
||||
title: string;
|
||||
/** Absent ⇒ this node is a folder. */
|
||||
url?: string;
|
||||
/** Epoch SECONDS. `chrome.bookmarks` uses milliseconds — convert at the adapter. */
|
||||
addDate?: number;
|
||||
/** Epoch SECONDS. */
|
||||
lastModified?: number;
|
||||
/** Netscape `PERSONAL_TOOLBAR_FOLDER`. Routing hint only — never stored by Chrome. */
|
||||
toolbar?: boolean;
|
||||
children?: BookmarkNode[];
|
||||
}
|
||||
|
||||
export interface TreeStats {
|
||||
bookmarks: number;
|
||||
folders: number;
|
||||
maxDepth: number;
|
||||
}
|
||||
|
||||
/** Non-fatal anomalies. Tolerated input never throws — it warns (docs/04 §1.2). */
|
||||
export type ParseWarningCode =
|
||||
| 'NO_BOOKMARKS'
|
||||
| 'DESCRIPTIONS_DROPPED'
|
||||
| 'FAVICONS_IGNORED'
|
||||
| 'INVALID_DATE'
|
||||
| 'MISSING_URL'
|
||||
| 'NEWER_VERSION'
|
||||
| 'EMPTY_TITLE';
|
||||
|
||||
export interface ParseWarning {
|
||||
code: ParseWarningCode;
|
||||
/** How many nodes this warning aggregates. One warning per code, not per node. */
|
||||
count: number;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export interface ParseResult {
|
||||
/** Top-level nodes from the file. */
|
||||
roots: BookmarkNode[];
|
||||
stats: TreeStats;
|
||||
warnings: ParseWarning[];
|
||||
}
|
||||
|
||||
export type FileFormat = 'netscape-html' | 'bm-json' | 'csv';
|
||||
|
||||
export type MergeMode = 'new-folder' | 'merge' | 'replace';
|
||||
|
||||
export interface PlanSegment {
|
||||
/** Chrome folder id to write this subtree under. Always resolved via getTree(). */
|
||||
rootId: string;
|
||||
nodes: BookmarkNode[];
|
||||
}
|
||||
|
||||
export interface ImportPlan {
|
||||
mode: MergeMode;
|
||||
dedupe: boolean;
|
||||
segments: PlanSegment[];
|
||||
stats: {
|
||||
/** Total nodes across ALL segments — folders included. Drives the progress bar. */
|
||||
toCreate: number;
|
||||
/** Bookmarks only. Drives the "Import n bookmarks" button label. */
|
||||
bookmarkCount: number;
|
||||
/** Dropped because the URL already exists in the browser. */
|
||||
skippedExisting: number;
|
||||
/** Dropped because the URL repeats within the file. */
|
||||
skippedInFile: number;
|
||||
};
|
||||
}
|
||||
|
||||
/** Closed code set — extend `docs/02 §7` before extending this union. */
|
||||
export type BmParseErrorCode =
|
||||
| 'NOT_NETSCAPE'
|
||||
| 'NOT_BM_JSON'
|
||||
| 'MALFORMED_JSON'
|
||||
| 'INVALID_NODE'
|
||||
| 'BAD_CSV_HEADER'
|
||||
| 'CSV_ROW_MISMATCH'
|
||||
| 'UNKNOWN_FORMAT'
|
||||
| 'FILE_TOO_LARGE'
|
||||
| 'TOO_MANY_NODES'
|
||||
| 'TOO_DEEP';
|
||||
|
||||
/**
|
||||
* The only error type `core/` throws. Carries a stable machine code plus a
|
||||
* short human detail; the UI localizes by code and shows `detail` in the
|
||||
* copyable technical block (docs/02 §7).
|
||||
*/
|
||||
export class BmParseError extends Error {
|
||||
readonly code: BmParseErrorCode;
|
||||
readonly line: number | undefined;
|
||||
readonly detail: string | undefined;
|
||||
|
||||
constructor(code: BmParseErrorCode, detail?: string, line?: number) {
|
||||
super(detail === undefined ? code : `${code}: ${detail}`);
|
||||
this.name = 'BmParseError';
|
||||
this.code = code;
|
||||
this.line = line;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
/** True when the node is a folder (no url). Narrows for callers. */
|
||||
export function isFolder(node: BookmarkNode): boolean {
|
||||
return node.url === undefined;
|
||||
}
|
||||
|
||||
/** Walk a tree depth-first, parents before children, siblings in order. */
|
||||
export function* walkTree(
|
||||
nodes: readonly BookmarkNode[],
|
||||
depth = 1,
|
||||
): Generator<{ node: BookmarkNode; depth: number }> {
|
||||
for (const node of nodes) {
|
||||
yield { node, depth };
|
||||
if (node.children !== undefined) yield* walkTree(node.children, depth + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/** Count bookmarks, folders and maximum depth in one pass. */
|
||||
export function computeStats(roots: readonly BookmarkNode[]): TreeStats {
|
||||
let bookmarks = 0;
|
||||
let folders = 0;
|
||||
let maxDepth = 0;
|
||||
for (const { node, depth } of walkTree(roots)) {
|
||||
if (isFolder(node)) folders++;
|
||||
else bookmarks++;
|
||||
if (depth > maxDepth) maxDepth = depth;
|
||||
}
|
||||
return { bookmarks, folders, maxDepth };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* URL normalization — docs/05 §2.
|
||||
*
|
||||
* Purpose: produce a stable comparison KEY for dedupe and diff.
|
||||
* Inputs: a raw href exactly as it appeared in the file or browser tree.
|
||||
* Guarantees: never throws, never mutates stored data. The key is only ever
|
||||
* used for comparison — the user's URL is stored verbatim.
|
||||
*
|
||||
* Explicitly NOT done: stripping `utm_*`, stripping `www.`, unifying
|
||||
* http/https. Too opinionated for a dedupe default; see the roadmap's
|
||||
* "aggressive dedupe" toggle.
|
||||
*/
|
||||
|
||||
const DEFAULT_PORTS: Record<string, string> = {
|
||||
'http:': '80',
|
||||
'https:': '443',
|
||||
'ftp:': '21',
|
||||
'ws:': '80',
|
||||
'wss:': '443',
|
||||
};
|
||||
|
||||
/**
|
||||
* Build the comparison key for a URL.
|
||||
*
|
||||
* Unparseable input (`javascript:`, `about:`, plain junk) falls back to the
|
||||
* trimmed original, so such bookmarks still dedupe against each other exactly
|
||||
* rather than collapsing together.
|
||||
*/
|
||||
export function normalizeUrl(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(trimmed);
|
||||
} catch {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
// The URL parser already lowercases protocol and hostname.
|
||||
if (url.port !== '' && DEFAULT_PORTS[url.protocol] === url.port) url.port = '';
|
||||
|
||||
// A bare origin is the same link with or without the trailing slash.
|
||||
// Drop the slash off the serialized URL rather than rebuilding from
|
||||
// protocol+host: rebuilding silently discards userinfo, which would collapse
|
||||
// https://alice@host/ and https://bob@host/ into one key and drop one of them
|
||||
// on import.
|
||||
if (url.pathname === '/' && url.search === '' && url.hash === '') {
|
||||
return url.toString().slice(0, -1);
|
||||
}
|
||||
|
||||
// Query and fragment are kept verbatim — `?q=` and `#section` are meaningful.
|
||||
return url.toString();
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* BM JSON v1 parser — docs/04 §2.
|
||||
*
|
||||
* Purpose: read our own lossless backup/round-trip format.
|
||||
* Inputs: decoded file text.
|
||||
* Guarantees: hand-rolled structural validation (no schema library — the
|
||||
* zero-dependency rule); unknown keys are ignored for forward compatibility.
|
||||
*/
|
||||
import { MAX_DEPTH, MAX_NODES } from '../limits';
|
||||
import {
|
||||
BmParseError,
|
||||
type BookmarkNode,
|
||||
computeStats,
|
||||
type ParseResult,
|
||||
type ParseWarning,
|
||||
} from '../model';
|
||||
|
||||
export const BM_JSON_FORMAT = 'bookmarkmagic';
|
||||
export const BM_JSON_VERSION = 1;
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** Accept a finite non-negative number; anything else means "absent". */
|
||||
function optionalEpoch(value: unknown): number | undefined {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return undefined;
|
||||
return Math.round(value);
|
||||
}
|
||||
|
||||
interface ReadContext {
|
||||
count: { nodes: number };
|
||||
}
|
||||
|
||||
function readNode(raw: unknown, path: string, depth: number, ctx: ReadContext): BookmarkNode {
|
||||
if (depth > MAX_DEPTH) {
|
||||
throw new BmParseError('TOO_DEEP', `nesting deeper than ${MAX_DEPTH} levels at ${path}`);
|
||||
}
|
||||
if (!isRecord(raw)) {
|
||||
throw new BmParseError('INVALID_NODE', `${path} is not an object`);
|
||||
}
|
||||
if (typeof raw.title !== 'string') {
|
||||
throw new BmParseError('INVALID_NODE', `${path}.title must be a string`);
|
||||
}
|
||||
if (raw.url !== undefined && typeof raw.url !== 'string') {
|
||||
throw new BmParseError('INVALID_NODE', `${path}.url must be a string when present`);
|
||||
}
|
||||
|
||||
const isFolderNode = raw.url === undefined;
|
||||
if (!isFolderNode && raw.children !== undefined) {
|
||||
throw new BmParseError('INVALID_NODE', `${path} has a url and children`);
|
||||
}
|
||||
if (raw.children !== undefined && !Array.isArray(raw.children)) {
|
||||
throw new BmParseError('INVALID_NODE', `${path}.children must be an array`);
|
||||
}
|
||||
|
||||
ctx.count.nodes++;
|
||||
if (ctx.count.nodes > MAX_NODES) {
|
||||
throw new BmParseError('TOO_MANY_NODES', `more than ${MAX_NODES} nodes`);
|
||||
}
|
||||
|
||||
const addDate = optionalEpoch(raw.addDate);
|
||||
const lastModified = optionalEpoch(raw.lastModified);
|
||||
|
||||
return {
|
||||
title: raw.title,
|
||||
...(!isFolderNode && { url: raw.url as string }),
|
||||
...(addDate !== undefined && { addDate }),
|
||||
...(lastModified !== undefined && { lastModified }),
|
||||
...(raw.toolbar === true && { toolbar: true }),
|
||||
// A folder may omit `children` — that means empty, not "not a folder".
|
||||
...(isFolderNode && {
|
||||
children: ((raw.children ?? []) as unknown[]).map((child, i) =>
|
||||
readNode(child, `${path}.children[${i}]`, depth + 1, ctx),
|
||||
),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a BM JSON v1 document.
|
||||
*
|
||||
* @throws {BmParseError} `MALFORMED_JSON`, `NOT_BM_JSON`, `INVALID_NODE`,
|
||||
* `TOO_MANY_NODES` or `TOO_DEEP`.
|
||||
*/
|
||||
export function parseBmJson(text: string): ParseResult {
|
||||
let doc: unknown;
|
||||
try {
|
||||
doc = JSON.parse(text) as unknown;
|
||||
} catch (err) {
|
||||
throw new BmParseError('MALFORMED_JSON', err instanceof Error ? err.message : 'invalid JSON');
|
||||
}
|
||||
|
||||
if (!isRecord(doc) || doc.format !== BM_JSON_FORMAT) {
|
||||
throw new BmParseError('NOT_BM_JSON', `expected "format": "${BM_JSON_FORMAT}"`);
|
||||
}
|
||||
if (!Array.isArray(doc.roots)) {
|
||||
throw new BmParseError('INVALID_NODE', 'roots must be an array');
|
||||
}
|
||||
|
||||
const warnings: ParseWarning[] = [];
|
||||
if (typeof doc.version === 'number' && doc.version > BM_JSON_VERSION) {
|
||||
warnings.push({
|
||||
code: 'NEWER_VERSION',
|
||||
count: 1,
|
||||
detail: `file version ${doc.version}, this build understands ${BM_JSON_VERSION} — best effort`,
|
||||
});
|
||||
}
|
||||
|
||||
const ctx: ReadContext = { count: { nodes: 0 } };
|
||||
const roots = doc.roots.map((node, i) => readNode(node, `roots[${i}]`, 1, ctx));
|
||||
if (roots.length === 0) warnings.push({ code: 'NO_BOOKMARKS', count: 1 });
|
||||
|
||||
return { roots, stats: computeStats(roots), warnings };
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/**
|
||||
* CSV parser — docs/04 §3, docs/05 §7.
|
||||
*
|
||||
* Purpose: read the spreadsheet-friendly flattened projection back into a tree.
|
||||
* Inputs: decoded file text; a leading BOM is tolerated.
|
||||
* Guarantees: hand-rolled RFC 4180-style state machine — `""` unescaping,
|
||||
* CRLF/LF tolerance, delimiter sniffed from the header row.
|
||||
*
|
||||
* CSV is lossy by construction (docs/04 §3): no empty folders, no
|
||||
* `lastModified`, no folder `addDate`, and no `toolbar` — a parsed CSV node
|
||||
* always has `toolbar === undefined`, so the first path segment is an ordinary
|
||||
* folder title and never a root reference.
|
||||
*/
|
||||
|
||||
import { splitPath } from '../csv-path';
|
||||
import { MAX_DEPTH, MAX_NODES } from '../limits';
|
||||
import {
|
||||
BmParseError,
|
||||
type BookmarkNode,
|
||||
computeStats,
|
||||
type ParseResult,
|
||||
type ParseWarning,
|
||||
} from '../model';
|
||||
import { normalizeEpochSeconds } from '../timestamps';
|
||||
|
||||
export const CSV_COLUMNS = ['folder_path', 'title', 'url', 'add_date'] as const;
|
||||
const DELIMITERS = [',', ';'] as const;
|
||||
|
||||
/** Split CSV text into rows of fields. Quotes may contain the delimiter and newlines. */
|
||||
export function parseCsvRows(text: string, delimiter: string): string[][] {
|
||||
const rows: string[][] = [];
|
||||
let row: string[] = [];
|
||||
let field = '';
|
||||
let inQuotes = false;
|
||||
let i = 0;
|
||||
|
||||
const endField = (): void => {
|
||||
row.push(field);
|
||||
field = '';
|
||||
};
|
||||
const endRow = (): void => {
|
||||
endField();
|
||||
rows.push(row);
|
||||
row = [];
|
||||
};
|
||||
|
||||
while (i < text.length) {
|
||||
const ch = text[i] as string;
|
||||
|
||||
if (inQuotes) {
|
||||
if (ch === '"') {
|
||||
if (text[i + 1] === '"') {
|
||||
field += '"';
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
inQuotes = false;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
field += ch;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '"' && field === '') {
|
||||
inQuotes = true;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === delimiter) {
|
||||
endField();
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '\r') {
|
||||
// CRLF or a lone CR both terminate the record.
|
||||
endRow();
|
||||
i += text[i + 1] === '\n' ? 2 : 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '\n') {
|
||||
endRow();
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
field += ch;
|
||||
i++;
|
||||
}
|
||||
|
||||
// A trailing newline produces no extra record; anything else is a final row.
|
||||
if (field !== '' || row.length > 0) endRow();
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the delimiter whose header row yields exactly the expected columns,
|
||||
* or null. Shared with `detect-format.ts` so sniffing and parsing can never
|
||||
* disagree about what counts as a CSV header — note fields may be quoted, so
|
||||
* this must go through the row parser rather than match on the raw text.
|
||||
*/
|
||||
export function matchCsvHeader(headerLine: string): string | null {
|
||||
for (const candidate of DELIMITERS) {
|
||||
const [header] = parseCsvRows(headerLine, candidate);
|
||||
if (header !== undefined && header.length === CSV_COLUMNS.length) {
|
||||
const normalized = header.map((h) => h.trim().toLowerCase());
|
||||
if (CSV_COLUMNS.every((col, i) => normalized[i] === col)) return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function sniffDelimiter(headerLine: string): string {
|
||||
const delimiter = matchCsvHeader(headerLine);
|
||||
if (delimiter === null) {
|
||||
throw new BmParseError(
|
||||
'BAD_CSV_HEADER',
|
||||
`expected header "${CSV_COLUMNS.join(',')}" (or ";"-separated)`,
|
||||
1,
|
||||
);
|
||||
}
|
||||
return delimiter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a bookmark at `segments`, creating intermediate folders as needed.
|
||||
* Returns how many folders were created, so the caller can hold synthesized
|
||||
* folders against MAX_NODES too — counting only rows would let a small file
|
||||
* build an unbounded tree.
|
||||
*/
|
||||
function insertAt(roots: BookmarkNode[], segments: string[], leaf: BookmarkNode): number {
|
||||
let level = roots;
|
||||
let created = 0;
|
||||
for (const segment of segments) {
|
||||
let folder = level.find((n) => n.url === undefined && n.title === segment);
|
||||
if (folder === undefined) {
|
||||
folder = { title: segment, children: [] };
|
||||
level.push(folder);
|
||||
created++;
|
||||
}
|
||||
// SAFETY: every folder we create or match here was created with children.
|
||||
level = folder.children as BookmarkNode[];
|
||||
}
|
||||
level.push(leaf);
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a CSV export.
|
||||
*
|
||||
* @throws {BmParseError} `BAD_CSV_HEADER`, `CSV_ROW_MISMATCH`,
|
||||
* `TOO_MANY_NODES` or `TOO_DEEP`.
|
||||
*/
|
||||
export function parseCsv(text: string): ParseResult {
|
||||
const body = text.replace(/^/, '');
|
||||
const firstBreak = body.search(/\r\n|\r|\n/);
|
||||
const headerLine = firstBreak === -1 ? body : body.slice(0, firstBreak);
|
||||
const delimiter = sniffDelimiter(headerLine);
|
||||
|
||||
const rows = parseCsvRows(body, delimiter);
|
||||
const warnings: ParseWarning[] = [];
|
||||
const roots: BookmarkNode[] = [];
|
||||
let invalidDates = 0;
|
||||
let missingUrls = 0;
|
||||
/** Bookmarks plus every folder synthesized from a path — the real node count. */
|
||||
let nodes = 0;
|
||||
|
||||
for (let r = 1; r < rows.length; r++) {
|
||||
const row = rows[r] as string[];
|
||||
if (row.length === 1 && row[0] === '') continue; // blank line
|
||||
|
||||
if (row.length !== CSV_COLUMNS.length) {
|
||||
throw new BmParseError(
|
||||
'CSV_ROW_MISMATCH',
|
||||
`row has ${row.length} fields, expected ${CSV_COLUMNS.length}`,
|
||||
r + 1,
|
||||
);
|
||||
}
|
||||
|
||||
const [pathField = '', title = '', url = '', addDateField = ''] = row;
|
||||
if (url.trim() === '') {
|
||||
missingUrls++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const segments = splitPath(pathField);
|
||||
if (segments.length + 1 > MAX_DEPTH) {
|
||||
throw new BmParseError('TOO_DEEP', `nesting deeper than ${MAX_DEPTH} levels`, r + 1);
|
||||
}
|
||||
|
||||
const parsed = normalizeEpochSeconds(addDateField);
|
||||
if (parsed.invalid) invalidDates++;
|
||||
|
||||
const createdFolders = insertAt(roots, segments, {
|
||||
title: title === '' ? url : title,
|
||||
url,
|
||||
...(parsed.seconds !== undefined && { addDate: parsed.seconds }),
|
||||
});
|
||||
|
||||
nodes += 1 + createdFolders;
|
||||
if (nodes > MAX_NODES) {
|
||||
throw new BmParseError('TOO_MANY_NODES', `more than ${MAX_NODES} nodes`, r + 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (missingUrls > 0) warnings.push({ code: 'MISSING_URL', count: missingUrls });
|
||||
if (invalidDates > 0) warnings.push({ code: 'INVALID_DATE', count: invalidDates });
|
||||
if (roots.length === 0) warnings.push({ code: 'NO_BOOKMARKS', count: 1 });
|
||||
|
||||
return { roots, stats: computeStats(roots), warnings };
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* Netscape Bookmark HTML parser — docs/04 §1, docs/05 §1.
|
||||
*
|
||||
* Purpose: turn any browser's bookmark export into `BookmarkNode[]`.
|
||||
* Inputs: the decoded file text (the read layer already stripped any BOM).
|
||||
* Guarantees: never regex-parses markup; reads `textContent`/`getAttribute`
|
||||
* only, so titles are inert; throws `BmParseError` and nothing else.
|
||||
*
|
||||
* Nodes from the parsed document are NEVER adopted into the live DOM — that,
|
||||
* not DOMParser's inertness, is the load-bearing rule (docs/09 T1).
|
||||
*/
|
||||
import { MAX_DEPTH, MAX_NODES } from '../limits';
|
||||
import {
|
||||
BmParseError,
|
||||
type BookmarkNode,
|
||||
computeStats,
|
||||
type ParseResult,
|
||||
type ParseWarning,
|
||||
type ParseWarningCode,
|
||||
} from '../model';
|
||||
import { normalizeEpochSeconds } from '../timestamps';
|
||||
|
||||
const DOCTYPE_PROBE_BYTES = 512;
|
||||
const DOCTYPE_MARKER = /NETSCAPE-Bookmark-file-1/i;
|
||||
|
||||
class WarningBag {
|
||||
private readonly counts = new Map<ParseWarningCode, number>();
|
||||
|
||||
/** A zero increment is a no-op — never emit a warning with count 0. */
|
||||
add(code: ParseWarningCode, times = 1): void {
|
||||
if (times <= 0) return;
|
||||
this.counts.set(code, (this.counts.get(code) ?? 0) + times);
|
||||
}
|
||||
|
||||
toArray(): ParseWarning[] {
|
||||
return [...this.counts].map(([code, count]) => ({ code, count }));
|
||||
}
|
||||
}
|
||||
|
||||
const tagOf = (el: Element): string => el.tagName.toLowerCase();
|
||||
|
||||
/**
|
||||
* Locate a folder's child list. Three places, in order (docs/05 §1):
|
||||
* 1. inside the `<DT>` — the normal case, because the HTML parser nests it
|
||||
* there whenever the file omits `</DT>`, which every browser does;
|
||||
* 2. inside or after a `<DD>` sibling — a `<DD>` closes the `<DT>` and then
|
||||
* swallows the following `<DL>`; missing this loses the whole subtree;
|
||||
* 3. the `<DT>`'s next-sibling `<DL>` — only reachable when the file emits an
|
||||
* explicit `</DT>`, which some third-party exporters do.
|
||||
*/
|
||||
function nextDlFor(dt: Element): Element | null {
|
||||
const inside = dt.querySelector(':scope > dl');
|
||||
if (inside !== null) return inside;
|
||||
|
||||
let sibling = dt.nextElementSibling;
|
||||
while (sibling !== null) {
|
||||
const tag = tagOf(sibling);
|
||||
if (tag === 'dl') return sibling;
|
||||
if (tag === 'dd') {
|
||||
const nested = sibling.querySelector(':scope > dl');
|
||||
if (nested !== null) return nested;
|
||||
sibling = sibling.nextElementSibling;
|
||||
continue;
|
||||
}
|
||||
if (tag === 'dt') return null; // next entry started — this folder is empty
|
||||
sibling = sibling.nextElementSibling;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readDates(
|
||||
el: Element,
|
||||
warnings: WarningBag,
|
||||
): Pick<BookmarkNode, 'addDate' | 'lastModified'> {
|
||||
const add = normalizeEpochSeconds(el.getAttribute('add_date'));
|
||||
const mod = normalizeEpochSeconds(el.getAttribute('last_modified'));
|
||||
if (add.invalid) warnings.add('INVALID_DATE');
|
||||
if (mod.invalid) warnings.add('INVALID_DATE');
|
||||
return {
|
||||
...(add.seconds !== undefined && { addDate: add.seconds }),
|
||||
...(mod.seconds !== undefined && { lastModified: mod.seconds }),
|
||||
};
|
||||
}
|
||||
|
||||
function countFavicons(el: Element): number {
|
||||
let n = 0;
|
||||
if (el.hasAttribute('icon')) n++;
|
||||
if (el.hasAttribute('icon_uri')) n++;
|
||||
return n > 0 ? 1 : 0;
|
||||
}
|
||||
|
||||
interface WalkContext {
|
||||
warnings: WarningBag;
|
||||
count: { nodes: number };
|
||||
}
|
||||
|
||||
function walkDl(dl: Element, depth: number, ctx: WalkContext): BookmarkNode[] {
|
||||
if (depth > MAX_DEPTH) {
|
||||
throw new BmParseError('TOO_DEEP', `nesting deeper than ${MAX_DEPTH} levels`);
|
||||
}
|
||||
|
||||
const out: BookmarkNode[] = [];
|
||||
for (const child of dl.children) {
|
||||
const tag = tagOf(child);
|
||||
// <HR> separators (Firefox) are skipped silently — docs/04 §1.2. Note the
|
||||
// HTML parser usually nests them inside the preceding <DT> rather than
|
||||
// leaving them here, since only dt/dd closes a dt; either way they are
|
||||
// never read as an entry.
|
||||
if (tag === 'hr') continue;
|
||||
if (tag === 'dd') {
|
||||
ctx.warnings.add('DESCRIPTIONS_DROPPED');
|
||||
continue;
|
||||
}
|
||||
if (tag !== 'dt') continue;
|
||||
|
||||
const node = readEntry(child, depth, ctx);
|
||||
if (node === null) continue;
|
||||
countNode(ctx);
|
||||
out.push(node);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function countNode(ctx: WalkContext): void {
|
||||
ctx.count.nodes++;
|
||||
if (ctx.count.nodes > MAX_NODES) {
|
||||
throw new BmParseError('TOO_MANY_NODES', `more than ${MAX_NODES} nodes`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect the top-level entries.
|
||||
*
|
||||
* Normally that is the single wrapper `<DL>` under `<body>`. But Safari has
|
||||
* been reported to emit top-level `<DT><H3>` folders with NO outer `<DL>`
|
||||
* (Mozilla bug 801450), and real files can mix both — one wrapped root list
|
||||
* plus loose `<DT>`s after it. Taking "the first outermost `<DL>`" silently
|
||||
* drops everything outside it, so walk `<body>` in document order instead and
|
||||
* accept both kinds of entry point.
|
||||
*
|
||||
* The `consumed` pass matters: when a file emits an explicit `</DT>`, a
|
||||
* folder's child `<DL>` also lands at body level, and emitting it again as a
|
||||
* root list would duplicate the whole subtree.
|
||||
*/
|
||||
function collectRoots(body: Element, ctx: WalkContext): BookmarkNode[] {
|
||||
const children = [...body.children];
|
||||
|
||||
const consumed = new Set<Element>();
|
||||
for (const el of children) {
|
||||
if (tagOf(el) !== 'dt') continue;
|
||||
const childList = nextDlFor(el);
|
||||
if (childList !== null) consumed.add(childList);
|
||||
}
|
||||
|
||||
const roots: BookmarkNode[] = [];
|
||||
for (const el of children) {
|
||||
const tag = tagOf(el);
|
||||
if (tag === 'dt') {
|
||||
const node = readEntry(el, 1, ctx);
|
||||
if (node === null) continue;
|
||||
countNode(ctx);
|
||||
roots.push(node);
|
||||
} else if (tag === 'dl' && !consumed.has(el)) {
|
||||
roots.push(...walkDl(el, 1, ctx));
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
function readEntry(dt: Element, depth: number, ctx: WalkContext): BookmarkNode | null {
|
||||
const h3 = dt.querySelector(':scope > h3');
|
||||
if (h3 !== null) {
|
||||
ctx.warnings.add('FAVICONS_IGNORED', countFavicons(h3));
|
||||
const childDl = nextDlFor(dt);
|
||||
return {
|
||||
title: h3.textContent ?? '',
|
||||
...readDates(h3, ctx.warnings),
|
||||
...(h3.hasAttribute('personal_toolbar_folder') && { toolbar: true }),
|
||||
children: childDl === null ? [] : walkDl(childDl, depth + 1, ctx),
|
||||
};
|
||||
}
|
||||
|
||||
const a = dt.querySelector(':scope > a');
|
||||
if (a === null) return null;
|
||||
|
||||
const href = a.getAttribute('href');
|
||||
if (href === null || href.trim() === '') {
|
||||
ctx.warnings.add('MISSING_URL');
|
||||
return null;
|
||||
}
|
||||
|
||||
ctx.warnings.add('FAVICONS_IGNORED', countFavicons(a));
|
||||
const title = a.textContent ?? '';
|
||||
if (title.trim() === '') ctx.warnings.add('EMPTY_TITLE');
|
||||
return {
|
||||
title: title === '' ? href : title,
|
||||
url: href,
|
||||
...readDates(a, ctx.warnings),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse Netscape bookmark HTML.
|
||||
*
|
||||
* @throws {BmParseError} `NOT_NETSCAPE` when neither the doctype nor any `<DL>`
|
||||
* is present; `TOO_MANY_NODES` / `TOO_DEEP` when a cap is exceeded.
|
||||
*/
|
||||
export function parseNetscapeHtml(text: string): ParseResult {
|
||||
const hasDoctype = DOCTYPE_MARKER.test(text.slice(0, DOCTYPE_PROBE_BYTES));
|
||||
const doc = new DOMParser().parseFromString(text, 'text/html');
|
||||
const body = doc.body;
|
||||
|
||||
const hasEntries =
|
||||
body !== null &&
|
||||
(doc.querySelector('dl') !== null || [...body.children].some((el) => tagOf(el) === 'dt'));
|
||||
|
||||
if (!hasEntries && !hasDoctype) {
|
||||
throw new BmParseError('NOT_NETSCAPE', 'no NETSCAPE doctype and no <DL> found');
|
||||
}
|
||||
|
||||
const warnings = new WarningBag();
|
||||
const roots =
|
||||
body === null || !hasEntries ? [] : collectRoots(body, { warnings, count: { nodes: 0 } });
|
||||
|
||||
if (roots.length === 0) warnings.add('NO_BOOKMARKS');
|
||||
return { roots, stats: computeStats(roots), warnings: warnings.toArray() };
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* BM JSON v1 serializer — docs/04 §2.
|
||||
*
|
||||
* Purpose: our lossless round-trip format, and the forced safety backup taken
|
||||
* before a Replace import.
|
||||
* Inputs: a tree plus the generator version and an export timestamp.
|
||||
* Guarantees: field order is stable so diffs between two backups stay small.
|
||||
*/
|
||||
import { type BookmarkNode, isFolder } from '../model';
|
||||
import { BM_JSON_FORMAT, BM_JSON_VERSION } from '../parse/bm-json';
|
||||
|
||||
export interface BmJsonOptions {
|
||||
/** App version, e.g. "1.0.0" — becomes `generator`. */
|
||||
version: string;
|
||||
/** ISO 8601 instant. Passed in so this module stays free of ambient time. */
|
||||
exportedAt: string;
|
||||
}
|
||||
|
||||
function toJsonNode(node: BookmarkNode): Record<string, unknown> {
|
||||
return {
|
||||
title: node.title,
|
||||
...(node.url !== undefined && { url: node.url }),
|
||||
...(node.toolbar === true && { toolbar: true }),
|
||||
...(node.addDate !== undefined && { addDate: node.addDate }),
|
||||
...(node.lastModified !== undefined && { lastModified: node.lastModified }),
|
||||
...(isFolder(node) && { children: (node.children ?? []).map(toJsonNode) }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Serialize a tree to BM JSON v1 (2-space indented, trailing newline). */
|
||||
export function serializeBmJson(roots: readonly BookmarkNode[], options: BmJsonOptions): string {
|
||||
const doc = {
|
||||
format: BM_JSON_FORMAT,
|
||||
version: BM_JSON_VERSION,
|
||||
generator: `BookmarkMagic ${options.version}`,
|
||||
exportedAt: options.exportedAt,
|
||||
roots: roots.map(toJsonNode),
|
||||
};
|
||||
return `${JSON.stringify(doc, null, 2)}\n`;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* CSV serializer — docs/04 §3.
|
||||
*
|
||||
* Purpose: a spreadsheet-friendly flattened projection of the tree.
|
||||
* Inputs: a tree, plus the delimiter chosen in Settings.
|
||||
* Guarantees: RFC 4180-style quoting, CRLF records, and a UTF-8 BOM so Excel
|
||||
* detects the encoding on double-click.
|
||||
*
|
||||
* Deviations from RFC 4180 are deliberate and documented (docs/04 §3): the
|
||||
* header row is required, `;` is offered as a delimiter for locales whose
|
||||
* Excel list separator is not a comma, and the BOM is an Excel accommodation.
|
||||
*/
|
||||
import { joinPath } from '../csv-path';
|
||||
import { type BookmarkNode, isFolder } from '../model';
|
||||
import { CSV_COLUMNS } from '../parse/csv';
|
||||
|
||||
export const CSV_BOM = '';
|
||||
const CRLF = '\r\n';
|
||||
|
||||
export type CsvDelimiter = ',' | ';';
|
||||
|
||||
export interface CsvOptions {
|
||||
delimiter?: CsvDelimiter;
|
||||
/** Excel wants the BOM; other consumers may not. Default true (docs/04 §3). */
|
||||
bom?: boolean;
|
||||
}
|
||||
|
||||
/** Quote when the field contains the delimiter, a quote, CR or LF. */
|
||||
function quote(value: string, delimiter: string): string {
|
||||
const needsQuotes =
|
||||
value.includes(delimiter) ||
|
||||
value.includes('"') ||
|
||||
value.includes('\r') ||
|
||||
value.includes('\n');
|
||||
if (!needsQuotes) return value;
|
||||
return `"${value.replace(/"/g, '""')}"`;
|
||||
}
|
||||
|
||||
function collectRows(nodes: readonly BookmarkNode[], trail: string[], rows: string[][]): void {
|
||||
for (const node of nodes) {
|
||||
if (isFolder(node)) {
|
||||
// Empty folders produce no row and are therefore lost — docs/04 §3.
|
||||
collectRows(node.children ?? [], [...trail, node.title], rows);
|
||||
continue;
|
||||
}
|
||||
rows.push([
|
||||
joinPath(trail),
|
||||
node.title,
|
||||
node.url as string,
|
||||
node.addDate === undefined ? '' : String(node.addDate),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Serialize a tree to CSV. */
|
||||
export function serializeCsv(roots: readonly BookmarkNode[], options: CsvOptions = {}): string {
|
||||
const delimiter = options.delimiter ?? ',';
|
||||
const rows: string[][] = [];
|
||||
collectRows(roots, [], rows);
|
||||
|
||||
const lines = [
|
||||
CSV_COLUMNS.join(delimiter),
|
||||
...rows.map((row) => row.map((field) => quote(field, delimiter)).join(delimiter)),
|
||||
];
|
||||
|
||||
const prefix = options.bom === false ? '' : CSV_BOM;
|
||||
return `${prefix}${lines.join(CRLF)}${CRLF}`;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* Markdown serializer — docs/04 §4. Export only; there is no Markdown parser.
|
||||
*
|
||||
* Purpose: a human-readable share format (blog posts, Discord, README).
|
||||
* Inputs: a tree, a heading date, and a style.
|
||||
* Guarantees: `[ ] ( )` escaped in titles; URLs containing `)` or whitespace
|
||||
* are angle-bracket wrapped so the link target survives.
|
||||
*/
|
||||
import { type BookmarkNode, isFolder } from '../model';
|
||||
|
||||
export type MarkdownStyle = 'nested' | 'flat';
|
||||
|
||||
export interface MarkdownOptions {
|
||||
/** Rendered into the H1, e.g. "2026-07-25". Passed in — no ambient time. */
|
||||
date: string;
|
||||
style?: MarkdownStyle;
|
||||
}
|
||||
|
||||
/** Escape the characters that would otherwise form link syntax. */
|
||||
export function escapeMarkdown(value: string): string {
|
||||
return value.replace(/([\\[\]()])/g, '\\$1');
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a URL in angle brackets when it contains characters that break `(...)`.
|
||||
*
|
||||
* Inside `<...>` CommonMark forbids `<`, `>` and line endings, so those must be
|
||||
* percent-encoded or the whole link renders as literal text.
|
||||
*/
|
||||
export function formatUrl(url: string): string {
|
||||
if (!/[\s()<>]/.test(url)) return url;
|
||||
const safe = url
|
||||
.replace(/</g, '%3C')
|
||||
.replace(/>/g, '%3E')
|
||||
.replace(/\r/g, '%0D')
|
||||
.replace(/\n/g, '%0A');
|
||||
return `<${safe}>`;
|
||||
}
|
||||
|
||||
function link(node: BookmarkNode): string {
|
||||
return `[${escapeMarkdown(node.title)}](${formatUrl(node.url as string)})`;
|
||||
}
|
||||
|
||||
function writeNested(nodes: readonly BookmarkNode[], depth: number, out: string[]): void {
|
||||
const pad = ' '.repeat(depth);
|
||||
for (const node of nodes) {
|
||||
if (isFolder(node)) {
|
||||
out.push(`${pad}- **${escapeMarkdown(node.title)}**`);
|
||||
writeNested(node.children ?? [], depth + 1, out);
|
||||
} else {
|
||||
out.push(`${pad}- ${link(node)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Collect every bookmark at or below a node, depth-first. */
|
||||
function flatten(nodes: readonly BookmarkNode[], into: BookmarkNode[]): void {
|
||||
for (const node of nodes) {
|
||||
if (isFolder(node)) flatten(node.children ?? [], into);
|
||||
else into.push(node);
|
||||
}
|
||||
}
|
||||
|
||||
function writeFlat(roots: readonly BookmarkNode[], out: string[]): void {
|
||||
const loose: BookmarkNode[] = [];
|
||||
for (const node of roots) if (!isFolder(node)) loose.push(node);
|
||||
for (const node of loose) out.push(`- ${link(node)}`);
|
||||
if (loose.length > 0) out.push('');
|
||||
|
||||
for (const node of roots) {
|
||||
if (!isFolder(node)) continue;
|
||||
const bookmarks: BookmarkNode[] = [];
|
||||
flatten(node.children ?? [], bookmarks);
|
||||
out.push(`## ${escapeMarkdown(node.title)}`, '');
|
||||
for (const bookmark of bookmarks) out.push(`- ${link(bookmark)}`);
|
||||
out.push('');
|
||||
}
|
||||
}
|
||||
|
||||
/** Serialize a tree to Markdown. */
|
||||
export function serializeMarkdown(
|
||||
roots: readonly BookmarkNode[],
|
||||
options: MarkdownOptions,
|
||||
): string {
|
||||
const out: string[] = [`# Bookmarks — ${options.date}`, ''];
|
||||
if ((options.style ?? 'nested') === 'flat') writeFlat(roots, out);
|
||||
else writeNested(roots, 0, out);
|
||||
return `${out.join('\n').replace(/\n+$/, '')}\n`;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Netscape Bookmark HTML serializer — docs/04 §1.1.
|
||||
*
|
||||
* Purpose: emit the interchange format every major browser reads.
|
||||
* Inputs: a `BookmarkNode[]` tree.
|
||||
* Guarantees: 4-space indent per depth (matches Chrome); attributes only when
|
||||
* values exist; `& < > "` escaped in titles and hrefs.
|
||||
*
|
||||
* `LAST_MODIFIED` is emitted on `<H3>` only, never on `<A>` — that is what
|
||||
* Chrome does, and it is why the round-trip suite projects `lastModified` away
|
||||
* for bookmarks (docs/11 §3).
|
||||
*/
|
||||
import { type BookmarkNode, isFolder } from '../model';
|
||||
|
||||
const HEADER = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<!-- This is an automatically generated file. It will be read and overwritten. DO NOT EDIT! -->
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks</H1>
|
||||
`;
|
||||
|
||||
/**
|
||||
* Escape the four characters that can break out of text or an attribute value,
|
||||
* plus CR.
|
||||
*
|
||||
* CR is not a markup hazard — it is a round-trip hazard. The HTML tokenizer
|
||||
* normalizes CR and CRLF to LF during input-stream preprocessing, so a title
|
||||
* containing `\r` would come back as `\n`. A numeric reference survives,
|
||||
* because character references are decoded *after* that normalization.
|
||||
* `\r` reaches us from BM JSON and from quoted CSV fields, so this is
|
||||
* reachable in production, not theoretical.
|
||||
*/
|
||||
export function escapeHtml(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/\r/g, ' ');
|
||||
}
|
||||
|
||||
function attr(name: string, value: number | undefined): string {
|
||||
return value === undefined ? '' : ` ${name}="${value}"`;
|
||||
}
|
||||
|
||||
function indent(depth: number): string {
|
||||
return ' '.repeat(depth);
|
||||
}
|
||||
|
||||
function writeNode(node: BookmarkNode, depth: number, out: string[]): void {
|
||||
const pad = indent(depth);
|
||||
if (isFolder(node)) {
|
||||
const toolbar = node.toolbar === true ? ' PERSONAL_TOOLBAR_FOLDER="true"' : '';
|
||||
out.push(
|
||||
`${pad}<DT><H3${attr('ADD_DATE', node.addDate)}${attr('LAST_MODIFIED', node.lastModified)}${toolbar}>${escapeHtml(node.title)}</H3>`,
|
||||
);
|
||||
out.push(`${pad}<DL><p>`);
|
||||
for (const child of node.children ?? []) writeNode(child, depth + 1, out);
|
||||
out.push(`${pad}</DL><p>`);
|
||||
return;
|
||||
}
|
||||
|
||||
// SAFETY: isFolder() is false, so url is defined by the model's invariant.
|
||||
const url = node.url as string;
|
||||
out.push(
|
||||
`${pad}<DT><A HREF="${escapeHtml(url)}"${attr('ADD_DATE', node.addDate)}>${escapeHtml(node.title)}</A>`,
|
||||
);
|
||||
}
|
||||
|
||||
/** Serialize a tree to Netscape bookmark HTML (UTF-8, LF line endings). */
|
||||
export function serializeNetscapeHtml(roots: readonly BookmarkNode[]): string {
|
||||
const out: string[] = ['<DL><p>'];
|
||||
for (const node of roots) writeNode(node, 1, out);
|
||||
out.push('</DL><p>');
|
||||
return `${HEADER}${out.join('\n')}\n`;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Epoch normalization — docs/05 §4.
|
||||
*
|
||||
* Purpose: turn the inconsistent epoch values found in bookmark files into
|
||||
* integer SECONDS, or into "absent" when the value carries no information.
|
||||
* Inputs: a raw attribute value (string from an attribute, or a number).
|
||||
* Guarantees: never throws; returns `undefined` for anything it cannot trust.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Bucket boundaries. Each is exactly 1000x the previous, so they are
|
||||
* non-overlapping and describe the same instants in different units:
|
||||
* 1e11 s = 1e14 ms = 1e17 us = 5138-11-16.
|
||||
*/
|
||||
const MS_FLOOR = 1e11;
|
||||
const US_FLOOR = 1e14;
|
||||
const US_CEIL = 1e17;
|
||||
|
||||
export interface TimestampResult {
|
||||
/** Integer epoch seconds, or undefined when absent/unusable. */
|
||||
seconds: number | undefined;
|
||||
/**
|
||||
* True only when the value was present but unusable — the caller raises an
|
||||
* INVALID_DATE warning. A missing attribute, or an explicit 0, is silent.
|
||||
*/
|
||||
invalid: boolean;
|
||||
}
|
||||
|
||||
const ABSENT: TimestampResult = { seconds: undefined, invalid: false };
|
||||
const INVALID: TimestampResult = { seconds: undefined, invalid: true };
|
||||
|
||||
/**
|
||||
* Normalize one epoch value to seconds.
|
||||
*
|
||||
* Two deliberate choices (docs/05 §4):
|
||||
* - The seconds floor is 1, not 1e8. Chrome's own importer accepts any
|
||||
* 0 < t < 2^32, so a higher floor would drop 1970-1973 dates that Chrome
|
||||
* imports fine.
|
||||
* - `0` is silent, not a warning. Chrome writes ADD_DATE="0" for undated
|
||||
* nodes, so warning on it would flood the warning list on normal exports.
|
||||
*/
|
||||
export function normalizeEpochSeconds(raw: string | number | null | undefined): TimestampResult {
|
||||
if (raw === null || raw === undefined) return ABSENT;
|
||||
if (typeof raw === 'string' && raw.trim() === '') return ABSENT;
|
||||
|
||||
const value = typeof raw === 'number' ? raw : Number(raw);
|
||||
if (!Number.isFinite(value)) return INVALID;
|
||||
if (value === 0) return ABSENT;
|
||||
if (value < 0) return INVALID;
|
||||
|
||||
if (value < MS_FLOOR) return { seconds: Math.round(value), invalid: false };
|
||||
if (value < US_FLOOR) return { seconds: Math.round(value / 1e3), invalid: false };
|
||||
if (value < US_CEIL) return { seconds: Math.round(value / 1e6), invalid: false };
|
||||
return INVALID;
|
||||
}
|
||||
|
||||
/**
|
||||
* Milliseconds (what `chrome.bookmarks` returns) to our seconds. This is the
|
||||
* ADAPTER conversion and is deliberately separate from the magnitude detection
|
||||
* above, which is for FILE input only — docs/05 §4.
|
||||
*/
|
||||
export function millisToSeconds(millis: number | undefined): number | undefined {
|
||||
if (millis === undefined || !Number.isFinite(millis) || millis <= 0) return undefined;
|
||||
return Math.round(millis / 1e3);
|
||||
}
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"format": "bookmarkmagic",
|
||||
"version": 1,
|
||||
"generator": "BookmarkMagic 0.1.0",
|
||||
"exportedAt": "2026-07-25T00:00:00Z",
|
||||
"roots": [
|
||||
{
|
||||
"title": "Bookmarks bar",
|
||||
"toolbar": true,
|
||||
"addDate": 1700000000,
|
||||
"lastModified": 1751500000,
|
||||
"children": [
|
||||
{ "title": "Example", "url": "https://example.com/", "addDate": 1700000001 },
|
||||
{
|
||||
"title": "Dev",
|
||||
"addDate": 1700000002,
|
||||
"children": [{ "title": "GitHub", "url": "https://github.com/", "addDate": 1700000003 }]
|
||||
},
|
||||
{ "title": "Empty", "children": [] }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<!-- This is an automatically generated file.
|
||||
It will be read and overwritten.
|
||||
DO NOT EDIT! -->
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><H3 ADD_DATE="1700000000" LAST_MODIFIED="1751500000" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://www.google.com/" ADD_DATE="1700000001">Google</A>
|
||||
<DT><H3 ADD_DATE="1700000002" LAST_MODIFIED="1751500001">Dev</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://github.com/" ADD_DATE="1700000003" ICON="data:image/png;base64,iVBORw0KGgo=">GitHub</A>
|
||||
<DT><A HREF="https://developer.mozilla.org/en-US/" ADD_DATE="1700000004">MDN Web Docs</A>
|
||||
</DL><p>
|
||||
<DT><H3 ADD_DATE="1700000005">Empty folder</H3>
|
||||
<DL><p></DL><p>
|
||||
</DL><p>
|
||||
<DT><H3 ADD_DATE="1700000006" LAST_MODIFIED="1751500002">Other bookmarks</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://example.com/?q=a&b=1#frag" ADD_DATE="0">Example & friends</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
folder_path,title,url,add_date
|
||||
"Bookmarks bar/Dev tools","GitHub","https://github.com/","1751500000"
|
||||
"","Example","https://example.com/","1751500001"
|
||||
"Escaped\/slash","Odd folder","https://odd.example/",""
|
||||
|
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
folder_path;title;url;add_date
|
||||
"Bookmarks bar";"Semi";"https://semi.example/";"1751500002"
|
||||
|
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><H3 ADD_DATE="1700100000" LAST_MODIFIED="1751600000" PERSONAL_TOOLBAR_FOLDER="true">Favorites bar</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://www.bing.com/" ADD_DATE="1700100001">Bing</A>
|
||||
<DT><A HREF="file:///C:/Users/Public/notes.txt" ADD_DATE="1700100002">Local notes</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<!-- This is an automatically generated file.
|
||||
It will be read and overwritten.
|
||||
DO NOT EDIT! -->
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1 LAST_MODIFIED="1751700000">Bookmarks Menu</H1>
|
||||
<DL><p>
|
||||
<DT><H3 ADD_DATE="1700200000" LAST_MODIFIED="1751700001" PERSONAL_TOOLBAR_FOLDER="true" UNFILED_BOOKMARKS_FOLDER="false">Bookmarks Toolbar</H3>
|
||||
<DD>Add bookmarks to this folder to see them displayed on the Bookmarks Toolbar
|
||||
<DL><p>
|
||||
<DT><A HREF="https://www.mozilla.org/" ADD_DATE="1700200001" LAST_MODIFIED="1751700002" SHORTCUTURL="moz" TAGS="browser,foss" ICON_URI="https://www.mozilla.org/favicon.ico" LAST_CHARSET="UTF-8">Mozilla</A>
|
||||
<HR>
|
||||
<DT><A HREF="https://support.mozilla.org/" ADD_DATE="1700200003">Support</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks</H1>
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A HREF="javascript:alert(1)" ADD_DATE="1700000000">Bookmarklet</A>
|
||||
<DT><A HREF="data:text/html,<h1>hi</h1>" ADD_DATE="1700000001">Data URL</A>
|
||||
<DT><A HREF="https://safe.example/" ADD_DATE="1700000002">Safe</A>
|
||||
</DL><p>
|
||||
+1
@@ -0,0 +1 @@
|
||||
<html><body><h1>Not bookmarks</h1><p>Just a page.</p></body></html>
|
||||
@@ -0,0 +1,9 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://evil.example/" ADD_DATE="1700000000" onerror="globalThis.__pwned=1"><img src=x onerror=alert(1)></A>
|
||||
<script>globalThis.__pwned = 1;</script>
|
||||
<DT><H3 onclick="globalThis.__pwned=1"><script>alert(2)</script></H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://ok.example/">Still parsed</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><H3 ADD_DATE="1700000000">Half a folder</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://example.com/" ADD_DATE="1700000001">Example</A>
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<Title>Bookmarks</Title>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><H3 FOLDED>Favorites</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://www.apple.com/">Apple</A>
|
||||
<DT><A HREF="https://www.icloud.com/">iCloud</A>
|
||||
</DL><p>
|
||||
<DT><H3 FOLDED>Reading List</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://webkit.org/blog/">WebKit Blog</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><H3 ADD_DATE="1700300000" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://vivaldi.com/" ADD_DATE="1700300001">Vivaldi</A>
|
||||
<DT><H3 ADD_DATE="1700300002">Speed Dial</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://forum.vivaldi.net/" ADD_DATE="1700300003">Forum</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
+302
@@ -0,0 +1,302 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p><DT><H3>level 0</H3>
|
||||
<DL><p><DT><H3>level 1</H3>
|
||||
<DL><p><DT><H3>level 2</H3>
|
||||
<DL><p><DT><H3>level 3</H3>
|
||||
<DL><p><DT><H3>level 4</H3>
|
||||
<DL><p><DT><H3>level 5</H3>
|
||||
<DL><p><DT><H3>level 6</H3>
|
||||
<DL><p><DT><H3>level 7</H3>
|
||||
<DL><p><DT><H3>level 8</H3>
|
||||
<DL><p><DT><H3>level 9</H3>
|
||||
<DL><p><DT><H3>level 10</H3>
|
||||
<DL><p><DT><H3>level 11</H3>
|
||||
<DL><p><DT><H3>level 12</H3>
|
||||
<DL><p><DT><H3>level 13</H3>
|
||||
<DL><p><DT><H3>level 14</H3>
|
||||
<DL><p><DT><H3>level 15</H3>
|
||||
<DL><p><DT><H3>level 16</H3>
|
||||
<DL><p><DT><H3>level 17</H3>
|
||||
<DL><p><DT><H3>level 18</H3>
|
||||
<DL><p><DT><H3>level 19</H3>
|
||||
<DL><p><DT><H3>level 20</H3>
|
||||
<DL><p><DT><H3>level 21</H3>
|
||||
<DL><p><DT><H3>level 22</H3>
|
||||
<DL><p><DT><H3>level 23</H3>
|
||||
<DL><p><DT><H3>level 24</H3>
|
||||
<DL><p><DT><H3>level 25</H3>
|
||||
<DL><p><DT><H3>level 26</H3>
|
||||
<DL><p><DT><H3>level 27</H3>
|
||||
<DL><p><DT><H3>level 28</H3>
|
||||
<DL><p><DT><H3>level 29</H3>
|
||||
<DL><p><DT><H3>level 30</H3>
|
||||
<DL><p><DT><H3>level 31</H3>
|
||||
<DL><p><DT><H3>level 32</H3>
|
||||
<DL><p><DT><H3>level 33</H3>
|
||||
<DL><p><DT><H3>level 34</H3>
|
||||
<DL><p><DT><H3>level 35</H3>
|
||||
<DL><p><DT><H3>level 36</H3>
|
||||
<DL><p><DT><H3>level 37</H3>
|
||||
<DL><p><DT><H3>level 38</H3>
|
||||
<DL><p><DT><H3>level 39</H3>
|
||||
<DL><p><DT><H3>level 40</H3>
|
||||
<DL><p><DT><H3>level 41</H3>
|
||||
<DL><p><DT><H3>level 42</H3>
|
||||
<DL><p><DT><H3>level 43</H3>
|
||||
<DL><p><DT><H3>level 44</H3>
|
||||
<DL><p><DT><H3>level 45</H3>
|
||||
<DL><p><DT><H3>level 46</H3>
|
||||
<DL><p><DT><H3>level 47</H3>
|
||||
<DL><p><DT><H3>level 48</H3>
|
||||
<DL><p><DT><H3>level 49</H3>
|
||||
<DL><p><DT><H3>level 50</H3>
|
||||
<DL><p><DT><H3>level 51</H3>
|
||||
<DL><p><DT><H3>level 52</H3>
|
||||
<DL><p><DT><H3>level 53</H3>
|
||||
<DL><p><DT><H3>level 54</H3>
|
||||
<DL><p><DT><H3>level 55</H3>
|
||||
<DL><p><DT><H3>level 56</H3>
|
||||
<DL><p><DT><H3>level 57</H3>
|
||||
<DL><p><DT><H3>level 58</H3>
|
||||
<DL><p><DT><H3>level 59</H3>
|
||||
<DL><p><DT><H3>level 60</H3>
|
||||
<DL><p><DT><H3>level 61</H3>
|
||||
<DL><p><DT><H3>level 62</H3>
|
||||
<DL><p><DT><H3>level 63</H3>
|
||||
<DL><p><DT><H3>level 64</H3>
|
||||
<DL><p><DT><H3>level 65</H3>
|
||||
<DL><p><DT><H3>level 66</H3>
|
||||
<DL><p><DT><H3>level 67</H3>
|
||||
<DL><p><DT><H3>level 68</H3>
|
||||
<DL><p><DT><H3>level 69</H3>
|
||||
<DL><p><DT><H3>level 70</H3>
|
||||
<DL><p><DT><H3>level 71</H3>
|
||||
<DL><p><DT><H3>level 72</H3>
|
||||
<DL><p><DT><H3>level 73</H3>
|
||||
<DL><p><DT><H3>level 74</H3>
|
||||
<DL><p><DT><H3>level 75</H3>
|
||||
<DL><p><DT><H3>level 76</H3>
|
||||
<DL><p><DT><H3>level 77</H3>
|
||||
<DL><p><DT><H3>level 78</H3>
|
||||
<DL><p><DT><H3>level 79</H3>
|
||||
<DL><p><DT><H3>level 80</H3>
|
||||
<DL><p><DT><H3>level 81</H3>
|
||||
<DL><p><DT><H3>level 82</H3>
|
||||
<DL><p><DT><H3>level 83</H3>
|
||||
<DL><p><DT><H3>level 84</H3>
|
||||
<DL><p><DT><H3>level 85</H3>
|
||||
<DL><p><DT><H3>level 86</H3>
|
||||
<DL><p><DT><H3>level 87</H3>
|
||||
<DL><p><DT><H3>level 88</H3>
|
||||
<DL><p><DT><H3>level 89</H3>
|
||||
<DL><p><DT><H3>level 90</H3>
|
||||
<DL><p><DT><H3>level 91</H3>
|
||||
<DL><p><DT><H3>level 92</H3>
|
||||
<DL><p><DT><H3>level 93</H3>
|
||||
<DL><p><DT><H3>level 94</H3>
|
||||
<DL><p><DT><H3>level 95</H3>
|
||||
<DL><p><DT><H3>level 96</H3>
|
||||
<DL><p><DT><H3>level 97</H3>
|
||||
<DL><p><DT><H3>level 98</H3>
|
||||
<DL><p><DT><H3>level 99</H3>
|
||||
<DL><p><DT><H3>level 100</H3>
|
||||
<DL><p><DT><H3>level 101</H3>
|
||||
<DL><p><DT><H3>level 102</H3>
|
||||
<DL><p><DT><H3>level 103</H3>
|
||||
<DL><p><DT><H3>level 104</H3>
|
||||
<DL><p><DT><H3>level 105</H3>
|
||||
<DL><p><DT><H3>level 106</H3>
|
||||
<DL><p><DT><H3>level 107</H3>
|
||||
<DL><p><DT><H3>level 108</H3>
|
||||
<DL><p><DT><H3>level 109</H3>
|
||||
<DL><p><DT><H3>level 110</H3>
|
||||
<DL><p><DT><H3>level 111</H3>
|
||||
<DL><p><DT><H3>level 112</H3>
|
||||
<DL><p><DT><H3>level 113</H3>
|
||||
<DL><p><DT><H3>level 114</H3>
|
||||
<DL><p><DT><H3>level 115</H3>
|
||||
<DL><p><DT><H3>level 116</H3>
|
||||
<DL><p><DT><H3>level 117</H3>
|
||||
<DL><p><DT><H3>level 118</H3>
|
||||
<DL><p><DT><H3>level 119</H3>
|
||||
<DL><p><DT><H3>level 120</H3>
|
||||
<DL><p><DT><H3>level 121</H3>
|
||||
<DL><p><DT><H3>level 122</H3>
|
||||
<DL><p><DT><H3>level 123</H3>
|
||||
<DL><p><DT><H3>level 124</H3>
|
||||
<DL><p><DT><H3>level 125</H3>
|
||||
<DL><p><DT><H3>level 126</H3>
|
||||
<DL><p><DT><H3>level 127</H3>
|
||||
<DL><p><DT><H3>level 128</H3>
|
||||
<DL><p><DT><H3>level 129</H3>
|
||||
<DL><p><DT><H3>level 130</H3>
|
||||
<DL><p><DT><H3>level 131</H3>
|
||||
<DL><p><DT><H3>level 132</H3>
|
||||
<DL><p><DT><H3>level 133</H3>
|
||||
<DL><p><DT><H3>level 134</H3>
|
||||
<DL><p><DT><H3>level 135</H3>
|
||||
<DL><p><DT><H3>level 136</H3>
|
||||
<DL><p><DT><H3>level 137</H3>
|
||||
<DL><p><DT><H3>level 138</H3>
|
||||
<DL><p><DT><H3>level 139</H3>
|
||||
<DL><p><DT><H3>level 140</H3>
|
||||
<DL><p><DT><H3>level 141</H3>
|
||||
<DL><p><DT><H3>level 142</H3>
|
||||
<DL><p><DT><H3>level 143</H3>
|
||||
<DL><p><DT><H3>level 144</H3>
|
||||
<DL><p><DT><H3>level 145</H3>
|
||||
<DL><p><DT><H3>level 146</H3>
|
||||
<DL><p><DT><H3>level 147</H3>
|
||||
<DL><p><DT><H3>level 148</H3>
|
||||
<DL><p><DT><H3>level 149</H3>
|
||||
<DL><p><DT><A HREF="https://deep.example/">Deep</A></DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><H3>🌸 桜 フォルダ</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://ar.example/">مرحبا بالعالم</A>
|
||||
<DT><A HREF="https://amp.example/?a=1&b=2">Tom & Jerry <3 "quoted"</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><H3 ADD_DATE="1700000000">Explicitly closed</H3></DT>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://sibling-dl.example/">Via sibling DL</A></DT>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><H3 ADD_DATE="1700000000">Described folder</H3>
|
||||
<DD>This description closes the DT and swallows the following DL.
|
||||
<DL><p>
|
||||
<DT><A HREF="https://kept.example/">Must survive</A>
|
||||
</DL><p>
|
||||
<DT><A HREF="https://sibling.example/">Sibling</A>
|
||||
</DL><p>
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://us.example/" ADD_DATE="1700000000000000">Microseconds</A>
|
||||
<DT><A HREF="https://ms.example/" ADD_DATE="1700000000000">Milliseconds</A>
|
||||
<DT><A HREF="https://s.example/" ADD_DATE="1700000000">Seconds</A>
|
||||
<DT><A HREF="https://bad.example/" ADD_DATE="not-a-date">Invalid</A>
|
||||
</DL><p>
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><H3 PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://in.example/">in</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
<DT><H3>Other Bookmarks</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://out.example/">out</A>
|
||||
</DL><p>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<Title>Bookmarks</Title>
|
||||
<H1>Bookmarks</H1>
|
||||
<DT><H3 FOLDED>Favorites</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://www.apple.com/">Apple</A>
|
||||
</DL><p>
|
||||
<DT><H3 FOLDED>Reading List</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://webkit.org/blog/">WebKit Blog</A>
|
||||
</DL><p>
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { BookmarkNode } from '@/lib/core/model';
|
||||
|
||||
/**
|
||||
* Test helpers for the round-trip suite (docs/11 §3).
|
||||
*
|
||||
* `project()` models each format's DOCUMENTED lossiness, so a round-trip can
|
||||
* assert equality without pretending CSV and HTML are lossless. If a
|
||||
* projection ever needs widening to make a test pass, that is a spec change —
|
||||
* fix docs/04 first, not this file.
|
||||
*/
|
||||
export type RoundTripFormat = 'bm-json' | 'netscape-html' | 'csv';
|
||||
|
||||
/** Deterministic PRNG — no Math.random, so failures reproduce from the seed. */
|
||||
export function makeRng(seed: number): () => number {
|
||||
let state = seed >>> 0 || 1;
|
||||
return () => {
|
||||
state ^= state << 13;
|
||||
state >>>= 0;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
state >>>= 0;
|
||||
return state / 0x1_0000_0000;
|
||||
};
|
||||
}
|
||||
|
||||
/** Titles chosen to break naive serializers. Never empty — see project(). */
|
||||
const NASTY_TITLES = [
|
||||
'plain',
|
||||
'with, comma',
|
||||
'with "quotes"',
|
||||
'with \n newline',
|
||||
'with \r carriage return',
|
||||
'crlf \r\n here',
|
||||
'with\ttab',
|
||||
'emoji 🌸 and 日本語',
|
||||
'RTL مرحبا',
|
||||
'</a> and <script>',
|
||||
'amp & lt < gt >',
|
||||
'slash / and back\\slash',
|
||||
'trailing space ',
|
||||
'[brackets](parens)',
|
||||
];
|
||||
|
||||
const URLS = [
|
||||
'https://example.com/',
|
||||
'https://example.com/path?q=1&r=2#frag',
|
||||
'http://localhost:3000/x',
|
||||
'https://例え.jp/パス',
|
||||
'https://example.com/a(b)c',
|
||||
'https://example.com/space%20here',
|
||||
'ftp://files.example.org/pub',
|
||||
];
|
||||
|
||||
export interface GenerateOptions {
|
||||
maxDepth?: number;
|
||||
maxChildren?: number;
|
||||
}
|
||||
|
||||
/** Build a random but reproducible tree. Bookmarks always have a non-empty title. */
|
||||
export function generateTree(rng: () => number, options: GenerateOptions = {}): BookmarkNode[] {
|
||||
const maxDepth = options.maxDepth ?? 4;
|
||||
const maxChildren = options.maxChildren ?? 4;
|
||||
|
||||
const pick = <T>(items: readonly T[]): T => items[Math.floor(rng() * items.length)] as T;
|
||||
|
||||
const build = (depth: number): BookmarkNode[] => {
|
||||
const count = Math.floor(rng() * (maxChildren + 1));
|
||||
const nodes: BookmarkNode[] = [];
|
||||
for (let i = 0; i < count; i++) {
|
||||
const isFolder = depth < maxDepth && rng() < 0.4;
|
||||
const title = `${pick(NASTY_TITLES)} ${i}`;
|
||||
if (isFolder) {
|
||||
nodes.push({
|
||||
title,
|
||||
...(rng() < 0.6 && { addDate: 1_600_000_000 + Math.floor(rng() * 1e7) }),
|
||||
...(rng() < 0.4 && { lastModified: 1_700_000_000 + Math.floor(rng() * 1e7) }),
|
||||
...(depth === 1 && rng() < 0.2 && { toolbar: true }),
|
||||
children: build(depth + 1),
|
||||
});
|
||||
} else {
|
||||
nodes.push({
|
||||
title,
|
||||
url: pick(URLS),
|
||||
...(rng() < 0.7 && { addDate: 1_600_000_000 + Math.floor(rng() * 1e7) }),
|
||||
...(rng() < 0.3 && { lastModified: 1_700_000_000 + Math.floor(rng() * 1e7) }),
|
||||
});
|
||||
}
|
||||
}
|
||||
return nodes;
|
||||
};
|
||||
|
||||
return build(1);
|
||||
}
|
||||
|
||||
/** True when a subtree contains no bookmark at any depth — CSV cannot represent it. */
|
||||
function hasNoBookmarks(node: BookmarkNode): boolean {
|
||||
if (node.url !== undefined) return false;
|
||||
return (node.children ?? []).every(hasNoBookmarks);
|
||||
}
|
||||
|
||||
function projectNode(node: BookmarkNode, format: RoundTripFormat): BookmarkNode | null {
|
||||
const isFolder = node.url === undefined;
|
||||
|
||||
if (format === 'bm-json') return node; // lossless
|
||||
|
||||
if (format === 'netscape-html') {
|
||||
// LAST_MODIFIED is emitted on <H3> only, never on <A> — matching Chrome.
|
||||
if (isFolder) {
|
||||
return { ...node, children: projectList(node.children ?? [], format) };
|
||||
}
|
||||
const { lastModified: _dropped, ...rest } = node;
|
||||
return rest;
|
||||
}
|
||||
|
||||
// csv: drop empty folders, toolbar everywhere, all folder metadata, and
|
||||
// lastModified on bookmarks. Survivors: folder path, title, url, addDate.
|
||||
if (isFolder) {
|
||||
if (hasNoBookmarks(node)) return null;
|
||||
return { title: node.title, children: projectList(node.children ?? [], format) };
|
||||
}
|
||||
return {
|
||||
title: node.title,
|
||||
url: node.url as string,
|
||||
...(node.addDate !== undefined && { addDate: node.addDate }),
|
||||
};
|
||||
}
|
||||
|
||||
function projectList(nodes: readonly BookmarkNode[], format: RoundTripFormat): BookmarkNode[] {
|
||||
const out: BookmarkNode[] = [];
|
||||
for (const node of nodes) {
|
||||
const projected = projectNode(node, format);
|
||||
if (projected !== null) out.push(projected);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Apply a format's documented losses to a tree, yielding the expected parse output. */
|
||||
export function project(roots: readonly BookmarkNode[], format: RoundTripFormat): BookmarkNode[] {
|
||||
return projectList(roots, format);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildUrlIndex, dedupeAgainst, findDuplicateGroups } from '@/lib/core/dedupe';
|
||||
import { diffAgainstBrowser, type NodeStatus } from '@/lib/core/diff';
|
||||
import type { BookmarkNode } from '@/lib/core/model';
|
||||
|
||||
const BROWSER: BookmarkNode[] = [
|
||||
{
|
||||
title: 'Bar',
|
||||
children: [{ title: 'Example', url: 'https://example.com/' }],
|
||||
},
|
||||
];
|
||||
|
||||
const FILE: BookmarkNode[] = [
|
||||
{
|
||||
title: 'Imported',
|
||||
children: [
|
||||
{ title: 'Example again', url: 'https://EXAMPLE.com' }, // same link, different case + slash
|
||||
{ title: 'New one', url: 'https://new.example/' },
|
||||
{ title: 'New one dup', url: 'https://new.example/' }, // in-file repeat
|
||||
],
|
||||
},
|
||||
{ title: 'Empty after dedupe', children: [{ title: 'x', url: 'https://example.com/' }] },
|
||||
];
|
||||
|
||||
describe('buildUrlIndex', () => {
|
||||
it('indexes every bookmark URL by normalized key', () => {
|
||||
const index = buildUrlIndex(BROWSER);
|
||||
expect(index.has('https://example.com')).toBe(true);
|
||||
expect(index.size).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dedupeAgainst', () => {
|
||||
const result = dedupeAgainst(FILE, buildUrlIndex(BROWSER));
|
||||
|
||||
it('counts browser duplicates and in-file repeats separately (docs/05 §3)', () => {
|
||||
expect(result.skippedExisting).toBe(2); // "Example again" + the one in the 2nd folder
|
||||
expect(result.skippedInFile).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps only the first occurrence of an in-file repeat', () => {
|
||||
expect(result.nodes[0]?.children).toEqual([{ title: 'New one', url: 'https://new.example/' }]);
|
||||
});
|
||||
|
||||
it('preserves folders that became empty', () => {
|
||||
expect(result.nodes[1]).toEqual({ title: 'Empty after dedupe', children: [] });
|
||||
});
|
||||
|
||||
it('does not mutate the input tree', () => {
|
||||
expect(FILE[0]?.children).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('skips nothing against an empty index — the Replace-mode guard', () => {
|
||||
// Replace deletes the browser tree first, so the plan is built against an
|
||||
// empty index. A user re-importing their own backup must lose nothing.
|
||||
const replace = dedupeAgainst(BROWSER, new Set<string>());
|
||||
expect(replace.skippedExisting).toBe(0);
|
||||
expect(replace.nodes).toEqual(BROWSER);
|
||||
});
|
||||
});
|
||||
|
||||
describe('diffAgainstBrowser', () => {
|
||||
it('counts every occurrence, so 3 copies of one URL count 3 times', () => {
|
||||
const tree: BookmarkNode[] = [
|
||||
{ title: 'a', url: 'https://example.com/' },
|
||||
{ title: 'b', url: 'https://example.com/' },
|
||||
{ title: 'c', url: 'https://fresh.example/' },
|
||||
];
|
||||
const { newCount, existsCount, status } = diffAgainstBrowser(tree, buildUrlIndex(BROWSER));
|
||||
expect(existsCount).toBe(2);
|
||||
expect(newCount).toBe(1);
|
||||
const first: NodeStatus | undefined = status.get(tree[0] as BookmarkNode);
|
||||
expect(first).toBe('exists');
|
||||
expect(status.get(tree[2] as BookmarkNode)).toBe('new');
|
||||
});
|
||||
|
||||
it('does not badge folders', () => {
|
||||
const tree: BookmarkNode[] = [{ title: 'folder', children: [] }];
|
||||
const { status } = diffAgainstBrowser(tree, new Set<string>());
|
||||
expect(status.has(tree[0] as BookmarkNode)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findDuplicateGroups', () => {
|
||||
it('groups by normalized URL, largest group first, and carries ids', () => {
|
||||
const live = [
|
||||
{ id: '1', url: 'https://a.example/' },
|
||||
{ id: '2', url: 'https://A.example' },
|
||||
{ id: '3', url: 'https://a.example/' },
|
||||
{ id: '4', url: 'https://b.example/' },
|
||||
{ id: '5', url: 'https://b.example/' },
|
||||
{ id: '6', title: 'folder' } as { id: string; url?: string },
|
||||
];
|
||||
const groups = findDuplicateGroups(live);
|
||||
expect(groups).toHaveLength(2);
|
||||
expect(groups[0]?.nodes.map((n) => n.id)).toEqual(['1', '2', '3']);
|
||||
expect(groups[1]?.nodes.map((n) => n.id)).toEqual(['4', '5']);
|
||||
});
|
||||
|
||||
it('returns nothing when every URL is unique', () => {
|
||||
expect(findDuplicateGroups([{ url: 'https://a.example/' }])).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { detectFormat, stripBom } from '@/lib/core/detect-format';
|
||||
import { BmParseError } from '@/lib/core/model';
|
||||
|
||||
const HTML = '<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<DL><p></DL><p>';
|
||||
const JSON_DOC = '{"format":"bookmarkmagic","version":1,"roots":[]}';
|
||||
const CSV = 'folder_path,title,url,add_date\r\n,"A",https://a.example/,\r\n';
|
||||
|
||||
describe('detectFormat — sniffs content, never the extension', () => {
|
||||
it('identifies each format', () => {
|
||||
expect(detectFormat(HTML)).toBe('netscape-html');
|
||||
expect(detectFormat(JSON_DOC)).toBe('bm-json');
|
||||
expect(detectFormat(CSV)).toBe('csv');
|
||||
});
|
||||
|
||||
it('is case-insensitive about the doctype', () => {
|
||||
expect(detectFormat('<!doctype netscape-bookmark-file-1>\n<dl><p></dl>')).toBe('netscape-html');
|
||||
});
|
||||
|
||||
it('ignores a wrong extension — the caller never passes one', () => {
|
||||
// A .json file that is really HTML, and a .html file that is really CSV.
|
||||
expect(detectFormat(HTML)).toBe('netscape-html');
|
||||
expect(detectFormat(CSV)).toBe('csv');
|
||||
});
|
||||
|
||||
it('tolerates a leading BOM on every format', () => {
|
||||
expect(detectFormat(`${HTML}`)).toBe('netscape-html');
|
||||
expect(detectFormat(`${JSON_DOC}`)).toBe('bm-json');
|
||||
expect(detectFormat(`${CSV}`)).toBe('csv');
|
||||
});
|
||||
|
||||
it('rejects JSON that is not ours', () => {
|
||||
// Chrome's internal Bookmarks file is explicitly out of scope for v1.
|
||||
expect(() => detectFormat('{"checksum":"x","roots":{"bookmark_bar":{}}}')).toThrow(
|
||||
BmParseError,
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts a <DL> document with no doctype and lets the parser judge it', () => {
|
||||
expect(detectFormat('<html><body><DL><p><DT><A HREF="x">t</A></DL></body></html>')).toBe(
|
||||
'netscape-html',
|
||||
);
|
||||
});
|
||||
|
||||
it('throws UNKNOWN_FORMAT on anything else', () => {
|
||||
try {
|
||||
detectFormat('just some text\nwith lines\n');
|
||||
expect.unreachable('should have thrown');
|
||||
} catch (err) {
|
||||
expect((err as BmParseError).code).toBe('UNKNOWN_FORMAT');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripBom', () => {
|
||||
it('removes only a leading U+FEFF', () => {
|
||||
expect(stripBom('abc')).toBe('abc');
|
||||
expect(stripBom('abc')).toBe('abc');
|
||||
expect(stripBom('ab')).toBe('ab');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { buildFolderPathIndex } from '@/lib/core/diff';
|
||||
import type { BookmarkNode } from '@/lib/core/model';
|
||||
|
||||
const TREE: BookmarkNode[] = [
|
||||
{
|
||||
title: 'Bookmarks bar',
|
||||
children: [
|
||||
{ title: 'Dev', children: [{ title: 'Deep', children: [] }] },
|
||||
{ title: 'Link', url: 'https://a.example/' },
|
||||
],
|
||||
},
|
||||
{ title: 'Other', children: [] },
|
||||
];
|
||||
|
||||
describe('buildFolderPathIndex — merge-mode folder matching (docs/05 §5)', () => {
|
||||
const index = buildFolderPathIndex(TREE);
|
||||
|
||||
it('keys folders by their full ancestor-title path', () => {
|
||||
expect([...index.keys()].sort()).toEqual(
|
||||
[
|
||||
JSON.stringify(['Bookmarks bar']),
|
||||
JSON.stringify(['Bookmarks bar', 'Dev']),
|
||||
JSON.stringify(['Bookmarks bar', 'Dev', 'Deep']),
|
||||
JSON.stringify(['Other']),
|
||||
].sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it('indexes folders only, never bookmarks', () => {
|
||||
expect(index.has(JSON.stringify(['Bookmarks bar', 'Link']))).toBe(false);
|
||||
});
|
||||
|
||||
it('matches are exact and case-sensitive', () => {
|
||||
expect(index.has(JSON.stringify(['bookmarks bar']))).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the first of two identically-named siblings', () => {
|
||||
const first: BookmarkNode = { title: 'Dup', children: [{ title: 'a', url: 'https://a/' }] };
|
||||
const second: BookmarkNode = { title: 'Dup', children: [] };
|
||||
const dupIndex = buildFolderPathIndex([first, second]);
|
||||
expect(dupIndex.get(JSON.stringify(['Dup']))).toBe(first);
|
||||
});
|
||||
|
||||
it('distinguishes same-named folders at different paths', () => {
|
||||
const tree: BookmarkNode[] = [
|
||||
{ title: 'A', children: [{ title: 'Shared', children: [] }] },
|
||||
{ title: 'B', children: [{ title: 'Shared', children: [] }] },
|
||||
];
|
||||
const paths = buildFolderPathIndex(tree);
|
||||
expect(paths.has(JSON.stringify(['A', 'Shared']))).toBe(true);
|
||||
expect(paths.has(JSON.stringify(['B', 'Shared']))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { detectFormat } from '@/lib/core/detect-format';
|
||||
import { type BmParseError, type BookmarkNode, walkTree } from '@/lib/core/model';
|
||||
import { parseBmJson } from '@/lib/core/parse/bm-json';
|
||||
import { parseCsv } from '@/lib/core/parse/csv';
|
||||
import { parseNetscapeHtml } from '@/lib/core/parse/netscape-html';
|
||||
import { serializeNetscapeHtml } from '@/lib/core/serialize/netscape-html';
|
||||
import { project } from '../../helpers/tree';
|
||||
|
||||
/**
|
||||
* Real-world fixtures — docs/11 §2.
|
||||
*
|
||||
* Rule: every browser-specific quirk discovered later gets a fixture and a
|
||||
* regression test in the same PR.
|
||||
*/
|
||||
// Vitest runs from the project root; import.meta.url is not a file: URL under
|
||||
// the jsdom environment, so resolve from cwd instead.
|
||||
const dir = join(process.cwd(), 'tests', 'fixtures');
|
||||
const read = (name: string): string => readFileSync(join(dir, name), 'utf8');
|
||||
|
||||
const BROWSER_EXPORTS = [
|
||||
'chrome-131-export.html',
|
||||
'edge-export.html',
|
||||
'firefox-html-export.html',
|
||||
'safari-export.html',
|
||||
'vivaldi-export.html',
|
||||
];
|
||||
|
||||
const urlsOf = (roots: readonly BookmarkNode[]): string[] => {
|
||||
const out: string[] = [];
|
||||
for (const { node } of walkTree(roots)) if (node.url !== undefined) out.push(node.url);
|
||||
return out.sort();
|
||||
};
|
||||
|
||||
describe.each(BROWSER_EXPORTS)('fixture: %s', (name) => {
|
||||
const text = read(name);
|
||||
|
||||
it('is detected as Netscape HTML', () => {
|
||||
expect(detectFormat(text)).toBe('netscape-html');
|
||||
});
|
||||
|
||||
it('parses to a non-empty tree', () => {
|
||||
const { roots, stats } = parseNetscapeHtml(text);
|
||||
expect(roots.length).toBeGreaterThan(0);
|
||||
expect(stats.bookmarks).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('re-imports its own HTML export under the documented projection', () => {
|
||||
// Not identity: Firefox writes LAST_MODIFIED on <A>, which our serializer
|
||||
// (like Chrome) does not emit — docs/04 §1.1, docs/11 §3.
|
||||
const once = parseNetscapeHtml(text).roots;
|
||||
expect(parseNetscapeHtml(serializeNetscapeHtml(once)).roots).toEqual(
|
||||
project(once, 'netscape-html'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fixture specifics', () => {
|
||||
it('chrome: reads the toolbar folder, preserves the empty folder, decodes entities', () => {
|
||||
const { roots, warnings } = parseNetscapeHtml(read('chrome-131-export.html'));
|
||||
expect(roots[0]?.title).toBe('Bookmarks bar');
|
||||
expect(roots[0]?.toolbar).toBe(true);
|
||||
expect(roots[0]?.children?.[2]).toEqual({
|
||||
title: 'Empty folder',
|
||||
addDate: 1700000005,
|
||||
children: [],
|
||||
});
|
||||
expect(urlsOf(roots)).toContain('https://example.com/?q=a&b=1#frag');
|
||||
// ICON present on one bookmark; ADD_DATE="0" must NOT warn.
|
||||
expect(warnings.find((w) => w.code === 'FAVICONS_IGNORED')?.count).toBe(1);
|
||||
expect(warnings.map((w) => w.code)).not.toContain('INVALID_DATE');
|
||||
});
|
||||
|
||||
it('edge: keeps a file:// bookmark verbatim', () => {
|
||||
const { roots } = parseNetscapeHtml(read('edge-export.html'));
|
||||
expect(urlsOf(roots)).toContain('file:///C:/Users/Public/notes.txt');
|
||||
});
|
||||
|
||||
it('firefox: DD does not eat the subtree, HR is skipped, extras ignored', () => {
|
||||
const { roots, warnings } = parseNetscapeHtml(read('firefox-html-export.html'));
|
||||
const toolbar = roots[0];
|
||||
expect(toolbar?.title).toBe('Bookmarks Toolbar');
|
||||
expect(urlsOf(roots)).toEqual(['https://support.mozilla.org/', 'https://www.mozilla.org/']);
|
||||
expect(warnings.map((w) => w.code)).toContain('DESCRIPTIONS_DROPPED');
|
||||
});
|
||||
|
||||
it('safari: both top-level folders survive', () => {
|
||||
const { roots } = parseNetscapeHtml(read('safari-export.html'));
|
||||
expect(roots.map((r) => r.title)).toEqual(['Favorites', 'Reading List']);
|
||||
expect(urlsOf(roots)).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('weird: dd fixture keeps the nested bookmark and its sibling', () => {
|
||||
const { roots } = parseNetscapeHtml(read('weird/folder-with-dd.html'));
|
||||
expect(roots[0]?.children?.[0]?.url).toBe('https://kept.example/');
|
||||
expect(roots[1]?.url).toBe('https://sibling.example/');
|
||||
});
|
||||
|
||||
it('weird: Safari export with no wrapper <DL> keeps both top-level folders', () => {
|
||||
const { roots } = parseNetscapeHtml(read('weird/safari-no-wrapper.html'));
|
||||
expect(roots.map((r) => r.title)).toEqual(['Favorites', 'Reading List']);
|
||||
expect(urlsOf(roots)).toEqual(['https://webkit.org/blog/', 'https://www.apple.com/']);
|
||||
});
|
||||
|
||||
it('weird: a wrapper <DL> mixed with loose top-level <DT>s keeps both halves', () => {
|
||||
const { roots } = parseNetscapeHtml(read('weird/mixed-wrapper.html'));
|
||||
expect(roots.map((r) => r.title)).toEqual(['Bookmarks bar', 'Other Bookmarks']);
|
||||
expect(urlsOf(roots)).toEqual(['https://in.example/', 'https://out.example/']);
|
||||
});
|
||||
|
||||
it('weird: explicit </DT> exercises the sibling-DL branch', () => {
|
||||
const { roots } = parseNetscapeHtml(read('weird/explicit-close-dt.html'));
|
||||
expect(roots[0]?.children?.[0]?.url).toBe('https://sibling-dl.example/');
|
||||
});
|
||||
|
||||
it('weird: epoch magnitudes all normalize to the same second', () => {
|
||||
const { roots, warnings } = parseNetscapeHtml(read('weird/microsecond-dates.html'));
|
||||
const dates = roots.filter((r) => r.url !== undefined).map((r) => r.addDate);
|
||||
expect(dates.slice(0, 3)).toEqual([1700000000, 1700000000, 1700000000]);
|
||||
expect(warnings.find((w) => w.code === 'INVALID_DATE')?.count).toBe(1);
|
||||
});
|
||||
|
||||
it('weird: depth 150 parses under the 200 cap', () => {
|
||||
const { stats } = parseNetscapeHtml(read('weird/deep-nesting.html'));
|
||||
expect(stats.maxDepth).toBe(151);
|
||||
});
|
||||
|
||||
it('weird: emoji, RTL and entities survive a round trip', () => {
|
||||
const once = parseNetscapeHtml(read('weird/emoji-rtl-titles.html')).roots;
|
||||
expect(once[0]?.title).toBe('🌸 桜 フォルダ');
|
||||
expect(once[0]?.children?.[1]?.title).toBe('Tom & Jerry <3 "quoted"');
|
||||
expect(parseNetscapeHtml(serializeNetscapeHtml(once)).roots).toEqual(once);
|
||||
});
|
||||
});
|
||||
|
||||
describe('malformed fixtures', () => {
|
||||
it('no-doctype: throws NOT_NETSCAPE', () => {
|
||||
try {
|
||||
parseNetscapeHtml(read('malformed/no-doctype.html'));
|
||||
expect.unreachable('should have thrown');
|
||||
} catch (err) {
|
||||
expect((err as BmParseError).code).toBe('NOT_NETSCAPE');
|
||||
}
|
||||
});
|
||||
|
||||
it('doctype-only: yields an empty result with NO_BOOKMARKS, not a crash', () => {
|
||||
const { roots, warnings } = parseNetscapeHtml(read('malformed/doctype-only.html'));
|
||||
expect(roots).toEqual([]);
|
||||
expect(warnings.map((w) => w.code)).toContain('NO_BOOKMARKS');
|
||||
});
|
||||
|
||||
it('truncated: recovers what it can', () => {
|
||||
const { roots } = parseNetscapeHtml(read('malformed/truncated.html'));
|
||||
expect(urlsOf(roots)).toEqual(['https://example.com/']);
|
||||
});
|
||||
|
||||
it('script-injection: titles are inert text and nothing executes (T1)', () => {
|
||||
const { roots } = parseNetscapeHtml(read('malformed/script-injection.html'));
|
||||
expect((globalThis as Record<string, unknown>).__pwned).toBeUndefined();
|
||||
const titles = [...walkTree(roots)].map(({ node }) => node.title);
|
||||
expect(titles).toContain('<img src=x onerror=alert(1)>');
|
||||
expect(titles).toContain('<script>alert(2)</script>');
|
||||
expect(urlsOf(roots)).toContain('https://ok.example/');
|
||||
});
|
||||
|
||||
it('js-url: dangerous schemes are parsed and stored verbatim, not dropped (T3)', () => {
|
||||
const { roots } = parseNetscapeHtml(read('malformed/js-url.html'));
|
||||
expect(urlsOf(roots)).toEqual([
|
||||
'data:text/html,<h1>hi</h1>',
|
||||
'https://safe.example/',
|
||||
'javascript:alert(1)',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('non-HTML fixtures', () => {
|
||||
it('bm-v1-sample.json detects and parses', () => {
|
||||
const text = read('bm-v1-sample.json');
|
||||
expect(detectFormat(text)).toBe('bm-json');
|
||||
const { roots, stats } = parseBmJson(text);
|
||||
expect(roots[0]?.toolbar).toBe(true);
|
||||
expect(stats).toEqual({ bookmarks: 2, folders: 3, maxDepth: 3 });
|
||||
});
|
||||
|
||||
it('csv-comma.csv detects, parses and honours the \\/ path escape', () => {
|
||||
const text = read('csv-comma.csv');
|
||||
expect(detectFormat(text)).toBe('csv');
|
||||
const { roots } = parseCsv(text);
|
||||
expect(roots.map((r) => r.title)).toEqual(['Bookmarks bar', 'Example', 'Escaped/slash']);
|
||||
});
|
||||
|
||||
it('csv-semicolon.csv detects and parses despite BOM + ; delimiter', () => {
|
||||
const text = read('csv-semicolon.csv');
|
||||
expect(detectFormat(text)).toBe('csv');
|
||||
expect(parseCsv(text).roots[0]?.children?.[0]?.url).toBe('https://semi.example/');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
BmParseError,
|
||||
type BookmarkNode,
|
||||
computeStats,
|
||||
type ImportPlan,
|
||||
isFolder,
|
||||
type MergeMode,
|
||||
type PlanSegment,
|
||||
walkTree,
|
||||
} from '@/lib/core/model';
|
||||
|
||||
const TREE: BookmarkNode[] = [
|
||||
{
|
||||
title: 'Bar',
|
||||
children: [
|
||||
{ title: 'a', url: 'https://a.example/' },
|
||||
{ title: 'Deep', children: [{ title: 'b', url: 'https://b.example/' }] },
|
||||
],
|
||||
},
|
||||
{ title: 'loose', url: 'https://c.example/' },
|
||||
];
|
||||
|
||||
describe('isFolder', () => {
|
||||
it('is defined by the absence of a url, not by children', () => {
|
||||
expect(isFolder({ title: 'f', children: [] })).toBe(true);
|
||||
expect(isFolder({ title: 'f' })).toBe(true);
|
||||
expect(isFolder({ title: 'b', url: 'https://x.test/' })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('walkTree', () => {
|
||||
it('yields parents before children, siblings in order, with 1-based depth', () => {
|
||||
expect([...walkTree(TREE)].map(({ node, depth }) => `${depth}:${node.title}`)).toEqual([
|
||||
'1:Bar',
|
||||
'2:a',
|
||||
'2:Deep',
|
||||
'3:b',
|
||||
'1:loose',
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles an empty forest', () => {
|
||||
expect([...walkTree([])]).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('computeStats', () => {
|
||||
it('counts bookmarks, folders and max depth in one pass', () => {
|
||||
expect(computeStats(TREE)).toEqual({ bookmarks: 3, folders: 2, maxDepth: 3 });
|
||||
});
|
||||
|
||||
it('reports zero depth for an empty forest', () => {
|
||||
expect(computeStats([])).toEqual({ bookmarks: 0, folders: 0, maxDepth: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('BmParseError', () => {
|
||||
it('carries a machine code plus optional detail and line', () => {
|
||||
const err = new BmParseError('CSV_ROW_MISMATCH', 'row has 3 fields', 7);
|
||||
expect(err).toBeInstanceOf(Error);
|
||||
expect(err.name).toBe('BmParseError');
|
||||
expect(err.code).toBe('CSV_ROW_MISMATCH');
|
||||
expect(err.line).toBe(7);
|
||||
expect(err.message).toContain('row has 3 fields');
|
||||
});
|
||||
|
||||
it('falls back to the bare code when there is no detail', () => {
|
||||
expect(new BmParseError('NOT_NETSCAPE').message).toBe('NOT_NETSCAPE');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ImportPlan can express every mode (docs/02 §4)', () => {
|
||||
const toolbarNodes: BookmarkNode[] = [{ title: 'bar item', url: 'https://a.example/' }];
|
||||
const otherNodes: BookmarkNode[] = [{ title: 'other item', url: 'https://b.example/' }];
|
||||
|
||||
const plan = (mode: MergeMode, segments: PlanSegment[]): ImportPlan => ({
|
||||
mode,
|
||||
dedupe: mode !== 'replace',
|
||||
segments,
|
||||
stats: {
|
||||
toCreate: segments.reduce((n, s) => n + [...walkTree(s.nodes)].length, 0),
|
||||
bookmarkCount: segments.reduce(
|
||||
(n, s) => n + [...walkTree(s.nodes)].filter(({ node }) => !isFolder(node)).length,
|
||||
0,
|
||||
),
|
||||
skippedExisting: 0,
|
||||
skippedInFile: 0,
|
||||
},
|
||||
});
|
||||
|
||||
it('new-folder is a single segment under one root', () => {
|
||||
const p = plan('new-folder', [
|
||||
{ rootId: '2', nodes: [{ title: 'Imported 2026-07-25', children: toolbarNodes }] },
|
||||
]);
|
||||
expect(p.segments).toHaveLength(1);
|
||||
expect(p.stats.toCreate).toBe(2); // wrapper folder + 1 bookmark
|
||||
expect(p.stats.bookmarkCount).toBe(1);
|
||||
});
|
||||
|
||||
it('merge and replace can target two roots at once', () => {
|
||||
for (const mode of ['merge', 'replace'] as const) {
|
||||
const p = plan(mode, [
|
||||
{ rootId: '1', nodes: toolbarNodes },
|
||||
{ rootId: '2', nodes: otherNodes },
|
||||
]);
|
||||
expect(p.segments.map((s) => s.rootId)).toEqual(['1', '2']);
|
||||
// One denominator for the whole import, not per segment.
|
||||
expect(p.stats.toCreate).toBe(2);
|
||||
}
|
||||
});
|
||||
|
||||
it('dedupe is off for replace — the browser tree is deleted first', () => {
|
||||
expect(plan('replace', []).dedupe).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { normalizeUrl } from '@/lib/core/normalize-url';
|
||||
|
||||
describe('normalizeUrl', () => {
|
||||
it('lowercases scheme and host but not the path', () => {
|
||||
expect(normalizeUrl('HTTPS://Example.COM/Path')).toBe('https://example.com/Path');
|
||||
});
|
||||
|
||||
it('strips default ports only', () => {
|
||||
expect(normalizeUrl('https://example.com:443/')).toBe('https://example.com');
|
||||
expect(normalizeUrl('http://example.com:80/')).toBe('http://example.com');
|
||||
// A non-default port is kept. The bare-origin rule still applies, so the
|
||||
// trailing slash is dropped here exactly as it is for the default-port case.
|
||||
expect(normalizeUrl('http://example.com:8080/')).toBe('http://example.com:8080');
|
||||
expect(normalizeUrl('http://example.com:8080/a')).toBe('http://example.com:8080/a');
|
||||
});
|
||||
|
||||
it('treats a bare origin the same with or without a trailing slash', () => {
|
||||
expect(normalizeUrl('https://example.com')).toBe(normalizeUrl('https://example.com/'));
|
||||
});
|
||||
|
||||
it('keeps query and fragment verbatim — they are meaningful', () => {
|
||||
expect(normalizeUrl('https://example.com/?q=1#frag')).toBe('https://example.com/?q=1#frag');
|
||||
expect(normalizeUrl('https://example.com/?b=2&a=1')).toBe('https://example.com/?b=2&a=1');
|
||||
});
|
||||
|
||||
it('does NOT strip utm_, www. or unify http/https (docs/05 §2)', () => {
|
||||
expect(normalizeUrl('https://www.example.com/?utm_source=x')).not.toBe(
|
||||
normalizeUrl('https://example.com/'),
|
||||
);
|
||||
expect(normalizeUrl('http://example.com/a')).not.toBe(normalizeUrl('https://example.com/a'));
|
||||
});
|
||||
|
||||
it('passes unparseable input through trimmed, so such links still match exactly', () => {
|
||||
expect(normalizeUrl(' javascript:alert(1) ')).toBe('javascript:alert(1)');
|
||||
expect(normalizeUrl('not a url')).toBe('not a url');
|
||||
expect(normalizeUrl('javascript:alert(1)')).toBe(normalizeUrl(' javascript:alert(1) '));
|
||||
});
|
||||
|
||||
it('never collapses two different URLs onto one key', () => {
|
||||
// A false-positive dedupe key is silent DATA LOSS: the second bookmark is
|
||||
// dropped on import. Userinfo is the case the bare-origin fast path missed.
|
||||
const distinct = [
|
||||
'https://alice@example.com/',
|
||||
'https://bob@example.com/',
|
||||
'https://alice:pw@example.com/',
|
||||
'https://example.com/',
|
||||
'https://example.com:8443/',
|
||||
'https://sub.example.com/',
|
||||
];
|
||||
const keys = distinct.map(normalizeUrl);
|
||||
expect(new Set(keys).size).toBe(distinct.length);
|
||||
});
|
||||
|
||||
it('is stable — normalizing twice changes nothing', () => {
|
||||
for (const raw of [
|
||||
'https://example.com',
|
||||
'https://example.com/a?b=1#c',
|
||||
'ftp://files.example.org:21/pub',
|
||||
'not a url',
|
||||
]) {
|
||||
expect(normalizeUrl(normalizeUrl(raw))).toBe(normalizeUrl(raw));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { BmParseError } from '@/lib/core/model';
|
||||
import { parseBmJson } from '@/lib/core/parse/bm-json';
|
||||
|
||||
const wrap = (roots: unknown, extra: Record<string, unknown> = {}): string =>
|
||||
JSON.stringify({ format: 'bookmarkmagic', version: 1, roots, ...extra });
|
||||
|
||||
describe('parseBmJson — happy path', () => {
|
||||
it('reads nodes, dates and the toolbar flag', () => {
|
||||
const { roots, stats } = parseBmJson(
|
||||
wrap([
|
||||
{
|
||||
title: 'Bar',
|
||||
toolbar: true,
|
||||
addDate: 1751500000,
|
||||
lastModified: 1751500001,
|
||||
children: [{ title: 'A', url: 'https://a.example/', addDate: 1751500002 }],
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(roots[0]?.toolbar).toBe(true);
|
||||
expect(roots[0]?.children?.[0]?.url).toBe('https://a.example/');
|
||||
expect(stats).toEqual({ bookmarks: 1, folders: 1, maxDepth: 2 });
|
||||
});
|
||||
|
||||
it('treats a folder with no children key as an empty folder', () => {
|
||||
const { roots } = parseBmJson(wrap([{ title: 'Empty' }]));
|
||||
expect(roots[0]).toEqual({ title: 'Empty', children: [] });
|
||||
});
|
||||
|
||||
it('ignores unknown keys for forward compatibility', () => {
|
||||
const { roots } = parseBmJson(
|
||||
wrap([{ title: 'A', url: 'https://a.example/', futureField: 1 }]),
|
||||
);
|
||||
expect(roots[0]).toEqual({ title: 'A', url: 'https://a.example/' });
|
||||
});
|
||||
|
||||
it('warns but still parses when the file version is newer', () => {
|
||||
const { warnings } = parseBmJson(wrap([], { version: 99 }));
|
||||
expect(warnings.map((w) => w.code)).toContain('NEWER_VERSION');
|
||||
});
|
||||
|
||||
it('drops non-positive dates rather than storing them', () => {
|
||||
const { roots } = parseBmJson(wrap([{ title: 'A', url: 'https://a.example/', addDate: 0 }]));
|
||||
expect(Object.hasOwn(roots[0] ?? {}, 'addDate')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseBmJson — rejections', () => {
|
||||
const expectCode = (text: string, code: string): void => {
|
||||
try {
|
||||
parseBmJson(text);
|
||||
expect.unreachable(`should have thrown ${code}`);
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(BmParseError);
|
||||
expect((err as BmParseError).code).toBe(code);
|
||||
}
|
||||
};
|
||||
|
||||
it('rejects malformed JSON', () => {
|
||||
expectCode('{ not json', 'MALFORMED_JSON');
|
||||
});
|
||||
|
||||
it('rejects JSON that is not ours', () => {
|
||||
expectCode('{"checksum":"x","roots":{}}', 'NOT_BM_JSON');
|
||||
expectCode('[]', 'NOT_BM_JSON');
|
||||
});
|
||||
|
||||
it('rejects a non-array roots', () => {
|
||||
expectCode('{"format":"bookmarkmagic","roots":{}}', 'INVALID_NODE');
|
||||
});
|
||||
|
||||
it('rejects structurally invalid nodes', () => {
|
||||
expectCode(wrap([null]), 'INVALID_NODE');
|
||||
expectCode(wrap([{ url: 'https://a.example/' }]), 'INVALID_NODE'); // no title
|
||||
expectCode(wrap([{ title: 'A', url: 42 }]), 'INVALID_NODE');
|
||||
expectCode(wrap([{ title: 'A', children: 'nope' }]), 'INVALID_NODE');
|
||||
expectCode(wrap([{ title: 'A', url: 'https://a.example/', children: [] }]), 'INVALID_NODE');
|
||||
});
|
||||
|
||||
it('names the offending path in the detail', () => {
|
||||
try {
|
||||
parseBmJson(wrap([{ title: 'ok', children: [{ nope: true }] }]));
|
||||
expect.unreachable('should have thrown');
|
||||
} catch (err) {
|
||||
expect((err as BmParseError).detail).toContain('roots[0].children[0]');
|
||||
}
|
||||
});
|
||||
|
||||
it('warns when there are no bookmarks at all', () => {
|
||||
expect(parseBmJson(wrap([])).warnings.map((w) => w.code)).toContain('NO_BOOKMARKS');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { joinPath, splitPath } from '@/lib/core/csv-path';
|
||||
import { BmParseError } from '@/lib/core/model';
|
||||
import { parseCsv, parseCsvRows } from '@/lib/core/parse/csv';
|
||||
import { CSV_BOM, type CsvDelimiter, serializeCsv } from '@/lib/core/serialize/csv';
|
||||
|
||||
const HEADER = 'folder_path,title,url,add_date';
|
||||
|
||||
describe('parseCsvRows — RFC 4180-style torture cases', () => {
|
||||
it('unescapes doubled quotes', () => {
|
||||
expect(parseCsvRows('a,"say ""hi""",c', ',')).toEqual([['a', 'say "hi"', 'c']]);
|
||||
});
|
||||
|
||||
it('keeps delimiters and newlines inside quotes', () => {
|
||||
expect(parseCsvRows('"a,b","c\nd"', ',')).toEqual([['a,b', 'c\nd']]);
|
||||
});
|
||||
|
||||
it('accepts CRLF, LF and a lone CR as record separators', () => {
|
||||
expect(parseCsvRows('a,b\r\nc,d\ne,f\rg,h', ',')).toEqual([
|
||||
['a', 'b'],
|
||||
['c', 'd'],
|
||||
['e', 'f'],
|
||||
['g', 'h'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('preserves CRLF inside a quoted field', () => {
|
||||
expect(parseCsvRows('"line1\r\nline2",b', ',')).toEqual([['line1\r\nline2', 'b']]);
|
||||
});
|
||||
|
||||
it('does not add a phantom row for a trailing newline', () => {
|
||||
expect(parseCsvRows('a,b\r\n', ',')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('handles empty fields', () => {
|
||||
expect(parseCsvRows('a,,c', ',')).toEqual([['a', '', 'c']]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('csv-path escaping', () => {
|
||||
it('round-trips slashes and backslashes in folder names', () => {
|
||||
for (const segments of [
|
||||
['plain'],
|
||||
['with/slash'],
|
||||
['with\\backslash'],
|
||||
['a/b', 'c\\d'],
|
||||
['\\', '/'],
|
||||
['trailing\\'],
|
||||
]) {
|
||||
expect(splitPath(joinPath(segments))).toEqual(segments);
|
||||
}
|
||||
});
|
||||
|
||||
it('treats an empty path as top level', () => {
|
||||
expect(splitPath('')).toEqual([]);
|
||||
expect(joinPath([])).toBe('');
|
||||
});
|
||||
|
||||
it('distinguishes "no path" from "one folder with an empty title"', () => {
|
||||
// Both would serialize to '' naively, dissolving the folder on re-import.
|
||||
expect(joinPath([''])).not.toBe('');
|
||||
expect(splitPath(joinPath(['']))).toEqual(['']);
|
||||
});
|
||||
|
||||
it('keeps an empty-titled folder through a full CSV cycle', () => {
|
||||
const tree = [{ title: '', children: [{ title: 'A', url: 'https://a.example/' }] }];
|
||||
expect(parseCsv(serializeCsv(tree, { bom: false })).roots).toEqual(tree);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseCsv', () => {
|
||||
it('rebuilds folders from paths', () => {
|
||||
const csv = `${HEADER}\r\n"Bookmarks bar/Dev tools","GitHub","https://github.com/","1751500000"\r\n"","Example","https://example.com/",""\r\n`;
|
||||
const { roots } = parseCsv(csv);
|
||||
expect(roots).toEqual([
|
||||
{
|
||||
title: 'Bookmarks bar',
|
||||
children: [
|
||||
{
|
||||
title: 'Dev tools',
|
||||
children: [{ title: 'GitHub', url: 'https://github.com/', addDate: 1751500000 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{ title: 'Example', url: 'https://example.com/' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('tolerates a UTF-8 BOM', () => {
|
||||
const { roots } = parseCsv(`${HEADER}\r\n"","A","https://a.example/",""\r\n`);
|
||||
expect(roots[0]?.url).toBe('https://a.example/');
|
||||
});
|
||||
|
||||
it('sniffs the semicolon delimiter from the header', () => {
|
||||
const delimiter: CsvDelimiter = ';';
|
||||
expect(serializeCsv([], { delimiter, bom: false }).trim()).toContain(delimiter);
|
||||
const csv = 'folder_path;title;url;add_date\r\n"";"A";"https://a.example/";""\r\n';
|
||||
expect(parseCsv(csv).roots[0]?.url).toBe('https://a.example/');
|
||||
});
|
||||
|
||||
it('never sets toolbar — CSV has no column for it (docs/04 §3)', () => {
|
||||
const csv = `${HEADER}\r\n"Bookmarks bar","A","https://a.example/",""\r\n`;
|
||||
const folder = parseCsv(csv).roots[0];
|
||||
expect(folder?.title).toBe('Bookmarks bar');
|
||||
expect(Object.hasOwn(folder ?? {}, 'toolbar')).toBe(false);
|
||||
});
|
||||
|
||||
it('warns on rows with no URL instead of inventing one', () => {
|
||||
const csv = `${HEADER}\r\n"","No link","",""\r\n"","A","https://a.example/",""\r\n`;
|
||||
const { roots, warnings } = parseCsv(csv);
|
||||
expect(roots).toHaveLength(1);
|
||||
expect(warnings.find((w) => w.code === 'MISSING_URL')?.count).toBe(1);
|
||||
});
|
||||
|
||||
it('accepts a fully quoted header row', () => {
|
||||
const csv = `"folder_path","title","url","add_date"\r\n"","A","https://a.example/",""\r\n`;
|
||||
expect(parseCsv(csv).roots[0]?.url).toBe('https://a.example/');
|
||||
});
|
||||
|
||||
it('counts synthesized folders against the node cap, not just rows', () => {
|
||||
// A file with few rows but very deep paths must not build an unbounded
|
||||
// tree: only counting bookmark rows let MAX_NODES be bypassed entirely.
|
||||
const deepPath = Array.from({ length: 60 }, (_, i) => `f${i}`).join('/');
|
||||
const { stats } = parseCsv(`${HEADER}\r\n"${deepPath}","A","https://a.example/",""\r\n`);
|
||||
expect(stats.folders).toBe(60);
|
||||
});
|
||||
|
||||
it('throws BAD_CSV_HEADER when the header is missing or reordered', () => {
|
||||
expect(() => parseCsv('title,url\r\na,b\r\n')).toThrow(BmParseError);
|
||||
expect(() => parseCsv('title,folder_path,url,add_date\r\n')).toThrow(BmParseError);
|
||||
});
|
||||
|
||||
it('throws CSV_ROW_MISMATCH with the offending line number', () => {
|
||||
const csv = `${HEADER}\r\n"","A","https://a.example/"\r\n`;
|
||||
try {
|
||||
parseCsv(csv);
|
||||
expect.unreachable('should have thrown');
|
||||
} catch (err) {
|
||||
expect((err as BmParseError).code).toBe('CSV_ROW_MISMATCH');
|
||||
expect((err as BmParseError).line).toBe(2);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('serializeCsv', () => {
|
||||
it('quotes only fields that need it, and escapes quotes', () => {
|
||||
const csv = serializeCsv(
|
||||
[
|
||||
{ title: 'plain', url: 'https://a.example/' },
|
||||
{ title: 'has, comma', url: 'https://b.example/' },
|
||||
{ title: 'has "quote"', url: 'https://c.example/' },
|
||||
{ title: 'has\nnewline', url: 'https://d.example/' },
|
||||
],
|
||||
{ bom: false },
|
||||
);
|
||||
const lines = csv.split('\r\n');
|
||||
expect(lines[1]).toBe(',plain,https://a.example/,');
|
||||
expect(lines[2]).toBe(',"has, comma",https://b.example/,');
|
||||
expect(lines[3]).toBe(',"has ""quote""",https://c.example/,');
|
||||
});
|
||||
|
||||
it('writes CRLF records and a BOM by default', () => {
|
||||
const csv = serializeCsv([{ title: 'a', url: 'https://a.example/' }]);
|
||||
expect(csv.startsWith(CSV_BOM)).toBe(true);
|
||||
expect(csv.endsWith('\r\n')).toBe(true);
|
||||
});
|
||||
|
||||
it('drops empty folders — the documented CSV loss', () => {
|
||||
const csv = serializeCsv([{ title: 'Empty', children: [] }], { bom: false });
|
||||
expect(csv.trim()).toBe(HEADER);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,289 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { BmParseError } from '@/lib/core/model';
|
||||
import { parseNetscapeHtml } from '@/lib/core/parse/netscape-html';
|
||||
import { escapeHtml, serializeNetscapeHtml } from '@/lib/core/serialize/netscape-html';
|
||||
|
||||
const CHROME = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
|
||||
<TITLE>Bookmarks</TITLE>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><H3 ADD_DATE="1751500000" LAST_MODIFIED="1751500001" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks bar</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://example.com/" ADD_DATE="1751500000">Example</A>
|
||||
<DT><H3 ADD_DATE="1751500000">Dev tools</H3>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://github.com/" ADD_DATE="1751500000">GitHub</A>
|
||||
</DL><p>
|
||||
</DL><p>
|
||||
<DT><H3>Other</H3>
|
||||
<DL><p></DL><p>
|
||||
</DL><p>`;
|
||||
|
||||
describe('parseNetscapeHtml — Chrome shape', () => {
|
||||
const result = parseNetscapeHtml(CHROME);
|
||||
|
||||
it('reads the toolbar folder and its nested children', () => {
|
||||
expect(result.roots).toHaveLength(2);
|
||||
const bar = result.roots[0];
|
||||
expect(bar?.title).toBe('Bookmarks bar');
|
||||
expect(bar?.toolbar).toBe(true);
|
||||
expect(bar?.addDate).toBe(1751500000);
|
||||
expect(bar?.lastModified).toBe(1751500001);
|
||||
expect(bar?.children).toHaveLength(2);
|
||||
expect(bar?.children?.[1]?.children?.[0]?.url).toBe('https://github.com/');
|
||||
});
|
||||
|
||||
it('preserves empty folders', () => {
|
||||
expect(result.roots[1]?.title).toBe('Other');
|
||||
expect(result.roots[1]?.children).toEqual([]);
|
||||
});
|
||||
|
||||
it('computes stats over the whole tree', () => {
|
||||
expect(result.stats).toEqual({ bookmarks: 2, folders: 3, maxDepth: 3 });
|
||||
});
|
||||
|
||||
it('marks non-toolbar folders by omitting the flag, not setting it false', () => {
|
||||
expect(Object.hasOwn(result.roots[1] ?? {}, 'toolbar')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseNetscapeHtml — tolerated shapes', () => {
|
||||
it('survives a <DD> between a folder and its child list (docs/04 §1.2)', () => {
|
||||
const withDd = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><H3>Folder</H3>
|
||||
<DD>a description that closes the DT and swallows the DL
|
||||
<DL><p>
|
||||
<DT><A HREF="https://kept.example/">Kept</A>
|
||||
</DL><p>
|
||||
</DL><p>`;
|
||||
const { roots, warnings } = parseNetscapeHtml(withDd);
|
||||
expect(roots[0]?.children?.[0]?.url).toBe('https://kept.example/');
|
||||
expect(warnings.map((w) => w.code)).toContain('DESCRIPTIONS_DROPPED');
|
||||
});
|
||||
|
||||
it('handles an explicit </DT> producing a sibling <DL> (docs/05 §1 case 3)', () => {
|
||||
const explicitClose = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><H3>Folder</H3></DT>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://sibling.example/">Sibling</A></DT>
|
||||
</DL><p>
|
||||
</DL><p>`;
|
||||
const { roots } = parseNetscapeHtml(explicitClose);
|
||||
expect(roots[0]?.children?.[0]?.url).toBe('https://sibling.example/');
|
||||
});
|
||||
|
||||
it('skips <HR> separators silently and keeps both neighbours (docs/04 §1.2)', () => {
|
||||
const withHr = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://a.example/">A</A>
|
||||
<HR>
|
||||
<DT><A HREF="https://b.example/">B</A>
|
||||
</DL><p>`;
|
||||
const { roots, warnings } = parseNetscapeHtml(withHr);
|
||||
expect(roots.map((r) => r.url)).toEqual(['https://a.example/', 'https://b.example/']);
|
||||
expect(warnings).toEqual([]);
|
||||
});
|
||||
|
||||
it('looks past a <DD> that has no nested <DL> to a later sibling list', () => {
|
||||
// Some exporters close the DD explicitly, so the DL lands after it rather
|
||||
// than inside it — nextDlFor must keep walking siblings.
|
||||
const ddThenDl = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><H3>Folder</H3>
|
||||
<DD>description</DD>
|
||||
<DL><p><DT><A HREF="https://after-dd.example/">After DD</A></DL><p>
|
||||
</DL><p>`;
|
||||
const { roots } = parseNetscapeHtml(ddThenDl);
|
||||
expect(roots[0]?.children?.[0]?.url).toBe('https://after-dd.example/');
|
||||
});
|
||||
|
||||
it('treats a folder followed straight by another entry as empty', () => {
|
||||
const emptyThenEntry = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><H3>Empty</H3></DT>
|
||||
<DT><A HREF="https://next.example/">Next</A>
|
||||
</DL><p>`;
|
||||
const { roots } = parseNetscapeHtml(emptyThenEntry);
|
||||
expect(roots[0]).toEqual({ title: 'Empty', children: [] });
|
||||
expect(roots[1]?.url).toBe('https://next.example/');
|
||||
});
|
||||
|
||||
it('skips an <A> with no usable HREF and warns', () => {
|
||||
const noHref = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A>No href at all</A>
|
||||
<DT><A HREF=" ">Blank href</A>
|
||||
<DT><A HREF="https://ok.example/">OK</A>
|
||||
</DL><p>`;
|
||||
const { roots, warnings } = parseNetscapeHtml(noHref);
|
||||
expect(roots).toHaveLength(1);
|
||||
expect(warnings.find((w) => w.code === 'MISSING_URL')?.count).toBe(2);
|
||||
});
|
||||
|
||||
it('falls back to the href when a bookmark has no text', () => {
|
||||
const noTitle = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p><DT><A HREF="https://untitled.example/"></A></DL><p>`;
|
||||
const { roots, warnings } = parseNetscapeHtml(noTitle);
|
||||
expect(roots[0]?.title).toBe('https://untitled.example/');
|
||||
expect(warnings.map((w) => w.code)).toContain('EMPTY_TITLE');
|
||||
});
|
||||
|
||||
it('ignores a <DT> that holds neither an <H3> nor an <A>', () => {
|
||||
const junk = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT>just text
|
||||
<DT><A HREF="https://ok.example/">OK</A>
|
||||
</DL><p>`;
|
||||
expect(parseNetscapeHtml(junk).roots).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('aggregates favicon warnings into a single entry', () => {
|
||||
const icons = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://a.example/" ICON="data:image/png;base64,AAA">A</A>
|
||||
<DT><A HREF="https://b.example/" ICON_URI="https://b.example/f.ico">B</A>
|
||||
</DL><p>`;
|
||||
const { warnings } = parseNetscapeHtml(icons);
|
||||
const favicon = warnings.filter((w) => w.code === 'FAVICONS_IGNORED');
|
||||
expect(favicon).toHaveLength(1);
|
||||
expect(favicon[0]?.count).toBe(2);
|
||||
});
|
||||
|
||||
it('ignores unknown Firefox/Safari/IE attributes silently', () => {
|
||||
const extras = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p>
|
||||
<DT><A HREF="https://a.example/" SHORTCUTURL="a" TAGS="x,y" LAST_CHARSET="UTF-8" LAST_VISIT="123">A</A>
|
||||
</DL><p>`;
|
||||
const { roots, warnings } = parseNetscapeHtml(extras);
|
||||
expect(roots[0]?.url).toBe('https://a.example/');
|
||||
expect(warnings.map((w) => w.code)).not.toContain('DESCRIPTIONS_DROPPED');
|
||||
});
|
||||
|
||||
it('reads sibling folders inside a normal wrapper <DL>', () => {
|
||||
const wrapped = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><H3>A</H3>
|
||||
<DL><p><DT><A HREF="https://a.example/">a</A></DL><p>
|
||||
<DT><H3>B</H3>
|
||||
<DL><p><DT><A HREF="https://b.example/">b</A></DL><p>
|
||||
</DL><p>`;
|
||||
const { roots } = parseNetscapeHtml(wrapped);
|
||||
expect(roots.map((r) => r.title)).toEqual(['A', 'B']);
|
||||
});
|
||||
|
||||
it('handles top-level folders with NO wrapper <DL> (Mozilla bug 801450)', () => {
|
||||
// The real Safari shape: DT>H3 sit directly under <body>. Taking "the first
|
||||
// outermost DL" here returns folder A's *inner* list, silently reporting a
|
||||
// clean parse of one bookmark and dropping A, B and b entirely.
|
||||
const safari = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<H1>Bookmarks</H1>
|
||||
<DT><H3>A</H3>
|
||||
<DL><p><DT><A HREF="https://a.example/">a</A></DL><p>
|
||||
<DT><H3>B</H3>
|
||||
<DL><p><DT><A HREF="https://b.example/">b</A></DL><p>`;
|
||||
const { roots, stats } = parseNetscapeHtml(safari);
|
||||
expect(roots.map((r) => r.title)).toEqual(['A', 'B']);
|
||||
expect(roots[1]?.children?.[0]?.url).toBe('https://b.example/');
|
||||
expect(stats).toEqual({ bookmarks: 2, folders: 2, maxDepth: 2 });
|
||||
});
|
||||
|
||||
it('handles a file that mixes a wrapper <DL> with loose top-level <DT>s', () => {
|
||||
const mixed = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<H1>Bookmarks</H1>
|
||||
<DL><p>
|
||||
<DT><H3>Bookmarks bar</H3>
|
||||
<DL><p><DT><A HREF="https://in.example/">in</A></DL><p>
|
||||
</DL><p>
|
||||
<DT><H3>Other Bookmarks</H3>
|
||||
<DL><p><DT><A HREF="https://out.example/">out</A></DL><p>`;
|
||||
const { roots } = parseNetscapeHtml(mixed);
|
||||
expect(roots.map((r) => r.title)).toEqual(['Bookmarks bar', 'Other Bookmarks']);
|
||||
});
|
||||
|
||||
it('does not emit a body-level child <DL> twice when </DT> is explicit', () => {
|
||||
// Here the folder's child list is ALSO a body child. Naively treating every
|
||||
// body-level DL as a root list would duplicate the subtree.
|
||||
const explicit = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DT><H3>X</H3></DT>
|
||||
<DL><p><DT><A HREF="https://once.example/">once</A></DL><p>`;
|
||||
const { roots, stats } = parseNetscapeHtml(explicit);
|
||||
expect(roots).toHaveLength(1);
|
||||
expect(roots[0]?.title).toBe('X');
|
||||
expect(stats).toEqual({ bookmarks: 1, folders: 1, maxDepth: 2 });
|
||||
});
|
||||
|
||||
it('treats ADD_DATE="0" as absent without warning (docs/05 §4)', () => {
|
||||
const zero = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p><DT><A HREF="https://a.example/" ADD_DATE="0">A</A></DL><p>`;
|
||||
const { roots, warnings } = parseNetscapeHtml(zero);
|
||||
expect(Object.hasOwn(roots[0] ?? {}, 'addDate')).toBe(false);
|
||||
expect(warnings.map((w) => w.code)).not.toContain('INVALID_DATE');
|
||||
});
|
||||
|
||||
it('returns an empty result for a doctype-only file, not a crash', () => {
|
||||
const { roots, warnings } = parseNetscapeHtml('<!DOCTYPE NETSCAPE-Bookmark-file-1>\n');
|
||||
expect(roots).toEqual([]);
|
||||
expect(warnings.map((w) => w.code)).toContain('NO_BOOKMARKS');
|
||||
});
|
||||
|
||||
it('keeps injected markup as inert text', () => {
|
||||
const hostile = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
|
||||
<DL><p><DT><A HREF="https://a.example/"><script>alert(1)</script></A></DL><p>`;
|
||||
const { roots } = parseNetscapeHtml(hostile);
|
||||
expect(roots[0]?.title).toBe('<script>alert(1)</script>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseNetscapeHtml — hard failures', () => {
|
||||
it('throws NOT_NETSCAPE when there is neither doctype nor <DL>', () => {
|
||||
expect(() => parseNetscapeHtml('<html><body><p>nope</p></body></html>')).toThrow(BmParseError);
|
||||
try {
|
||||
parseNetscapeHtml('<html><body><p>nope</p></body></html>');
|
||||
} catch (err) {
|
||||
expect((err as BmParseError).code).toBe('NOT_NETSCAPE');
|
||||
}
|
||||
});
|
||||
|
||||
it('throws TOO_DEEP past the depth cap', () => {
|
||||
const open = '<DL><p><DT><H3>f</H3>'.repeat(205);
|
||||
const close = '</DL><p>'.repeat(205);
|
||||
try {
|
||||
parseNetscapeHtml(`<!DOCTYPE NETSCAPE-Bookmark-file-1>${open}${close}`);
|
||||
expect.unreachable('should have thrown');
|
||||
} catch (err) {
|
||||
expect((err as BmParseError).code).toBe('TOO_DEEP');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('escapeHtml', () => {
|
||||
it('escapes exactly the four characters that can break text or an attribute', () => {
|
||||
expect(escapeHtml('a & b < c > d " e')).toBe('a & b < c > d " e');
|
||||
});
|
||||
|
||||
it('escapes & first so entities are not double-encoded into nonsense', () => {
|
||||
expect(escapeHtml('<')).toBe('&lt;');
|
||||
});
|
||||
|
||||
it('leaves single quotes alone — we only ever emit double-quoted attributes', () => {
|
||||
expect(escapeHtml("it's")).toBe("it's");
|
||||
});
|
||||
});
|
||||
|
||||
describe('round-trip HTML', () => {
|
||||
it('parse(serialize(parse(x))) is stable', () => {
|
||||
const once = parseNetscapeHtml(CHROME);
|
||||
const twice = parseNetscapeHtml(serializeNetscapeHtml(once.roots));
|
||||
expect(twice.roots).toEqual(once.roots);
|
||||
});
|
||||
|
||||
it('escapes and restores the four special characters', () => {
|
||||
const tree = [{ title: 'a & b < c > d " e', url: 'https://x.test/?a=1&b=2' }];
|
||||
const back = parseNetscapeHtml(serializeNetscapeHtml(tree));
|
||||
expect(back.roots).toEqual(tree);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { BookmarkNode } from '@/lib/core/model';
|
||||
import { parseBmJson } from '@/lib/core/parse/bm-json';
|
||||
import { parseCsv } from '@/lib/core/parse/csv';
|
||||
import { parseNetscapeHtml } from '@/lib/core/parse/netscape-html';
|
||||
import { serializeBmJson } from '@/lib/core/serialize/bm-json';
|
||||
import { serializeCsv } from '@/lib/core/serialize/csv';
|
||||
import { serializeNetscapeHtml } from '@/lib/core/serialize/netscape-html';
|
||||
import { generateTree, makeRng, project, type RoundTripFormat } from '../../helpers/tree';
|
||||
|
||||
/**
|
||||
* The flagship suite — docs/11 §3.
|
||||
*
|
||||
* `parse(serialize(t)).roots deepEquals project(t, format)`, plus
|
||||
* `warnings.length === 0`, so a parser that silently degrades cannot pass.
|
||||
*/
|
||||
const ROUND_TRIPS: Record<
|
||||
RoundTripFormat,
|
||||
{
|
||||
serialize: (t: readonly BookmarkNode[]) => string;
|
||||
parse: (s: string) => ReturnType<typeof parseBmJson>;
|
||||
}
|
||||
> = {
|
||||
'bm-json': {
|
||||
serialize: (t) => serializeBmJson(t, { version: '0.1.0', exportedAt: '2026-07-25T00:00:00Z' }),
|
||||
parse: parseBmJson,
|
||||
},
|
||||
'netscape-html': { serialize: serializeNetscapeHtml, parse: parseNetscapeHtml },
|
||||
csv: { serialize: (t) => serializeCsv(t), parse: parseCsv },
|
||||
};
|
||||
|
||||
const FORMATS = Object.keys(ROUND_TRIPS) as RoundTripFormat[];
|
||||
|
||||
const SAMPLE: BookmarkNode[] = [
|
||||
{
|
||||
title: 'Bookmarks bar',
|
||||
toolbar: true,
|
||||
addDate: 1751500000,
|
||||
lastModified: 1751500001,
|
||||
children: [
|
||||
{ title: 'Example', url: 'https://example.com/', addDate: 1751500000 },
|
||||
{
|
||||
title: 'Dev tools',
|
||||
addDate: 1751500002,
|
||||
children: [{ title: 'GitHub', url: 'https://github.com/', addDate: 1751500003 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: 'Other',
|
||||
children: [{ title: 'Nested only', children: [] }],
|
||||
},
|
||||
];
|
||||
|
||||
describe.each(FORMATS)('round-trip: %s', (format) => {
|
||||
const { serialize, parse } = ROUND_TRIPS[format];
|
||||
|
||||
it('reproduces the sample tree under the documented projection', () => {
|
||||
const result = parse(serialize(SAMPLE));
|
||||
expect(result.roots).toEqual(project(SAMPLE, format));
|
||||
});
|
||||
|
||||
it('emits no warnings for a clean tree', () => {
|
||||
// CSV drops the sample's empty folders, which legitimately yields nothing
|
||||
// to warn about; HTML/JSON must be silent too.
|
||||
expect(parse(serialize(SAMPLE)).warnings).toEqual([]);
|
||||
});
|
||||
|
||||
it('survives 200 seeded random trees', () => {
|
||||
for (let seed = 1; seed <= 200; seed++) {
|
||||
const tree = generateTree(makeRng(seed));
|
||||
const expected = project(tree, format);
|
||||
let actual: BookmarkNode[];
|
||||
try {
|
||||
actual = parse(serialize(tree)).roots;
|
||||
} catch (err) {
|
||||
throw new Error(`seed ${seed} (${format}) threw: ${String(err)}`);
|
||||
}
|
||||
expect(actual, `seed ${seed} (${format})`).toEqual(expected);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('round-trip: cross-format', () => {
|
||||
it('HTML → JSON → CSV keeps every bookmark URL that CSV can carry', () => {
|
||||
const viaHtml = parseNetscapeHtml(serializeNetscapeHtml(SAMPLE)).roots;
|
||||
const viaJson = parseBmJson(
|
||||
serializeBmJson(viaHtml, { version: '0.1.0', exportedAt: '2026-07-25T00:00:00Z' }),
|
||||
).roots;
|
||||
const viaCsv = parseCsv(serializeCsv(viaJson)).roots;
|
||||
|
||||
const urls = (nodes: readonly BookmarkNode[]): string[] => {
|
||||
const out: string[] = [];
|
||||
const walk = (list: readonly BookmarkNode[]): void => {
|
||||
for (const n of list) {
|
||||
if (n.url !== undefined) out.push(n.url);
|
||||
walk(n.children ?? []);
|
||||
}
|
||||
};
|
||||
walk(nodes);
|
||||
return out.sort();
|
||||
};
|
||||
|
||||
expect(urls(viaCsv)).toEqual(urls(SAMPLE));
|
||||
});
|
||||
|
||||
it('CSV re-imports its own export, BOM and all', () => {
|
||||
const csv = serializeCsv(SAMPLE);
|
||||
expect(csv.charCodeAt(0)).toBe(0xfeff);
|
||||
expect(parseCsv(csv).roots).toEqual(project(SAMPLE, 'csv'));
|
||||
});
|
||||
|
||||
it('CSV round-trips with the semicolon delimiter too', () => {
|
||||
const csv = serializeCsv(SAMPLE, { delimiter: ';' });
|
||||
expect(parseCsv(csv).roots).toEqual(project(SAMPLE, 'csv'));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { BookmarkNode } from '@/lib/core/model';
|
||||
import {
|
||||
escapeMarkdown,
|
||||
formatUrl,
|
||||
type MarkdownStyle,
|
||||
serializeMarkdown,
|
||||
} from '@/lib/core/serialize/markdown';
|
||||
|
||||
const TREE: BookmarkNode[] = [
|
||||
{
|
||||
title: 'Bookmarks bar',
|
||||
children: [
|
||||
{ title: 'Dev tools', children: [{ title: 'GitHub', url: 'https://github.com/' }] },
|
||||
{ title: 'Example', url: 'https://example.com/' },
|
||||
],
|
||||
},
|
||||
{ title: 'Loose', url: 'https://loose.example/' },
|
||||
];
|
||||
|
||||
describe('serializeMarkdown — nested (default)', () => {
|
||||
const md = serializeMarkdown(TREE, { date: '2026-07-25' });
|
||||
|
||||
it('renders a heading and an indented list', () => {
|
||||
expect(md).toBe(
|
||||
[
|
||||
'# Bookmarks — 2026-07-25',
|
||||
'',
|
||||
'- **Bookmarks bar**',
|
||||
' - **Dev tools**',
|
||||
' - [GitHub](https://github.com/)',
|
||||
' - [Example](https://example.com/)',
|
||||
'- [Loose](https://loose.example/)',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('serializeMarkdown — flat', () => {
|
||||
it('uses ## per top-level folder and flattens the links beneath it', () => {
|
||||
const style: MarkdownStyle = 'flat';
|
||||
const md = serializeMarkdown(TREE, { date: '2026-07-25', style });
|
||||
expect(md).toBe(
|
||||
[
|
||||
'# Bookmarks — 2026-07-25',
|
||||
'',
|
||||
'- [Loose](https://loose.example/)',
|
||||
'',
|
||||
'## Bookmarks bar',
|
||||
'',
|
||||
'- [GitHub](https://github.com/)',
|
||||
'- [Example](https://example.com/)',
|
||||
'',
|
||||
].join('\n'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('markdown escaping', () => {
|
||||
it('escapes link syntax in titles', () => {
|
||||
expect(escapeMarkdown('a [b] (c) \\d')).toBe('a \\[b\\] \\(c\\) \\\\d');
|
||||
});
|
||||
|
||||
it('angle-wraps URLs containing parens or spaces', () => {
|
||||
expect(formatUrl('https://a.example/x')).toBe('https://a.example/x');
|
||||
expect(formatUrl('https://a.example/a(b)')).toBe('<https://a.example/a(b)>');
|
||||
expect(formatUrl('https://a.example/a b')).toBe('<https://a.example/a b>');
|
||||
});
|
||||
|
||||
it('percent-encodes what CommonMark forbids inside <...>', () => {
|
||||
// An unencoded < > or line ending inside the angle-bracket form makes the
|
||||
// whole link render as literal text.
|
||||
expect(formatUrl('https://a.example/<x>')).toBe('<https://a.example/%3Cx%3E>');
|
||||
expect(formatUrl('https://a.example/a\r\nb')).toBe('<https://a.example/a%0D%0Ab>');
|
||||
expect(formatUrl('https://a.example/<')).not.toContain('/<');
|
||||
});
|
||||
|
||||
it('keeps a title with brackets from breaking the link', () => {
|
||||
const md = serializeMarkdown([{ title: '[x](y)', url: 'https://a.example/(z)' }], {
|
||||
date: '2026-07-25',
|
||||
});
|
||||
expect(md).toContain('- [\\[x\\]\\(y\\)](<https://a.example/(z)>)');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { millisToSeconds, normalizeEpochSeconds } from '@/lib/core/timestamps';
|
||||
|
||||
describe('normalizeEpochSeconds — magnitude table (docs/05 §4)', () => {
|
||||
it('keeps seconds', () => {
|
||||
expect(normalizeEpochSeconds('1751500000')).toEqual({ seconds: 1751500000, invalid: false });
|
||||
});
|
||||
|
||||
it('converts milliseconds', () => {
|
||||
expect(normalizeEpochSeconds(1_751_500_000_000)).toEqual({
|
||||
seconds: 1751500000,
|
||||
invalid: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('converts microseconds', () => {
|
||||
expect(normalizeEpochSeconds(1_751_500_000_000_000)).toEqual({
|
||||
seconds: 1751500000,
|
||||
invalid: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats bucket boundaries as non-overlapping', () => {
|
||||
// 1e11 is the first millisecond value; 1e11-1 is still seconds.
|
||||
expect(normalizeEpochSeconds(1e11 - 1).seconds).toBe(Math.round(1e11 - 1));
|
||||
expect(normalizeEpochSeconds(1e11).seconds).toBe(1e8);
|
||||
expect(normalizeEpochSeconds(1e14).seconds).toBe(1e8);
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeEpochSeconds — absent vs invalid', () => {
|
||||
it('treats a missing attribute as absent, silently', () => {
|
||||
expect(normalizeEpochSeconds(null)).toEqual({ seconds: undefined, invalid: false });
|
||||
expect(normalizeEpochSeconds(undefined)).toEqual({ seconds: undefined, invalid: false });
|
||||
expect(normalizeEpochSeconds('')).toEqual({ seconds: undefined, invalid: false });
|
||||
});
|
||||
|
||||
it('treats 0 as absent, silently — Chrome writes ADD_DATE="0" routinely', () => {
|
||||
expect(normalizeEpochSeconds('0')).toEqual({ seconds: undefined, invalid: false });
|
||||
expect(normalizeEpochSeconds(0)).toEqual({ seconds: undefined, invalid: false });
|
||||
});
|
||||
|
||||
it('accepts dates Chrome accepts, down to 1 second past the epoch', () => {
|
||||
// A 1e8 floor would drop 1970-1973, which Chrome's own importer takes.
|
||||
expect(normalizeEpochSeconds(1).seconds).toBe(1);
|
||||
expect(normalizeEpochSeconds(86_400).seconds).toBe(86_400);
|
||||
});
|
||||
|
||||
it('flags garbage as invalid so the caller can warn', () => {
|
||||
expect(normalizeEpochSeconds('not a number').invalid).toBe(true);
|
||||
expect(normalizeEpochSeconds(-5).invalid).toBe(true);
|
||||
expect(normalizeEpochSeconds(Number.NaN).invalid).toBe(true);
|
||||
expect(normalizeEpochSeconds(1e18).invalid).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('millisToSeconds — the chrome.bookmarks adapter conversion', () => {
|
||||
it('divides by 1000 and rounds', () => {
|
||||
expect(millisToSeconds(1_751_500_000_499)).toBe(1751500000);
|
||||
});
|
||||
|
||||
it('returns undefined for absent or unusable values', () => {
|
||||
expect(millisToSeconds(undefined)).toBeUndefined();
|
||||
expect(millisToSeconds(0)).toBeUndefined();
|
||||
expect(millisToSeconds(-1)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user