@noy4/docserve 0.1.1 → 0.2.0

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.
package/bin.mjs CHANGED
@@ -4,18 +4,18 @@
4
4
  // docserve [dir] [command] [options]
5
5
  //
6
6
  // Flow:
7
- // parse args ──▶ stop / status ──▶ state.json
7
+ // parse args ──▶ stop / status ──▶ state files
8
8
  // └─ start
9
- // ├─ single-instance check (readLiveState)
10
- // ├─ --background ──▶ spawn detached ──▶ wait for state.json
11
- // └─ foreground ──▶ runServer() (writes state.json on bind)
9
+ // ├─ single-instance check (findByDir)
10
+ // ├─ --background ──▶ spawn detached ──▶ wait for the state file
11
+ // └─ foreground ──▶ runServer() (writes its state file on bind)
12
12
  import fs from "node:fs"
13
13
  import path from "node:path"
14
14
  import { exec, spawn } from "node:child_process"
15
15
  import { fileURLToPath } from "node:url"
16
16
  import { parseArgs } from "node:util"
17
17
  import { runServer } from "./server/index.mjs"
18
- import { clearState, readLiveState } from "./server/state.mjs"
18
+ import { findByDir, listLiveStates, removeState } from "./server/state.mjs"
19
19
 
20
20
  const pkg = JSON.parse(fs.readFileSync(new URL("./package.json", import.meta.url), "utf8"))
21
21
  const VERSION = pkg.version
@@ -32,20 +32,20 @@ Arguments:
32
32
  dir Folder of HTML files to serve (default: current directory)
33
33
 
34
34
  Commands:
35
- stop Stop the running docserve server
36
- status Show whether a server is running (exit 1 if none)
35
+ stop Stop the server serving [dir], or every server when [dir] is omitted
36
+ status List the running servers (url + docs); exit 1 if none
37
37
 
38
38
  Options:
39
39
  --open Open the gallery in the browser once the port is bound
40
40
  --port <number> Port to bind (default: ${DEFAULT_PORT}); falls back +1 up to 20 tries
41
- --background Start detached; the bound port and pid land in state.json
41
+ --background Start detached; the bound port and pid land in the state dir
42
42
  -h, --help Show this help
43
43
  -v, --version Show version
