@johnhenry/sitefile 0.0.1 → 0.0.3

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 (130) hide show
  1. package/CHANGELOG.md +480 -3
  2. package/README.md +70 -21
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/canonical.d.ts +16 -0
  6. package/lib/src/canonical.js +46 -0
  7. package/lib/src/car.d.ts +34 -0
  8. package/lib/src/car.js +203 -0
  9. package/lib/src/checklinks.js +8 -2
  10. package/lib/src/cli/bake.js +4 -3
  11. package/lib/src/cli/build-image.d.ts +1 -0
  12. package/lib/src/cli/build-image.js +1 -0
  13. package/lib/src/cli/common.js +4 -1
  14. package/lib/src/cli/hosts.d.ts +5 -0
  15. package/lib/src/cli/hosts.js +78 -0
  16. package/lib/src/cli/images.js +23 -5
  17. package/lib/src/cli/import-config.d.ts +2 -0
  18. package/lib/src/cli/import-config.js +56 -0
  19. package/lib/src/cli/index.d.ts +3 -1
  20. package/lib/src/cli/index.js +31 -2
  21. package/lib/src/cli/integrity.d.ts +2 -0
  22. package/lib/src/cli/integrity.js +77 -0
  23. package/lib/src/cli/network.d.ts +7 -0
  24. package/lib/src/cli/network.js +14 -3
  25. package/lib/src/cli/serve-keys.d.ts +39 -0
  26. package/lib/src/cli/serve-keys.js +106 -0
  27. package/lib/src/cli/serve-worker.js +46 -8
  28. package/lib/src/cli/servers.d.ts +124 -1
  29. package/lib/src/cli/servers.js +705 -62
  30. package/lib/src/cli/up.d.ts +2 -0
  31. package/lib/src/cli/up.js +193 -0
  32. package/lib/src/cli/watch.d.ts +14 -1
  33. package/lib/src/cli/watch.js +20 -3
  34. package/lib/src/cli.js +138 -18
  35. package/lib/src/csp.d.ts +17 -0
  36. package/lib/src/csp.js +52 -0
  37. package/lib/src/dictionary.d.ts +16 -0
  38. package/lib/src/dictionary.js +89 -0
  39. package/lib/src/epub.d.ts +5 -0
  40. package/lib/src/epub.js +113 -0
  41. package/lib/src/errors.d.ts +22 -9
  42. package/lib/src/errors.js +20 -1
  43. package/lib/src/executor.d.ts +31 -1
  44. package/lib/src/executor.js +192 -22
  45. package/lib/src/explain.js +33 -3
  46. package/lib/src/export-for.d.ts +42 -0
  47. package/lib/src/export-for.js +466 -0
  48. package/lib/src/export-formats.d.ts +2 -2
  49. package/lib/src/export-formats.js +52 -2
  50. package/lib/src/fingerprint.d.ts +3 -1
  51. package/lib/src/fingerprint.js +32 -5
  52. package/lib/src/host-config.d.ts +34 -0
  53. package/lib/src/host-config.js +645 -0
  54. package/lib/src/hosts.d.ts +47 -0
  55. package/lib/src/hosts.js +106 -0
  56. package/lib/src/index.d.ts +1 -1
  57. package/lib/src/index.js +1 -1
  58. package/lib/src/integrity.d.ts +115 -0
  59. package/lib/src/integrity.js +273 -0
  60. package/lib/src/language/ast.d.ts +116 -3
  61. package/lib/src/language/ast.js +7 -1
  62. package/lib/src/language/parser.js +176 -7
  63. package/lib/src/language/validate.js +21 -0
  64. package/lib/src/links.d.ts +33 -0
  65. package/lib/src/links.js +271 -3
  66. package/lib/src/lint.d.ts +1 -1
  67. package/lib/src/lint.js +26 -1
  68. package/lib/src/mime-data.d.ts +2 -0
  69. package/lib/src/mime-data.js +92 -0
  70. package/lib/src/oci.d.ts +20 -2
  71. package/lib/src/oci.js +70 -28
  72. package/lib/src/outdated.d.ts +3 -0
  73. package/lib/src/outdated.js +4 -4
  74. package/lib/src/planner.d.ts +69 -2
  75. package/lib/src/planner.js +150 -8
  76. package/lib/src/plugins/cache.d.ts +11 -0
  77. package/lib/src/plugins/cache.js +29 -0
  78. package/lib/src/plugins/host.d.ts +51 -2
  79. package/lib/src/plugins/host.js +144 -18
  80. package/lib/src/plugins/wasm.js +1 -3
  81. package/lib/src/portable.d.ts +8 -0
  82. package/lib/src/portable.js +47 -0
  83. package/lib/src/precache.d.ts +33 -0
  84. package/lib/src/precache.js +75 -0
  85. package/lib/src/precompress.d.ts +19 -0
  86. package/lib/src/precompress.js +35 -0
  87. package/lib/src/qr.d.ts +18 -0
  88. package/lib/src/qr.js +372 -0
  89. package/lib/src/registry-ops.js +4 -2
  90. package/lib/src/reload-client.d.ts +2 -0
  91. package/lib/src/reload-client.js +304 -0
  92. package/lib/src/resources/archive.d.ts +36 -0
  93. package/lib/src/resources/archive.js +338 -67
  94. package/lib/src/resources/convert.js +3 -1
  95. package/lib/src/resources/https.d.ts +9 -1
  96. package/lib/src/resources/https.js +36 -0
  97. package/lib/src/resources/network.d.ts +25 -3
  98. package/lib/src/resources/network.js +77 -6
  99. package/lib/src/secrets.d.ts +12 -3
  100. package/lib/src/secrets.js +18 -5
  101. package/lib/src/serve-auth.d.ts +32 -0
  102. package/lib/src/serve-auth.js +112 -0
  103. package/lib/src/serve-rules.d.ts +83 -7
  104. package/lib/src/serve-rules.js +264 -53
  105. package/lib/src/server.d.ts +437 -10
  106. package/lib/src/server.js +1236 -52
  107. package/lib/src/servers-file.d.ts +36 -0
  108. package/lib/src/servers-file.js +101 -0
  109. package/lib/src/servers.d.ts +109 -7
  110. package/lib/src/servers.js +151 -29
  111. package/lib/src/single-file.d.ts +12 -0
  112. package/lib/src/single-file.js +147 -0
  113. package/lib/src/site.d.ts +54 -0
  114. package/lib/src/site.js +204 -6
  115. package/lib/src/store.js +9 -5
  116. package/lib/src/swbn.d.ts +10 -0
  117. package/lib/src/swbn.js +86 -0
  118. package/lib/src/toml.d.ts +17 -0
  119. package/lib/src/toml.js +323 -0
  120. package/lib/src/wacz.d.ts +6 -0
  121. package/lib/src/wacz.js +96 -0
  122. package/lib/src/warc.d.ts +28 -0
  123. package/lib/src/warc.js +252 -0
  124. package/lib/src/watch.d.ts +12 -1
  125. package/lib/src/watch.js +67 -1
  126. package/lib/src/wbn.d.ts +9 -1
  127. package/lib/src/wbn.js +23 -33
  128. package/lib/src/zstd.d.ts +4 -0
  129. package/lib/src/zstd.js +328 -0
  130. package/package.json +1 -1
