@ultimat3/cli 31.51.0 → 31.52.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/README.md +9 -9
- package/package.json +29 -29
- package/src/catalog-layout.ts +194 -0
- package/src/cmd-i18n-spec.ts +4 -4
- package/src/cmd-i18n-split.ts +133 -0
- package/src/cmd-i18n.ts +46 -66
- package/src/config-redact.ts +20 -4
- package/src/db-rollback-pass.ts +4 -1
- package/src/dev-child-watch.ts +16 -0
- package/src/dev-db-migrate.ts +27 -46
- package/src/dev-db-migrator-hold.ts +131 -0
- package/src/dev-db-rollback.ts +11 -2
- package/src/dev-rebuild-schema.ts +7 -24
- package/src/generate-catalog-locales.ts +25 -2
- package/src/generate-follow-ups.ts +8 -3
- package/src/i18n-audit.ts +17 -33
- package/src/i18n-index.ts +108 -31
- package/src/i18n-locale-parity.ts +14 -6
- package/src/i18n-new-locale.ts +75 -0
- package/src/i18n-registration.ts +52 -27
- package/src/island-capture.ts +36 -7
- package/src/merge-state.ts +3 -2
- package/src/messages-floor.ts +2 -0
- package/src/messages.ts +2 -0
- package/src/serve-boot-telemetry.ts +106 -0
- package/src/serve-boot.ts +23 -4
- package/src/shot-blank.ts +70 -0
- package/src/templates/catalog-barrel.ts +84 -0
- package/src/templates/guard-released-forms.ts +2 -1
- package/src/templates/guard-untranslated-string.ts +27 -6
- package/src/templates/locales.ts +6 -0
- package/src/templates/scaffold-gitattributes.ts +9 -2
- package/src/templates/scaffold-i18n.ts +10 -6
- package/src/templates/shapes/offline.ts +5 -2
- package/src/test-ignores.ts +3 -2
- package/src/verify-floor.ts +9 -1
- package/src/verify-local-only.ts +66 -0
- package/src/verify-run.ts +17 -2
- package/wiki/Actions.md +1 -1
- package/wiki/Auth.md +3 -3
- package/wiki/Batching-And-Preloading.md +1 -0
- package/wiki/CLI-Reference-Data.md +241 -0
- package/wiki/CLI-Reference-Gate.md +572 -0
- package/wiki/CLI-Reference-Project.md +414 -0
- package/wiki/CLI-Reference-Ship.md +348 -0
- package/wiki/CLI-Reference-Tools.md +666 -0
- package/wiki/CLI-Reference.md +14 -2225
- package/wiki/Compared.md +8 -8
- package/wiki/Configuration.md +26 -2
- package/wiki/Deployment.md +1 -1
- package/wiki/Entities-And-Migrations.md +3 -2
- package/wiki/I18n.md +39 -5
- package/wiki/Installation.md +1 -1
- package/wiki/Jobs-And-Workflows.md +29 -1
- package/wiki/Known-Gaps.md +3 -0
- package/wiki/Observability.md +15 -1
- package/wiki/Outbound-HTTP.md +62 -2
- package/wiki/PWA-And-Offline.md +1 -1
- package/wiki/Policies-And-Authz.md +10 -0
- package/wiki/Realtime.md +29 -2
- package/wiki/Static-Assets.md +1 -1
- package/wiki/Testing.md +33 -0
- package/wiki/Theming.md +31 -8
- package/wiki/Troubleshooting.md +1 -1
- package/wiki/Upgrading.md +5 -1
package/src/cmd-i18n.ts
CHANGED
|
@@ -1,34 +1,28 @@
|
|
|
1
|
-
// `x i18n check|add <locale>|sync <locale
|
|
1
|
+
// `x i18n check|add <locale>|sync <locale>|split [<locale>]` — the command every X_LOCALE_UNSUPPORTED,
|
|
2
2
|
// X_CATALOG_MISSING_KEYS and X_CATALOG_INVALID fix line already names. CLI wiring only: the
|
|
3
3
|
// facts come from `i18n-audit.ts`, the audit itself from `@ultimat3/i18n`'s own `auditCatalogs`.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
// one there is — `Bun.write` overwrites, so an existence check before it is a race a second
|
|
7
|
-
// `x i18n add` wins. `mkdir` comes with it because `open` does not create the parent directory
|
|
8
|
-
// `Bun.write` would, and `node:path` because Bun exposes no path API to build what either of them
|
|
9
|
-
// takes.
|
|
10
|
-
import { type FileHandle, mkdir, open } from 'node:fs/promises';
|
|
11
|
-
import { dirname, join } from 'node:path';
|
|
12
|
-
import { DEFAULT_LOCALE, stringField } from '@ultimat3/core';
|
|
5
|
+
import { DEFAULT_LOCALE } from '@ultimat3/core';
|
|
13
6
|
import type { Catalog } from '@ultimat3/i18n';
|
|
14
7
|
import { auditCatalogs, catalogFor, catalogKeys } from '@ultimat3/i18n';
|
|
15
8
|
import { adminKeyLabel, mountedAdminKeys } from './admin-catalog-keys';
|
|
16
9
|
import { loadApp } from './app-load';
|
|
17
10
|
import { requireAppRoot } from './app-root';
|
|
11
|
+
import type { CatalogLayout } from './catalog-layout';
|
|
12
|
+
import {
|
|
13
|
+
catalogLocation,
|
|
14
|
+
loadLayoutCatalogs,
|
|
15
|
+
readCatalogLayout,
|
|
16
|
+
writeLocaleCatalog,
|
|
17
|
+
} from './catalog-layout';
|
|
18
18
|
import { i18nSpec } from './cmd-i18n-spec';
|
|
19
|
+
import { runSplit } from './cmd-i18n-split';
|
|
19
20
|
import type { CliCommand, CommandContext } from './command';
|
|
20
|
-
import { BadFlagError,
|
|
21
|
-
import {
|
|
22
|
-
auditApp,
|
|
23
|
-
loadCatalogs,
|
|
24
|
-
resolveDefaultLocale,
|
|
25
|
-
scanSource,
|
|
26
|
-
seedCatalog,
|
|
27
|
-
serializeCatalog,
|
|
28
|
-
syncCatalog,
|
|
29
|
-
} from './i18n-audit';
|
|
21
|
+
import { BadFlagError, MissingPositionalError } from './errors';
|
|
22
|
+
import { auditApp, resolveDefaultLocale, scanSource, seedCatalog, syncCatalog } from './i18n-audit';
|
|
30
23
|
import { syncI18nIndex } from './i18n-index';
|
|
31
24
|
import { localeParityFindings } from './i18n-locale-parity';
|
|
25
|
+
import { writeNewLocale } from './i18n-new-locale';
|
|
32
26
|
import {
|
|
33
27
|
checkRegistration,
|
|
34
28
|
isLoudMiss,
|
|
@@ -48,41 +42,6 @@ export { I18N_SUBCOMMANDS } from './cmd-i18n-spec';
|
|
|
48
42
|
/** `ExtractReport` is plain JSON by construction — same idiom as `cmd-registries.ts`'s `asJson`. */
|
|
49
43
|
const asJson = (value: object): Record<string, JsonValue> => value as Record<string, JsonValue>;
|
|
50
44
|
|
|
51
|
-
/**
|
|
52
|
-
* `open`'s failure when the file is already there — the one errno this command translates.
|
|
53
|
-
*
|
|
54
|
-
* `stringField`, never `'code' in error && error.code`: `in` narrows for the COMPILER and promises
|
|
55
|
-
* the runtime nothing, so the read still happens on a value this process did not build and a
|
|
56
|
-
* throwing getter takes the command down one line after the guard written to make it safe. The
|
|
57
|
-
* same repair `dev-lock.ts` took for the cast spelling of the identical read.
|
|
58
|
-
*/
|
|
59
|
-
const isAlreadyExists = (error: unknown): boolean => stringField(error, 'code') === 'EEXIST';
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* The exclusive half of the create: `wx` fails rather than truncates, so an existing catalog is
|
|
63
|
-
* refused by the write itself. An `existsSync` before a `Bun.write` is the same answer with a
|
|
64
|
-
* window in it, and what falls through that window is a translator's work.
|
|
65
|
-
*/
|
|
66
|
-
async function openExclusive(absolute: string, locale: string): Promise<FileHandle> {
|
|
67
|
-
try {
|
|
68
|
-
return await open(absolute, 'wx');
|
|
69
|
-
} catch (error) {
|
|
70
|
-
if (isAlreadyExists(error)) throw new CatalogExistsError({ locale, path: catalogPath(locale) });
|
|
71
|
-
throw error;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** `x i18n add`'s only write. `catalogs/` may not exist yet, and `open` never creates it. */
|
|
76
|
-
async function writeNewCatalog(absolute: string, locale: string, contents: string): Promise<void> {
|
|
77
|
-
await mkdir(dirname(absolute), { recursive: true });
|
|
78
|
-
const handle = await openExclusive(absolute, locale);
|
|
79
|
-
try {
|
|
80
|
-
await handle.writeFile(contents);
|
|
81
|
-
} finally {
|
|
82
|
-
await handle.close();
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
45
|
function requireLocalePositional(ctx: CommandContext, sub: string): string {
|
|
87
46
|
const raw = ctx.args.positionals[0];
|
|
88
47
|
if (raw === undefined) {
|
|
@@ -132,21 +91,31 @@ const unansweredAdminKeys = (locale: string, keys: readonly string[]): readonly
|
|
|
132
91
|
unanswered(catalogFor(locale), keys);
|
|
133
92
|
|
|
134
93
|
async function runCheck(root: string): Promise<CommandResult> {
|
|
135
|
-
const { report: audited, catalogs, extraction, ignoreUnused } = await auditApp(root);
|
|
94
|
+
const { report: audited, catalogs, extraction, ignoreUnused, layout } = await auditApp(root);
|
|
136
95
|
// Corrected once, before anything reads it: the table's `missing` column, the summary count, the
|
|
137
96
|
// findings and `--json`'s `data` are four projections of one report, and a placeholder counted in
|
|
138
97
|
// only some of them is the command disagreeing with itself about the same app.
|
|
139
98
|
const report = withPlaceholdersMissing(audited, catalogs);
|
|
140
99
|
// The runtime question, asked after the file question and never instead of it: a catalog can be
|
|
141
100
|
// complete on disk, used everywhere in source, and reach no registry at all (issue #249).
|
|
142
|
-
const registration = await checkRegistration({
|
|
101
|
+
const registration = await checkRegistration({
|
|
102
|
+
root,
|
|
103
|
+
catalogs,
|
|
104
|
+
extraction,
|
|
105
|
+
ignoreUnused,
|
|
106
|
+
layout,
|
|
107
|
+
});
|
|
143
108
|
// The two rules only a comparison with the reference locale can see: a slot one side does not
|
|
144
109
|
// have, and a string nobody translated. The same call `x verify`'s `i18n` step makes, so the
|
|
145
110
|
// command and the gate answer about an app with one voice.
|
|
146
|
-
const parity = localeParityFindings(catalogs);
|
|
111
|
+
const parity = localeParityFindings(catalogs, layout);
|
|
147
112
|
const parityLocales = new Set(parity.map((finding) => finding.meta?.['locale'])).size;
|
|
148
113
|
|
|
149
|
-
const findings: Finding[] = [
|
|
114
|
+
const findings: Finding[] = [
|
|
115
|
+
...missingKeyFindings(report, layout),
|
|
116
|
+
...registration.findings,
|
|
117
|
+
...parity,
|
|
118
|
+
];
|
|
150
119
|
|
|
151
120
|
// Whether the LOCALE has a catalog is the wrong question — the framework's own `en` is always
|
|
152
121
|
// registered, so a locale-presence column reads `yes` for an app whose every key is a loud miss.
|
|
@@ -228,12 +197,14 @@ async function runCheck(root: string): Promise<CommandResult> {
|
|
|
228
197
|
|
|
229
198
|
async function runAdd(root: string, ctx: CommandContext): Promise<CommandResult> {
|
|
230
199
|
const locale = resolveOneLocale(ctx, 'add');
|
|
231
|
-
const path = catalogPath(locale);
|
|
232
200
|
const app = await loadApp(root);
|
|
233
|
-
const
|
|
201
|
+
const layout = await readCatalogLayout(root);
|
|
202
|
+
const catalogs = await loadLayoutCatalogs(root, layout);
|
|
234
203
|
const from = resolveDefaultLocale(app.locales.defaultLocale, catalogs);
|
|
235
204
|
const seeded = seedCatalog(from === undefined ? {} : (catalogs[from] ?? {}));
|
|
236
|
-
|
|
205
|
+
// In the default locale's form: a split app's new locale is a directory of the same files.
|
|
206
|
+
const source = from === undefined ? undefined : layout[from];
|
|
207
|
+
const path = await writeNewLocale(root, locale, seeded, source);
|
|
237
208
|
// The second half of adding a locale, and without it this command SHIPPED A RED GATE: the file
|
|
238
209
|
// landed, `packages/i18n/src/index.ts` still said `locales: { en }`, and `x verify --only i18n`
|
|
239
210
|
// answered `X_CATALOG_UNREGISTERED` with a fix naming an edit that had already been made. Same
|
|
@@ -319,6 +290,7 @@ async function adminCatalog(locale: string, seeded: boolean): Promise<Catalog> {
|
|
|
319
290
|
async function backfillDefault(
|
|
320
291
|
root: string,
|
|
321
292
|
catalogs: Readonly<Record<string, Catalog>>,
|
|
293
|
+
layout: CatalogLayout,
|
|
322
294
|
from: string,
|
|
323
295
|
adminKeys: readonly string[],
|
|
324
296
|
): Promise<readonly string[]> {
|
|
@@ -330,13 +302,14 @@ async function backfillDefault(
|
|
|
330
302
|
};
|
|
331
303
|
const source = Object.fromEntries(adminKeys.map((key) => [key, real(key)]));
|
|
332
304
|
const { merged, added } = syncCatalog(target, source);
|
|
333
|
-
if (added.length > 0) await
|
|
305
|
+
if (added.length > 0) await writeLocaleCatalog(root, from, merged, layout[from]);
|
|
334
306
|
return added;
|
|
335
307
|
}
|
|
336
308
|
|
|
337
309
|
async function runSync(root: string, ctx: CommandContext): Promise<CommandResult> {
|
|
338
310
|
const locale = resolveOneLocale(ctx, 'sync');
|
|
339
|
-
const
|
|
311
|
+
const layout = await readCatalogLayout(root);
|
|
312
|
+
const catalogs = await loadLayoutCatalogs(root, layout);
|
|
340
313
|
const target = catalogs[locale];
|
|
341
314
|
if (target === undefined) {
|
|
342
315
|
throw new BadFlagError({
|
|
@@ -364,9 +337,12 @@ async function runSync(root: string, ctx: CommandContext): Promise<CommandResult
|
|
|
364
337
|
: seedCatalog(catalogs[from] ?? {})),
|
|
365
338
|
};
|
|
366
339
|
const { merged, added } = syncCatalog(target, source);
|
|
367
|
-
|
|
340
|
+
// Into the locale's own form: a split locale's key lands in its namespace file, created if new.
|
|
341
|
+
if (added.length > 0) await writeLocaleCatalog(root, locale, merged, layout[locale]);
|
|
368
342
|
const adminAdded = added.filter((key) => Object.hasOwn(admin, key));
|
|
369
|
-
const defaultAdded = seeded
|
|
343
|
+
const defaultAdded = seeded
|
|
344
|
+
? []
|
|
345
|
+
: await backfillDefault(root, catalogs, layout, from, adminAdded);
|
|
370
346
|
// Unconditional, and not only when keys moved: a catalog that reached disk some other way — a
|
|
371
347
|
// hand-created file, a `git merge` — is exactly the unregistered locale the gate refuses, and
|
|
372
348
|
// this is the command its `fix:` names. Re-deriving an index that is already correct writes the
|
|
@@ -389,7 +365,7 @@ async function runSync(root: string, ctx: CommandContext): Promise<CommandResult
|
|
|
389
365
|
from: from ?? locale,
|
|
390
366
|
added,
|
|
391
367
|
total,
|
|
392
|
-
path:
|
|
368
|
+
path: catalogLocation(layout, locale),
|
|
393
369
|
registered,
|
|
394
370
|
// Which of `added` still need a human: every one but an admin label in the default locale.
|
|
395
371
|
// `⟦key⟧` where there was no catalog to copy from, `⟦<default string>⟧` on a real merge —
|
|
@@ -410,6 +386,10 @@ export const i18nCommand: CliCommand = {
|
|
|
410
386
|
const sub = ctx.args.subcommand ?? 'check';
|
|
411
387
|
if (sub === 'add') return runAdd(root, ctx);
|
|
412
388
|
if (sub === 'sync') return runSync(root, ctx);
|
|
389
|
+
if (sub === 'split') {
|
|
390
|
+
const named = ctx.args.positionals[0] === undefined ? undefined : resolveOneLocale(ctx, sub);
|
|
391
|
+
return runSplit(root, named);
|
|
392
|
+
}
|
|
413
393
|
return runCheck(root);
|
|
414
394
|
},
|
|
415
395
|
};
|
package/src/config-redact.ts
CHANGED
|
@@ -1,13 +1,29 @@
|
|
|
1
1
|
// The resolved `AppConfig` as JSON an operator may paste into an issue: every credential-named key
|
|
2
|
-
// and every `secret()` value replaced, a URL's password cut out of its userinfo
|
|
3
|
-
//
|
|
2
|
+
// and every `secret()` value replaced, a URL's password cut out of its userinfo — a `proxy` URL's
|
|
3
|
+
// whole userinfo. The rules are core's (`isRedactedKey`, `redactUrlPassword`, `replaceUrlUserinfo`).
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
isRedactedKey,
|
|
7
|
+
isSecret,
|
|
8
|
+
REDACTED,
|
|
9
|
+
redactUrlPassword,
|
|
10
|
+
replaceUrlUserinfo,
|
|
11
|
+
} from '@ultimat3/core';
|
|
6
12
|
import type { JsonValue } from './output';
|
|
7
13
|
|
|
8
14
|
/** Past this depth a config is not data an operator wrote; the walk stops rather than recurse. */
|
|
9
15
|
const MAX_DEPTH = 16;
|
|
10
16
|
|
|
17
|
+
/**
|
|
18
|
+
* A proxy URL carries its credential in the USER as often as the password (`http://sk-token@egress`),
|
|
19
|
+
* so `outbound.proxy` — any `proxy` key — loses the whole userinfo, as core's boot line shows it.
|
|
20
|
+
*/
|
|
21
|
+
const redactedEntry = (key: string, item: unknown, depth: number): JsonValue => {
|
|
22
|
+
if (isRedactedKey(key)) return REDACTED;
|
|
23
|
+
if (key === 'proxy' && typeof item === 'string') return replaceUrlUserinfo(item, () => REDACTED);
|
|
24
|
+
return redactConfigValue(item, depth + 1);
|
|
25
|
+
};
|
|
26
|
+
|
|
11
27
|
export function redactConfigValue(value: unknown, depth = 0): JsonValue {
|
|
12
28
|
if (isSecret(value)) return REDACTED;
|
|
13
29
|
if (value === null || value === undefined) return null;
|
|
@@ -26,7 +42,7 @@ export function redactConfigValue(value: unknown, depth = 0): JsonValue {
|
|
|
26
42
|
// `defineProperty`, never `out[key] =`: a config key is the app's string, and `__proto__`
|
|
27
43
|
// assigned would re-prototype the record instead of adding a field.
|
|
28
44
|
Object.defineProperty(out, key, {
|
|
29
|
-
value:
|
|
45
|
+
value: redactedEntry(key, item, depth),
|
|
30
46
|
enumerable: true,
|
|
31
47
|
writable: true,
|
|
32
48
|
configurable: true,
|
package/src/db-rollback-pass.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// beside a live `x dev` holding the embedded database — that process, asked over `/_x`
|
|
3
3
|
// (`dev-db-rollback.ts`). The rule `db-migrate-pass.ts` states: PGlite takes one opener.
|
|
4
4
|
|
|
5
|
+
import type { DbClient } from '@ultimat3/db';
|
|
5
6
|
import { rollback } from '@ultimat3/db';
|
|
6
7
|
import { t } from '@ultimat3/schema';
|
|
7
8
|
import { DEV_ROLLBACK_PATH } from './db-dev-wire';
|
|
@@ -19,17 +20,19 @@ const REVERTED = t.object({ reverted: t.array(t.string) });
|
|
|
19
20
|
/**
|
|
20
21
|
* `rollback()` over the ambient client, with this command's two questions asked under the lock.
|
|
21
22
|
* Shared by the command and the dev route, so the holder cannot reverse what the command refuses.
|
|
23
|
+
* `on` is the dev route's held session (`dev-db-migrator-hold.ts`): its client, and no second lock.
|
|
22
24
|
*/
|
|
23
25
|
export async function reverseApplied(
|
|
24
26
|
root: string,
|
|
25
27
|
env: Env,
|
|
26
28
|
steps: number,
|
|
29
|
+
on: { readonly client?: DbClient; readonly lock?: boolean } = {},
|
|
27
30
|
): Promise<readonly string[]> {
|
|
28
31
|
const migrations = await readMigrations(root);
|
|
29
32
|
// The binding, so a database on another machine needs the names whatever the environment says.
|
|
30
33
|
const database = resolveServices(root, env).db;
|
|
31
34
|
const confirm = rollbackConfirm(await withoutDown(root, migrations), env, steps, database);
|
|
32
|
-
return rollback({ migrations, steps, confirm });
|
|
35
|
+
return rollback({ migrations, steps, confirm, client: on.client, lock: on.lock });
|
|
33
36
|
}
|
|
34
37
|
|
|
35
38
|
/** The ids reversed, most recently applied first. */
|
package/src/dev-child-watch.ts
CHANGED
|
@@ -153,6 +153,22 @@ export function hardExit(
|
|
|
153
153
|
};
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
+
/**
|
|
157
|
+
* A stop this process begins on its own because serving on is unsafe — the embedded session that
|
|
158
|
+
* could not be made `x_app` again after a migrate pass (`dev-db-migrator-hold.ts`). Its own hard
|
|
159
|
+
* exit, since an unsupervised `x dev` starts no watch: that drain meets a database whose turn is
|
|
160
|
+
* never given back, and a hook waiting on it must not keep the process. Exit 1 if it comes to that.
|
|
161
|
+
*/
|
|
162
|
+
export function stopDevServing(
|
|
163
|
+
signal: string,
|
|
164
|
+
exit: (code: number) => void = (code) => process.exit(code),
|
|
165
|
+
begin: (signal: string) => Promise<void> = drain,
|
|
166
|
+
afterMs: () => number = devHardExitMs,
|
|
167
|
+
): void {
|
|
168
|
+
hardExit(exit, afterMs)(1);
|
|
169
|
+
void begin(signal);
|
|
170
|
+
}
|
|
171
|
+
|
|
156
172
|
/** What the supervisor sends for a stop: the signal it would have forwarded on POSIX. */
|
|
157
173
|
export interface DevDrainMessage {
|
|
158
174
|
readonly type: 'x-dev-drain';
|
package/src/dev-db-migrate.ts
CHANGED
|
@@ -3,26 +3,25 @@
|
|
|
3
3
|
// so the command asks the holder instead of opening `.x/pgdata` a second time. Loopback Host and
|
|
4
4
|
// peer, same-origin: the `/_x/db` doors.
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { renderThrowable, UltimateError } from '@ultimat3/core';
|
|
7
7
|
import type { DriftDifference } from '@ultimat3/db';
|
|
8
|
-
import { checkDrift,
|
|
8
|
+
import { checkDrift, migrate } from '@ultimat3/db';
|
|
9
9
|
import type { CatalogDescription } from '@ultimat3/db/schema-dump';
|
|
10
10
|
import { introspectCatalog } from '@ultimat3/db/schema-dump';
|
|
11
11
|
import type { Route, UltimateRequest } from '@ultimat3/http';
|
|
12
12
|
import { jsonResponse } from '@ultimat3/http';
|
|
13
|
-
import { loadAppConfig } from './app-config-load';
|
|
14
13
|
import { acceptCreatedTables } from './db-accept-created';
|
|
15
14
|
import { DEV_LEDGER_PATH, DEV_MIGRATE_PATH, DEV_ROLLBACK_PATH } from './db-dev-wire';
|
|
16
15
|
import { frameworkStorageDrift } from './db-object-drift';
|
|
17
16
|
import { assertSameOrigin, hostRefusal } from './dev-dashboard-guard';
|
|
17
|
+
import { devMigratorPass } from './dev-db-migrator-hold';
|
|
18
18
|
import { ledgerInDev, rollbackInDev, stepsOf } from './dev-db-rollback';
|
|
19
19
|
import { ledgerMoved } from './dev-db-settled';
|
|
20
20
|
import { readMigrations } from './migrations';
|
|
21
|
-
import { rowSecurityDeclared } from './row-security-boot';
|
|
22
21
|
import { stopRunStartFix } from './stop-run-start';
|
|
23
22
|
|
|
24
23
|
/** The command that works when this process cannot apply: the embedded database to itself. */
|
|
25
|
-
|
|
24
|
+
const MIGRATE_ALONE_FIX = stopRunStartFix(['db', 'migrate']);
|
|
26
25
|
|
|
27
26
|
/** One applied pass as it crosses the wire: `runMigrations`' report, and the live catalog. */
|
|
28
27
|
export interface DevMigrateData {
|
|
@@ -38,50 +37,36 @@ export interface DevMigrateData {
|
|
|
38
37
|
|
|
39
38
|
type Env = Readonly<Record<string, string | undefined>>;
|
|
40
39
|
|
|
41
|
-
/**
|
|
42
|
-
* With `database.rowSecurity`, this process serves as `x_app` and a migration must run as
|
|
43
|
-
* `x_migrator` from the bootstrap session — one embedded session cannot be both while it serves.
|
|
44
|
-
*/
|
|
45
|
-
export async function devCanMigrate(root: string): Promise<boolean> {
|
|
46
|
-
return !rowSecurityDeclared(await loadAppConfig(root));
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** Refused where this process serves as `x_app`; `fix` is the command run alone, start to start. */
|
|
50
|
-
async function assertDevCanMigrate(root: string, fix: string): Promise<void> {
|
|
51
|
-
if (await devCanMigrate(root)) return;
|
|
52
|
-
throw new NotImplementedError({
|
|
53
|
-
cause:
|
|
54
|
-
'this x dev serves the embedded database as x_app (database.rowSecurity), and migrations run as x_migrator — one embedded session cannot hold both',
|
|
55
|
-
fix,
|
|
56
|
-
});
|
|
57
|
-
}
|
|
58
|
-
|
|
59
40
|
/**
|
|
60
41
|
* `serve.ts`'s `runMigrations` over the client this process already holds: the same file list,
|
|
61
42
|
* the same ledger, the same post-condition. No boot and no `stop()` — the database is `x dev`'s.
|
|
43
|
+
* Where it serves as `x_app`, the whole pass is one hold of the session (`devMigratorPass`).
|
|
62
44
|
*/
|
|
63
45
|
export async function migrateInDev(root: string, env: Env): Promise<DevMigrateData> {
|
|
64
|
-
await assertDevCanMigrate(root, MIGRATE_ALONE_FIX);
|
|
65
46
|
const migrations = await readMigrations(root);
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
47
|
+
return devMigratorPass(root, env, async ({ client, lock, bootstrap }) => {
|
|
48
|
+
const report = await migrate({
|
|
49
|
+
migrations,
|
|
50
|
+
client,
|
|
51
|
+
lock,
|
|
52
|
+
...(env['APP_VERSION'] === undefined ? {} : { appVersion: env['APP_VERSION'] }),
|
|
53
|
+
});
|
|
54
|
+
// As `runMigrations` reads them: after the migrate step, as the bootstrap user. One at a
|
|
55
|
+
// time — under the hold they share one session with no turn queue between them.
|
|
56
|
+
await bootstrap();
|
|
57
|
+
const drift = acceptCreatedTables(await checkDrift({ migrations, client }), migrations);
|
|
58
|
+
const catalog = await introspectCatalog({ client });
|
|
59
|
+
const storage = await frameworkStorageDrift(client);
|
|
60
|
+
return {
|
|
61
|
+
applied: report.applied.map((entry) => entry.id),
|
|
62
|
+
skipped: report.skipped.length,
|
|
63
|
+
appVersion: report.appVersion,
|
|
64
|
+
durationMs: report.durationMs,
|
|
65
|
+
drift: drift.differences,
|
|
66
|
+
catalog,
|
|
67
|
+
storage,
|
|
68
|
+
};
|
|
69
69
|
});
|
|
70
|
-
const drift = acceptCreatedTables(await checkDrift({ migrations }), migrations);
|
|
71
|
-
const client = db();
|
|
72
|
-
const [catalog, storage] = await Promise.all([
|
|
73
|
-
introspectCatalog({ client }),
|
|
74
|
-
frameworkStorageDrift(client),
|
|
75
|
-
]);
|
|
76
|
-
return {
|
|
77
|
-
applied: report.applied.map((entry) => entry.id),
|
|
78
|
-
skipped: report.skipped.length,
|
|
79
|
-
appVersion: report.appVersion,
|
|
80
|
-
durationMs: report.durationMs,
|
|
81
|
-
drift: drift.differences,
|
|
82
|
-
catalog,
|
|
83
|
-
storage,
|
|
84
|
-
};
|
|
85
70
|
}
|
|
86
71
|
|
|
87
72
|
/** The refusal as the command re-throws it: the code, cause and fix of whatever stopped the pass. */
|
|
@@ -143,10 +128,6 @@ export function devMigrateRoutes(input: DevMigrateRouteInput): readonly Route[]
|
|
|
143
128
|
),
|
|
144
129
|
door(input, DEV_ROLLBACK_PATH, 'dev._x.db.rollback', async (request) => {
|
|
145
130
|
const steps = stepsOf(request.url.searchParams.get('steps'));
|
|
146
|
-
await assertDevCanMigrate(
|
|
147
|
-
root,
|
|
148
|
-
stopRunStartFix(['db', 'rollback', '--steps', String(steps)]),
|
|
149
|
-
);
|
|
150
131
|
return rollbackInDev(root, env, steps).finally(ledgerMoved);
|
|
151
132
|
}),
|
|
152
133
|
// A read, behind the same doors and the same verb: nothing under `/_x/db` answers a GET.
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// A migrate or rollback pass inside a live `x dev` whose embedded session serves as `x_app`
|
|
2
|
+
// (`database.rowSecurity`): the one PGlite session is taken exclusively, becomes `x_migrator` for
|
|
3
|
+
// the pass, and serves as `x_app` again before any other statement runs — or never serves again.
|
|
4
|
+
|
|
5
|
+
import { logger, renderThrowable } from '@ultimat3/core';
|
|
6
|
+
import type { DbClient } from '@ultimat3/db';
|
|
7
|
+
import {
|
|
8
|
+
assertRowSecurityBinds,
|
|
9
|
+
baseClient,
|
|
10
|
+
DbError,
|
|
11
|
+
db,
|
|
12
|
+
holdMigratorRole,
|
|
13
|
+
isReservable,
|
|
14
|
+
raw,
|
|
15
|
+
serveAsAppRole,
|
|
16
|
+
} from '@ultimat3/db';
|
|
17
|
+
import { loadAppConfig } from './app-config-load';
|
|
18
|
+
import { stopDevServing } from './dev-child-watch';
|
|
19
|
+
import { rowSecurityDeclared } from './row-security-boot';
|
|
20
|
+
import { resolveServices } from './runtime-bindings';
|
|
21
|
+
import { stopRunStartFix } from './stop-run-start';
|
|
22
|
+
|
|
23
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
24
|
+
|
|
25
|
+
/** What a pass runs on. Every statement of the pass goes to `client`, never to the ambient one. */
|
|
26
|
+
export interface MigratorPass {
|
|
27
|
+
readonly client: DbClient;
|
|
28
|
+
/**
|
|
29
|
+
* `migrate()`/`rollback()`'s `lock`. `false` under the hold: the advisory lock would reserve the
|
|
30
|
+
* session a second time and wait for the turn this pass is holding, and the hold already is the
|
|
31
|
+
* exclusion — PGlite has one session and one opener.
|
|
32
|
+
*/
|
|
33
|
+
readonly lock: boolean;
|
|
34
|
+
/** `reset role`: the reads `x db migrate` alone makes after its migrate step, as the bootstrap user. */
|
|
35
|
+
readonly bootstrap: () => Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface MigratorHoldSeams {
|
|
39
|
+
/** The client whose session is held. Defaults to the ambient one. */
|
|
40
|
+
readonly client?: DbClient | undefined;
|
|
41
|
+
/** Run once when the session could not be made `x_app` again. Defaults to `stopDevServing`. */
|
|
42
|
+
readonly stopServing?: (() => void) | undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** After the turn that will never be released: start again, and the boot arms the roles afresh. */
|
|
46
|
+
const RESTART_FIX = 'x stop --json && x dev';
|
|
47
|
+
|
|
48
|
+
const roleLost = (error: unknown): DbError =>
|
|
49
|
+
new DbError({
|
|
50
|
+
code: 'X_DB_ROW_SECURITY_BYPASSED',
|
|
51
|
+
cause: `x dev ran a migrate pass as x_migrator and could not serve as x_app again (${renderThrowable(error)}), so it stopped serving: no statement reaches the embedded session, whose role is no longer one row security binds`,
|
|
52
|
+
fix: RESTART_FIX,
|
|
53
|
+
sourceError: error,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Back to what the boot armed (`armRowSecurity`), judged again. `rollback` first: a pass that died
|
|
58
|
+
* inside a transaction would otherwise take the `set role` below with it at that transaction's end
|
|
59
|
+
* — and outside a transaction it is a warning, not an error.
|
|
60
|
+
*/
|
|
61
|
+
async function serveAgain(session: DbClient): Promise<void> {
|
|
62
|
+
await session.execute(raw('rollback'));
|
|
63
|
+
await session.execute(raw('reset role'));
|
|
64
|
+
await serveAsAppRole(session);
|
|
65
|
+
await assertRowSecurityBinds(session);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* `run` as `x_migrator` on the reserved session. PGlite's `reserve()` holds its turn queue, so a
|
|
70
|
+
* request's statement issued meanwhile waits and then runs as `x_app`: nothing but the pass ever
|
|
71
|
+
* sees the migrator or the bootstrap superuser. The turn is given back only once the session is
|
|
72
|
+
* `x_app` and bound by row security again; otherwise it is kept for the life of the process —
|
|
73
|
+
* every later statement waits rather than reading every tenant's rows — and `stopServing` runs.
|
|
74
|
+
*/
|
|
75
|
+
export async function withMigratorHold<T>(
|
|
76
|
+
run: (pass: MigratorPass) => Promise<T>,
|
|
77
|
+
seams: MigratorHoldSeams = {},
|
|
78
|
+
): Promise<T> {
|
|
79
|
+
const client = seams.client ?? baseClient();
|
|
80
|
+
if (!isReservable(client)) {
|
|
81
|
+
throw new DbError({
|
|
82
|
+
code: 'X_DB_ROW_SECURITY_BYPASSED',
|
|
83
|
+
cause:
|
|
84
|
+
'x dev serves the embedded database as x_app and its client cannot reserve the session, so a pass as x_migrator would run beside the requests it serves',
|
|
85
|
+
fix: stopRunStartFix(['db', 'migrate']),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
const session = await client.reserve();
|
|
89
|
+
let outcome: { readonly value: T } | { readonly error: unknown };
|
|
90
|
+
try {
|
|
91
|
+
await session.execute(raw('reset role'));
|
|
92
|
+
await holdMigratorRole(session);
|
|
93
|
+
const value = await run({
|
|
94
|
+
client: session,
|
|
95
|
+
lock: false,
|
|
96
|
+
bootstrap: async () => {
|
|
97
|
+
await session.execute(raw('reset role'));
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
outcome = { value };
|
|
101
|
+
} catch (error) {
|
|
102
|
+
outcome = { error };
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
await serveAgain(session);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
// No `session.release()`: the turn is the only thing between a request and a superuser.
|
|
108
|
+
const lost = roleLost(error);
|
|
109
|
+
logger.error(lost.code, { code: lost.code, cause: lost.cause, fix: lost.fix });
|
|
110
|
+
(seams.stopServing ?? (() => stopDevServing('row-security-lost')))();
|
|
111
|
+
throw lost;
|
|
112
|
+
}
|
|
113
|
+
session.release();
|
|
114
|
+
if ('error' in outcome) throw outcome.error;
|
|
115
|
+
return outcome.value;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A pass run by this `x dev`. Held only where the roles are ours and the session is one — the
|
|
120
|
+
* embedded database with `database.rowSecurity`. Anywhere else it is the ambient client under the
|
|
121
|
+
* migrate lock: an external database's migrator is whoever `DATABASE_URL` connects as.
|
|
122
|
+
*/
|
|
123
|
+
export async function devMigratorPass<T>(
|
|
124
|
+
root: string,
|
|
125
|
+
env: Env,
|
|
126
|
+
run: (pass: MigratorPass) => Promise<T>,
|
|
127
|
+
): Promise<T> {
|
|
128
|
+
const embedded = resolveServices(root, env).db.mode === 'embedded';
|
|
129
|
+
if (embedded && rowSecurityDeclared(await loadAppConfig(root))) return withMigratorHold(run);
|
|
130
|
+
return run({ client: db(), lock: true, bootstrap: async () => undefined });
|
|
131
|
+
}
|
package/src/dev-db-rollback.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { db, isLedgerMissing, readLedger } from '@ultimat3/db';
|
|
6
6
|
import { ROLLBACK_STEPS } from './db-dev-wire';
|
|
7
7
|
import { reverseApplied } from './db-rollback-pass';
|
|
8
|
+
import { devMigratorPass } from './dev-db-migrator-hold';
|
|
8
9
|
import { parseIntFlag } from './flag-number';
|
|
9
10
|
|
|
10
11
|
type Env = Readonly<Record<string, string | undefined>>;
|
|
@@ -12,13 +13,21 @@ type Env = Readonly<Record<string, string | undefined>>;
|
|
|
12
13
|
/** `?steps=n`, through the command's own reader: the door refuses what the flag refuses. */
|
|
13
14
|
export const stepsOf = (raw: string | null): number => parseIntFlag(raw ?? '', ROLLBACK_STEPS);
|
|
14
15
|
|
|
15
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* `rollback()` over the client this process already holds, with the command's own two refusals.
|
|
18
|
+
* Where it serves as `x_app`, the reversal runs as `x_migrator` under the same hold a migrate
|
|
19
|
+
* pass takes (`dev-db-migrator-hold.ts`).
|
|
20
|
+
*/
|
|
16
21
|
export async function rollbackInDev(
|
|
17
22
|
root: string,
|
|
18
23
|
env: Env,
|
|
19
24
|
steps: number,
|
|
20
25
|
): Promise<{ readonly reverted: readonly string[] }> {
|
|
21
|
-
return {
|
|
26
|
+
return {
|
|
27
|
+
reverted: await devMigratorPass(root, env, ({ client, lock }) =>
|
|
28
|
+
reverseApplied(root, env, steps, { client, lock }),
|
|
29
|
+
),
|
|
30
|
+
};
|
|
22
31
|
}
|
|
23
32
|
|
|
24
33
|
/** Each applied migration's id and the checksum it was applied with; no ledger is no rows. */
|
|
@@ -6,27 +6,18 @@ import type { Migration } from '@ultimat3/db';
|
|
|
6
6
|
import { db, dbClientInstalled, isLedgerMissing, readLedger } from '@ultimat3/db';
|
|
7
7
|
import { AppMigrationsUnappliedError } from './app-migrations-verdict';
|
|
8
8
|
import { type AppliedRow, refuseEdited } from './db-applied-edits';
|
|
9
|
-
import { devCanMigrate, MIGRATE_ALONE_FIX } from './dev-db-migrate';
|
|
10
9
|
import { checkSourceDrift } from './drift';
|
|
11
10
|
import { readMigrations } from './migrations';
|
|
12
11
|
import type { Finding } from './output';
|
|
13
12
|
import { findingFrom } from './output';
|
|
14
|
-
import { resolveServices } from './runtime-bindings';
|
|
15
13
|
|
|
16
14
|
/**
|
|
17
15
|
* The migrate half too: `x dev` applies no migration unasked, so `x db gen` alone leaves the page
|
|
18
|
-
* red. Beside this process `x db migrate` is applied BY it (`dev-db-migrate.ts`), embedded or not
|
|
16
|
+
* red. Beside this process `x db migrate` is applied BY it (`dev-db-migrate.ts`), embedded or not,
|
|
17
|
+
* and with `database.rowSecurity` as `x_migrator` under a hold (`dev-db-migrator-hold.ts`).
|
|
19
18
|
*/
|
|
20
19
|
export const SCHEMA_AHEAD_FIX = 'x db gen "describe the change" && x db migrate';
|
|
21
20
|
|
|
22
|
-
/** Where this process cannot apply the pass itself: the embedded database, to the command alone. */
|
|
23
|
-
export const SCHEMA_AHEAD_FIX_ALONE = `x db gen "describe the change" && ${MIGRATE_ALONE_FIX}`;
|
|
24
|
-
|
|
25
|
-
/** Whether `x db migrate` works while this `x dev` runs: any external database, or a pass it takes. */
|
|
26
|
-
export async function migratesBesideDev(root: string): Promise<boolean> {
|
|
27
|
-
return resolveServices(root, Bun.env).db.mode !== 'embedded' || (await devCanMigrate(root));
|
|
28
|
-
}
|
|
29
|
-
|
|
30
21
|
/** What `ledgerFindings` asks — the seam a test hands rows through. */
|
|
31
22
|
export interface LedgerReads {
|
|
32
23
|
readonly migrations: (root: string) => Promise<readonly Migration[]>;
|
|
@@ -62,7 +53,6 @@ const READS: LedgerReads = {
|
|
|
62
53
|
*/
|
|
63
54
|
export async function ledgerFindings(
|
|
64
55
|
root: string,
|
|
65
|
-
beside: (root: string) => Promise<boolean> = migratesBesideDev,
|
|
66
56
|
reads: LedgerReads = READS,
|
|
67
57
|
): Promise<readonly Finding[]> {
|
|
68
58
|
const migrations = await reads.migrations(root);
|
|
@@ -72,10 +62,9 @@ export async function ledgerFindings(
|
|
|
72
62
|
const missing = migrations.map((migration) => migration.id).filter((id) => !applied.has(id));
|
|
73
63
|
const findings: Finding[] = [];
|
|
74
64
|
if (missing.length > 0) {
|
|
75
|
-
|
|
76
|
-
new AppMigrationsUnappliedError({ missing, ledger: ledger !== undefined }),
|
|
65
|
+
findings.push(
|
|
66
|
+
findingFrom(new AppMigrationsUnappliedError({ missing, ledger: ledger !== undefined })),
|
|
77
67
|
);
|
|
78
|
-
findings.push((await beside(root)) ? behind : { ...behind, fix: MIGRATE_ALONE_FIX });
|
|
79
68
|
}
|
|
80
69
|
try {
|
|
81
70
|
refuseEdited(ledger ?? [], migrations);
|
|
@@ -109,23 +98,17 @@ function marked(findings: readonly Finding[]): readonly Finding[] {
|
|
|
109
98
|
export async function schemaAheadFindings(
|
|
110
99
|
root: string,
|
|
111
100
|
check: (root: string) => Promise<readonly Finding[]> = checkSourceDrift,
|
|
112
|
-
|
|
113
|
-
ledger: (
|
|
114
|
-
root: string,
|
|
115
|
-
beside: (root: string) => Promise<boolean>,
|
|
116
|
-
) => Promise<readonly Finding[]> = ledgerFindings,
|
|
101
|
+
ledger: (root: string) => Promise<readonly Finding[]> = ledgerFindings,
|
|
117
102
|
): Promise<readonly Finding[]> {
|
|
118
103
|
try {
|
|
119
104
|
const drifted = await check(root);
|
|
120
|
-
const fix =
|
|
121
|
-
drifted.length === 0 || (await beside(root)) ? SCHEMA_AHEAD_FIX : SCHEMA_AHEAD_FIX_ALONE;
|
|
122
105
|
return marked([
|
|
123
106
|
...drifted.map((finding) => ({
|
|
124
107
|
...finding,
|
|
125
108
|
cause: `entities are ahead of the migrations: ${finding.cause}`,
|
|
126
|
-
fix,
|
|
109
|
+
fix: SCHEMA_AHEAD_FIX,
|
|
127
110
|
})),
|
|
128
|
-
...(await ledger(root
|
|
111
|
+
...(await ledger(root)),
|
|
129
112
|
]);
|
|
130
113
|
} catch (error) {
|
|
131
114
|
return marked([findingFrom(error)]);
|