44
44
  `
45
45
 
46
46
  async function main() {
47
47
  const args = parseCliArgs()
48
- if (args.command === "stop") return stopServer()
48
+ if (args.command === "stop") return stopServer(args)
49
49
  if (args.command === "status") return showStatus()
50
50
  return startServer(args)
51
51
  }
@@ -114,27 +114,39 @@ function parseCliArgs() {
114
114
  }
115
115
  }
116
116
 
117
- function stopServer() {
118
- const state = readLiveState() // stale state (dead pid) is removed silently
119
- if (!state) {
117
+ function stopServer(args) {
118
+ const dir = args.dir ? path.resolve(args.dir) : null
119
+ // listLiveStates() prunes stale state (dead pid) silently.
120
+ const states = dir ? [findByDir(dir)].filter(Boolean) : listLiveStates()
121
+ if (!states.length) {
122
+ if (dir) {
123
+ console.error(`docserve is not serving ${dir}.`)
124
+ process.exit(1)
125
+ }
120
126
  console.log("docserve is not running.")
121
127
  return
122
128
  }
123
- try {
124
- process.kill(state.pid, "SIGTERM")
125
- } catch {}
126
- clearState()
127
- console.log(`Stopped docserve (${state.url})`)
129
+ for (const state of states) {
130
+ try {
131
+ process.kill(state.pid, "SIGTERM")
132
+ } catch {}
133
+ removeState(state)
134
+ console.log(`Stopped docserve (${state.url})`)
135
+ console.log(` docs : ${state.docsDir}`)
136
+ }
128
137
  }
129
138
 
130
139
  function showStatus() {
131
- const state = readLiveState()
132
- if (!state) {
140
+ const states = listLiveStates()
141
+ if (!states.length) {
133
142
  console.error("docserve is not running.")
134
143
  process.exit(1)
135
144
  }
136
- console.log(state.url)
137
- console.log(`docs : ${state.docsDir}`)
145
+ for (const [index, state] of states.entries()) {
146
+ if (index > 0) console.log()
147
+ console.log(state.url)
148
+ console.log(`docs : ${state.docsDir}`)
149
+ }
138
150
  }
139
151
 
140
152
  async function startServer(args) {
@@ -144,22 +156,13 @@ async function startServer(args) {
144
156
  process.exit(1)
145
157
  }
146
158
 
147
- // Single instance: same docsDir just opens its URL; a different docsDir
148
- // requires docserve stop first.
149
- const running = readLiveState()
159
+ // Single instance per folder: same docsDir just opens its URL; a different
160
+ // docsDir starts its own instance (the port fallback avoids collisions).
161
+ const running = findByDir(docsDir)
150
162
  if (running) {
151
- if (running.docsDir === docsDir) {
152
- if (args.open) openBrowser(running.url)
153
- console.log(`docserve is already serving this folder: ${running.url}`)
154
- return
155
- }
156
- console.error([
157
- "[docserve] A server is already running for a different folder.",
158
- ` url : ${running.url}`,
159
- ` docs : ${running.docsDir}`,
160
- "Stop it first: docserve stop",
161
- ].join("\n"))
162
- process.exit(1)
163
+ if (args.open) openBrowser(running.url)
164
+ console.log(`docserve is already serving this folder: ${running.url}`)
165
+ return
163
166
  }
164
167
 
165
168
  if (args.background) return startBackground(args, docsDir)
@@ -177,7 +180,7 @@ async function startBackground(args, docsDir) {
177
180
  const child = spawn(process.execPath, childArgs, { detached: true, stdio: "ignore" })
178
181
  child.unref()
179
182
 
180
- const state = await waitForState()
183
+ const state = await waitForState(child.pid)
181
184
  if (!state) {
182
185
  console.error("[docserve] Server did not report startup (no state file). Try running in the foreground.")
183
186
  process.exit(1)
@@ -189,10 +192,11 @@ async function startBackground(args, docsDir) {
189
192
  console.log(" stop : docserve stop")
190
193
  }
191
194
 
192
- async function waitForState({ timeoutMs = 10000, intervalMs = 200 } = {}) {
195
+ // Poll the state dir until the server with the given pid reports its state.
196
+ async function waitForState(pid, { timeoutMs = 10000, intervalMs = 200 } = {}) {
193
197
  const deadline = Date.now() + timeoutMs
194
198
  while (Date.now() < deadline) {
195
- const state = readLiveState()
199
+ const state = listLiveStates().find((entry) => entry.pid === pid)
196
200
  if (state) return state
197
201
  await new Promise((resolve) => setTimeout(resolve, intervalMs))
198
202
  }
package/index.html CHANGED
@@ -35,7 +35,7 @@
35
35
  background: var(--bg);
36
36
  color: var(--text);
37
37
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Hiragino Sans", "Noto Sans JP", sans-serif;
38
- padding: 40px 24px;
38
+ padding: 40px 80px;
39
39
  }
40
40
 
41
41
  h1 {
@@ -134,12 +134,20 @@
134
134
  flex: 1;
135
135
  flex-direction: column;
136
136
  justify-content: space-between;
137
- gap: 6px;
137
+ gap: 8px;
138
138
  padding: 10px 12px;
139
139
  border-top: 1px solid var(--border);
140
140
  }
141
141
 
142
142
  .meta .title { font-size: 0.85rem; font-weight: 600; line-height: 1.4; }
143
+ .meta .title .favicon {
144
+ width: 16px;
145
+ height: 16px;
146
+ margin-right: 6px;
147
+ vertical-align: -3px;
148
+ border-radius: 4px;
149
+ object-fit: contain;
150
+ }
143
151
  .date { font-size: 0.7rem; color: var(--muted); }
144
152
 
145
153
  .empty {
@@ -289,7 +297,18 @@
289
297
  }),
290
298
  ]),
291
299
  el("div", { class: "meta" }, [
292
- el("div", { class: "title", text: file.title }),
300
+ el("div", { class: "title" }, [
301
+ file.favicon
302
+ ? el("img", {
303
+ class: "favicon",
304
+ src: file.favicon,
305
+ alt: "",
306
+ loading: "lazy",
307
+ onerror: (e) => e.currentTarget.remove(),
308
+ })
309
+ : null,
310
+ el("span", { text: file.title }),
311
+ ]),
293
312
  el("div", { class: "date", text: displayDate(file.created) }),
294
313
  ]),
295
314
  ])
@@ -324,12 +343,14 @@
324
343
  }
325
344
 
326
345
  function connectLiveReload() {
327
- // Reload when the set of files changes; a dropped socket recovers after restart.
346
+ // Reload when the set of files or the gallery template itself changes;
347
+ // a dropped socket recovers after restart.
328
348
  const ws = new WebSocket(`${location.protocol === "https:" ? "wss:" : "ws:"}//${location.host}/__reload`)
