@quickback-dev/cli 0.60.4 → 0.60.6
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/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +89 -13
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/compile.test.js +52 -5
- package/dist/commands/compile.test.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/lib/api-client.d.ts +15 -0
- package/dist/lib/api-client.d.ts.map +1 -1
- package/dist/lib/api-client.js.map +1 -1
- package/dist/lib/file-loader-typescript-fallback.test.d.ts +2 -0
- package/dist/lib/file-loader-typescript-fallback.test.d.ts.map +1 -0
- package/dist/lib/file-loader-typescript-fallback.test.js +58 -0
- package/dist/lib/file-loader-typescript-fallback.test.js.map +1 -0
- package/dist/lib/file-loader.d.ts +17 -0
- package/dist/lib/file-loader.d.ts.map +1 -1
- package/dist/lib/file-loader.js +64 -12
- package/dist/lib/file-loader.js.map +1 -1
- package/dist/lib/migrations/commit.d.ts +38 -0
- package/dist/lib/migrations/commit.d.ts.map +1 -0
- package/dist/lib/migrations/commit.js +39 -0
- package/dist/lib/migrations/commit.js.map +1 -0
- package/dist/lib/migrations/drizzle-prompts.d.ts +97 -0
- package/dist/lib/migrations/drizzle-prompts.d.ts.map +1 -0
- package/dist/lib/migrations/drizzle-prompts.js +190 -0
- package/dist/lib/migrations/drizzle-prompts.js.map +1 -0
- package/dist/lib/migrations/drizzle-prompts.test.d.ts +2 -0
- package/dist/lib/migrations/drizzle-prompts.test.d.ts.map +1 -0
- package/dist/lib/migrations/drizzle-prompts.test.js +135 -0
- package/dist/lib/migrations/drizzle-prompts.test.js.map +1 -0
- package/dist/lib/migrations/drizzle-wrapper.d.ts +28 -0
- package/dist/lib/migrations/drizzle-wrapper.d.ts.map +1 -0
- package/dist/lib/migrations/drizzle-wrapper.js +63 -0
- package/dist/lib/migrations/drizzle-wrapper.js.map +1 -0
- package/dist/lib/migrations/executor.d.ts +4 -1
- package/dist/lib/migrations/executor.d.ts.map +1 -1
- package/dist/lib/migrations/executor.js +0 -6
- package/dist/lib/migrations/executor.js.map +1 -1
- package/dist/lib/migrations/file-envelopes.d.ts +42 -0
- package/dist/lib/migrations/file-envelopes.d.ts.map +1 -0
- package/dist/lib/migrations/file-envelopes.js +255 -0
- package/dist/lib/migrations/file-envelopes.js.map +1 -0
- package/dist/lib/migrations/postprocessors/audit-migration-hardening.d.ts +29 -0
- package/dist/lib/migrations/postprocessors/audit-migration-hardening.d.ts.map +1 -0
- package/dist/lib/migrations/postprocessors/audit-migration-hardening.js +67 -0
- package/dist/lib/migrations/postprocessors/audit-migration-hardening.js.map +1 -0
- package/dist/lib/migrations/postprocessors/index.d.ts +58 -0
- package/dist/lib/migrations/postprocessors/index.d.ts.map +1 -0
- package/dist/lib/migrations/postprocessors/index.js +344 -0
- package/dist/lib/migrations/postprocessors/index.js.map +1 -0
- package/dist/lib/migrations/postprocessors/index.test.d.ts +2 -0
- package/dist/lib/migrations/postprocessors/index.test.d.ts.map +1 -0
- package/dist/lib/migrations/postprocessors/index.test.js +298 -0
- package/dist/lib/migrations/postprocessors/index.test.js.map +1 -0
- package/dist/lib/migrations/postprocessors/migration-reorder.d.ts +39 -0
- package/dist/lib/migrations/postprocessors/migration-reorder.d.ts.map +1 -0
- package/dist/lib/migrations/postprocessors/migration-reorder.js +185 -0
- package/dist/lib/migrations/postprocessors/migration-reorder.js.map +1 -0
- package/dist/lib/migrations/postprocessors/trigger-sql.d.ts +51 -0
- package/dist/lib/migrations/postprocessors/trigger-sql.d.ts.map +1 -0
- package/dist/lib/migrations/postprocessors/trigger-sql.js +62 -0
- package/dist/lib/migrations/postprocessors/trigger-sql.js.map +1 -0
- package/dist/lib/migrations/prior-state.d.ts +63 -0
- package/dist/lib/migrations/prior-state.d.ts.map +1 -0
- package/dist/lib/migrations/prior-state.js +141 -0
- package/dist/lib/migrations/prior-state.js.map +1 -0
- package/dist/lib/migrations/prompt-runner.d.ts +32 -0
- package/dist/lib/migrations/prompt-runner.d.ts.map +1 -0
- package/dist/lib/migrations/prompt-runner.js +158 -0
- package/dist/lib/migrations/prompt-runner.js.map +1 -0
- package/dist/lib/migrations/prompt-runner.test.d.ts +2 -0
- package/dist/lib/migrations/prompt-runner.test.d.ts.map +1 -0
- package/dist/lib/migrations/prompt-runner.test.js +131 -0
- package/dist/lib/migrations/prompt-runner.test.js.map +1 -0
- package/dist/lib/migrations/schema-contract.d.ts +44 -0
- package/dist/lib/migrations/schema-contract.d.ts.map +1 -0
- package/dist/lib/migrations/schema-contract.js +51 -0
- package/dist/lib/migrations/schema-contract.js.map +1 -0
- package/dist/skill/docs/api/errors.md +1 -0
- package/dist/skill/docs/configure/domains.md +84 -0
- package/dist/skill/docs/define/firewall.md +1 -0
- package/dist/skill/docs/define/masking.md +16 -1
- package/dist/skill/docs/define/relationships.md +35 -0
- package/dist/skill/docs/define/schema.md +20 -0
- package/dist/skill/docs/platform/database/d1.md +14 -0
- package/dist/skill/docs/platform/database/neon.md +12 -5
- package/dist/skill/docs/start/deploy-browser.md +3 -0
- package/dist/skill/docs/tooling/cli.md +15 -0
- package/dist/skill/docs/tooling/output.md +28 -10
- package/package.json +2 -2
- package/src/skill/docs/api/errors.md +1 -0
- package/src/skill/docs/configure/domains.md +84 -0
- package/src/skill/docs/define/firewall.md +1 -0
- package/src/skill/docs/define/masking.md +16 -1
- package/src/skill/docs/define/relationships.md +35 -0
- package/src/skill/docs/define/schema.md +20 -0
- package/src/skill/docs/platform/database/d1.md +14 -0
- package/src/skill/docs/platform/database/neon.md +12 -5
- package/src/skill/docs/start/deploy-browser.md +3 -0
- package/src/skill/docs/tooling/cli.md +15 -0
- package/src/skill/docs/tooling/output.md +28 -10
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-runner.d.ts","sourceRoot":"","sources":["../../../src/lib/migrations/prompt-runner.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAoC,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAI3F,MAAM,WAAW,wBAAwB;IACvC,oEAAoE;IACpE,WAAW,EAAE,MAAM,CAAC;IACpB,kDAAkD;IAClD,GAAG,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACjC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,wBAAwB,GAChC,sBAAsB,CAUxB"}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { runMigrationCommand } from './command-runner.js';
|
|
6
|
+
import { DRIZZLE_GENERATE_WRAPPER_FILENAME, buildDrizzleGenerateWrapper, } from './drizzle-wrapper.js';
|
|
7
|
+
import { KEYSTROKE_ACCEPT_CREATE, drizzlePromptKey, extractLatestDrizzlePrompt, formatDrizzlePromptError, isDrizzleTtyAbort, keystrokesForOption, resolvePromptWithHints, } from './drizzle-prompts.js';
|
|
8
|
+
import { MigrationExecutorError } from './errors.js';
|
|
9
|
+
const MAX_CAPTURE_BYTES = 256 * 1024;
|
|
10
|
+
/**
|
|
11
|
+
* A migration command runner that can answer drizzle-kit's create-or-rename
|
|
12
|
+
* prompt.
|
|
13
|
+
*
|
|
14
|
+
* ── The two-attempt strategy ─────────────────────────────────────────────
|
|
15
|
+
*
|
|
16
|
+
* 1. Run drizzle-kit normally. Fast and clean for the common additive diff,
|
|
17
|
+
* which has no prompt at all. We deliberately do NOT fake a TTY here:
|
|
18
|
+
* under a TTY drizzle renders interactive spinners that never settle in a
|
|
19
|
+
* non-real terminal, so faking it unconditionally would hang the common
|
|
20
|
+
* case to serve the rare one.
|
|
21
|
+
*
|
|
22
|
+
* 2. Only if drizzle aborted on its non-TTY create/rename resolver, retry
|
|
23
|
+
* through the fake-TTY wrapper so the prompt actually renders and
|
|
24
|
+
* keystrokes can answer it.
|
|
25
|
+
*
|
|
26
|
+
* CRITICAL: drizzle-kit 0.31 prints "Interactive prompts require a TTY" on
|
|
27
|
+
* stderr and then EXITS 0. The retry must key off that message, never off a
|
|
28
|
+
* non-zero exit code. Gating on failure is a bug that already shipped
|
|
29
|
+
* compiler-side once (see run-compilation.ts) and silently skipped generation
|
|
30
|
+
* for every add+drop diff — a compile that looks successful and produces no
|
|
31
|
+
* migration.
|
|
32
|
+
*/
|
|
33
|
+
export function createPromptAwareMigrationRunner(options) {
|
|
34
|
+
return async (invocation) => {
|
|
35
|
+
const first = await runMigrationCommand(invocation);
|
|
36
|
+
if (!isDrizzleTtyAbort(first.stdout, first.stderr))
|
|
37
|
+
return first;
|
|
38
|
+
options.log?.('drizzle-kit hit its non-TTY rename resolver; retrying via fake-TTY wrapper...');
|
|
39
|
+
return await runThroughWrapper(invocation, options);
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
async function runThroughWrapper(invocation, options) {
|
|
43
|
+
// The wrapper lives outside the project so it can never be mistaken for
|
|
44
|
+
// project source or land in the migration tree the executor inventories.
|
|
45
|
+
const wrapperDir = await mkdtemp(join(tmpdir(), 'qb-drizzle-wrapper-'));
|
|
46
|
+
const wrapperPath = join(wrapperDir, DRIZZLE_GENERATE_WRAPPER_FILENAME);
|
|
47
|
+
await writeFile(wrapperPath, buildDrizzleGenerateWrapper(options.projectRoot), 'utf-8');
|
|
48
|
+
try {
|
|
49
|
+
return await spawnAnswering(wrapperPath, invocation, options);
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
await rm(wrapperDir, { recursive: true, force: true });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function spawnAnswering(wrapperPath, invocation, options) {
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
const child = spawn(process.execPath, [wrapperPath, ...invocation.args], {
|
|
58
|
+
cwd: invocation.cwd,
|
|
59
|
+
env: invocation.env ?? process.env,
|
|
60
|
+
shell: false,
|
|
61
|
+
// stdin MUST be piped — this is the whole point. The default runner uses
|
|
62
|
+
// 'ignore', which is why it structurally cannot answer a prompt.
|
|
63
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
64
|
+
signal: invocation.signal,
|
|
65
|
+
});
|
|
66
|
+
let stdout = '';
|
|
67
|
+
let stderr = '';
|
|
68
|
+
let overflow = false;
|
|
69
|
+
let capturedBytes = 0;
|
|
70
|
+
let unresolvedPromptError = null;
|
|
71
|
+
const answered = new Set();
|
|
72
|
+
const append = (current, chunk) => {
|
|
73
|
+
if (overflow)
|
|
74
|
+
return current;
|
|
75
|
+
const text = String(chunk);
|
|
76
|
+
capturedBytes += Buffer.byteLength(text);
|
|
77
|
+
const next = current + text;
|
|
78
|
+
if (capturedBytes > MAX_CAPTURE_BYTES) {
|
|
79
|
+
overflow = true;
|
|
80
|
+
child.kill('SIGTERM');
|
|
81
|
+
return next.slice(0, MAX_CAPTURE_BYTES);
|
|
82
|
+
}
|
|
83
|
+
return next;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Answer whichever prompt is currently on screen.
|
|
87
|
+
*
|
|
88
|
+
* Output accumulates, so an already-answered prompt stays in the buffer —
|
|
89
|
+
* `answered` keys off (entity, table, name) so each is written to exactly
|
|
90
|
+
* once. Without that, every subsequent chunk would re-send keystrokes and
|
|
91
|
+
* desynchronize the selection.
|
|
92
|
+
*/
|
|
93
|
+
const handlePromptOutput = () => {
|
|
94
|
+
if (unresolvedPromptError)
|
|
95
|
+
return;
|
|
96
|
+
if (!invocation.renameHints && !invocation.autoCreateRenames)
|
|
97
|
+
return;
|
|
98
|
+
const prompt = extractLatestDrizzlePrompt(`${stdout}\n${stderr}`);
|
|
99
|
+
if (!prompt)
|
|
100
|
+
return;
|
|
101
|
+
const key = drizzlePromptKey(prompt);
|
|
102
|
+
if (answered.has(key))
|
|
103
|
+
return;
|
|
104
|
+
const movesDown = invocation.renameHints
|
|
105
|
+
? resolvePromptWithHints(prompt, invocation.renameHints)
|
|
106
|
+
: null;
|
|
107
|
+
if (movesDown !== null) {
|
|
108
|
+
answered.add(key);
|
|
109
|
+
options.log?.(`Resolving ${prompt.entity} "${prompt.toName}" from rename hint`);
|
|
110
|
+
child.stdin?.write(keystrokesForOption(movesDown));
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (invocation.autoCreateRenames) {
|
|
114
|
+
answered.add(key);
|
|
115
|
+
options.log?.(`Auto-selecting "create" for ${prompt.entity} "${prompt.toName}" (autoCreateRenames)`);
|
|
116
|
+
child.stdin?.write(KEYSTROKE_ACCEPT_CREATE);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
// No hint and no auto-create: refuse rather than guess. Guessing here
|
|
120
|
+
// means DROP + ADD on a column the user meant to rename.
|
|
121
|
+
unresolvedPromptError = formatDrizzlePromptError(prompt);
|
|
122
|
+
child.kill('SIGTERM');
|
|
123
|
+
setTimeout(() => child.kill('SIGKILL'), 2_000).unref?.();
|
|
124
|
+
};
|
|
125
|
+
child.stdout?.on('data', (chunk) => {
|
|
126
|
+
stdout = append(stdout, chunk);
|
|
127
|
+
handlePromptOutput();
|
|
128
|
+
});
|
|
129
|
+
child.stderr?.on('data', (chunk) => {
|
|
130
|
+
stderr = append(stderr, chunk);
|
|
131
|
+
handlePromptOutput();
|
|
132
|
+
});
|
|
133
|
+
child.on('error', (error) => {
|
|
134
|
+
reject(new MigrationExecutorError('MIGRATION_COMMAND_FAILED', 'Failed to start the fake-TTY drizzle-kit wrapper', { cause: error }));
|
|
135
|
+
});
|
|
136
|
+
child.on('close', (exitCode) => {
|
|
137
|
+
if (unresolvedPromptError) {
|
|
138
|
+
reject(new MigrationExecutorError('MIGRATION_PLAN_INVALID', unresolvedPromptError));
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (overflow) {
|
|
142
|
+
reject(new MigrationExecutorError('MIGRATION_COMMAND_FAILED', `Local migration command exceeded the ${MAX_CAPTURE_BYTES}-byte output limit`));
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
// A second TTY abort means the wrapper failed to present its fake TTY.
|
|
146
|
+
// Surfacing it is important: the alternative is reporting success on a
|
|
147
|
+
// run that generated nothing.
|
|
148
|
+
if (isDrizzleTtyAbort(stdout, stderr)) {
|
|
149
|
+
reject(new MigrationExecutorError('MIGRATION_COMMAND_FAILED', 'drizzle-kit still reported "Interactive prompts require a TTY" when run through the ' +
|
|
150
|
+
'fake-TTY wrapper, so no migration was generated. This usually means the wrapper ' +
|
|
151
|
+
'could not resolve the project\'s drizzle-kit.'));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
resolve({ exitCode: exitCode ?? 1, stdout, stderr });
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
//# sourceMappingURL=prompt-runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-runner.js","sourceRoot":"","sources":["../../../src/lib/migrations/prompt-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EACL,iCAAiC,EACjC,2BAA2B,GAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,uBAAuB,EACvB,gBAAgB,EAChB,0BAA0B,EAC1B,wBAAwB,EACxB,iBAAiB,EACjB,mBAAmB,EACnB,sBAAsB,GACvB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,sBAAsB,EAAE,MAAM,aAAa,CAAC;AAGrD,MAAM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OAAO,CAAC,EAAE,QAAQ,EAAE,QAAQ,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;QACvD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-runner.test.d.ts","sourceRoot":"","sources":["../../../src/lib/migrations/prompt-runner.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { chmod, mkdtemp, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { createPromptAwareMigrationRunner } from './prompt-runner.js';
|
|
6
|
+
/**
|
|
7
|
+
* A stand-in for drizzle-kit that reproduces the two behaviors that matter:
|
|
8
|
+
* it refuses to prompt without a TTY (printing the abort and exiting 0), and
|
|
9
|
+
* when it does prompt it reads a selection from stdin the way a keypress-based
|
|
10
|
+
* prompt does.
|
|
11
|
+
*
|
|
12
|
+
* Mocking the runner would prove nothing here — the whole question is whether
|
|
13
|
+
* real keystrokes reach a real child process's stdin. So the fake is a real
|
|
14
|
+
* script and the runner really spawns it.
|
|
15
|
+
*/
|
|
16
|
+
const FAKE_DRIZZLE = `#!/usr/bin/env node
|
|
17
|
+
const ESC = '\\u001b';
|
|
18
|
+
if (!process.stdin.isTTY) {
|
|
19
|
+
process.stderr.write('Interactive prompts require a TTY\\n');
|
|
20
|
+
process.exit(0); // drizzle-kit 0.31 exits 0 here — that is the trap
|
|
21
|
+
}
|
|
22
|
+
process.stdout.write(
|
|
23
|
+
ESC + '[1mIs title column in projects table created or renamed from another column?' + ESC + '[0m\\n' +
|
|
24
|
+
' + title create column\\n' +
|
|
25
|
+
' ~ name > title rename column\\n' +
|
|
26
|
+
' ~ label > title rename column\\n'
|
|
27
|
+
);
|
|
28
|
+
let seen = '';
|
|
29
|
+
// A real prompt awaits a promise, which keeps the child alive until a key
|
|
30
|
+
// arrives. The wrapper unrefs the stdin bridge so it cannot hold the loop by
|
|
31
|
+
// itself, so the fake must hold it the same way the real one does — without
|
|
32
|
+
// this the child exits before the parent's keystrokes land.
|
|
33
|
+
const alive = setInterval(() => {}, 1000);
|
|
34
|
+
process.stdin.on('data', (chunk) => {
|
|
35
|
+
seen += chunk.toString();
|
|
36
|
+
if (!seen.includes('\\r')) return;
|
|
37
|
+
const downs = (seen.match(/\\u001b\\[B/g) || []).length;
|
|
38
|
+
require('fs').writeFileSync(process.env.QB_SELECTION_FILE, String(downs));
|
|
39
|
+
process.stdout.write('selected ' + downs + '\\n');
|
|
40
|
+
clearInterval(alive);
|
|
41
|
+
process.exit(0);
|
|
42
|
+
});
|
|
43
|
+
`;
|
|
44
|
+
/** The wrapper resolves drizzle-kit from projectRoot; point it at the fake. */
|
|
45
|
+
async function fixture() {
|
|
46
|
+
const projectRoot = await mkdtemp(join(tmpdir(), 'qb-prompt-runner-'));
|
|
47
|
+
const pkgDir = join(projectRoot, 'node_modules', 'drizzle-kit');
|
|
48
|
+
await Bun.write(join(pkgDir, 'package.json'), JSON.stringify({ name: 'drizzle-kit' }));
|
|
49
|
+
await Bun.write(join(pkgDir, 'bin.cjs'), FAKE_DRIZZLE);
|
|
50
|
+
await Bun.write(join(projectRoot, 'package.json'), JSON.stringify({ name: 'proj' }));
|
|
51
|
+
const binDir = join(projectRoot, 'node_modules', '.bin');
|
|
52
|
+
const bin = join(binDir, 'drizzle-kit');
|
|
53
|
+
await Bun.write(bin, FAKE_DRIZZLE);
|
|
54
|
+
await chmod(bin, 0o755);
|
|
55
|
+
return { projectRoot, selectionFile: join(projectRoot, 'selection.txt') };
|
|
56
|
+
}
|
|
57
|
+
function invocation(projectRoot, extra = {}) {
|
|
58
|
+
return {
|
|
59
|
+
executable: join(projectRoot, 'node_modules', '.bin', 'drizzle-kit'),
|
|
60
|
+
args: ['generate', '--config', 'drizzle.config.ts'],
|
|
61
|
+
cwd: projectRoot,
|
|
62
|
+
...extra,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
describe('createPromptAwareMigrationRunner', () => {
|
|
66
|
+
test('retries through the fake-TTY wrapper on a TTY abort and answers from a hint', async () => {
|
|
67
|
+
const { projectRoot, selectionFile } = await fixture();
|
|
68
|
+
const runner = createPromptAwareMigrationRunner({ projectRoot });
|
|
69
|
+
const result = await runner(invocation(projectRoot, {
|
|
70
|
+
env: { ...process.env, QB_SELECTION_FILE: selectionFile },
|
|
71
|
+
renameHints: { columns: { projects: { title: 'label' } } },
|
|
72
|
+
}));
|
|
73
|
+
expect(result.exitCode).toBe(0);
|
|
74
|
+
// 'label' is the SECOND rename candidate, so two arrow-downs past "create".
|
|
75
|
+
// A off-by-one here would rename from `name` — the wrong column.
|
|
76
|
+
expect(await readFile(selectionFile, 'utf-8')).toBe('2');
|
|
77
|
+
});
|
|
78
|
+
test('selects the first rename candidate when the hint names it', async () => {
|
|
79
|
+
const { projectRoot, selectionFile } = await fixture();
|
|
80
|
+
const runner = createPromptAwareMigrationRunner({ projectRoot });
|
|
81
|
+
await runner(invocation(projectRoot, {
|
|
82
|
+
env: { ...process.env, QB_SELECTION_FILE: selectionFile },
|
|
83
|
+
renameHints: { columns: { projects: { title: 'name' } } },
|
|
84
|
+
}));
|
|
85
|
+
expect(await readFile(selectionFile, 'utf-8')).toBe('1');
|
|
86
|
+
});
|
|
87
|
+
test('falls back to "create" (zero arrow-downs) under autoCreateRenames', async () => {
|
|
88
|
+
const { projectRoot, selectionFile } = await fixture();
|
|
89
|
+
const runner = createPromptAwareMigrationRunner({ projectRoot });
|
|
90
|
+
await runner(invocation(projectRoot, {
|
|
91
|
+
env: { ...process.env, QB_SELECTION_FILE: selectionFile },
|
|
92
|
+
autoCreateRenames: true,
|
|
93
|
+
}));
|
|
94
|
+
expect(await readFile(selectionFile, 'utf-8')).toBe('0');
|
|
95
|
+
});
|
|
96
|
+
test('a hint takes precedence over autoCreateRenames', async () => {
|
|
97
|
+
const { projectRoot, selectionFile } = await fixture();
|
|
98
|
+
const runner = createPromptAwareMigrationRunner({ projectRoot });
|
|
99
|
+
await runner(invocation(projectRoot, {
|
|
100
|
+
env: { ...process.env, QB_SELECTION_FILE: selectionFile },
|
|
101
|
+
autoCreateRenames: true,
|
|
102
|
+
renameHints: { columns: { projects: { title: 'label' } } },
|
|
103
|
+
}));
|
|
104
|
+
// Falling back to create here would DROP + ADD a column the user
|
|
105
|
+
// explicitly declared as renamed.
|
|
106
|
+
expect(await readFile(selectionFile, 'utf-8')).toBe('2');
|
|
107
|
+
});
|
|
108
|
+
test('refuses, naming the hint key, when neither a hint nor auto-create applies', async () => {
|
|
109
|
+
const { projectRoot, selectionFile } = await fixture();
|
|
110
|
+
const runner = createPromptAwareMigrationRunner({ projectRoot });
|
|
111
|
+
await expect(runner(invocation(projectRoot, {
|
|
112
|
+
env: { ...process.env, QB_SELECTION_FILE: selectionFile },
|
|
113
|
+
renameHints: { columns: { other_table: { something: 'else' } } },
|
|
114
|
+
}))).rejects.toThrow(/compiler\.migrations\.renames\.columns\["projects"\]\["title"\]/);
|
|
115
|
+
});
|
|
116
|
+
test('does not retry when the first attempt produced no TTY abort', async () => {
|
|
117
|
+
const projectRoot = await mkdtemp(join(tmpdir(), 'qb-prompt-runner-clean-'));
|
|
118
|
+
const binDir = join(projectRoot, 'node_modules', '.bin');
|
|
119
|
+
const bin = join(binDir, 'drizzle-kit');
|
|
120
|
+
await Bun.write(bin, '#!/bin/sh\necho "No schema changes, nothing to migrate"\n');
|
|
121
|
+
await chmod(bin, 0o755);
|
|
122
|
+
// No drizzle-kit package installed: if the runner retried through the
|
|
123
|
+
// wrapper it would fail to resolve one, so a clean pass proves it didn't.
|
|
124
|
+
await writeFile(join(projectRoot, 'package.json'), JSON.stringify({ name: 'proj' }));
|
|
125
|
+
const runner = createPromptAwareMigrationRunner({ projectRoot });
|
|
126
|
+
const result = await runner(invocation(projectRoot));
|
|
127
|
+
expect(result.exitCode).toBe(0);
|
|
128
|
+
expect(result.stdout).toContain('No schema changes');
|
|
129
|
+
});
|
|
130
|
+
});
|
|
131
|
+
//# sourceMappingURL=prompt-runner.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-runner.test.js","sourceRoot":"","sources":["../../../src/lib/migrations/prompt-runner.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAClD,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,gCAAgC,EAAE,MAAM,oBAAoB,CAAC;AAGtE;;;;;;;;;GASG;AACH,MAAM,YAAY,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BpB,CAAC;AAEF,+EAA+E;AAC/E,KAAK,UAAU,OAAO;IACpB,MAAM,WAAW,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,mBAAmB,CAAC,CAAC,CAAC;IACvE,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,aAAa,CAAC,CAAC;IAChE,MAAM,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,cAAc,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,CAAC,CAAC;IACvF,MAAM,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,YAAY,CAAC,CAAC;IACvD,MAAM,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,cAAc,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,I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7E,MAAM,WAAW,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,yBAAyB,CAAC,CAAC,CAAC;QAC7E,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,MAAM,CAAC,CAAC;QACzD,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;QACxC,MAAM,GAAG,CAAC,KAAK,CAAC,GAAG,EAAE,2DAA2D,CAAC,CAAC;QAClF,MAAM,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACxB,sEAAsE;QACtE,0EAA0E;QAC1E,MAAM,SAAS,CAAC,IAAI,CAAC,WAAW,EAAE,cAAc,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC;QAErF,MAAM,MAAM,GAAG,gCAAgC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC;QACjE,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;QAErD,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAChC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,SAAS,CAAC,mBAAmB,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The schema contract the CLI sends alongside a locally-owned migration run.
|
|
3
|
+
*
|
|
4
|
+
* `engineVersion` is read from the schema engine this CLI actually bundles,
|
|
5
|
+
* never hard-coded. The compiler compares it against its own constant and
|
|
6
|
+
* rejects a mismatch outright (SCHEMA_ENGINE_VERSION_MISMATCH) — that check is
|
|
7
|
+
* the guard that stops a CLI and compiler from lowering feature schema
|
|
8
|
+
* differently while both believe they agree. Reading it from the loaded module
|
|
9
|
+
* is what makes the guard real: hard-coding the string here would let the
|
|
10
|
+
* bundle drift from the value we claim.
|
|
11
|
+
*/
|
|
12
|
+
export declare function resolveSchemaEngineVersion(): Promise<string>;
|
|
13
|
+
export interface SchemaHashInput {
|
|
14
|
+
name: string;
|
|
15
|
+
areaPath?: string[];
|
|
16
|
+
schema?: {
|
|
17
|
+
source?: string;
|
|
18
|
+
} | undefined;
|
|
19
|
+
tables?: unknown;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Content hash of the migration-facing schema surface.
|
|
23
|
+
*
|
|
24
|
+
* Scope note: the compiler currently validates that this is a non-empty string
|
|
25
|
+
* and echoes it back on `meta.schema` — it does not yet re-derive and compare
|
|
26
|
+
* it (plan 001 leaves canonical re-derivation to the shared engine's hash API,
|
|
27
|
+
* which has not landed). So this is not yet a security boundary, and must not
|
|
28
|
+
* be relied on as one.
|
|
29
|
+
*
|
|
30
|
+
* It is still computed honestly rather than stubbed, for two reasons: the value
|
|
31
|
+
* becomes load-bearing the moment that API lands, and a stable hash today gives
|
|
32
|
+
* the compile response something meaningful to key on. Inputs are sorted and
|
|
33
|
+
* the digest covers only what can change generated schema — feature identity,
|
|
34
|
+
* area placement, and authored schema source.
|
|
35
|
+
*/
|
|
36
|
+
export declare function computeSchemaHash(features: readonly SchemaHashInput[], config: {
|
|
37
|
+
name?: string;
|
|
38
|
+
providers?: {
|
|
39
|
+
database?: {
|
|
40
|
+
name?: string;
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
}): string;
|
|
44
|
+
//# sourceMappingURL=schema-contract.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-contract.d.ts","sourceRoot":"","sources":["../../../src/lib/migrations/schema-contract.ts"],"names":[],"mappings":"AAIA;;;;;;;;;;GAUG;AACH,wBAAsB,0BAA0B,IAAI,OAAO,CAAC,MAAM,CAAC,CAGlE;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,MAAM,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IACzC,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,iBAAiB,CAC/B,QAAQ,EAAE,SAAS,eAAe,EAAE,EACpC,MAAM,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE;YAAE,IAAI,CAAC,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAA;CAAE,GACtE,MAAM,CAoBR"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { loadSchemaEngine } from '../schema-engine-loader.js';
|
|
3
|
+
/**
|
|
4
|
+
* The schema contract the CLI sends alongside a locally-owned migration run.
|
|
5
|
+
*
|
|
6
|
+
* `engineVersion` is read from the schema engine this CLI actually bundles,
|
|
7
|
+
* never hard-coded. The compiler compares it against its own constant and
|
|
8
|
+
* rejects a mismatch outright (SCHEMA_ENGINE_VERSION_MISMATCH) — that check is
|
|
9
|
+
* the guard that stops a CLI and compiler from lowering feature schema
|
|
10
|
+
* differently while both believe they agree. Reading it from the loaded module
|
|
11
|
+
* is what makes the guard real: hard-coding the string here would let the
|
|
12
|
+
* bundle drift from the value we claim.
|
|
13
|
+
*/
|
|
14
|
+
export async function resolveSchemaEngineVersion() {
|
|
15
|
+
const engine = await loadSchemaEngine();
|
|
16
|
+
return engine.SCHEMA_ENGINE_VERSION;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Content hash of the migration-facing schema surface.
|
|
20
|
+
*
|
|
21
|
+
* Scope note: the compiler currently validates that this is a non-empty string
|
|
22
|
+
* and echoes it back on `meta.schema` — it does not yet re-derive and compare
|
|
23
|
+
* it (plan 001 leaves canonical re-derivation to the shared engine's hash API,
|
|
24
|
+
* which has not landed). So this is not yet a security boundary, and must not
|
|
25
|
+
* be relied on as one.
|
|
26
|
+
*
|
|
27
|
+
* It is still computed honestly rather than stubbed, for two reasons: the value
|
|
28
|
+
* becomes load-bearing the moment that API lands, and a stable hash today gives
|
|
29
|
+
* the compile response something meaningful to key on. Inputs are sorted and
|
|
30
|
+
* the digest covers only what can change generated schema — feature identity,
|
|
31
|
+
* area placement, and authored schema source.
|
|
32
|
+
*/
|
|
33
|
+
export function computeSchemaHash(features, config) {
|
|
34
|
+
const hash = createHash('sha256');
|
|
35
|
+
hash.update(`project:${config.name ?? ''}\n`);
|
|
36
|
+
hash.update(`dialect:${config.providers?.database?.name ?? ''}\n`);
|
|
37
|
+
const canonical = features
|
|
38
|
+
.map((feature) => ({
|
|
39
|
+
name: feature.name,
|
|
40
|
+
area: (feature.areaPath ?? []).join('/'),
|
|
41
|
+
source: feature.schema?.source ?? '',
|
|
42
|
+
}))
|
|
43
|
+
.sort((a, b) => (a.area + a.name).localeCompare(b.area + b.name));
|
|
44
|
+
for (const entry of canonical) {
|
|
45
|
+
hash.update(`feature:${entry.area}/${entry.name}\n`);
|
|
46
|
+
hash.update(entry.source);
|
|
47
|
+
hash.update('\n');
|
|
48
|
+
}
|
|
49
|
+
return hash.digest('hex');
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=schema-contract.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-contract.js","sourceRoot":"","sources":["../../../src/lib/migrations/schema-contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9D;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,0BAA0B;IAC9C,MAAM,MAAM,GAAG,MAAM,gBAAgB,EAAE,CAAC;IACxC,OAAO,MAAM,CAAC,qBAAqB,CAAC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| Unauthorized | Missing or expired authentication |
|
|
14
14
|
| `403` | Forbidden | Access denied (wrong role, condition failed) or firewall blocked it |
|
|
15
15
|
| `404` | Not Found | Firewall blocked the record on a resource that set `firewallErrorMode: 'hide'` (or the route doesn't exist) |
|
|
16
|
+
| `405` | Method Not Allowed | The path is a real route, but not for this verb — the response carries an `Allow` header listing the methods it does accept |
|
|
16
17
|
| `409` | Conflict | Unique constraint hit, or a duplicate [`Idempotency-Key`](/platform/api-contract#idempotency-key) still in flight |
|
|
17
18
|
| `412` | Precondition Failed | `If-Match` revision mismatch — [changesets](/define/changesets) and plain single-record `PATCH`/`PUT`/`DELETE` |
|
|
18
19
|
| `422` | Unprocessable | `Idempotency-Key` reused with a different request or principal |
|
|
@@ -175,6 +175,90 @@ If you enable `cms` and `account` without custom domains, everything is served o
|
|
|
175
175
|
|
|
176
176
|
This is the simplest setup — no DNS configuration needed, no cross-subdomain cookies. Auth cookies work naturally because everything is same-origin.
|
|
177
177
|
|
|
178
|
+
## Named Environments
|
|
179
|
+
|
|
180
|
+
A project with [named environments](/platform/database/neon#named-cloudflare-deployment-environments) deploys the same bundle to several Workers (`wrangler deploy -e dev`, `-e prod`), and each target needs its own hostnames. Two rules make that safe:
|
|
181
|
+
|
|
182
|
+
1. **The base config emits no `routes` block.** Wrangler treats `routes` as an *inheritable* key — a top-level block would be inherited by any `[env.*]` that declares none, and `deploy -e dev` would rebind the production hostname to the dev Worker.
|
|
183
|
+
2. **Every environment claims every hostname the top level generates.** The top-level domain config still defines the *shape* — which roles exist and what the Worker bakes in for each — and `environments.<name>.domains` supplies the actual hostnames.
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
// quickback.config.ts — the worker block of each environment is omitted here;
|
|
187
|
+
// see Named deployment environments for the full target contract.
|
|
188
|
+
api: { domain: "api.attend.vip" }, // the SHAPE: this project has an API hostname
|
|
189
|
+
environments: {
|
|
190
|
+
dev: { domains: { api: "api-dev.attend.vip" }, worker: { /* … */ } },
|
|
191
|
+
prod: { domains: { api: "api.attend.vip" }, worker: { /* … */ } },
|
|
192
|
+
},
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
```toml title="wrangler.toml (generated)"
|
|
196
|
+
# no top-level routes — each target owns its own
|
|
197
|
+
[env.dev]
|
|
198
|
+
routes = [
|
|
199
|
+
{ pattern = "api-dev.attend.vip", custom_domain = true },
|
|
200
|
+
]
|
|
201
|
+
|
|
202
|
+
[env.prod]
|
|
203
|
+
routes = [
|
|
204
|
+
{ pattern = "api.attend.vip", custom_domain = true },
|
|
205
|
+
]
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Each `domains` key maps 1:1 to a top-level source:
|
|
209
|
+
|
|
210
|
+
| `domains` key | Claims |
|
|
211
|
+
|---------------|--------|
|
|
212
|
+
| `primary` | `domain` |
|
|
213
|
+
| `api` | `api.domain` |
|
|
214
|
+
| `auth` | `auth.domain` |
|
|
215
|
+
| `cms` | `cms.domain` |
|
|
216
|
+
| `account` | `account.domain` |
|
|
217
|
+
| `admin` | `account.adminDomain` |
|
|
218
|
+
| `webhook` | the derived `webhook.{baseDomain}` route |
|
|
219
|
+
| `apps.<name>[i]` | `apps.<name>.domain` (index `0`) and each `aliasDomains` entry (`1`+) |
|
|
220
|
+
| `routes[i]` | `providers.runtime.config.routes[i]` |
|
|
221
|
+
|
|
222
|
+
When the project generates exactly **one** hostname, `domain: "api-dev.attend.vip"` is accepted as shorthand for the single role.
|
|
223
|
+
|
|
224
|
+
`domains: 'none'` marks a workers.dev-only target. It emits `routes = []` rather than omitting the block, so inheritance cannot hand that target a sibling's custom domain.
|
|
225
|
+
|
|
226
|
+
The compile fails, naming the config path to fix, when an environment leaves a generated hostname unclaimed, claims a key the top level does not generate, or claims a hostname another target already owns.
|
|
227
|
+
|
|
228
|
+
### The unified hostname per target
|
|
229
|
+
|
|
230
|
+
The auto-inferred `quickback.{baseDomain}` host — where every surface coexists and `/` redirects to `/cms/` — is inferred for named-environment projects too, once **per target**:
|
|
231
|
+
|
|
232
|
+
| Target | Claims | Inferred unified host |
|
|
233
|
+
|--------|--------|-----------------------|
|
|
234
|
+
| `dev` | `api-dev.attend.vip` | `quickback-dev.attend.vip` |
|
|
235
|
+
| `prod` | `api.attend.vip` | `quickback-prod.attend.vip` |
|
|
236
|
+
|
|
237
|
+
The single-target name can't carry over verbatim: every environment would infer the same `quickback.attend.vip` from a shared base domain, and one custom domain cannot belong to two Workers. The environment key is the only thing that makes the name unique by construction.
|
|
238
|
+
|
|
239
|
+
It's a hyphen rather than a new label (`quickback-dev.attend.vip`, not `quickback.dev.attend.vip`) because Cloudflare's Universal SSL covers exactly one level of subdomain — the extra label would deploy without a certificate.
|
|
240
|
+
|
|
241
|
+
Set `domains.primary` to override the name on any target. That's how one environment keeps the bare hostname a single-target project would have inferred:
|
|
242
|
+
|
|
243
|
+
```typescript
|
|
244
|
+
prod: { domains: { api: "api.attend.vip", primary: "quickback.attend.vip" } },
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Inference is skipped when the project declares `domain` explicitly (that becomes a real `primary` source each target claims by hand), when the top level configures no domains at all, and for a `domains: 'none'` target.
|
|
248
|
+
|
|
249
|
+
> **These are real custom domains**
|
|
250
|
+
>
|
|
251
|
+
> Every inferred hostname is emitted as a `custom_domain` route, so Wrangler provisions the DNS record on deploy — same as the single-target `quickback.{baseDomain}` has always done. The zone has to be on the deploying Cloudflare account.
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
Each target's unified host joins `trustedOrigins` and the CSP origin list, but does **not** become the target's `BETTER_AUTH_URL` — that stays on the auth or API hostname, matching what a single-target project resolves.
|
|
255
|
+
|
|
256
|
+
### One bundle, several hostnames
|
|
257
|
+
|
|
258
|
+
Every environment runs the *same* compiled Worker, so hostname-sensitive behavior is baked once, at compile time, against every environment's hostnames at once. `domains` is what makes that work: an environment's `cms` hostname gets the CMS domain's API-route block, its `api` hostname gets the `/v1/*` rewriter, its app hostnames serve the app SPA, and all of them join `trustedOrigins`, the CSP origin list, and cross-subdomain cookie inference.
|
|
259
|
+
|
|
260
|
+
Each target's `BETTER_AUTH_URL` also defaults to the hostname it claims (unified → auth → API → UI), so a dev deploy authenticates against its own origin instead of production's. Setting `worker.vars.BETTER_AUTH_URL` explicitly still wins.
|
|
261
|
+
|
|
178
262
|
## Preview Deploys
|
|
179
263
|
|
|
180
264
|
The same compiled bundle can be deployed to additional hostnames — preview environments, staging, per-PR URLs — without recompiling. Set the `EXTRA_APP_HOSTS` env var on the deploy target (a comma-separated list of hostnames) and the worker treats each one like an entry in `apps[*].domain`:
|
|
@@ -223,6 +223,7 @@ Key properties:
|
|
|
223
223
|
- **The relationship table's own firewall is AND'd into the subquery.** Soft-deleting a `event_guests` row revokes access immediately; cross-tenant relationship rows can't grant access.
|
|
224
224
|
- **Anonymous callers fail closed.** `ctx.userId` is null-guarded; the subquery short-circuits to `WHERE 1 = 0` for unauthenticated requests.
|
|
225
225
|
- **The relationship table must be tenant-scoped** (`firewall: { exception: true }` is rejected at compile time on relationship tables).
|
|
226
|
+
- **The relationship table needs its own `defineTable`.** That `<event_guests' own firewall>` line in the SQL above is the table's generated firewall helper — a bare Drizzle export has none, so a `from:` table with no `export default defineTable(...)` is a compile error naming the table.
|
|
226
227
|
|
|
227
228
|
See [Access — relationships](/define/relationships#authzrelationships) for the full `authz.relationships` shape and role-binding patterns.
|
|
228
229
|
|
|
@@ -199,7 +199,7 @@ masking: {
|
|
|
199
199
|
## Show Conditions
|
|
200
200
|
|
|
201
201
|
```typescript
|
|
202
|
-
show: {
|
|
202
|
+
show: 'never' | {
|
|
203
203
|
roles?: string[]; // Unmasked if user has any of these roles
|
|
204
204
|
or?: 'owner'; // Unmasked if user is the record owner
|
|
205
205
|
}
|
|
@@ -207,6 +207,21 @@ show: {
|
|
|
207
207
|
|
|
208
208
|
The `'owner'` condition compares against the owner column declared via `q.scope('owner')` (or auto-detected from a `userId` / `ownerId` column). If no owner scope is present, it falls back to `createdBy`.
|
|
209
209
|
|
|
210
|
+
### `show: 'never'` — masked for everyone, deliberately
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
masking: {
|
|
214
|
+
emailNormalized: { type: 'email', show: 'never' },
|
|
215
|
+
}
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
`show: { roles: [] }` has the same effect, but it doesn't say the same thing. An empty role list reads as an oversight, and it is also what authors fall back to when the audience they wanted is **inexpressible** — masking gates on org and scoped roles, so a table gated `access: { userRole: ['sysadmin'] }` cannot name its own audience in a mask. Two different intentions, one spelling, and no way for the next reader to tell them apart.
|
|
219
|
+
|
|
220
|
+
Write `'never'` when nobody is the intent. Any other string is a compile error rather than a guess — `show: 'admin'` is a plausible typo, and masking-for-everyone is the wrong thing to assume from it.
|
|
221
|
+
|
|
222
|
+
> This does **not** add a `userRole` axis to masking. Gating a mask on Better Auth user roles (`sysadmin`, `appmanager`) is still refused at compile time. `'never'` only lets the deliberate case say so out loud; a mask that wants the same audience as a `userRole`-gated table still has to go through a gated view.
|
|
223
|
+
|
|
224
|
+
|
|
210
225
|
### Relationship-aware field projection
|
|
211
226
|
|
|
212
227
|
For relationship-specific field visibility, use a named view gated by the
|
|
@@ -53,6 +53,41 @@ export default defineConfig({
|
|
|
53
53
|
});
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
+
> **The `from:` table needs its own defineTable**
|
|
57
|
+
>
|
|
58
|
+
> A relationship resolves through the `from:` table's **generated resource module**
|
|
59
|
+
> (`<table>.resource.ts`) — that's what supplies the firewall the subquery AND's in. The
|
|
60
|
+
> compiler emits that module only for tables with an `export default defineTable(...)`, so a
|
|
61
|
+
> join table declared as a bare Drizzle export is a compile error naming the table:
|
|
62
|
+
>
|
|
63
|
+
> ```typescript
|
|
64
|
+
> // features/conversations/conversation_members.ts
|
|
65
|
+
> export const conversation_members = sqliteTable('conversation_members', {
|
|
66
|
+
> id: text('id').primaryKey(),
|
|
67
|
+
> userId: text('user_id').notNull(),
|
|
68
|
+
> conversationId: text('conversation_id').notNull(),
|
|
69
|
+
> organizationId: text('organization_id').notNull(),
|
|
70
|
+
> // ── quickback:audit (compiler-managed — edits are validated, not merged) ──
|
|
71
|
+
> // Raw Drizzle tables spell the managed columns out; `...q.audit()` is
|
|
72
|
+
> // q-DSL only. See [Escape hatches](/define/escape-hatches).
|
|
73
|
+
> createdAt: text('created_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()),
|
|
74
|
+
> modifiedAt: text('modified_at').notNull().default('1970-01-01T00:00:00.000Z').$defaultFn(() => new Date().toISOString()).$onUpdate(() => new Date().toISOString()),
|
|
75
|
+
> createdBy: text('created_by'),
|
|
76
|
+
> modifiedBy: text('modified_by'),
|
|
77
|
+
> deletedAt: text('deleted_at'),
|
|
78
|
+
> deletedBy: text('deleted_by'),
|
|
79
|
+
> });
|
|
80
|
+
>
|
|
81
|
+
> // Required — without this, `from: 'conversation_members'` cannot compile.
|
|
82
|
+
> export default defineTable(conversation_members, {
|
|
83
|
+
> firewall: [{ field: 'organizationId', equals: 'ctx.activeOrgId' }],
|
|
84
|
+
> });
|
|
85
|
+
> ```
|
|
86
|
+
>
|
|
87
|
+
> Adding `defineTable` does not force a public API onto the join table — gate or omit its
|
|
88
|
+
> `read` / `crud` blocks as you would any other table. What it supplies is the firewall.
|
|
89
|
+
|
|
90
|
+
|
|
56
91
|
### Using relationship-roles in resources
|
|
57
92
|
|
|
58
93
|
Resource definitions reference declared roles by name in `roles: [...]` arrays exactly like BA roles or pseudo-roles. The compiler rewrites the access tree at build time so the runtime route does an inline relationship lookup against the declared table.
|
|
@@ -405,6 +405,26 @@ Audit fields are a separate concept from soft-delete (`deletedAt`/`deletedBy`)
|
|
|
405
405
|
|
|
406
406
|
Opt out of audit injection entirely with `compiler.features.auditFields: false` in `quickback.config.ts`. (You almost never want to.)
|
|
407
407
|
|
|
408
|
+
#### Writing through a raw handle — `auditStamp(ctx)`
|
|
409
|
+
|
|
410
|
+
The scoped `db` injected into actions stamps these four columns for you. A handle built directly from `createDb()` does not — that's the documented escape hatch for system writes, sessionless principals, and broad reads the scoped wrapper over-narrows.
|
|
411
|
+
|
|
412
|
+
Those writes still land in audit-managed tables, and the managed columns carry a DDL default of the unix epoch (so `ALTER TABLE ADD COLUMN` works on populated tables). An omitted column therefore **does not** fail loudly on `NOT NULL` — it silently persists `1970-01-01T00:00:00.000Z`, which reads as a real timestamp everywhere downstream.
|
|
413
|
+
|
|
414
|
+
Spread the stamp instead of hand-writing four columns at each call site:
|
|
415
|
+
|
|
416
|
+
```typescript
|
|
417
|
+
import { auditStamp } from '../lib/audit-wrapper';
|
|
418
|
+
|
|
419
|
+
await db.insert(invoices).values({ ...auditStamp(ctx), amount, organizationId });
|
|
420
|
+
await db.update(invoices).set({ ...auditStamp(ctx, 'update'), status });
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
`'insert'` (the default) returns all four columns; `'update'` returns only `modifiedAt` / `modifiedBy`, so an update never rewrites `createdAt`. Actor resolution is identical to the wrapper's, including the delegated-principal and `scope:<kind>:<subjectId>` lanes, and it **fails closed** the same way — a raw handle is not a licence to write an anonymous audit row.
|
|
424
|
+
|
|
425
|
+
> For genuinely context-free writes — cron, seed scripts, backfills that must preserve historical timestamps — pass your own values. `auditStamp` needs a real caller and throws without one, by design.
|
|
426
|
+
|
|
427
|
+
|
|
408
428
|
### Declaring them visibly — `...q.audit()` / `...q.softDelete()`
|
|
409
429
|
|
|
410
430
|
Historically these columns were invisible: injected into the *generated* schema only, so the table object in your editor didn't have them. They are now declared **visibly** (required by default — see below) so `$infer`, your editor, and the emitted schema all agree:
|