@@ -1,27 +1,251 @@
1
1
  import http from 'node:http';
2
+ import { SitefileError } from './errors.js';
3
+ import { type FetchPolicy } from './resources/types.js';
4
+ import { type RedirectRequest, type ServeRedirect } from './serve-rules.js';
2
5
  import type { Tree } from './tree.js';
6
+ import { RELOAD_CLIENT } from './reload-client.js';
7
+ import type { BasicAuth } from './serve-auth.js';
8
+ /** `serve`'s proxying (#172): `--proxy` routes and the fetch policy every proxied request follows. */
9
+ export interface ServeProxy {
10
+ /** `--proxy /prefix=https://host/path`: requests under `prefix` go to `target` + the rest of the path. */
11
+ readonly routes: ReadonlyArray<{
12
+ readonly prefix: string;
13
+ readonly target: string;
14
+ }>;
15
+ /**
16
+ * The policy: https only unless allowHttp, public addresses only unless allowPrivateNetwork, and a strict
17
+ * host list (`--allow-hosts`, plus each `--proxy` route's host): a `_redirects` proxy rule to any other
18
+ * host is refused.
19
+ */
20
+ readonly policy: FetchPolicy;
21
+ }
3
22
  export interface SiteServerOptions {
4
- /** Fall back to `/index.html` for unknown extension-less paths (single-page apps). */
23
+ /**
24
+ * Single-page apps: answer a page navigation ({@link isNavigation}) for a path nothing else answers
25
+ * with the nearest app shell ({@link spaFallback}). Never for subresources (scripts, images, `fetch()`).
26
+ */
5
27
  readonly spa?: boolean;
28
+ /** Proxy rules (`_redirects` status 200 to a URL) and `--proxy` routes; without this every proxy rule is refused. */
29
+ readonly proxy?: ServeProxy;
30
+ /** `--spa-exclude`: request paths (`*` matches any characters) that never fall back. */
31
+ readonly spaExclude?: readonly string[];
32
+ /** `--spa-fallback`: the one file every fallback serves, instead of the nearest `200.html` or `index.html`. */
33
+ readonly spaFallback?: string;
6
34
  /** One access-log line per request: `METHOD /path STATUS BYTES MSms`. */
7
35
  readonly log?: (line: string) => void;
8
36
  /** Sent as `x-sitefile-server` so `servers` can tell its own servers from a reused port. */
9
37
  readonly serverId?: string;
10
38
  /**
11
- * `serve --watch`: answer {@link RELOAD_PATH} with an event stream and add
12
- * {@link RELOAD_SCRIPT} to HTML responses. Never set otherwise, and never written to exports.
39
+ * `serve --watch`: answer {@link RELOAD_PATH} with an event stream and {@link RELOAD_SCRIPT_PATH}
40
+ * with the client script, and add {@link RELOAD_SCRIPT} to HTML navigations. Never set otherwise,
41
+ * and never written to exports.
13
42
  */
14
43
  readonly liveReload?: LiveReload;
44
+ /**
45
+ * When the served files last changed (Unix seconds), read per request: sent as `Last-Modified` on
46
+ * file responses, and `If-Modified-Since` (without `If-None-Match`) gives `304`. Unset: neither.
47
+ */
48
+ readonly lastModified?: () => number | undefined;
49
+ /** Problems a person should know about (without the `warning: ` prefix), e.g. a CSP that blocks live reload. */
50
+ readonly warn?: (message: string) => void;
51
+ /**
52
+ * `--base /repo/`: serve the site under this path prefix (a GitHub Pages project site); `/`
53
+ * redirects to it, `/repo` gets its slash, everything else is 404. Normalized by {@link normalizeBase}.
54
+ */
55
+ readonly base?: string | (() => string | undefined);
56
+ /**
57
+ * `--rewrite-base`: the production URL ({@link normalizeProductionUrl}) that HTML, CSS and XML
58
+ * responses have replaced by this server's origin and `--base`, so absolute self-links stay local.
59
+ */
60
+ readonly rewriteBase?: string | (() => string | undefined);
61
+ /** `--host-profile` / `--html-handling`: behave like a static host ({@link hostProfile}). Absent: sitefile's own rules. */
62
+ readonly profile?: RoutingProfile;
63
+ /**
64
+ * Foreground and `--watch` servers (never detached or shared ones): a 404 with no `404.html` to
65
+ * answer it lists near misses ({@link nearMisses}).
66
+ */
67
+ readonly devNotFound?: boolean;
68
+ /** `--country`: what `_redirects` `Country=` conditions match (there is no geolocation locally). */
69
+ readonly country?: string;
70
+ /**
71
+ * DNS-rebinding guard: when set, a request whose `Host` is not `localhost`, a `*.localhost` name,
72
+ * an IP address or a name this list allows gets `403` ({@link hostAllowed}). `*` allows every
73
+ * host; unset: no check (the CLI always sets it).
74
+ */
75
+ readonly allowedHosts?: readonly string[];
76
+ /** `--cors`: `Access-Control-Allow-Origin: *` on every response (`_headers` still wins) and `OPTIONS` preflights answered with `204`. */
77
+ readonly cors?: boolean;
78
+ /**
79
+ * `--isolate`: cross-origin isolation (SharedArrayBuffer, wasm threads) on every response:
80
+ * `Cross-Origin-Opener-Policy: same-origin`, this `Cross-Origin-Embedder-Policy` and
81
+ * `Cross-Origin-Resource-Policy: same-origin`. `_headers` still wins.
82
+ */
83
+ readonly isolate?: 'require-corp' | 'credentialless';
84
+ /** `--max-age`, `--immutable`, `--max-age-html`: a production `Cache-Control` preview for files ({@link cacheControlFor}). */
85
+ readonly cache?: CachePreview;
86
+ /** `--log-format`: access-log lines as text (the default, `GET /path 200 1234 1.2ms`) or one JSON object each ({@link accessLogLine}). */
87
+ readonly logFormat?: 'text' | 'json';
88
+ /** `--log-ip`: add the client address to access-log lines. */
89
+ readonly logIp?: boolean;
90
+ /** `--quiet`: no access-log lines (other log lines still go to {@link log}). */
91
+ readonly quiet?: boolean;
92
+ /** `--auth`, `--auth-file`: every request needs one of these credentials (`Authorization: Basic`), else `401`. */
93
+ readonly auth?: BasicAuth;
94
+ /** `--max-connections-per-ip`: open connections one non-loopback client may hold (0 or unset: no limit); a connection over it gets `503` with `Retry-After: 1` and is closed. */
95
+ readonly maxConnectionsPerIp?: number;
96
+ /** Count loopback clients against {@link maxConnectionsPerIp} too (tests only). */
97
+ readonly limitLoopback?: boolean;
98
+ /** `--random-route`: {@link base} is a secret, so `/` is a plain `404` instead of a redirect into it. */
99
+ readonly hideBase?: boolean;
100
+ /** `--allow-ip`, `--deny-ip` (CIDRs, {@link parseCidr}): a non-loopback client they refuse gets `403` before anything else. */
101
+ readonly ipRules?: {
102
+ readonly allow: readonly Cidr[];
103
+ readonly deny: readonly Cidr[];
104
+ };
105
+ /** `X-Robots-Tag: noindex` on every response (the CLI sets it on non-loopback binds). */
106
+ readonly noindex?: boolean;
107
+ /** Add the client address and device (from `User-Agent`) to access-log lines of non-loopback clients. */
108
+ readonly clientInfo?: boolean;
109
+ /** `--tls-cert`, `--tls-key`: serve HTTPS with this PEM certificate chain and private key. */
110
+ readonly tls?: {
111
+ readonly cert: string | Uint8Array;
112
+ readonly key: string | Uint8Array;
113
+ };
114
+ /** `--compress`: gzip compressible files of at least 1024 bytes on the fly when no precompressed variant exists. */
115
+ readonly compress?: boolean;
116
+ /** `--throttle`: response bandwidth (bytes per second) and latency added before each response. */
117
+ readonly throttle?: Throttle;
118
+ /** `--mime`, `--mime-file`: content types by lowercase extension, checked before the built-in table. */
119
+ readonly mime?: ReadonlyMap<string, string>;
120
+ /**
121
+ * Where file contents come from when the tree holds only digests (a zip served in place,
122
+ * `openZipFile`): `read` returns a file's bytes (undefined: use the node's), `deflated` a
123
+ * deflated file's raw deflate stream, sent as `content-encoding: gzip` to clients that accept it.
124
+ */
125
+ readonly content?: SiteContent;
126
+ }
127
+ /** Contents read on demand ({@link SiteServerOptions.content}). */
128
+ export interface SiteContent {
129
+ read(path: string): Uint8Array | undefined;
130
+ deflated?(path: string): {
131
+ readonly deflate: Uint8Array;
132
+ readonly crc: number;
133
+ readonly size: number;
134
+ } | undefined;
15
135
  }
