@cexi/hoonfca 0.0.0-stage → 1.0.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/LICENSE +191 -0
- package/README.md +363 -2
- package/dist/cjs.cjs +9 -0
- package/dist/global-types.d.ts +2 -0
- package/dist/index.d.mts +1254 -0
- package/dist/index.d.ts +1254 -0
- package/dist/index.js +17481 -0
- package/dist/index.mjs +17435 -0
- package/docs/ARCHITECTURE.md +467 -0
- package/docs/DOCS.md +709 -0
- package/docs/sqlite-cache-recovery.md +49 -0
- package/fca-config.example.json +33 -0
- package/npm-shrinkwrap.json +4859 -0
- package/package.json +111 -4
- package/scripts/check-package-exports.cjs +84 -0
- package/scripts/recover-sqlite-cache.cjs +504 -0
- package/scripts/sqlite-cache-dump.py +123 -0
package/package.json
CHANGED
|
@@ -1,6 +1,113 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cexi/hoonfca",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Unofficial Facebook Chat API for Node.js - Interact with Facebook Messenger programmatically",
|
|
5
|
+
"main": "dist/cjs.cjs",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"require": "./dist/cjs.cjs",
|
|
11
|
+
"import": "./dist/index.mjs",
|
|
12
|
+
"default": "./dist/index.mjs"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist/",
|
|
17
|
+
"docs/",
|
|
18
|
+
"scripts/check-package-exports.cjs",
|
|
19
|
+
"scripts/recover-sqlite-cache.cjs",
|
|
20
|
+
"scripts/sqlite-cache-dump.py",
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE",
|
|
23
|
+
"fca-config.example.json",
|
|
24
|
+
"npm-shrinkwrap.json"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"test": "node ./test/fca.test.cjs",
|
|
28
|
+
"test:build": "npm run build && node ./test/fca.test.cjs",
|
|
29
|
+
"lint": "eslint --ext .cjs scripts test",
|
|
30
|
+
"typecheck": "tsc -p tsconfig.typecheck.json --noEmit",
|
|
31
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean --out-dir dist --external gradient-string --external form-data --external combined-stream && node scripts/cjs-bridge.cjs",
|
|
32
|
+
"build:types": "tsc -p tsconfig.build.json --emitDeclarationOnly"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/bdrakib123/hoon-fca.git"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"facebook",
|
|
40
|
+
"chat",
|
|
41
|
+
"api",
|
|
42
|
+
"messenger",
|
|
43
|
+
"bot",
|
|
44
|
+
"unofficial",
|
|
45
|
+
"automation",
|
|
46
|
+
"facebook-api",
|
|
47
|
+
"facebook-chat",
|
|
48
|
+
"facebook-messenger",
|
|
49
|
+
"chatbot",
|
|
50
|
+
"nodejs",
|
|
51
|
+
"fca"
|
|
52
|
+
],
|
|
53
|
+
"author": {
|
|
54
|
+
"name": "Hoon",
|
|
55
|
+
"url": "https://www.facebook.com/hoon6t9"
|
|
56
|
+
},
|
|
57
|
+
"contributors": [
|
|
58
|
+
{
|
|
59
|
+
"name": "Rakib",
|
|
60
|
+
"url": "https://github.com/bdrakib123"
|
|
61
|
+
}
|
|
62
|
+
],
|
|
63
|
+
"license": "Apache-2.0",
|
|
64
|
+
"bugs": {
|
|
65
|
+
"url": "https://github.com/bdrakib123/hoon-fca/issues"
|
|
66
|
+
},
|
|
67
|
+
"homepage": "https://github.com/bdrakib123/hoon-fca#readme",
|
|
68
|
+
"engines": {
|
|
69
|
+
"node": ">=20.18.1"
|
|
70
|
+
},
|
|
71
|
+
"dependencies": {
|
|
72
|
+
"axios": "^1.13.5",
|
|
73
|
+
"axios-cookiejar-support": "^5.0.5",
|
|
74
|
+
"bluebird": "^3.7.2",
|
|
75
|
+
"cheerio": "^1.0.0-rc.10",
|
|
76
|
+
"cli-progress": "^3.12.0",
|
|
77
|
+
"duplexify": "^4.1.3",
|
|
78
|
+
"gradient-string": "^3.0.0",
|
|
79
|
+
"https-proxy-agent": "^4.0.0",
|
|
80
|
+
"mqtt": "^4.3.8",
|
|
81
|
+
"ora": "^9.3.0",
|
|
82
|
+
"picocolors": "^1.1.1",
|
|
83
|
+
"sequelize": "^6.37.6",
|
|
84
|
+
"sqlite3": "^6.0.1",
|
|
85
|
+
"totp-generator": "^1.0.0",
|
|
86
|
+
"ws": "^8.18.1"
|
|
87
|
+
},
|
|
88
|
+
"overrides": {
|
|
89
|
+
"follow-redirects": "1.16.2",
|
|
90
|
+
"ip-address": "10.7.5",
|
|
91
|
+
"axios-cookiejar-support": {
|
|
92
|
+
"http-cookie-agent": {
|
|
93
|
+
"undici": "6.29.1"
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
"cheerio": {
|
|
97
|
+
"undici": "7.30.1"
|
|
98
|
+
}
|
|
99
|
+
},
|
|
100
|
+
"devDependencies": {
|
|
101
|
+
"@types/cli-progress": "^3.11.6",
|
|
102
|
+
"@types/duplexify": "^3.6.5",
|
|
103
|
+
"@types/node": "^24.6.1",
|
|
104
|
+
"@types/ws": "^8.18.1",
|
|
105
|
+
"eslint": "^8.50.0",
|
|
106
|
+
"tsup": "^8.5.1",
|
|
107
|
+
"typescript": "^5.9.3"
|
|
108
|
+
},
|
|
109
|
+
"publishConfig": {
|
|
110
|
+
"access": "public",
|
|
111
|
+
"registry": "https://registry.npmjs.org/"
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
|
|
6
|
+
const packageRoot = path.resolve(__dirname, "..");
|
|
7
|
+
const manifestPath = path.join(packageRoot, "package.json");
|
|
8
|
+
const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
|
|
9
|
+
const packageExports = manifest.exports?.["."];
|
|
10
|
+
const targets = {
|
|
11
|
+
main: manifest.main,
|
|
12
|
+
require: packageExports?.require,
|
|
13
|
+
import: packageExports?.import,
|
|
14
|
+
types: packageExports?.types || manifest.types
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
for (const [kind, relativePath] of Object.entries(targets)) {
|
|
18
|
+
if (typeof relativePath !== "string") {
|
|
19
|
+
throw new Error(`Missing package ${kind} export`);
|
|
20
|
+
}
|
|
21
|
+
const resolvedPath = path.resolve(packageRoot, relativePath);
|
|
22
|
+
if (!resolvedPath.startsWith(`${packageRoot}${path.sep}`)) {
|
|
23
|
+
throw new Error(`Package ${kind} export escapes the package directory`);
|
|
24
|
+
}
|
|
25
|
+
if (!fs.statSync(resolvedPath).isFile()) {
|
|
26
|
+
throw new Error(`Package ${kind} export is not a file`);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const declarationDirectory = path.dirname(path.resolve(packageRoot, targets.types));
|
|
31
|
+
const globalTypesPath = path.join(declarationDirectory, "global-types.d.ts");
|
|
32
|
+
if (!fs.existsSync(globalTypesPath)) {
|
|
33
|
+
throw new Error("Package global type declarations are missing");
|
|
34
|
+
}
|
|
35
|
+
for (const declarationName of ["index.d.ts", "index.d.mts"]) {
|
|
36
|
+
const declarationPath = path.join(declarationDirectory, declarationName);
|
|
37
|
+
const declaration = fs.readFileSync(declarationPath, "utf8");
|
|
38
|
+
if (!declaration.includes('/// <reference path="./global-types.d.ts" />')) {
|
|
39
|
+
throw new Error(`${declarationName} does not include global type declarations`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const cjsBridge = fs.readFileSync(
|
|
44
|
+
path.resolve(packageRoot, targets.require),
|
|
45
|
+
"utf8"
|
|
46
|
+
);
|
|
47
|
+
if (!cjsBridge.includes('require("./index.js")')) {
|
|
48
|
+
throw new Error("Package CommonJS bridge does not target dist/index.js");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
for (const [kind, relativePath] of [
|
|
52
|
+
[
|
|
53
|
+
"CommonJS implementation",
|
|
54
|
+
path.join(path.dirname(targets.require), "index.js")
|
|
55
|
+
],
|
|
56
|
+
["ES module implementation", targets.import]
|
|
57
|
+
]) {
|
|
58
|
+
const source = fs.readFileSync(
|
|
59
|
+
path.resolve(packageRoot, relativePath),
|
|
60
|
+
"utf8"
|
|
61
|
+
);
|
|
62
|
+
for (const marker of [
|
|
63
|
+
"serializeSqliteWrite",
|
|
64
|
+
"findOrCreateRecord",
|
|
65
|
+
"PRAGMA integrity_check",
|
|
66
|
+
"PRAGMA busy_timeout = 10000",
|
|
67
|
+
"PRAGMA journal_mode = WAL",
|
|
68
|
+
"SQLite cache integrity check failed",
|
|
69
|
+
"SQLITE_BUSY",
|
|
70
|
+
"SQLITE_LOCKED",
|
|
71
|
+
"wrapError",
|
|
72
|
+
"Failed to create user"
|
|
73
|
+
]) {
|
|
74
|
+
if (!source.includes(marker)) {
|
|
75
|
+
throw new Error(`Package ${kind} bundle is missing ${marker}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
process.stdout.write(`${JSON.stringify({
|
|
81
|
+
package: manifest.name,
|
|
82
|
+
version: manifest.version,
|
|
83
|
+
targets
|
|
84
|
+
}, null, 2)}\n`);
|
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { spawn } = require("node:child_process");
|
|
6
|
+
const sqlite3 = require("sqlite3");
|
|
7
|
+
|
|
8
|
+
function openDatabase(filename, mode = sqlite3.OPEN_READONLY) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const database = new sqlite3.Database(filename, mode, (error) => {
|
|
11
|
+
if (error) {
|
|
12
|
+
reject(error);
|
|
13
|
+
} else {
|
|
14
|
+
resolve(database);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function closeDatabase(database) {
|
|
21
|
+
return new Promise((resolve, reject) => {
|
|
22
|
+
database.close((error) => error ? reject(error) : resolve());
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function all(database, sql, parameters = []) {
|
|
27
|
+
return new Promise((resolve, reject) => {
|
|
28
|
+
database.all(sql, parameters, (error, rows) => {
|
|
29
|
+
error ? reject(error) : resolve(rows);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function quoteIdentifier(identifier) {
|
|
35
|
+
return `"${String(identifier).replaceAll('"', '""')}"`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function inspectDatabase(filename) {
|
|
39
|
+
let database;
|
|
40
|
+
try {
|
|
41
|
+
database = await openDatabase(filename);
|
|
42
|
+
const integrityRows = await all(database, "PRAGMA integrity_check");
|
|
43
|
+
const quickRows = await all(database, "PRAGMA quick_check");
|
|
44
|
+
const tables = await all(
|
|
45
|
+
database,
|
|
46
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
47
|
+
);
|
|
48
|
+
const rowCounts = {};
|
|
49
|
+
for (const { name } of tables) {
|
|
50
|
+
try {
|
|
51
|
+
const rows = await all(database, `SELECT COUNT(*) AS count FROM ${quoteIdentifier(name)}`);
|
|
52
|
+
rowCounts[name] = rows[0].count;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
rowCounts[name] = { error: error.message };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let foreignKeyErrors;
|
|
59
|
+
try {
|
|
60
|
+
foreignKeyErrors = await all(database, "PRAGMA foreign_key_check");
|
|
61
|
+
} catch (error) {
|
|
62
|
+
foreignKeyErrors = [{ error: error.message }];
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const integrity = integrityRows.map((row) => Object.values(row)[0]);
|
|
66
|
+
const quickCheck = quickRows.map((row) => Object.values(row)[0]);
|
|
67
|
+
return {
|
|
68
|
+
integrity,
|
|
69
|
+
integrityOk: integrity.length === 1 && integrity[0] === "ok",
|
|
70
|
+
quickCheck,
|
|
71
|
+
quickCheckOk: quickCheck.length === 1 && quickCheck[0] === "ok",
|
|
72
|
+
rowCounts,
|
|
73
|
+
foreignKeyErrorCount: foreignKeyErrors.length,
|
|
74
|
+
foreignKeyErrors: foreignKeyErrors.slice(0, 20)
|
|
75
|
+
};
|
|
76
|
+
} catch (error) {
|
|
77
|
+
return {
|
|
78
|
+
integrityOk: false,
|
|
79
|
+
quickCheckOk: false,
|
|
80
|
+
error: error.message
|
|
81
|
+
};
|
|
82
|
+
} finally {
|
|
83
|
+
if (database) {
|
|
84
|
+
await closeDatabase(database);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function createVerifiedCopy(source, snapshot) {
|
|
90
|
+
await fs.promises.mkdir(path.dirname(snapshot), { recursive: true });
|
|
91
|
+
const reserved = await fs.promises.open(snapshot, "wx");
|
|
92
|
+
await reserved.close();
|
|
93
|
+
const sourceDb = await openDatabase(source);
|
|
94
|
+
try {
|
|
95
|
+
const backup = sourceDb.backup(snapshot);
|
|
96
|
+
try {
|
|
97
|
+
await new Promise((resolve, reject) => {
|
|
98
|
+
backup.step(-1, (error) => error ? reject(error) : resolve());
|
|
99
|
+
});
|
|
100
|
+
} finally {
|
|
101
|
+
await new Promise((resolve, reject) => {
|
|
102
|
+
backup.finish((error) => error ? reject(error) : resolve());
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
} finally {
|
|
106
|
+
await closeDatabase(sourceDb);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function runSqliteRecovery(snapshot, recovered, sqliteCommand) {
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
const reader = spawn(sqliteCommand, [snapshot, ".recover"], {
|
|
113
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
114
|
+
});
|
|
115
|
+
const writer = spawn(sqliteCommand, ["-bail", recovered], {
|
|
116
|
+
stdio: ["pipe", "ignore", "pipe"]
|
|
117
|
+
});
|
|
118
|
+
let readerError = "";
|
|
119
|
+
let writerError = "";
|
|
120
|
+
let readerCode;
|
|
121
|
+
let writerCode;
|
|
122
|
+
|
|
123
|
+
reader.stderr.setEncoding("utf8");
|
|
124
|
+
writer.stderr.setEncoding("utf8");
|
|
125
|
+
reader.stderr.on("data", (chunk) => { readerError += chunk; });
|
|
126
|
+
writer.stderr.on("data", (chunk) => { writerError += chunk; });
|
|
127
|
+
reader.stdout.pipe(writer.stdin);
|
|
128
|
+
|
|
129
|
+
reader.once("error", reject);
|
|
130
|
+
writer.once("error", reject);
|
|
131
|
+
reader.once("close", (code) => {
|
|
132
|
+
readerCode = code;
|
|
133
|
+
finish();
|
|
134
|
+
});
|
|
135
|
+
writer.once("close", (code) => {
|
|
136
|
+
writerCode = code;
|
|
137
|
+
finish();
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
function finish() {
|
|
141
|
+
if (readerCode === undefined || writerCode === undefined) {
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (readerCode !== 0 || writerCode !== 0) {
|
|
145
|
+
reject(new Error(
|
|
146
|
+
`sqlite3 recovery failed (recover=${readerCode}, apply=${writerCode}): ` +
|
|
147
|
+
`${readerError}${writerError}`.trim().slice(0, 4000)
|
|
148
|
+
));
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
resolve();
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function runPythonDump(snapshot, recovered, pythonCommand) {
|
|
157
|
+
return new Promise((resolve, reject) => {
|
|
158
|
+
const process = spawn(pythonCommand, [
|
|
159
|
+
path.join(__dirname, "sqlite-cache-dump.py"),
|
|
160
|
+
snapshot,
|
|
161
|
+
recovered
|
|
162
|
+
], { stdio: ["ignore", "ignore", "pipe"] });
|
|
163
|
+
let stderr = "";
|
|
164
|
+
process.stderr.setEncoding("utf8");
|
|
165
|
+
process.stderr.on("data", (chunk) => { stderr += chunk; });
|
|
166
|
+
process.once("error", reject);
|
|
167
|
+
process.once("close", (code) => {
|
|
168
|
+
if (code === 0) {
|
|
169
|
+
resolve();
|
|
170
|
+
} else {
|
|
171
|
+
reject(new Error(
|
|
172
|
+
`Python SQLite dump failed (exit=${code}): ${stderr.trim().slice(0, 4000)}`
|
|
173
|
+
));
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function runPythonRowSalvage(snapshot, recovered, pythonCommand) {
|
|
180
|
+
return new Promise((resolve, reject) => {
|
|
181
|
+
const process = spawn(pythonCommand, [
|
|
182
|
+
path.join(__dirname, "sqlite-cache-dump.py"),
|
|
183
|
+
"--salvage-rows",
|
|
184
|
+
snapshot,
|
|
185
|
+
recovered
|
|
186
|
+
], { stdio: ["ignore", "ignore", "pipe"] });
|
|
187
|
+
let stderr = "";
|
|
188
|
+
process.stderr.setEncoding("utf8");
|
|
189
|
+
process.stderr.on("data", (chunk) => { stderr += chunk; });
|
|
190
|
+
process.once("error", reject);
|
|
191
|
+
process.once("close", (code) => {
|
|
192
|
+
if (code === 0) {
|
|
193
|
+
resolve();
|
|
194
|
+
} else {
|
|
195
|
+
reject(new Error(
|
|
196
|
+
`Python SQLite row salvage failed (exit=${code}): ${stderr.trim().slice(0, 4000)}`
|
|
197
|
+
));
|
|
198
|
+
}
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function compareRecords(snapshot, recovered) {
|
|
204
|
+
const database = await openDatabase(recovered, sqlite3.OPEN_READWRITE);
|
|
205
|
+
try {
|
|
206
|
+
await new Promise((resolve, reject) => {
|
|
207
|
+
database.run("ATTACH DATABASE ? AS verified_source", [snapshot], (error) => {
|
|
208
|
+
error ? reject(error) : resolve();
|
|
209
|
+
});
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const sourceTables = await all(
|
|
213
|
+
database,
|
|
214
|
+
"SELECT name FROM verified_source.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
215
|
+
);
|
|
216
|
+
const recoveredTables = await all(
|
|
217
|
+
database,
|
|
218
|
+
"SELECT name FROM main.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
219
|
+
);
|
|
220
|
+
const results = [];
|
|
221
|
+
results.tableDifferences = JSON.stringify(sourceTables.map((table) => table.name)) ===
|
|
222
|
+
JSON.stringify(recoveredTables.map((table) => table.name))
|
|
223
|
+
? []
|
|
224
|
+
: [{
|
|
225
|
+
source: sourceTables.map((table) => table.name),
|
|
226
|
+
recovered: recoveredTables.map((table) => table.name)
|
|
227
|
+
}];
|
|
228
|
+
|
|
229
|
+
for (const { name } of sourceTables) {
|
|
230
|
+
const quoted = quoteIdentifier(name);
|
|
231
|
+
const recoveredTable = await all(
|
|
232
|
+
database,
|
|
233
|
+
"SELECT 1 FROM main.sqlite_master WHERE type = 'table' AND name = ?",
|
|
234
|
+
[name]
|
|
235
|
+
);
|
|
236
|
+
|
|
237
|
+
if (!recoveredTable.length) {
|
|
238
|
+
const sourceCount = await all(
|
|
239
|
+
database,
|
|
240
|
+
`SELECT COUNT(*) AS count FROM verified_source.${quoted}`
|
|
241
|
+
);
|
|
242
|
+
results.push({
|
|
243
|
+
table: name,
|
|
244
|
+
sourceRows: sourceCount[0].count,
|
|
245
|
+
recoveredRows: 0,
|
|
246
|
+
missingRows: sourceCount[0].count,
|
|
247
|
+
extraRows: 0,
|
|
248
|
+
changedRows: 0,
|
|
249
|
+
error: null
|
|
250
|
+
});
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
try {
|
|
255
|
+
const sourceRows = await all(database, `SELECT * FROM verified_source.${quoted}`);
|
|
256
|
+
const recoveredRows = await all(database, `SELECT * FROM main.${quoted}`);
|
|
257
|
+
const sourceColumns = await all(database, `PRAGMA verified_source.table_info(${quoted})`);
|
|
258
|
+
const recoveredColumns = await all(database, `PRAGMA main.table_info(${quoted})`);
|
|
259
|
+
const schemaSignature = (columns) => columns.map((column) => ({
|
|
260
|
+
name: column.name,
|
|
261
|
+
type: column.type,
|
|
262
|
+
notnull: column.notnull,
|
|
263
|
+
defaultValue: column.dflt_value,
|
|
264
|
+
primaryKey: column.pk
|
|
265
|
+
}));
|
|
266
|
+
const schemaMismatch = JSON.stringify(schemaSignature(sourceColumns)) !==
|
|
267
|
+
JSON.stringify(schemaSignature(recoveredColumns));
|
|
268
|
+
const primaryKeys = sourceColumns
|
|
269
|
+
.filter((column) => column.pk > 0)
|
|
270
|
+
.sort((left, right) => left.pk - right.pk)
|
|
271
|
+
.map((column) => column.name);
|
|
272
|
+
const rowKey = (row) => JSON.stringify(
|
|
273
|
+
primaryKeys.length
|
|
274
|
+
? primaryKeys.map((column) => row[column])
|
|
275
|
+
: row
|
|
276
|
+
);
|
|
277
|
+
const recoveredByKey = new Map();
|
|
278
|
+
for (const row of recoveredRows) {
|
|
279
|
+
const key = rowKey(row);
|
|
280
|
+
const rows = recoveredByKey.get(key) || [];
|
|
281
|
+
rows.push(row);
|
|
282
|
+
recoveredByKey.set(key, rows);
|
|
283
|
+
}
|
|
284
|
+
let missingRows = 0;
|
|
285
|
+
let changedRows = 0;
|
|
286
|
+
for (const sourceRow of sourceRows) {
|
|
287
|
+
const candidates = recoveredByKey.get(rowKey(sourceRow));
|
|
288
|
+
if (!candidates?.length) {
|
|
289
|
+
missingRows += 1;
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const sourceValue = JSON.stringify(sourceRow);
|
|
293
|
+
const matchIndex = candidates.findIndex(
|
|
294
|
+
(row) => JSON.stringify(row) === sourceValue
|
|
295
|
+
);
|
|
296
|
+
if (matchIndex !== -1) {
|
|
297
|
+
candidates.splice(matchIndex, 1);
|
|
298
|
+
} else {
|
|
299
|
+
changedRows += 1;
|
|
300
|
+
candidates.shift();
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
const extraRows = [...recoveredByKey.values()]
|
|
304
|
+
.reduce((count, rows) => count + rows.length, 0);
|
|
305
|
+
const sourceTableIndexes = await all(
|
|
306
|
+
database,
|
|
307
|
+
`PRAGMA verified_source.index_list(${quoted})`
|
|
308
|
+
);
|
|
309
|
+
const recoveredTableIndexes = await all(
|
|
310
|
+
database,
|
|
311
|
+
`PRAGMA main.index_list(${quoted})`
|
|
312
|
+
);
|
|
313
|
+
const normalizeTableIndexes = (indexes) => indexes
|
|
314
|
+
.map(({ name: indexName, unique, origin, partial }) => ({
|
|
315
|
+
name: indexName,
|
|
316
|
+
unique,
|
|
317
|
+
origin,
|
|
318
|
+
partial
|
|
319
|
+
}))
|
|
320
|
+
.sort((left, right) => left.name.localeCompare(right.name));
|
|
321
|
+
const indexMismatch = JSON.stringify(normalizeTableIndexes(sourceTableIndexes)) !==
|
|
322
|
+
JSON.stringify(normalizeTableIndexes(recoveredTableIndexes));
|
|
323
|
+
results.push({
|
|
324
|
+
table: name,
|
|
325
|
+
sourceRows: sourceRows.length,
|
|
326
|
+
recoveredRows: recoveredRows.length,
|
|
327
|
+
missingRows,
|
|
328
|
+
extraRows,
|
|
329
|
+
changedRows,
|
|
330
|
+
schemaMismatch,
|
|
331
|
+
indexMismatch,
|
|
332
|
+
error: null
|
|
333
|
+
});
|
|
334
|
+
} catch (error) {
|
|
335
|
+
results.push({
|
|
336
|
+
table: name,
|
|
337
|
+
sourceRows: null,
|
|
338
|
+
recoveredRows: null,
|
|
339
|
+
missingRows: null,
|
|
340
|
+
extraRows: null,
|
|
341
|
+
changedRows: null,
|
|
342
|
+
schemaMismatch: null,
|
|
343
|
+
indexMismatch: null,
|
|
344
|
+
error: error.message
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
const sourceIndexes = await all(
|
|
350
|
+
database,
|
|
351
|
+
"SELECT name, tbl_name, sql FROM verified_source.sqlite_master " +
|
|
352
|
+
"WHERE type = 'index' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
353
|
+
);
|
|
354
|
+
const recoveredIndexes = await all(
|
|
355
|
+
database,
|
|
356
|
+
"SELECT name, tbl_name, sql FROM main.sqlite_master " +
|
|
357
|
+
"WHERE type = 'index' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
358
|
+
);
|
|
359
|
+
const normalizeIndexes = (indexes) => indexes.map((index) => ({
|
|
360
|
+
name: index.name,
|
|
361
|
+
table: index.tbl_name,
|
|
362
|
+
sql: index.sql
|
|
363
|
+
}));
|
|
364
|
+
results.indexDifferences = JSON.stringify(normalizeIndexes(sourceIndexes)) ===
|
|
365
|
+
JSON.stringify(normalizeIndexes(recoveredIndexes))
|
|
366
|
+
? []
|
|
367
|
+
: [{
|
|
368
|
+
source: normalizeIndexes(sourceIndexes),
|
|
369
|
+
recovered: normalizeIndexes(recoveredIndexes)
|
|
370
|
+
}];
|
|
371
|
+
return results;
|
|
372
|
+
} finally {
|
|
373
|
+
await closeDatabase(database);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async function recoverCache({
|
|
378
|
+
source,
|
|
379
|
+
snapshot,
|
|
380
|
+
recovered,
|
|
381
|
+
sqliteCommand = "sqlite3",
|
|
382
|
+
pythonCommand = "python3"
|
|
383
|
+
}) {
|
|
384
|
+
const paths = [source, snapshot, recovered].map((filename) => path.resolve(filename));
|
|
385
|
+
if (new Set(paths).size !== paths.length) {
|
|
386
|
+
throw new Error("Source, snapshot, and recovered database paths must be different.");
|
|
387
|
+
}
|
|
388
|
+
if (!fs.existsSync(paths[0])) {
|
|
389
|
+
throw new Error("Source database does not exist.");
|
|
390
|
+
}
|
|
391
|
+
if (fs.existsSync(paths[1]) || fs.existsSync(paths[2])) {
|
|
392
|
+
throw new Error("Snapshot and recovered paths must not already exist.");
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
await createVerifiedCopy(paths[0], paths[1]);
|
|
396
|
+
const snapshotCheck = await inspectDatabase(paths[1]);
|
|
397
|
+
let recoveryError = null;
|
|
398
|
+
let pythonDumpError = null;
|
|
399
|
+
let pythonSalvageError = null;
|
|
400
|
+
let recoveryMethod = "unverified";
|
|
401
|
+
let recoveredPath = paths[2];
|
|
402
|
+
if (snapshotCheck.integrityOk) {
|
|
403
|
+
await createVerifiedCopy(paths[1], paths[2]);
|
|
404
|
+
recoveryMethod = "verified-copy";
|
|
405
|
+
} else {
|
|
406
|
+
await fs.promises.mkdir(path.dirname(paths[2]), { recursive: true });
|
|
407
|
+
const output = await fs.promises.open(paths[2], "wx");
|
|
408
|
+
await output.close();
|
|
409
|
+
try {
|
|
410
|
+
await runSqliteRecovery(paths[1], paths[2], sqliteCommand);
|
|
411
|
+
recoveryMethod = "sqlite3-.recover";
|
|
412
|
+
} catch (error) {
|
|
413
|
+
recoveryError = error.message;
|
|
414
|
+
recoveredPath = `${paths[2]}.python-dump`;
|
|
415
|
+
if (fs.existsSync(recoveredPath)) {
|
|
416
|
+
throw new Error(`Python dump output already exists: ${recoveredPath}`);
|
|
417
|
+
}
|
|
418
|
+
const pythonOutput = await fs.promises.open(recoveredPath, "wx");
|
|
419
|
+
await pythonOutput.close();
|
|
420
|
+
try {
|
|
421
|
+
await runPythonDump(paths[1], recoveredPath, pythonCommand);
|
|
422
|
+
recoveryMethod = "python-sql-dump";
|
|
423
|
+
} catch (pythonError) {
|
|
424
|
+
pythonDumpError = pythonError.message;
|
|
425
|
+
recoveredPath = `${paths[2]}.python-row-salvage`;
|
|
426
|
+
if (fs.existsSync(recoveredPath)) {
|
|
427
|
+
throw new Error(`Python row-salvage output already exists: ${recoveredPath}`);
|
|
428
|
+
}
|
|
429
|
+
const salvageOutput = await fs.promises.open(recoveredPath, "wx");
|
|
430
|
+
await salvageOutput.close();
|
|
431
|
+
try {
|
|
432
|
+
await runPythonRowSalvage(paths[1], recoveredPath, pythonCommand);
|
|
433
|
+
recoveryMethod = "python-row-salvage";
|
|
434
|
+
} catch (salvageError) {
|
|
435
|
+
pythonSalvageError = salvageError.message;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const recoveredCheck = await inspectDatabase(recoveredPath);
|
|
442
|
+
let records = [];
|
|
443
|
+
let recordComparisonError = null;
|
|
444
|
+
try {
|
|
445
|
+
records = await compareRecords(paths[1], recoveredPath);
|
|
446
|
+
} catch (error) {
|
|
447
|
+
recordComparisonError = error.message;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
const tableComparisons = records.filter((record) => record.table);
|
|
451
|
+
return {
|
|
452
|
+
snapshotCheck,
|
|
453
|
+
recoveredCheck,
|
|
454
|
+
recoveryError,
|
|
455
|
+
pythonDumpError,
|
|
456
|
+
pythonSalvageError,
|
|
457
|
+
recoveryMethod,
|
|
458
|
+
recoveredPath,
|
|
459
|
+
records,
|
|
460
|
+
tableDifferences: records.tableDifferences || [],
|
|
461
|
+
indexDifferences: records.indexDifferences || [],
|
|
462
|
+
recordComparisonError,
|
|
463
|
+
verified: recoveredCheck.integrityOk &&
|
|
464
|
+
recoveredCheck.quickCheckOk &&
|
|
465
|
+
recoveredCheck.foreignKeyErrorCount === 0 &&
|
|
466
|
+
!recordComparisonError &&
|
|
467
|
+
tableComparisons.every((record) =>
|
|
468
|
+
!record.error &&
|
|
469
|
+
record.missingRows === 0 &&
|
|
470
|
+
record.extraRows === 0 &&
|
|
471
|
+
record.changedRows === 0 &&
|
|
472
|
+
!record.schemaMismatch &&
|
|
473
|
+
!record.indexMismatch
|
|
474
|
+
) &&
|
|
475
|
+
records.tableDifferences?.length === 0 &&
|
|
476
|
+
records.indexDifferences?.length === 0
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
module.exports = {
|
|
481
|
+
compareRecords,
|
|
482
|
+
inspectDatabase,
|
|
483
|
+
recoverCache
|
|
484
|
+
};
|
|
485
|
+
|
|
486
|
+
if (require.main === module) {
|
|
487
|
+
const [, , source, snapshot, recovered] = process.argv;
|
|
488
|
+
if (!source || !snapshot || !recovered) {
|
|
489
|
+
console.error("Usage: node scripts/recover-sqlite-cache.cjs <source> <new-snapshot> <new-recovered-copy>");
|
|
490
|
+
process.exitCode = 2;
|
|
491
|
+
} else {
|
|
492
|
+
recoverCache({ source, snapshot, recovered })
|
|
493
|
+
.then((report) => {
|
|
494
|
+
console.log(JSON.stringify(report, null, 2));
|
|
495
|
+
if (!report.verified) {
|
|
496
|
+
process.exitCode = 1;
|
|
497
|
+
}
|
|
498
|
+
})
|
|
499
|
+
.catch((error) => {
|
|
500
|
+
console.error(`SQLite cache recovery stopped: ${error.message}`);
|
|
501
|
+
process.exitCode = 1;
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
}
|