@aria-framework/db-worker 0.4.2 → 0.6.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/database.js CHANGED
@@ -15,6 +15,7 @@ const fs = require('fs');
15
15
  const path = require('path');
16
16
 
17
17
  let _db = null;
18
+ let _driver = null;
18
19
  let _logger = console;
19
20
 
20
21
  /**
@@ -40,6 +41,8 @@ function init(dbPath, opts = {}) {
40
41
 
41
42
  if (typeof opts.onOpen === 'function') opts.onOpen(_db);
42
43
 
44
+
45
+
43
46
  // Performance + safety pragmas. WAL gives concurrent readers + one writer;
44
47
  // synchronous=NORMAL is the recommended pairing (FULL fsyncs every write).
45
48
  _db.pragma('journal_mode = WAL');
@@ -47,6 +50,8 @@ function init(dbPath, opts = {}) {
47
50
  _db.pragma('foreign_keys = ON');
48
51
  _db.pragma('busy_timeout = 5000');
49
52
 
53
+ _driver = _adoptSqliteDriver(_db);
54
+
50
55
  // Migration tracking table.
51
56
  _db.exec(`
52
57
  CREATE TABLE IF NOT EXISTS migrations (
@@ -65,41 +70,108 @@ function init(dbPath, opts = {}) {
65
70
  * Each migration runs inside a transaction with its tracking-row insert.
66
71
  * @param {string} migrationsDir - Directory of .sql files (numbered names)
67
72
  */