136
+ /** Whether an `accept-encoding` header accepts gzip (`gzip` or `x-gzip` with a non-zero q). */
137
+ export declare function acceptsGzip(header: string | undefined): boolean;
138
+ /** A gzip member around a raw deflate stream: fixed header (no name, mtime 0, OS unknown), CRC-32 and size. */
139
+ export declare function gzipMember(deflate: Uint8Array, crc: number, size: number): Uint8Array;
16
140
  /** Reserved for the live-reload event stream while `serve --watch` runs. */
17
141
  export declare const RELOAD_PATH = "/__sitefile/reload";
18
- /** Added to served HTML (before the last `</body>`, else at the end) under `serve --watch`. */
19
- export declare const RELOAD_SCRIPT = "<script>new EventSource(\"/__sitefile/reload\").onmessage=function(){location.reload()}</script>";
20
- /** Open live-reload streams; {@link LiveReload.reload} tells every page to reload. */
142
+ /** Reserved for the live-reload client script ({@link RELOAD_CLIENT}) while `serve --watch` runs. */
143
+ export declare const RELOAD_SCRIPT_PATH = "/__sitefile/reload.js";
144
+ /** Added to navigated HTML (before the last `</body>`, else at the end) under `serve --watch`. */
145
+ export declare const RELOAD_SCRIPT = "<script src=\"/__sitefile/reload.js\"></script>";
146
+ export { RELOAD_CLIENT };
147
+ /**
148
+ * Whether a request is a page navigation, which gets the reload script: `Sec-Fetch-Mode: navigate`
149
+ * when the browser sends it, else `Sec-Fetch-Dest` document/iframe/frame, else an `Accept` naming
150
+ * `text/html`. A `fetch()` of an HTML fragment is none of these and is served unchanged.
151
+ */
152
+ export declare function isNavigation(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
153
+ /**
154
+ * The directive of a `Content-Security-Policy` value that blocks live reload: `script-src` when
155
+ * a same-origin script cannot run, `connect-src` when the event stream cannot connect, else
156
+ * undefined. A comma separates policies, and each one is enforced. Only `'self'`, `*`, `http:` and
157
+ * `https:` count as allowing the server's own origin (host sources are not matched), and
158
+ * `'strict-dynamic'` makes `'self'` ignored for scripts.
159
+ */
160
+ export declare function cspBlocksReload(value: string): 'script-src' | 'connect-src' | undefined;
161
+ /** Heartbeat interval on the event stream. */
162
+ export declare const HEARTBEAT_MS = 15000;
163
+ /** Headers of the event stream (also on HEAD): no proxy buffering (`X-Accel-Buffering`), no compression or other transforms. */
164
+ export declare const STREAM_HEADERS: Readonly<Record<string, string>>;
165
+ /** What the client script does besides reloading (`serve --watch` flags). */
166
+ export interface LiveReloadOptions {
167
+ /** Unregister the page's service workers and empty its Cache Storage before each reload (default true; `--keep-service-workers` turns it off). */
168
+ readonly resetServiceWorkers?: boolean;
169
+ /** Swap changed stylesheets in place instead of reloading when only CSS changed (default true; `--no-css-inject` turns it off). */
170
+ readonly cssInject?: boolean;
171
+ /** Forward the page's `console.log`/`console.info` too, not only errors and warnings (`--console`). */
172
+ readonly console?: boolean;
173
+ /** Show a Rebuilding badge and a build-error overlay in the page (default true; `--no-overlay` turns it off). */
174
+ readonly overlay?: boolean;
175
+ /** After a rebuild that changed exactly one page, go to that page (`--navigate-to-changed`; default false). */
176
+ readonly navigateToChanged?: boolean;
177
+ /** `--reload`: `morph` (default) updates a page in place when only HTML changed; `full` always reloads. */
178
+ readonly reload?: 'full' | 'morph';
179
+ }
180
+ /** The script served at {@link RELOAD_SCRIPT_PATH}: {@link RELOAD_CLIENT} called with `options` (keys in a fixed order). */
181
+ export declare function clientScript(options?: LiveReloadOptions): string;
182
+ /** Reserved for browser console messages (POST) while `serve --watch` runs. */
183
+ export declare const CONSOLE_PATH = "/__sitefile/console";
184
+ /** Largest console message body accepted (bytes). */
185
+ export declare const MAX_CONSOLE_BODY: number;
186
+ /** At most this many console messages are logged per {@link CONSOLE_WINDOW_MS}. */
187
+ export declare const CONSOLE_LIMIT = 50;
188
+ export declare const CONSOLE_WINDOW_MS = 10000;
189
+ /**
190
+ * The server-log lines for one console message body (JSON `{level, message, stack, url, line, col}`),
191
+ * or undefined when it is not one. `level` is error, warn, log or info; log and info give no lines
192
+ * unless `all` (`--console`). The first line is `browser <level>: <message> (<url>:<line>:<col>)`;
193
+ * up to 5 stack lines follow, indented.
194
+ */
195
+ export declare function consoleLines(body: string, all: boolean): string[] | undefined;
196
+ /** A console POST comes from a page of this server: `Origin` is `http(s)://<Host>`, and `Sec-Fetch-Site` (when sent) is same-origin. */
197
+ export declare function isSameOriginPost(headers: Readonly<Record<string, string | string[] | undefined>>): boolean;
198
+ /** The event that tells every page to reload. */
199
+ export declare const RELOAD_EVENT = "{\"type\":\"reload\"}";
200
+ /** Sent when a rebuild starts (pages show a Rebuilding badge). */
201
+ export declare const BUILDING_EVENT = "{\"type\":\"building\"}";
202
+ /** Sent after a good rebuild that changed nothing (pages clear the badge and any error overlay). */
203
+ export declare const OK_EVENT = "{\"type\":\"ok\"}";
204
+ /** The event for a failed rebuild: `{"type":"error","code","message"[,"file","line","column"]}`. */
205
+ export declare function errorEvent(e: SitefileError): string;
206
+ /**
207
+ * The URL path that serves `file`: `/dir/` for `/dir/index.html` (and `/` for `/index.html`),
208
+ * else the file path; each segment percent-encoded like encodeURIComponent.
209
+ */
210
+ export declare function pageUrlFor(file: string): string;
211
+ /**
212
+ * The live-reload event for a new tree (undefined when no file changed): `{"type":"css","paths":[...]}`
213
+ * when `cssInject` is on and every changed file is a stylesheet that is in both trees (added or
214
+ * removed files always reload), else {@link RELOAD_EVENT}; with `navigate`, a reload where exactly
215
+ * one HTML file was added or changed also names its page: `{"type":"reload","path":"/posts/a/"}`.
216
+ * A reload where only existing HTML files changed (nothing added or removed, no other type) is
217
+ * marked `"morph":true`: pages may update in place. Paths are sorted.
218
+ */
219
+ export declare function reloadEventFor(prev: Tree, next: Tree, cssInject: boolean, navigate?: boolean): string | undefined;
220
+ /** Open live-reload streams; {@link LiveReload.send} gives every page an event ({@link LiveReload.reload}: reload). */
21
221
  export declare class LiveReload {
22
222
  private readonly clients;
23
- /** Hold `res` open as a text/event-stream until the client goes away. */
223
+ /** The client script for this session ({@link clientScript}). */
224
+ readonly script: string;
225
+ /** Time between heartbeat comments on an open stream (15 s; tests pass less). */
226
+ private readonly heartbeatMs;
227
+ constructor(options?: LiveReloadOptions, heartbeatMs?: number);
228
+ /**
229
+ * Hold `res` open as a text/event-stream until the client goes away. The headers keep proxies
230
+ * and tunnels from buffering or compressing it, and a comment every 15 s keeps idle
231
+ * connections from being cut (and finds clients that went away).
232
+ */
24
233
  attach(res: http.ServerResponse, headers: Record<string, string>): void;
234
+ readonly console: boolean;
235
+ private consoleWindow;
236
+ private consoleCount;
237
+ /**
238
+ * Whether one more console message may be logged now (at most {@link CONSOLE_LIMIT} per
239
+ * {@link CONSOLE_WINDOW_MS}); the first refused one in a window also returns a notice line.
240
+ */
241
+ admitConsole(now: number): {
242
+ ok: boolean;
243
+ notice?: string;
244
+ };
245
+ /** The last error event, until a good build: sent to streams that open meanwhile. */
246
+ private failure;
247
+ /** Send `event` (one line of JSON) to every open page. */
248
+ send(event: string): void;
25
249
  reload(): void;
26
250
  get size(): number;
27
251
  }
@@ -29,11 +253,206 @@ export declare class LiveReload {
29
253
  export declare function injectReloadScript(html: Uint8Array): Uint8Array;
30
254
  /** Decode a request path into safe segments, or undefined when it is malformed or unsafe. */
31
255
  export declare function safeSegments(rawPath: string): string[] | undefined;
256
+ /**
257
+ * The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
258
+ * section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
259
+ * `/` for an empty path); any other target is returned as it is. The authority is not checked.
260
+ */
261
+ /** One access-log request, as {@link accessLogLine} writes it. */
262
+ export interface AccessLogEntry {
263
+ readonly ts: string;
264
+ readonly method: string;
265
+ /** The request target as received (made printable: other bytes become `%xx`). */
266
+ readonly target: string;
267
+ readonly status: number;
268
+ readonly bytes: number;
269
+ readonly ms: number;
270
+ /** `Content-Range` of a `206`/`416`, else undefined. */
271
+ readonly range?: string;
272
+ /** The client address (`--log-ip`, or a non-loopback client with client info), else undefined. */
273
+ /** What answered, as the `_redirects` log note (` → /new (_redirects:3)`), else undefined. */
274
+ readonly note?: string;
275
+ /** The client address (`--log-ip`), else undefined. */
276
+ readonly remote?: string;
277
+ /** The client's device ({@link deviceOf}), for non-loopback clients with client info. */
278
+ readonly device?: string;
279
+ }
280
+ /**
281
+ * An access-log line. Text: `METHOD target STATUS BYTES MSms` (then ` <remote>` with `--log-ip`). JSON, a stable
282
+ * contract (docs/CLI.md): `{"type":"request","ts","method","path","query","status","bytes","ms","encoding","range"}`
283
+ * and `"remote"` with `--log-ip`, in that order; `path` and `query` split the target at the first `?` (the `?`
284
+ * dropped), `ms` has one decimal, `range` is the response's `Content-Range` or null.
285
+ */
286
+ export declare function accessLogLine(format: 'text' | 'json', e: AccessLogEntry): string;
287
+ /** A log line that is not a request, as a JSON object (`--log-format json`): `warning: …` and `error…` lines get their own types. */
288
+ export declare function jsonLogLine(ts: string, line: string): string;
289
+ /** `{"type":"started","ts","site","files","url"}`: a server is listening (`--log-format json`). */
290
+ export declare function startedLogLine(ts: string, site: string, files: number, url: string): string;
291
+ /** `{"type":"stopped","ts","signal"}`: a server shuts down (`--log-format json`). */
292
+ export declare function stoppedLogLine(ts: string, signal: string): string;
293
+ /**
294
+ * A detached server's log line as JSON (`server logs --json`): JSON lines as they are; a text line
295
+ * (`<ISO time> <rest>`) as a request, started, stopped, warning, error or message object.
296
+ */
297
+ export declare function logLineAsJson(line: string): string;
298
+ /**
299
+ * Whether an `Accept-Encoding` value accepts `coding`: listed (or `*`) with a q-value above 0, ASCII
300
+ * case-insensitive; an explicit entry wins over `*`.
301
+ */
302
+ export declare function acceptsEncoding(header: string | undefined, coding: string): boolean;
303
+ /** Media types worth compressing: `text/*`, JSON, XML, SVG, JavaScript, wasm and `+json`/`+xml` types. */
304
+ export declare function isCompressible(type: string): boolean;
305
+ /** `--throttle` limits ({@link parseThrottle}). */
306
+ export interface Throttle {
307
+ readonly bytesPerSecond: number;
308
+ readonly latencyMs: number;
309
+ }
310
+ /** Presets: Chrome DevTools' "3G" (1.6 Mbit/s, 150 ms) and "Slow 3G" (400 kbit/s, 400 ms). */
311
+ export declare const THROTTLE_PRESETS: Readonly<Record<string, Throttle>>;
312
+ /** `3g`, `slow-3g` or `<kbit/s>[/<latency ms>]`, else undefined. */
313
+ export declare function parseThrottle(value: string): Throttle | undefined;
314
+ /** `--mime ext=type` (a leading `.` is dropped; the extension is lowercased), else undefined. */
315
+ export declare function parseMimeFlag(value: string): [string, string] | undefined;
316
+ /** A `mime.types` file (nginx `types { type ext ...; }` or Apache `type ext ...` lines; `#` comments): ext → type. */
317
+ export declare function parseMimeTypes(text: string, origin: string): Map<string, string>;
318
+ /** Production cache headers to preview instead of `no-cache` (`serve --max-age`). */
319
+ export interface CachePreview {
320
+ /** Seconds for files other than HTML: `public, max-age=N`. */
321
+ readonly maxAge?: number;
322
+ /** Adds `immutable` to the non-HTML value (needs {@link maxAge}). */
323
+ readonly immutable?: boolean;
324
+ /** Seconds for HTML pages (absent: they keep `no-cache`, the common production practice). */
325
+ readonly maxAgeHtml?: number;
326
+ }
327
+ /** The `Cache-Control` a file of media `type` gets under `cache`, or undefined to keep `no-cache`. */
328
+ export declare function cacheControlFor(type: string, cache: CachePreview | undefined): string | undefined;
329
+ /**
330
+ * The origin form of a request target: an absolute-form target (`http://host/path?q`, RFC 9112
331
+ * section 3.2.2, sent by proxies and some clients) loses its scheme and authority (`/path?q`, or
332
+ * `/` for an empty path); any other target is returned as it is. The authority is not checked.
333
+ */
334
+ /** `Access-Control-Request-Headers` echoed in a preflight answer, when it is a plain list of header names. */
335
+ export declare function preflightHeaders(value: string | undefined): string | undefined;
336
+ /** A parsed CIDR block: 4 or 16 address bytes and a prefix length. */
337
+ export interface Cidr {
338
+ readonly bytes: readonly number[];
339
+ readonly prefix: number;
340
+ }
341
+ /** Address bytes of an IPv4 or IPv6 literal (`::ffff:a.b.c.d` becomes IPv4), else undefined. */
342
+ export declare function ipBytes(text: string): number[] | undefined;
343
+ /** `a.b.c.d/n`, `x::y/n` or a bare address (a /32 or /128), else undefined. */
344
+ export declare function parseCidr(text: string): Cidr | undefined;
345
+ /** Whether `--allow-ip`/`--deny-ip` let a client in: loopback always; else not denied, and allowed when an allow list is given. */
346
+ export declare function ipAllowed(rules: SiteServerOptions['ipRules'], remote: string): boolean;
347
+ /** A short device name from a `User-Agent` (`iPhone`, `iPad`, `Android`, `Windows`, `Mac`, `Linux`), or `other`. */
348
+ export declare function deviceOf(userAgent: string | undefined): string;
349
+ /**
350
+ * The DNS-rebinding guard of {@link SiteServerOptions.allowedHosts}: whether a `Host` header value
351
+ * may be answered. Always allowed: no list, `*` in the list, no `Host`, an IP address (a rebinding
352
+ * attack needs a name), `localhost` and `*.localhost`. Otherwise the name (ASCII lowercase, without
353
+ * port and trailing dot) must equal an entry, or end with an entry that starts with `.` (or equal
354
+ * it without the dot).
355
+ */
356
+ export declare function hostAllowed(allowed: readonly string[] | undefined, host: string | undefined): boolean;
357
+ /** An `--allowed-host` value, lowercased: `*`, or a host name (letters, digits, `-`, `.`; a leading `.` for subdomains). */
358
+ export declare function parseAllowedHost(value: string): string | undefined;
359
+ export declare function originForm(target: string): string;
360
+ /** An IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`, RFC 9110 section 5.6.7) for Unix seconds. */
361
+ export declare function httpDate(secs: number): string;
362
+ /** Unix seconds of an IMF-fixdate, or undefined for anything else (the obsolete formats too). */
363
+ export declare function parseHttpDate(value: string): number | undefined;
364
+ /**
365
+ * The link-values of a `Link` header that become `103 Early Hints`: split at commas outside `<…>`
366
+ * and quotes, kept when well formed and `rel=preload` or `rel=preconnect` (ASCII case-insensitive).
367
+ */
368
+ export declare function earlyHints(link: string): string[];
369
+ /**
370
+ * The byte range a `Range` header asks of a body of `size` bytes: `[start, end]` (inclusive),
371
+ * `'unsatisfiable'` (416), or undefined when the header is absent, malformed, not in bytes, or
372
+ * asks for several ranges (those are ignored: the whole body is sent, as RFC 9110 allows).
373
+ */
374
+ export declare function byteRange(header: string | undefined, size: number): [number, number] | 'unsatisfiable' | undefined;
375
+ /**
376
+ * The app shell a `--spa` navigation to a missing path gets: `fallback` when given (`--spa-fallback`),
377
+ * else the `200.html` (Surge) or `index.html` of the request's directory or the closest parent that
378
+ * has one, so `/admin/users/5` gets `/admin/index.html` before `/index.html`. Undefined when none exists.
379
+ */
380
+ export declare function spaFallback(segs: readonly string[], trailingSlash: boolean, isFile: (p: string) => boolean, fallback?: string): string | undefined;
381
+ /** `--html-handling` (Cloudflare's names): `auto`, `force-slash`, `drop-slash` or `none`. */
382
+ export type HtmlHandling = 'auto' | 'force-slash' | 'drop-slash' | 'none';
383
+ export declare const HTML_HANDLINGS: readonly HtmlHandling[];
384
+ export declare const HOST_PROFILES: readonly ['netlify', 'cloudflare', 'vercel', 'github-pages', 'firebase'];
385
+ export type HostProfileName = (typeof HOST_PROFILES)[number];
386
+ /** How a server routes like a static host (`--host-profile`, `--html-handling`). */
387
+ export interface RoutingProfile {
388
+ /** Canonical page URLs; undefined keeps sitefile's own rules (clean URLs plus both spellings). */
389
+ readonly htmlHandling?: HtmlHandling;
390
+ /** The status of a canonicalizing redirect. */
391
+ readonly redirectStatus: number;
392
+ /** Whether `/_redirects` and `/_headers` are read (and hidden). */
393
+ readonly siteFiles: boolean;
394
+ /** Which 404.html answers a miss: the nearest, only the root one, or (no 404.html) `/index.html` with 200. */
395
+ readonly notFound: 'nearest' | 'root' | 'index';
396
+ /** Sitefile's own rules only: `/about/` with only `about.html` redirects to `/about`, or is 404. */
397
+ readonly slashHtml: 'redirect' | 'not-found';
398
+ }
399
+ /**
400
+ * The routing of a host profile, with `--html-handling` replacing its HTML handling (the profile
401
+ * undefined: sitefile's rules, a 307 for the canonical redirects as on Cloudflare).
402
+ *
403
+ * | profile | HTML handling | redirect | `_redirects`/`_headers` | 404 |
404
+ * | netlify | auto | 301 | yes | nearest 404.html |
405
+ * | cloudflare | auto | 307 | yes | nearest 404.html, else /index.html (200) |
406
+ * | vercel | none | 308 | no | /404.html |
407
+ * | github-pages | sitefile's, `/about/` 404 | 301 | no | /404.html |
408
+ * | firebase | none | 301 | no | /404.html |
409
+ */
410
+ export declare function hostProfile(name: HostProfileName | undefined, htmlHandling?: HtmlHandling): RoutingProfile;
411
+ /** The server's routing profile for the flags (undefined: sitefile's own rules). */
412
+ export declare function routingFor(o: {
413
+ hostProfile?: HostProfileName | undefined;
414
+ htmlHandling?: HtmlHandling | undefined;
415
+ }): RoutingProfile | undefined;
416
+ /** A near miss for a 404: a file (`path`) or a `_redirects` rule (`line`), and why. */
417
+ export interface NearMiss {
418
+ readonly path?: string;
419
+ readonly line?: number;
420
+ readonly why: string;
421
+ }
422
+ /**
423
+ * What a missing path almost matched (at most 20): files whose path differs only in ASCII letter case
424
+ * from the path, `<path>.html` or `<path>/index.html` (which work on a case-insensitive disk but not on a
425
+ * host), sorted by path; then `_redirects` rules whose source matches but whose query parameters or
426
+ * conditions do not, in file order.
427
+ */
428
+ export declare function nearMisses(tree: Tree, isFile: (p: string) => boolean, vpath: string, redirects: readonly ServeRedirect[], req: RedirectRequest): NearMiss[];
429
+ /** The development 404 page listing near misses. */
430
+ export declare function nearMissPage(vpath: string, misses: readonly NearMiss[], mount?: string): string;
431
+ /** Types `--rewrite-base` rewrites: HTML, CSS and any XML (feeds, sitemaps, SVG). */
432
+ export declare function isRebasedType(type: string): boolean;
433
+ /**
434
+ * A production URL for `--rewrite-base`: `scheme://host[/path]` without a trailing slash, query or
435
+ * fragment (`https://example.com/blog/` → `https://example.com/blog`), or undefined when it is not an
436
+ * http(s) URL with a host.
437
+ */
438
+ export declare function normalizeProductionUrl(raw: string): string | undefined;
439
+ /**
440
+ * `body` with every `from` (a production URL) replaced by `to` (the local origin and base), where
441
+ * the next byte cannot continue a host or path segment (a letter, digit, `.`, `-`, `_`, `~`, `:` or `%`),
442
+ * so `https://example.com` does not match `https://example.com.evil` and `/blog` not `/blogroll`.
443
+ */
444
+ export declare function rewriteBaseUrls(body: Uint8Array, from: string, to: string): Uint8Array;
445
+ /**
446
+ * A `--base` value as `/a/b/` (segments percent-encoded like encodeURIComponent, NFC), `/` for none, or undefined when it is not a
447
+ * safe absolute path. The path of a URL (`https://user.github.io/repo/`) is taken as well.
448
+ */
449
+ export declare function normalizeBase(raw: string): string | undefined;
32
450
  /**
33
451
  * An HTTP server for an immutable Tree. GET and HEAD only; nothing outside the tree is
34
452
  * ever reachable because lookups are exact map keys built from validated segments.
35
- * Honours `/404.html`, `/_redirects` and `/_headers` (which it never serves), and answers
36
- * `/about` with `/about.html` when there is no such file or directory.
453
+ * Honours `/404.html`, `/_redirects` and `/_headers` (which it never serves), answers
454
+ * `/about` with `/about.html` when there is no such file or directory, and redirects `/about/`
455
+ * to `/about` when only `/about.html` answers it.
37
456
  */
38
457
  export declare function createSiteServer(site: Tree | (() => Tree), options?: SiteServerOptions): http.Server;
39
458
  /** Listen on host:port (port 0 = any free port); EADDRINUSE and friends become E_SERVER. */
@@ -42,4 +461,12 @@ export declare function listen(server: http.Server, host: string, port: number):
42
461
  port: number;
43
462
  }>;
44
463
  export declare function closeServer(server: http.Server): Promise<void>;
45
- export declare function formatUrl(host: string, port: number): string;
464
+ /**
465
+ * The addresses other machines can reach a server bound to all interfaces at: the up, non-loopback
466
+ * interface addresses, IPv4 for `0.0.0.0`, IPv4 then IPv6 for `::` (IPv6 link-local `fe80::/10`
467
+ * left out: it needs a zone), each family sorted as text, without duplicates. Empty for any other bind.
468
+ */
469
+ export declare function networkAddresses(bindHost: string): string[];
470
+ /** {@link networkAddresses} as URLs. */
471
+ export declare function networkUrls(bindHost: string, port: number, scheme?: 'http' | 'https'): string[];
472
+ export declare function formatUrl(host: string, port: number, scheme?: 'http' | 'https'): string;