|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * "Does the local dev database hold a Studio customization that this build |
| 5 | + * leaves behind?" — the question `os build` asks after it writes the artifact. |
| 6 | + * |
| 7 | + * A change saved in Studio to an item a package ships is an item of that |
| 8 | + * base's paired customization package `<base>.custom` (ADR-0146 D2, D3), |
| 9 | + * stored in the environment's database and never in `src/`. `os build` and |
| 10 | + * the scaffold's `Dockerfile` compile `src/` alone, so a developer who tuned a |
| 11 | + * view on `os dev` and then deployed lost it with no word said. ADR-0146 D2's |
| 12 | + * way to move it is the package export (`os package export`), committed and |
| 13 | + * installed on the target; this module only lets the build say so, once, at |
| 14 | + * the moment the change is left behind. |
| 15 | + * |
| 16 | + * ## Cheap, local, read-only |
| 17 | + * |
| 18 | + * No server door and no network round trip: the build reads the SQLite file |
| 19 | + * `os dev` would open — resolved by the ONE shared resolution |
| 20 | + * (`resolveProjectDatabaseUrl`, `@objectstack/runtime`), over the environment |
| 21 | + * `os dev` reads (this process's, with the project's development `.env*` files |
| 22 | + * under it, as dotenv-flow layers them, and without loading them into this |
| 23 | + * process) — opened read-only, one aggregate `SELECT` over `sys_metadata`. |
| 24 | + * A database that is not a local SQLite file (Postgres, MongoDB, libSQL, a |
| 25 | + * `:memory:` URL) is not probed: reading it would be a network round trip, so |
| 26 | + * the answer is `not_applicable` and the build prints nothing. |
| 27 | + * |
| 28 | + * ## What counts |
| 29 | + * |
| 30 | + * Every `sys_metadata` row whose `package_id` ends in the pair suffix |
| 31 | + * (`CUSTOMIZATION_PACKAGE_SUFFIX`), counted per package. Those rows are what |
| 32 | + * `os package export` carries in a pair's export; an ensured pair with no item |
| 33 | + * yet has no row here and nothing to lose, so it is not counted. |
| 34 | + * |
| 35 | + * ## Never a verdict it did not reach |
| 36 | + * |
| 37 | + * A file that cannot be read, a missing `better-sqlite3` (the optional native |
| 38 | + * driver), or a database with no `sys_metadata` table yet are told apart: |
| 39 | + * the first two answer `unknown` with the reason, the last `none` (a database |
| 40 | + * `os dev` never booted holds no customization). The build never fails on |
| 41 | + * this probe; `unknown` is printed as such, never as "nothing to export". |
| 42 | + */ |
| 43 | + |
| 44 | +import { existsSync } from 'node:fs'; |
| 45 | +import path from 'node:path'; |
| 46 | +import dotenvFlow from 'dotenv-flow'; |
| 47 | +import { CUSTOMIZATION_PACKAGE_SUFFIX } from '@objectstack/spec/kernel'; |
| 48 | + |
| 49 | +/** One pair package and how many stored items it holds. */ |
| 50 | +export interface LocalCustomizationPackage { |
| 51 | + id: string; |
| 52 | + items: number; |
| 53 | +} |
| 54 | + |
| 55 | +export type LocalCustomizationReading = |
| 56 | + /** No local SQLite file to read: a remote or in-memory database, or none created yet. */ |
| 57 | + | { status: 'not_applicable' } |
| 58 | + /** Read: no stored item of any `.custom` package. */ |
| 59 | + | { status: 'none'; filename: string } |
| 60 | + /** Read: these `.custom` packages hold stored items, which the build does not carry. */ |
| 61 | + | { status: 'found'; filename: string; packages: LocalCustomizationPackage[] } |
| 62 | + /** The file exists but could not be read; `detail` says why. */ |
| 63 | + | { status: 'unknown'; filename: string; detail: string }; |
| 64 | + |
| 65 | +/** |
| 66 | + * The environment `os dev` resolves its database from: this process's |
| 67 | + * variables over the project's development `.env*` files (dotenv-flow never |
| 68 | + * overrides a variable the process already has). Nothing is loaded into |
| 69 | + * `process.env`. |
| 70 | + */ |
| 71 | +export function devDatabaseEnv( |
| 72 | + projectRoot: string, |
| 73 | + processEnv: Record<string, string | undefined> = process.env, |
| 74 | +): Record<string, string | undefined> { |
| 75 | + let fromFiles: Record<string, string> = {}; |
| 76 | + try { |
| 77 | + const files = dotenvFlow.listFiles({ node_env: 'development', path: projectRoot }); |
| 78 | + if (files.length > 0) fromFiles = dotenvFlow.parse(files); |
| 79 | + } catch { |
| 80 | + // An unreadable `.env*` file: `os dev` loads with `silent: true` and boots |
| 81 | + // without it, so the build resolves without it too. |
| 82 | + } |
| 83 | + return { ...fromFiles, ...processEnv }; |
| 84 | +} |
| 85 | + |
| 86 | +/** The SQLite file a resolved database URL names, or `null` when it names none on disk. */ |
| 87 | +export function localSqliteFile( |
| 88 | + url: string, |
| 89 | + sqliteFilenameFromUrl: (url: string, kind: 'sqlite' | 'sqlite-wasm') => string, |
| 90 | +): string | null { |
| 91 | + const kind = /^file:/i.test(url) ? 'sqlite' : /^wasm-sqlite:\/\//i.test(url) ? 'sqlite-wasm' : null; |
| 92 | + if (!kind) return null; |
| 93 | + let filename: string; |
| 94 | + try { |
| 95 | + filename = sqliteFilenameFromUrl(url, kind); |
| 96 | + } catch { |
| 97 | + return null; |
| 98 | + } |
| 99 | + if (!filename || filename === ':memory:' || filename.startsWith(':')) return null; |
| 100 | + return filename; |
| 101 | +} |
| 102 | + |
| 103 | +/** The aggregate read: stored items per `.custom` package. */ |
| 104 | +export const LOCAL_CUSTOMIZATION_QUERY = |
| 105 | + "SELECT package_id AS id, COUNT(*) AS items FROM sys_metadata WHERE package_id LIKE ? ESCAPE '\\' " |
| 106 | + + 'GROUP BY package_id ORDER BY package_id'; |
| 107 | + |
| 108 | +/** `%.custom`, with LIKE's own wildcards in the suffix escaped. */ |
| 109 | +function suffixPattern(): string { |
| 110 | + return `%${CUSTOMIZATION_PACKAGE_SUFFIX.replace(/[\\%_]/g, (c) => `\\${c}`)}`; |
| 111 | +} |
| 112 | + |
| 113 | +/** Read the stored `.custom` items of one SQLite file. */ |
| 114 | +export async function readCustomizationsFromSqlite(filename: string): Promise<LocalCustomizationReading> { |
| 115 | + if (!existsSync(filename)) return { status: 'not_applicable' }; |
| 116 | + |
| 117 | + let Database: any; |
| 118 | + try { |
| 119 | + Database = (await import('better-sqlite3')).default; |
| 120 | + } catch (e: any) { |
| 121 | + return { status: 'unknown', filename, detail: `better-sqlite3 is not loadable (${e?.message ?? e})` }; |
| 122 | + } |
| 123 | + |
| 124 | + let db: any; |
| 125 | + try { |
| 126 | + db = new Database(filename, { readonly: true, fileMustExist: true }); |
| 127 | + const table = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sys_metadata'").get(); |
| 128 | + if (!table) return { status: 'none', filename }; |
| 129 | + const rows = db.prepare(LOCAL_CUSTOMIZATION_QUERY).all(suffixPattern()) as Array<{ id: unknown; items: unknown }>; |
| 130 | + const packages = rows |
| 131 | + .filter((r) => typeof r.id === 'string' && r.id.endsWith(CUSTOMIZATION_PACKAGE_SUFFIX)) |
| 132 | + .map((r) => ({ id: r.id as string, items: Number(r.items) })); |
| 133 | + return packages.length > 0 ? { status: 'found', filename, packages } : { status: 'none', filename }; |
| 134 | + } catch (e: any) { |
| 135 | + return { status: 'unknown', filename, detail: e?.message ?? String(e) }; |
| 136 | + } finally { |
| 137 | + try { db?.close(); } catch { /* never opened */ } |
| 138 | + } |
| 139 | +} |
| 140 | + |
| 141 | +/** |
| 142 | + * Resolve the database `os dev` opens for `projectRoot` and read its stored |
| 143 | + * `.custom` items. Never throws. |
| 144 | + */ |
| 145 | +export async function readLocalCustomizations(opts: { |
| 146 | + projectRoot: string; |
| 147 | + artifactPath?: string; |
| 148 | + env?: Record<string, string | undefined>; |
| 149 | +}): Promise<LocalCustomizationReading> { |
| 150 | + let filename: string | null; |
| 151 | + try { |
| 152 | + const { resolveProjectDatabaseUrl, sqliteFilenameFromUrl } = await import('@objectstack/runtime'); |
| 153 | + const { url } = resolveProjectDatabaseUrl({ |
| 154 | + env: opts.env ?? devDatabaseEnv(opts.projectRoot), |
| 155 | + projectRoot: opts.projectRoot, |
| 156 | + artifactPath: opts.artifactPath, |
| 157 | + }); |
| 158 | + filename = localSqliteFile(url, sqliteFilenameFromUrl); |
| 159 | + } catch { |
| 160 | + // A database selection the dev boot itself refuses: that boot reports it; |
| 161 | + // there is no file here to read. |
| 162 | + return { status: 'not_applicable' }; |
| 163 | + } |
| 164 | + if (!filename) return { status: 'not_applicable' }; |
| 165 | + return readCustomizationsFromSqlite(path.resolve(filename)); |
| 166 | +} |
| 167 | + |
| 168 | +/** |
| 169 | + * The notice lines for a reading, or `[]` when there is nothing to say. Said |
| 170 | + * once per build: what is left behind, where it lives, and the one command |
| 171 | + * that takes it out. |
| 172 | + */ |
| 173 | +export function localCustomizationNotice(reading: LocalCustomizationReading): string[] { |
| 174 | + if (reading.status === 'found') { |
| 175 | + const total = reading.packages.reduce((n, p) => n + p.items, 0); |
| 176 | + const list = reading.packages.map((p) => `${p.id} (${p.items})`).join(', '); |
| 177 | + return [ |
| 178 | + `This build does not carry ${total} Studio customization${total === 1 ? '' : 's'} stored in your dev database: ${list}.`, |
| 179 | + `They live in ${reading.filename}, not in src/, so a deployment of this artifact (or the Dockerfile) does not have them.`, |
| 180 | + 'Make the change in src/ to ship it with the app, or take it out as a package while `os dev` runs: `os package export`.', |
| 181 | + ]; |
| 182 | + } |
| 183 | + if (reading.status === 'unknown') { |
| 184 | + return [ |
| 185 | + `Could not check ${reading.filename} for Studio customizations this build leaves behind (${reading.detail}).`, |
| 186 | + 'A change saved in Studio is never in src/; `os package export` takes it out while `os dev` runs.', |
| 187 | + ]; |
| 188 | + } |
| 189 | + return []; |
| 190 | +} |
0 commit comments