Repository navigation
feat(core): docmd serve, a production server for the built site - #273
Merged
Merged
Conversation
…Static Add packages/core/src/server/static.ts (createStaticHandler, MIME_TYPES) and server/ui-assets.ts (resolveUiAsset). `docmd dev` now serves files through it; `docmd serve` (next commit) uses it without the dev parts. - Keeps the existing behaviour: the safePath boundary (403 on traversal, raw and encoded), extensionless -> .html, directory -> 301 + index.html, and a custom 404.html. - Adds Cache-Control: no-cache, a weak ETag (W/"size-mtimeMs") with 304 on If-None-Match (weak comparison), X-Content-Type-Options: nosniff on every response, and HEAD. - The request path is read from the raw URL, so `/../x` reaches safePath and gets 403 instead of being normalised away. Absolute-form targets (`GET http://host/dir`) are reduced to their pathname, and a directory redirect keeps the query string. - Transformed HTML gets its own weak ETag (-t suffix), so a dev-served page and a prod-served page on the same origin never 304 each other. - A throwing extra route answers 500 (or destroys the socket once headers are out) instead of leaving an unhandled rejection. - MIME table: jpeg and woff/ttf types corrected; mjs, map, webmanifest, xml, wasm, webp, avif, otf and pdf added. - dev's serveStatic becomes a thin wrapper that supplies transformHtml (dev identity + api script injection), the "(docmd dev server)" 404 footer and the /__dev/docmd-api.js route; MIME_TYPES is re-exported from dev-utils. The dev-only identity helpers stay in dev-utils, so the handler never references them. - tests/cli-contracts/static-server.test.js (loopback HTTP, port 0), registered as `static-server` in tests/runner.js.
`docmd serve` builds the site once, then serves it with the production
static handler. Unlike `docmd dev` it does not open a browser, watch
files, probe for a free port, inject developer identity or touch stdin.
- Binds host:port first and answers 503 (/healthz included) until the
startup build finishes, so a second `docmd serve` against a live port
fails with "Port N is already in use" and never wipes the running
instance's output. There is no fallback to port + 1.
- The output dir is cleared before the build, so stale files are never
served. An output dir equal to or containing the project root or the
source dir (including `/`) is refused (outputDirConflict).
- Bind address: CLI > DOCMD_HOST / PORT > serve.host / serve.port >
127.0.0.1:3000 (resolveServeBind). The port is validated once, on the
resolved value.
- `serve` config section with `host` and `port`: normalizeServeConfig
never throws, so build and dev keep working with a bad block; `serve`
is a known config key, so no unknown-key warning.
- createServeRouter: GET/HEAD /healthz returns
{"status":"ok","version":...} (405 for other methods); everything else
goes to the static handler. A WebSocket upgrade gets HTTP 404.
- SIGTERM/SIGINT close the server and the worker pool and exit 0. Idle
connections close at once; in-flight ones may finish within a 4 s
budget (below `docmd stop`'s 5 s grace), then are cut.
- Workspace roots are refused for now; every startup failure exits 1.
- `docmd stop`: the command-line matcher is exported as isDocmdCommand
and recognises `docmd serve`.
- CLI: `serve` command and help line, `stop` help mentions dev/serve,
`serve` exported from @docmd/core.
- Tests: serve.test.js (precedence table, config defaults, router,
output-dir guard, stop predicate, one long-lived serve spawn covering
the build, stale files, no dev script, upgrade 404, SIGTERM and no
browser), serve-startup.test.js (port in use, invalid config,
workspace, SIGINT), a `serve --host 0.0.0.0` spawn in host-flag, and
the shared tests/_lib/serve-harness.js.
This was referenced Nov 11, 2026
Member
|
Milestone feature! Step 4 of #267 brings first-class This finally provides a dedicated, lightweight production static server with proper caching headers ( Comprehensive test coverage across all edge cases. Merging! |
mgks
added a commit
that referenced
this pull request
Nov 11, 2026
…ture additions Synchronize working branch 'dev-0.9.10' with 'main' following the review, security audit, and integration of 6 community pull requests alongside our static asset root mirroring feature. Merged Community Contributions: - PR #271 (@GPT-AGI / Ting Zhang): fix(parser): resolve folder-index links from nested pages Fixes relative link resolution for non-index folder references from deep subdirectories. - PR #274 (@svallory): fix(core): build finds 0 pages when an ancestor folder matches .gitignore Confines gitignore matching to repository root and avoids empty builds when parent paths match ignore patterns. - PR #275 (@svallory): fix(build): keep git tree clean after pnpm -r run build Eliminates timestamps from generated plugin registry and ignores pre-built native binaries across architectures. - PR #276 (@svallory): fix(tests): give each test run its own temp fixture root Isolates test fixtures into unique run directories under os.tmpdir() to prevent concurrency collisions. - PR #272 (@svallory): feat(api,core): plugin actions receive caller context; one shared action host Introduces shared ActionHost with caller context (identity, mode, transport, headers without cookies), origin allowlisting, and unified rebuild queue. - PR #273 (@svallory): feat(core): docmd serve, a production server for the built site Adds zero-dependency production HTTP/WS server with gzip compression, security headers (CSP, HSTS, CORS), health check endpoints (/healthz, /livez, /readyz), and SPA / clean URL routing. Working Branch Features Included: - feat(core): Zero-config static root asset mirroring Copies static assets from 'public/' or 'static/' (and docs/public/) directly to the output root ('site/'), preserving directory structure and files like 'funding.json', 'CNAME', and '.well-known/'. Adds canonical 'static' configuration option with support for boolean or custom directory lists. - feat(cli): --host flag support for dev and serve commands (defaults to loopback 127.0.0.1 for CWE-1385 protection, configurable to 0.0.0.0 for container / LAN hosting). Documentation Impact: - Configuration Reference: Document 'static' setting (boolean | string[]). - CLI Reference: Document 'docmd serve' command options and '--host' flag. - Plugin Guide: Document ActionHost caller context and execution modes.
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Step 4 of #267.
docmd servebuilds the site once and serves it with a production static handler. No browser, no file watcher, no port probing, no dev script injection. This PR is static serving only: plugin actions underservecome in step 5 and use the action host from step 3.Why docmd needs it
devin production: the official Docker image's default command isdev --host 0.0.0.0(docker/Dockerfile:185). [Bug]:docmd devcrashes in the official Docker image because it always tries to spawnxdg-open#156 (docmd devcrashing onxdg-openin the container) is what happens when laptop behaviour runs there.servegives the image a real production mode.requiresLiveServerand register actions, but onlydocmd devhosts them, so a plugin that writes cannot work on a deployed site. This command is the base the next steps build on.preview, Nextstart, Docusaurusserve. Today docmd users reach fornpx serve site.devsimple.devstays the laptop tool (localhost origin guard, auto-open, port + 1, watcher,isDevbuilds);servegets the production rules.Static handler (
packages/core/src/server/static.ts), first commitserveStatic, which becomes a thin wrapper that adds the dev parts (identity and api script injection, the dev 404 footer,/__dev/docmd-api.js). Behaviour fordocmd devis unchanged.safePathboundary (403 on raw and encoded traversal), extensionless →.html, directory → 301 +index.html, custom404.html.Cache-Control: no-cache, a weak ETag with 304 onIf-None-Match,X-Content-Type-Options: nosniffon every response, andHEAD. Absolute-form targets (GET http://host/dir) are reduced to their pathname.jpegandwoff/ttfcorrected;mjs,map,webmanifest,xml,wasm,webp,avif,otf,pdfadded.docmd serve(packages/core/src/commands/serve.ts), second commithost:portfirst and answers 503 until the startup build finishes, so a seconddocmd serveon a live port fails with "Port N is already in use" and never wipes the running instance's output. No fallback to port + 1.--host/--port>DOCMD_HOST/PORT>serve.host/serve.portin the config >127.0.0.1:3000.GET/HEAD /healthzreturns{"status":"ok","version":"…"}for container health checks; a WebSocket upgrade gets 404.SIGTERM/SIGINTclose the server and the worker pool and exit 0 within 4 s (belowdocmd stop's 5 s grace).docmd stopnow recognisesdocmd serveprocesses.serveconfig section withhostandportonly. It never throws inbuildordev, andserveis a known key, so no unknown-key warning.Not in this PR: the Docker image's default command. Switching it to
serveis step 7, together with the docs.Type of change
How it was verified
New test files, registered in
tests/runner.js:tests/cli-contracts/static-server.test.js: two in-process servers on port 0 (bare and with the dev wrapper). Caching headers and 304, traversal (raw, encoded, sibling-prefix), the MIME table, HEAD over a raw socket, absolute-form targets, directory redirects, custom 404, a throwing extra route, and the dev wrapper's injection.tests/cli-contracts/serve.test.js: the bind precedence table, config defaults, the router in-process, the output-dir guard table, thedocmd stopmatcher, and one realdocmd servespawn (build, stale file not served, no dev script in the HTML, upgrade 404, SIGTERM exit 0 within 5 s, no browser opened).tests/cli-contracts/serve-startup.test.js: port in use, invalid config, workspace root (each exits 1, nothing left listening) and SIGINT.tests/cli-contracts/host-flag.test.jsalso checksserve --host 0.0.0.0and that--helplistsserve.Results:
node tests/runner.js --only=static-server,serve,serve-startup,host-flag,features,validate-workspace: 282 passed, 0 failed./healthzaccepting any method;serve.hostnot falling back to the default;safePathwithpath.joinin the static handler.pnpm lint: 0 errors, 1400 warnings (main: 1403). The new files have no warnings.Checklist:
servedocs page follows in step 7, with plugin actions)