@otwdesign/cli 0.0.0-stage → 1.0.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.
@@ -0,0 +1,80 @@
1
+ import { Agent, createServer, request, type IncomingMessage, type Server } from 'node:http'
2
+
3
+ const MAINTENANCE = `<!doctype html>
4
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
5
+ <meta http-equiv="refresh" content="5"><title>Updating</title></head>
6
+ <body style="font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1rem;color:#1d2327">
7
+ <h1 style="font-weight:400">This site is being updated.</h1><p>It will be back in a moment.</p>
8
+ </body></html>`
9
+
10
+ /** Hop-by-hop headers belong to one connection and must not be forwarded (RFC 9110 §7.6.1). */
11
+ const HOP_BY_HOP = new Set([
12
+ 'connection',
13
+ 'keep-alive',
14
+ 'proxy-authenticate',
15
+ 'proxy-authorization',
16
+ 'te',
17
+ 'trailer',
18
+ 'transfer-encoding',
19
+ 'upgrade',
20
+ ])
21
+
22
+ function forwardedHeaders(incoming: IncomingMessage): Record<string, string | string[]> {
23
+ const headers: Record<string, string | string[]> = {}
24
+ for (const [name, value] of Object.entries(incoming.headers)) {
25
+ if (value !== undefined && !HOP_BY_HOP.has(name)) headers[name] = value
26
+ }
27
+ const client = incoming.socket.remoteAddress ?? ''
28
+ const prior = incoming.headers['x-forwarded-for']
29
+ headers['x-forwarded-for'] = prior ? `${String(prior)}, ${client}` : client
30
+ headers['x-forwarded-proto'] ??= 'http'
31
+ // An outer proxy's (nginx terminating TLS, say) says more than ours can.
32
+ headers['x-forwarded-host'] ??= incoming.headers.host ?? ''
33
+ return headers
34
+ }
35
+
36
+ /**
37
+ * The public port. Requests go to the live release's port; between releases (an update on the
38
+ * embedded database, which one process holds at a time) visitors get a short 503 to retry.
39
+ */
40
+ export function createProxy(target: () => number | null): Server {
41
+ const agent = new Agent({ keepAlive: true })
42
+ return createServer((incoming, outgoing) => {
43
+ const port = target()
44
+ if (port === null) {
45
+ outgoing
46
+ .writeHead(503, {
47
+ 'content-type': 'text/html; charset=utf-8',
48
+ 'retry-after': '10',
49
+ 'cache-control': 'no-store',
50
+ })
51
+ .end(MAINTENANCE)
52
+ return
53
+ }
54
+ const upstream = request(
55
+ {
56
+ host: '127.0.0.1',
57
+ port,
58
+ method: incoming.method,
59
+ path: incoming.url,
60
+ headers: forwardedHeaders(incoming),
61
+ agent,
62
+ },
63
+ (response) => {
64
+ const headers = Object.fromEntries(
65
+ Object.entries(response.headers).filter(([name]) => !HOP_BY_HOP.has(name)),
66
+ )
67
+ outgoing.writeHead(response.statusCode ?? 502, headers)
68
+ response.pipe(outgoing)
69
+ },
70
+ )
71
+ upstream.on('error', () => {
72
+ if (!outgoing.headersSent) {
73
+ outgoing.writeHead(502, { 'content-type': 'text/plain' }).end('Bad gateway')
74
+ } else {
75
+ outgoing.destroy()
76
+ }
77
+ })
78
+ incoming.pipe(upstream)
79
+ })
80
+ }
@@ -0,0 +1,195 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { copyFile, cp, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
4
+ import type { PackageChange } from '@otwdesign/core'
5
+ import { MARKER, removeRoute } from '../generate.ts'
6
+ import { CORE_PACKAGES, readSitePackages, writeChanges, type PackageManager } from '../update.ts'
7
+ import type { BuiltRelease, Log } from './supervisor.ts'
8
+
9
+ /** Built, installed or local state: never copied into a release, never copied back. */
10
+ const NOT_SOURCE = new Set([
11
+ 'node_modules',
12
+ '.next',
13
+ '.cms',
14
+ '.data',
15
+ '.git',
16
+ 'coverage',
17
+ 'test-results',
18
+ 'playwright-report',
19
+ ])
20
+
21
+ const LOCKFILES: Record<PackageManager, string[]> = {
22
+ pnpm: ['pnpm-lock.yaml'],
23
+ npm: ['package-lock.json'],
24
+ yarn: ['yarn.lock'],
25
+ bun: ['bun.lock', 'bun.lockb'],
26
+ }
27
+
28
+ function isSource(site: string, path: string): boolean {
29
+ const top = relative(site, path).split(sep)[0]
30
+ return top === '' || !NOT_SOURCE.has(top!)
31
+ }
32
+
33
+ interface PackageJson {
34
+ dependencies?: Record<string, string>
35
+ devDependencies?: Record<string, string>
36
+ }
37
+
38
+ /**
39
+ * A release lives deeper than the site, so `link:../x` and `file:../x` would point elsewhere:
40
+ * make them absolute. Returns whether any were, since such a lockfile can't go back to the site.
41
+ */
42
+ async function anchorLocalSpecs(site: string, dir: string): Promise<boolean> {
43
+ const file = join(dir, 'package.json')
44
+ const manifest = JSON.parse(await readFile(file, 'utf8')) as PackageJson
45
+ let changed = false
46
+ for (const deps of [manifest.dependencies, manifest.devDependencies]) {
47
+ for (const [name, spec] of Object.entries(deps ?? {})) {
48
+ const local = /^(link|file):(.+)$/.exec(spec)
49
+ if (local && !isAbsolute(local[2]!)) {
50
+ deps![name] = `${local[1]}:${resolve(site, local[2]!)}`
51
+ changed = true
52
+ }
53
+ }
54
+ }
55
+ if (changed) await writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`)
56
+ return changed
57
+ }
58
+
59
+ /** Runs a command, streaming its output into the job's log, so a slow install shows it is alive. */
60
+ export function step(
61
+ command: string,
62
+ args: string[],
63
+ cwd: string,
64
+ log: Log,
65
+ env?: NodeJS.ProcessEnv,
66
+ ): Promise<void> {
67
+ log(`$ ${command} ${args.join(' ')}`)
68
+ return new Promise((resolvePromise, reject) => {
69
+ const child = spawn(command, args, {
70
+ cwd,
71
+ env: { ...process.env, ...env },
72
+ stdio: ['ignore', 'pipe', 'pipe'],
73
+ })
74
+ for (const stream of [child.stdout, child.stderr]) {
75
+ let pending = ''
76
+ stream.setEncoding('utf8')
77
+ stream.on('data', (chunk: string) => {
78
+ const lines = (pending + chunk).split('\n')
79
+ pending = lines.pop() ?? ''
80
+ for (const line of lines) log(line)
81
+ })
82
+ stream.on('end', () => pending && log(pending))
83
+ }
84
+ child.on('error', reject)
85
+ child.on('close', (code) =>
86
+ code === 0
87
+ ? resolvePromise()
88
+ : reject(new Error(`${command} ${args[0]} exited with ${code}`)),
89
+ )
90
+ })
91
+ }
92
+
93
+ function installArgs(manager: PackageManager): string[] {
94
+ // The release is a standalone copy, even inside a workspace's tree; and package.json just changed.
95
+ return manager === 'pnpm'
96
+ ? ['install', '--ignore-workspace', '--no-frozen-lockfile']
97
+ : ['install']
98
+ }
99
+
100
+ export interface ReleaseBuilder {
101
+ site: string
102
+ manager: PackageManager
103
+ /** `.cms/releases` under the site. */
104
+ releasesDir: string
105
+ }
106
+
107
+ /** Copies the site, applies the update, installs and builds: a release ready to start. */
108
+ export async function buildRelease(
109
+ { site, manager, releasesDir }: ReleaseBuilder,
110
+ id: string,
111
+ changes: readonly PackageChange[],
112
+ log: Log,
113
+ ): Promise<BuiltRelease> {
114
+ const dir = join(releasesDir, id)
115
+ try {
116
+ // Entry by entry: Node won't copy a directory into itself, even past a filter, and
117
+ // releases live inside the site.
118
+ await mkdir(dir, { recursive: true })
119
+ for (const entry of await readdir(site)) {
120
+ if (NOT_SOURCE.has(entry)) continue
121
+ await cp(join(site, entry), join(dir, entry), { recursive: true })
122
+ }
123
+ await anchorLocalSpecs(site, dir)
124
+ if (changes.length > 0) await writeChanges(dir, changes)
125
+ await step(manager, installArgs(manager), dir, log)
126
+ await step(manager, ['run', 'build'], dir, log)
127
+ } catch (error) {
128
+ await rm(dir, { recursive: true, force: true })
129
+ throw error
130
+ }
131
+ const { installed, plugins } = await readSitePackages(dir)
132
+ const versions = Object.fromEntries(
133
+ Object.entries(installed).filter(
134
+ ([name]) => plugins.includes(name) || (CORE_PACKAGES as readonly string[]).includes(name),
135
+ ),
136
+ )
137
+ return { id, dir, createdAt: new Date().toISOString(), versions }
138
+ }
139
+
140
+ /** Files `cms generate` owns in a tree, relative to it. */
141
+ async function managedFiles(root: string, dir = root): Promise<string[]> {
142
+ const found: string[] = []
143
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
144
+ const path = join(dir, entry.name)
145
+ if (!isSource(root, path)) continue
146
+ if (entry.isDirectory()) found.push(...(await managedFiles(root, path)))
147
+ else if (/\.tsx?$/.test(entry.name)) {
148
+ const head = (await readFile(path, 'utf8')).slice(0, MARKER.length)
149
+ if (head === MARKER) found.push(relative(root, path))
150
+ }
151
+ }
152
+ return found
153
+ }
154
+
155
+ /**
156
+ * After a switch, the site's own copy should say what runs: the new versions in package.json,
157
+ * the lockfile, and the route files the new CLI wrote, without the ones it retired. Files the
158
+ * site owns (no marker) stay. Returns what it couldn't copy, to tell the administrator.
159
+ */
160
+ export async function writeBack(
161
+ { site, manager }: ReleaseBuilder,
162
+ release: BuiltRelease,
163
+ changes: readonly PackageChange[],
164
+ ): Promise<string[]> {
165
+ const skipped: string[] = []
166
+ if (changes.length > 0) await writeChanges(site, changes)
167
+ const anchored = await readFile(join(release.dir, 'package.json'), 'utf8').then((raw) =>
168
+ /"(link|file):\//.test(raw),
169
+ )
170
+ for (const lockfile of LOCKFILES[manager]) {
171
+ const from = join(release.dir, lockfile)
172
+ // A lockfile with the release's absolute local paths would be wrong in the site.
173
+ if (anchored) {
174
+ skipped.push(lockfile)
175
+ continue
176
+ }
177
+ await copyFile(from, join(site, lockfile)).catch(() => {})
178
+ }
179
+ const released = new Set(await managedFiles(release.dir))
180
+ for (const file of released) {
181
+ const target = join(site, file)
182
+ const current = await readFile(target, 'utf8').catch(() => null)
183
+ if (current !== null && !current.startsWith(MARKER)) continue
184
+ await mkdir(dirname(target), { recursive: true })
185
+ await copyFile(join(release.dir, file), target)
186
+ }
187
+ for (const file of await managedFiles(site)) {
188
+ if (!released.has(file)) await removeRoute(join(site, file))
189
+ }
190
+ return skipped
191
+ }
192
+
193
+ export async function removeRelease(release: BuiltRelease): Promise<void> {
194
+ await rm(release.dir, { recursive: true, force: true })
195
+ }
@@ -0,0 +1,43 @@
1
+ import { cp, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
2
+ import { dirname, join } from 'node:path'
3
+ import type { ServeState } from './supervisor.ts'
4
+
5
+ const EMPTY: ServeState = { current: null, releases: [], autoUpdate: 'off', lastCheck: null }
6
+
7
+ export async function loadState(file: string): Promise<ServeState> {
8
+ const raw = await readFile(file, 'utf8').catch((error: NodeJS.ErrnoException) => {
9
+ if (error.code === 'ENOENT') return null
10
+ throw error
11
+ })
12
+ return raw ? { ...EMPTY, ...(JSON.parse(raw) as Partial<ServeState>) } : structuredClone(EMPTY)
13
+ }
14
+
15
+ /** Written beside and renamed over, so a crash mid-write never leaves half a file. */
16
+ export async function saveState(file: string, state: ServeState): Promise<void> {
17
+ await mkdir(dirname(file), { recursive: true })
18
+ const temporary = `${file}.${process.pid}.tmp`
19
+ await writeFile(temporary, `${JSON.stringify(state, null, 2)}\n`)
20
+ await rename(temporary, file)
21
+ }
22
+
23
+ const BACKUPS_KEPT = 3
24
+
25
+ /** The embedded database's directory, copied while no release holds it. */
26
+ export async function backupDatabase(
27
+ dataDir: string,
28
+ backupsDir: string,
29
+ now: Date,
30
+ ): Promise<string> {
31
+ const target = join(backupsDir, `pglite-${now.toISOString().replace(/[:.]/g, '-')}`)
32
+ await cp(dataDir, target, { recursive: true, errorOnExist: true, force: false })
33
+ const all = (await readdir(backupsDir)).filter((name) => name.startsWith('pglite-')).sort()
34
+ for (const old of all.slice(0, Math.max(0, all.length - BACKUPS_KEPT))) {
35
+ await rm(join(backupsDir, old), { recursive: true, force: true })
36
+ }
37
+ return target
38
+ }
39
+
40
+ export async function restoreDatabase(backup: string, dataDir: string): Promise<void> {
41
+ await rm(dataDir, { recursive: true, force: true })
42
+ await cp(backup, dataDir, { recursive: true })
43
+ }