# Design ## Stack - TypeScript everywhere. One npm package: - `src/client` — React 18 single-page app built by Vite 6. - `src/worker` — the Cloudflare Worker (JSON API). - `src/shared` — code used by both: parsing, paths and link rules, link rewriting, search, merge, dates, templates, fuzzy match, settings. - Editor: CodeMirror 6 (`@codemirror/state`, `view`, `commands`, `language`, `lang-markdown`, `autocomplete`, `search`, `@lezer/highlight`). - Reading view and embeds: `markdown-it` with `html: false`. - Properties: `yaml` (parse and stringify). Graph: `d3-force` on a canvas. - Tests: Vitest (unit, `tests/`), Playwright (end to end, `e2e/`). - Wrangler 4 for dev, migrations, types and deploy. - Read `spekkr.inputs.json` in `src/shared/settings.ts` (imported by both sides, bundled at build time): `appName`, `accentColor`, `seedDemo`. Vite replaces `%APP_NAME%` in `index.html`; an inline script in `index.html` sets `data-theme` from `localStorage.theme` before paint. ## Cloudflare config `wrangler.jsonc`: ```jsonc { "$schema": "node_modules/wrangler/config-schema.json", "name": "linked-notes", "main": "src/worker/index.ts", "compatibility_date": "2026-11-16", "assets": { "directory": "./dist", "binding": "ASSETS", "not_found_handling": "single-page-application", "run_worker_first": ["/api/*"] }, "d1_databases": [ { "binding": "DB", "database_name": "linked-notes", // Local dev works with this placeholder; replace it before deploying. "database_id": "00000000-0000-0000-0000-000000000000", "migrations_dir": "migrations" } ], "r2_buckets": [{ "binding": "FILES", "bucket_name": "linked-notes-files" }], "vars": { "NOW": "", "TEST_CLOCK": "0", "ALLOW_SIGNUP": "" }, "observability": { "enabled": true, "traces": { "enabled": true } } } ``` When `cloudflare_access` is on, also add `"workers_dev": false` and `"preview_urls": false` (the site is then reached only through its custom domain, behind Cloudflare Access). `src/shared/settings.ts` reads `spekkr.inputs.json`: `appName`, `accentColor`, `seedDemo`, `access` (one of `only_me`, `invite_only`, `open`; anything else means `only_me`) and `cloudflareAccess`. Scripts: | script | command | |---|---| | `build` | `vite build` | | `db:migrate:local` | `wrangler d1 migrations apply DB --local` | | `dev` | `npm run build && npm run db:migrate:local && wrangler dev` | | `test` | `vitest run` | | `e2e` | `playwright test` | | `deploy` | `npm run build && wrangler deploy` | | `types` | `wrangler types --strict-vars=false` | Two tsconfigs: `tsconfig.json` (client, shared, tests, e2e; DOM libs) and `tsconfig.worker.json` (worker + shared + `worker-configuration.d.ts`, `"types": []`, no DOM, no Node types) so Node-only APIs fail to type-check in the Worker. ## Deploy Once, with a Cloudflare account: `npx wrangler login`; `npx wrangler d1 create linked-notes` and put the id in `wrangler.jsonc`; `npx wrangler r2 bucket create linked-notes-files`; `npx wrangler d1 migrations apply DB --remote`; then `npm run deploy`. Leave `NOW` empty and `TEST_CLOCK` `"0"` in production; `ALLOW_SIGNUP` empty follows `access`. The README has these sections: run it on your computer (with the demo login), tests, "Who can sign up" (the three modes, the owner, invites, `ALLOW_SIGNUP`), deploy (the steps above), and "Optional: Cloudflare Access in front of the site" with these numbered steps (part of the deploy when `cloudflare_access` is on): 1. Serve the app on a custom domain in a zone on the account: `"routes": [{ "pattern": "notes.example.com", "custom_domain": true }]`. 2. Set `"workers_dev": false` and `"preview_urls": false`, deploy, and check in Workers & Pages > the Worker > Settings > Domains & Routes that workers.dev and Preview URLs are disabled. 3. Zero Trust > Access controls > Applications > Add an application > Self-hosted; name it; public hostname `notes.example.com`; save. 4. Add an Allow policy: Include > Emails > the allowed addresses (or Emails ending in `@domain`). An application with no policy lets nobody in. 5. Keep One-time PIN enabled as a login method (Zero Trust > Integrations > Identity providers) so allowed people get a code by email; choose a session duration. 6. Check in a private window: the Access email-and-code step comes first, then the app's own sign-in. ## Data model `migrations/0001_init.sql`: ```sql -- Linked notes: accounts, vaults, files and the link/tag/search index. CREATE TABLE users ( id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, -- stored lower-case name TEXT NOT NULL, password_hash TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE TABLE sessions ( token_hash TEXT PRIMARY KEY, -- SHA-256 hex of the cookie token user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires_at TEXT NOT NULL ); CREATE TABLE vaults ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, name TEXT NOT NULL, seq INTEGER NOT NULL DEFAULT 0, -- bumped by every change; the sync cursor settings TEXT NOT NULL DEFAULT '{}', -- JSON, see design.md "Vault settings" created_at TEXT NOT NULL, UNIQUE (user_id, name) ); CREATE TABLE files ( id INTEGER PRIMARY KEY, vault_id INTEGER NOT NULL REFERENCES vaults(id) ON DELETE CASCADE, path TEXT NOT NULL, -- "Folder/Note.md"; folders have no extension path_lc TEXT NOT NULL, key TEXT NOT NULL, -- lower-case last segment without ".md" kind TEXT NOT NULL CHECK (kind IN ('note','folder','attachment')), content TEXT, -- notes only size INTEGER NOT NULL DEFAULT 0, mime TEXT, -- attachments only r2_key TEXT, -- attachments only version INTEGER NOT NULL DEFAULT 1, rev TEXT NOT NULL, -- random token of the last write (guards index writes) seq INTEGER NOT NULL, ctime TEXT NOT NULL, mtime TEXT NOT NULL, deleted_at TEXT -- set while in the trash ); CREATE UNIQUE INDEX files_live_path ON files (vault_id, path_lc) WHERE deleted_at IS NULL; CREATE INDEX files_key ON files (vault_id, key); CREATE INDEX files_seq ON files (vault_id, seq); CREATE TABLE links ( id INTEGER PRIMARY KEY, vault_id INTEGER NOT NULL, source_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE, kind TEXT NOT NULL, -- link | embed format TEXT NOT NULL, -- wiki | md linkpath TEXT NOT NULL, subpath TEXT NOT NULL, display TEXT, line INTEGER NOT NULL, prop TEXT, -- property name when the link is in frontmatter target_key TEXT NOT NULL, target_id INTEGER -- NULL while unresolved ); CREATE INDEX links_source ON links (source_id); CREATE INDEX links_target ON links (vault_id, target_id); CREATE INDEX links_key ON links (vault_id, target_key); CREATE TABLE tags (vault_id INTEGER NOT NULL, file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE, tag TEXT NOT NULL, tag_lc TEXT NOT NULL, line INTEGER NOT NULL); CREATE INDEX tags_file ON tags (file_id); CREATE INDEX tags_vault ON tags (vault_id, tag_lc); CREATE TABLE headings (file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE, vault_id INTEGER NOT NULL, level INTEGER NOT NULL, text TEXT NOT NULL, line INTEGER NOT NULL); CREATE INDEX headings_file ON headings (file_id); CREATE TABLE blocks (file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE, block_id TEXT NOT NULL, line INTEGER NOT NULL, text TEXT NOT NULL); CREATE INDEX blocks_file ON blocks (file_id); CREATE TABLE aliases (vault_id INTEGER NOT NULL, file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE, alias TEXT NOT NULL, alias_lc TEXT NOT NULL); CREATE INDEX aliases_file ON aliases (file_id); CREATE INDEX aliases_vault ON aliases (vault_id, alias_lc); CREATE TABLE props (vault_id INTEGER NOT NULL, file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE, key TEXT NOT NULL, key_lc TEXT NOT NULL, value TEXT NOT NULL); CREATE INDEX props_file ON props (file_id); CREATE INDEX props_vault ON props (vault_id, key_lc); CREATE TABLE prop_types (vault_id INTEGER NOT NULL REFERENCES vaults(id) ON DELETE CASCADE, key_lc TEXT NOT NULL, type TEXT NOT NULL, PRIMARY KEY (vault_id, key_lc)); CREATE TABLE bookmarks ( id INTEGER PRIMARY KEY, vault_id INTEGER NOT NULL REFERENCES vaults(id) ON DELETE CASCADE, parent_id INTEGER REFERENCES bookmarks(id) ON DELETE CASCADE, position REAL NOT NULL, type TEXT NOT NULL CHECK (type IN ('group','file','folder','search','heading','block','graph')), title TEXT, path TEXT, subpath TEXT, query TEXT ); CREATE INDEX bookmarks_vault ON bookmarks (vault_id); -- Full-text index of note names and bodies. rowid = files.id. Trigram tokens give substring matches. CREATE VIRTUAL TABLE notes_fts USING fts5 (name, body, vault_id UNINDEXED, tokenize = 'trigram'); ``` `migrations/0002_access.sql` (R24; also upgrades an existing database): ```sql ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'member'; -- 'owner' | 'member' | 'demo' ALTER TABLE users ADD COLUMN disabled_at TEXT; -- set when the owner removes access UPDATE users SET role = 'demo' WHERE email = 'sam@example.com'; UPDATE users SET role = 'owner' WHERE id = (SELECT MIN(id) FROM users WHERE role = 'member'); CREATE UNIQUE INDEX users_one_owner ON users(role) WHERE role = 'owner'; CREATE TABLE invites ( id INTEGER PRIMARY KEY, email TEXT NOT NULL, -- lower-case token_hash TEXT NOT NULL UNIQUE, -- SHA-256 hex of the link token created_by INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, created_at TEXT NOT NULL, expires_at TEXT NOT NULL, -- created_at + 7 days used_at TEXT ); CREATE INDEX invites_email ON invites(email); ``` Sign-up policy (`signupPolicy(env, req)` in the Worker): mode = `access` (or the `test_access` cookie when `TEST_CLOCK` is `"1"`); override = `ALLOW_SIGNUP` (or `test_allow_signup`, where `auto` means empty); `firstAccount` = no row with role `owner`. `signup` is `closed` when the override is `"0"`; else `open` when the override is `"1"`, or `firstAccount`, or mode is `open`; else `invite` for `invite_only` and `closed` for `only_me`. The account insert is `INSERT INTO users (...) SELECT ?, ..., CASE WHEN EXISTS (owner) THEN 'member' ELSE 'owner' END WHERE ? = 0 OR NOT EXISTS (owner)`, with the flag set to 1 when only an owner may be created (mode not `open`, no override `"1"`, no invite), and 0 changes means 403 "Sign-up is closed on this site". An invite is marked used (`UPDATE ... WHERE used_at IS NULL AND expires_at > now`, must change one row) before the account is inserted. Sessions of a person whose access is removed are deleted, and session lookups require `disabled_at IS NULL`. Notes: - `files.key` is the lower-cased name without `.md` (for a note) or the lower-cased file name (for an attachment). Links store `target_key`, the same thing computed from their link path, so "which links might point at this name" is one indexed lookup. - `files.version` goes up by one on every content save or move. `files.seq` is the vault `seq` at the file's last change (sync cursor). - `files.rev` is a random token written by each change. Index rows for a file are written in the same D1 batch as the change, and each index statement is guarded with `WHERE (SELECT rev FROM files WHERE id=?)=?`, so if two saves race, only the index of the winning write survives. - Deleted files keep their row with `deleted_at` set (the trash). Their index rows are removed. Purging deletes the row and, for attachments, the R2 object. - `props.value` is the JSON of the property's value. `prop_types` holds the chosen type per property name per vault; when absent the type is inferred (array → list, number → number, boolean → checkbox, `YYYY-MM-DD` → date, `YYYY-MM-DDTHH:mm` → datetime, else text; `tags` is always tags, `aliases` and `cssclasses` are lists). - `notes_fts` uses the trigram tokenizer (substring matching, any language). `rowid` is `files.id`. Attachments are not in it. ## Vault settings Stored as JSON in `vaults.settings`; the server fills in defaults and drops unknown keys or bad values (`cleanSettings`): | key | default | values | |---|---|---| | `newNoteLocation` | `root` | `root`, `current`, `folder` | | `newNoteFolder` | `""` | folder path | | `attachmentLocation` | `folder` | `root`, `current`, `folder`, `subfolder` | | `attachmentFolder` | `Attachments` | folder path (or subfolder name) | | `linkFormat` | `shortest` | `shortest`, `relative`, `absolute` | | `useWikilinks` | `true` | | | `autoUpdateLinks` | `true` | | | `defaultMode` | `live` | `live`, `source`, `reading` | | `propertiesInDocument` | `visible` | `visible`, `hidden`, `source` | | `readableLineLength` | `true` | | | `deleteBehavior` | `trash` | `trash`, `permanent` | | `dailyFolder` | `""` | | | `dailyFormat` | `YYYY-MM-DD` | date format | | `dailyTemplate` | `""` | note path | | `openDailyOnStart` | `false` | | | `templatesFolder` | `Templates` | | | `templateDateFormat` | `YYYY-MM-DD` | | | `templateTimeFormat` | `HH:mm` | | | `hotkeys` | `{}` | command id → combo (`""` = none) | | `pinnedCommands` | `[]` | up to 20 command ids | Device-only state lives in `localStorage`: `theme`, `font-size`, `ws:` (workspace layout), `graph::global|local`, `recent-commands`, recent searches, explorer sort, `lastVault`. The client applies settings changes at once and rolls back if the server refuses. ## Parsing (src/shared/parse.ts) `parseNote(text)` returns frontmatter, headings, blocks, links, tags, tasks, aliases and line offsets. Rules: - **Frontmatter**: only when the very first line is `---`; ends at the next line that is `---` (or `...`). Parsed with `yaml`; a parse error or a non-object marks it invalid, and invalid frontmatter contributes nothing. - **Masked regions**: fenced code blocks (``` or ~~~, until the same fence), inline code spans, and `%% ... %%` comments (can span lines) are ignored for links, tags, headings and blocks. - **Headings**: ATX `#`–`######` followed by a space. A trailing block id is not part of the text. - **Blocks**: a line ending in ` ^id` (letters, digits, `-`) gives that id to the paragraph or list item it ends. A line holding only `^id` gives the id to the block just above it (one blank line between is allowed). - **Wikilinks**: `[[inner]]`, embed when preceded by `!`. `inner` splits at the first unescaped `|` into target and display; `\|` (as in tables) also splits. The target splits at the first `#` into link path and subpath. A subpath is a chain of headings `#A#B` or a block `#^id`. - **Markdown links**: `[text](dest)` and `![alt](dest)` where dest is not a URL with a scheme; dest is percent-decoded; `` allowed. `|300` or `|300x200` at the end of an embed's display/alt text is a size. - **Links in properties**: string values (also inside lists) that are exactly `[[...]]` are links with `prop` set to the property name. - **Tags**: see R10; `TAG_RE = /(^|[\s(,;])#([\p{L}\p{N}\p{Extended_Pictographic}_\-/]+)/gu`, must contain a character that is not a digit or `/`, not in headings' leading `#`s, not inside links/URLs/masked regions. Plus each entry of the `tags` property (with or without `#`, comma or space separated strings allowed). - **Tasks**: list items `- [ ]`, `* [x]`, `1. [ ]`; any character other than space in the brackets counts as done. - `resolveSubpath(note, "#A#B" | "#^id")` gives the line range: a heading section runs to the next heading of the same or higher level; nested headings must appear in order; heading text compares after removing `# | ^ : [ ] %`, collapsing spaces and ignoring case. Live preview and the properties block: the editor hides the block with a CodeMirror `StateField` holding one block `Decoration.replace` from 0 to the end of the closing `---` line. It is computed when the editor is created and on every document change, reconfigure and refresh (so it never depends on where the cursor is), and an `EditorState.transactionFilter` moves an empty cursor that would land before the body start to the body start. The editor is created with its selection at the body start. Source mode and "Properties in document: Source" skip both. ## Link rules (src/shared/paths.ts) `resolveLink(linkpath, sourcePath, files)`: 1. Empty link path (`[[#Heading]]`) is the source note. 2. A link path starting `./` or `../` is joined to the source note's folder and normalised; it matches that exact path only. 3. Otherwise, candidate names are `lp + ".md"` and `lp` (or just `lp` if it already ends in `.md`). Notes may omit `.md`; every other file needs its extension. Matching ignores case. Leading `/` is ignored. 4. An exact vault path match wins. 5. Else the same path inside the source note's folder. 6. Else every file whose path ends with `/` + candidate: the one with the fewest folders, then the shortest path, then A→Z. 7. Else the link is unresolved. `linktextFor(target, source, allPaths, format)`: - `shortest`: the name (without `.md` for notes) when no other file in the vault has the same name (ignoring case), else the full vault path without `.md`. - `relative`: path from the source note's folder, starting `./` or `../`. - `absolute`: full vault path without `.md`. Markdown links percent-encode each path segment and keep `.md`. **Rewrite on move** (`rewriteLinks`, `src/shared/rewrite.ts`): for each link in each note that could be affected (notes whose links resolved to a moved file, plus the moved notes themselves), compare where it resolved before the move with where its text resolves after. If it pointed at a moved file, or it would no longer resolve to the same file, write a new link to the same file: same kind (wiki/md), same embed `!`, same subpath and display text, and the same form (`./`/`../` → relative, contains `/` → absolute, bare name → vault link format). Unresolved links are left alone. Edits are applied from the end of the text backwards. **Server move algorithm** (`Vault.move`): validate the new path, refuse a taken path or a folder into itself; collect every moved file (the file, or the folder and everything under it); collect affected notes; compute new texts; then D1 batches of at most 400 statements (normally just one): bump `seq`, update paths (in two steps through a temporary prefix to dodge the unique index), write rewritten texts with `version+1`, re-index changed notes, and re-resolve links whose `target_key` matches an old or new name, and move bookmarks that point at moved paths. Returns `{ file, updatedNotes, updatedLinks }`. `dryRun: true` returns the counts only. `updateLinks: false` skips rewriting. ## Search (src/shared/search.ts) Grammar (case-insensitive keywords): ``` query := or or := and ("OR" and)* and := unary+ -- juxtaposition is AND unary := "-" unary | primary primary := "(" or ")" | OPERATOR ":" (primary) -- file: path: content: tag: line: block: -- section: task: task-todo: task-done: -- match-case: ignore-case: | "[" key (":" value)? "]" -- value: "null", ">N", "=N", "<=N", or a primary | "\"" phrase "\"" | "/" regex "/" | word ``` - A bare word or phrase matches the note text or its path. `file:` matches the file name, `path:` the full path, `content:` the text only. `tag:` matches a tag or any tag nested under it (`tag:#idea` matches `#idea/later`), `#` optional. `line:`, `block:`, `section:` require all inner terms within one line / one block (paragraph or list item) / one heading section. `task:` searches task lines; `task-todo:`/`task-done:` only unfinished/finished ones. `[key]` means the property exists, `[key:null]` that it is empty, `[key:value]` matches the value (lists match any item), `[key:>3]` compares numbers. - Case: ignore case unless the Match case toggle or `match-case:` is on. - Errors (`QueryError`) are shown in the search pane instead of results: "A bracket is not closed", "A bracket is closed but was never opened", "A property filter is missing its closing ]", "A property filter needs a property name", "A property filter is missing its value", "Something is missing around OR or a bracket", "That regular expression is not valid", and "Unexpected …" for any other stray token. - `requiredTerms(ast)`: words and phrases that every match must contain (inside ANDs only, not under `-` or `OR`), used to build an FTS5 query of quoted terms of 3+ characters. If there are none the Worker scans every live note of the vault. - Each result returns up to 20 matched lines with `[start, end]` ranges for highlighting, and `explain(ast)` gives the plain-language reading used by "Explain search term". ## Sync protocol - `GET /api/vaults/:v/changes?since=N` → `{ seq, files: FileMeta[] }` with every file (including trashed ones, `deleted: true`) whose `seq > N`. The client applies them, and for open notes whose `version` moved on fetches the new text: if the note has no unsaved edits the editor shows the new text; otherwise the next save handles it as below. - `PUT /files/:id/content { content, baseVersion }`: the Worker runs a batch `[bump seq, UPDATE files SET content=?, version=version+1, ... WHERE id=? AND version=?, ...guarded index writes]` and checks the update's `changes`. 0 changes → 409 `{ error: "This note changed on another device", current: { ...meta, content } }`. - Client on 409: `merge3(base, mine, theirs)` (line-based diff3 over LCS): non-overlapping changes merge; identical changes merge; anything else is a conflict. Clean → save the merged text against the new version. Conflict → keep theirs in the note, create ` (conflict YYYYMMDDHHmm).md` (app clock, browser zone) with mine, toast. - 404 on save → create a free-named note in the same folder with the text. - Network failure → status "Offline – ...", retry every 5 s; other errors → "Not saved – retrying". ## API JSON in and out (`content-type: application/json`) except uploads (raw body) and `raw/:id`. Errors are `{ error, fields? }` with 400/401/403/404/ 409/413/415. `FileMeta = { id, path, kind, size, mime, version, seq, ctime, mtime, deleted, aliases }`. | method | path | does | |---|---|---| | GET | `/api/now` | `{ now }` (frozen/test clock aware) | | GET | `/api/config` | no sign-in; `{ access, signup: "open"\|"invite"\|"closed", firstAccount }` (R24) | | POST | `/api/auth/signup` | `{ name, email, password, invite? }` → session, "My notes" vault with Welcome; `{ id, name, email, role }`; 403 when closed or the invite is missing/bad | | POST | `/api/auth/login` | `{ email, password }`; 403 "This account no longer has access to this site" when removed | | POST | `/api/auth/logout` | | | GET/PATCH | `/api/me` | `{ id, email, name, role }`; PATCH `{ name }` | | GET | `/api/invites/check?token=` | no sign-in; `{ email }` or 404 "This invite link is not valid or has expired" | | GET | `/api/people` | owner only; `{ members: [{ id, name, email, role, createdAt, removed }], invites: [{ id, email, createdAt, expiresAt }] }` (pending only; demo account left out) | | POST | `/api/invites` | owner only, `invite_only` only; `{ email }` → 201 `{ id, email, expiresAt, link }`; replaces a pending invite to the same email | | DELETE | `/api/invites/:id` | owner only; revoke a pending invite | | POST | `/api/people/:id/access` | owner only; `{ access: false }` removes access (and sessions), `{ access: true }` gives it back; not for the owner | | POST | `/api/me/password` | `{ current, next }` | | GET/POST | `/api/vaults` | list; create `{ name }` (1–60, unique per person) | | PATCH | `/api/vaults/:v` | `{ name?, settings? }` (settings patch, merged) | | DELETE | `/api/vaults/:v` | `{ confirm: }`; not the last one | | GET | `/api/vaults/:v/tree` | `{ seq, files }` live files | | GET | `/api/vaults/:v/changes?since=` | see Sync | | GET | `/api/vaults/:v/files/:id` | meta + `content` for notes | | POST | `/api/vaults/:v/notes` | `{ path, content? }` → 201; creates missing folders; 409 if taken | | POST | `/api/vaults/:v/folders` | `{ path }` | | PUT | `/api/vaults/:v/files/:id/content` | `{ content, baseVersion }` | | POST | `/api/vaults/:v/files/:id/move` | `{ path, updateLinks?, dryRun? }` | | DELETE | `/api/vaults/:v/files/:id` | to the trash, or deletes for good when the vault setting `deleteBehavior` is `permanent` | | GET | `/api/vaults/:v/trash` | trashed files (top-level of each deletion) | | POST | `/api/vaults/:v/trash/:id/restore` | free name if taken | | DELETE | `/api/vaults/:v/trash/:id` and `/trash` | purge one / all | | POST | `/api/vaults/:v/attachments?path=` | raw bytes → 201 meta | | GET | `/api/vaults/:v/raw/:id` | attachment bytes | | GET | `/api/vaults/:v/search?q=&sort=&case=` | `{ results: [{ ...meta, matches: [{ line, text, ranges }], matchCount }], total, explain }` (at most 500 results, 20 lines each) | | GET | `/api/vaults/:v/files/:id/backlinks` | `{ linked: [...], unlinked: [...] }` with lines and ranges | | GET | `/api/vaults/:v/tags` | `[{ tag, count }]` | | GET | `/api/vaults/:v/graph` | `{ nodes, links: [{ source, target \| unresolved }], tags }` | | GET | `/api/vaults/:v/headings?q=` | headings across the vault (for `[[##`) | | GET | `/api/vaults/:v/properties` | `[{ key, count, type }]` incl. typed-but-unused keys | | GET | `/api/vaults/:v/properties/:key/values` | distinct values (suggestions) | | PUT | `/api/vaults/:v/properties/:key/type` | `{ type }` | | GET/POST | `/api/vaults/:v/bookmarks` | list; create `{ type, path?, subpath?, query?, title?, parentId? }` | | PATCH/DELETE | `/api/vaults/:v/bookmarks/:id` | `{ title?, parentId?, position? }` | Bookmarks of files are stored by path and rewritten in the move batch. ## Commands Ids, names and default keys ("Mod" = Cmd on macOS, Ctrl elsewhere): | id | name | key | |---|---|---| | `switcher:open` | Quick switcher: Open | Mod+O | | `palette:open` | Command palette: Open | Mod+P | | `file:new` | Create new note | Mod+N | | `file:new-tab` | Create new note in new tab | Mod+Shift+N | | `file:new-folder` | Create new folder | | | `file:rename` | Rename file | F2 | | `file:move` | Move current file to another folder | | | `file:duplicate` | Make a copy of the current file | | | `file:delete` | Delete current file | | | `file:reveal` | Reveal current file in navigation | | | `editor:toggle-reading` | Toggle reading view | Mod+E | | `editor:toggle-source` | Toggle live preview/source mode | | | `editor:bold` / `italic` / `highlight` / `code` | Toggle bold / italics / highlight / code | Mod+B / Mod+I / – / – | | `editor:md-link` | Insert Markdown link | Mod+K | | `editor:internal-link` | Add internal link | | | `editor:task` | Toggle checkbox status | Mod+Enter | | `editor:add-property` | Add file property | Mod+; | | `search:open` | Search: Search in all files | Mod+Shift+F | | `find:in-note` | Search current file | Mod+F | | `graph:open` | Graph view: Open graph view | Mod+G | | `graph:local` | Graph view: Open local graph | | | `daily:today` / `prev` / `next` | Daily notes: Open today's / previous / next daily note | | | `templates:insert` | Templates: Insert template | | | `templates:date` / `time` | Templates: Insert current date / time | | | `bookmarks:add` | Bookmarks: Bookmark current view | Mod+D | | `bookmarks:show`, `files:show`, `tags:show`, `backlinks:show`, `outgoing:show`, `outline:show`, `properties:show` | Show that pane | | | `tab:new` / `tab:close` | New tab / Close current tab | Mod+T / Mod+W | | `tab:next` / `tab:prev` | Go to next / previous tab | Ctrl+Tab / Ctrl+Shift+Tab | | `tab:goto-1`…`tab:goto-7`, `tab:goto-8` | Go to tab #N / Go to last tab | Mod+1…Mod+8 | | `tab:split-right` / `tab:split-down` | Split right / down | | | `nav:back` / `nav:forward` | Navigate back / forward | Mod+Alt+← / → | | `sidebar:left` / `sidebar:right` | Toggle left / right sidebar | Mod+\ / Mod+Shift+\ | | `random:open` | Open random note | | | `theme:toggle` | Toggle light/dark mode | | | `settings:open` | Open settings | Mod+, | | `app:sign-out` | Sign out | | ## Dates (src/shared/dates.ts) Tokens: `YYYY YY MMMM MMM MM M Do DD D dddd ddd dd d HH H hh h mm m ss s A a`, `[literal]`. English month and weekday names. `parseDate(text, fmt)` reads date tokens back (used to find daily notes for previous/next) and rejects impossible dates. `partsInZone(iso, zone)` via `Intl`. ## Templates (src/shared/templates.ts) `applyVariables(text, { title, now, dateFormat, timeFormat })` replaces `{{title}}`, `{{date}}`, `{{time}}`, `{{date:FMT}}`, `{{time:FMT}}` (spaces inside braces allowed). `insertTemplate(doc, cursor, tpl)` inserts the template body at the cursor and merges the template's frontmatter into the note's (note values win; lists are unioned; a note without frontmatter gets the template's). Returns the new text and cursor. ## Demo data When `seed_demo` is on and the users table is empty, the first request creates `sam@example.com` / `demo-pass-123` ("Sam Lee", role `demo`, so it is never the owner in R24) with the vault "Demo vault" (settings: `dailyFolder: "Daily"`, `dailyTemplate: "Templates/Daily template.md"`). Creation times are an hour apart in the order below (for the graph time-lapse): - `Attachments/Roadmap.svg` — a small drawn roadmap (three boxes). - `Welcome.md` — links `[[Getting started]]`, `[[Projects/Launch plan|the launch plan]]`, `[[People/Ana Ruiz|Ana]]`, tag `#demo`. - `Getting started.md` — tag property `guide`; headings "Make a note", "Link notes", "The one tip to remember", "Find things"; links `[[Linking basics#Headings]]`; embeds `![[Linking basics#^tip]]`. - `Linking basics.md` — alias "Links 101", tag `guide`, a paragraph ending ` ^tip`, headings "Headings" and "Blocks", link `[[Getting started#Find things]]`. - `Projects/Launch plan.md` — properties `status: Active`, `due: 2026-12-01`, `owner: "[[People/Ana Ruiz]]"`, tags `project`; mentions "Ana" as plain text; links `[[People/Ben Okafor|Ben]]`, embeds `![[Attachments/Roadmap.svg]]`; tasks (one done); an unresolved `[[Meeting notes|review meeting]]`; a "Risks" section mentioning testing with `[[Ideas]]` and `#risk`. - `Projects/Ideas.md` — mentions "Launch plan" as plain text; `#idea`, `#idea/later`. - `People/Ana Ruiz.md` (alias Ana, role Product lead, tag person), `People/Ben Okafor.md` (alias Ben, role Engineer, links `[[Ana Ruiz]]` and `[[Launch plan]]`). - `Daily/2026-11-13.md` (plain-text "Ana", link to Linking basics), `Daily/2026-11-14.md` (links Launch plan and `[[Ideas|ideas list]]`, `#idea`). - `Reading list.md` (tag reading, three tasks), `Templates/Daily template.md` (`# {{date:dddd D MMMM}}`, Plan, Log), `Templates/Meeting.md` (tags meeting, `attendees: []`, `# {{title}}`, `Date: {{date}} {{time}}`). - Bookmarks: Welcome; search "Open projects" = `tag:#project`; group "People" holding Ana Ruiz. New accounts get only `Welcome.md` explaining links, tags, Ctrl/Cmd+O and Ctrl/Cmd+P. ## Unit tests Parsing: P1 wikilinks with heading, block and display text; P2 embeds and Markdown links, URLs are not vault links; P3 links and tags inside code and comments are ignored; P4 tags: nested, unicode, need a non-digit, not in URLs or headings; P5 frontmatter tags, aliases and links in properties; P6 invalid frontmatter is flagged and ignored; P7 headings and block ids (end of line and on their own line after a blank line); P8 resolveSubpath for nested headings and blocks; P9 escaped pipe in tables splits display text; P10 tasks. Link resolution: L1 exact vault path wins, case-insensitive, `.md` optional; L2 vault root beats same folder for an exact path, same folder beats other folders; L3 bare name with no exact match: fewest folders, then shortest path, then A→Z; L4 relative paths, and attachments need the extension; L5 empty link path is the note itself, unknown names are unresolved; L6 shortest link text uses the bare name only when unique. Rewriting: W1 rename keeps subpath, display text and embeds and leaves other links (`[o](Old.md)` → `[o](New%20name.md)`); W2 moving into a folder where the name clashes writes the path; W3 moving the linking note itself keeps a `./` link relative (`[[./Sib]]` from `A/n` moved to `B/n` → `[[../A/Sib]]`), and nothing to do returns null; W4 links in frontmatter are rewritten in place. Search: S1 AND, OR, parentheses, negation; S2 phrases, case and regex; S3 `file:`/`path:` match attachments too; S4 `tag:` matches nested and frontmatter tags but not plain text; S5 `line:`, `section:`, `block:`, task operators; S6 properties; S7 match line ranges; S8 required terms and errors. Access and cookies: the session cookie has `Secure` on any host except `localhost` and `127.0.0.1`; the default `access` is `only_me` and `cloudflare_access` is off. Other: M1 different lines merge; M2 same line differently is a conflict, identical edits are fine; M3 insertions at both ends; D1 format tokens and literals; D2 parse back, reject impossible dates, add days across months; T1 variables; T2 template properties merge; F1 fuzzy: letters in order, prefix beats scattered. ## Screens - **/login, /signup**: centred card on a soft accent-tinted background; product mark (a rounded accent square) and `app_name`; fields; primary button; link to the other page (the sign-up link only while sign-up is open). When sign-up is not possible the card shows the reason (R24) instead of the form; a short muted note above the fields for the first account and for an invite. - **Settings > People**: an email input with "Invite"; the new link in a bordered box with "Copy link"; "Pending invites" and "People with access" as compact rows with small buttons and an Owner / Member / No access badge. **Settings > About**: heading, one line, two rows. - **/app?vault=ID** (desktop): a 44 px icon ribbon at the far left; the left sidebar (tabs Files, Search, Bookmarks, Tags; vault switcher at the bottom: menu of vaults plus "Manage vaults…"); the main area with tab groups; the right sidebar (tabs Backlinks, Outgoing links, Outline, Local graph, All properties); a thin status bar (sync state, Backlinks, word and character count, view mode menu). - **Note view**: header row with the folder path faded and the note name as an inline editable input (`.view-title-input`), reading/editing toggle and More options; the Properties panel; the editor or reading view with generous padding; readable width 760 px. - **Graph view**: full-bleed canvas; floating control box top right (gear, play); settings panel as a floating card with Filters, Groups, Display, Forces. - **Dialogs**: quick switcher, command palette and pickers are a 620 px card near the top with a borderless input, a list, and a key-hint footer. Settings is a 900×640 dialog with a left section list. - **Mobile**: see R22. ## Look Own design; system font stack; 14 px UI, 16 px note text (adjustable). Light: white canvas, `#f6f6f8` sidebars, `#e1e1e6` borders, text `#1f1f24`. Dark: `#1d1d21` canvas, `#25252a` sidebars, `#36363e` borders, text `#e4e4ea`. Accent from `accent_color` (default `#7c5cff`) for links, active items, selection tints (14 % mix), switches and focus rings. Unresolved links use a faded accent. Tags are small accent-tinted pills. Radius 6 px, cards 12 px, soft shadows. All icons are simple inline SVG strokes drawn for this app.