73
+ /**
74
+ * Apply pending numbered migrations, in filename order, each in its own transaction.
75
+ *
76
+ * RETURNS A PROMISE, BUT THE SQLITE PATH HAS ALREADY FINISHED BY THE TIME IT DOES — and that
77
+ * asymmetry is deliberate, not an oversight. The first consumer has 31 TOP-LEVEL call sites in
78
+ * CommonJS scripts (`database.runMigrations();` at module scope) which physically cannot await.
79
+ * Making this unconditionally async broke every one of them with "no such table: users", because
80
+ * the schema was still being created when the next line queried it.
81
+ *
82
+ * So: on SQLite the work runs synchronously and THROWS synchronously, then hands back an
83
+ * already-resolved promise — an ignored return value is safe. On Postgres it is genuinely async
84
+ * and a caller MUST await; not awaiting there fails loudly on the first query against a missing
85
+ * relation, which is the right kind of failure.
86
+ *
87
+ * The migration FILES stay app-side and app-dialect: an app owns its schema, and a portable DDL
88
+ * layer would be a leaky translation of the one thing engines differ on most. The framework
89
+ * guarantees only the LEDGER (which files ran) and the transaction around each.
90
+ *
91
+ * @returns {Promise<{applied: number}>}
92
+ */
68
93
  function runMigrations(migrationsDir) {
69
- const db = getDb();
94
+ const d = driver();
95
+ if (!d) throw new Error('runMigrations: call init()/initDriver() first');
70
96
 
71
97
  if (!migrationsDir || !fs.existsSync(migrationsDir)) {
72
98
  _logger.warn('No migrations directory found');
73
- return;
99
+ return Promise.resolve({ applied: 0 });
74
100
  }
75
-
76
- const files = fs.readdirSync(migrationsDir)
77
- .filter(f => f.endsWith('.sql'))
78
- .sort();
79
-
80
- const applied = new Set(
81
- db.prepare('SELECT filename FROM migrations').all().map(r => r.filename)
82
- );
83
-
84
- let count = 0;
85
- for (const file of files) {
86
- if (applied.has(file)) continue;
87
-
88
- const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
89
- const runMigration = db.transaction(() => {
90
- db.exec(sql);
91
- db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(file);
92
- });
93
-
94
- runMigration();
95
- count++;
96
- _logger.info(`Migration applied: ${file}`);
101
+ const files = fs.readdirSync(migrationsDir).filter((f) => f.endsWith('.sql')).sort();
102
+
103
+ // ── the synchronous path, unchanged in behaviour since 0.1.0 ──────────────────────────────
104
+ if (d.kind === 'sqlite') {
105
+ const db = d.raw;
106
+ const applied = new Set(db.prepare('SELECT filename FROM migrations').all().map((r) => r.filename));
107
+ let count = 0;
108
+ for (const file of files) {
109
+ if (applied.has(file)) continue;
110
+ const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
111
+ // One transaction per FILE, not per run: a failing migration must not roll back the ones
112
+ // that already succeeded, or a half-fixed database re-runs work it has already done.
113
+ db.transaction(() => {
114
+ db.exec(sql);
115
+ db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(file);
116
+ })();
117
+ count++;
118
+ _logger.info(`Migration applied: ${file}`);
119
+ }
120
+ _logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
121
+ return Promise.resolve({ applied: count });
97
122
  }
98
123
 
99
- _logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
124
+ // ── the async path, for engines that have no synchronous driver ───────────────────────────
125
+ return (async () => {
126
+ const applied = new Set((await d.all('SELECT filename FROM migrations')).map((r) => r.filename));
127
+ let count = 0;
128
+ for (const file of files) {
129
+ if (applied.has(file)) continue;
130
+ const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf8');
131
+ await d.transaction(async (tx) => {
132
+ await tx.exec(sql);
133
+ await tx.run('INSERT INTO migrations (filename) VALUES (?)', [file]);
134
+ });
135
+ count++;
136
+ _logger.info(`Migration applied: ${file}`);
137
+ }
138
+ _logger.info(count === 0 ? 'No pending migrations' : `Applied ${count} migration(s)`);
139
+ return { applied: count };
140
+ })();
141
+ }
142
+
143
+ /**
144
+ * Wrap an ALREADY-OPEN better-sqlite3 handle in the driver contract.
145
+ *
146
+ * The legacy init() path opens and configures the handle itself, so the driver must adopt it
147
+ * rather than open a second one — two connections to the same file is how you get a writer
148
+ * fighting its own lock.
149
+ */
150
+ function _adoptSqliteDriver(db) {
151
+ const { dialectFor } = require('./dialect');
152
+ const stmt = (sql) => db.prepare(sql);
153
+ const api = {
154
+ kind: 'sqlite',
155
+ dialect: dialectFor('sqlite'),
156
+ concurrency: 'serial',
157
+ raw: db,
158
+ async get(sql, params = []) { return stmt(sql).get(...params) || null; },
159
+ async all(sql, params = []) { return stmt(sql).all(...params); },
160
+ async run(sql, params = []) {
161
+ const info = stmt(sql).run(...params);
162
+ return { changes: info.changes, lastId: info.lastInsertRowid };
163
+ },
164
+ async exec(sql) { db.exec(sql); },
165
+ async transaction(fn) {
166
+ db.exec('BEGIN');
167
+ try { const out = await fn(api); db.exec('COMMIT'); return out; }
168
+ catch (e) { try { db.exec('ROLLBACK'); } catch (_) {} throw e; }
169
+ },
170
+ async close() { db.close(); }
171
+ };
172
+ return api;
100
173
  }
101
174
 
102
- /** Get the database instance. Throws if not initialized. */
103
175
  function getDb() {
104
176
  if (!_db) throw new Error('Database not initialized. Call init() first.');
105
177
  return _db;
@@ -114,4 +186,55 @@ function close() {
114
186
  }
115
187
  }
116
188
 
117
- module.exports = { init, runMigrations, getDb, close };
189
+ /**
190
+ * The DRIVER behind this database — the async, engine-agnostic contract stores are written
191
+ * against (0.6.0). `getDb()` still returns the raw better-sqlite3 handle and always will: 400+
192
+ * synchronous call sites in the first consumer depend on it, and breaking them to gain an
193
+ * abstraction they do not use would be the tail wagging the dog. The two coexist deliberately —
194
+ * app code keeps its handle, framework stores take the driver.
195
+ *
196
+ * Null until init(). The worker reads `.concurrency` off it to decide whether to serialise
197
+ * invokes, and treats a missing driver as 'serial' — the safe default.
198
+ */
199
+ function driver() {
200
+ return _driver;
201
+ }
202
+
203
+ /**
204
+ * Open a database through the DRIVER contract instead of the legacy sqlite path.
205
+ * `initDriver({ kind: 'postgres', connectionString })` is how a Postgres-native app boots;
206
+ * `kind: 'sqlite'` is identical to init() but hands back the driver as well.
207
+ */
208
+ async function ensureMigrationsTable() {
209
+ const d = driver();
210
+ const t = d.dialect;
211
+ // The LEDGER is the one table the framework owns, so it is the one DDL that must be
212
+ // dialect-aware. Everything else is the app's.
213
+ await d.exec(`
214
+ CREATE TABLE IF NOT EXISTS migrations (
215
+ id ${t.autoIncrementPk()},
216
+ filename TEXT NOT NULL UNIQUE,
217
+ applied_at TEXT NOT NULL DEFAULT (${t.now()})
218
+ )`);
219
+ }
220
+
221
+ async function initDriver(opts = {}) {
222
+ const kind = opts.kind || 'sqlite';
223
+ if (kind === 'sqlite') {
224
+ const { createSqliteDriver } = require('./driver/sqlite');
225
+ _driver = createSqliteDriver(opts);
226
+ _db = _driver.raw; // keep getDb() working for app code
227
+ } else if (kind === 'postgres') {
228
+ const { createPostgresDriver } = require('./driver/postgres');
229
+ _driver = createPostgresDriver(opts);
230
+ _db = null; // there IS no synchronous handle; getDb() must throw
231
+ } else {
232
+ throw new Error(`initDriver: unknown kind '${kind}'`);
233
+ }
234
+ await ensureMigrationsTable();
235
+ _logger = opts.logger || _logger;
236
+ _logger.info(`Database opened (${kind})`);
237
+ return _driver;
238
+ }
239
+
240
+ module.exports = { init, initDriver, runMigrations, getDb, driver, close };
package/dialect.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The SQL differences between SQLite and PostgreSQL, NAMED rather than scattered.
3
+ *
4
+ * A store writes `d.now()` instead of `datetime('now')`, so the divergence lives in one
5
+ * reviewable file instead of 159 call sites. Everything NOT in here is deliberately absent
6
+ * because both engines already agree on it — and that list is longer than it looks:
7
+ *
8
+ * - `ON CONFLICT (...) DO UPDATE/NOTHING` is standard in both (SQLite since 3.24; the
9
+ * framework requires far newer). So there is no `insertOrIgnore()` here — stores write the
10
+ * portable form and `INSERT OR IGNORE` never appears.
11
+ * - LIMIT/OFFSET, CTEs, window functions, `COUNT(*) FILTER (WHERE …)` — all shared.
12
+ * - Placeholders are NOT a dialect concern: stores always write `?` and the driver rewrites
13
+ * to `$1…$n` for pg (see driver/postgres.js, which scans string literals properly rather
14
+ * than blindly replacing).
15
+ *
16
+ * TIMESTAMPS ARE THE ONE MODELLING DECISION, not just a syntax swap. SQLite has no date type
17
+ * and this framework stores `YYYY-MM-DD HH:MM:SS` UTC text; Postgres has real `timestamptz`.
18
+ * `now()` therefore emits each engine's native value and a store must COMPARE using the same
19
+ * helpers (`now()`, `nowMinusDays()`) rather than hand-built strings — mixing a literal
20
+ * '2026-01-01' comparison with a timestamptz column is the silent-wrong-answer this prevents.
21
+ */
22
+
23
+ 'use strict';
24
+
25
+ /** Quote an identifier. Both engines accept double quotes; this exists so callers never hand-roll. */
26
+ const ident = (name) => `"${String(name).replace(/"/g, '""')}"`;
27
+
28
+ const sqlite = {
29
+ kind: 'sqlite',
30
+ ident,
31
+ /** Current UTC timestamp, in this engine's native form. */
32
+ now: () => "datetime('now')",
33
+ /** N whole days before now — used by retention cuts. */
34
+ nowMinusDays: (n) => `datetime('now', '-${Number(n)} days')`,
35
+ /** Native timestamp type. SQLite has none, so this is the same text value. */
36
+ nowTz: () => "datetime('now')",
37
+ /** Read a JSON path out of a column: jsonPath('detail', '$.model'). */
38
+ jsonPath: (col, path) => `json_extract(${col}, '${String(path).replace(/'/g, "''")}')`,
39
+ /** Case-insensitive LIKE. SQLite's LIKE is already case-insensitive for ASCII. */
40
+ ilike: () => 'LIKE',
41
+ /** Suffix that makes run() report a new row's id. SQLite reports it out of band. */
42
+ returning: () => '',
43
+ /** DDL fragment for an auto-incrementing primary key (only secure-keystore needs this). */
44
+ autoIncrementPk: () => 'INTEGER PRIMARY KEY AUTOINCREMENT',
45
+ /** Portable-ish text column. */
46
+ textType: () => 'TEXT'
47
+ };
48
+
49
+ const postgres = {
50
+ kind: 'postgres',
51
+ ident,
52
+ // TEXT, not timestamptz — and the live contract suite is why. Every framework store inherited
53
+ // TEXT timestamps from SQLite (`YYYY-MM-DD HH:MM:SS` UTC), and `NOW()` returns timestamptz,
54
+ // so `created_at < NOW()` failed outright with "operator does not exist: text < timestamp
55
+ // with time zone". Emitting the same text shape on both engines keeps one store SQL correct
56
+ // for both; an app wanting a real timestamptz column in its OWN tables uses nowTz().
57
+ now: () => "to_char(NOW() AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')",
58
+ nowMinusDays: (n) => `to_char((NOW() - INTERVAL '${Number(n)} days') AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS')`,
59
+ /** Native timestamptz, for an app that declares real timestamp columns. */
60
+ nowTz: () => 'NOW()',
61
+ // The ::jsonb cast is load-bearing: `->>` is not defined on TEXT, and the framework's JSON
62
+ // columns are TEXT by SQLite heritage ("operator does not exist: text ->> unknown"). On a
63
+ // column already declared jsonb the cast is a no-op, so an app SHOULD declare jsonb for
64
+ // indexability without this needing to know which it got.
65
+ jsonPath: (col, path) => {
66
+ const key = String(path).replace(/^\$\./, '');
67
+ if (key.includes('.') || key.includes('[')) {
68
+ const parts = key.replace(/\[\]$/, '').split('.').map((p) => p.replace(/'/g, "''"));
69
+ return `((${col})::jsonb #>> '{${parts.join(',')}}')`;
70
+ }
71
+ return `((${col})::jsonb ->> '${key.replace(/'/g, "''")}')`;
72
+ },
73
+ ilike: () => 'ILIKE',
74
+ returning: (col = 'id') => ` RETURNING ${ident(col)}`,
75
+ autoIncrementPk: () => 'BIGSERIAL PRIMARY KEY',
76
+ textType: () => 'TEXT'
77
+ };
78
+
79
+ function dialectFor(kind) {
80
+ if (kind === 'sqlite') return sqlite;
81
+ if (kind === 'postgres') return postgres;
82
+ throw new Error(`dialectFor: unknown driver kind '${kind}' (expected 'sqlite' or 'postgres')`);
83
+ }
84
+
85
+ module.exports = { dialectFor, sqlite, postgres };
@@ -0,0 +1,163 @@
1
+ /**
2
+ * The PostgreSQL driver — `pg` behind the same async driver contract as SQLite.
3
+ *
4
+ * CONCURRENCY IS 'pool', which is the point of using it. Where the SQLite driver serialises
5
+ * (single writer, so nothing is lost by it), this one runs invokes concurrently against a
6
+ * connection pool — and `transaction()` takes a DEDICATED client for its whole duration, so
7
+ * concurrent work can never interleave inside somebody else's BEGIN.
8
+ *
9
+ * PLACEHOLDERS. Stores write `?` because that is what the SQLite half has always used and
10
+ * rewriting 400 call sites to `$1` would be the tail wagging the dog. Converting them is NOT a
11
+ * blind replace: a `?` inside a string literal ('what?') must survive untouched, so the
12
+ * rewriter scans the statement and tracks quote state, including doubled '' escapes and
13
+ * dollar-quoted bodies. Getting that wrong corrupts data silently rather than erroring, which
14
+ * is why it has its own tests.
15
+ *
16
+ * `pg` is an OPTIONAL PEER — a SQLite-only consumer (Support101) must never install it.
17
+ */
18
+
19
+ 'use strict';
20
+
21
+ const { dialectFor } = require('../dialect');
22
+
23
+ /**
24
+ * Rewrite `?` placeholders to `$1..$n`, leaving any `?` inside a literal alone.
25
+ *
26
+ * Handles: single-quoted strings with '' escapes, double-quoted identifiers, line comments,
27
+ * block comments, and $tag$ dollar-quoted bodies. Anything else is ordinary SQL.
28
+ */
29
+ function toDollarParams(sql) {
30
+ let out = '';
31
+ let n = 0;
32
+ let i = 0;
33
+ while (i < sql.length) {
34
+ const c = sql[i];
35
+
36
+ if (c === "'") { // string literal, '' is an escaped quote
37
+ let j = i + 1;
38
+ while (j < sql.length) {
39
+ if (sql[j] === "'" && sql[j + 1] === "'") { j += 2; continue; }
40
+ if (sql[j] === "'") break;
41
+ j++;
42
+ }
43
+ out += sql.slice(i, j + 1); i = j + 1; continue;
44
+ }
45
+ if (c === '"') { // quoted identifier
46
+ const j = sql.indexOf('"', i + 1);
47
+ const end = j === -1 ? sql.length - 1 : j;
48
+ out += sql.slice(i, end + 1); i = end + 1; continue;
49
+ }
50
+ if (c === '-' && sql[i + 1] === '-') { // line comment
51
+ const j = sql.indexOf('\n', i);
52
+ const end = j === -1 ? sql.length : j;
53
+ out += sql.slice(i, end); i = end; continue;
54
+ }
55
+ if (c === '/' && sql[i + 1] === '*') { // block comment
56
+ const j = sql.indexOf('*/', i + 2);
57
+ const end = j === -1 ? sql.length : j + 2;
58
+ out += sql.slice(i, end); i = end; continue;
59
+ }
60
+ if (c === '$') { // dollar-quoted body: $tag$ … $tag$
61
+ const m = /^\$[A-Za-z_0-9]*\$/.exec(sql.slice(i));
62
+ if (m) {
63
+ const tag = m[0];
64
+ const j = sql.indexOf(tag, i + tag.length);
65
+ const end = j === -1 ? sql.length : j + tag.length;
66
+ out += sql.slice(i, end); i = end; continue;
67
+ }
68
+ }
69
+ if (c === '?') { out += '$' + (++n); i++; continue; }
70
+
71
+ out += c; i++;
72
+ }
73
+ return out;
74
+ }
75
+
76
+ /**
77
+ * @param {object} opts
78
+ * connectionString postgres://user:pass@host:port/db (required unless host/user/… given)
79
+ * pool extra node-postgres Pool options (max, idleTimeoutMillis, ssl…)
80
+ * logger needs .info/.warn/.error
81
+ */
82
+ function createPostgresDriver(opts = {}) {
83
+ let pg;
84
+ try {
85
+ pg = require('pg');
86
+ } catch (e) {
87
+ throw new Error(
88
+ 'createPostgresDriver: `pg` is not installed. It is an optional peer — add it to the ' +
89
+ 'consuming app, or use the sqlite driver. (' + e.message + ')'
90
+ );
91
+ }
92
+ if (!opts.connectionString && !opts.host) {
93
+ throw new Error('createPostgresDriver({ connectionString }): a connection string (or host/user/database) is required');
94
+ }
95
+
96
+ const pool = new pg.Pool({
97
+ connectionString: opts.connectionString,
98
+ ...(opts.pool || {})
99
+ });
100
+
101
+ /** Build the contract over either the pool or one checked-out client (inside a transaction). */
102
+ const apiOver = (exec, extra = {}) => ({
103
+ kind: 'postgres',
104
+ dialect: dialectFor('postgres'),
105
+ concurrency: 'pool',
106
+
107
+ async get(sql, params = []) {
108
+ const r = await exec(toDollarParams(sql), params);
109
+ return r.rows[0] || null;
110
+ },
111
+ async all(sql, params = []) {
112
+ const r = await exec(toDollarParams(sql), params);
113
+ return r.rows;
114
+ },
115
+ /**
116
+ * `lastId` comes from a RETURNING clause. A store that needs the new id appends
117
+ * `d.returning('id')`, which is empty on SQLite (where it arrives out of band) and
118
+ * ` RETURNING "id"` here — so the store's SQL stays one string for both engines.
119
+ */
120
+ async run(sql, params = []) {
121
+ const r = await exec(toDollarParams(sql), params);
122
+ const row = r.rows && r.rows[0];
123
+ const lastId = row ? (row.id !== undefined ? row.id : Object.values(row)[0]) : undefined;
124
+ return { changes: r.rowCount, lastId };
125
+ },
126
+ async exec(sql) {
127
+ await exec(sql); // DDL: never parameterised, so no rewrite
128
+ },
129
+ ...extra
130
+ });
131
+
132
+ const poolApi = apiOver((sql, params) => pool.query(sql, params), {
133
+ /**
134
+ * A dedicated client for the whole transaction. Without this, a pooled query from another
135
+ * concurrent invoke could land between the BEGIN and the COMMIT — the same interleaving
136
+ * hazard the SQLite driver avoids by serialising, solved here the way Postgres intends.
137
+ */
138
+ async transaction(fn) {
139
+ const client = await pool.connect();
140
+ const txApi = apiOver((sql, params) => client.query(sql, params), {
141
+ // Nested transaction() reuses the same client rather than deadlocking on a second one.
142
+ transaction: (inner) => inner(txApi)
143
+ });
144
+ try {
145
+ await client.query('BEGIN');
146
+ const out = await fn(txApi);
147
+ await client.query('COMMIT');
148
+ return out;
149
+ } catch (e) {
150
+ try { await client.query('ROLLBACK'); } catch (_) { /* the original error is what matters */ }
151
+ throw e;
152
+ } finally {
153
+ client.release();
154
+ }
155
+ },
156
+ async close() { await pool.end(); },
157
+ raw: pool
158
+ });
159
+
160
+ return poolApi;
161
+ }
162
+
163
+ module.exports = { createPostgresDriver, toDollarParams };
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The SQLite driver — better-sqlite3 behind the async driver contract.
3
+ *
4
+ * Synchronous underneath, Promise-returning on the surface. That is not a wrapper for its own
5
+ * sake: it lets every store be written ONCE, async, against one contract, and the SQLite path
6
+ * pays only a microtask for it.
7
+ *
8
+ * CONCURRENCY IS 'serial', AND THAT IS A CORRECTNESS REQUIREMENT, not a performance choice.
9
+ * Before the stores went async, a model method ran to completion before the worker handled the
10
+ * next message — transactions were atomic by construction. The moment a store awaits, a second
11
+ * queued invoke can interleave BETWEEN statements, and if either is mid-transaction the
12
+ * atomicity is gone. The worker honours `concurrency` by processing one invoke at a time for
13
+ * this driver. Nothing is lost: SQLite is single-writer regardless.
14
+ *
15
+ * better-sqlite3 stays an OPTIONAL PEER — a Postgres-only consumer must not build a native
16
+ * module it never opens.
17
+ */
18
+
19
+ 'use strict';
20
+
21
+ const fs = require('fs');
22
+ const path = require('path');
23
+ const { dialectFor } = require('../dialect');
24
+
25
+ /**
26
+ * @param {object} opts
27
+ * path database file (required)
28
+ * onOpen (db) => void, BEFORE pragmas — the SQLCipher `pragma key` hook
29
+ * logger needs .info/.warn/.error
30
+ * pragmas override/extend the defaults
31
+ */
32
+ function createSqliteDriver(opts = {}) {
33
+ if (!opts.path) throw new Error("createSqliteDriver({ path }): the database file path is required");
34
+ let Database;
35
+ try {
36
+ Database = require('better-sqlite3');
37
+ } catch (e) {
38
+ throw new Error(
39
+ 'createSqliteDriver: better-sqlite3 is not installed. It is an optional peer — add it to ' +
40
+ 'the consuming app, or use the postgres driver. (' + e.message + ')'
41
+ );
42
+ }
43
+
44
+ const dir = path.dirname(opts.path);
45
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
46
+
47
+ const db = new Database(opts.path);
48
+ // BEFORE the pragmas: an encrypted database must be keyed before it will answer anything.
49
+ if (typeof opts.onOpen === 'function') opts.onOpen(db);
50
+
51
+ const pragmas = {
52
+ journal_mode: 'WAL', // concurrent readers + one writer
53
+ synchronous: 'NORMAL', // the recommended pairing with WAL (FULL fsyncs every write)
54
+ foreign_keys: 'ON',
55
+ busy_timeout: 5000,
56
+ ...(opts.pragmas || {})
57
+ };
58
+ for (const [k, v] of Object.entries(pragmas)) db.pragma(`${k} = ${v}`);
59
+
60
+ const stmt = (sql) => db.prepare(sql);
61
+
62
+ const api = {
63
+ kind: 'sqlite',
64
+ dialect: dialectFor('sqlite'),
65
+ concurrency: 'serial',
66
+ /** The raw handle, for the few things that genuinely need it (backup's VACUUM INTO). */
67
+ raw: db,
68
+
69
+ async get(sql, params = []) {
70
+ return stmt(sql).get(...params) || null;
71
+ },
72
+ async all(sql, params = []) {
73
+ return stmt(sql).all(...params);
74
+ },
75
+ async run(sql, params = []) {
76
+ const info = stmt(sql).run(...params);
77
+ return { changes: info.changes, lastId: info.lastInsertRowid };
78
+ },
79
+ /** Multi-statement DDL. Never parameterised — migrations only. */
80
+ async exec(sql) {
81
+ db.exec(sql);
82
+ },
83
+
84
+ /**
85
+ * Transactions are run with explicit BEGIN/COMMIT rather than better-sqlite3's
86
+ * `db.transaction(fn)`, because that helper REFUSES an async callback — and every callback
87
+ * here is async by contract. Safe only because this driver declares 'serial': nothing else
88
+ * can issue a statement between the BEGIN and the COMMIT.
89
+ */
90
+ async transaction(fn) {
91
+ db.exec('BEGIN');
92
+ try {
93
+ const out = await fn(api);
94
+ db.exec('COMMIT');
95
+ return out;
96
+ } catch (e) {
97
+ try { db.exec('ROLLBACK'); } catch (_) { /* the failure that matters is the original */ }
98
+ throw e;
99
+ }
100
+ },
101
+
102
+ async close() {
103
+ db.close();
104
+ }
105
+ };
106
+ return api;
107
+ }
108
+
109
+ module.exports = { createSqliteDriver };
package/index.js CHANGED
@@ -9,8 +9,25 @@
9
9
  * runMigrations(dir) + getDb() + close(). Singleton per thread.
10
10
  */
11
11
 
12
+ // 0.6.0 — MULTI-ENGINE. The driver contract (get/all/run/exec/transaction + dialect +
13
+ // concurrency) lets a store be written once and run on either engine, selected per APP. SQLite
14
+ // stays the default and Support101 never moves; app 3 boots with kind:'postgres'. `pg` and
15
+ // better-sqlite3 are both OPTIONAL peers — neither consumer installs the other's driver.
16
+ const { createSqliteDriver } = require('./driver/sqlite');
17
+ const { createPostgresDriver } = require('./driver/postgres');
18
+ const { dialectFor } = require('./dialect');
19
+
12
20
  module.exports = {
21
+ createSqliteDriver,
22
+ createPostgresDriver,
23
+ dialectFor,
13
24
  DbClient: require('./client').DbClient,
14
25
  runWorker: require('./worker').runWorker,
15
- database: require('./database')
26
+ database: require('./database'),
27
+ // 0.5.0 — Tier-2 extractions (2026-08-22 audit): the PRAGMA/schema utilities and the KV store
28
+ // both apps carried, plus the guard for this package's own registry contract.
29
+ ...require('./tableOrder'),
30
+ ...require('./schemaSnapshot'),
31
+ ...require('./workerRegistry'),
32
+ ...require('./settingsStore')
16
33
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.4.2",
3
+ "version": "0.6.0",
4
4
  "description": "Aria App Framework — db-worker module. Async RPC bridge over synchronous better-sqlite3: a worker-thread dispatcher (runWorker), a main-thread client with per-call timeouts and crash handling (DbClient), and a SQLite layer with WAL pragmas + a numbered-migration runner (database).",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -12,12 +12,27 @@
12
12
  "index.js",
13
13
  "database.js",
14
14
  "worker.js",
15
- "client.js"
15
+ "client.js",
16
+ "tableOrder.js",
17
+ "schemaSnapshot.js",
18
+ "workerRegistry.js",
19
+ "settingsStore.js",
20
+ "dialect.js",
21
+ "driver/"
16
22
  ],
17
23
  "peerDependencies": {
18
- "better-sqlite3": ">=9"
24
+ "better-sqlite3": ">=9",
25
+ "pg": ">=8"
26
+ },
27
+ "peerDependenciesMeta": {
28
+ "better-sqlite3": { "optional": true },
29
+ "pg": { "optional": true }
19
30
  },
20
31
  "devDependencies": {
21
- "better-sqlite3": "^12.10.0"
32
+ "better-sqlite3": "^12.10.0",
33
+ "pg": "^8.23.0"
34
+ },
35
+ "scripts": {
36
+ "test": "node test/driverContract.js && node test/migrations.js && node test/smoke.js && node test/tier2.js"
22
37
  }
23
38
  }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Schema snapshot + structural diff + build-from-migrations — the tooling a migration SQUASH
3
+ * needs, and the drift detector it leaves behind.
4
+ *
5
+ * BE HONEST ABOUT WHAT A SNAPSHOT COMPARISON PROVES. Comparing a squashed baseline against the
6
+ * original chain proves squash fidelity — but only while the chain still exists. Once the chain
7
+ * is deleted and the snapshot is regenerated from the baseline, the same comparison is a DRIFT
8
+ * DETECTOR (someone hand-editing the baseline instead of adding a migration), not a proof of
9
+ * fidelity. Support101 learned this across two releases; document which one your fixture is.
10
+ *
11
+ * better-sqlite3 arrives via the package's peer dependency, same as database.js.
12
+ */
13
+
14
+ 'use strict';
15
+
16
+ const fs = require('fs');
17
+ const os = require('os');
18
+ const path = require('path');
19
+
20
+ /** Normalise whitespace so formatting differences are not reported as drift. */
21
+ const norm = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim();
22
+
23
+ /**
24
+ * Everything that defines the shape of a database, in a comparable form: tables (columns with
25
+ * type/notnull/default/pk, FK list, index list with uniqueness), named indexes, triggers, views,
26
+ * and SEED DATA (any table with content on a fresh build — a baseline that omits it produces a
27
+ * broken install), with timestamp columns excluded because they differ per build. The
28
+ * `migrations` table is excluded — two builds legitimately record different filenames.
29
+ *
30
+ * @param {string} dbPath
31
+ * @param {{Database?: Function, timestampColumns?: RegExp}} [opts]
32
+ */
33
+ function snapshotSchema(dbPath, opts = {}) {
34
+ const Database = opts.Database || require('better-sqlite3');
35
+ const tsRe = opts.timestampColumns || /^(created_at|updated_at|applied_at)$/;
36
+ const db = new Database(dbPath, { readonly: true });
37
+ const out = { tables: {}, indexes: {}, triggers: {}, views: {}, data: {} };
38
+
39
+ const objects = db.prepare(
40
+ "SELECT type, name, tbl_name, sql FROM sqlite_master WHERE name NOT LIKE 'sqlite_%' ORDER BY type, name"
41
+ ).all();
42
+
43
+ for (const o of objects) {
44
+ if (o.name === 'migrations' || o.tbl_name === 'migrations') continue;
45
+ if (o.type === 'trigger') { out.triggers[o.name] = norm(o.sql); continue; }
46
+ if (o.type === 'view') { out.views[o.name] = norm(o.sql); continue; }
47
+ if (o.type === 'index') {
48
+ // Auto-indexes have no SQL; they are captured via index_list below instead.
49
+ if (o.sql) out.indexes[o.name] = norm(o.sql);
50
+ continue;
51
+ }
52
+ if (o.type !== 'table') continue;
53
+
54
+ out.tables[o.name] = {
55
+ columns: db.prepare(`PRAGMA table_info(${JSON.stringify(o.name)})`).all()
56
+ .map((c) => ({ name: c.name, type: norm(c.type).toUpperCase(), notnull: c.notnull, dflt: norm(c.dflt_value), pk: c.pk })),
57
+ foreignKeys: db.prepare(`PRAGMA foreign_key_list(${JSON.stringify(o.name)})`).all()
58
+ .map((f) => ({ table: f.table, from: f.from, to: f.to, onDelete: f.on_delete, onUpdate: f.on_update }))
59
+ .sort((a, b) => (a.from + a.table).localeCompare(b.from + b.table)),
60
+ indexList: db.prepare(`PRAGMA index_list(${JSON.stringify(o.name)})`).all()
61
+ .map((i) => ({
62
+ name: i.name, unique: i.unique, partial: i.partial,
63
+ columns: db.prepare(`PRAGMA index_info(${JSON.stringify(i.name)})`).all().map((c) => c.name)
64
+ }))
65
+ .sort((a, b) => a.name.localeCompare(b.name))
66
+ };
67
+ }
68
+
69
+ for (const name of Object.keys(out.tables)) {
70
+ const n = db.prepare(`SELECT COUNT(*) AS c FROM ${JSON.stringify(name)}`).get().c;
71
+ if (!n) continue;
72
+ const cols = out.tables[name].columns.map((c) => c.name).filter((c) => !tsRe.test(c));
73
+ if (!cols.length) continue;
74
+ const order = cols.map((c) => JSON.stringify(c)).join(', ');
75
+ out.data[name] = db.prepare(
76
+ `SELECT ${cols.map((c) => JSON.stringify(c)).join(', ')} FROM ${JSON.stringify(name)} ORDER BY ${order}`
77
+ ).all();
78
+ }
79
+
80
+ db.close();
81
+ return out;
82
+ }
83
+
84
+ /**
85
+ * Human-readable FIRST difference between two snapshots, or null when identical. One readable
86
+ * path beats a JSON dump — the point is telling a person what moved.
87
+ * @param {*} a @param {*} b
88
+ * @param {{aLabel?: string, bLabel?: string}} [labels]
89
+ */
90
+ function firstDifference(a, b, labels = {}, pathStr = '') {
91
+ const aL = labels.aLabel || 'a';
92
+ const bL = labels.bLabel || 'b';
93
+ const ja = JSON.stringify(a), jb = JSON.stringify(b);
94
+ if (ja === jb) return null;
95
+ if (a && b && typeof a === 'object' && typeof b === 'object' && !Array.isArray(a) && !Array.isArray(b)) {
96
+ for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) {
97
+ if (!(k in a)) return `${pathStr}.${k}: MISSING from the ${aL} build`;
98
+ if (!(k in b)) return `${pathStr}.${k}: MISSING from the ${bL} build`;
99
+ const d = firstDifference(a[k], b[k], labels, `${pathStr}.${k}`);
100
+ if (d) return d;
101
+ }
102
+ }
103
+ return `${pathStr}:\n ${aL} = ${ja.slice(0, 400)}\n ${bL} = ${jb.slice(0, 400)}`;
104
+ }
105
+
106
+ /**
107
+ * Apply a list of .sql files to a fresh temp database and return its path. Reproduces the
108
+ * migration runner's own `migrations` table so migrations that touch it behave.
109
+ * @param {string[]} files absolute paths, in order
110
+ * @param {{Database?: Function, label?: string}} [opts]
111
+ */
112
+ function buildFromMigrations(files, opts = {}) {
113
+ const Database = opts.Database || require('better-sqlite3');
114
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), `aria-mig-${opts.label || 'build'}-`));
115
+ const dbPath = path.join(dir, 'db.sqlite');
116
+ const db = new Database(dbPath);
117
+ db.exec("CREATE TABLE IF NOT EXISTS migrations (id INTEGER PRIMARY KEY, filename TEXT NOT NULL UNIQUE, applied_at TEXT NOT NULL DEFAULT (datetime('now')))");
118
+ for (const f of files) {
119
+ const sql = fs.readFileSync(f, 'utf8');
120
+ const run = db.transaction(() => {
121
+ db.exec(sql);
122
+ db.prepare('INSERT INTO migrations (filename) VALUES (?)').run(path.basename(f));
123
+ });
124
+ run();
125
+ }
126
+ db.close();
127
+ return dbPath;
128
+ }
129
+
130
+ module.exports = { snapshotSchema, firstDifference, buildFromMigrations };
@@ -0,0 +1,82 @@
1
+ /**
2
+ * createSettingsStore — the key/value settings table both apps carried (one as `settings`, one as
3
+ * `app_settings`), reduced to one store with the differences as options.
4
+ *
5
+ * UPSERT IS ALWAYS `ON CONFLICT DO UPDATE`, never `INSERT OR REPLACE`. They are not equivalent:
6
+ * OR REPLACE deletes the row and reinserts it, which FIRES DELETE TRIGGERS and drops any column
7
+ * the insert does not name. One consumer used each; standardising on the non-destructive form is
8
+ * part of the extraction, not an accident of it.
9
+ *
10
+ * The typed accessors (session-timeout parsing, brand-name defaults, currency tables) are app
11
+ * CONTENT and stay in the consuming model, which keeps this store as its base.
12
+ */
13
+
14
+ 'use strict';
15
+
16
+ /**
17
+ * @param {{getDb: () => object, table?: string, touchUpdatedAt?: boolean}} opts
18
+ * touchUpdatedAt: set true when the table carries an updated_at column to stamp on write.
19
+ */
20
+ function createSettingsStore(opts = {}) {
21
+ const getDb = opts.getDb;
22
+ if (typeof getDb !== 'function') throw new Error('createSettingsStore({ getDb }): pass a function returning the open db');
23
+ const table = opts.table || 'settings';
24
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) throw new Error(`createSettingsStore: suspicious table name "${table}"`);
25
+ const touch = opts.touchUpdatedAt
26
+ ? ", updated_at = datetime('now')"
27
+ : '';
28
+ const insertCols = opts.touchUpdatedAt ? '(key, value, updated_at)' : '(key, value)';
29
+ const insertVals = opts.touchUpdatedAt ? "(?, ?, datetime('now'))" : '(?, ?)';
30
+ const upsert = `INSERT INTO ${table} ${insertCols} VALUES ${insertVals}
31
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value${touch}`;
32
+
33
+ return {
34
+ /** Raw value (string) or null if unset. */
35
+ get(key) {
36
+ const row = getDb().prepare(`SELECT value FROM ${table} WHERE key = ?`).get(key);
37
+ return row ? row.value : null;
38
+ },
39
+
40
+ /** Upsert one setting (non-destructive; see the header). */
41
+ set(key, value) {
42
+ return getDb().prepare(upsert).run(key, value == null ? null : String(value));
43
+ },
44
+
45
+ /**
46
+ * Upsert several settings in ONE transaction. `undefined` values are skipped (an absent form
47
+ * field is not a request to clear); null is stored as null.
48
+ */
49
+ setMultiple(keyValues) {
50
+ const db = getDb();
51
+ const stmt = db.prepare(upsert);
52
+ const run = db.transaction(() => {
53
+ for (const [key, value] of Object.entries(keyValues || {})) {
54
+ if (value !== undefined) stmt.run(key, value == null ? null : String(value));
55
+ }
56
+ });
57
+ run();
58
+ },
59
+
60
+ /**
61
+ * All settings whose key starts with `prefix`, as { key: value }. The prefix is LIKE-ESCAPED:
62
+ * `_` is a LIKE wildcard, so an unescaped 'company_' would also match 'companyXname' — a
63
+ * latent bug in the hand-rolled version this replaces.
64
+ */
65
+ getByPrefix(prefix) {
66
+ const esc = String(prefix).replace(/[\\%_]/g, (c) => '\\' + c);
67
+ const rows = getDb()
68
+ .prepare(`SELECT key, value FROM ${table} WHERE key LIKE ? ESCAPE '\\'`)
69
+ .all(esc + '%');
70
+ const out = {};
71
+ for (const r of rows) out[r.key] = r.value;
72
+ return out;
73
+ },
74
+
75
+ /** All settings as an array of { key, value }, ordered by key. */
76
+ all() {
77
+ return getDb().prepare(`SELECT key, value FROM ${table} ORDER BY key`).all();
78
+ }
79
+ };
80
+ }
81
+
82
+ module.exports = { createSettingsStore };
package/tableOrder.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Order tables PARENTS FIRST by foreign-key dependency (PRAGMA foreign_key_list).
3
+ *
4
+ * Extracted from Support101's fixture tooling, where the exporter and loader each once had their
5
+ * own copy that disagreed on cycle handling: the loader threw and named the cycle, the exporter
6
+ * appended the remainder in arbitrary order — producing a fixture whose table order made the
7
+ * loader fail LATER with an opaque foreign-key error instead of naming the problem at export
8
+ * time. Throwing is correct for both: a set that cannot be ordered cannot be loaded, so finding
9
+ * out early is strictly better. (The sibling app hand-maintains the same ordering as a comment in
10
+ * a wipe script — the exact drift this function exists to end.)
11
+ */
12
+
13
+ 'use strict';
14
+
15
+ /**
16
+ * @param {object} db better-sqlite3 handle (for PRAGMA foreign_key_list)
17
+ * @param {string[]} names tables to order
18
+ * @returns {string[]} the same names, parents before children
19
+ * @throws if the foreign keys among `names` contain a cycle
20
+ */
21
+ function orderByDependency(db, names) {
22
+ const set = new Set(names);
23
+ const deps = new Map();
24
+ for (const t of names) {
25
+ const fks = db.prepare(`PRAGMA foreign_key_list(${JSON.stringify(t)})`).all();
26
+ // Self-references are ignored: a row pointing at its own table cannot be resolved by
27
+ // ordering, and treating it as a dependency would look like a cycle.
28
+ deps.set(t, new Set(fks.map((f) => f.table).filter((n) => n !== t && set.has(n))));
29
+ }
30
+
31
+ const out = [];
32
+ const done = new Set();
33
+ let guard = 0;
34
+ while (out.length < names.length) {
35
+ if (++guard > names.length + 5) {
36
+ const left = names.filter((n) => !done.has(n));
37
+ throw new Error(`circular foreign keys among: ${left.join(', ')}`);
38
+ }
39
+ for (const t of names) {
40
+ if (done.has(t)) continue;
41
+ if ([...deps.get(t)].every((d) => done.has(d))) { out.push(t); done.add(t); }
42
+ }
43
+ }
44
+ return out;
45
+ }
46
+
47
+ module.exports = { orderByDependency };
package/worker.js CHANGED
@@ -24,17 +24,53 @@ const { performance } = require('perf_hooks');
24
24
  * @param {Object} opts
