@noy4/docserve 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/bin.mjs +2 -2
  2. package/dist/widget/index.js +11803 -0
  3. package/package.json +24 -3
  4. package/src/node/adapter.mjs +67 -0
  5. package/src/node/assets.mjs +36 -0
  6. package/src/node/dates.mjs +73 -0
  7. package/src/node/docs-info.mjs +39 -0
  8. package/src/node/files.mjs +43 -0
  9. package/src/node/gallery.mjs +33 -0
  10. package/src/node/inject.mjs +43 -0
  11. package/src/node/meta.mjs +137 -0
  12. package/src/node/routes.mjs +105 -0
  13. package/src/node/scan.mjs +87 -0
  14. package/src/node/serve-static.mjs +158 -0
  15. package/src/node/server.mjs +69 -0
  16. package/src/node/watch.mjs +119 -0
  17. package/src/plugins/collapse/client.js +45 -0
  18. package/src/plugins/collapse/collapse.css +74 -0
  19. package/src/plugins/collapse/commands.ts +81 -0
  20. package/src/plugins/collapse/model.ts +123 -0
  21. package/src/plugins/collapse/sections.ts +105 -0
  22. package/src/plugins/collapse/view.ts +84 -0
  23. package/src/plugins/copy/client.js +72 -0
  24. package/src/plugins/copy/copy.css +21 -0
  25. package/src/plugins/home/client.js +24 -0
  26. package/src/plugins/sidebar/client.js +106 -0
  27. package/src/plugins/sidebar/grouping.js +108 -0
  28. package/src/plugins/sidebar/icons.js +25 -0
  29. package/src/plugins/sidebar/model.ts +91 -0
  30. package/src/plugins/sidebar/resize-model.ts +47 -0
  31. package/src/plugins/sidebar/sidebar.css +663 -0
  32. package/src/plugins/sidebar/tree-model.ts +23 -0
  33. package/src/plugins/sidebar/tree.ts +69 -0
  34. package/src/plugins/sidebar/ui/PageList.tsx +153 -0
  35. package/src/plugins/sidebar/ui/RadioMenu.tsx +201 -0
  36. package/src/plugins/sidebar/ui/Sidebar.tsx +95 -0
  37. package/src/plugins/sidebar/ui/SidebarHeader.tsx +87 -0
  38. package/src/plugins/sidebar/ui/TreeList.tsx +121 -0
  39. package/src/plugins/sidebar/ui/preview-model.ts +134 -0
  40. package/src/plugins/sidebar/ui/useModel.ts +25 -0
  41. package/src/plugins/toc/client.js +55 -0
  42. package/src/plugins/toc/commands.ts +49 -0
  43. package/src/plugins/toc/heading-html.ts +40 -0
  44. package/src/plugins/toc/model.ts +178 -0
  45. package/src/plugins/toc/outline.js +94 -0
  46. package/src/plugins/toc/scroll-spy.ts +35 -0
  47. package/src/plugins/toc/toc.css +214 -0
  48. package/src/plugins/toc/ui/TocPanel.tsx +87 -0
  49. package/src/shared/types.d.ts +193 -0
  50. package/src/widget/commands.js +214 -0
  51. package/src/widget/docks.js +127 -0
  52. package/src/widget/host.js +187 -0
  53. package/src/widget/index.js +22 -0
  54. package/src/widget/lib/disposables.js +44 -0
  55. package/src/widget/lib/dom.js +106 -0
  56. package/src/widget/lib/events.js +65 -0
  57. package/src/widget/lib/headings.js +132 -0
  58. package/src/widget/lib/persisted-signal.js +40 -0
  59. package/src/widget/lib/storage.js +70 -0
  60. package/src/widget/live.js +86 -0
  61. package/src/widget/pages.js +65 -0
  62. package/src/widget/palette.css +162 -0
  63. package/src/widget/palette.js +259 -0
  64. package/src/widget/placement.js +204 -0
  65. package/src/widget/plugins.js +39 -0
  66. package/src/widget/rpc.js +32 -0
  67. package/src/widget/styles.js +31 -0
  68. package/src/widget/ui.js +50 -0
  69. package/src/widget/widget.css +206 -0
  70. package/server/files.mjs +0 -261
  71. package/server/index.mjs +0 -198
  72. package/server/inject.html +0 -88
  73. package/server/inject.mjs +0 -28
  74. package/server/watch.mjs +0 -104
  75. /package/{server → src/node}/state.mjs +0 -0
  76. /package/{server → src/node}/websocket.mjs +0 -0
