@ultimat3/cli 31.2.0 → 31.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.
@@ -0,0 +1,121 @@
1
+ // `x doctor`'s database checks: the external Postgres answers `select 1`, and the embedded PGlite
2
+ // the app would open where there is none is installed. Facts read here, decided by pure rules.
3
+
4
+ // why: Bun has no synchronous file-exists or path-walking API; the peer is found on disk, never loaded.
5
+ import { existsSync } from 'node:fs';
6
+ import { dirname, join, resolve, sep } from 'node:path';
7
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
8
+ import { checkDb, PGLITE_FIX, PGLITE_MISSING, postgresClient } from '@ultimat3/db';
9
+ import type { Finding } from './output';
10
+ import { findingFrom } from './output';
11
+
12
+ /** What `x doctor` reads about the embedded database, without opening it. */
13
+ export interface EmbeddedDatabase {
14
+ /**
15
+ * True while `DATABASE_URL` is unset or blank — the condition that makes PGlite the app's
16
+ * database (`resolveServices`), and the same reading `probeDatabase` returns `null` on.
17
+ */
18
+ readonly selected: boolean;
19
+ /** Does `@electric-sql/pglite` resolve from the app root? */
20
+ readonly resolved: boolean;
21
+ }
22
+
23
+ const finding = (code: string, cause: string, fix: string): Finding => ({
24
+ code,
25
+ cause,
26
+ fix,
27
+ docs: ERROR_DOCS_URL,
28
+ });
29
+
30
+ /**
31
+ * The rule, pure. Red only where the embedded database is the one that would be opened: an app
32
+ * pointed at a real Postgres never loads PGlite, and a finding about an absent optional peer there
33
+ * is noise the reader learns to skim.
34
+ *
35
+ * `@ultimat3/db`'s own refusal, not a CLI twin of it — same `X_DB_UNAVAILABLE`, same sentence,
36
+ * same runnable fix. The package already says this the moment a query arrives; `x doctor` is what
37
+ * says it before `bin/setup` gets that far.
38
+ */
39
+ export const embeddedDatabaseFinding = (fact: EmbeddedDatabase): Finding | undefined =>
40
+ fact.selected && !fact.resolved
41
+ ? finding(
42
+ 'X_DB_UNAVAILABLE',
43
+ `${PGLITE_MISSING} — and DATABASE_URL is unset or blank, so the embedded one is the database this app would open`,
44
+ PGLITE_FIX,
45
+ )
46
+ : undefined;
47
+
48
+ /**
49
+ * `DATABASE_URL` as BOTH halves of the database question read it: unset and blank are one case.
50
+ * One seam, because the two halves are complementary — a second reading of the same variable is
51
+ * how a configuration ends up reported by neither probe, or by both.
52
+ */
53
+ export const externalUrl = (raw: string | undefined): string | undefined =>
54
+ raw === undefined || raw.trim() === '' ? undefined : raw;
55
+
56
+ /**
57
+ * Is the optional peer INSTALLED for this app — a `node_modules` walk up from the app root.
58
+ *
59
+ * Never an IMPORT: loading PGlite boots 26 MB of WASM and takes the single-writer lock the next
60
+ * command needs, and a diagnostic must not be the reason `x dev` cannot open the database it just
61
+ * reported on.
62
+ *
63
+ * Never `Bun.resolveSync` either, which was this check's first draft. It falls back to Bun's
64
+ * machine-global install cache: measured 2026-09-11 against a freshly scaffolded app with no
65
+ * `node_modules` anywhere above it, `Bun.resolveSync('@electric-sql/pglite', <app>)` answered
66
+ * `~/.bun/install/cache/@electric-sql/pglite@0.5.8@@@1/dist/index.js` — a version the app does not
67
+ * depend on, in a directory `bun install` never wrote for it. A box that had downloaded the package
68
+ * ONCE, for anything, would have read as ready on every app after it, which is the exact opposite
69
+ * of the question. The walk asks what `bun add` answers, and nothing else.
70
+ *
71
+ * Up from the root and not at it, because an app checked out inside a larger workspace is installed
72
+ * by the hoisting one: `examples/dummy` in this repository has no `node_modules` of its own.
73
+ */
74
+ export const installedAbove = (dir: string, specifier: string): boolean => {
75
+ let current = resolve(dir);
76
+ // Bounded by the path itself — one segment per step — rather than by `for (;;)` and the promise
77
+ // that `dirname('/')` is `/`. The loop still stops on that, one step earlier.
78
+ for (let remaining = current.split(sep).length; remaining > 0; remaining -= 1) {
79
+ if (existsSync(join(current, 'node_modules', specifier, 'package.json'))) return true;
80
+ const parent = dirname(current);
81
+ if (parent === current) return false;
82
+ current = parent;
83
+ }
84
+ return false;
85
+ };
86
+
87
+ /**
88
+ * A real `select 1` through the app's own driver, not a TCP connect: a running Postgres with the
89
+ * wrong credentials or a database that does not exist accepts the socket and refuses the session,
90
+ * which is the case an operator most needs told about before a deploy.
91
+ *
92
+ * The pool is CLOSED on every path — this command exits, and a held pool is a connection slot the
93
+ * next `x db migrate` cannot have.
94
+ */
95
+ export async function probeDatabase(
96
+ url: string | undefined,
97
+ env: Readonly<Record<string, string | undefined>>,
98
+ ): Promise<Finding | null> {
99
+ if (externalUrl(url) === undefined) return null;
100
+ let client: ReturnType<typeof postgresClient>;
101
+ try {
102
+ client = postgresClient({ url, env, applicationName: 'x-doctor' });
103
+ } catch (error) {
104
+ return findingFrom(error);
105
+ }
106
+ try {
107
+ const report = await checkDb(client);
108
+ if (report.ok) return null;
109
+ // `DbHealthReport.error` is `checkDb`'s own rendering of what refused, never this file's — the
110
+ // caught value is `checkDb`'s to read, and it is the one function that already reads it safely.
111
+ return finding(
112
+ 'X_DB_UNAVAILABLE',
113
+ `DATABASE_URL does not answer \`select 1\`: ${report.error ?? 'no reason reported'}`,
114
+ // `dbUnavailable`'s own two branches, verbatim: a second wording for one condition is two
115
+ // answers to "what do I do", and this one is reached first, before any command opens a pool.
116
+ 'set DATABASE_URL to a reachable Postgres url, or run `x dev` to use the embedded PGlite',
117
+ );
118
+ } finally {
119
+ await client.close();
120
+ }
121
+ }
@@ -0,0 +1,88 @@
1
+ // `x doctor`'s port checks: both ports `x dev` binds, probed by role, and the one reading of which
2
+ // port that is (`--port`, then `PORT`, then 3000).
3
+
4
+ import { ERROR_DOCS_URL } from '@ultimat3/core';
5
+ import type { DoctorProbe } from './doctor-probe';
6
+ import { PORT_RANGE, portPairAfter, readIntFlag } from './flag-number';
7
+ import type { Finding } from './output';
8
+ import { findingFrom } from './output';
9
+ import type { ParsedArgs } from './parse';
10
+ import { syncPortFor } from './role-sync';
11
+ import { portFromEnv } from './serve-env';
12
+ import { quoteArg } from './shell-quote';
13
+
14
+ const finding = (code: string, cause: string, fix: string): Finding => ({
15
+ code,
16
+ cause,
17
+ fix,
18
+ docs: ERROR_DOCS_URL,
19
+ });
20
+
21
+ /**
22
+ * Both ports `x dev` binds, each labelled with the role that wants it. `x dev --port 3999` printed
23
+ * `web listening on 3999`, then died on 4000 as `X_CLI_UNEXPECTED` with a caught `Error` rendered
24
+ * into its cause — and `x doctor --port 3999` answered "no findings", because it probed the web
25
+ * port and only the web port (#F5). The neighbouring port is not an implementation detail an
26
+ * operator can ignore: `docker-compose.prod.yml` publishes `3001:3001` from it and `docker/helm`
27
+ * derives `PORT = .port - 1` from it, so it is part of the contract `x dev` runs by.
28
+ *
29
+ * The suggested port moves BOTH: `x dev --port N` occupies N and N+1, so a free N beside a taken
30
+ * N+1 is still not a runnable command. It did not move both until 2026-09 — the line was
31
+ * `neighbouringPort(probe.port)`, which for the sync finding IS the port the finding is about, and
32
+ * a docblock claiming otherwise is how it survived. `portPairAfter` is the one reader of that rule
33
+ * and `role-sync.ts`'s own refusal shares it.
34
+ *
35
+ * The sync port is `syncPortFor`, never `neighbouringPort` again: that helper answers 65534 for a
36
+ * web port of 65535 — BELOW the web port, and a port `x dev` never binds — where the boot refuses
37
+ * the run outright with `X_PORT_INVALID`. A probe that reports on a socket the command would never
38
+ * open is answering a question nobody asked, so the boot's own rule decides, and its refusal is
39
+ * reported instead of a probe. Alone, and ahead of the web port: there is no runnable `x dev` at
40
+ * this port whatever the other one answers, and a second finding about it is noise over the cause.
41
+ */
42
+ export async function portFindings(
43
+ probe: Pick<DoctorProbe, 'port' | 'portFree'>,
44
+ ): Promise<readonly Finding[]> {
45
+ let syncPort: number;
46
+ try {
47
+ syncPort = syncPortFor(probe.port);
48
+ } catch (error) {
49
+ // The boot's own error, carried whole — `findingFrom` reads its code, cause and fix off the
50
+ // value rather than rendering it, which is what `scripts/catch-render.ts` requires.
51
+ return [findingFrom(error)];
52
+ }
53
+ const wanted = [
54
+ { port: probe.port, role: 'web' },
55
+ { port: syncPort, role: 'sync' },
56
+ ] as const;
57
+ const findings: Finding[] = [];
58
+ for (const entry of wanted) {
59
+ if (await probe.portFree(entry.port)) continue;
60
+ findings.push(
61
+ finding(
62
+ 'X_PORT_IN_USE',
63
+ `port ${entry.port} is already listening, and \`x dev --port ${probe.port}\` binds it for the ${entry.role} role`,
64
+ `x dev --port ${quoteArg(String(portPairAfter(probe.port)))}`,
65
+ ),
66
+ );
67
+ }
68
+ return findings;
69
+ }
70
+
71
+ /**
72
+ * The port to TEST, and the one place `x doctor` reads it: `devPortFor`'s order — `--port`, then
73
+ * `PORT` (`portFromEnv`, the one reader of it), then 3000 — so the probe answers about the port
74
+ * `x dev` will bind. It probed 3000 under `PORT=4000` while dev bound 4000 and 4001. `PORT_RANGE.min`
75
+ * is 0 because `x dev --port 0` means "let the kernel pick"; here 0 means nothing, and
76
+ * `Bun.serve({ port: 0 })` always succeeds — so the port check could not fail.
77
+ */
78
+ export const doctorPort = (
79
+ args: ParsedArgs,
80
+ env: Readonly<Record<string, string | undefined>>,
81
+ ): number =>
82
+ readIntFlag(args, {
83
+ name: 'port',
84
+ command: 'doctor',
85
+ ...PORT_RANGE,
86
+ min: 1,
87
+ example: 'x doctor --port 3000',
88
+ }) ?? portFromEnv(env);
@@ -0,0 +1,148 @@
1
+ // The seam `runDoctor` reads instead of the environment, and the real one over this machine: every
2
+ // fact `x doctor` judges is reached through `DoctorProbe`, so every rule is testable with a stub.
3
+
4
+ // why: Bun has no synchronous file-exists or path-join API; the probe answers `exists` synchronously.
5
+ import { existsSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { PGLITE_PACKAGE } from '@ultimat3/db';
8
+ import { loadApp } from './app-load';
9
+ import { IMPORT_UNRESOLVED } from './app-load-unresolved';
10
+ import { findAppRoot } from './app-root';
11
+ import { checkMigrationSnapshots } from './db-snapshot';
12
+ import { type AuthStorageFact, authStorageProbe } from './doctor-auth';
13
+ import type { EmbeddedDatabase } from './doctor-database';
14
+ import { externalUrl, installedAbove, probeDatabase } from './doctor-database';
15
+ import type { OfflineFallbackFact } from './doctor-offline';
16
+ import { offlineFallbackProbe } from './doctor-offline';
17
+ import type { PoolerFact } from './doctor-pooler';
18
+ import { poolerProbe } from './doctor-pooler';
19
+ import { rowSecurityProbe } from './doctor-row-security';
20
+ import type { SealedKeysFact } from './doctor-sealed';
21
+ import { sealedKeysProbe } from './doctor-sealed';
22
+ import { typescriptProbe } from './doctor-typescript';
23
+ import { machineSecretFindings } from './framework-env';
24
+ import type { Finding } from './output';
25
+ import { portFree } from './port-probe';
26
+ import { checkMigrationDrift } from './schema-drift';
27
+ import type { TypescriptLag } from './typescript-floor';
28
+
29
+ /**
30
+ * The injection seam `runDoctor` reads instead of the environment. Not a semver surface —
31
+ * `wiki/Upgrading.md` covers `X_*` codes, the eight primitive shapes, the `x` CLI surface, the
32
+ * tier table and `app.config.ts` fields, and not this — so a new fact the probe must report is a
33
+ * REQUIRED field: an optional one lets an implementation skip the check and still typecheck.
34
+ */
35
+ export interface DoctorProbe {
36
+ readonly bunVersion: string;
37
+ /** App root, or undefined when the command runs outside an app. */
38
+ readonly root: string | undefined;
39
+ readonly port: number;
40
+ /** `APP_URL` as this environment declares it; `undefined` when unset. */
41
+ readonly appUrl: string | undefined;
42
+ /**
43
+ * The framework's own secrets this machine lacks — `framework-env.ts`'s
44
+ * `machineSecretFindings`, gated by `namedDeployed`: only an environment NAMED staging or
45
+ * production (an unnamed developer shell owes nothing; `x env check` is the fail-closed answer).
46
+ * The list's own `needed`/`unsafe` decide; doctor reports.
47
+ */
48
+ readonly frameworkFindings: readonly Finding[];
49
+ exists(relativePath: string): boolean;
50
+ portFree(port: number): Promise<boolean>;
51
+ /**
52
+ * Is the configured database reachable, and what refused? `null` is "reachable, or there is
53
+ * nothing external to reach" — an unset `DATABASE_URL` is embedded PGlite, which `x dev` owns
54
+ * and which a probe would take the single-writer lock on.
55
+ *
56
+ * Until this existed `x doctor` answered "no findings — environment is shippable" against
57
+ * `DATABASE_URL=postgres://nope:nope@localhost:5432/nope`, while `x db migrate` on the same env
58
+ * correctly answered `X_DB_UNAVAILABLE` (#F5).
59
+ */
60
+ database(): Promise<Finding | null>;
61
+ /**
62
+ * Is the EMBEDDED database usable, and is it the one this environment would open? A FACT and not
63
+ * a finding, the split `offlineFallback` makes below: reaching a module resolver is IO, and what
64
+ * an unresolvable optional peer MEANS is a pure rule with a pure test.
65
+ *
66
+ * `database()` answers `null` the moment `DATABASE_URL` is unset — which is exactly a bare VM,
67
+ * the configuration `x dev` invents a database FOR — so until this existed `x doctor` was silent
68
+ * about the only database a fresh box has. `bin/setup` found out instead, at `x db migrate`.
69
+ */
70
+ embeddedDatabase(): Promise<EmbeddedDatabase>;
71
+ drift(): Promise<readonly Finding[]>;
72
+ /**
73
+ * The other half of the migrations directory: a newest migration with no `.snapshot.json`, which
74
+ * is what `x db gen` refuses on. Separate from `drift()` because they are separate questions with
75
+ * separate remedies — one is "generate a migration", the other is "this migration is incomplete".
76
+ */
77
+ snapshots(): Promise<readonly Finding[]>;
78
+ /**
79
+ * What the app declared as its offline fallback, and which routes it really serves. A FACT and
80
+ * not a finding, because deciding is `offlineFallbackFinding`'s and this seam's whole job is
81
+ * reaching the disk — the same split `drift()` makes one question over.
82
+ */
83
+ offlineFallback(): Promise<OfflineFallbackFact>;
84
+ /**
85
+ * The app's `.sealed()` columns and the master keys this environment declares. A FACT, for the
86
+ * reason `offlineFallback` is one: loading the app and opening the secrets file is IO, and what
87
+ * a retired key beside a sealed column means is `sealedKeyFindings`' pure rule.
88
+ */
89
+ sealedKeys(): Promise<SealedKeysFact>;
90
+ /**
91
+ * What an upgrade left in the auth tables for an operator to finish: unsealed second-factor
92
+ * secrets, and tables no release reads. Asked of an external database only.
93
+ */
94
+ authStorage(): Promise<AuthStorageFact>;
95
+ /** The statement bound the session really reads, and what a pooler refused (`doctor-pooler.ts`). */
96
+ pooler(): Promise<PoolerFact>;
97
+ /** Each manifest whose `typescript` range lags the scaffold's (`doctor-typescript.ts`). */
98
+ typescript(): Promise<readonly TypescriptLag[]>;
99
+ /** With `database.rowSecurity` on, whether the serving role is exempt (`doctor-row-security.ts`). */
100
+ rowSecurity?(): Promise<readonly Finding[]>;
101
+ }
102
+
103
+ export function probeFor(
104
+ cwd: string,
105
+ bunVersion: string,
106
+ port: number,
107
+ // The environment `doctorPort` read `PORT` from, so `APP_URL` is judged against the same one.
108
+ env: Readonly<Record<string, string | undefined>> = process.env,
109
+ ): DoctorProbe {
110
+ const root = findAppRoot(cwd)?.dir;
111
+ return {
112
+ bunVersion,
113
+ root,
114
+ port,
115
+ appUrl: env['APP_URL'],
116
+ frameworkFindings: machineSecretFindings(env),
117
+ exists: (relativePath) => (root === undefined ? false : existsSync(join(root, relativePath))),
118
+ portFree,
119
+ database: () => probeDatabase(process.env['DATABASE_URL'], env),
120
+ // `root ?? cwd` because the walk needs a directory that exists; outside an app `runDoctor`
121
+ // returns on `X_NOT_IN_APP` before this is ever asked, so the value only has to be honest.
122
+ embeddedDatabase: async () => ({
123
+ selected: externalUrl(process.env['DATABASE_URL']) === undefined,
124
+ resolved: installedAbove(root ?? cwd, PGLITE_PACKAGE),
125
+ }),
126
+ drift: async () => (root === undefined ? [] : checkMigrationDrift(root)),
127
+ // The import half too: `X_CLI_UNEXPECTED` used to send a reader here and find this silent.
128
+ snapshots: async () =>
129
+ root === undefined
130
+ ? []
131
+ : [...(await unresolvedImportFindings(root)), ...(await checkMigrationSnapshots(root))],
132
+ // `routes: undefined` outside an app is "not judged", which is what the caller already is:
133
+ // `runDoctor` returns on `X_NOT_IN_APP` before this can be asked.
134
+ offlineFallback: async () =>
135
+ root === undefined ? { fallback: null, routes: undefined } : offlineFallbackProbe(root),
136
+ sealedKeys: async () =>
137
+ root === undefined ? { columns: undefined, keys: undefined } : sealedKeysProbe(root),
138
+ authStorage: () => authStorageProbe(process.env['DATABASE_URL'], env),
139
+ pooler: () => poolerProbe(process.env['DATABASE_URL'], env),
140
+ typescript: async () => (root === undefined ? [] : typescriptProbe(root)),
141
+ rowSecurity: async () =>
142
+ root === undefined ? [] : rowSecurityProbe(root, process.env['DATABASE_URL'], env),
143
+ };
144
+ }
145
+
146
+ /** What a load reports, narrowed to the one failure a doctor can name a repair for. */
147
+ const unresolvedImportFindings = async (root: string): Promise<readonly Finding[]> =>
148
+ (await loadApp(root)).findings.filter((finding) => finding.code === IMPORT_UNRESOLVED);
@@ -20,7 +20,7 @@ import {
20
20
  SQL_AUTH_LIMIT_TABLES,
21
21
  SQL_AUTH_SERVER_TABLES,
22
22
  SQL_TOTP_REPLAY_TABLE,
23
- } from '@ultimat3/auth';
23
+ } from '@ultimat3/auth/schema';
24
24
  import { FAILURES_TABLE, SQL_FAILURES_TABLE } from '@ultimat3/db';
