Book cataloging web app for my home library.
  • TypeScript 51.5%
  • JavaScript 20.8%
  • Python 15.7%
  • HTML 7%
  • CSS 5%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Eric Yager 01346a5b95
migrate from wrangler to the cf CLI
Generated cloudflare.config.ts / wrangler.config.ts with `cf migrate`
(1.0.0-rc.2), declared secrets via bindings.secret(), and switched
scripts to cf dev/build/deploy and `cf workers types`. Env types are now
inferred into .cloudflare/types, replacing worker-configuration.d.ts and
src/env.d.ts. wrangler.jsonc stays only for vitest-pool-workers.

Bumps wrangler to 4.166 and @cloudflare/workers-types (peer dep).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-20 19:43:30 -05:00
.vscode create home library management web app, version 1 2026-08-24 15:00:18 -04:00
migrations create home library management web app, version 1 2026-08-24 15:00:18 -04:00
public add logo and use it as favicon 2026-11-20 19:30:07 -05:00
scripts migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
src migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
test migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
.editorconfig create home library management web app, version 1 2026-08-24 15:00:18 -04:00
.envrc migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
.gitignore migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
.prettierrc create home library management web app, version 1 2026-08-24 15:00:18 -04:00
AGENTS.md migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
bookshelf.py create home library management web app, version 1 2026-08-24 15:00:18 -04:00
cloudflare.config.ts migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
LICENSE add license 2026-10-05 16:15:03 -04:00
package-lock.json migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
package.json migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
README.md migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
requirements.txt create home library management web app, version 1 2026-08-24 15:00:18 -04:00
schema.sql create home library management web app, version 1 2026-08-24 15:00:18 -04:00
tsconfig.json migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
vitest.config.mts add auto-suggest for BISAC category 2026-10-05 15:42:12 -04:00
wrangler.config.ts migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00
wrangler.jsonc migrate from wrangler to the cf CLI 2026-11-20 19:43:30 -05:00

Librarian

A single-user, password-protected book catalog running on Cloudflare Workers + D1. Scan a barcode with your phone camera, auto-fill metadata from Open Library, and organize books onto named, orderable shelves — sorted by BISAC subject heading.

Stack

  • Cloudflare Workers (TypeScript, no framework) + static assets served from public/
  • D1 (SQLite) for storage, one DB binding
  • Vanilla HTML/CSS/JS frontend, no build step
  • Barcode scanning via the native BarcodeDetector API (Android Chrome) with a ZXing-based fallback (public/vendor/zxing.min.js) for browsers without it, e.g. iOS Safari
  • Auth: password → signed session cookie, plus an optional bearer token for scripts/agents

Project layout

