|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; |
| 4 | +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'; |
| 5 | +import { tmpdir } from 'node:os'; |
| 6 | +import { dirname, join, resolve } from 'node:path'; |
| 7 | +import { fileURLToPath } from 'node:url'; |
| 8 | +import Database from 'better-sqlite3'; |
| 9 | +import { isExitSignal } from '../../utils/format.js'; |
| 10 | +import MigrateApply from './apply.js'; |
| 11 | +import MigrateListPreferences from './list-preferences.js'; |
| 12 | + |
| 13 | +// Pay the first transform of the dist-resolved workspace deps the commands |
| 14 | +// reach through dynamic `import()`s at MODULE LOAD, not inside a case. |
| 15 | +import '@objectstack/runtime'; |
| 16 | +import '@objectstack/objectql'; |
| 17 | + |
| 18 | +/** |
| 19 | + * `os migrate list-preferences` against a real SQLite database: the step that |
| 20 | + * removes the `sys_user_preference` rows keyed `ui.list.<object>`, which no |
| 21 | + * Console reads any more (objectstack#35955). |
| 22 | + * |
| 23 | + * ## The database |
| 24 | + * |
| 25 | + * The schema this version creates (`os migrate apply --yes` over an empty |
| 26 | + * file), with the rows an earlier Console left: three `ui.list.*` rows for two |
| 27 | + * users, and two CONTROLS that are never touched — another family's row |
| 28 | + * (`ui.record.account`) and a key that only looks alike (`ui.lists`). |
| 29 | + * |
| 30 | + * ## The cases run in order over ONE database, as an operator runs the steps |
| 31 | + * |
| 32 | + * 1. a dry run reports the rows and deletes nothing; |
| 33 | + * 2. `--apply` without `--export` is refused, and so is an export path that |
| 34 | + * already exists — both with nothing deleted; |
| 35 | + * 3. `--apply --export` writes the export (owner-only, every row as stored), |
| 36 | + * deletes exactly the `ui.list.*` rows, and keeps the controls; |
| 37 | + * 4. a re-run finds nothing and writes no export. |
| 38 | + */ |
| 39 | + |
| 40 | +const HERE = dirname(fileURLToPath(import.meta.url)); |
| 41 | +const CLI_ROOT = resolve(HERE, '..', '..', '..'); |
| 42 | +const CASE_TIMEOUT_MS = 240_000; |
| 43 | + |
| 44 | +const RETIRED = [ |
| 45 | + { id: 'pref_l1', user_id: 'u1', key: 'ui.list.account', value: '{"viewOrder":["account.all"]}' }, |
| 46 | + { id: 'pref_l2', user_id: 'u1', key: 'ui.list.contact', value: '{"perView":{"contact.all":{"rowHeight":"compact"}}}' }, |
| 47 | + { id: 'pref_l3', user_id: 'u2', key: 'ui.list.account', value: '{"perView":{"account.all":{"sort":[{"field":"name","order":"desc"}]}}}' }, |
| 48 | +]; |
| 49 | +const CONTROLS = [ |
| 50 | + { id: 'pref_r1', user_id: 'u1', key: 'ui.record.account', value: '{"showEmptyFields":true}' }, |
| 51 | + { id: 'pref_x1', user_id: 'u2', key: 'ui.lists', value: '{}' }, |
| 52 | +]; |
| 53 | + |
| 54 | +type Invoke = (argv: string[]) => Promise<unknown>; |
| 55 | +const invoke = (command: { run: (argv: string[], opts: { root: string }) => Promise<unknown> }): Invoke => |
| 56 | + (argv) => command.run(argv, { root: CLI_ROOT }); |
| 57 | + |
| 58 | +/** Env that would point a command's boot somewhere other than the fixture. */ |
| 59 | +const OVERRIDING_ENV = [ |
| 60 | + 'OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME', |
| 61 | + 'OS_TELEMETRY_DB', 'OS_AUTH_SECRET', 'AUTH_SECRET', 'BETTER_AUTH_SECRET', 'OS_ARTIFACT_PATH', |
| 62 | +] as const; |
| 63 | + |
| 64 | +/** Run one command and capture its JSON document and exit status. */ |
| 65 | +async function runJson(command: Invoke, argv: string[]): Promise<{ payload: any; exitCode: number }> { |
| 66 | + const savedExit = process.exitCode; |
| 67 | + const swallow = ((_chunk: unknown, ...rest: unknown[]) => { |
| 68 | + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; |
| 69 | + if (cb) cb(); |
| 70 | + return true; |
| 71 | + }) as typeof process.stdout.write; |
| 72 | + const stdout = vi.spyOn(process.stdout, 'write').mockImplementation(swallow); |
| 73 | + vi.spyOn(process.stderr, 'write').mockImplementation(swallow); |
| 74 | + vi.spyOn(console, 'log').mockImplementation(() => {}); |
| 75 | + vi.spyOn(console, 'warn').mockImplementation(() => {}); |
| 76 | + vi.spyOn(console, 'error').mockImplementation(() => {}); |
| 77 | + let processExit: number | undefined; |
| 78 | + vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { |
| 79 | + processExit = code ?? 0; |
| 80 | + throw new Error(`__PROCESS_EXIT__:${processExit}`); |
| 81 | + }) as never); |
| 82 | + let thrownExit: number | undefined; |
| 83 | + try { |
| 84 | + try { |
| 85 | + await command(argv); |
| 86 | + } catch (error) { |
| 87 | + const trapped = error instanceof Error && error.message.startsWith('__PROCESS_EXIT__'); |
| 88 | + if (!trapped && !isExitSignal(error)) throw error; |
| 89 | + if (!trapped) thrownExit = (error as { oclif?: { exit?: number } }).oclif?.exit; |
| 90 | + } |
| 91 | + const out = stdout.mock.calls.map((c) => String(c[0])).join('').trim(); |
| 92 | + let payload: any; |
| 93 | + try { |
| 94 | + payload = JSON.parse(out); |
| 95 | + } catch { |
| 96 | + payload = { unparsed: out.slice(-400) }; |
| 97 | + } |
| 98 | + return { payload, exitCode: processExit ?? thrownExit ?? (process.exitCode as number | undefined) ?? 0 }; |
| 99 | + } finally { |
| 100 | + process.exitCode = savedExit; |
| 101 | + vi.restoreAllMocks(); |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +let dir: string; |
| 106 | +let dbFile: string; |
| 107 | +const savedEnv: Record<string, string | undefined> = {}; |
| 108 | +const savedCwd = process.cwd(); |
| 109 | + |
| 110 | +function withDb<T>(fn: (db: Database.Database) => T, readonly = true): T { |
| 111 | + const db = new Database(dbFile, { readonly }); |
| 112 | + try { |
| 113 | + return fn(db); |
| 114 | + } finally { |
| 115 | + db.close(); |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +/** Insert a row, filling every other NOT NULL column without a default with a placeholder of its type. */ |
| 120 | +function plant(db: Database.Database, table: string, values: Record<string, unknown>): void { |
| 121 | + const columns = db.prepare(`PRAGMA table_info('${table}')`).all() as Array< |
| 122 | + { name: string; type: string; notnull: number; dflt_value: unknown; pk: number } |
| 123 | + >; |
| 124 | + const row: Record<string, unknown> = { ...values }; |
| 125 | + for (const c of columns) { |
| 126 | + if (c.name in row || !c.notnull || c.dflt_value !== null) continue; |
| 127 | + row[c.name] = /INT|BOOL|REAL|NUM/i.test(c.type) ? 0 : `${c.name}-placeholder`; |
| 128 | + } |
| 129 | + const names = Object.keys(row); |
| 130 | + db.prepare(`INSERT INTO "${table}" (${names.map((n) => `"${n}"`).join(', ')}) VALUES (${names.map(() => '?').join(', ')})`) |
| 131 | + .run(...names.map((n) => row[n] as never)); |
| 132 | +} |
| 133 | + |
| 134 | +const storedIds = (): string[] => |
| 135 | + withDb((db) => (db.prepare("SELECT id FROM sys_user_preference WHERE id LIKE 'pref_%' ORDER BY id").all() as |
| 136 | + Array<{ id: string }>).map((r) => r.id)); |
| 137 | + |
| 138 | +beforeAll(async () => { |
| 139 | + for (const key of [...OVERRIDING_ENV, 'NODE_ENV'] as const) savedEnv[key] = process.env[key]; |
| 140 | + for (const key of OVERRIDING_ENV) delete process.env[key]; |
| 141 | + dir = mkdtempSync(join(tmpdir(), 'os-35955-list-prefs-')); |
| 142 | + mkdirSync(join(dir, 'dist'), { recursive: true }); |
| 143 | + writeFileSync( |
| 144 | + join(dir, 'objectstack.config.ts'), |
| 145 | + [ |
| 146 | + 'export default {', |
| 147 | + " manifest: { id: 'com.example.os35955listprefs', name: 'list prefs', version: '0.0.0', type: 'app' },", |
| 148 | + " objects: [{ name: 'os35955_thing', fields: { title: { type: 'text' } } }],", |
| 149 | + '};', |
| 150 | + '', |
| 151 | + ].join('\n'), |
| 152 | + ); |
| 153 | + process.env.OS_ARTIFACT_PATH = join(dir, 'dist', 'objectstack.json'); |
| 154 | + process.env.NODE_ENV = 'production'; |
| 155 | + process.env.OS_TELEMETRY_DB = '0'; |
| 156 | + dbFile = join(dir, 'upgraded.db'); |
| 157 | + process.chdir(dir); |
| 158 | + try { |
| 159 | + const created = await runJson(invoke(MigrateApply), ['--database-url', `file:${dbFile}`, '--yes', '--json']); |
| 160 | + expect(created.exitCode, JSON.stringify(created.payload).slice(0, 400)).toBe(0); |
| 161 | + } finally { |
| 162 | + process.chdir(savedCwd); |
| 163 | + } |
| 164 | + withDb((db) => { |
| 165 | + for (const row of [...RETIRED, ...CONTROLS]) plant(db, 'sys_user_preference', row); |
| 166 | + }, false); |
| 167 | + expect(storedIds()).toEqual([...RETIRED, ...CONTROLS].map((r) => r.id).sort()); |
| 168 | +}, CASE_TIMEOUT_MS); |
| 169 | + |
| 170 | +afterAll(() => { |
| 171 | + process.chdir(savedCwd); |
| 172 | + for (const [key, value] of Object.entries(savedEnv)) { |
| 173 | + if (value === undefined) delete process.env[key]; |
| 174 | + else process.env[key] = value; |
| 175 | + } |
| 176 | + try { rmSync(dir, { recursive: true, force: true }); } catch { /* best-effort */ } |
| 177 | +}); |
| 178 | + |
| 179 | +beforeEach(() => { process.chdir(dir); }); |
| 180 | +afterEach(() => { process.chdir(savedCwd); }); |
| 181 | + |
| 182 | +describe('os migrate list-preferences removes the ui.list.* preference rows (objectstack#35955)', () => { |
| 183 | + const db = () => `file:${dbFile}`; |
| 184 | + const run = (argv: string[]) => runJson(invoke(MigrateListPreferences), ['--database-url', db(), ...argv, '--json']); |
| 185 | + const all = [...RETIRED, ...CONTROLS].map((r) => r.id).sort(); |
| 186 | + |
| 187 | + it('1. a dry run reports the rows, users and objects, and deletes nothing', async () => { |
| 188 | + const { payload, exitCode } = await run([]); |
| 189 | + expect(exitCode).toBe(0); |
| 190 | + expect(payload).toMatchObject({ apply: false, rows: 3, users: 2, objects: ['account', 'contact'], deleted: 0, remaining: 3 }); |
| 191 | + expect(storedIds()).toEqual(all); |
| 192 | + }, CASE_TIMEOUT_MS); |
| 193 | + |
| 194 | + it('2. --apply is refused without --export, and over an existing export, with nothing deleted', async () => { |
| 195 | + const bare = await run(['--apply', '--yes']); |
| 196 | + expect(bare.exitCode).toBe(1); |
| 197 | + expect(bare.payload.error).toBe('export_required'); |
| 198 | + |
| 199 | + const taken = join(dir, 'taken.json'); |
| 200 | + writeFileSync(taken, 'keep me\n'); |
| 201 | + const over = await run(['--apply', '--yes', '--export', taken]); |
| 202 | + expect(over.exitCode).toBe(1); |
| 203 | + expect(over.payload.error).toBe('export_exists'); |
| 204 | + expect(readFileSync(taken, 'utf8')).toBe('keep me\n'); |
| 205 | + expect(storedIds()).toEqual(all); |
| 206 | + }, CASE_TIMEOUT_MS); |
| 207 | + |
| 208 | + it('3. --apply --export writes every retired row to an owner-only export, then deletes exactly those rows', async () => { |
| 209 | + const exportPath = join(dir, 'list-preferences-export.json'); |
| 210 | + const { payload, exitCode } = await run(['--apply', '--yes', '--export', exportPath]); |
| 211 | + expect(exitCode, JSON.stringify(payload).slice(0, 400)).toBe(0); |
| 212 | + expect(payload).toMatchObject({ apply: true, rows: 3, users: 2, deleted: 3, remaining: 0, failures: [] }); |
| 213 | + |
| 214 | + const doc = JSON.parse(readFileSync(exportPath, 'utf8')); |
| 215 | + expect(doc.keyPrefix).toBe('ui.list.'); |
| 216 | + expect(doc.rows.map((r: { id: string }) => r.id).sort()).toEqual(RETIRED.map((r) => r.id)); |
| 217 | + expect(doc.rows.find((r: { id: string }) => r.id === 'pref_l3')).toMatchObject({ user_id: 'u2', key: 'ui.list.account' }); |
| 218 | + if (process.platform !== 'win32') expect(statSync(exportPath).mode & 0o077).toBe(0); |
| 219 | + |
| 220 | + expect(storedIds()).toEqual(CONTROLS.map((r) => r.id).sort()); |
| 221 | + }, CASE_TIMEOUT_MS); |
| 222 | + |
| 223 | + it('4. a re-run finds nothing, writes no export, and keeps the controls', async () => { |
| 224 | + const exportPath = join(dir, 'second-export.json'); |
| 225 | + const { payload, exitCode } = await run(['--apply', '--yes', '--export', exportPath]); |
| 226 | + expect(exitCode).toBe(0); |
| 227 | + expect(payload).toMatchObject({ rows: 0, deleted: 0, remaining: 0 }); |
| 228 | + expect(existsSync(exportPath)).toBe(false); |
| 229 | + expect(storedIds()).toEqual(CONTROLS.map((r) => r.id).sort()); |
| 230 | + }, CASE_TIMEOUT_MS); |
| 231 | +}); |
0 commit comments