25
25
  import { SQL_RATE_LIMIT_TABLE } from '@ultimat3/http';
26
26
  import { SQL_JOBS_TABLE } from '@ultimat3/jobs';
@@ -123,7 +123,9 @@ export const FRAMEWORK_SCHEMA: readonly FrameworkSchema[] = Object.freeze([
123
123
  * here on exactly the rule the rate-limit and audit rows already follow.
124
124
  *
125
125
  * `AUTH_TABLE_NAMES` rather than eight literals: @ultimat3/auth already publishes the list, and a
126
- * second copy is a second thing to keep right when a table is added.
126
+ * second copy is a second thing to keep right when a table is added. Every auth row reads
127
+ * `@ultimat3/auth/schema`, a leaf, for the admin row's reason: not one auth runtime module on
128
+ * `ROLE=migrate`'s path (#1051).
127
129
  */
128
130
  Object.freeze({
129
131
  pkg: '@ultimat3/auth',
@@ -0,0 +1,35 @@
1
+ // The pool the island build runs its groups through: at most `width` at once, answers in item
2
+ // order, and stopped by its first failure.
3
+
4
+ /**
5
+ * `run` over `items`, at most `width` at a time, answers in `items` order. 159 builds at once (the
6
+ * bench app) bought nothing over twelve — the plugins' callbacks share one JS thread — and held
7
+ * every build's graph in memory together.
8
+ */
9
+ export async function boundedMap<T, R>(
10
+ items: readonly T[],
11
+ width: number,
12
+ run: (item: T) => Promise<R>,
13
+ ): Promise<R[]> {
14
+ const results: R[] = new Array(items.length);
15
+ let next = 0;
16
+ // Set by the first rejection and read before every start: the builds already in flight finish
17
+ // (a `Bun.build` cannot be cancelled), but no idle worker takes another group — in `x dev` one
18
+ // island's syntax error left every remaining group bundling, ~12 s, into the next generation.
19
+ // And the call answers only once those in flight HAVE finished: each registers stylesheets and
20
+ // pins chunk bytes process-wide, so one outliving the call would write into the next generation.
21
+ let failure: { readonly error: unknown } | undefined;
22
+ const worker = async (): Promise<void> => {
23
+ for (let index = next++; failure === undefined && index < items.length; index = next++) {
24
+ try {
25
+ results[index] = await run(items[index] as T);
26
+ } catch (error) {
27
+ if (failure === undefined) failure = { error };
28
+ }
29
+ }
30
+ };
31
+ const workers = Math.max(1, Math.min(width, items.length));
32
+ await Promise.all(Array.from({ length: items.length === 0 ? 0 : workers }, worker));
33
+ if (failure !== undefined) throw failure.error;
34
+ return results;
35
+ }