@noy4/docserve 0.1.2 → 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.
Files changed (3) hide show
  1. package/bin.mjs +43 -39
  2. package/package.json +1 -1
  3. package/server/state.mjs +80 -26
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noy4/docserve",
3
- "version": "0.1.2",
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/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
  }