329
349
  ws.addEventListener("message", (e) => {
330
350
  let change
331
351
  try { change = JSON.parse(e.data) } catch { return }
332
- if (change?.type === "change" && change.contentSetChanged) location.reload()
352
+ if (change?.type === "change" && (change.contentSetChanged || change.templateChanged))
353
+ location.reload()
333
354
  })
334
355
  ws.addEventListener("close", () => setTimeout(() => location.reload(), 1000))
335
356
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noy4/docserve",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Serves a folder of HTML as a card gallery with live reload.",
5
5
  "type": "module",
6
6
  "bin": {
package/server/files.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  // File metadata for /api/files: recursive *.html listing (excluding index.html),
2
- // <title> / <meta name="created_at"> extraction, and git date maps cached per
3
- // repo root.
2
+ // <title> / <meta name="created_at"> / <link rel="icon"> extraction, and git date
3
+ // maps cached per repo root.
4
4
  //
5
5
  // Created-date priority: meta created_at > oldest git add commit > birthtime.
6
6
  import { open, readdir, stat } from "node:fs/promises"
7
7
  import { realpathSync } from "node:fs"
8
- import { basename, isAbsolute, join, relative, sep } from "node:path"
8
+ import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"
9
9
  import { execFile } from "node:child_process"
10
10
  import { promisify } from "node:util"
11
11
 
@@ -43,7 +43,7 @@ export async function apiFiles(docsDir) {
43
43
  } catch {
44
44
  continue // deleted between listing and stat
45
45
  }
46
- const { title, date } = await metaOf(full, st.mtimeMs)
46
+ const { title, date, favicon } = await metaOf(full, st.mtimeMs, docsDir)
47
47
  let key
48
48
  try {
49
49
  key = realpathSync(full)
@@ -55,6 +55,7 @@ export async function apiFiles(docsDir) {
55
55
  title: title ?? basename(full),
56
56
  url: `/${rel}`,
57
57
  path: full,
58
+ favicon: favicon ?? undefined,
58
59
  created: date ?? created.get(key) ?? Math.floor(st.birthtimeMs / 1000),
59
60
  modified: modified.get(key) ?? Math.floor(st.mtimeMs / 1000),
60
61
  })
@@ -63,20 +64,21 @@ export async function apiFiles(docsDir) {
63
64
  return files
64
65
  }
65
66
 
66
- // <title> + <meta name="created_at"> extracted from the head of a report; cached by
67
- // path + mtime so repeated /api/files calls only re-read files that changed.
68
- const metaCache = new Map() // "path:mtimeMs" -> { title, created }
67
+ // <title>, <meta name="created_at"> and <link rel="icon"> extracted from the head
68
+ // of a report; cached by path + mtime so repeated /api/files calls only re-read
69
+ // files that changed.
70
+ const metaCache = new Map() // "path:mtimeMs" -> { title, date, favicon }
69
71
 
70
- async function metaOf(full, mtimeMs) {
72
+ async function metaOf(full, mtimeMs, docsDir) {
71
73
  const key = `${full}:${mtimeMs}`
72
74
  const cached = metaCache.get(key)
73
75
  if (cached !== undefined) return cached
74
- const meta = await extractMeta(full)
76
+ const meta = await extractMeta(full, docsDir)
75
77
  metaCache.set(key, meta)
76
78
  return meta
77
79
  }
78
80
 
79
- async function extractMeta(full) {
81
+ async function extractMeta(full, docsDir) {
80
82
  const findTitle = (text) => text.match(/<title>([^<]*)<\/title>/)?.[1]?.trim() ?? null
81
83
  const findDate = (text) => {
82
84
  for (const tag of text.match(/<meta\b[^>]*>/gi) ?? []) {
@@ -86,6 +88,31 @@ async function extractMeta(full) {
86
88
  }
87
89
  return null
88
90
  }
91
+ // Attribute value from a tag string ("v", 'v', or bare); null when absent.
92
+ const attrOf = (tag, name) => {
93
+ const m = tag.match(new RegExp(`(?<![\\w-])${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"))
94
+ return m?.[1] ?? m?.[2] ?? m?.[3] ?? null
95
+ }
96
+ // First <link rel="...icon..."> href resolved to a URL served from docsDir;
97
+ // data: and absolute http(s) URLs are kept as-is.
98
+ const findFavicon = (text) => {
99
+ // Quoted values may contain ">" (inline SVG data URIs), so scan links
100
+ // value-aware instead of with a plain [^>]* tag match.
101
+ for (const tag of text.match(/<link\b(?:"[^"]*"|'[^']*'|[^>])*>/gi) ?? []) {
102
+ const rel = attrOf(tag, "rel")
103
+ if (!rel || !/\bicon\b/i.test(rel)) continue
104
+ const href = attrOf(tag, "href")?.trim()
105
+ if (!href) continue
106
+ if (/^data:/i.test(href)) return href.replaceAll("#", "%23")
107
+ if (/^(https?:|\/\/)/i.test(href)) return href
108
+ const target = href.startsWith("/")
109
+ ? join(docsDir, href.split(/[?#]/)[0])
110
+ : join(dirname(full), href.split(/[?#]/)[0])
111
+ if (!isWithin(docsDir, target)) return null
112
+ return `/${normalizedRelative(docsDir, target)}`
113
+ }
114
+ return null
115
+ }
89
116
  try {
90
117
  const handle = await open(full, "r")
91
118
  try {
@@ -95,13 +122,14 @@ async function extractMeta(full) {
95
122
  }
96
123
  // Titles and meta tags live in <head>; read only the first 4 KB.
97
124
  const head = await read(4096, 0)
98
- let meta = { title: findTitle(head), date: findDate(head) }
99
- if (meta.title === null || meta.date === null) {
125
+ let meta = { title: findTitle(head), date: findDate(head), favicon: findFavicon(head) }
126
+ if (meta.title === null || meta.date === null || meta.favicon === null) {
100
127
  // Fallback for documents with a long preamble (inline favicon etc.)
101
128
  const text = await read(1 << 20, 0)
102
129
  meta = {
103
130
  title: meta.title ?? findTitle(text),
104
131
  date: meta.date ?? findDate(text),
132
+ favicon: meta.favicon ?? findFavicon(text),
105
133
  }
106
134
  }
107
135
  return meta
@@ -109,7 +137,7 @@ async function extractMeta(full) {
109
137
  await handle.close()
110
138
  }
111
139
  } catch {
112
- return { title: null, date: null }
140
+ return { title: null, date: null, favicon: null }
113
141
  }
114
142
  }
115
143
 
package/server/index.mjs CHANGED
@@ -48,7 +48,7 @@ const MIME = {
48
48
 
49
49
  export async function runServer({ docsDir, port: initialPort, open = false }) {
50
50
  const wss = new WebSocketServer({ path: WS_PATH })
51
- const updateListener = new UpdateListener({ wss, docsDir })
51
+ const updateListener = new UpdateListener({ wss, docsDir, templatePath: INDEX_TEMPLATE })
52
52
  let port = initialPort // actually bound port (may fall back +1 on conflict)
53
53
 
54
54
  const cleanup = () => {
package/server/state.mjs CHANGED
@@ -1,20 +1,42 @@
1
- // state.json read/write + pid liveness.
1
+ // Per-instance state files + pid liveness.
2
2
  //
3
- // The server writes ~/.cache/docserve/state.json once the port is bound and
4
- // removes it on clean shutdown. Readers verify the PID is alive and treat
5
- // dead-PID state as stale (removed in place).
3
+ // Each server owns one file: ~/.docserve/state/<port>-<name>.json
4
+ // (name = sanitized folder name), written once the port is bound and removed
5
+ // on clean shutdown. Readers verify the PID is alive and treat dead-PID state
6
+ // as stale (removed in place). DOCSERVE_HOME overrides the docserve home
7
+ // (test isolation).
6
8
  import fs from "node:fs"
7
9
  import os from "node:os"
8
10
  import path from "node:path"
9
11
 
10
- // DOCSERVE_STATE overrides the state file path (test isolation).
11
- export function statePath() {
12
- return process.env.DOCSERVE_STATE || path.join(os.homedir(), ".cache", "docserve", "state.json")
12
+ let ownFile = null // file written by this process, removed by clearState()
13
+
14
+ // DOCSERVE_HOME overrides the docserve home (test isolation).
15
+ export function homeDir() {
16
+ return process.env.DOCSERVE_HOME || path.join(os.homedir(), ".docserve")
17
+ }
18
+
19
+ export function stateDir() {
20
+ return path.join(homeDir(), "state")
13
21
  }
14
22
 
15
- export function readState() {
23
+ // <port>-<name>.json, e.g. 4242-reports.json. The port prefix keeps files
24
+ // unique (the port is exclusively bound while the server runs); the folder
25
+ // name is cosmetic. Parsing always reads the file contents, never the name.
26
+ function fileName(state) {
27
+ const name = path
28
+ .basename(state.docsDir)
29
+ .replace(/[\0\\/:*?"<>|]/g, "-")
30
+ .replace(/\p{Cc}/gu, "")
31
+ .replace(/^\.+/, "")
32
+ .slice(0, 40)
33
+ .replace(/^[-.]+|[-.]+$/g, "")
34
+ return `${state.port}-${name || "docs"}.json`
35
+ }
36
+
37
+ function readStateFile(file) {
16
38
  try {
17
- const state = JSON.parse(fs.readFileSync(statePath(), "utf8"))
39
+ const state = JSON.parse(fs.readFileSync(file, "utf8"))
18
40
  if (
19
41
  typeof state?.pid === "number" &&
20
42
  typeof state?.port === "number" &&
@@ -29,33 +51,65 @@ export function readState() {
29
51
  }
30
52
  }
31
53
 
54
+ export function isProcessAlive(pid) {
55
+ try {
56
+ process.kill(pid, 0)
57
+ return true
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
32
63
  export function writeState(state) {
33
- fs.mkdirSync(path.dirname(statePath()), { recursive: true })
34
- fs.writeFileSync(statePath(), JSON.stringify(state, null, 2) + "\n")
64
+ fs.mkdirSync(stateDir(), { recursive: true })
65
+ const file = path.join(stateDir(), fileName(state))
66
+ const tmp = `${file}.${process.pid}.tmp`
67
+ fs.writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n")
68
+ fs.renameSync(tmp, file)
69
+ ownFile = file
35
70
  }
36
71
 
72
+ // Remove this process's own instance file (server shutdown).
37
73
  export function clearState() {
74
+ if (!ownFile) return
38
75
  try {
39
- fs.rmSync(statePath(), { force: true })
76
+ fs.rmSync(ownFile, { force: true })
40
77
  } catch {}
78
+ ownFile = null
41
79
  }
42
80
 
43
- export function isProcessAlive(pid) {
81
+ // Remove the file of a specific instance (CLI stop).
82
+ export function removeState(state) {
44
83
  try {
45
- process.kill(pid, 0)
46
- return true
47
- } catch {
48
- return false
49
- }
84
+ fs.rmSync(path.join(stateDir(), fileName(state)), { force: true })
85
+ } catch {}
50
86
  }
51
87
 
52
- // Read the state and drop stale entries (dead pid) in place.
53
- export function readLiveState() {
54
- const state = readState()
55
- if (!state) return null
56
- if (!isProcessAlive(state.pid)) {
57
- clearState()
58
- return null
88
+ // All live instances, sorted by port. Stale files (dead pid) are pruned in
89
+ // place; unparseable files are left for inspection.
90
+ export function listLiveStates() {
91
+ let entries = []
92
+ try {
93
+ entries = fs.readdirSync(stateDir())
94
+ } catch {}
95
+ const states = []
96
+ for (const entry of entries) {
97
+ if (!entry.endsWith(".json")) continue
98
+ const file = path.join(stateDir(), entry)
99
+ const state = readStateFile(file)
100
+ if (!state) continue
101
+ if (!isProcessAlive(state.pid)) {
102
+ try {
103
+ fs.rmSync(file, { force: true })
104
+ } catch {}
105
+ continue
106
+ }
107
+ states.push(state)
59
108
  }
60
- return state
109
+ return states.sort((a, b) => a.port - b.port)
110
+ }
111
+
112
+ export function findByDir(docsDir) {
113
+ const resolved = path.resolve(docsDir)
114
+ return listLiveStates().find((state) => state.docsDir === resolved) ?? null
61
115
  }
package/server/watch.mjs CHANGED
@@ -1,18 +1,22 @@
1
1
  // UpdateListener: watch docsDir recursively for *.html changes and broadcast
2
- // debounced batches over the reload socket.
2
+ // debounced batches over the reload socket. The gallery template is watched
3
+ // too; its edits set templateChanged so gallery tabs pick them up even though
4
+ // nothing in docsDir changed.
3
5
  //
4
6
  // The gallery list is every *.html except any index.html; files outside that
5
7
  // set never flip contentSetChanged.
6
8
  import { existsSync, watch } from "node:fs"
7
- import { basename, resolve } from "node:path"
9
+ import { basename, dirname, resolve } from "node:path"
8
10
  import { isWithin, listHtmlFiles, normalizedRelative } from "./files.mjs"
9
11
 
10
12
  const DEBOUNCE_MS = 50 // like livePreview.previewDebounceDelay
13
+ const TEMPLATE_TOUCH = "\u0000template" // sentinel: never a real docsDir-relative path
11
14
 
12
15
  export class UpdateListener {
13
16
  constructor(options = {}) {
14
17
  this.wss = options.wss
15
18
  this.docsDir = options.docsDir
19
+ this.templatePath = options.templatePath
16
20
  this.debounceMs = options.debounceMs ?? DEBOUNCE_MS
17
21
  this.knownFiles = new Set()
18
22
  this.broadcastQueue = Promise.resolve()
@@ -42,12 +46,25 @@ export class UpdateListener {
42
46
  this.queueBroadcast(normalizedRelative(this.docsDir, full))
43
47
  }).on("error", () => {}),
44
48
  )
49
+
50
+ if (this.templatePath) {
51
+ // Watch the template's directory: atomic saves replace the file, so the
52
+ // file itself would miss events.
53
+ const templateName = basename(this.templatePath)
54
+ this.watchers.push(
55
+ watch(dirname(this.templatePath), (event, filename) => {
56
+ if (filename === templateName) this.queueBroadcast(TEMPLATE_TOUCH)
57
+ }).on("error", () => {}),
58
+ )
59
+ }
45
60
  }
46
61
 
47
62
  async broadcastChanges(touched) {
48
63
  let contentSetChanged = false
64
+ const templateChanged = touched.includes(TEMPLATE_TOUCH)
65
+ const pages = touched.filter((rel) => rel !== TEMPLATE_TOUCH)
49
66
 
50
- for (const rel of touched) {
67
+ for (const rel of pages) {
51
68
  if (basename(rel) === "index.html") continue // never a gallery card
52
69
  const full = resolve(this.docsDir, rel)
53
70
  const exists = existsSync(full)
@@ -62,7 +79,7 @@ export class UpdateListener {
62
79
  }
63
80
  }
64
81
 
65
- this.wss.broadcast({ type: "change", pages: touched, contentSetChanged })
82
+ this.wss.broadcast({ type: "change", pages, contentSetChanged, templateChanged })
66
83
  }
67
84
 
68
85
  close() {