25
25
  * @param {(workerData: any) => Object} opts.init - App boot; returns the model registry
26
26
  */
27
- function runWorker({ init }) {
27
+ async function runWorker({ init }) {
28
28
  if (typeof init !== 'function') {
29
29
  throw new Error('runWorker({ init }): init must be a function (workerData) => modelRegistry');
30
30
  }
31
31
 
32
32
  try {
33
- const models = init(workerData) || {};
33
+ // AWAITED since 0.6.0. An app's init opens the database and runs migrations, and on
34
+ // Postgres both of those are async — an un-awaited init would hand back a Promise as the
35
+ // model registry and serve queries against an unmigrated database. `await` on a synchronous
36
+ // init returns the same object it always did, so the SQLite path is unchanged.
37
+ const models = (await init(workerData)) || {};
34
38
 
35
39
  parentPort.postMessage({ type: 'ready' });
36
40
 
41
+ // SERIALISATION — a correctness requirement, not a throttle.
42
+ //
43
+ // Before the stores went async, a model method ran to completion before the next message was
44
+ // handled, so a transaction could not be interrupted. The moment a store awaits, a second
45
+ // queued invoke can interleave BETWEEN a BEGIN and its COMMIT and break atomicity. Drivers
46
+ // therefore DECLARE their concurrency: 'serial' chains every invoke behind the last (SQLite
47
+ // is single-writer anyway, so nothing is lost), 'pool' lets them run concurrently because a
48
+ // Postgres transaction holds its own dedicated client.
49
+ //
50
+ // Default 'serial': a driver that forgets to declare gets the SAFE behaviour, not the fast one.
51
+ let tail = Promise.resolve();
52
+ const serial = () => {
53
+ // Required lazily: the app's init() opens the database, so the driver does not exist when
54
+ // this module loads. Reading it per message also means a driver swapped at runtime (tests
55
+ // do this) is honoured rather than cached wrong.
56
+ try {
57
+ const d = require('./database').driver();
58
+ return !d || d.concurrency !== 'pool';
59
+ } catch (_) {
60
+ return true; // no driver, no information — take the SAFE branch
61
+ }
62
+ };
63
+
37
64
  parentPort.on('message', async (msg) => {
65
+ if (serial()) {
66
+ const mine = tail.then(() => handle(msg));
67
+ tail = mine.catch(() => {}); // one failed invoke must not stall the queue behind it
68
+ return mine;
69
+ }
70
+ return handle(msg);
71
+ });
72
+
73
+ async function handle(msg) {
38
74
  const { id, model, method, args } = msg;
39
75
  // Worker-side execution time, shipped back so the client's slow-call log
40
76
  // attributes slowness to the query that WAS slow, not to calls that were
@@ -70,7 +106,7 @@ function runWorker({ init }) {
70
106
  }
71
107
  parentPort.postMessage({ id, error: payload, execMs: Math.round(performance.now() - t0) });
72
108
  }
73
- });
109
+ }
74
110
  } catch (err) {
75
111
  parentPort.postMessage({ type: 'init-error', error: err.message });
76
112
  }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * assertWorkerRegistry — the guard for this package's one standing contract: every model the app