package/package.json CHANGED
@@ -1,19 +1,40 @@
1
1
  {
2
2
  "name": "@noy4/docserve",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Serves a folder of HTML as a card gallery with live reload.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "docserve": "./bin.mjs"
8
8
  },
9
9
  "scripts": {
10
- "test": "node --test"
10
+ "dev": "node scripts/dev.mjs",
11
+ "build": "vite build",
12
+ "test": "npm run build && node --test --test-timeout=60000",
13
+ "typecheck": "tsc --noEmit",
14
+ "pack:check": "npm pack --dry-run",
15
+ "prepack": "npm run build"
11
16
  },
12
17
  "files": [
13
18
  "bin.mjs",
14
19
  "index.html",
15
- "server/"
20
+ "src/",
21
+ "dist/widget/*.js"
16
22
  ],
23
+ "devDependencies": {
24
+ "@iconify/json": "^2.2.558",
25
+ "@preact/signals-react": "^3.12.0",
26
+ "@preact/signals-react-transform": "^0.8.3",
27
+ "@rolldown/plugin-babel": "^0.2.4",
28
+ "@types/node": "^22.10.0",
29
+ "@types/react": "^19.3.0",
30
+ "@types/react-dom": "^19.3.0",
31
+ "@vitejs/plugin-react": "^6.1.1",
32
+ "react": "^19.3.1",
33
+ "react-dom": "^19.3.1",
34
+ "typescript": "^5.7.0",
35
+ "unplugin-icons": "^24.0.0",
36
+ "vite": "^8.3.2"
37
+ },
17
38
  "engines": {
18
39
  "node": ">=22.12.0"
19
40
  },
