@crombolo/server 0.50.0 → 0.51.1

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.
@@ -0,0 +1,309 @@
1
+ /**
2
+ * The site's `public/` folder (story 284): its files at the root of the site,
3
+ * at the same paths. Listed as the server starts and when the folder changes,
4
+ * so a page request asks a map and never the disk, and only a path in the map
5
+ * is ever served. docs/rendering.md, "Public files".
6
+ */
7
+ import { existsSync, type FSWatcher, readdirSync, realpathSync, statSync, watch } from 'node:fs'
8
+ import { basename, dirname, join, relative, sep } from 'node:path'
9
+ import { serveStaticFile } from '@crombolo/backoffice-host'
10
+ import { hashedAddress, splitHashedAddress } from '@crombolo/render'
11
+ import { BUNDLE_SECTIONS, hashFile, type PublicSource } from '@crombolo/transfer'
12
+ import { isSitePath } from './middleware.ts'
13
+
14
+ /** Where a CLI finds out what a server is: never a site's to answer. */
15
+ export const REMOTE_DISCOVERY_PATH = '/.well-known/crombolo-remote'
16
+
17
+ /** Above this, `bundle build` says what is making the bundle heavy. */
18
+ export const PUBLIC_WARNING_BYTES = 100 * 1024 ** 2
19
+
20
+ const IMMUTABLE = 'public, max-age=31536000, immutable'
21
+ const WELL_KNOWN = '.well-known'
22
+ /** What git needs to keep an empty folder: it travels with the folder, and is never served. */
23
+ const FOLDER_KEEPER = '.gitkeep'
24
+ const RESCAN_DELAY_MS = 25
25
+ /**
26
+ * After a node is told of a change, it lists the folder again at these delays:
27
+ * a shared folder can show another machine's write up to a minute late.
28
+ */
29
+ const RELIST_AFTER_MS = [5_000, 15_000, 30_000, 60_000, 90_000]
30
+
31
+ /** Whether an address is the CMS's own, which no public file can take. */
32
+ export function isReservedPublicPath(path: string, backOfficePath: string): boolean {
33
+ const lower = path.toLowerCase()
34
+ if (lower === '/robots.txt' || lower === '/sitemap.xml') return false
35
+ return (
36
+ !isSitePath(path, backOfficePath) ||
37
+ lower === REMOTE_DISCOVERY_PATH ||
38
+ ['/css', '/scripts'].some((prefix) => lower === prefix || lower.startsWith(`${prefix}/`))
39
+ )
40
+ }
41
+
42
+ /** A dotfile, and anything in a dot folder, stays private except under `.well-known/`. Pure. */
43
+ const isServable = (relativePath: string): boolean =>
44
+ relativePath
45
+ .split('/')
46
+ .every((part, index) => !part.startsWith('.') || (index === 0 && part === WELL_KNOWN))
47
+
48
+ /** A symlink counts only when it ends inside the folder and at a file. */
49
+ function isInsideFolder(root: string, file: string): boolean {
50
+ try {
51
+ const real = realpathSync(file)
52
+ return real.startsWith(`${realpathSync(root)}${sep}`) && statSync(real).isFile()
53
+ } catch {
54
+ return false
55
+ }
56
+ }
57
+
58
+ /** Every regular file under `root`, relative and `/`-separated, dotfiles included. */
59
+ function filesIn(root: string, dir = root, out: string[] = []): string[] {
60
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
61
+ const path = join(dir, entry.name)
62
+ if (entry.isDirectory()) filesIn(root, path, out)
63
+ else if (entry.isFile() || (entry.isSymbolicLink() && isInsideFolder(root, path)))
64
+ out.push(relative(root, path).split(sep).join('/'))
65
+ }
66
+ return out
67
+ }
68
+
69
+ /** What a bundle carries from the folder: the files that are served, and what keeps it in git. */
70
+ export function publicSources(root: string): PublicSource[] {
71
+ if (!existsSync(root)) return []
72
+ return filesIn(root)
73
+ .filter((path) => isServable(path) || basename(path) === FOLDER_KEEPER)
74
+ .sort()
75
+ .map((path) => {
76
+ const source = join(root, path)
77
+ return {
78
+ path: `${BUNDLE_SECTIONS.public}/${path}`,
79
+ size: statSync(source).size,
80
+ sha256: hashFile(source),
81
+ source,
82
+ }
83
+ })
84
+ }
85
+
86
+ export interface PublicClash {
87
+ /** The file, inside the folder. */
88
+ file: string
89
+ /** `reserved`: it can never answer. `route`: it takes a route's address. `generated`: it replaces what the CMS writes there. */
90
+ kind: 'reserved' | 'route' | 'generated'
91
+ address: string
92
+ }
93
+
94
+ /** Each public file at an address something else answers, from files alone. */
95
+ export function publicClashes(options: {
96
+ publicDir: string
97
+ backOfficePath: string
98
+ routes?: readonly { path: string }[]
99
+ }): PublicClash[] {
100
+ const routes = (options.routes ?? []).map((route) => new URLPattern({ pathname: route.path }))
101
+ return filesFrom(options.publicDir).flatMap((file): PublicClash[] => {
102
+ const address = `/${file}`
103
+ if (isReservedPublicPath(address, options.backOfficePath))
104
+ return [{ file, kind: 'reserved', address }]
105
+ if (address === '/robots.txt' || address === '/sitemap.xml')
106
+ return [{ file, kind: 'generated', address }]
107
+ return routes.some((route) => route.test({ pathname: address }))
108
+ ? [{ file, kind: 'route', address }]
109
+ : []
110
+ })
111
+ }
112
+
113
+ interface PublicEntry {
114
+ file: string
115
+ /** Of the file's bytes, worked out when first asked for and kept until it changes. */
116
+ hash?: string
117
+ size: number
118
+ modified: number
119
+ }
120
+
121
+ /** The URL path of each file, decoded; a malformed escape matches nothing. */
122
+ function decoded(pathname: string): string | undefined {
123
+ try {
124
+ return decodeURIComponent(pathname)
125
+ } catch {
126
+ return undefined
127
+ }
128
+ }
129
+
130
+ export class PublicFiles {
131
+ readonly #root: string
132
+ readonly #backOfficePath: string
133
+ #index = new Map<string, PublicEntry>()
134
+ #folder: FSWatcher | undefined
135
+ #parent: FSWatcher | undefined
136
+ #rescan: ReturnType<typeof setTimeout> | undefined
137
+ #relist: ReturnType<typeof setTimeout>[] = []
138
+ readonly #watch: boolean
139
+ readonly #relistAfter: readonly number[]
140
+
141
+ constructor(
142
+ root: string,
143
+ backOfficePath: string,
144
+ options: { watch?: boolean; relistAfterMs?: readonly number[] } = {},
145
+ ) {
146
+ this.#root = root
147
+ this.#backOfficePath = backOfficePath
148
+ this.#watch = options.watch !== false
149
+ this.#relistAfter = options.relistAfterMs ?? RELIST_AFTER_MS
150
+ }
151
+
152
+ /** Lists the folder and watches it, and watches for it being made or replaced. */
153
+ start(): void {
154
+ this.#list()
155
+ if (!this.#watch) return
156
+ this.#watchFolder()
157
+ try {
158
+ const name = basename(this.#root)
159
+ this.#parent = watch(dirname(this.#root), (_event, changed) => {
160
+ if (changed !== null && changed.toString() !== name) return
161
+ this.#watchFolder()
162
+ this.#scheduleRescan()
163
+ })
164
+ this.#parent.on('error', () => {})
165
+ } catch {
166
+ // A folder that cannot be watched keeps the files it started with.
167
+ }
168
+ }
169
+
170
+ /** The folder changed where no watcher can see: listed now, and again as it settles. */
171
+ changed(): void {
172
+ for (const timer of this.#relist.splice(0)) clearTimeout(timer)
173
+ this.#list()
174
+ this.#relist = this.#relistAfter.map((delay) => {
175
+ const timer = setTimeout(() => this.#list(), delay)
176
+ timer.unref?.()
177
+ return timer
178
+ })
179
+ }
180
+
181
+ close(): void {
182
+ clearTimeout(this.#rescan)
183
+ for (const timer of this.#relist.splice(0)) clearTimeout(timer)
184
+ this.#folder?.close()
185
+ this.#parent?.close()
186
+ }
187
+
188
+ /** Whether a request path is a public file. */
189
+ has(pathname: string): boolean {
190
+ const path = decoded(pathname)
191
+ return path !== undefined && this.#index.has(path)
192
+ }
193
+
194
+ /** The URL paths of the files, sorted. */
195
+ paths(): string[] {
196
+ return [...this.#index.keys()].sort()
197
+ }
198
+
199
+ /** The files at an address that `page` says has a page. */
200
+ async hiding(page: (path: string) => Promise<unknown>): Promise<string[]> {
201
+ const found = await Promise.all(
202
+ this.paths().map(async (path) => ((await page(path)) ? [path] : [])),
203
+ )
204
+ return found.flat()
205
+ }
206
+
207
+ /** The hashed address of a file the site has, or undefined. */
208
+ address(path: string): string | undefined {
209
+ const entry = this.#index.get(path)
210
+ if (!entry) return undefined
211
+ try {
212
+ entry.hash ??= addressHash(entry.file)
213
+ return hashedAddress(path, entry.hash)
214
+ } catch {
215
+ return undefined
216
+ }
217
+ }
218
+
219
+ /**
220
+ * A public file's answer, or undefined when the path is not one. The hashed
221
+ * address answers only while the hash is the file's, and nothing when not.
222
+ */
223
+ async serve(request: Request, pathname: string): Promise<Response | undefined> {
224
+ const path = decoded(pathname)
225
+ if (path === undefined) return undefined
226
+ const own = this.#index.get(path)
227
+ if (own) return this.#send(own, 'no-cache', request)
228
+ const hashed = splitHashedAddress(path)
229
+ const entry = hashed && this.#index.get(hashed.path)
230
+ if (!hashed || !entry) return undefined
231
+ if (this.#hashNow(entry) !== hashed.hash)
232
+ return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
233
+ return this.#send(entry, IMMUTABLE, request)
234
+ }
235
+
236
+ async #send(entry: PublicEntry, cacheControl: string, request: Request) {
237
+ const response = await serveStaticFile({ file: entry.file, cacheControl }, request)
238
+ response?.headers.set('x-content-type-options', 'nosniff')
239
+ return response
240
+ }
241
+
242
+ /** The hash of the bytes as they are now, so a change the watcher missed is never kept. */
243
+ #hashNow(entry: PublicEntry): string | undefined {
244
+ try {
245
+ const stat = statSync(entry.file)
246
+ if (stat.size !== entry.size || stat.mtimeMs !== entry.modified) entry.hash = undefined
247
+ entry.size = stat.size
248
+ entry.modified = stat.mtimeMs
249
+ entry.hash ??= addressHash(entry.file)
250
+ return entry.hash
251
+ } catch {
252
+ return undefined
253
+ }
254
+ }
255
+
256
+ #list(): void {
257
+ const next = new Map<string, PublicEntry>()
258
+ for (const path of filesFrom(this.#root)) {
259
+ const key = `/${path}`
260
+ if (isReservedPublicPath(key, this.#backOfficePath)) continue
261
+ const file = join(this.#root, path)
262
+ try {
263
+ const stat = statSync(file)
264
+ const known = this.#index.get(key)
265
+ const same = known?.size === stat.size && known.modified === stat.mtimeMs
266
+ next.set(key, {
267
+ file,
268
+ size: stat.size,
269
+ modified: stat.mtimeMs,
270
+ ...(same && known.hash ? { hash: known.hash } : {}),
271
+ })
272
+ } catch {
273
+ // Gone between the listing and the look: it is not there.
274
+ }
275
+ }
276
+ this.#index = next
277
+ }
278
+
279
+ #watchFolder(): void {
280
+ this.#folder?.close()
281
+ this.#folder = undefined
282
+ if (!existsSync(this.#root)) return
283
+ try {
284
+ this.#folder = watch(this.#root, { recursive: true }, () => this.#scheduleRescan())
285
+ this.#folder.on('error', () => {})
286
+ } catch {
287
+ // As in `start`.
288
+ }
289
+ }
290
+
291
+ /** Listed again as a whole: a folder moved in reports only its own name. */
292
+ #scheduleRescan(): void {
293
+ clearTimeout(this.#rescan)
294
+ this.#rescan = setTimeout(() => this.#list(), RESCAN_DELAY_MS)
295
+ this.#rescan.unref?.()
296
+ }
297
+ }
298
+
299
+ /** The servable files of a folder, which may not exist. */
300
+ function filesFrom(root: string): string[] {
301
+ try {
302
+ return existsSync(root) ? filesIn(root).filter(isServable) : []
303
+ } catch {
304
+ return []
305
+ }
306
+ }
307
+
308
+ /** `contentHash` of the file's bytes, without holding them in memory. */
309
+ const addressHash = (file: string): string => hashFile(file).slice(0, 8)
@@ -170,7 +170,7 @@ export async function replaceSummary(
170
170
  const filesRemoved: string[] = []
171
171
  for (const { section, dir } of folders) {
172
172
  if (!existsSync(dir)) continue
173
- for (const path of new Bun.Glob('**/*').scanSync({ cwd: dir, onlyFiles: true })) {
173
+ for (const path of new Bun.Glob('**/*').scanSync({ cwd: dir, onlyFiles: true, dot: true })) {
174
174
  const bundlePath = `${section}/${path.split(sep).join('/')}`
175
175
  if (!carriedPaths.has(bundlePath)) filesRemoved.push(join(dir, path))
176
176
  }