@otwdesign/db-next 0.0.0-stage → 1.4.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.
package/src/init.ts ADDED
@@ -0,0 +1,556 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import {
3
+ accessSync,
4
+ constants,
5
+ existsSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ realpathSync,
11
+ statSync,
12
+ writeFileSync,
13
+ } from 'node:fs'
14
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
15
+ import { MIN_PASSWORD } from './session.ts'
16
+
17
+ /*
18
+ * `otw-db-next init`: OTW DB added to a Next.js app that's already there. What it finds
19
+ * (`detect`), what it would do about it (`plan`) and doing it (`apply`) are apart, so the first
20
+ * two can be looked at without anything being written.
21
+ */
22
+
23
+ export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun'
24
+
25
+ /** What `init` found in the app's directory. */
26
+ export interface Detected {
27
+ /** The app's directory, absolute. */
28
+ dir: string
29
+ /** `next` is among its dependencies. */
30
+ next: boolean
31
+ /** `src` when the app keeps `app/` or `pages/` there, else empty. */
32
+ src: '' | 'src'
33
+ typescript: boolean
34
+ manager: PackageManager
35
+ /** `basePath` from next.config, such as `/docs`; empty without one. */
36
+ nextBasePath: string
37
+ /** next.config sets a `basePath` that isn't a plain path, so it wasn't taken. */
38
+ basePathUnread: boolean
39
+ /** Its middleware (or proxy, as Next 16 calls it), relative to the app; null without one. */
40
+ middleware: string | null
41
+ /**
42
+ * Files that are there and weren't read: not a file, or larger than any such file is. What
43
+ * they'd have said isn't known, which isn't the same as their saying nothing.
44
+ */
45
+ unread: string[]
46
+ /** DB_ADMIN_PASSWORD is set in `.env`, a file apps usually keep in git. */
47
+ passwordInDotEnv: boolean
48
+ /** The names already set in `.env.local` and `.env`. */
49
+ envNames: ReadonlySet<string>
50
+ /** The tool's own names those files mention at all, set or in a comment an earlier run left. */
51
+ envMentions: ReadonlySet<string>
52
+ /** The app uses Supabase: its packages, or its address in the env. */
53
+ supabase: boolean
54
+ /**
55
+ * The Node major package.json holds the app to (`20`, `20.x`, `^18.17`), when it holds it to
56
+ * one: the number, never the text, which is someone's and gets printed.
57
+ */
58
+ nodeMajor: number | null
59
+ /** `@otwdesign/db-next` is a dependency already. */
60
+ installed: boolean
61
+ }
62
+
63
+ export interface InitFlags {
64
+ /** Where the tool goes, such as `/db` (the default) or `/admin/db`. */
65
+ path?: string
66
+ /** Install nothing: the files only. */
67
+ install?: boolean
68
+ }
69
+
70
+ /** What `init` would do: files to write, a command, and what to say and leave to the person. */
71
+ export interface InitPlan {
72
+ /** Why nothing can be done; when set, the rest is empty. */
73
+ refused: string | null
74
+ files: { path: string; content: string }[]
75
+ /**
76
+ * The variables still to set, as lines for the person to add to their environment: `init`
77
+ * writes none of them. The password is theirs to choose and to place, and a file in a folder
78
+ * someone else may have prepared is no place for a tool to put a secret.
79
+ */
80
+ env: string[]
81
+ /** The command that installs the package; null with `--no-install`, or when it's there. */
82
+ install: { command: string; args: string[] } | null
83
+ /** What the person should know, or do next. */
84
+ notes: string[]
85
+ /** Where the tool will be, as the browser has it. */
86
+ url: string
87
+ }
88
+
89
+ const PATH = /^(?:\/[A-Za-z0-9._~-]+)+$/
90
+ /** The app's own PostgreSQL, by the names `appConnections()` reads. */
91
+ const OWN = ['DATABASE_URL_UNPOOLED', 'POSTGRES_URL_NON_POOLING', 'DATABASE_URL', 'POSTGRES_URL']
92
+
93
+ /** Whether `path` is `root` or inside it. */
94
+ function within(root: string, path: string): boolean {
95
+ const from = relative(root, path)
96
+ return from === '' || (!from.startsWith('..') && !isAbsolute(from))
97
+ }
98
+
99
+ /** More than any file read here holds: a package.json, a next.config, an env file. */
100
+ const MOST = 1024 * 1024
101
+
102
+ /**
103
+ * A file's text, without a byte-order mark; null when it isn't there, isn't a file (a pipe of
104
+ * that name would be waited on for ever) or is larger than such files are (read whole, it is a
105
+ * wait as long as its author likes).
106
+ */
107
+ function read(path: string): string | null {
108
+ try {
109
+ const file = statSync(path)
110
+ if (!file.isFile() || file.size > MOST) return null
111
+ return readFileSync(path, 'utf8').replace(/^\uFEFF/, '')
112
+ } catch {
113
+ return null
114
+ }
115
+ }
116
+
117
+ /** The package manager, by the nearest lockfile on the way up (a monorepo keeps it at its root). */
118
+ function managerOf(dir: string, packageManager: unknown): PackageManager {
119
+ const locks: [string, PackageManager][] = [
120
+ ['pnpm-lock.yaml', 'pnpm'],
121
+ ['yarn.lock', 'yarn'],
122
+ ['bun.lock', 'bun'],
123
+ ['bun.lockb', 'bun'],
124
+ ['package-lock.json', 'npm'],
125
+ ]
126
+ for (let at = dir; ; at = dirname(at)) {
127
+ for (const [file, manager] of locks) if (existsSync(join(at, file))) return manager
128
+ if (dirname(at) === at) break
129
+ }
130
+ const named = typeof packageManager === 'string' ? packageManager.split('@')[0] : ''
131
+ return named === 'pnpm' || named === 'yarn' || named === 'bun' ? named : 'npm'
132
+ }
133
+
134
+ /** The names a dotenv file sets, comments and blank lines aside. */
135
+ function envNames(text: string | null): string[] {
136
+ return (text ?? '')
137
+ .split('\n')
138
+ .map((line) => /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line)?.[1])
139
+ .filter((name): name is string => !!name)
140
+ }
141
+
142
+ /** Whether `path` is a folder, or leads to one. */
143
+ function isDirectory(path: string): boolean {
144
+ try {
145
+ return statSync(path).isDirectory()
146
+ } catch {
147
+ return false
148
+ }
149
+ }
150
+
151
+ /** Whether files can be made in the folder `path`. */
152
+ function writable(path: string): boolean {
153
+ try {
154
+ accessSync(path, constants.W_OK | constants.X_OK)
155
+ return true
156
+ } catch {
157
+ return false
158
+ }
159
+ }
160
+
161
+ /** The names in the folder `path`; null when it can't be listed. */
162
+ function namesIn(path: string): string[] | null {
163
+ try {
164
+ return readdirSync(path)
165
+ } catch {
166
+ return null
167
+ }
168
+ }
169
+
170
+ /** Whether there is anything at `path`, a link that leads nowhere included. */
171
+ function entry(path: string): boolean {
172
+ try {
173
+ lstatSync(path)
174
+ return true
175
+ } catch {
176
+ return false
177
+ }
178
+ }
179
+
180
+ /** What a file of JSON holds, when it holds an object: nothing else has anything to read. */
181
+ function objectIn(text: string | null): Record<string, unknown> {
182
+ try {
183
+ const value: unknown = JSON.parse(text ?? '{}')
184
+ return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {}
185
+ } catch {
186
+ return {}
187
+ }
188
+ }
189
+
190
+ /** A path as `--path` and a route take it: short, segments of plain characters, none of them dots alone. */
191
+ function plainPath(path: string): boolean {
192
+ // Of a length paths have: it's written into a file and printed, as often as it's long.
193
+ if (path.length > 200) return false
194
+ return PATH.test(path) && !path.split('/').some((segment) => /^\.+$/.test(segment))
195
+ }
196
+
197
+ /**
198
+ * `basePath` as next.config sets it: the path, an empty string when it sets none, null when what
199
+ * the file says of it can't be taken for one plain path. It is taken only in the one shape that
200
+ * needs no reading of JavaScript: the word once in the file, as a key with a short quoted value,
201
+ * on a line with no comment before it and nothing joined on after it. Anything else (a variable, two mentions, a value built
202
+ * from parts) gets a note and no guess: a wrong address is worse than one to fill in. A block
203
+ * comment over several lines isn't seen for what it is; the note says where the address goes.
204
+ */
205
+ function basePathIn(config: string): string | null {
206
+ const first = config.indexOf('basePath')
207
+ if (first < 0) return ''
208
+ if (config.indexOf('basePath', first + 1) >= 0) return null
209
+ const before = config.slice(config.lastIndexOf('\n', first) + 1, first)
210
+ const set = /^basePath\s*:\s*(['"`])([^'"`\n\\$]{0,201})\1(?=[ \t]*(?:[,}\r\n]|$))/.exec(
211
+ config.slice(first, first + 300),
212
+ )
213
+ if (!set || /\/\/|\/\*|^\s*\*/.test(before)) return null
214
+ const value = set[2]!.replace(/\/$/, '')
215
+ return value === '' || plainPath(value) ? value : null
216
+ }
217
+
218
+ /**
219
+ * The Node major `engines.node` holds an app to, when it names one version line: `20`, `20.x`,
220
+ * `^18.17`. A range open upwards (`>=18`) names none.
221
+ */
222
+ function pinnedMajor(range: unknown): number | null {
223
+ // Text only: package.json is someone's file.
224
+ if (typeof range !== 'string') return null
225
+ const pinned = /^[\^~=v]?\s*(\d{1,4})(?:\.(?:x|\*|\d+))*$/.exec(range.trim())
226
+ return pinned ? Number(pinned[1]) : null
227
+ }
228
+
229
+ const CONFIGS = ['next.config.ts', 'next.config.mjs', 'next.config.js', 'next.config.cjs']
230
+ /** The env files Next.js reads, on a machine and in a build. */
231
+ const ENV_FILES = [
232
+ '.env.local',
233
+ '.env',
234
+ '.env.development.local',
235
+ '.env.development',
236
+ '.env.production.local',
237
+ '.env.production',
238
+ ]
239
+
240
+ /** Looks at the app in `dir`. */
241
+ export function detect(dir: string): Detected {
242
+ const root = resolve(dir)
243
+ const manifest = objectIn(read(join(root, 'package.json'))) as {
244
+ dependencies?: Record<string, string>
245
+ devDependencies?: Record<string, string>
246
+ engines?: { node?: string }
247
+ packageManager?: unknown
248
+ }
249
+ const dependencies = { ...manifest.dependencies, ...manifest.devDependencies }
250
+ const has = (path: string) => existsSync(join(root, path))
251
+ const src = has('src/app') || has('src/pages') ? 'src' : ''
252
+ const config = CONFIGS.map((file) => read(join(root, file))).find((text) => text !== null)
253
+ const middleware =
254
+ ['middleware.ts', 'middleware.js', 'proxy.ts', 'proxy.js']
255
+ .flatMap((file) => [file, join('src', file)])
256
+ .find(has) ?? null
257
+ const basePath = basePathIn(config ?? '')
258
+ const envFiles = ENV_FILES.map((file) => read(join(root, file)))
259
+ const unread = ['package.json', ...CONFIGS, ...ENV_FILES].filter(
260
+ (file) => entry(join(root, file)) && read(join(root, file)) === null,
261
+ )
262
+ const names = new Set(envFiles.flatMap(envNames))
263
+ const mentions = new Set(envFiles.flatMap((text) => text?.match(/DB_ADMIN_[A-Z0-9_]+/g) ?? []))
264
+ return {
265
+ dir: root,
266
+ next: 'next' in dependencies,
267
+ src,
268
+ typescript: has('tsconfig.json'),
269
+ manager: managerOf(root, manifest.packageManager),
270
+ nextBasePath: basePath ?? '',
271
+ basePathUnread: basePath === null,
272
+ unread,
273
+ middleware,
274
+ passwordInDotEnv: envNames(read(join(root, '.env'))).includes('DB_ADMIN_PASSWORD'),
275
+ envNames: names,
276
+ envMentions: mentions,
277
+ supabase:
278
+ '@supabase/supabase-js' in dependencies ||
279
+ '@supabase/ssr' in dependencies ||
280
+ names.has('NEXT_PUBLIC_SUPABASE_URL') ||
281
+ names.has('SUPABASE_URL'),
282
+ nodeMajor: pinnedMajor(manifest.engines?.node),
283
+ installed: '@otwdesign/db-next' in dependencies,
284
+ }
285
+ }
286
+
287
+ /**
288
+ * The route file: all of the tool's setup an app holds. The comments are for whoever opens it
289
+ * months later and wonders where the password and the databases come from.
290
+ */
291
+ export function routeFile(basePath: string): string {
292
+ const options = basePath === '/db' ? '' : `{ basePath: '${basePath}' }`
293
+ return `import { createDbRoute } from '@otwdesign/db-next'
294
+
295
+ // OTW DB at ${basePath}: its page, its files and its API, all in this one route.
296
+ // Who gets in: anyone with DB_ADMIN_PASSWORD, and the app's signed-in users listed in
297
+ // DB_ADMIN_USERS (their emails, comma-separated), who need no password.
298
+ // Which databases: DB_ADMIN_<NAME>_URL, or the app's own (DATABASE_URL), read-only.
299
+ export const runtime = 'nodejs'
300
+ export const dynamic = 'force-dynamic'
301
+
302
+ export const { GET, POST } = createDbRoute(${options})
303
+ `
304
+ }
305
+
306
+ /** What to do in the app `detect` found. Writes nothing. */
307
+ export function plan(detected: Detected, flags: InitFlags = {}): InitPlan {
308
+ const nothing = { files: [], env: [], install: null, notes: [], url: '' }
309
+ if (detected.unread.includes('package.json')) {
310
+ return {
311
+ ...nothing,
312
+ refused: 'package.json couldn’t be read: it isn’t a file, or is larger than such a file is.',
313
+ }
314
+ }
315
+ if (!detected.next) {
316
+ return {
317
+ ...nothing,
318
+ refused:
319
+ 'This isn’t a Next.js app: package.json has no "next" among its dependencies. Run it in the app’s own directory.',
320
+ }
321
+ }
322
+ const path = (flags.path ?? '/db').replace(/\/+$/, '')
323
+ // A segment of dots alone is this folder, or the one above it: out of the app, by two of them.
324
+ if (!plainPath(path)) {
325
+ return {
326
+ ...nothing,
327
+ refused: `--path is a path such as /db or /admin/db: segments of letters, digits, . _ ~ and -, not "${flags.path}".`,
328
+ }
329
+ }
330
+ const app = join(detected.src, 'app')
331
+ const route = join(app, ...path.split('/').filter(Boolean))
332
+ const pages = join(detected.src, 'pages', ...path.split('/').filter(Boolean))
333
+ // As the browser has it: next.config's basePath comes before every route of the app.
334
+ const basePath = `${detected.nextBasePath.replace(/\/+$/, '')}${path}`
335
+ const file = join(route, '[[...path]]', detected.typescript ? 'route.ts' : 'route.js')
336
+ // An earlier run's own route, as it wrote it: this one goes on from there (an install that
337
+ // failed, a password still to set) and writes over nothing.
338
+ const written =
339
+ read(join(detected.dir, file)) === routeFile(basePath) &&
340
+ namesIn(join(detected.dir, route))?.length === 1
341
+ const taken = written
342
+ ? undefined
343
+ : [
344
+ route,
345
+ pages,
346
+ ...['tsx', 'ts', 'jsx', 'js'].map((extension) => `${pages}.${extension}`),
347
+ ].find((candidate) => existsSync(join(detected.dir, candidate)))
348
+ // Through a link, the route would be written outside the app, where the link leads.
349
+ let inside = detected.dir
350
+ for (const segment of file.split(sep).slice(0, -1)) {
351
+ const next = join(inside, segment)
352
+ if (!entry(next)) break
353
+ inside = next
354
+ }
355
+ if (inside !== detected.dir && !isDirectory(inside)) {
356
+ return {
357
+ ...nothing,
358
+ refused: `${relative(detected.dir, inside)} isn’t a folder: the route can’t be written under it.`,
359
+ }
360
+ }
361
+ let leadsOut: boolean
362
+ try {
363
+ leadsOut = !within(realpathSync(detected.dir), realpathSync(inside))
364
+ } catch {
365
+ // A link that leads nowhere: nothing can be made in it either.
366
+ leadsOut = true
367
+ }
368
+ if (leadsOut) {
369
+ return {
370
+ ...nothing,
371
+ refused: `${relative(detected.dir, inside)} is a link to somewhere outside this app: the route would be written there. Run it in the app the link leads to.`,
372
+ }
373
+ }
374
+ if (!written && !taken && !writable(inside)) {
375
+ // Said now, as a dry run would have to: the run itself would stop here.
376
+ return {
377
+ ...nothing,
378
+ refused: `${relative(detected.dir, inside) || 'This folder'} can’t be written in: the route can’t be made there. Check its permissions.`,
379
+ }
380
+ }
381
+ if (taken) {
382
+ return {
383
+ ...nothing,
384
+ refused: `${taken} is there already: the app has something at ${path}. Choose another place with --path, such as --path /admin/db.`,
385
+ }
386
+ }
387
+ const notes: string[] = []
388
+
389
+ const lines: string[] = []
390
+ if (!detected.envNames.has('DB_ADMIN_PASSWORD')) {
391
+ lines.push(
392
+ `# OTW DB (${basePath}). A password of your own, ${MIN_PASSWORD} characters at least: whoever has it can open the database.`,
393
+ 'DB_ADMIN_PASSWORD=',
394
+ )
395
+ notes.push(
396
+ `Choose a strong password of your own and set it as DB_ADMIN_PASSWORD: ${MIN_PASSWORD} characters at least, from your password manager or a command such as openssl rand -base64 32. It’s set in none of the app’s env files; until it’s set somewhere, nobody signs in with a password. Keep it out of git: in .env.local on your machine (git check-ignore .env.local names the file when git leaves it alone), in your host’s settings where the app runs.`,
397
+ )
398
+ }
399
+ if (!detected.envMentions.has('DB_ADMIN_USERS')) {
400
+ lines.push(
401
+ '# The app’s signed-in users who get in without it: their emails, comma-separated.',
402
+ '# DB_ADMIN_USERS=you@example.com,colleague@example.com',
403
+ )
404
+ }
405
+ const named = [...detected.envNames].some((name) => /^DB_ADMIN_[A-Z0-9_]+_URL$/.test(name))
406
+ const own = OWN.find((name) => detected.envNames.has(name))
407
+ if (!named && !detected.envMentions.has('DB_ADMIN_MAIN_URL')) {
408
+ lines.push(
409
+ ...(own
410
+ ? [
411
+ `# The database it opens: the app’s own (${own}), read-only. To choose another, or more:`,
412
+ '# DB_ADMIN_MAIN_URL=postgres://user:password@host:5432/database',
413
+ ]
414
+ : [
415
+ '# The database it opens, such as postgres://user:password@host:5432/database:',
416
+ 'DB_ADMIN_MAIN_URL=',
417
+ ]),
418
+ '# DB_ADMIN_MAIN_ACCESS=write # read, unless you say so',
419
+ )
420
+ }
421
+
422
+ const unread = detected.unread.filter((file) => file !== 'package.json')
423
+ if (unread.length) {
424
+ notes.push(
425
+ `Not read, so what ${unread.length > 1 ? 'they set' : 'it sets'} isn’t counted above: ${unread.join(', ')} (not a file, or larger than such a file is). Check there for DB_ADMIN_PASSWORD and the database’s address yourself.`,
426
+ )
427
+ }
428
+ if (detected.passwordInDotEnv) {
429
+ notes.push(
430
+ 'DB_ADMIN_PASSWORD is set in .env, a file apps usually keep in git. If git has it, whoever can read the repository has the password: move it to .env.local (or your host’s settings) and choose a new one.',
431
+ )
432
+ }
433
+ if (!named && !own) {
434
+ notes.push(
435
+ detected.supabase
436
+ ? 'This app talks to Supabase through its API, so it holds no address of the database itself. In Supabase, open Connect, copy the “Session pooler” connection string, and set it as DB_ADMIN_MAIN_URL. (Not “Direct connection”: Vercel can’t reach it. Not “Transaction pooler”: the tool keeps a session.)'
437
+ : 'No database address was found. Set DB_ADMIN_MAIN_URL to the database to open, such as postgres://user:password@host:5432/database.',
438
+ )
439
+ }
440
+ if (detected.middleware) {
441
+ notes.push(
442
+ `This app has ${detected.middleware}. If it signs people in on every route, or redirects them, leave ${basePath} out of its matcher: the tool has its own sign-in, and its API must not be answered with a login page. For example: matcher: ['/((?!${basePath.slice(1)}|_next/static|_next/image|favicon.ico).*)']`,
443
+ )
444
+ }
445
+ if (detected.supabase) {
446
+ notes.push(
447
+ 'On Supabase Auth, the users you list in DB_ADMIN_USERS are recognised by their session, with no code. List only people who already have an account, and keep “Confirm email” on in Supabase: an address nobody has registered yet could otherwise be signed up by anyone.',
448
+ )
449
+ } else {
450
+ notes.push(
451
+ 'To let your own signed-in users in without the password, list their emails in DB_ADMIN_USERS and tell the route who is signed in: createDbRoute({ user: async () => (await auth())?.user?.email }).',
452
+ )
453
+ }
454
+ if (detected.nodeMajor !== null && detected.nodeMajor < 22) {
455
+ notes.push(
456
+ `package.json asks for Node ${detected.nodeMajor}; OTW DB needs 22.18 or newer. On Vercel, set the project’s Node.js version to 22 or 24.`,
457
+ )
458
+ }
459
+ if (detected.basePathUnread) {
460
+ notes.push(
461
+ `next.config mentions basePath in a way this couldn’t read as one plain path, so the route was written without it. If the app is served under one, name the whole address in the route file: createDbRoute({ basePath: '<your basePath>${path}' }).`,
462
+ )
463
+ }
464
+ notes.push(
465
+ 'On your host, set the same variables. On Vercel: vercel env add DB_ADMIN_PASSWORD (and DB_ADMIN_USERS, DB_ADMIN_MAIN_URL where you use them), then deploy.',
466
+ )
467
+
468
+ const add = { npm: 'install', pnpm: 'add', yarn: 'add', bun: 'add' }[detected.manager]
469
+ return {
470
+ refused: null,
471
+ files: written ? [] : [{ path: file, content: routeFile(basePath) }],
472
+ env: lines,
473
+ install:
474
+ flags.install === false || detected.installed
475
+ ? null
476
+ : { command: detected.manager, args: [add, '@otwdesign/db-next'] },
477
+ notes,
478
+ url: basePath,
479
+ }
480
+ }
481
+
482
+ /** How `apply` went. */
483
+ export interface InitOutcome {
484
+ /** Why the package wasn't installed, when installing it was tried and failed. */
485
+ installFailed: string | null
486
+ }
487
+
488
+ /**
489
+ * Does what the plan says, in the app's directory. `run` installs; a test stands in for it. An
490
+ * install that fails (no network, a registry that says no) is reported, not thrown: the files
491
+ * are written by then, and what's left to do must still be said.
492
+ */
493
+ export function apply(
494
+ detected: Detected,
495
+ planned: InitPlan,
496
+ run: (command: string, args: string[], cwd: string) => void = (command, args, cwd) =>
497
+ // On Windows the package managers are .cmd files, which only a shell runs. The command and
498
+ // its arguments are this file's own words, never what someone typed.
499
+ void execFileSync(command, args, {
500
+ cwd,
501
+ stdio: 'inherit',
502
+ shell: process.platform === 'win32',
503
+ }),
504
+ ): InitOutcome {
505
+ if (planned.refused) throw new Error(planned.refused)
506
+ for (const file of planned.files) {
507
+ const target = join(detected.dir, file.path)
508
+ mkdirSync(dirname(target), { recursive: true })
509
+ // Never over what's there: `plan` refused if it was, and this holds if it appeared since.
510
+ writeFileSync(target, file.content, { flag: 'wx' })
511
+ }
512
+ if (planned.install) {
513
+ try {
514
+ run(planned.install.command, planned.install.args, detected.dir)
515
+ } catch (error) {
516
+ return { installFailed: (error as Error).message.split('\n')[0] ?? 'it failed' }
517
+ }
518
+ }
519
+ return { installFailed: null }
520
+ }
521
+
522
+ /** What was done, or would be, for the terminal. */
523
+ export function report(
524
+ detected: Detected,
525
+ planned: InitPlan,
526
+ dryRun: boolean,
527
+ outcome: InitOutcome = { installFailed: null },
528
+ ): string {
529
+ if (planned.refused) return `${planned.refused}\n`
530
+ const did = dryRun ? 'Would' : 'Did'
531
+ const out = [`OTW DB for this Next.js app, at ${planned.url}:`, '']
532
+ for (const file of planned.files) out.push(` ${did} write ${file.path}`)
533
+ if (planned.install) {
534
+ const command = `${planned.install.command} ${planned.install.args.join(' ')}`
535
+ out.push(
536
+ outcome.installFailed
537
+ ? ` Couldn’t run ${command} (${outcome.installFailed}). Run it yourself, in this directory.`
538
+ : ` ${did} run ${command}`,
539
+ )
540
+ }
541
+ if (planned.env.length) {
542
+ out.push(
543
+ '',
544
+ ' Yours to add to the app’s environment (.env.local on your machine, your host’s settings):',
545
+ ...planned.env.map((line) => ` ${line}`),
546
+ )
547
+ }
548
+ out.push('', ...planned.notes.flatMap((note) => [`- ${note}`, '']))
549
+ out.push(
550
+ dryRun
551
+ ? 'Nothing was changed: run it again without --dry-run.'
552
+ : `${planned.env.includes('DB_ADMIN_PASSWORD=') ? 'Set DB_ADMIN_PASSWORD, start' : 'Start'} the app and open ${planned.url}.`,
553
+ )
554
+ // Text and line ends only. Nothing above quotes the app's files; this holds if a later line does.
555
+ return `${out.join('\n')}\n`.replace(/[^\n\P{Cc}]/gu, '')
556
+ }