src/
  index.ts    request router; applies the auth gate, dispatches /api/*, falls through to ASSETS
  auth.ts     password verification, session cookie sign/verify, bearer-token check
  classify.ts BISAC/Cutter sort comparators, author surname parsing, autoCutter
  bisac.ts    the BISAC list (from data/bisac.json): validation, canonical spelling, by-major index
  suggest.ts  BISAC suggestions via Workers AI's Clef decision model
  lookup.ts   Open Library metadata fetch (by ISBN), plus work description/subjects for suggest.ts
  books.ts    /api/books, /api/books/:id, /api/lookup/:isbn, /api/suggest-bisac handlers
  shelves.ts  /api/shelves handlers
  env.d.ts    hand-written Env fields for secrets (see "Types" below)
public/
  login.html, index.html, app.js, scan.js, style.css
scripts/
  hash-password.mjs   turns a chosen password into a PASSWORD_HASH value
  fetch-bisac.mjs     scrapes the BISAC list from bisg.org into data/bisac.json
data/
  bisac.json          the BISAC list -- gitignored, generated by fetch-bisac.mjs (see "BISAC list")
schema.sql            D1 schema (shelves, books)
migrations/           ALTER TABLE steps for existing D1 databases (schema.sql alone only
                      covers CREATE TABLE IF NOT EXISTS, i.e. fresh databases)

Setup

Requires Node and the cf CLI (installed as a dev dependency along with Wrangler, which cf uses as its bundler — npm install pulls both in). Config lives in cloudflare.config.ts (bindings, routes, secrets) and wrangler.config.ts (bundler settings). wrangler.jsonc is kept only for the vitest pool — keep it in sync if you change bindings. Run npx cf auth login once; cf does not reuse a Wrangler login.

  1. Install dependencies

    npm install
    

    Then fetch the BISAC list (required: the Worker won't build without it; see BISAC list):

    node scripts/fetch-bisac.mjs
    
  2. Create the D1 database (skip if cloudflare.config.ts already has a real D1 id):

    npx cf d1 create --name librarian-db
    

    Paste the printed ID into the DB binding in cloudflare.config.ts (and the d1_databases block in wrangler.jsonc, for tests). cf D1 commands take the database ID, not the name; the commands below use $DB_ID for it.

  3. Apply the schema:

    DB_ID=945c39fa-63e3-479c-8778-189a68e2a754
    npx cf d1 raw "$DB_ID" --local --sql "$(cat schema.sql)"
    npx cf d1 raw "$DB_ID" --sql "$(cat schema.sql)"   # remote, once you're ready to deploy
    

    If a database already exists from before the bisac column was added, also run the migration against it (safe to skip on a brand-new database, since schema.sql already includes the column):

    npx cf d1 raw "$DB_ID" --local --sql "$(cat migrations/0001_add_bisac.sql)"
    npx cf d1 raw "$DB_ID" --sql "$(cat migrations/0001_add_bisac.sql)"
    
  4. Set the login password:

    npx cf workers secrets update PASSWORD_HASH --worker librarian \
      --text "$(node scripts/hash-password.mjs '<chosen password>')"
    
  5. Set the session-signing secret (any long random string):

    npx cf workers secrets update SESSION_SECRET --worker librarian \
      --text "$(node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")"
    
  6. (Optional) Enable API access for scripts/agents — see Agent/script API access below.

  7. Generate TypeScript bindings (re-run after any cloudflare.config.ts binding change; npm run build also regenerates them):

    npm run cf-typegen
    

BISAC list

books.bisac must be an official BISAC Subject Heading: the API rejects anything else with a 400. It does fix case and spacing for you, so philosophy/ethics & moral philosophy is stored as PHILOSOPHY / Ethics & Moral Philosophy. The list itself is © Book Industry Study Group and can't be redistributed, so it isn't committed. scripts/fetch-bisac.mjs scrapes the public per-heading pages linked from bisg.org/complete-bisac-subject-headings-list and writes data/bisac.json (gitignored). src/bisac.ts imports that file, so it gets bundled into the Worker at build/deploy time; nothing reads it at runtime.

Format of data/bisac.json: a single flat JSON object mapping each 9-character BISAC code to its full heading text. The text is exactly what gets stored in books.bisac, with the major heading first and the levels joined by " / " (space, slash, space):

{
	"FIC009020": "FICTION / Fantasy / Epic",
	"PHI005000": "PHILOSOPHY / Ethics & Moral Philosophy",
	"PHI000000": "PHILOSOPHY / General"
}
  • Keys are sorted by code. Every heading has at least two levels: each major heading has its own "MAJOR / General" entry, and nothing is a bare major heading.
  • HTML entities are decoded and the text is NFC-normalized (Bandes Dessinées, not &eacute;).
  • These parts of the source pages are dropped: cross-reference-only lines (... see ..., which have no code), trailing (see also ...) scope notes, and the * that marks a new heading. Parentheses that belong to the heading itself are kept, e.g. HISTORY / United States / State & Local / Midwest (IA, IL, ...).
  • The 2026-10-05 scrape has 5,860 headings under 53 major headings. The script fails rather than writing a partial file if it parses fewer than 3,000, or if any HTML entities are left undecoded. Either one usually means bisg.org changed its markup.

Re-run the script when BISG publishes a revision (yearly), then re-validate the catalog against the new list. Headings get renamed between editions (e.g. HISTORY / Military / World War II → HISTORY / Wars & Conflicts / World War II / General), and when one is renamed, also update its key in SECTION_RANK / SECTION_OVERRIDE in src/classify.ts.

BISAC suggestions (Workers AI / Clef)

The edit form has a Suggest button next to the BISAC field. It calls POST /api/suggest-bisac, which asks Clef, Cloudflare's decision model, to pick from the official list. Clef answers with a probability for each option instead of generating text, so it can't invent a heading that isn't on the list. A single question can offer at most 255 options, so src/suggest.ts asks in two stages: first the major heading, then a heading within that major. Majors with more than 255 headings are split into chunks, and the best few from each chunk go to a final round. If the model isn't sure about the major heading, it also tries the runner-up. The form shows the top 3 headings with their probabilities. Clicking one fills the field, and nothing is saved until you hit Save. A suggestion whose major heading has no shelf section in src/classify.ts is marked "sorts last".

The title is required. If an ISBN is given, the Open Library work description and subject tags are added to what the model sees, and they help noticeably.

Cost: Clef bills only input tokens, at $0.24/M (clef-flash, the cheaper option, is $0.09/M). One suggestion is about 1–8k tokens, depending on how many chunks are needed. At most that's ~175 neurons, against the free allowance of 10,000/day on any plan, so a few dozen books a day stays free. To switch models, change MODEL/MODEL_SELECTOR in src/suggest.ts.

Note: the AI binding is always remote. npm run dev calls the real Clef, which uses up the same free allowance and needs a cf auth login. Tests stub Clef (remoteBindings: false in vitest.config.mts).

Usage

npm run dev      # local dev server (cf dev)
npm run build    # build into .cloudflare/output (cf build)
npm run deploy   # deploy to Cloudflare (cf deploy; `npx cf deploy --dry-run` to check first)
npm test         # run the vitest suite

Local dev serves against D1's local simulation in .cloudflare/state (populated by the --local schema step above); npm run deploy ships the Worker to the domain configured in cloudflare.config.ts (books.yager.me custom domain).

Once deployed, log in with the password from step 4. From the app you can:

  • Scan a barcode (camera permission required; native scanning on Android Chrome, ZXing fallback elsewhere including iOS Safari) to look up an ISBN via Open Library and review/edit the fields before saving.
  • Add manually using the same editable review form.
  • Sort the catalog by BISAC heading, author, or title.
  • Create, rename, reorder, and delete shelves; assign books to a shelf or leave them unshelved.

Types

npm run cf-typegen (= cf workers types) writes .cloudflare/types/index.d.ts (gitignored), inferring Env directly from cloudflare.config.ts — including the secrets declared there with bindings.secret(). Run it after a fresh clone, before tsc.

Agent/script API access

The REST API also accepts a bearer token, separate from the human cookie login, so a script or coding agent can read and patch book data directly (e.g. filling in missing bisac/cutter fields) without going around the app's validation logic. See AGENTS.md for the endpoint reference and example curl calls.

To enable it:

TOKEN=$(node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
npx cf workers secrets update API_TOKEN --worker librarian --text "$TOKEN"
pass insert -m librarian/api-token <<<"$TOKEN"

Export the same value as LIBRARIAN_API_TOKEN wherever the script/agent runs. Leaving API_TOKEN unset disables this path entirely — normal cookie login is unaffected either way.

In this repo that export is handled by .envrc, which pulls the token from pass:

pass insert librarian/api-token   # same value as the API_TOKEN secret
direnv allow                      # once per checkout

.envrc is committed (it contains only the pass lookup, not the token) so the setup carries across machines. Loading it per-directory rather than from a shell rc means the GPG decrypt — and its pinentry prompt — happens when you enter the project, not on every new terminal.

Testing

npm test

Vitest + @cloudflare/vitest-pool-workers, config in vitest.config.mts. Covers classify.ts sort/Cutter behavior, the auth module (password hashing, session cookie round-trip, bearer token checks), and the BISAC suggestion pipeline against a stubbed Clef (staging, chunking and the final round, runner-up expansion, canonicalization) — see test/. Needs data/bisac.json.