3
+ * invokes via dbClient.invoke('Name', ...) MUST be registered in the worker, or the call throws
4
+ * "Unknown model" at runtime.
5
+ *
6
+ * A comment asking for diligence is not a mechanism (Support101 shipped a 500 on its busiest page
7
+ * that way); this is the mechanism, hardened by that incident:
8
+ * - BOTH directions: invoked-but-unregistered (a page 500s) AND registered-but-file-deleted
9
+ * (the whole worker crashes on boot, which is worse and harder to read).
10
+ * - Both invoke spellings (db.invoke / dbClient.invoke) — the sibling app's home-grown draft
11
+ * matched only one and missed the other entirely.
12
+ * - Repo-root files scanned flat (server.js is often the SOLE invoke site of boot-only models
13
+ * like a backfill sweep) without descending into node_modules.
14
+ * - SIZE SELF-CHECKS, so a drifted parser fails loudly instead of passing vacuously with two
15
+ * empty sets.
16
+ *
17
+ * Static on both sides, because the registry lives inside a worker init() that needs a database
18
+ * and an encryption key before it will run. The registry parser expects literal
19
+ * `Name: require(...)` lines anywhere in the worker file — a registry expressed as a spread or a
20
+ * loop parses to zero, which the self-check turns into a failure, not a pass.
21
+ *
22
+ * @param {{
23
+ * root: string, app root (absolute)
24
+ * workerFile?: string, default 'lib/db-worker.js'
25
+ * dirs?: string[], scanned recursively; default ['routes','lib','helpers','models','middleware']
26
+ * scanRootFiles?: boolean, default true — flat scan of root *.js (server.js et al)
27
+ * modelsDir?: string, default 'models' — for the registered-but-missing-file direction
28
+ * minRegistered?: number, parser self-check floor (default 5)
29
+ * minInvoked?: number scanner self-check floor (default 5)
30
+ * }} opts
31
+ * @returns {{registered: string[], invoked: string[]}} on success
32
+ * @throws Error naming every violation
33
+ */
34
+
35
+ 'use strict';
36
+
37
+ const fs = require('fs');
38
+ const path = require('path');
39
+
40
+ function assertWorkerRegistry(opts = {}) {
41
+ const root = opts.root;
42
+ if (!root) throw new Error('assertWorkerRegistry({ root }): the app root is required');
43
+ const workerFile = path.join(root, opts.workerFile || path.join('lib', 'db-worker.js'));
44
+ const dirs = opts.dirs || ['routes', 'lib', 'helpers', 'models', 'middleware'];
45
+ const modelsDir = path.join(root, opts.modelsDir || 'models');
46
+ const minRegistered = opts.minRegistered == null ? 5 : opts.minRegistered;
47
+ const minInvoked = opts.minInvoked == null ? 5 : opts.minInvoked;
48
+
49
+ // The names the worker will answer to. Scanned over the WHOLE file rather than sliced from a
50
+ // literal 'return {': one consumer returns its registry, the other assigns it to a const — and
51
+ // an indexOf miss would silently scan one character. `Name: require(...)` lines are the shape;
52
+ // in a worker file that shape is the registry, and the size self-check below guards the rest.
53
+ const src = fs.readFileSync(workerFile, 'utf8');
54
+ const registered = new Set([...src.matchAll(/^\s*(\w+):\s*require\(/gm)].map((m) => m[1]));
55
+
56
+ // Every model name any server-side file asks the worker for, with where it asked.
57
+ const invoked = new Map();
58
+ const scanFile = (full) => {
59
+ const text = fs.readFileSync(full, 'utf8');
60
+ for (const m of text.matchAll(/\b(?:db|dbClient)\.invoke\(\s*['"](\w+)['"]/g)) {
61
+ if (!invoked.has(m[1])) invoked.set(m[1], []);
62
+ invoked.get(m[1]).push(path.relative(root, full));
63
+ }
64
+ };
65
+ if (opts.scanRootFiles !== false) {
66
+ for (const e of fs.readdirSync(root, { withFileTypes: true })) {
67
+ if (e.isFile() && e.name.endsWith('.js')) scanFile(path.join(root, e.name));
68
+ }
69
+ }
70
+ const walk = (dir) => {
71
+ let entries;
72
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { return; }
73
+ for (const e of entries) {
74
+ const full = path.join(dir, e.name);
75
+ if (e.isDirectory()) { walk(full); continue; }
76
+ if (e.name.endsWith('.js')) scanFile(full);
77
+ }
78
+ };
79
+ for (const d of dirs) walk(path.join(root, d));
80
+
81
+ const problems = [];
82
+ if (registered.size < minRegistered) {
83
+ problems.push(`only ${registered.size} registered models found — the registry parser has drifted from ${opts.workerFile || 'lib/db-worker.js'}`);
84
+ }
85
+ if (invoked.size < minInvoked) {
86
+ problems.push(`only ${invoked.size} invoked models found — the invoke scan has drifted`);
87
+ }
88
+ for (const [name, where] of invoked) {
89
+ if (!registered.has(name)) {
90
+ problems.push(`${name} is invoked but not registered (every call throws "Unknown model"): ${[...new Set(where)].join(', ')}`);
91
+ }
92
+ }
93
+ for (const name of registered) {
94
+ if (!fs.existsSync(path.join(modelsDir, name + '.js'))) {
95
+ problems.push(`the worker registers ${name} but ${opts.modelsDir || 'models'}/${name}.js does not exist — the WORKER crashes on boot`);
96
+ }
97
+ }
98
+ if (problems.length) {
99
+ throw new Error('worker registry violations:\n - ' + problems.join('\n - '));
100
+ }
101
+ return { registered: [...registered].sort(), invoked: [...invoked.keys()].sort() };
102
+ }
103
+
104
+ module.exports = { assertWorkerRegistry };