@@ -0,0 +1,67 @@
1
+ // node:http ⇄ Fetch adapter: one Request in, one Response out. Bodies are
2
+ // streamed to the client; the server is read-only, so request bodies are not
3
+ // forwarded.
4
+ import { Readable } from "node:stream"
5
+
6
+ /**
7
+ * @param {(request: Request) => Promise<Response>} handler
8
+ * @returns {(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => Promise<void>}
9
+ */
10
+ export function createNodeServerAdapter(handler) {
11
+ return async function nodeHandler(req, res) {
12
+ let response
13
+ try {
14
+ response = await handler(toWebRequest(req))
15
+ } catch (err) {
16
+ console.error(err)
17
+ sendText(res, 500, "Internal Server Error")
18
+ return
19
+ }
20
+
21
+ res.statusCode = response.status
22
+ if (response.statusText) res.statusMessage = response.statusText
23
+ response.headers.forEach((value, name) => res.setHeader(name, value))
24
+
25
+ if (!response.body || req.method === "HEAD") {
26
+ await response.body?.cancel().catch(() => { })
27
+ res.end()
28
+ return
29
+ }
30
+
31
+ const body = Readable.fromWeb(/** @type {any} */ (response.body))
32
+ body.on("error", (err) => {
33
+ console.error(err)
34
+ res.destroy(err)
35
+ })
36
+ // The client went away before the body finished: stop reading the file.
37
+ res.on("close", () => {
38
+ if (!res.writableEnded) body.destroy()
39
+ })
40
+ body.pipe(res)
41
+ }
42
+ }
43
+
44
+ /**
45
+ * @param {import("node:http").IncomingMessage} req
46
+ * @returns {Request}
47
+ */
48
+ function toWebRequest(req) {
49
+ const host = req.headers.host || "localhost"
50
+ const headers = new Headers()
51
+ for (const [name, value] of Object.entries(req.headers)) {
52
+ if (value === undefined) continue
53
+ if (Array.isArray(value)) for (const item of value) headers.append(name, item)
54
+ else headers.set(name, value)
55
+ }
56
+ return new Request(`http://${host}${req.url}`, { method: req.method, headers })
57
+ }
58
+
59
+ /**
60
+ * @param {import("node:http").ServerResponse} res
61
+ * @param {number} status
62
+ * @param {string} body
63
+ */
64
+ function sendText(res, status, body) {
65
+ res.writeHead(status, { "content-type": "text/plain; charset=utf-8" })
66
+ res.end(body)
67
+ }
@@ -0,0 +1,36 @@
1
+ // Widget and plugin assets: the same static handler as the docs tree, rooted
2
+ // at src/widget and src/plugins and read per request so edits need no restart.
3
+ import { createStaticHandler } from "./serve-static.mjs"
4
+
5
+ export { MIME } from "./serve-static.mjs"
6
+
7
+ /** @type {Map<string, (request: Request) => Promise<Response | null>>} */
8
+ const handlers = new Map()
9
+
10
+ /**
11
+ * @param {string} root
12
+ */
13
+ function handlerFor(root) {
14
+ let handler = handlers.get(root)
15
+ if (!handler) {
16
+ handler = createStaticHandler({ root, headers: { "cache-control": "no-store" } })
17
+ handlers.set(root, handler)
18
+ }
19
+ return handler
20
+ }
21
+
22
+ /**
23
+ * Serve a file from the widget or plugin tree by its decoded relative path;
24
+ * symlinks must stay inside root.
25
+ * @param {string} root
26
+ * @param {string} relative
27
+ * @returns {Promise<Response>}
28
+ */
29
+ export async function serveAsset(root, relative) {
30
+ if (!relative) return new Response("Not Found", { status: 404 })
31
+
32
+ // Re-encode segment-wise so the handler's single decode yields the input.
33
+ const encoded = relative.split("/").map(encodeURIComponent).join("/")
34
+ const response = await handlerFor(root)(new Request(`http://localhost/${encoded}`))
35
+ return response ?? new Response("Not Found", { status: 404 })
36
+ }
@@ -0,0 +1,73 @@
1
+ // Created/modified dates from git history, keyed by absolute path.
2
+ import { execFile } from "node:child_process"
3
+ import { join } from "node:path"
4
+ import { promisify } from "node:util"
5
+ import { realpath } from "./scan.mjs"
6
+
7
+ const run = promisify(execFile)
8
+
9
+ /** @typedef {{ created: Map<string, number>, modified: Map<string, number> }} DateMaps */
10
+
11
+ /** @type {Map<string, DateMaps>} */
12
+ const gitMapsCache = new Map() // repo root (or docsDir when not a repo) -> DateMaps
13
+
14
+ /**
15
+ * A single full-repo scan with cwd set to the docs dir, cached per repo root in
16
+ * module scope. git log outputs newest first: overwriting keeps the oldest add
17
+ * (= creation date) and the newest touch (= modified date).
18
+ * @param {string} docsDir
19
+ * @returns {Promise<DateMaps>}
20
+ */
21
+ export async function gitDateMaps(docsDir) {
22
+ const cwd = realpath(docsDir)
23
+ const top = (await git(["rev-parse", "--show-toplevel"], cwd)).trim()
24
+ const root = top ? realpath(top) : null
25
+ const cacheKey = root ?? cwd
26
+ let maps = gitMapsCache.get(cacheKey)
27
+ if (maps) return maps
28
+
29
+ maps = { created: new Map(), modified: new Map() }
30
+ if (root) {
31
+ try {
32
+ const [first, last] = await Promise.all([
33
+ git(["log", "--diff-filter=A", "--name-only", "--format=c:%at"], cwd),
34
+ git(["log", "--name-only", "--format=m:%at"], cwd),
35
+ ])
36
+ /** @type {number | undefined} */
37
+ let ts
38
+ for (const line of first.split("\n")) {
39
+ if (line.startsWith("c:")) {
40
+ ts = parseInt(line.slice(2), 10)
41
+ } else if (line && ts !== undefined) {
42
+ maps.created.set(join(root, line), ts) // oldest add wins
43
+ }
44
+ }
45
+ ts = undefined
46
+ for (const line of last.split("\n")) {
47
+ if (line.startsWith("m:")) {
48
+ ts = parseInt(line.slice(2), 10)
49
+ } else if (line && ts !== undefined) {
50
+ maps.modified.set(join(root, line), ts) // newest touch wins
51
+ }
52
+ }
53
+ } catch {
54
+ // unreadable history → fall back to fs dates
55
+ }
56
+ }
57
+ gitMapsCache.set(cacheKey, maps)
58
+ return maps
59
+ }
60
+
61
+ /**
62
+ * @param {string[]} args
63
+ * @param {string} cwd
64
+ * @returns {Promise<string>}
65
+ */
66
+ async function git(args, cwd) {
67
+ try {
68
+ const { stdout } = await run("git", args, { cwd, timeout: 10000, maxBuffer: 64 * 1024 * 1024 })
69
+ return stdout
70
+ } catch {
71
+ return ""
72
+ }
73
+ }
@@ -0,0 +1,39 @@
1
+ // Identity of the served folder, shared by the gallery template and the
2
+ // injected widget: display name, ~-collapsed path, deterministic hue.
3
+ import os from "node:os"
4
+ import { basename } from "node:path"
5
+
6
+ /** @typedef {{ name: string, path: string, hue: number }} DocsInfo */
7
+
8
+ /**
9
+ * @param {string} docsDir
10
+ * @returns {DocsInfo}
11
+ */
12
+ export function docsInfo(docsDir) {
13
+ return {
14
+ name: basename(docsDir) || docsDir,
15
+ path: displayPath(docsDir),
16
+ hue: faviconHue(docsDir),
17
+ }
18
+ }
19
+
20
+ // Collapse the home directory prefix to ~ for display.
21
+ /**
22
+ * @param {string} p
23
+ * @returns {string}
24
+ */
25
+ function displayPath(p) {
26
+ const home = os.homedir()
27
+ return p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p
28
+ }
29
+
30
+ // Deterministic hue for the folder favicon: the same path always yields the same color.
31
+ /**
32
+ * @param {string} s
33
+ * @returns {number}
34
+ */
35
+ function faviconHue(s) {
36
+ let h = 0
37
+ for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0
38
+ return ((h % 360) + 360) % 360
39
+ }
@@ -0,0 +1,43 @@
1
+ // /api/files payload: page metadata composed from scanning, head parsing and
2
+ // git dates.
3
+ import { realpathSync } from "node:fs"
4
+ import { stat } from "node:fs/promises"
5
+ import { basename } from "node:path"
6
+ import { gitDateMaps } from "./dates.mjs"
7
+ import { metaOf } from "./meta.mjs"
8
+ import { listHtmlFiles, normalizedRelative } from "./scan.mjs"
9
+
10
+ /**
11
+ * @param {string} docsDir
12
+ */
13
+ export async function apiFiles(docsDir) {
14
+ const paths = await listHtmlFiles(docsDir)
15
+ const { created, modified } = await gitDateMaps(docsDir)
16
+ const files = []
17
+ for (const full of paths) {
18
+ let st
19
+ try {
20
+ st = await stat(full)
21
+ } catch {
22
+ continue // deleted between listing and stat
23
+ }
24
+ const { title, date, favicon } = await metaOf(full, st.mtimeMs, docsDir)
25
+ let key
26
+ try {
27
+ key = realpathSync(full)
28
+ } catch {
29
+ continue
30
+ }
31
+ const rel = normalizedRelative(docsDir, full)
32
+ files.push({
33
+ title: title ?? basename(full),
34
+ url: `/${rel}`,
35
+ filePath: full,
36
+ favicon: favicon ?? undefined,
37
+ created: date ?? created.get(key) ?? Math.floor(st.birthtimeMs / 1000),
38
+ modified: modified.get(key) ?? Math.floor(st.mtimeMs / 1000),
39
+ })
40
+ }
41
+ files.sort((a, b) => b.created - a.created || a.title.localeCompare(b.title, "ja") || a.url.localeCompare(b.url))
42
+ return files
43
+ }
@@ -0,0 +1,33 @@
1
+ // The gallery template served at / and /index.html. Every other HTML file comes
2
+ // from the docs folder and is injected instead.
3
+ import { readFile } from "node:fs/promises"
4
+ import { resolve } from "node:path"
5
+ import { docsInfo } from "./docs-info.mjs"
6
+
7
+ export const INDEX_TEMPLATE = resolve(import.meta.dirname, "..", "..", "index.html")
8
+
9
+ /**
10
+ * @param {string} docsDir
11
+ * @returns {Promise<Response>}
12
+ */
13
+ export async function galleryResponse(docsDir) {
14
+ try {
15
+ const { name, path, hue } = docsInfo(docsDir)
16
+ let html = await readFile(INDEX_TEMPLATE, "utf8")
17
+ html = html
18
+ .replaceAll("__DOCS_DIR_NAME__", escapeHtml(name))
19
+ .replaceAll("__DOCS_DIR__", escapeHtml(path))
20
+ .replaceAll("__FAVICON_HUE__", String(hue))
21
+ return new Response(html, { headers: { "content-type": "text/html; charset=utf-8" } })
22
+ } catch {
23
+ return new Response("Gallery template missing", { status: 500 })
24
+ }
25
+ }
26
+
27
+ /**
28
+ * @param {string} s
29
+ * @returns {string}
30
+ */
31
+ function escapeHtml(s) {
32
+ return s.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
33
+ }
@@ -0,0 +1,43 @@
1
+ // Injection: every HTML response from the docs root gets the widget tags before
2
+ // the last </body>. The gallery template is served separately and never reaches
3
+ // this module.
4
+ import { docsInfo } from "./docs-info.mjs"
5
+
6
+ export const WS_PATH = "/__reload"
7
+
8
+ const MARKER = "<!--docserve-widget-->"
9
+ const SCRIPT_SRC = "/__docserve/widget/index.js"
10
+
11
+ /**
12
+ * Append the widget once. Idempotent: a second pass over the same document is a
13
+ * no-op. Without a </body> the tags are appended at the end.
14
+ * @param {string} html
15
+ * @param {string} page Docs-relative path, e.g. `guides/intro.html`.
16
+ * @param {string} [docsDir]
17
+ * @returns {string}
18
+ */
19
+ export function injectIntoHtml(html, page, docsDir = "") {
20
+ if (html.includes(MARKER)) return html
21
+
22
+ const docs = docsInfo(docsDir)
23
+ const tags = [
24
+ MARKER,
25
+ '<link rel="stylesheet" href="/__docserve/widget/widget.css" data-docserve-widget>',
26
+ `<script type="module" src="${SCRIPT_SRC}" data-docserve-widget data-page="${escapeAttribute(page)}" data-docs-name="${escapeAttribute(docs.name)}" data-docs-path="${escapeAttribute(docs.path)}" data-docs-hue="${docs.hue}"></script>`,
27
+ ].join("\n")
28
+
29
+ const index = html.toLowerCase().lastIndexOf("</body>")
30
+ return index === -1 ? `${html}\n${tags}` : `${html.slice(0, index)}${tags}\n${html.slice(index)}`
31
+ }
32
+
33
+ /**
34
+ * @param {string} value
35
+ * @returns {string}
36
+ */
37
+ function escapeAttribute(value) {
38
+ return value
39
+ .replace(/&/g, "&amp;")
40
+ .replace(/"/g, "&quot;")
41
+ .replace(/</g, "&lt;")
42
+ .replace(/>/g, "&gt;")
43
+ }
@@ -0,0 +1,137 @@
1
+ // Title, created_at and favicon extracted from the head of a document, cached
2
+ // by path + mtime so repeated /api/files calls only re-read changed files.
3
+ import { open } from "node:fs/promises"
4
+ import { dirname, join } from "node:path"
5
+ import { isWithin, normalizedRelative } from "./scan.mjs"
6
+
7
+ /** @typedef {{ title: string | null, date: number | null, favicon: string | null }} DocMeta */
8
+
9
+ /** @type {Map<string, DocMeta>} */
10
+ const metaCache = new Map() // "path:mtimeMs" -> DocMeta
11
+
12
+ /**
13
+ * @param {string} full
14
+ * @param {number} mtimeMs
15
+ * @param {string} docsDir
16
+ * @returns {Promise<DocMeta>}
17
+ */
18
+ export async function metaOf(full, mtimeMs, docsDir) {
19
+ const key = `${full}:${mtimeMs}`
20
+ const cached = metaCache.get(key)
21
+ if (cached !== undefined) return cached
22
+ const meta = await extractMeta(full, docsDir)
23
+ metaCache.set(key, meta)
24
+ return meta
25
+ }
26
+
27
+ /**
28
+ * @param {string} full
29
+ * @param {string} docsDir
30
+ * @returns {Promise<DocMeta>}
31
+ */
32
+ async function extractMeta(full, docsDir) {
33
+ /** @param {string} text */
34
+ const findTitle = (text) => {
35
+ const raw = text.match(/<title>([^<]*)<\/title>/)?.[1]?.trim()
36
+ return raw == null ? null : decodeEntities(raw)
37
+ }
38
+ /** @param {string} text */
39
+ const findDate = (text) => {
40
+ for (const tag of text.match(/<meta\b[^>]*>/gi) ?? []) {
41
+ if (!/\bname\s*=\s*["']created_at["']/i.test(tag)) continue
42
+ const d = new Date(tag.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1]?.trim() ?? "")
43
+ if (!isNaN(d.getTime())) return Math.floor(d.getTime() / 1000)
44
+ }
45
+ return null
46
+ }
47
+ // Attribute value from a tag string ("v", 'v', or bare); null when absent.
48
+ /**
49
+ * @param {string} tag
50
+ * @param {string} name
51
+ */
52
+ const attrOf = (tag, name) => {
53
+ const m = tag.match(new RegExp(`(?<![\\w-])${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"))
54
+ return m?.[1] ?? m?.[2] ?? m?.[3] ?? null
55
+ }
56
+ // First <link rel="...icon..."> href resolved to a URL served from docsDir;
57
+ // data: and absolute http(s) URLs are kept as-is.
58
+ /** @param {string} text */
59
+ const findFavicon = (text) => {
60
+ // Quoted values may contain ">" (inline SVG data URIs), so scan links
61
+ // value-aware instead of with a plain [^>]* tag match.
62
+ for (const tag of text.match(/<link\b(?:"[^"]*"|'[^']*'|[^>])*>/gi) ?? []) {
63
+ const rel = attrOf(tag, "rel")
64
+ if (!rel || !/\bicon\b/i.test(rel)) continue
65
+ const href = attrOf(tag, "href")?.trim()
66
+ if (!href) continue
67
+ if (/^data:/i.test(href)) return href.replaceAll("#", "%23")
68
+ if (/^(https?:|\/\/)/i.test(href)) return href
69
+ const target = href.startsWith("/")
70
+ ? join(docsDir, href.split(/[?#]/)[0])
71
+ : join(dirname(full), href.split(/[?#]/)[0])
72
+ if (!isWithin(docsDir, target)) return null
73
+ return `/${normalizedRelative(docsDir, target)}`
74
+ }
75
+ return null
76
+ }
77
+ try {
78
+ const handle = await open(full, "r")
79
+ try {
80
+ /**
81
+ * @param {number} len
82
+ * @param {number} pos
83
+ */
84
+ const read = async (len, pos) => {
85
+ const { buffer, bytesRead } = await handle.read(Buffer.alloc(len), 0, len, pos)
86
+ return buffer.toString("utf8", 0, bytesRead)
87
+ }
88
+ // Titles and meta tags live in <head>; read only the first 4 KB.
89
+ const head = await read(4096, 0)
90
+ /** @type {DocMeta} */
91
+ let meta = {
92
+ title: findTitle(head),
93
+ date: findDate(head),
94
+ favicon: findFavicon(head),
95
+ }
96
+ if (meta.title === null || meta.date === null || meta.favicon === null) {
97
+ // Fallback for documents with a long preamble (inline favicon etc.)
98
+ const text = await read(1 << 20, 0)
99
+ meta = {
100
+ title: meta.title ?? findTitle(text),
101
+ date: meta.date ?? findDate(text),
102
+ favicon: meta.favicon ?? findFavicon(text),
103
+ }
104
+ }
105
+ return meta
106
+ } finally {
107
+ await handle.close()
108
+ }
109
+ } catch {
110
+ return { title: null, date: null, favicon: null }
111
+ }
112
+ }
113
+
114
+ // Decode <title> entities so cards read "A & B", not "A &amp; B".
115
+ const ENTITIES = {
116
+ amp: "&",
117
+ lt: "<",
118
+ gt: ">",
119
+ quot: '"',
120
+ apos: "'",
121
+ nbsp: "\u00a0",
122
+ }
123
+
124
+ /**
125
+ * @param {string} s
126
+ * @returns {string}
127
+ */
128
+ function decodeEntities(s) {
129
+ return s.replace(/&(#[xX]?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/g, (m, ref) => {
130
+ if (ref[0] === "#") {
131
+ const hex = /[xX]/.test(ref[1])
132
+ const cp = parseInt(hex ? ref.slice(2) : ref.slice(1), hex ? 16 : 10)
133
+ return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : m
134
+ }
135
+ return ENTITIES[ref.toLowerCase()] ?? m
136
+ })
137
+ }
@@ -0,0 +1,105 @@
1
+ // HTTP routing: an ordered table of handlers over one docs static handler.
2
+ // Nothing here knows about listening, signals or sockets.
3
+ import { resolve } from "node:path"
4
+ import { serveAsset } from "./assets.mjs"
5
+ import { apiFiles } from "./files.mjs"
6
+ import { galleryResponse } from "./gallery.mjs"
7
+ import { injectIntoHtml } from "./inject.mjs"
8
+ import { createStaticHandler } from "./serve-static.mjs"
9
+
10
+ const WIDGET_DIR = resolve(import.meta.dirname, "..", "widget")
11
+ const PLUGINS_DIR = resolve(import.meta.dirname, "..", "plugins")
12
+ const DIST_WIDGET_DIR = resolve(import.meta.dirname, "..", "..", "dist", "widget")
13
+ const INTERNAL_PREFIX = "/__docserve/"
14
+ const WIDGET_PREFIX = `${INTERNAL_PREFIX}widget/`
15
+ const PLUGINS_PREFIX = `${INTERNAL_PREFIX}plugins/`
16
+
17
+ /**
18
+ * @param {{ docsDir: string }} options
19
+ * @returns {(request: Request) => Promise<Response>}
20
+ */
21
+ export function createHandler({ docsDir }) {
22
+ // Every other HTML response is injected; the gallery template is not.
23
+ const docs = createStaticHandler({
24
+ root: docsDir,
25
+ headers: { "cache-control": "no-store" },
26
+ transform: (html, relative) => injectIntoHtml(html, relative, docsDir),
27
+ })
28
+
29
+ /** @type {Array<{ match: (pathname: string) => boolean, handle: (request: Request, url: URL) => Promise<Response> }>} */
30
+ const routes = [
31
+ { match: (pathname) => pathname === "/api/files", handle: serveFiles },
32
+ { match: (pathname) => pathname.startsWith(INTERNAL_PREFIX), handle: serveInternal },
33
+ { match: (pathname) => pathname === "/" || pathname === "/index.html", handle: serveGallery },
34
+ { match: () => true, handle: serveDocs },
35
+ ]
36
+
37
+ return async function handler(request) {
38
+ const url = new URL(request.url)
39
+ const route = routes.find((candidate) => candidate.match(url.pathname))
40
+ return route.handle(request, url)
41
+ }
42
+
43
+ /**
44
+ * @returns {Promise<Response>}
45
+ */
46
+ async function serveFiles() {
47
+ try {
48
+ return Response.json(await apiFiles(docsDir), { headers: { "cache-control": "no-store" } })
49
+ } catch (err) {
50
+ console.error(err)
51
+ return Response.json([], { headers: { "cache-control": "no-store" } })
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Widget bundle and plugin sources, read per request (widget JS comes from dist).
57
+ * @param {Request} request
58
+ * @param {URL} url
59
+ * @returns {Promise<Response>}
60
+ */
61
+ async function serveInternal(request, url) {
62
+ if (url.pathname.startsWith(WIDGET_PREFIX))
63
+ return serveWidget(url.pathname.slice(WIDGET_PREFIX.length))
64
+ if (url.pathname.startsWith(PLUGINS_PREFIX))
65
+ return serveAsset(PLUGINS_DIR, url.pathname.slice(PLUGINS_PREFIX.length))
66
+ return new Response("Not Found", { status: 404 })
67
+ }
68
+
69
+ /**
70
+ * Built widget first, source files (CSS) as the fallback. A JS request that
71
+ * misses the build is an error: the source entry now has bare imports.
72
+ * @param {string} relative
73
+ * @returns {Promise<Response>}
74
+ */
75
+ async function serveWidget(relative) {
76
+ if (!relative) return new Response("Not Found", { status: 404 })
77
+
78
+ const built = await serveAsset(DIST_WIDGET_DIR, relative)
79
+ if (built.status !== 404) return built
80
+
81
+ if (/\.m?js$/.test(relative)) {
82
+ return new Response("Widget bundle missing: run `pnpm -C cli build`", {
83
+ status: 503,
84
+ headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
85
+ })
86
+ }
87
+
88
+ return serveAsset(WIDGET_DIR, relative)
89
+ }
90
+
91
+ /**
92
+ * @returns {Promise<Response>}
93
+ */
94
+ async function serveGallery() {
95
+ return galleryResponse(docsDir)
96
+ }
97
+
98
+ /**
99
+ * @param {Request} request
100
+ * @returns {Promise<Response>}
101
+ */
102
+ async function serveDocs(request) {
103
+ return (await docs(request)) ?? new Response("Not Found", { status: 404 })
104
+ }
105
+ }