@aria-framework/db-worker 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -112,6 +112,12 @@ Model methods may be sync or async (thenables are awaited). BigInts in results
112
112
 
113
113
  ## Changelog
114
114
 
115
+ - **0.4.2** — sanitizeForTransfer passes `Map`/`Set` through untouched (like
116
+ Date/Buffer/typed arrays — structured clone handles them natively; the
117
+ generic object branch would silently mangle them to `{}`). Latent-bug guard
118
+ from an Acc101 review: no current consumer returns one across the boundary,
119
+ but the first future model method that does now works instead of delivering
120
+ empty data with no error signal.
115
121
  - **0.4.1** — third-review fixes (all in the 0.4.0 additions). (1) Boot-crash
116
122
  suppression latched: a hard boot crash emits 'error' AND 'exit'; the exit
117
123
  handler no longer fires the death policy after the error handler consumed
package/index.js CHANGED
@@ -12,5 +12,11 @@
12
12
  module.exports = {
13
13
  DbClient: require('./client').DbClient,
14
14
  runWorker: require('./worker').runWorker,
15
- database: require('./database')
15
+ database: require('./database'),
16
+ // 0.5.0 — Tier-2 extractions (2026-08-22 audit): the PRAGMA/schema utilities and the KV store
17
+ // both apps carried, plus the guard for this package's own registry contract.
18
+ ...require('./tableOrder'),
19
+ ...require('./schemaSnapshot'),
20
+ ...require('./workerRegistry'),
21
+ ...require('./settingsStore')
16
22
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aria-framework/db-worker",
3
- "version": "0.4.1",
3
+ "version": "0.5.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,19 @@
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"
16
20
  ],
17
21
  "peerDependencies": {
18
22
  "better-sqlite3": ">=9"
19
23
  },
20
24
  "devDependencies": {
21
25
  "better-sqlite3": "^12.10.0"
26
+ },
27
+ "scripts": {
28
+ "test": "node test/smoke.js && node test/tier2.js"
22
29
  }
23
30
  }
@@ -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
@@ -88,7 +88,8 @@ function sanitizeForTransfer(obj, ctx) {
88
88
  if (obj === null || obj === undefined) return obj;
89
89
  if (typeof obj === 'bigint') return Number(obj);
90
90
  if (typeof obj !== 'object') return obj;
91
- if (obj instanceof Date || Buffer.isBuffer(obj) || ArrayBuffer.isView(obj)) return obj;
91
+ if (obj instanceof Date || Buffer.isBuffer(obj) || ArrayBuffer.isView(obj)
92
+ || obj instanceof Map || obj instanceof Set) return obj;
92
93
  // Two structures: `path` (ancestor set) detects TRUE cycles — an object
93
94
  // containing itself must throw; `memo` (obj → sanitized copy) makes shared/
94
95
  // diamond references legal AND linear-time: the same source object always
@@ -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 };