@covro/covro 0.11.0 → 0.11.1-dev.2
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/dist/backups/compact.js +45 -0
- package/dist/backups/compact.js.map +7 -0
- package/dist/backups/factory.js +3 -1
- package/dist/backups/factory.js.map +2 -2
- package/dist/backups/store.js +7 -1
- package/dist/backups/store.js.map +2 -2
- package/dist/update-worker.cjs +55 -6
- package/dist/updates/worker.js +4 -3
- package/dist/updates/worker.js.map +2 -2
- package/dist/web/assets/{abnfDiagram-WEYOIA3C-Hs1QxS5F.js → abnfDiagram-WEYOIA3C-BSubEQ-7.js} +1 -1
- package/dist/web/assets/{arc-Yi84Ptf_.js → arc-BCL-dxsD.js} +1 -1
- package/dist/web/assets/{architecture-WOLXFQ4H-D5R4yrK5.js → architecture-WOLXFQ4H-DurVyzju.js} +1 -1
- package/dist/web/assets/{architectureDiagram-ZHVYKT53-BVn-Yyha.js → architectureDiagram-ZHVYKT53-BcOqgbBU.js} +1 -1
- package/dist/web/assets/{blockDiagram-RJAE7QA3-Cl0jJyYC.js → blockDiagram-RJAE7QA3-LHBF62jw.js} +1 -1
- package/dist/web/assets/{c4Diagram-XDPPPE54-BDf0NRFG.js → c4Diagram-XDPPPE54-Bkndc3-B.js} +1 -1
- package/dist/web/assets/channel-C3vabAXG.js +1 -0
- package/dist/web/assets/{chunk-2E7WHVMD-Zsnk121M.js → chunk-2E7WHVMD-CvJej-BB.js} +1 -1
- package/dist/web/assets/{chunk-4EMNKR2T-CgLHLqly.js → chunk-4EMNKR2T-Cj3qH5PV.js} +1 -1
- package/dist/web/assets/{chunk-55XCU76K-BHDUfuaD.js → chunk-55XCU76K-4xFZSSFI.js} +1 -1
- package/dist/web/assets/{chunk-7S6XSTFO-6-KVQAUN.js → chunk-7S6XSTFO-BfDoTYCv.js} +1 -1
- package/dist/web/assets/{chunk-AQDTSKZB-Br8YkxWS.js → chunk-AQDTSKZB-B7IwBsvT.js} +1 -1
- package/dist/web/assets/{chunk-DSNLSHJZ-DsAg5EQh.js → chunk-DSNLSHJZ-xcJjdhWM.js} +1 -1
- package/dist/web/assets/{chunk-HAGFOTED-DzFzhmwk.js → chunk-HAGFOTED-CDzHEIn6.js} +1 -1
- package/dist/web/assets/{chunk-HNE4Q36P-OsVBWdaT.js → chunk-HNE4Q36P-bheerq1e.js} +1 -1
- package/dist/web/assets/{chunk-NQOKRVIF-Dyt_LpzK.js → chunk-NQOKRVIF-Chat1bRr.js} +1 -1
- package/dist/web/assets/{chunk-UHW7PFBP-D6Wfdn1K.js → chunk-UHW7PFBP-lloh8YsY.js} +1 -1
- package/dist/web/assets/{chunk-VQ5W62QI-t95a_jAa.js → chunk-VQ5W62QI-r_YvnHX8.js} +1 -1
- package/dist/web/assets/{chunk-WQQL4CDK-BJ-dd_Vo.js → chunk-WQQL4CDK-CVI6LEmu.js} +1 -1
- package/dist/web/assets/{chunk-XXDRQBXY-DujGbJQQ.js → chunk-XXDRQBXY-2LUO2r6P.js} +1 -1
- package/dist/web/assets/{chunk-YZO67HFG-CmuofP1x.js → chunk-YZO67HFG-DjpC9Pn-.js} +1 -1
- package/dist/web/assets/{chunk-ZAUX2LTX-L_kEzBr0.js → chunk-ZAUX2LTX-DFYzBxer.js} +1 -1
- package/dist/web/assets/{chunk-ZCHMQSOR-BNFfRYVU.js → chunk-ZCHMQSOR-BjMF-FQl.js} +1 -1
- package/dist/web/assets/{classDiagram-v2-4MYWR3UA-CM8t3Q1V.js → classDiagram-v2-4MYWR3UA-REceQuLZ.js} +1 -1
- package/dist/web/assets/{cose-bilkent-JH36ORCC-C9bH-KuG.js → cose-bilkent-JH36ORCC-CqinaCl2.js} +1 -1
- package/dist/web/assets/{cynefin-EF2NZ3EQ-CoOnVRkB.js → cynefin-EF2NZ3EQ-DzAOttrW.js} +1 -1
- package/dist/web/assets/{cynefinDiagram-WF24UDRP-DDcZi2hV.js → cynefinDiagram-WF24UDRP-Dh4fp2Vn.js} +1 -1
- package/dist/web/assets/{dagre-NK4GIZVX-BJe2QeFW.js → dagre-NK4GIZVX-CVMm7h8A.js} +1 -1
- package/dist/web/assets/{diagram-CBK3MWTC-B8sGYNNO.js → diagram-CBK3MWTC-i3YyfRYC.js} +1 -1
- package/dist/web/assets/{diagram-I5XIIV2D-CNSUd2IG.js → diagram-I5XIIV2D-BSUS6AgH.js} +1 -1
- package/dist/web/assets/{diagram-ODIL2UCW-BV94fh1m.js → diagram-ODIL2UCW-DY7dK384.js} +1 -1
- package/dist/web/assets/{diagram-PFBEJUXE-DWzUXWtr.js → diagram-PFBEJUXE-C_wr4nJC.js} +1 -1
- package/dist/web/assets/{diagram-RJA3I4VV-DbR5tUPI.js → diagram-RJA3I4VV-kFVETsOb.js} +1 -1
- package/dist/web/assets/{diagram-TYUNFSNR-DZUg3UL7.js → diagram-TYUNFSNR-Clla-6jR.js} +1 -1
- package/dist/web/assets/{dist-CBWw8-8f.js → dist-PxL1MpGF.js} +1 -1
- package/dist/web/assets/{ebnfDiagram-V4P3TTPT-Dh19TY0l.js → ebnfDiagram-V4P3TTPT-wLtWIi2U.js} +1 -1
- package/dist/web/assets/{elk-QONTBCTQ-BKL3cPZt.js → elk-QONTBCTQ-CIc7x9Yl.js} +1 -1
- package/dist/web/assets/{erDiagram-KYQIGQAA-B1ZCU54i.js → erDiagram-KYQIGQAA-CE6scQx1.js} +1 -1
- package/dist/web/assets/{eventmodeling-K75KTNOO-B0nkhELK.js → eventmodeling-K75KTNOO-Du4pViRK.js} +1 -1
- package/dist/web/assets/flowDiagram-IUGLLWBU-DH5LUJ78.js +1 -0
- package/dist/web/assets/{ganttDiagram-R7GPNTJY-Cfik_x-_.js → ganttDiagram-R7GPNTJY-DhI6Wkl0.js} +1 -1
- package/dist/web/assets/{gitGraph-VSP46ZUC-IaWrHMbk.js → gitGraph-VSP46ZUC-BZ2IRYfH.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-PDYL7XHY-Bf9iLSqi.js → gitGraphDiagram-PDYL7XHY-CF3ROFD7.js} +1 -1
- package/dist/web/assets/{index-DzrsSdAx.js → index-jxmna5w3.js} +3 -3
- package/dist/web/assets/{info-OHQRW6UA-qChB7My9.js → info-OHQRW6UA-XS65KJ1x.js} +1 -1
- package/dist/web/assets/{infoDiagram-MVDRKAX5-Dx-EJ73Z.js → infoDiagram-MVDRKAX5-Ccf6TTC8.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-HPEHV2GE-DcOrGUmN.js → ishikawaDiagram-HPEHV2GE-aPiOfWT8.js} +1 -1
- package/dist/web/assets/{journeyDiagram-BOSHW7O7-BoSQvr88.js → journeyDiagram-BOSHW7O7-CjJfwlw5.js} +1 -1
- package/dist/web/assets/{kanban-definition-FNSA4HC5-CKv6zPit.js → kanban-definition-FNSA4HC5-Bfkkk3lr.js} +1 -1
- package/dist/web/assets/{line-DVV9QhWH.js → line-Bgfk4ck3.js} +1 -1
- package/dist/web/assets/{linear-Cpsrk35i.js → linear-Bq2O40Qj.js} +1 -1
- package/dist/web/assets/{mermaid-parser.core-DHAb_E0V.js → mermaid-parser.core-CagmNEON.js} +3 -3
- package/dist/web/assets/{mermaid.core-B1NdRfSJ.js → mermaid.core-BhI_0ceg.js} +4 -4
- package/dist/web/assets/{mindmap-definition-6OY57UG3-DyVdGRza.js → mindmap-definition-6OY57UG3-Bo-8vZjv.js} +1 -1
- package/dist/web/assets/{packet-JDAUHWVQ-DsHzWbBE.js → packet-JDAUHWVQ-Co0qHDRd.js} +1 -1
- package/dist/web/assets/{pegDiagram-ECIUJNBX-CVHu7N-g.js → pegDiagram-ECIUJNBX-B06cLNB1.js} +1 -1
- package/dist/web/assets/{pie-XZMESJXO-Bo4CUzUJ.js → pie-XZMESJXO-Cj2YnQpt.js} +1 -1
- package/dist/web/assets/{pieDiagram-GNMPY74T--MNlZxEA.js → pieDiagram-GNMPY74T-CtNnt_pL.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-D57K4MC3-C8NqVii7.js → quadrantDiagram-D57K4MC3-CN4ranEt.js} +1 -1
- package/dist/web/assets/{radar-ABXABTNO-X6Uqprp6.js → radar-ABXABTNO-D4Zfy8Uo.js} +1 -1
- package/dist/web/assets/{railroad-I3PHUGI6-BfNgkGQY.js → railroad-I3PHUGI6-CZoE8AvJ.js} +1 -1
- package/dist/web/assets/{railroad-abnf-LNEFI6M7-BArxuhQb.js → railroad-abnf-LNEFI6M7-DAQazLBn.js} +1 -1
- package/dist/web/assets/{railroad-ebnf-DWYD2UWJ-7y5FJiSp.js → railroad-ebnf-DWYD2UWJ-BB0xIfny.js} +1 -1
- package/dist/web/assets/{railroad-peg-JR7BVNR7-u63FmBnv.js → railroad-peg-JR7BVNR7-DFDAmH89.js} +1 -1
- package/dist/web/assets/{railroadDiagram-Y72NRBL7-EpkzutgD.js → railroadDiagram-Y72NRBL7-DkFU88Sw.js} +1 -1
- package/dist/web/assets/{requirementDiagram-EQYSW5RA-DiTJxWGV.js → requirementDiagram-EQYSW5RA-BnyEKyMn.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-SY24JHO5-BF3ie6ML.js → sankeyDiagram-SY24JHO5-hiN5MEZe.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-BLEHNHQU-CP9bDY2W.js → sequenceDiagram-BLEHNHQU-BZyhOknA.js} +1 -1
- package/dist/web/assets/{src-CnQkv3xo.js → src-Ca_VLzGx.js} +1 -1
- package/dist/web/assets/{stateDiagram-v2-A6IESKWZ-BdkIIAWl.js → stateDiagram-v2-A6IESKWZ-C-JGDrRz.js} +1 -1
- package/dist/web/assets/{swimlanes-B3ENRKFQ-DnTDzetu.js → swimlanes-B3ENRKFQ-BaXFv3gx.js} +1 -1
- package/dist/web/assets/swimlanesDiagram-AYQRV4AK-C5LMuklZ.js +8 -0
- package/dist/web/assets/{timeline-definition-JXYKGLGB-C-NabcIM.js → timeline-definition-JXYKGLGB-2u2TqP7P.js} +1 -1
- package/dist/web/assets/{treeView-D4JQ5SDB-DagoiWWm.js → treeView-D4JQ5SDB-aNXmkGah.js} +1 -1
- package/dist/web/assets/{treemap-SAJKECNS-BS50bNV6.js → treemap-SAJKECNS-CbcbKmdu.js} +1 -1
- package/dist/web/assets/{usecaseDiagram-WPOLBNNX-BInox1aT.js → usecaseDiagram-WPOLBNNX-DZy2qxN6.js} +1 -1
- package/dist/web/assets/{vennDiagram-Q3Y3IDCW-DQ-a80j2.js → vennDiagram-Q3Y3IDCW-CTSjeZtr.js} +1 -1
- package/dist/web/assets/{wardley-7MLQ67FV-2Et7Ky3V.js → wardley-7MLQ67FV-CijzrqwE.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-IVAIDKWA-B_n7qQEe.js → wardleyDiagram-IVAIDKWA-BXHTPQcB.js} +1 -1
- package/dist/web/assets/{xychartDiagram-4URNHDU4-BXbaYcIR.js → xychartDiagram-4URNHDU4-C3L6Nfn2.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +4 -4
- package/dist/web/assets/channel-DRTZPvNA.js +0 -1
- package/dist/web/assets/flowDiagram-IUGLLWBU-BmKP6T9Y.js +0 -1
- package/dist/web/assets/swimlanesDiagram-AYQRV4AK-BTvQJ2C2.js +0 -8
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Worker } from "node:worker_threads";
|
|
2
|
+
const script = `
|
|
3
|
+
const { parentPort, workerData } = require('node:worker_threads');
|
|
4
|
+
try {
|
|
5
|
+
const Sqlite = require(workerData.sqliteModulePath);
|
|
6
|
+
const db = new Sqlite(workerData.filename, { fileMustExist: true });
|
|
7
|
+
try {
|
|
8
|
+
db.exec('VACUUM');
|
|
9
|
+
// In WAL mode the main file only shrinks once the new pages are checkpointed.
|
|
10
|
+
const [checkpoint] = db.pragma('wal_checkpoint(TRUNCATE)');
|
|
11
|
+
if (checkpoint.busy) {
|
|
12
|
+
throw Object.assign(new Error('WAL checkpoint was blocked'), { code: 'SQLITE_BUSY' });
|
|
13
|
+
}
|
|
14
|
+
} finally {
|
|
15
|
+
db.close();
|
|
16
|
+
}
|
|
17
|
+
} catch (error) {
|
|
18
|
+
parentPort.postMessage(error.code || 'SQLITE_COMPACTION_FAILED');
|
|
19
|
+
}
|
|
20
|
+
`;
|
|
21
|
+
function compactDatabase(filename, sqliteModulePath) {
|
|
22
|
+
return new Promise((resolve, reject) => {
|
|
23
|
+
const worker = new Worker(script, {
|
|
24
|
+
eval: true,
|
|
25
|
+
execArgv: [],
|
|
26
|
+
workerData: { filename, sqliteModulePath }
|
|
27
|
+
});
|
|
28
|
+
let error;
|
|
29
|
+
worker.once("message", (code) => {
|
|
30
|
+
error = Object.assign(new Error("Source database compaction failed"), { code });
|
|
31
|
+
});
|
|
32
|
+
worker.once("error", (failure) => {
|
|
33
|
+
error = failure;
|
|
34
|
+
});
|
|
35
|
+
worker.once("exit", (code) => {
|
|
36
|
+
if (error) reject(error);
|
|
37
|
+
else if (code !== 0) reject(new Error("Database compaction worker exited early"));
|
|
38
|
+
else resolve();
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
export {
|
|
43
|
+
compactDatabase
|
|
44
|
+
};
|
|
45
|
+
//# sourceMappingURL=compact.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/backups/compact.ts"],
|
|
4
|
+
"sourcesContent": ["import { Worker } from 'node:worker_threads';\n\n// The gateway and the bundled upgrade worker share this script and pass the SQLite\n// module from the installation that owns the source database.\nconst script = `\n const { parentPort, workerData } = require('node:worker_threads');\n try {\n const Sqlite = require(workerData.sqliteModulePath);\n const db = new Sqlite(workerData.filename, { fileMustExist: true });\n try {\n db.exec('VACUUM');\n // In WAL mode the main file only shrinks once the new pages are checkpointed.\n const [checkpoint] = db.pragma('wal_checkpoint(TRUNCATE)');\n if (checkpoint.busy) {\n throw Object.assign(new Error('WAL checkpoint was blocked'), { code: 'SQLITE_BUSY' });\n }\n } finally {\n db.close();\n }\n } catch (error) {\n parentPort.postMessage(error.code || 'SQLITE_COMPACTION_FAILED');\n }\n`;\n\nexport function compactDatabase(filename: string, sqliteModulePath: string): Promise<void> {\n return new Promise((resolve, reject) => {\n // Keep the gateway responsive and let the maintenance and configuration locks renew.\n const worker = new Worker(script, {\n eval: true,\n execArgv: [],\n workerData: { filename, sqliteModulePath },\n });\n let error: Error | undefined;\n worker.once('message', (code: string) => {\n error = Object.assign(new Error('Source database compaction failed'), { code });\n });\n worker.once('error', (failure) => {\n error = failure;\n });\n worker.once('exit', (code) => {\n if (error) reject(error);\n else if (code !== 0) reject(new Error('Database compaction worker exited early'));\n else resolve();\n });\n });\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,cAAc;AAIvB,MAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBR,SAAS,gBAAgB,UAAkB,kBAAyC;AACzF,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AAEtC,UAAM,SAAS,IAAI,OAAO,QAAQ;AAAA,MAChC,MAAM;AAAA,MACN,UAAU,CAAC;AAAA,MACX,YAAY,EAAE,UAAU,iBAAiB;AAAA,IAC3C,CAAC;AACD,QAAI;AACJ,WAAO,KAAK,WAAW,CAAC,SAAiB;AACvC,cAAQ,OAAO,OAAO,IAAI,MAAM,mCAAmC,GAAG,EAAE,KAAK,CAAC;AAAA,IAChF,CAAC;AACD,WAAO,KAAK,SAAS,CAAC,YAAY;AAChC,cAAQ;AAAA,IACV,CAAC;AACD,WAAO,KAAK,QAAQ,CAAC,SAAS;AAC5B,UAAI,MAAO,QAAO,KAAK;AAAA,eACd,SAAS,EAAG,QAAO,IAAI,MAAM,yCAAyC,CAAC;AAAA,UAC3E,SAAQ;AAAA,IACf,CAAC;AAAA,EACH,CAAC;AACH;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/backups/factory.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
1
2
|
import Database from "better-sqlite3";
|
|
2
3
|
import { packageInfo, paths } from "../cli/paths.js";
|
|
3
4
|
import { databaseCompatibilitySchema } from "../shared/database.js";
|
|
@@ -13,7 +14,8 @@ function createBackupStore(config, dataDir, migrationsFolder = runtimeMigrations
|
|
|
13
14
|
commit: packageInfo.covroCommit,
|
|
14
15
|
contract: databaseCompatibilitySchema.parse(packageInfo.covroDatabase),
|
|
15
16
|
migrations: readMigrations(migrationsFolder),
|
|
16
|
-
Sqlite: Database
|
|
17
|
+
Sqlite: Database,
|
|
18
|
+
sqliteModulePath: createRequire(import.meta.url).resolve("better-sqlite3")
|
|
17
19
|
});
|
|
18
20
|
}
|
|
19
21
|
export {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/backups/factory.ts"],
|
|
4
|
-
"sourcesContent": ["import Database from 'better-sqlite3';\nimport { packageInfo, paths } from '../cli/paths.js';\nimport { databaseCompatibilitySchema } from '../shared/database.js';\nimport { readMigrations } from '../server/db/history.js';\nimport { runtimeMigrationsFolder } from '../server/db/migrate.js';\nimport { BackupStore, backupDirectory } from './store.js';\n\nexport function createBackupStore(\n config: string,\n dataDir: string,\n migrationsFolder = runtimeMigrationsFolder,\n) {\n return new BackupStore({\n directory: backupDirectory(paths(config).home, dataDir),\n config,\n dataDir,\n appVersion: packageInfo.version,\n commit: packageInfo.covroCommit,\n contract: databaseCompatibilitySchema.parse(packageInfo.covroDatabase),\n migrations: readMigrations(migrationsFolder),\n Sqlite: Database,\n });\n}\n"],
|
|
5
|
-
"mappings": "AAAA,OAAO,cAAc;AACrB,SAAS,aAAa,aAAa;AACnC,SAAS,mCAAmC;AAC5C,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,aAAa,uBAAuB;AAEtC,SAAS,kBACd,QACA,SACA,mBAAmB,yBACnB;AACA,SAAO,IAAI,YAAY;AAAA,IACrB,WAAW,gBAAgB,MAAM,MAAM,EAAE,MAAM,OAAO;AAAA,IACtD;AAAA,IACA;AAAA,IACA,YAAY,YAAY;AAAA,IACxB,QAAQ,YAAY;AAAA,IACpB,UAAU,4BAA4B,MAAM,YAAY,aAAa;AAAA,IACrE,YAAY,eAAe,gBAAgB;AAAA,IAC3C,QAAQ;AAAA,
|
|
4
|
+
"sourcesContent": ["import { createRequire } from 'node:module';\nimport Database from 'better-sqlite3';\nimport { packageInfo, paths } from '../cli/paths.js';\nimport { databaseCompatibilitySchema } from '../shared/database.js';\nimport { readMigrations } from '../server/db/history.js';\nimport { runtimeMigrationsFolder } from '../server/db/migrate.js';\nimport { BackupStore, backupDirectory } from './store.js';\n\nexport function createBackupStore(\n config: string,\n dataDir: string,\n migrationsFolder = runtimeMigrationsFolder,\n) {\n return new BackupStore({\n directory: backupDirectory(paths(config).home, dataDir),\n config,\n dataDir,\n appVersion: packageInfo.version,\n commit: packageInfo.covroCommit,\n contract: databaseCompatibilitySchema.parse(packageInfo.covroDatabase),\n migrations: readMigrations(migrationsFolder),\n Sqlite: Database,\n sqliteModulePath: createRequire(import.meta.url).resolve('better-sqlite3'),\n });\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,qBAAqB;AAC9B,OAAO,cAAc;AACrB,SAAS,aAAa,aAAa;AACnC,SAAS,mCAAmC;AAC5C,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,aAAa,uBAAuB;AAEtC,SAAS,kBACd,QACA,SACA,mBAAmB,yBACnB;AACA,SAAO,IAAI,YAAY;AAAA,IACrB,WAAW,gBAAgB,MAAM,MAAM,EAAE,MAAM,OAAO;AAAA,IACtD;AAAA,IACA;AAAA,IACA,YAAY,YAAY;AAAA,IACxB,QAAQ,YAAY;AAAA,IACpB,UAAU,4BAA4B,MAAM,YAAY,aAAa;AAAA,IACrE,YAAY,eAAe,gBAAgB;AAAA,IAC3C,QAAQ;AAAA,IACR,kBAAkB,cAAc,YAAY,GAAG,EAAE,QAAQ,gBAAgB;AAAA,EAC3E,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/backups/store.js
CHANGED
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
import { MAX_CONFIG_BYTES } from "../server/config-store.js";
|
|
19
19
|
import { parseConfig, parseFileConfig } from "../server/config.js";
|
|
20
20
|
import { copyDurable, readJson, saveJson } from "../updates/files.js";
|
|
21
|
+
import { compactDatabase } from "./compact.js";
|
|
21
22
|
const backupDirectory = (home, dataDir) => join(home, "backups", createHash("sha256").update(resolve(dataDir)).digest("hex").slice(0, 16));
|
|
22
23
|
async function fingerprint(path) {
|
|
23
24
|
const info = await lstat(path);
|
|
@@ -94,6 +95,7 @@ class BackupStore {
|
|
|
94
95
|
}
|
|
95
96
|
return records.sort((a, b) => b.createdAt - a.createdAt);
|
|
96
97
|
}
|
|
98
|
+
/** Caller must hold the maintenance lock and pause application writes. */
|
|
97
99
|
async create(input) {
|
|
98
100
|
const { Sqlite, migrations, config, dataDir, appVersion, commit } = this.options;
|
|
99
101
|
const id = backupIdSchema.parse(input.id ?? randomUUID());
|
|
@@ -136,9 +138,13 @@ class BackupStore {
|
|
|
136
138
|
} finally {
|
|
137
139
|
await configFile.close();
|
|
138
140
|
}
|
|
139
|
-
|
|
141
|
+
const source = join(dataDir, "app.sqlite");
|
|
142
|
+
sqlite = new Sqlite(source, { readonly: true, fileMustExist: true });
|
|
140
143
|
const history = inspectDatabase(sqlite, migrations);
|
|
141
144
|
requireRestorable(history.schemaVersion, this.options.contract);
|
|
145
|
+
input.signal?.throwIfAborted();
|
|
146
|
+
await compactDatabase(source, this.options.sqliteModulePath);
|
|
147
|
+
input.signal?.throwIfAborted();
|
|
142
148
|
await sqlite.backup(join(directory, "app.sqlite"), {
|
|
143
149
|
progress: ({ totalPages, remainingPages }) => {
|
|
144
150
|
input.signal?.throwIfAborted();
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/backups/store.ts"],
|
|
4
|
-
"sourcesContent": ["import { z, ZodError } from 'zod';\nimport { createHash, randomUUID } from 'node:crypto';\nimport { createReadStream } from 'node:fs';\nimport { chmod, lstat, mkdir, open, readFile, readdir, rm } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport type Database from 'better-sqlite3';\nimport lockfile from 'proper-lockfile';\nimport {\n backupIdSchema,\n backupManifestSchema,\n backupRecordSchema,\n type BackupManifest,\n type BackupRecord,\n} from '../shared/backups.js';\nimport { AppError } from '../shared/errors.js';\nimport type { DatabaseCompatibility } from '../shared/database.js';\nimport {\n inspectDatabase,\n readMigrations,\n requireRestorable,\n type Migration,\n} from '../server/db/history.js';\nimport { MAX_CONFIG_BYTES } from '../server/config-store.js';\nimport { parseConfig, parseFileConfig } from '../server/config.js';\nimport { copyDurable, readJson, saveJson } from '../updates/files.js';\n\nexport interface BackupOptions {\n directory: string;\n config: string;\n dataDir: string;\n appVersion: string;\n commit?: string;\n contract: DatabaseCompatibility;\n migrations: Migration[];\n Sqlite: typeof Database;\n}\nexport const backupDirectory = (home: string, dataDir: string) =>\n join(home, 'backups', createHash('sha256').update(resolve(dataDir)).digest('hex').slice(0, 16));\n\nasync function fingerprint(path: string) {\n const info = await lstat(path);\n if (!info.isFile() || info.isSymbolicLink())\n throw new Error('Backup contains a non-regular file');\n const hash = createHash('sha256');\n for await (const chunk of createReadStream(path)) hash.update(chunk);\n return { size: info.size, sha256: hash.digest('hex') };\n}\nexport function backupFailure(error: unknown) {\n if (error instanceof SyntaxError || error instanceof ZodError)\n return '\u670D\u52A1\u914D\u7F6E\u65E0\u6548\uFF0C\u5907\u4EFD\u672A\u5B8C\u6210\uFF1B\u8BF7\u68C0\u67E5\u914D\u7F6E\u540E\u91CD\u8BD5\u3002';\n const code = (error as NodeJS.ErrnoException)?.code;\n if (code === 'ENOSPC' || code === 'SQLITE_FULL') return '\u78C1\u76D8\u7A7A\u95F4\u4E0D\u8DB3\uFF0C\u5907\u4EFD\u672A\u5B8C\u6210\u3002';\n if (code === 'EACCES' || code === 'EPERM' || code === 'EROFS')\n return '\u65E0\u6CD5\u5199\u5165\u5907\u4EFD\u76EE\u5F55\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u6743\u9650\u3002';\n if (code === 'ELOCKED') return '\u914D\u7F6E\u6216\u5907\u4EFD\u76EE\u5F55\u6B63\u5728\u88AB\u5176\u4ED6\u64CD\u4F5C\u4F7F\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002';\n return '\u5907\u4EFD\u9A8C\u8BC1\u6216\u6587\u4EF6\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u78C1\u76D8\u3001\u6743\u9650\u53CA\u6587\u4EF6\u5B8C\u6574\u6027\u540E\u91CD\u8BD5\u3002';\n}\n\nexport class BackupStore {\n constructor(readonly options: BackupOptions) {}\n path(id: string) {\n return join(this.options.directory, backupIdSchema.parse(id));\n }\n async record(record: BackupRecord) {\n await saveJson(join(this.path(record.id), 'record.json'), record);\n }\n async list(): Promise<BackupRecord[]> {\n let names: string[];\n try {\n names = await readdir(this.options.directory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n const records: BackupRecord[] = [];\n for (const id of names.filter((name) => backupIdSchema.safeParse(name).success)) {\n try {\n const value = await readJson(join(this.path(id), 'record.json'));\n if (value === undefined) continue;\n const record = backupRecordSchema.parse(value);\n if (record.id !== id) throw new Error('Backup record identity mismatch');\n const parsed = backupManifestSchema.safeParse(\n await readJson(join(this.path(id), 'snapshot.json')),\n );\n if (parsed.success && parsed.data.id === id)\n records.push({\n ...record,\n path: this.path(id),\n phase: ['waiting', 'copying', 'verifying'].includes(record.phase)\n ? 'succeeded'\n : record.phase,\n manifest: parsed.data,\n });\n else\n records.push({\n ...record,\n path: this.path(id),\n phase: record.phase === 'succeeded' ? 'corrupt' : record.phase,\n manifest: undefined,\n });\n } catch {\n records.push({\n id,\n path: this.path(id),\n phase: 'corrupt',\n trigger: 'manual',\n createdAt: 0,\n updatedAt: 0,\n message: '\u5907\u4EFD\u8BB0\u5F55\u635F\u574F\uFF0C\u4E0D\u80FD\u6062\u590D\u3002',\n });\n }\n }\n return records.sort((a, b) => b.createdAt - a.createdAt);\n }\n async create(input: {\n id?: string;\n trigger: BackupManifest['trigger'];\n protectedBy?: string;\n signal?: AbortSignal;\n reserved?: boolean;\n progress?: (record: BackupRecord) => void;\n }): Promise<BackupManifest> {\n const { Sqlite, migrations, config, dataDir, appVersion, commit } = this.options;\n const id = backupIdSchema.parse(input.id ?? randomUUID());\n const directory = this.path(id);\n await mkdir(this.options.directory, { recursive: true, mode: 0o700 });\n if (\n !(await lstat(this.options.directory)).isDirectory() ||\n (await lstat(this.options.directory)).isSymbolicLink()\n )\n throw new Error('Invalid backup directory');\n await chmod(this.options.directory, 0o700);\n // Exclusive creation prevents overwriting a usable backup or replaying the same operation.\n if (input.reserved) {\n const reserved = await readJson<BackupRecord>(join(directory, 'record.json'));\n if (\n reserved?.id !== id ||\n reserved.phase !== 'waiting' ||\n (await readJson(join(directory, 'snapshot.json')))\n )\n throw new Error('Invalid backup reservation');\n } else await mkdir(directory, { mode: 0o700 });\n const record: BackupRecord = {\n id,\n phase: 'copying',\n trigger: input.trigger,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n path: directory,\n message: '\u6B63\u5728\u751F\u6210\u6570\u636E\u5E93\u4E0E\u914D\u7F6E\u5FEB\u7167',\n };\n let release: (() => Promise<void>) | undefined;\n let sqlite: Database.Database | undefined;\n try {\n await this.record(record);\n input.progress?.({ ...record });\n input.signal?.throwIfAborted();\n release = await lockfile.lock(config, { realpath: false, retries: 0 });\n const configStat = await lstat(config);\n if (!configStat.isFile() || configStat.size > MAX_CONFIG_BYTES)\n throw new Error('Invalid config file');\n const contents = await readFile(config, 'utf8');\n if (parseConfig(JSON.parse(contents), config).dataDir !== resolve(dataDir))\n throw new Error('Saved configuration no longer identifies the running data directory');\n const configFile = await open(join(directory, 'config.json'), 'wx', 0o600);\n try {\n await configFile.writeFile(contents);\n await configFile.sync();\n } finally {\n await configFile.close();\n }\n sqlite = new Sqlite(join(dataDir, 'app.sqlite'), { readonly: true, fileMustExist: true });\n const history = inspectDatabase(sqlite, migrations);\n requireRestorable(history.schemaVersion, this.options.contract);\n await sqlite.backup(join(directory, 'app.sqlite'), {\n progress: ({ totalPages, remainingPages }) => {\n input.signal?.throwIfAborted();\n input.progress?.({\n ...record,\n progress: Math.round(((totalPages - remainingPages) / totalPages) * 100),\n });\n return 100;\n },\n });\n sqlite.close();\n sqlite = undefined;\n await chmod(join(directory, 'app.sqlite'), 0o600);\n if ((await readFile(config, 'utf8')) !== contents)\n throw new Error('Configuration changed externally during backup');\n input.signal?.throwIfAborted();\n record.phase = 'verifying';\n record.message = '\u6B63\u5728\u9A8C\u8BC1\u5907\u4EFD\u5B8C\u6574\u6027';\n record.updatedAt = Date.now();\n await this.record(record);\n input.progress?.({ ...record });\n const files = await Promise.all(\n (['app.sqlite', 'config.json'] as const).map(async (name) => ({\n name,\n ...(await fingerprint(join(directory, name))),\n })),\n );\n const manifest = backupManifestSchema.parse({\n formatVersion: 1,\n complete: true,\n id,\n createdAt: record.createdAt,\n appVersion,\n commit,\n trigger: input.trigger,\n configPath: config,\n dataDir,\n schemaVersion: history.schemaVersion,\n migrationHashes: history.migrationHashes,\n files,\n protectedBy: input.protectedBy,\n });\n this.checkDatabase(directory, manifest);\n // Make the copied SQLite durable before publishing the completion manifest.\n const file = await open(join(directory, 'app.sqlite'), 'r');\n try {\n await file.sync();\n } finally {\n await file.close();\n }\n input.signal?.throwIfAborted();\n await saveJson(join(directory, 'snapshot.json'), manifest);\n record.phase = 'succeeded';\n record.message = '\u5907\u4EFD\u6210\u529F\uFF0C\u5B8C\u6574\u6027\u9A8C\u8BC1\u901A\u8FC7';\n record.updatedAt = Date.now();\n record.manifest = manifest;\n await this.record(record).catch(() => {});\n input.progress?.({ ...record });\n return manifest;\n } catch (error) {\n record.phase = input.signal?.aborted ? 'cancelled' : 'failed';\n record.message = input.signal?.aborted\n ? '\u5907\u4EFD\u5DF2\u53D6\u6D88\uFF0C\u672A\u751F\u6210\u53EF\u6062\u590D\u5FEB\u7167\u3002'\n : backupFailure(error);\n record.updatedAt = Date.now();\n await this.record(record).catch(() => {});\n input.progress?.({ ...record });\n throw new AppError('BACKUP_FAILED', record.message, 500);\n } finally {\n sqlite?.close();\n await release?.();\n }\n }\n private checkDatabase(directory: string, manifest: BackupManifest) {\n const sqlite = new this.options.Sqlite(join(directory, 'app.sqlite'), {\n readonly: true,\n fileMustExist: true,\n });\n try {\n if (\n sqlite.pragma('integrity_check', { simple: true }) !== 'ok' ||\n (sqlite.pragma('foreign_key_check') as unknown[]).length\n )\n throw new Error('Invalid backup database');\n const history = inspectDatabase(sqlite, this.options.migrations);\n requireRestorable(history.schemaVersion, this.options.contract);\n if (\n history.schemaVersion !== manifest.schemaVersion ||\n JSON.stringify(history.migrationHashes) !== JSON.stringify(manifest.migrationHashes)\n )\n throw new Error('Backup database differs from manifest');\n } finally {\n sqlite.close();\n }\n }\n async verify(id: string): Promise<BackupManifest> {\n const directory = this.path(id);\n if (!(await lstat(directory)).isDirectory() || (await lstat(directory)).isSymbolicLink())\n throw new Error('Invalid backup directory');\n const manifest = backupManifestSchema.parse(await readJson(join(directory, 'snapshot.json')));\n if (manifest.id !== id) throw new Error('Backup identity mismatch');\n for (const file of manifest.files) {\n const actual = await fingerprint(join(directory, file.name));\n if (actual.size !== file.size || actual.sha256 !== file.sha256)\n throw new Error('Backup checksum mismatch');\n }\n parseFileConfig(JSON.parse(await readFile(join(directory, 'config.json'), 'utf8')));\n this.checkDatabase(directory, manifest);\n return manifest;\n }\n /** Caller must own the instance lock, and must not have resumed business writes. */\n async restoreFiles(id: string) {\n await this.verify(id);\n for (const name of ['app.sqlite-wal', 'app.sqlite-shm'])\n await rm(join(this.options.dataDir, name), { force: true });\n await copyDurable(join(this.path(id), 'app.sqlite'), join(this.options.dataDir, 'app.sqlite'));\n await chmod(join(this.options.dataDir, 'app.sqlite'), 0o600);\n await copyDurable(join(this.path(id), 'config.json'), this.options.config);\n await chmod(this.options.config, 0o600);\n }\n}\n\n/** Read-only verification for snapshots created before versioned manifests existed. */\nexport async function verifyLegacySnapshot(\n directory: string,\n Sqlite: typeof Database,\n migrationsFolder: string,\n) {\n z.object({ complete: z.literal(true) })\n .strict()\n .parse(await readJson(join(directory, 'snapshot.json')));\n parseFileConfig(JSON.parse(await readFile(join(directory, 'config.json'), 'utf8')));\n const db = new Sqlite(join(directory, 'app.sqlite'), { readonly: true, fileMustExist: true });\n try {\n if (\n db.pragma('integrity_check', { simple: true }) !== 'ok' ||\n (db.pragma('foreign_key_check') as unknown[]).length\n )\n throw new Error('\u65E7\u5907\u4EFD\u6570\u636E\u5E93\u635F\u574F');\n inspectDatabase(db, readMigrations(migrationsFolder));\n } finally {\n db.close();\n }\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,GAAG,gBAAgB;AAC5B,SAAS,YAAY,kBAAkB;AACvC,SAAS,wBAAwB;AACjC,SAAS,OAAO,OAAO,OAAO,MAAM,UAAU,SAAS,UAAU;AACjE,SAAS,MAAM,eAAe;AAE9B,OAAO,cAAc;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,gBAAgB;AAEzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,wBAAwB;AACjC,SAAS,aAAa,uBAAuB;AAC7C,SAAS,aAAa,UAAU,gBAAgB;
|
|
4
|
+
"sourcesContent": ["import { z, ZodError } from 'zod';\nimport { createHash, randomUUID } from 'node:crypto';\nimport { createReadStream } from 'node:fs';\nimport { chmod, lstat, mkdir, open, readFile, readdir, rm } from 'node:fs/promises';\nimport { join, resolve } from 'node:path';\nimport type Database from 'better-sqlite3';\nimport lockfile from 'proper-lockfile';\nimport {\n backupIdSchema,\n backupManifestSchema,\n backupRecordSchema,\n type BackupManifest,\n type BackupRecord,\n} from '../shared/backups.js';\nimport { AppError } from '../shared/errors.js';\nimport type { DatabaseCompatibility } from '../shared/database.js';\nimport {\n inspectDatabase,\n readMigrations,\n requireRestorable,\n type Migration,\n} from '../server/db/history.js';\nimport { MAX_CONFIG_BYTES } from '../server/config-store.js';\nimport { parseConfig, parseFileConfig } from '../server/config.js';\nimport { copyDurable, readJson, saveJson } from '../updates/files.js';\nimport { compactDatabase } from './compact.js';\n\nexport interface BackupOptions {\n directory: string;\n config: string;\n dataDir: string;\n appVersion: string;\n commit?: string;\n contract: DatabaseCompatibility;\n migrations: Migration[];\n Sqlite: typeof Database;\n sqliteModulePath: string;\n}\nexport const backupDirectory = (home: string, dataDir: string) =>\n join(home, 'backups', createHash('sha256').update(resolve(dataDir)).digest('hex').slice(0, 16));\n\nasync function fingerprint(path: string) {\n const info = await lstat(path);\n if (!info.isFile() || info.isSymbolicLink())\n throw new Error('Backup contains a non-regular file');\n const hash = createHash('sha256');\n for await (const chunk of createReadStream(path)) hash.update(chunk);\n return { size: info.size, sha256: hash.digest('hex') };\n}\nexport function backupFailure(error: unknown) {\n if (error instanceof SyntaxError || error instanceof ZodError)\n return '\u670D\u52A1\u914D\u7F6E\u65E0\u6548\uFF0C\u5907\u4EFD\u672A\u5B8C\u6210\uFF1B\u8BF7\u68C0\u67E5\u914D\u7F6E\u540E\u91CD\u8BD5\u3002';\n const code = (error as NodeJS.ErrnoException)?.code;\n if (code === 'ENOSPC' || code === 'SQLITE_FULL') return '\u78C1\u76D8\u7A7A\u95F4\u4E0D\u8DB3\uFF0C\u5907\u4EFD\u672A\u5B8C\u6210\u3002';\n if (code === 'EACCES' || code === 'EPERM' || code === 'EROFS')\n return '\u65E0\u6CD5\u5199\u5165\u5907\u4EFD\u76EE\u5F55\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u6743\u9650\u3002';\n if (code === 'ELOCKED') return '\u914D\u7F6E\u6216\u5907\u4EFD\u76EE\u5F55\u6B63\u5728\u88AB\u5176\u4ED6\u64CD\u4F5C\u4F7F\u7528\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002';\n return '\u5907\u4EFD\u9A8C\u8BC1\u6216\u6587\u4EF6\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u78C1\u76D8\u3001\u6743\u9650\u53CA\u6587\u4EF6\u5B8C\u6574\u6027\u540E\u91CD\u8BD5\u3002';\n}\n\nexport class BackupStore {\n constructor(readonly options: BackupOptions) {}\n path(id: string) {\n return join(this.options.directory, backupIdSchema.parse(id));\n }\n async record(record: BackupRecord) {\n await saveJson(join(this.path(record.id), 'record.json'), record);\n }\n async list(): Promise<BackupRecord[]> {\n let names: string[];\n try {\n names = await readdir(this.options.directory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n const records: BackupRecord[] = [];\n for (const id of names.filter((name) => backupIdSchema.safeParse(name).success)) {\n try {\n const value = await readJson(join(this.path(id), 'record.json'));\n if (value === undefined) continue;\n const record = backupRecordSchema.parse(value);\n if (record.id !== id) throw new Error('Backup record identity mismatch');\n const parsed = backupManifestSchema.safeParse(\n await readJson(join(this.path(id), 'snapshot.json')),\n );\n if (parsed.success && parsed.data.id === id)\n records.push({\n ...record,\n path: this.path(id),\n phase: ['waiting', 'copying', 'verifying'].includes(record.phase)\n ? 'succeeded'\n : record.phase,\n manifest: parsed.data,\n });\n else\n records.push({\n ...record,\n path: this.path(id),\n phase: record.phase === 'succeeded' ? 'corrupt' : record.phase,\n manifest: undefined,\n });\n } catch {\n records.push({\n id,\n path: this.path(id),\n phase: 'corrupt',\n trigger: 'manual',\n createdAt: 0,\n updatedAt: 0,\n message: '\u5907\u4EFD\u8BB0\u5F55\u635F\u574F\uFF0C\u4E0D\u80FD\u6062\u590D\u3002',\n });\n }\n }\n return records.sort((a, b) => b.createdAt - a.createdAt);\n }\n /** Caller must hold the maintenance lock and pause application writes. */\n async create(input: {\n id?: string;\n trigger: BackupManifest['trigger'];\n protectedBy?: string;\n signal?: AbortSignal;\n reserved?: boolean;\n progress?: (record: BackupRecord) => void;\n }): Promise<BackupManifest> {\n const { Sqlite, migrations, config, dataDir, appVersion, commit } = this.options;\n const id = backupIdSchema.parse(input.id ?? randomUUID());\n const directory = this.path(id);\n await mkdir(this.options.directory, { recursive: true, mode: 0o700 });\n if (\n !(await lstat(this.options.directory)).isDirectory() ||\n (await lstat(this.options.directory)).isSymbolicLink()\n )\n throw new Error('Invalid backup directory');\n await chmod(this.options.directory, 0o700);\n // Exclusive creation prevents overwriting a usable backup or replaying the same operation.\n if (input.reserved) {\n const reserved = await readJson<BackupRecord>(join(directory, 'record.json'));\n if (\n reserved?.id !== id ||\n reserved.phase !== 'waiting' ||\n (await readJson(join(directory, 'snapshot.json')))\n )\n throw new Error('Invalid backup reservation');\n } else await mkdir(directory, { mode: 0o700 });\n const record: BackupRecord = {\n id,\n phase: 'copying',\n trigger: input.trigger,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n path: directory,\n message: '\u6B63\u5728\u751F\u6210\u6570\u636E\u5E93\u4E0E\u914D\u7F6E\u5FEB\u7167',\n };\n let release: (() => Promise<void>) | undefined;\n let sqlite: Database.Database | undefined;\n try {\n await this.record(record);\n input.progress?.({ ...record });\n input.signal?.throwIfAborted();\n release = await lockfile.lock(config, { realpath: false, retries: 0 });\n const configStat = await lstat(config);\n if (!configStat.isFile() || configStat.size > MAX_CONFIG_BYTES)\n throw new Error('Invalid config file');\n const contents = await readFile(config, 'utf8');\n if (parseConfig(JSON.parse(contents), config).dataDir !== resolve(dataDir))\n throw new Error('Saved configuration no longer identifies the running data directory');\n const configFile = await open(join(directory, 'config.json'), 'wx', 0o600);\n try {\n await configFile.writeFile(contents);\n await configFile.sync();\n } finally {\n await configFile.close();\n }\n const source = join(dataDir, 'app.sqlite');\n sqlite = new Sqlite(source, { readonly: true, fileMustExist: true });\n const history = inspectDatabase(sqlite, migrations);\n requireRestorable(history.schemaVersion, this.options.contract);\n input.signal?.throwIfAborted();\n await compactDatabase(source, this.options.sqliteModulePath);\n input.signal?.throwIfAborted();\n await sqlite.backup(join(directory, 'app.sqlite'), {\n progress: ({ totalPages, remainingPages }) => {\n input.signal?.throwIfAborted();\n input.progress?.({\n ...record,\n progress: Math.round(((totalPages - remainingPages) / totalPages) * 100),\n });\n return 100;\n },\n });\n sqlite.close();\n sqlite = undefined;\n await chmod(join(directory, 'app.sqlite'), 0o600);\n if ((await readFile(config, 'utf8')) !== contents)\n throw new Error('Configuration changed externally during backup');\n input.signal?.throwIfAborted();\n record.phase = 'verifying';\n record.message = '\u6B63\u5728\u9A8C\u8BC1\u5907\u4EFD\u5B8C\u6574\u6027';\n record.updatedAt = Date.now();\n await this.record(record);\n input.progress?.({ ...record });\n const files = await Promise.all(\n (['app.sqlite', 'config.json'] as const).map(async (name) => ({\n name,\n ...(await fingerprint(join(directory, name))),\n })),\n );\n const manifest = backupManifestSchema.parse({\n formatVersion: 1,\n complete: true,\n id,\n createdAt: record.createdAt,\n appVersion,\n commit,\n trigger: input.trigger,\n configPath: config,\n dataDir,\n schemaVersion: history.schemaVersion,\n migrationHashes: history.migrationHashes,\n files,\n protectedBy: input.protectedBy,\n });\n this.checkDatabase(directory, manifest);\n // Make the copied SQLite durable before publishing the completion manifest.\n const file = await open(join(directory, 'app.sqlite'), 'r');\n try {\n await file.sync();\n } finally {\n await file.close();\n }\n input.signal?.throwIfAborted();\n await saveJson(join(directory, 'snapshot.json'), manifest);\n record.phase = 'succeeded';\n record.message = '\u5907\u4EFD\u6210\u529F\uFF0C\u5B8C\u6574\u6027\u9A8C\u8BC1\u901A\u8FC7';\n record.updatedAt = Date.now();\n record.manifest = manifest;\n await this.record(record).catch(() => {});\n input.progress?.({ ...record });\n return manifest;\n } catch (error) {\n record.phase = input.signal?.aborted ? 'cancelled' : 'failed';\n record.message = input.signal?.aborted\n ? '\u5907\u4EFD\u5DF2\u53D6\u6D88\uFF0C\u672A\u751F\u6210\u53EF\u6062\u590D\u5FEB\u7167\u3002'\n : backupFailure(error);\n record.updatedAt = Date.now();\n await this.record(record).catch(() => {});\n input.progress?.({ ...record });\n throw new AppError('BACKUP_FAILED', record.message, 500);\n } finally {\n sqlite?.close();\n await release?.();\n }\n }\n private checkDatabase(directory: string, manifest: BackupManifest) {\n const sqlite = new this.options.Sqlite(join(directory, 'app.sqlite'), {\n readonly: true,\n fileMustExist: true,\n });\n try {\n if (\n sqlite.pragma('integrity_check', { simple: true }) !== 'ok' ||\n (sqlite.pragma('foreign_key_check') as unknown[]).length\n )\n throw new Error('Invalid backup database');\n const history = inspectDatabase(sqlite, this.options.migrations);\n requireRestorable(history.schemaVersion, this.options.contract);\n if (\n history.schemaVersion !== manifest.schemaVersion ||\n JSON.stringify(history.migrationHashes) !== JSON.stringify(manifest.migrationHashes)\n )\n throw new Error('Backup database differs from manifest');\n } finally {\n sqlite.close();\n }\n }\n async verify(id: string): Promise<BackupManifest> {\n const directory = this.path(id);\n if (!(await lstat(directory)).isDirectory() || (await lstat(directory)).isSymbolicLink())\n throw new Error('Invalid backup directory');\n const manifest = backupManifestSchema.parse(await readJson(join(directory, 'snapshot.json')));\n if (manifest.id !== id) throw new Error('Backup identity mismatch');\n for (const file of manifest.files) {\n const actual = await fingerprint(join(directory, file.name));\n if (actual.size !== file.size || actual.sha256 !== file.sha256)\n throw new Error('Backup checksum mismatch');\n }\n parseFileConfig(JSON.parse(await readFile(join(directory, 'config.json'), 'utf8')));\n this.checkDatabase(directory, manifest);\n return manifest;\n }\n /** Caller must own the instance lock, and must not have resumed business writes. */\n async restoreFiles(id: string) {\n await this.verify(id);\n for (const name of ['app.sqlite-wal', 'app.sqlite-shm'])\n await rm(join(this.options.dataDir, name), { force: true });\n await copyDurable(join(this.path(id), 'app.sqlite'), join(this.options.dataDir, 'app.sqlite'));\n await chmod(join(this.options.dataDir, 'app.sqlite'), 0o600);\n await copyDurable(join(this.path(id), 'config.json'), this.options.config);\n await chmod(this.options.config, 0o600);\n }\n}\n\n/** Read-only verification for snapshots created before versioned manifests existed. */\nexport async function verifyLegacySnapshot(\n directory: string,\n Sqlite: typeof Database,\n migrationsFolder: string,\n) {\n z.object({ complete: z.literal(true) })\n .strict()\n .parse(await readJson(join(directory, 'snapshot.json')));\n parseFileConfig(JSON.parse(await readFile(join(directory, 'config.json'), 'utf8')));\n const db = new Sqlite(join(directory, 'app.sqlite'), { readonly: true, fileMustExist: true });\n try {\n if (\n db.pragma('integrity_check', { simple: true }) !== 'ok' ||\n (db.pragma('foreign_key_check') as unknown[]).length\n )\n throw new Error('\u65E7\u5907\u4EFD\u6570\u636E\u5E93\u635F\u574F');\n inspectDatabase(db, readMigrations(migrationsFolder));\n } finally {\n db.close();\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,GAAG,gBAAgB;AAC5B,SAAS,YAAY,kBAAkB;AACvC,SAAS,wBAAwB;AACjC,SAAS,OAAO,OAAO,OAAO,MAAM,UAAU,SAAS,UAAU;AACjE,SAAS,MAAM,eAAe;AAE9B,OAAO,cAAc;AACrB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,gBAAgB;AAEzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,wBAAwB;AACjC,SAAS,aAAa,uBAAuB;AAC7C,SAAS,aAAa,UAAU,gBAAgB;AAChD,SAAS,uBAAuB;AAazB,MAAM,kBAAkB,CAAC,MAAc,YAC5C,KAAK,MAAM,WAAW,WAAW,QAAQ,EAAE,OAAO,QAAQ,OAAO,CAAC,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE,CAAC;AAEhG,eAAe,YAAY,MAAc;AACvC,QAAM,OAAO,MAAM,MAAM,IAAI;AAC7B,MAAI,CAAC,KAAK,OAAO,KAAK,KAAK,eAAe;AACxC,UAAM,IAAI,MAAM,o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AQ,MAAM;AACzE,UAAM,MAAM,KAAK,QAAQ,QAAQ,GAAK;AAAA,EACxC;AACF;AAGA,eAAsB,qBACpB,WACA,QACA,kBACA;AACA,IAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,IAAI,EAAE,CAAC,EACnC,OAAO,EACP,MAAM,MAAM,SAAS,KAAK,WAAW,eAAe,CAAC,CAAC;AACzD,kBAAgB,KAAK,MAAM,MAAM,SAAS,KAAK,WAAW,aAAa,GAAG,MAAM,CAAC,CAAC;AAClF,QAAM,KAAK,IAAI,OAAO,KAAK,WAAW,YAAY,GAAG,EAAE,UAAU,MAAM,eAAe,KAAK,CAAC;AAC5F,MAAI;AACF,QACE,GAAG,OAAO,mBAAmB,EAAE,QAAQ,KAAK,CAAC,MAAM,QAClD,GAAG,OAAO,mBAAmB,EAAgB;AAE9C,YAAM,IAAI,MAAM,kDAAU;AAC5B,oBAAgB,IAAI,eAAe,gBAAgB,CAAC;AAAA,EACtD,UAAE;AACA,OAAG,MAAM;AAAA,EACX;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/update-worker.cjs
CHANGED
|
@@ -2044,7 +2044,7 @@ var require_thread_stream = __commonJS({
|
|
|
2044
2044
|
"use strict";
|
|
2045
2045
|
var { version: version3 } = require_package();
|
|
2046
2046
|
var { EventEmitter } = require("events");
|
|
2047
|
-
var { Worker } = require("worker_threads");
|
|
2047
|
+
var { Worker: Worker2 } = require("worker_threads");
|
|
2048
2048
|
var { join: join15 } = require("path");
|
|
2049
2049
|
var { pathToFileURL } = require("url");
|
|
2050
2050
|
var { wait } = require_wait();
|
|
@@ -2098,7 +2098,7 @@ var require_thread_stream = __commonJS({
|
|
|
2098
2098
|
const { filename, workerData } = opts;
|
|
2099
2099
|
const bundlerOverrides = "__bundlerPathsOverrides" in globalThis ? globalThis.__bundlerPathsOverrides : {};
|
|
2100
2100
|
const toExecute = bundlerOverrides["thread-stream-worker"] || join15(__dirname, "lib", "worker.js");
|
|
2101
|
-
const worker2 = new
|
|
2101
|
+
const worker2 = new Worker2(toExecute, {
|
|
2102
2102
|
...opts.workerOpts,
|
|
2103
2103
|
name: opts.workerOpts?.name || "thread-stream",
|
|
2104
2104
|
trackUnmanagedFds: false,
|
|
@@ -38304,6 +38304,49 @@ async function copyDurable(source, target) {
|
|
|
38304
38304
|
await syncDirectory((0, import_node_path5.dirname)(target));
|
|
38305
38305
|
}
|
|
38306
38306
|
|
|
38307
|
+
// src/backups/compact.ts
|
|
38308
|
+
var import_node_worker_threads = require("node:worker_threads");
|
|
38309
|
+
var script = `
|
|
38310
|
+
const { parentPort, workerData } = require('node:worker_threads');
|
|
38311
|
+
try {
|
|
38312
|
+
const Sqlite = require(workerData.sqliteModulePath);
|
|
38313
|
+
const db = new Sqlite(workerData.filename, { fileMustExist: true });
|
|
38314
|
+
try {
|
|
38315
|
+
db.exec('VACUUM');
|
|
38316
|
+
// In WAL mode the main file only shrinks once the new pages are checkpointed.
|
|
38317
|
+
const [checkpoint] = db.pragma('wal_checkpoint(TRUNCATE)');
|
|
38318
|
+
if (checkpoint.busy) {
|
|
38319
|
+
throw Object.assign(new Error('WAL checkpoint was blocked'), { code: 'SQLITE_BUSY' });
|
|
38320
|
+
}
|
|
38321
|
+
} finally {
|
|
38322
|
+
db.close();
|
|
38323
|
+
}
|
|
38324
|
+
} catch (error) {
|
|
38325
|
+
parentPort.postMessage(error.code || 'SQLITE_COMPACTION_FAILED');
|
|
38326
|
+
}
|
|
38327
|
+
`;
|
|
38328
|
+
function compactDatabase(filename, sqliteModulePath) {
|
|
38329
|
+
return new Promise((resolve4, reject) => {
|
|
38330
|
+
const worker2 = new import_node_worker_threads.Worker(script, {
|
|
38331
|
+
eval: true,
|
|
38332
|
+
execArgv: [],
|
|
38333
|
+
workerData: { filename, sqliteModulePath }
|
|
38334
|
+
});
|
|
38335
|
+
let error62;
|
|
38336
|
+
worker2.once("message", (code) => {
|
|
38337
|
+
error62 = Object.assign(new Error("Source database compaction failed"), { code });
|
|
38338
|
+
});
|
|
38339
|
+
worker2.once("error", (failure2) => {
|
|
38340
|
+
error62 = failure2;
|
|
38341
|
+
});
|
|
38342
|
+
worker2.once("exit", (code) => {
|
|
38343
|
+
if (error62) reject(error62);
|
|
38344
|
+
else if (code !== 0) reject(new Error("Database compaction worker exited early"));
|
|
38345
|
+
else resolve4();
|
|
38346
|
+
});
|
|
38347
|
+
});
|
|
38348
|
+
}
|
|
38349
|
+
|
|
38307
38350
|
// src/backups/store.ts
|
|
38308
38351
|
var backupDirectory = (home, dataDir) => (0, import_node_path6.join)(home, "backups", (0, import_node_crypto4.createHash)("sha256").update((0, import_node_path6.resolve)(dataDir)).digest("hex").slice(0, 16));
|
|
38309
38352
|
async function fingerprint(path) {
|
|
@@ -38381,6 +38424,7 @@ var BackupStore = class {
|
|
|
38381
38424
|
}
|
|
38382
38425
|
return records.sort((a, b) => b.createdAt - a.createdAt);
|
|
38383
38426
|
}
|
|
38427
|
+
/** Caller must hold the maintenance lock and pause application writes. */
|
|
38384
38428
|
async create(input2) {
|
|
38385
38429
|
const { Sqlite, migrations, config: config2, dataDir, appVersion, commit } = this.options;
|
|
38386
38430
|
const id = backupIdSchema.parse(input2.id ?? (0, import_node_crypto4.randomUUID)());
|
|
@@ -38423,9 +38467,13 @@ var BackupStore = class {
|
|
|
38423
38467
|
} finally {
|
|
38424
38468
|
await configFile.close();
|
|
38425
38469
|
}
|
|
38426
|
-
|
|
38470
|
+
const source = (0, import_node_path6.join)(dataDir, "app.sqlite");
|
|
38471
|
+
sqlite = new Sqlite(source, { readonly: true, fileMustExist: true });
|
|
38427
38472
|
const history = inspectDatabase(sqlite, migrations);
|
|
38428
38473
|
requireRestorable(history.schemaVersion, this.options.contract);
|
|
38474
|
+
input2.signal?.throwIfAborted();
|
|
38475
|
+
await compactDatabase(source, this.options.sqliteModulePath);
|
|
38476
|
+
input2.signal?.throwIfAborted();
|
|
38429
38477
|
await sqlite.backup((0, import_node_path6.join)(directory, "app.sqlite"), {
|
|
38430
38478
|
progress: ({ totalPages, remainingPages }) => {
|
|
38431
38479
|
input2.signal?.throwIfAborted();
|
|
@@ -39832,9 +39880,9 @@ async function workerCore(directory, logger) {
|
|
|
39832
39880
|
const sameRoot = paths.root.replace(/\/$/, "") === context2.root.replace(/\/$/, "");
|
|
39833
39881
|
const originalRoot = sameRoot && previousMetadata?.version === record2.from ? paths.previous : context2.root;
|
|
39834
39882
|
const originalMetadata = await readJson((0, import_node_path16.join)(originalRoot, "package.json"));
|
|
39835
|
-
const
|
|
39836
|
-
|
|
39837
|
-
);
|
|
39883
|
+
const requireOriginal = (0, import_node_module.createRequire)((0, import_node_path16.join)(originalRoot, "package.json"));
|
|
39884
|
+
const sqliteModulePath = requireOriginal.resolve("better-sqlite3");
|
|
39885
|
+
const Sqlite = requireOriginal(sqliteModulePath);
|
|
39838
39886
|
const migrations = readMigrations((0, import_node_path16.join)(originalRoot, "dist/drizzle"));
|
|
39839
39887
|
const backups = new BackupStore({
|
|
39840
39888
|
directory: backupDirectory(context2.location.home, context2.dataDir),
|
|
@@ -39850,6 +39898,7 @@ async function workerCore(directory, logger) {
|
|
|
39850
39898
|
}
|
|
39851
39899
|
),
|
|
39852
39900
|
Sqlite,
|
|
39901
|
+
sqliteModulePath,
|
|
39853
39902
|
migrations
|
|
39854
39903
|
});
|
|
39855
39904
|
if (process.argv[3] === "--repair") {
|
package/dist/updates/worker.js
CHANGED
|
@@ -152,9 +152,9 @@ async function workerCore(directory, logger) {
|
|
|
152
152
|
const sameRoot = paths.root.replace(/\/$/, "") === context.root.replace(/\/$/, "");
|
|
153
153
|
const originalRoot = sameRoot && previousMetadata?.version === record.from ? paths.previous : context.root;
|
|
154
154
|
const originalMetadata = await readJson(join(originalRoot, "package.json"));
|
|
155
|
-
const
|
|
156
|
-
|
|
157
|
-
);
|
|
155
|
+
const requireOriginal = createRequire(join(originalRoot, "package.json"));
|
|
156
|
+
const sqliteModulePath = requireOriginal.resolve("better-sqlite3");
|
|
157
|
+
const Sqlite = requireOriginal(sqliteModulePath);
|
|
158
158
|
const migrations = readMigrations(join(originalRoot, "dist/drizzle"));
|
|
159
159
|
const backups = new BackupStore({
|
|
160
160
|
directory: backupDirectory(context.location.home, context.dataDir),
|
|
@@ -170,6 +170,7 @@ async function workerCore(directory, logger) {
|
|
|
170
170
|
}
|
|
171
171
|
),
|
|
172
172
|
Sqlite,
|
|
173
|
+
sqliteModulePath,
|
|
173
174
|
migrations
|
|
174
175
|
});
|
|
175
176
|
if (process.argv[3] === "--repair") {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/updates/worker.ts"],
|
|
4
|
-
"sourcesContent": ["import { loggingOptions } from '../logging/config.js';\nimport { monitorCrashes } from '../logging/lifecycle.js';\nimport { createLogging, type Logger } from '../logging/logger.js';\nimport { errorFields } from '../logging/fields.js';\nimport { BackupStore, backupDirectory, verifyLegacySnapshot } from '../backups/store.js';\nimport { acquireMaintenanceLock } from '../backups/lock.js';\nimport { acquireInstanceLock } from '../server/instance-lock.js';\nimport { inspectDatabase, readMigrations } from '../server/db/history.js';\nimport { databaseCompatibilitySchema } from '../shared/database.js';\nimport { npmPackageName } from '../shared/package.js';\nimport {\n codexCompatibilitySchema,\n requireCodexCompatibility,\n} from '../shared/codex-compatibility.js';\n// Bundled with its pure JavaScript dependencies and copied outside the installation before launch.\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { createRequire } from 'node:module';\nimport { access, mkdir, readdir, rm, rename } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { setTimeout } from 'node:timers/promises';\nimport lockfile from 'proper-lockfile';\nimport type Database from 'better-sqlite3';\nimport type { UpdateRun, RuntimeIdentity } from '../shared/updates.js';\nimport type { UpdateContext } from './manager.js';\nimport { control, isNotRunning } from '../cli/control.js';\nimport { startBackground, stopBackground } from '../cli/background.js';\nimport { copyDurable, readJson, saveJson } from './files.js';\nimport { confirmAutomaticFreeze, waitForAutomaticPlan } from './plan.js';\nimport { activateUpdate, transactionPaths } from './transaction.js';\nimport { inspectInstallation, registry } from './registry.js';\nimport {\n assertRuntime,\n resolveRuntimeTarget,\n targetNpmEnvironment,\n verifyRuntimeExecutable,\n} from './runtime.js';\nimport {\n snapshotLaunch,\n switchLaunch,\n restoreLaunch,\n type LaunchSnapshot,\n} from '../cli/runtime-launch.js';\nimport { probeRestartCodex, assertCodexTarget } from './codex-target.js';\nimport { assertCodexIdentity, type CodexIdentity } from '../codex/identity.js';\n\nconst exec = promisify(execFile);\nconst message = (error: unknown) => (error instanceof Error ? error.message : String(error));\ntype DaemonStatus = {\n version: string;\n pid: number;\n maintenance?: boolean;\n codexVersion?: string | null;\n codexReady?: boolean;\n codexIdentity?: CodexIdentity;\n runtime?: RuntimeIdentity;\n};\n\nasync function startService(context: UpdateContext, candidate = false) {\n // Shared with `covro start`: never inherit a Background security session on macOS.\n // Activation is checked from the durable update record by the daemon.\n const target = candidate ? context.target : undefined;\n await startBackground(\n context.location,\n join(context.root, 'bin/covro.mjs'),\n target ? { node: target.node, entry: target.entry, path: target.path } : context.source,\n );\n}\nasync function stopService(context: UpdateContext) {\n await stopBackground(context.location);\n}\n\nasync function verifyRestoredService(context: UpdateContext, version: string) {\n for (let attempt = 0; attempt < 240; attempt++) {\n try {\n const restored = await control<DaemonStatus>(context.location, 'status');\n if (restored.version !== version || restored.maintenance)\n throw new Error('\u65E7\u7248\u6062\u590D\u8EAB\u4EFD\u4E0D\u5339\u914D');\n const record = await readJson<UpdateRun>(join(context.directory, 'run.json'));\n if (record?.runtime) assertRuntime(restored.runtime, record.runtime.from);\n return;\n } catch (error) {\n if (attempt === 239) throw error;\n }\n await setTimeout(250);\n }\n}\n\nasync function verifyMigrations(context: UpdateContext, candidate: string) {\n // Loading the existing native addon happens before any package path is replaced.\n const require = createRequire(join(context.root, 'package.json'));\n const Sqlite = require('better-sqlite3') as typeof Database;\n const filename = join(context.dataDir, 'app.sqlite');\n try {\n await access(filename);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw error;\n }\n const db = new Sqlite(filename, { readonly: true, fileMustExist: true });\n try {\n const migrations = readMigrations(join(candidate, 'dist/drizzle'));\n const metadata = await readJson<{ covroDatabase?: unknown }>(join(candidate, 'package.json'));\n if (metadata?.covroDatabase) {\n const contract = databaseCompatibilitySchema.parse(metadata.covroDatabase);\n if (contract.schemaVersion !== migrations.length)\n throw new Error('\u76EE\u6807\u7248\u672C\u7684 Schema \u58F0\u660E\u4E0E\u8FC1\u79FB\u4E0D\u4E00\u81F4');\n }\n inspectDatabase(db, migrations);\n } finally {\n db.close();\n }\n}\n\nasync function workerCore(directory: string, logger: Logger) {\n await mkdir(directory, { recursive: true, mode: 0o700 });\n const release = await lockfile.lock(directory, {\n stale: 10_000,\n update: 2_000,\n retries: { retries: 30, minTimeout: 100, maxTimeout: 500 },\n });\n let record = await readJson<UpdateRun>(join(directory, 'run.json'));\n const context = await readJson<UpdateContext>(join(directory, 'context.json'));\n if (!record || !context) {\n await release();\n throw new Error('\u7F3A\u5C11\u5347\u7EA7\u8BB0\u5F55');\n }\n const update = async (phase: UpdateRun['phase'], detail: string) => {\n record = { ...record!, phase, message: detail, updatedAt: Date.now() };\n await saveJson(join(directory, 'run.json'), record);\n logger.info('update.phase_changed', { updateId: record.id, stage: phase });\n };\n let paths = transactionPaths(\n context.target?.root ?? context.root,\n record.id,\n context.dataDir,\n context.location.config,\n join(backupDirectory(context.location.home, context.dataDir), record.id),\n );\n let releaseMaintenance: (() => Promise<void>) | undefined;\n let releaseData: (() => Promise<void>) | undefined;\n try {\n if (record.automatic && !record.transactionStartedAt && process.argv[3] !== '--repair') {\n record = await waitForAutomaticPlan(record, {\n status: (fresh) =>\n control(context.location, 'automatic-update-plan', { id: record!.id, fresh }),\n readiness: () => control(context.location, 'update-readiness'),\n save: async (next) => {\n record = next;\n await saveJson(join(directory, 'run.json'), record);\n },\n freeze: (checkedAt) =>\n confirmAutomaticFreeze(\n record!.id,\n () =>\n control(context.location, 'freeze-automatic-update', { id: record!.id, checkedAt }),\n () => readJson<UpdateRun>(join(directory, 'run.json')),\n ),\n pause: () => setTimeout(2_000),\n });\n const frozen = await readJson<UpdateContext>(join(directory, 'context.json'));\n if (!frozen) throw new Error('\u7F3A\u5C11\u56FA\u5B9A\u76EE\u6807\u8FD0\u884C\u73AF\u5883');\n Object.assign(context, frozen);\n paths = transactionPaths(\n context.target?.root ?? context.root,\n record.id,\n context.dataDir,\n context.location.config,\n join(backupDirectory(context.location.home, context.dataDir), record.id),\n );\n }\n if (record.runtime) await verifyRuntimeExecutable(record.runtime.from);\n const previousMetadata = await readJson<{ version: string }>(\n join(paths.previous, 'package.json'),\n );\n const sameRoot = paths.root.replace(/\\/$/, '') === context.root.replace(/\\/$/, '');\n const originalRoot =\n sameRoot && previousMetadata?.version === record.from ? paths.previous : context.root;\n const originalMetadata = await readJson<{\n version: string;\n covroCommit?: string;\n covroDatabase?: unknown;\n }>(join(originalRoot, 'package.json'));\n const Sqlite = createRequire(join(originalRoot, 'package.json'))(\n 'better-sqlite3',\n ) as typeof Database;\n const migrations = readMigrations(join(originalRoot, 'dist/drizzle'));\n const backups = new BackupStore({\n directory: backupDirectory(context.location.home, context.dataDir),\n config: paths.config,\n dataDir: paths.dataDir,\n appVersion: record.from,\n commit: originalMetadata?.covroCommit,\n contract: databaseCompatibilitySchema.parse(\n originalMetadata?.covroDatabase ?? {\n schemaVersion: migrations.length,\n minRestorableSchemaVersion: 1,\n backupFormatVersion: 1,\n },\n ),\n Sqlite,\n migrations,\n });\n if (process.argv[3] === '--repair') {\n releaseMaintenance = await acquireMaintenanceLock(context.dataDir);\n if (!(await readJson(join(paths.backup, 'snapshot.json'))))\n paths.backup = join(directory, `backup-${record.id}`);\n const active = await control<DaemonStatus>(context.location, 'status').catch(\n (error: unknown) => {\n if (isNotRunning(error)) return undefined;\n throw error;\n },\n );\n if (record.committed) return;\n if (active && !active.maintenance && active.version !== record.from)\n throw new Error('\u5F53\u524D\u670D\u52A1\u53EF\u80FD\u5DF2\u63A5\u53D7\u65B0\u7248\u4E1A\u52A1\u6570\u636E\uFF1B\u62D2\u7EDD\u6062\u590D\u65E7\u5FEB\u7167\uFF0C\u8BF7\u4F7F\u7528\u517C\u5BB9\u7248\u672C\u68C0\u67E5\u3002');\n const previous = await readJson<{ version: string; name: string }>(\n join(paths.previous, 'package.json'),\n );\n if (previous || context.reuseTarget) {\n if (active && !active.maintenance)\n throw new Error('\u65E7\u670D\u52A1\u5DF2\u6062\u590D\u4E1A\u52A1\u5199\u5165\uFF1B\u62D2\u7EDD\u7528\u5347\u7EA7\u524D\u5FEB\u7167\u8986\u76D6\u73B0\u6709\u6570\u636E\uFF0C\u8BF7\u4FDD\u7559\u73B0\u573A\u68C0\u67E5\u3002');\n if (\n previous &&\n (previous.name !== npmPackageName ||\n previous.version !== (context.target?.version ?? record.from))\n )\n throw new Error('\u65E7\u7248\u5907\u4EFD\u8EAB\u4EFD\u4E0D\u5339\u914D');\n const snapshot = await readJson<{ complete: boolean; formatVersion?: number }>(\n join(paths.backup, 'snapshot.json'),\n );\n if (snapshot?.formatVersion === 1) {\n const verified = await backups.verify(record.id);\n if (\n verified.appVersion !== record.from ||\n verified.protectedBy !== record.id ||\n verified.configPath !== paths.config ||\n verified.dataDir !== paths.dataDir\n )\n throw new Error('\u5907\u4EFD\u8EAB\u4EFD\u4E0D\u5339\u914D');\n } else await verifyLegacySnapshot(paths.backup, Sqlite, join(originalRoot, 'dist/drizzle'));\n } else if (sameRoot) {\n const original = await readJson<{ name: string; version: string }>(\n join(paths.root, 'package.json'),\n );\n if (original?.name !== npmPackageName || original.version !== record.from)\n throw new Error('\u672A\u627E\u5230\u5B8C\u6574\u7684\u4E0A\u4E00\u7248\u672C\u5B89\u88C5');\n }\n if (active && !active.maintenance) {\n const admission = await control<{ ready: boolean }>(context.location, 'prepare-update');\n if (!admission.ready) throw new Error('\u4ECD\u6709\u4EFB\u52A1\u3001\u5BA1\u6279\u6216\u5F85\u6838\u5BF9\u64CD\u4F5C\uFF0C\u4E0D\u80FD\u6062\u590D\u65E7\u5B89\u88C5');\n }\n await stopService(context);\n releaseData = await acquireInstanceLock(context.dataDir);\n if (previous) {\n await rm(paths.root, { recursive: true, force: true });\n await rename(paths.previous, paths.root);\n }\n if (previous || context.reuseTarget) {\n for (const name of ['app.sqlite', 'app.sqlite-wal', 'app.sqlite-shm']) {\n await rm(join(paths.dataDir, name), { force: true });\n try {\n await copyDurable(join(paths.backup, name), join(paths.dataDir, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n }\n await copyDurable(join(paths.backup, 'config.json'), paths.config);\n }\n const launch = await readJson<LaunchSnapshot>(join(directory, `launch-${record.id}.json`));\n if (launch) await restoreLaunch(context.location, launch);\n const restored = await readJson<{ name: string; version: string }>(\n join(context.root, 'package.json'),\n );\n if (restored?.name !== npmPackageName || restored.version !== record.from)\n throw new Error('\u672A\u627E\u5230\u5B8C\u6574\u7684\u4E0A\u4E00\u7248\u672C\u5B89\u88C5');\n await update('rolledBack', '\u5DF2\u6062\u590D\u4E0A\u6B21\u672A\u5B8C\u6210\u7684\u5347\u7EA7\uFF0C\u6B63\u5728\u542F\u52A8\u4E0A\u4E00\u7248\u672C');\n try {\n await releaseData?.();\n releaseData = undefined;\n await startService(context);\n await verifyRestoredService(context, record.from);\n await update('rolledBack', '\u5DF2\u6062\u590D\u4E0A\u6B21\u672A\u5B8C\u6210\u7684\u5347\u7EA7\uFF0C\u4E0A\u4E00\u7248\u672C\u5DF2\u5C31\u7EEA');\n } catch (error) {\n await update('failed', `\u65E7\u7248\u6062\u590D\u542F\u52A8\u5931\u8D25\uFF0C\u4FDD\u7559\u5907\u4EFD\uFF1A${message(error)}`);\n throw error;\n }\n return;\n }\n const reason = await inspectInstallation(context.root);\n if (reason) throw new Error(reason);\n // A second managed configuration must be stopped before replacing their shared npm package.\n for (const key of await readdir(join(context.location.home, 'instances'))) {\n if (key === context.location.key) continue;\n const instance = await readJson<{ root: string; config: string; socket: string }>(\n join(context.location.home, 'instances', key, 'instance.json'),\n );\n if (\n !instance ||\n ![context.root.replace(/\\/$/, ''), paths.root].includes(instance.root.replace(/\\/$/, ''))\n )\n continue;\n try {\n await control({ ...context.location, socket: instance.socket }, 'status');\n throw new Error('\u540C\u4E00 npm \u5B89\u88C5\u8FD8\u6709\u5176\u4ED6 Covro \u5B9E\u4F8B\uFF0C\u8BF7\u5148\u505C\u6B62\u5176\u4ED6\u5B9E\u4F8B\u518D\u5347\u7EA7\u3002');\n } catch (error) {\n if (!isNotRunning(error)) throw error;\n }\n }\n await access(dirname(context.root), constants.W_OK);\n await access(dirname(paths.root), constants.W_OK);\n if (context.target) {\n const target = await resolveRuntimeTarget();\n assertRuntime(target, context.target);\n if (\n target.npm !== context.target.npm ||\n target.npmVersion !== context.target.npmVersion ||\n target.prefix !== context.target.prefix ||\n target.path !== context.target.path ||\n target.version !== context.target.version\n )\n throw new Error('\u76EE\u6807 Node/npm \u73AF\u5883\u5728\u68C0\u67E5\u540E\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0\u3002');\n }\n const candidateRoot = context.reuseTarget ? paths.root : paths.candidate;\n const node = context.target?.node ?? process.execPath;\n const env = targetNpmEnvironment(\n context.target?.path ?? process.env.PATH ?? '/usr/bin:/bin',\n context.target?.npmConfig,\n );\n const restartRuntime = context.target ?? context.source;\n if (!record.codex?.target || !restartRuntime)\n throw new Error('\u7F3A\u5C11\u91CD\u542F\u76EE\u6807 Codex \u6765\u6E90\u8BB0\u5F55\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0');\n if (record.codex.version !== record.codex.target.identity.version)\n throw new Error('Codex \u7248\u672C\u4E0E\u91CD\u542F\u76EE\u6807\u6765\u6E90\u8BB0\u5F55\u4E0D\u5339\u914D\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0');\n let probeRoot = context.reuseTarget ? candidateRoot : context.root;\n const checkRestartCodex = async () => {\n const actual = await probeRestartCodex(\n context.location,\n context.root,\n restartRuntime,\n context.source,\n probeRoot,\n );\n assertCodexTarget(actual, record!.codex!.target!);\n requireCodexCompatibility(\n record!.codex!.manifest,\n actual.identity.version,\n record!.codex!.confirmedUnverified,\n 'restart',\n );\n };\n // Recheck before npm installation as well as after every wait. Never compare against the old process.\n await checkRestartCodex();\n // npm global layout keeps production dependencies nested in the package being swapped.\n if (!context.reuseTarget)\n await exec(\n context.target?.node ?? 'npm',\n [\n ...(context.target ? [context.target.npm] : []),\n 'install',\n '--global',\n '--prefix',\n paths.prefix,\n '--omit=dev',\n '--no-audit',\n '--no-fund',\n `--registry=${registry}`,\n '--allow-scripts=better-sqlite3',\n `${npmPackageName}@${record.target}`,\n ],\n { env, timeout: 10 * 60_000, maxBuffer: 2 * 1024 * 1024 },\n );\n const candidate = await readJson<{\n name: string;\n version: string;\n covroCodex?: unknown;\n covroCommit?: string;\n gitHead?: string;\n }>(join(candidateRoot, 'package.json'));\n if (candidate?.name !== npmPackageName || candidate.version !== record.target)\n throw new Error('\u5019\u9009\u5305\u8EAB\u4EFD\u6216\u7248\u672C\u4E0D\u5339\u914D');\n if (record.commit && (candidate.covroCommit ?? candidate.gitHead) !== record.commit)\n throw new Error('\u5019\u9009\u5305\u6E90\u7801\u63D0\u4EA4\u4E0E\u68C0\u67E5\u65F6\u4E0D\u4E00\u81F4\uFF0C\u62D2\u7EDD\u5207\u6362');\n if (!record.codex) throw new Error('\u7F3A\u5C11 Codex \u5347\u7EA7\u6821\u9A8C\u8BB0\u5F55\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0');\n const manifest = codexCompatibilitySchema.parse(candidate.covroCodex);\n if (JSON.stringify(manifest) !== JSON.stringify(record.codex.manifest))\n throw new Error('\u5019\u9009\u5305\u7684 Codex \u517C\u5BB9\u58F0\u660E\u4E0E\u68C0\u67E5\u65F6\u4E0D\u4E00\u81F4\uFF0C\u62D2\u7EDD\u5207\u6362');\n const checkRunningCodex = (state: DaemonStatus) => {\n if (state.codexVersion !== record!.codex!.version)\n throw new Error('\u91CD\u542F\u540E\u7684 Codex \u7248\u672C\u4E0E\u5347\u7EA7\u6821\u9A8C\u8BB0\u5F55\u4E0D\u5339\u914D');\n assertCodexIdentity(state.codexIdentity, record!.codex!.target!.identity);\n requireCodexCompatibility(\n manifest,\n state.codexVersion ?? null,\n record!.codex!.confirmedUnverified,\n );\n };\n probeRoot = candidateRoot;\n await checkRestartCodex();\n const versionProbe = await exec(node, [join(candidateRoot, 'bin/covro.mjs'), '--version'], {\n timeout: 30_000,\n env,\n });\n if (versionProbe.stdout.trim() !== record.target)\n throw new Error('\u76EE\u6807 Node \u6267\u884C Covro \u5165\u53E3\u540E\u8FD4\u56DE\u7684\u7248\u672C\u4E0D\u5339\u914D');\n const nativeProbe =\n 'const {createRequire}=await import(\"node:module\"); const r=createRequire(process.argv[1]); const DB=r(\"better-sqlite3\"); const db=new DB(\":memory:\"); db.close();';\n await exec(\n node,\n ['--input-type=module', '-e', nativeProbe, join(candidateRoot, 'package.json')],\n { env, timeout: 30_000 },\n );\n await verifyMigrations(context, candidateRoot);\n const launch: LaunchSnapshot = await snapshotLaunch(\n context.location,\n context.source ?? {\n node: process.execPath,\n entry: join(context.root, 'bin/covro.mjs'),\n path: process.env.PATH ?? '/usr/bin:/bin',\n },\n );\n if (context.target)\n launch.target = { node, entry: context.target.entry, path: context.target.path };\n await saveJson(join(directory, `launch-${record.id}.json`), launch);\n releaseMaintenance = await acquireMaintenanceLock(context.dataDir);\n await activateUpdate(\n paths,\n {\n backup: async () => {\n releaseData = await acquireInstanceLock(context.dataDir);\n await backups.create({ id: record!.id, trigger: 'preUpgrade', protectedBy: record!.id });\n },\n restore: async () => {\n releaseData ??= await acquireInstanceLock(context.dataDir);\n await backups.restoreFiles(record!.id);\n },\n switchLaunch: context.target\n ? () =>\n switchLaunch(\n context.location,\n { node, entry: context.target!.entry, path: context.target!.path },\n launch,\n )\n : undefined,\n restoreLaunch: () => restoreLaunch(context.location, launch),\n phase: update,\n waitForIdle: async () => {\n // Queue without blocking normal work; admission closes atomically only after all blockers clear.\n for (;;) {\n await checkRestartCodex();\n const result = await control<{ ready: boolean; reason?: string }>(\n context.location,\n 'prepare-update',\n );\n if (result.ready) {\n await checkRestartCodex();\n await verifyMigrations(context, candidateRoot);\n const pinned = await readJson<typeof candidate>(join(candidateRoot, 'package.json'));\n if (JSON.stringify(pinned) !== JSON.stringify(candidate))\n throw new Error('\u56FA\u5B9A\u5019\u9009\u5305\u5728\u5B89\u88C5\u540E\u53D1\u751F\u53D8\u5316\uFF0C\u62D2\u7EDD\u5207\u6362');\n return;\n }\n await update('waiting', result.reason ?? '\u7B49\u5F85\u6240\u6709\u4EFB\u52A1\u7ED3\u675F');\n await setTimeout(2_000);\n }\n },\n beforeStop: checkRestartCodex,\n stop: () => stopService(context),\n start: async (candidate) => {\n await releaseData?.();\n releaseData = undefined;\n await startService(context, candidate);\n if (!candidate) await verifyRestoredService(context, record!.from);\n },\n verify: async () => {\n for (let attempt = 0; attempt < 240; attempt++) {\n const current = await control<DaemonStatus>(context.location, 'status').catch(\n () => undefined,\n );\n if (current) {\n if (current.version !== record!.target || !current.maintenance)\n throw new Error('\u65B0\u7248\u670D\u52A1\u8EAB\u4EFD\u6216\u7EF4\u62A4\u72B6\u6001\u4E0D\u5339\u914D');\n if (record!.runtime) assertRuntime(current.runtime, record!.runtime.target);\n if (current.codexVersion && current.codexVersion !== record!.codex!.version)\n throw new Error('\u91CD\u542F\u540E\u7684 Codex \u7248\u672C\u4E0E\u5347\u7EA7\u6821\u9A8C\u8BB0\u5F55\u4E0D\u5339\u914D');\n if (current.codexReady) {\n checkRunningCodex(current);\n return;\n }\n }\n await setTimeout(250);\n }\n throw new Error('\u65B0\u7248\u670D\u52A1\u6216 Codex \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u62D2\u7EDD\u6FC0\u6D3B');\n },\n commit: async () => {\n // Gateway commits the durable result before reopening task admission.\n await control(context.location, 'activate-update', {\n id: record!.id,\n channel: record!.channel,\n });\n const final = await readJson<UpdateRun>(join(directory, 'run.json'));\n if (!final?.committed) throw new Error('\u65B0\u7248\u5C1A\u672A\u786E\u8BA4\u5347\u7EA7\u63D0\u4EA4');\n record = final;\n },\n hasCommitted: async () =>\n Boolean((await readJson<UpdateRun>(join(directory, 'run.json')))?.committed),\n resume: async () => {\n await control(context.location, 'cancel-update').catch(() => {});\n },\n },\n context.reuseTarget,\n );\n } catch (error) {\n const latest = await readJson<UpdateRun>(join(directory, 'run.json'));\n if (latest?.committed) {\n // A lost commit response cannot authorize restoring older data.\n record = latest;\n } else if (!['rolledBack', 'failed'].includes(record.phase))\n await update(\n (error as NodeJS.ErrnoException).code === 'UPDATE_PLAN_CANCELLED' ? 'cancelled' : 'failed',\n message(error),\n );\n logger.error('update.failed', { updateId: record.id, ...errorFields(error) });\n process.exitCode =\n record.committed || ['rolledBack', 'cancelled'].includes(record.phase) ? 0 : 1;\n } finally {\n await releaseData?.();\n await releaseMaintenance?.();\n await release();\n // Keep the last good installation and database backup for explicit recovery.\n if (record.phase === 'succeeded' || record.phase === 'rolledBack') {\n await rm(paths.prefix, { recursive: true, force: true });\n }\n }\n}\n\nasync function worker(directory: string) {\n const context = await readJson<UpdateContext>(join(directory, 'context.json'));\n if (!context) throw new Error('Missing update context');\n const record = await readJson<UpdateRun>(join(directory, 'run.json'));\n const logging = await createLogging({\n ...loggingOptions(join(context.location.state, 'logs'), record?.from ?? 'unknown'),\n component: 'update_worker',\n });\n const removeMonitor = monitorCrashes(logging.logger, logging.flushSync);\n const logger = logging.logger.child({ updateId: record?.id, operationId: record?.id });\n logger.info('update.worker_started');\n try {\n await workerCore(directory, logger);\n } catch (error) {\n logger.error('update.worker_failed', errorFields(error));\n throw error;\n } finally {\n logger.info('update.worker_finished');\n removeMonitor();\n await logging.close();\n }\n}\nif (process.argv[2])\n void worker(process.argv[2]).catch(() => {\n // Bootstrap stderr has no arbitrary exception text or environment values.\n console.error(\n JSON.stringify({\n time: new Date().toISOString(),\n level: 60,\n event: 'update.bootstrap_failed',\n }),\n );\n process.exitCode = 1;\n });\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,SAAS,qBAAkC;AAC3C,SAAS,mBAAmB;AAC5B,SAAS,aAAa,iBAAiB,4BAA4B;AACnE,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,iBAAiB,sBAAsB;AAChD,SAAS,mCAAmC;AAC5C,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,QAAQ,OAAO,SAAS,IAAI,cAAc;AACnD,SAAS,iBAAiB;AAC1B,SAAS,SAAS,YAAY;AAC9B,SAAS,kBAAkB;AAC3B,OAAO,cAAc;AAIrB,SAAS,SAAS,oBAAoB;AACtC,SAAS,iBAAiB,sBAAsB;AAChD,SAAS,aAAa,UAAU,gBAAgB;AAChD,SAAS,wBAAwB,4BAA4B;AAC7D,SAAS,gBAAgB,wBAAwB;AACjD,SAAS,qBAAqB,gBAAgB;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,mBAAmB,yBAAyB;AACrD,SAAS,2BAA+C;AAExD,MAAM,OAAO,UAAU,QAAQ;AAC/B,MAAM,UAAU,CAAC,UAAoB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAW1F,eAAe,aAAa,SAAwB,YAAY,OAAO;AAGrE,QAAM,SAAS,YAAY,QAAQ,SAAS;AAC5C,QAAM;AAAA,IACJ,QAAQ;AAAA,IACR,KA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AoB,KAAK,WAAW,UAAU,CAAC;AACpE,QAAM,UAAU,MAAM,cAAc;AAAA,IAClC,GAAG,eAAe,KAAK,QAAQ,SAAS,OAAO,MAAM,GAAG,QAAQ,QAAQ,SAAS;AAAA,IACjF,WAAW;AAAA,EACb,CAAC;AACD,QAAM,gBAAgB,eAAe,QAAQ,QAAQ,QAAQ,SAAS;AACtE,QAAM,SAAS,QAAQ,OAAO,MAAM,EAAE,UAAU,QAAQ,IAAI,aAAa,QAAQ,GAAG,CAAC;AACrF,SAAO,KAAK,uBAAuB;AACnC,MAAI;AACF,UAAM,WAAW,WAAW,MAAM;AAAA,EACpC,SAAS,OAAO;AACd,WAAO,MAAM,wBAAwB,YAAY,KAAK,CAAC;AACvD,UAAM;AAAA,EACR,UAAE;AACA,WAAO,KAAK,wBAAwB;AACpC,kBAAc;AACd,UAAM,QAAQ,MAAM;AAAA,EACtB;AACF;AACA,IAAI,QAAQ,KAAK,CAAC;AAChB,OAAK,OAAO,QAAQ,KAAK,CAAC,CAAC,EAAE,MAAM,MAAM;AAEvC,YAAQ;AAAA,MACN,KAAK,UAAU;AAAA,QACb,OAAM,oBAAI,KAAK,GAAE,YAAY;AAAA,QAC7B,OAAO;AAAA,QACP,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AACA,YAAQ,WAAW;AAAA,EACrB,CAAC;",
|
|
4
|
+
"sourcesContent": ["import { loggingOptions } from '../logging/config.js';\nimport { monitorCrashes } from '../logging/lifecycle.js';\nimport { createLogging, type Logger } from '../logging/logger.js';\nimport { errorFields } from '../logging/fields.js';\nimport { BackupStore, backupDirectory, verifyLegacySnapshot } from '../backups/store.js';\nimport { acquireMaintenanceLock } from '../backups/lock.js';\nimport { acquireInstanceLock } from '../server/instance-lock.js';\nimport { inspectDatabase, readMigrations } from '../server/db/history.js';\nimport { databaseCompatibilitySchema } from '../shared/database.js';\nimport { npmPackageName } from '../shared/package.js';\nimport {\n codexCompatibilitySchema,\n requireCodexCompatibility,\n} from '../shared/codex-compatibility.js';\n// Bundled with its pure JavaScript dependencies and copied outside the installation before launch.\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\nimport { createRequire } from 'node:module';\nimport { access, mkdir, readdir, rm, rename } from 'node:fs/promises';\nimport { constants } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { setTimeout } from 'node:timers/promises';\nimport lockfile from 'proper-lockfile';\nimport type Database from 'better-sqlite3';\nimport type { UpdateRun, RuntimeIdentity } from '../shared/updates.js';\nimport type { UpdateContext } from './manager.js';\nimport { control, isNotRunning } from '../cli/control.js';\nimport { startBackground, stopBackground } from '../cli/background.js';\nimport { copyDurable, readJson, saveJson } from './files.js';\nimport { confirmAutomaticFreeze, waitForAutomaticPlan } from './plan.js';\nimport { activateUpdate, transactionPaths } from './transaction.js';\nimport { inspectInstallation, registry } from './registry.js';\nimport {\n assertRuntime,\n resolveRuntimeTarget,\n targetNpmEnvironment,\n verifyRuntimeExecutable,\n} from './runtime.js';\nimport {\n snapshotLaunch,\n switchLaunch,\n restoreLaunch,\n type LaunchSnapshot,\n} from '../cli/runtime-launch.js';\nimport { probeRestartCodex, assertCodexTarget } from './codex-target.js';\nimport { assertCodexIdentity, type CodexIdentity } from '../codex/identity.js';\n\nconst exec = promisify(execFile);\nconst message = (error: unknown) => (error instanceof Error ? error.message : String(error));\ntype DaemonStatus = {\n version: string;\n pid: number;\n maintenance?: boolean;\n codexVersion?: string | null;\n codexReady?: boolean;\n codexIdentity?: CodexIdentity;\n runtime?: RuntimeIdentity;\n};\n\nasync function startService(context: UpdateContext, candidate = false) {\n // Shared with `covro start`: never inherit a Background security session on macOS.\n // Activation is checked from the durable update record by the daemon.\n const target = candidate ? context.target : undefined;\n await startBackground(\n context.location,\n join(context.root, 'bin/covro.mjs'),\n target ? { node: target.node, entry: target.entry, path: target.path } : context.source,\n );\n}\nasync function stopService(context: UpdateContext) {\n await stopBackground(context.location);\n}\n\nasync function verifyRestoredService(context: UpdateContext, version: string) {\n for (let attempt = 0; attempt < 240; attempt++) {\n try {\n const restored = await control<DaemonStatus>(context.location, 'status');\n if (restored.version !== version || restored.maintenance)\n throw new Error('\u65E7\u7248\u6062\u590D\u8EAB\u4EFD\u4E0D\u5339\u914D');\n const record = await readJson<UpdateRun>(join(context.directory, 'run.json'));\n if (record?.runtime) assertRuntime(restored.runtime, record.runtime.from);\n return;\n } catch (error) {\n if (attempt === 239) throw error;\n }\n await setTimeout(250);\n }\n}\n\nasync function verifyMigrations(context: UpdateContext, candidate: string) {\n // Loading the existing native addon happens before any package path is replaced.\n const require = createRequire(join(context.root, 'package.json'));\n const Sqlite = require('better-sqlite3') as typeof Database;\n const filename = join(context.dataDir, 'app.sqlite');\n try {\n await access(filename);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw error;\n }\n const db = new Sqlite(filename, { readonly: true, fileMustExist: true });\n try {\n const migrations = readMigrations(join(candidate, 'dist/drizzle'));\n const metadata = await readJson<{ covroDatabase?: unknown }>(join(candidate, 'package.json'));\n if (metadata?.covroDatabase) {\n const contract = databaseCompatibilitySchema.parse(metadata.covroDatabase);\n if (contract.schemaVersion !== migrations.length)\n throw new Error('\u76EE\u6807\u7248\u672C\u7684 Schema \u58F0\u660E\u4E0E\u8FC1\u79FB\u4E0D\u4E00\u81F4');\n }\n inspectDatabase(db, migrations);\n } finally {\n db.close();\n }\n}\n\nasync function workerCore(directory: string, logger: Logger) {\n await mkdir(directory, { recursive: true, mode: 0o700 });\n const release = await lockfile.lock(directory, {\n stale: 10_000,\n update: 2_000,\n retries: { retries: 30, minTimeout: 100, maxTimeout: 500 },\n });\n let record = await readJson<UpdateRun>(join(directory, 'run.json'));\n const context = await readJson<UpdateContext>(join(directory, 'context.json'));\n if (!record || !context) {\n await release();\n throw new Error('\u7F3A\u5C11\u5347\u7EA7\u8BB0\u5F55');\n }\n const update = async (phase: UpdateRun['phase'], detail: string) => {\n record = { ...record!, phase, message: detail, updatedAt: Date.now() };\n await saveJson(join(directory, 'run.json'), record);\n logger.info('update.phase_changed', { updateId: record.id, stage: phase });\n };\n let paths = transactionPaths(\n context.target?.root ?? context.root,\n record.id,\n context.dataDir,\n context.location.config,\n join(backupDirectory(context.location.home, context.dataDir), record.id),\n );\n let releaseMaintenance: (() => Promise<void>) | undefined;\n let releaseData: (() => Promise<void>) | undefined;\n try {\n if (record.automatic && !record.transactionStartedAt && process.argv[3] !== '--repair') {\n record = await waitForAutomaticPlan(record, {\n status: (fresh) =>\n control(context.location, 'automatic-update-plan', { id: record!.id, fresh }),\n readiness: () => control(context.location, 'update-readiness'),\n save: async (next) => {\n record = next;\n await saveJson(join(directory, 'run.json'), record);\n },\n freeze: (checkedAt) =>\n confirmAutomaticFreeze(\n record!.id,\n () =>\n control(context.location, 'freeze-automatic-update', { id: record!.id, checkedAt }),\n () => readJson<UpdateRun>(join(directory, 'run.json')),\n ),\n pause: () => setTimeout(2_000),\n });\n const frozen = await readJson<UpdateContext>(join(directory, 'context.json'));\n if (!frozen) throw new Error('\u7F3A\u5C11\u56FA\u5B9A\u76EE\u6807\u8FD0\u884C\u73AF\u5883');\n Object.assign(context, frozen);\n paths = transactionPaths(\n context.target?.root ?? context.root,\n record.id,\n context.dataDir,\n context.location.config,\n join(backupDirectory(context.location.home, context.dataDir), record.id),\n );\n }\n if (record.runtime) await verifyRuntimeExecutable(record.runtime.from);\n const previousMetadata = await readJson<{ version: string }>(\n join(paths.previous, 'package.json'),\n );\n const sameRoot = paths.root.replace(/\\/$/, '') === context.root.replace(/\\/$/, '');\n const originalRoot =\n sameRoot && previousMetadata?.version === record.from ? paths.previous : context.root;\n const originalMetadata = await readJson<{\n version: string;\n covroCommit?: string;\n covroDatabase?: unknown;\n }>(join(originalRoot, 'package.json'));\n const requireOriginal = createRequire(join(originalRoot, 'package.json'));\n const sqliteModulePath = requireOriginal.resolve('better-sqlite3');\n const Sqlite = requireOriginal(sqliteModulePath) as typeof Database;\n const migrations = readMigrations(join(originalRoot, 'dist/drizzle'));\n const backups = new BackupStore({\n directory: backupDirectory(context.location.home, context.dataDir),\n config: paths.config,\n dataDir: paths.dataDir,\n appVersion: record.from,\n commit: originalMetadata?.covroCommit,\n contract: databaseCompatibilitySchema.parse(\n originalMetadata?.covroDatabase ?? {\n schemaVersion: migrations.length,\n minRestorableSchemaVersion: 1,\n backupFormatVersion: 1,\n },\n ),\n Sqlite,\n sqliteModulePath,\n migrations,\n });\n if (process.argv[3] === '--repair') {\n releaseMaintenance = await acquireMaintenanceLock(context.dataDir);\n if (!(await readJson(join(paths.backup, 'snapshot.json'))))\n paths.backup = join(directory, `backup-${record.id}`);\n const active = await control<DaemonStatus>(context.location, 'status').catch(\n (error: unknown) => {\n if (isNotRunning(error)) return undefined;\n throw error;\n },\n );\n if (record.committed) return;\n if (active && !active.maintenance && active.version !== record.from)\n throw new Error('\u5F53\u524D\u670D\u52A1\u53EF\u80FD\u5DF2\u63A5\u53D7\u65B0\u7248\u4E1A\u52A1\u6570\u636E\uFF1B\u62D2\u7EDD\u6062\u590D\u65E7\u5FEB\u7167\uFF0C\u8BF7\u4F7F\u7528\u517C\u5BB9\u7248\u672C\u68C0\u67E5\u3002');\n const previous = await readJson<{ version: string; name: string }>(\n join(paths.previous, 'package.json'),\n );\n if (previous || context.reuseTarget) {\n if (active && !active.maintenance)\n throw new Error('\u65E7\u670D\u52A1\u5DF2\u6062\u590D\u4E1A\u52A1\u5199\u5165\uFF1B\u62D2\u7EDD\u7528\u5347\u7EA7\u524D\u5FEB\u7167\u8986\u76D6\u73B0\u6709\u6570\u636E\uFF0C\u8BF7\u4FDD\u7559\u73B0\u573A\u68C0\u67E5\u3002');\n if (\n previous &&\n (previous.name !== npmPackageName ||\n previous.version !== (context.target?.version ?? record.from))\n )\n throw new Error('\u65E7\u7248\u5907\u4EFD\u8EAB\u4EFD\u4E0D\u5339\u914D');\n const snapshot = await readJson<{ complete: boolean; formatVersion?: number }>(\n join(paths.backup, 'snapshot.json'),\n );\n if (snapshot?.formatVersion === 1) {\n const verified = await backups.verify(record.id);\n if (\n verified.appVersion !== record.from ||\n verified.protectedBy !== record.id ||\n verified.configPath !== paths.config ||\n verified.dataDir !== paths.dataDir\n )\n throw new Error('\u5907\u4EFD\u8EAB\u4EFD\u4E0D\u5339\u914D');\n } else await verifyLegacySnapshot(paths.backup, Sqlite, join(originalRoot, 'dist/drizzle'));\n } else if (sameRoot) {\n const original = await readJson<{ name: string; version: string }>(\n join(paths.root, 'package.json'),\n );\n if (original?.name !== npmPackageName || original.version !== record.from)\n throw new Error('\u672A\u627E\u5230\u5B8C\u6574\u7684\u4E0A\u4E00\u7248\u672C\u5B89\u88C5');\n }\n if (active && !active.maintenance) {\n const admission = await control<{ ready: boolean }>(context.location, 'prepare-update');\n if (!admission.ready) throw new Error('\u4ECD\u6709\u4EFB\u52A1\u3001\u5BA1\u6279\u6216\u5F85\u6838\u5BF9\u64CD\u4F5C\uFF0C\u4E0D\u80FD\u6062\u590D\u65E7\u5B89\u88C5');\n }\n await stopService(context);\n releaseData = await acquireInstanceLock(context.dataDir);\n if (previous) {\n await rm(paths.root, { recursive: true, force: true });\n await rename(paths.previous, paths.root);\n }\n if (previous || context.reuseTarget) {\n for (const name of ['app.sqlite', 'app.sqlite-wal', 'app.sqlite-shm']) {\n await rm(join(paths.dataDir, name), { force: true });\n try {\n await copyDurable(join(paths.backup, name), join(paths.dataDir, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n }\n await copyDurable(join(paths.backup, 'config.json'), paths.config);\n }\n const launch = await readJson<LaunchSnapshot>(join(directory, `launch-${record.id}.json`));\n if (launch) await restoreLaunch(context.location, launch);\n const restored = await readJson<{ name: string; version: string }>(\n join(context.root, 'package.json'),\n );\n if (restored?.name !== npmPackageName || restored.version !== record.from)\n throw new Error('\u672A\u627E\u5230\u5B8C\u6574\u7684\u4E0A\u4E00\u7248\u672C\u5B89\u88C5');\n await update('rolledBack', '\u5DF2\u6062\u590D\u4E0A\u6B21\u672A\u5B8C\u6210\u7684\u5347\u7EA7\uFF0C\u6B63\u5728\u542F\u52A8\u4E0A\u4E00\u7248\u672C');\n try {\n await releaseData?.();\n releaseData = undefined;\n await startService(context);\n await verifyRestoredService(context, record.from);\n await update('rolledBack', '\u5DF2\u6062\u590D\u4E0A\u6B21\u672A\u5B8C\u6210\u7684\u5347\u7EA7\uFF0C\u4E0A\u4E00\u7248\u672C\u5DF2\u5C31\u7EEA');\n } catch (error) {\n await update('failed', `\u65E7\u7248\u6062\u590D\u542F\u52A8\u5931\u8D25\uFF0C\u4FDD\u7559\u5907\u4EFD\uFF1A${message(error)}`);\n throw error;\n }\n return;\n }\n const reason = await inspectInstallation(context.root);\n if (reason) throw new Error(reason);\n // A second managed configuration must be stopped before replacing their shared npm package.\n for (const key of await readdir(join(context.location.home, 'instances'))) {\n if (key === context.location.key) continue;\n const instance = await readJson<{ root: string; config: string; socket: string }>(\n join(context.location.home, 'instances', key, 'instance.json'),\n );\n if (\n !instance ||\n ![context.root.replace(/\\/$/, ''), paths.root].includes(instance.root.replace(/\\/$/, ''))\n )\n continue;\n try {\n await control({ ...context.location, socket: instance.socket }, 'status');\n throw new Error('\u540C\u4E00 npm \u5B89\u88C5\u8FD8\u6709\u5176\u4ED6 Covro \u5B9E\u4F8B\uFF0C\u8BF7\u5148\u505C\u6B62\u5176\u4ED6\u5B9E\u4F8B\u518D\u5347\u7EA7\u3002');\n } catch (error) {\n if (!isNotRunning(error)) throw error;\n }\n }\n await access(dirname(context.root), constants.W_OK);\n await access(dirname(paths.root), constants.W_OK);\n if (context.target) {\n const target = await resolveRuntimeTarget();\n assertRuntime(target, context.target);\n if (\n target.npm !== context.target.npm ||\n target.npmVersion !== context.target.npmVersion ||\n target.prefix !== context.target.prefix ||\n target.path !== context.target.path ||\n target.version !== context.target.version\n )\n throw new Error('\u76EE\u6807 Node/npm \u73AF\u5883\u5728\u68C0\u67E5\u540E\u53D8\u5316\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0\u3002');\n }\n const candidateRoot = context.reuseTarget ? paths.root : paths.candidate;\n const node = context.target?.node ?? process.execPath;\n const env = targetNpmEnvironment(\n context.target?.path ?? process.env.PATH ?? '/usr/bin:/bin',\n context.target?.npmConfig,\n );\n const restartRuntime = context.target ?? context.source;\n if (!record.codex?.target || !restartRuntime)\n throw new Error('\u7F3A\u5C11\u91CD\u542F\u76EE\u6807 Codex \u6765\u6E90\u8BB0\u5F55\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0');\n if (record.codex.version !== record.codex.target.identity.version)\n throw new Error('Codex \u7248\u672C\u4E0E\u91CD\u542F\u76EE\u6807\u6765\u6E90\u8BB0\u5F55\u4E0D\u5339\u914D\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0');\n let probeRoot = context.reuseTarget ? candidateRoot : context.root;\n const checkRestartCodex = async () => {\n const actual = await probeRestartCodex(\n context.location,\n context.root,\n restartRuntime,\n context.source,\n probeRoot,\n );\n assertCodexTarget(actual, record!.codex!.target!);\n requireCodexCompatibility(\n record!.codex!.manifest,\n actual.identity.version,\n record!.codex!.confirmedUnverified,\n 'restart',\n );\n };\n // Recheck before npm installation as well as after every wait. Never compare against the old process.\n await checkRestartCodex();\n // npm global layout keeps production dependencies nested in the package being swapped.\n if (!context.reuseTarget)\n await exec(\n context.target?.node ?? 'npm',\n [\n ...(context.target ? [context.target.npm] : []),\n 'install',\n '--global',\n '--prefix',\n paths.prefix,\n '--omit=dev',\n '--no-audit',\n '--no-fund',\n `--registry=${registry}`,\n '--allow-scripts=better-sqlite3',\n `${npmPackageName}@${record.target}`,\n ],\n { env, timeout: 10 * 60_000, maxBuffer: 2 * 1024 * 1024 },\n );\n const candidate = await readJson<{\n name: string;\n version: string;\n covroCodex?: unknown;\n covroCommit?: string;\n gitHead?: string;\n }>(join(candidateRoot, 'package.json'));\n if (candidate?.name !== npmPackageName || candidate.version !== record.target)\n throw new Error('\u5019\u9009\u5305\u8EAB\u4EFD\u6216\u7248\u672C\u4E0D\u5339\u914D');\n if (record.commit && (candidate.covroCommit ?? candidate.gitHead) !== record.commit)\n throw new Error('\u5019\u9009\u5305\u6E90\u7801\u63D0\u4EA4\u4E0E\u68C0\u67E5\u65F6\u4E0D\u4E00\u81F4\uFF0C\u62D2\u7EDD\u5207\u6362');\n if (!record.codex) throw new Error('\u7F3A\u5C11 Codex \u5347\u7EA7\u6821\u9A8C\u8BB0\u5F55\uFF0C\u8BF7\u91CD\u65B0\u68C0\u67E5\u66F4\u65B0');\n const manifest = codexCompatibilitySchema.parse(candidate.covroCodex);\n if (JSON.stringify(manifest) !== JSON.stringify(record.codex.manifest))\n throw new Error('\u5019\u9009\u5305\u7684 Codex \u517C\u5BB9\u58F0\u660E\u4E0E\u68C0\u67E5\u65F6\u4E0D\u4E00\u81F4\uFF0C\u62D2\u7EDD\u5207\u6362');\n const checkRunningCodex = (state: DaemonStatus) => {\n if (state.codexVersion !== record!.codex!.version)\n throw new Error('\u91CD\u542F\u540E\u7684 Codex \u7248\u672C\u4E0E\u5347\u7EA7\u6821\u9A8C\u8BB0\u5F55\u4E0D\u5339\u914D');\n assertCodexIdentity(state.codexIdentity, record!.codex!.target!.identity);\n requireCodexCompatibility(\n manifest,\n state.codexVersion ?? null,\n record!.codex!.confirmedUnverified,\n );\n };\n probeRoot = candidateRoot;\n await checkRestartCodex();\n const versionProbe = await exec(node, [join(candidateRoot, 'bin/covro.mjs'), '--version'], {\n timeout: 30_000,\n env,\n });\n if (versionProbe.stdout.trim() !== record.target)\n throw new Error('\u76EE\u6807 Node \u6267\u884C Covro \u5165\u53E3\u540E\u8FD4\u56DE\u7684\u7248\u672C\u4E0D\u5339\u914D');\n const nativeProbe =\n 'const {createRequire}=await import(\"node:module\"); const r=createRequire(process.argv[1]); const DB=r(\"better-sqlite3\"); const db=new DB(\":memory:\"); db.close();';\n await exec(\n node,\n ['--input-type=module', '-e', nativeProbe, join(candidateRoot, 'package.json')],\n { env, timeout: 30_000 },\n );\n await verifyMigrations(context, candidateRoot);\n const launch: LaunchSnapshot = await snapshotLaunch(\n context.location,\n context.source ?? {\n node: process.execPath,\n entry: join(context.root, 'bin/covro.mjs'),\n path: process.env.PATH ?? '/usr/bin:/bin',\n },\n );\n if (context.target)\n launch.target = { node, entry: context.target.entry, path: context.target.path };\n await saveJson(join(directory, `launch-${record.id}.json`), launch);\n releaseMaintenance = await acquireMaintenanceLock(context.dataDir);\n await activateUpdate(\n paths,\n {\n backup: async () => {\n releaseData = await acquireInstanceLock(context.dataDir);\n await backups.create({ id: record!.id, trigger: 'preUpgrade', protectedBy: record!.id });\n },\n restore: async () => {\n releaseData ??= await acquireInstanceLock(context.dataDir);\n await backups.restoreFiles(record!.id);\n },\n switchLaunch: context.target\n ? () =>\n switchLaunch(\n context.location,\n { node, entry: context.target!.entry, path: context.target!.path },\n launch,\n )\n : undefined,\n restoreLaunch: () => restoreLaunch(context.location, launch),\n phase: update,\n waitForIdle: async () => {\n // Queue without blocking normal work; admission closes atomically only after all blockers clear.\n for (;;) {\n await checkRestartCodex();\n const result = await control<{ ready: boolean; reason?: string }>(\n context.location,\n 'prepare-update',\n );\n if (result.ready) {\n await checkRestartCodex();\n await verifyMigrations(context, candidateRoot);\n const pinned = await readJson<typeof candidate>(join(candidateRoot, 'package.json'));\n if (JSON.stringify(pinned) !== JSON.stringify(candidate))\n throw new Error('\u56FA\u5B9A\u5019\u9009\u5305\u5728\u5B89\u88C5\u540E\u53D1\u751F\u53D8\u5316\uFF0C\u62D2\u7EDD\u5207\u6362');\n return;\n }\n await update('waiting', result.reason ?? '\u7B49\u5F85\u6240\u6709\u4EFB\u52A1\u7ED3\u675F');\n await setTimeout(2_000);\n }\n },\n beforeStop: checkRestartCodex,\n stop: () => stopService(context),\n start: async (candidate) => {\n await releaseData?.();\n releaseData = undefined;\n await startService(context, candidate);\n if (!candidate) await verifyRestoredService(context, record!.from);\n },\n verify: async () => {\n for (let attempt = 0; attempt < 240; attempt++) {\n const current = await control<DaemonStatus>(context.location, 'status').catch(\n () => undefined,\n );\n if (current) {\n if (current.version !== record!.target || !current.maintenance)\n throw new Error('\u65B0\u7248\u670D\u52A1\u8EAB\u4EFD\u6216\u7EF4\u62A4\u72B6\u6001\u4E0D\u5339\u914D');\n if (record!.runtime) assertRuntime(current.runtime, record!.runtime.target);\n if (current.codexVersion && current.codexVersion !== record!.codex!.version)\n throw new Error('\u91CD\u542F\u540E\u7684 Codex \u7248\u672C\u4E0E\u5347\u7EA7\u6821\u9A8C\u8BB0\u5F55\u4E0D\u5339\u914D');\n if (current.codexReady) {\n checkRunningCodex(current);\n return;\n }\n }\n await setTimeout(250);\n }\n throw new Error('\u65B0\u7248\u670D\u52A1\u6216 Codex \u8FDE\u63A5\u672A\u5C31\u7EEA\uFF0C\u62D2\u7EDD\u6FC0\u6D3B');\n },\n commit: async () => {\n // Gateway commits the durable result before reopening task admission.\n await control(context.location, 'activate-update', {\n id: record!.id,\n channel: record!.channel,\n });\n const final = await readJson<UpdateRun>(join(directory, 'run.json'));\n if (!final?.committed) throw new Error('\u65B0\u7248\u5C1A\u672A\u786E\u8BA4\u5347\u7EA7\u63D0\u4EA4');\n record = final;\n },\n hasCommitted: async () =>\n Boolean((await readJson<UpdateRun>(join(directory, 'run.json')))?.committed),\n resume: async () => {\n await control(context.location, 'cancel-update').catch(() => {});\n },\n },\n context.reuseTarget,\n );\n } catch (error) {\n const latest = await readJson<UpdateRun>(join(directory, 'run.json'));\n if (latest?.committed) {\n // A lost commit response cannot authorize restoring older data.\n record = latest;\n } else if (!['rolledBack', 'failed'].includes(record.phase))\n await update(\n (error as NodeJS.ErrnoException).code === 'UPDATE_PLAN_CANCELLED' ? 'cancelled' : 'failed',\n message(error),\n );\n logger.error('update.failed', { updateId: record.id, ...errorFields(error) });\n process.exitCode =\n record.committed || ['rolledBack', 'cancelled'].includes(record.phase) ? 0 : 1;\n } finally {\n await releaseData?.();\n await releaseMaintenance?.();\n await release();\n // Keep the last good installation and database backup for explicit recovery.\n if (record.phase === 'succeeded' || record.phase === 'rolledBack') {\n await rm(paths.prefix, { recursive: true, force: true });\n }\n }\n}\n\nasync function worker(directory: string) {\n const context = await readJson<UpdateContext>(join(directory, 'context.json'));\n if (!context) throw new Error('Missing update context');\n const record = await readJson<UpdateRun>(join(directory, 'run.json'));\n const logging = await createLogging({\n ...loggingOptions(join(context.location.state, 'logs'), record?.from ?? 'unknown'),\n component: 'update_worker',\n });\n const removeMonitor = monitorCrashes(logging.logger, logging.flushSync);\n const logger = logging.logger.child({ updateId: record?.id, operationId: record?.id });\n logger.info('update.worker_started');\n try {\n await workerCore(directory, logger);\n } catch (error) {\n logger.error('update.worker_failed', errorFields(error));\n throw error;\n } finally {\n logger.info('update.worker_finished');\n removeMonitor();\n await logging.close();\n }\n}\nif (process.argv[2])\n void worker(process.argv[2]).catch(() => {\n // Bootstrap stderr has no arbitrary exception text or environment values.\n console.error(\n JSON.stringify({\n time: new Date().toISOString(),\n level: 60,\n event: 'update.bootstrap_failed',\n }),\n );\n process.exitCode = 1;\n });\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,sBAAsB;AAC/B,SAAS,sBAAsB;AAC/B,SAAS,qBAAkC;AAC3C,SAAS,mBAAmB;AAC5B,SAAS,aAAa,iBAAiB,4BAA4B;AACnE,SAAS,8BAA8B;AACvC,SAAS,2BAA2B;AACpC,SAAS,iBAAiB,sBAAsB;AAChD,SAAS,mCAAmC;AAC5C,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,QAAQ,OAAO,SAAS,IAAI,cAAc;AACnD,SAAS,iBAAiB;AAC1B,SAAS,SAAS,YAAY;AAC9B,SAAS,kBAAkB;AAC3B,OAAO,cAAc;AAIrB,SAAS,SAAS,oBAAoB;AACtC,SAAS,iBAAiB,sBAAsB;AAChD,SAAS,aAAa,UAAU,gBAAgB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;AAAA,QACb,OAAM,oBAAI,KAAK,GAAE,YAAY;AAAA,QAC7B,OAAO;AAAA,QACP,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AACA,YAAQ,WAAW;AAAA,EACrB,CAAC;",
|
|
6
6
|
"names": ["require", "launch", "candidate"]
|
|
7
7
|
}
|
package/dist/web/assets/{abnfDiagram-WEYOIA3C-Hs1QxS5F.js → abnfDiagram-WEYOIA3C-BSubEQ-7.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as e,t}from"./mermaid-parser.core-
|
|
1
|
+
import{m as e,t}from"./mermaid-parser.core-CagmNEON.js";import{n}from"./chunk-Y2CYZVJY-DsF7k-Jl.js";import{m as r}from"./src-Ca_VLzGx.js";import"./chunk-DSNLSHJZ-xcJjdhWM.js";import{n as i,r as a,t as o}from"./chunk-2E7WHVMD-CvJej-BB.js";import{t as s}from"./chunk-JWPE2WC7-DVXcaiue.js";import"./mermaid.core-BhI_0ceg.js";var c=e().RailroadAbnf.parser.LangiumParser,l=n(e=>{let t=e.alternatives.map(u);return t.length===1?t[0]:{type:`choice`,alternatives:t}},`transformAlternation`),u=n(e=>{let t=e.elements.map(f);return t.length===1?t[0]:{type:`sequence`,elements:t}},`transformConcatenation`),d=n(e=>{if(e.includes(`*`)){let[t,n]=e.split(`*`);return{min:t?parseInt(t,10):0,max:n?parseInt(n,10):1/0}}let t=parseInt(e,10);return{min:t,max:t}},`parseRepeat`),f=n(e=>{let t=p(e.primary);if(!e.repeat)return t;let{min:n,max:r}=d(e.repeat);return n===0&&r===1?{type:`optional`,element:t}:{type:`repetition`,element:t,min:n,max:r}},`transformElement`),p=n(e=>{switch(e.$type){case`AbnfStringLiteral`:return{type:`terminal`,value:e.value};case`AbnfNumVal`:return{type:`terminal`,value:e.value};case`AbnfRuleName`:return{type:`nonterminal`,name:e.name};case`AbnfGroup`:return l(e.element);case`AbnfOptionalGroup`:return{type:`optional`,element:l(e.element)};default:throw Error(`Unsupported ABNF primary node: ${e.$type}`)}},`transformPrimary`),m=n(e=>({name:e.name,definition:l(e.definition)}),`transformRule`),h=n(e=>{s(e,o),e.title&&o.setTitle(e.title),e.rules.map(e=>o.addRule(m(e)))},`populateDb`),g={parser:{parse:n(e=>{o.clear(),r.debug(`[ABNF Parser] Starting Langium parse`);let n=c.parse(e);if(n.lexerErrors.length>0||n.parserErrors.length>0)throw new t(n);let i=n.value;r.debug(`[ABNF Parser] Parsed rules:`,i.rules.length),h(i),r.debug(`[ABNF Parser] Parse complete`)},`parse`),parser:{yy:o}},db:o,renderer:a,styles:i};export{g as diagram};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e,t}from"./path-fybaL0A-.js";import{a as n,c as r,d as i,f as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,u as p}from"./dist-
|
|
1
|
+
import{n as e,t}from"./path-fybaL0A-.js";import{a as n,c as r,d as i,f as a,i as o,l as s,m as c,n as l,o as u,p as d,r as f,u as p}from"./dist-PxL1MpGF.js";function m(e){return e.innerRadius}function h(e){return e.outerRadius}function g(e){return e.startAngle}function _(e){return e.endAngle}function v(e){return e&&e.padAngle}function y(e,t,n,r,i,a,o,s){var c=n-e,l=r-t,u=o-i,d=s-a,f=d*c-u*l;if(!(f*f<1e-12))return f=(u*(t-a)-d*(e-i))/f,[e+f*c,t+f*l]}function b(e,t,n,r,i,a,o){var c=e-n,l=t-r,u=(o?a:-a)/d(c*c+l*l),f=u*l,p=-u*c,m=e+f,h=t+p,g=n+f,_=r+p,v=(m+g)/2,y=(h+_)/2,b=g-m,x=_-h,S=b*b+x*x,C=i-a,w=m*_-g*h,T=(x<0?-1:1)*d(s(0,C*C*S-w*w)),E=(w*x-b*T)/S,D=(-w*b-x*T)/S,O=(w*x+b*T)/S,k=(-w*b+x*T)/S,A=E-v,j=D-y,M=O-v,N=k-y;return A*A+j*j>M*M+N*N&&(E=O,D=k),{cx:E,cy:D,x01:-f,y01:-p,x11:E*(i/C-1),y11:D*(i/C-1)}}function x(){var s=m,x=h,S=e(0),C=null,w=g,T=_,E=v,D=null,O=t(k);function k(){var e,t,m=+s.apply(this,arguments),h=+x.apply(this,arguments),g=w.apply(this,arguments)-r,_=T.apply(this,arguments)-r,v=l(_-g),k=_>g;if(D||=e=O(),h<m&&(t=h,h=m,m=t),!(h>1e-12))D.moveTo(0,0);else if(v>c-1e-12)D.moveTo(h*u(g),h*a(g)),D.arc(0,0,h,g,_,!k),m>1e-12&&(D.moveTo(m*u(_),m*a(_)),D.arc(0,0,m,_,g,k));else{var A=g,j=_,M=g,N=_,P=v,F=v,I=E.apply(this,arguments)/2,L=I>1e-12&&(C?+C.apply(this,arguments):d(m*m+h*h)),R=p(l(h-m)/2,+S.apply(this,arguments)),z=R,B=R,V,H;if(L>1e-12){var U=o(L/m*a(I)),W=o(L/h*a(I));(P-=U*2)>1e-12?(U*=k?1:-1,M+=U,N-=U):(P=0,M=N=(g+_)/2),(F-=W*2)>1e-12?(W*=k?1:-1,A+=W,j-=W):(F=0,A=j=(g+_)/2)}var G=h*u(A),K=h*a(A),q=m*u(N),J=m*a(N);if(R>1e-12){var Y=h*u(j),X=h*a(j),Z=m*u(M),Q=m*a(M),$;if(v<i){if($=y(G,K,Z,Q,Y,X,q,J)){var ee=G-$[0],te=K-$[1],ne=Y-$[0],re=X-$[1],ie=1/a(f((ee*ne+te*re)/(d(ee*ee+te*te)*d(ne*ne+re*re)))/2),ae=d($[0]*$[0]+$[1]*$[1]);z=p(R,(m-ae)/(ie-1)),B=p(R,(h-ae)/(ie+1))}else z=B=0}}F>1e-12?B>1e-12?(V=b(Z,Q,G,K,h,B,k),H=b(Y,X,q,J,h,B,k),D.moveTo(V.cx+V.x01,V.cy+V.y01),B<R?D.arc(V.cx,V.cy,B,n(V.y01,V.x01),n(H.y01,H.x01),!k):(D.arc(V.cx,V.cy,B,n(V.y01,V.x01),n(V.y11,V.x11),!k),D.arc(0,0,h,n(V.cy+V.y11,V.cx+V.x11),n(H.cy+H.y11,H.cx+H.x11),!k),D.arc(H.cx,H.cy,B,n(H.y11,H.x11),n(H.y01,H.x01),!k))):(D.moveTo(G,K),D.arc(0,0,h,A,j,!k)):D.moveTo(G,K),!(m>1e-12)||!(P>1e-12)?D.lineTo(q,J):z>1e-12?(V=b(q,J,Y,X,m,-z,k),H=b(G,K,Z,Q,m,-z,k),D.lineTo(V.cx+V.x01,V.cy+V.y01),z<R?D.arc(V.cx,V.cy,z,n(V.y01,V.x01),n(H.y01,H.x01),!k):(D.arc(V.cx,V.cy,z,n(V.y01,V.x01),n(V.y11,V.x11),!k),D.arc(0,0,m,n(V.cy+V.y11,V.cx+V.x11),n(H.cy+H.y11,H.cx+H.x11),k),D.arc(H.cx,H.cy,z,n(H.y11,H.x11),n(H.y01,H.x01),!k))):D.arc(0,0,m,N,M,k)}if(D.closePath(),e)return D=null,e+``||null}return k.centroid=function(){var e=(+s.apply(this,arguments)+ +x.apply(this,arguments))/2,t=(+w.apply(this,arguments)+ +T.apply(this,arguments))/2-i/2;return[u(t)*e,a(t)*e]},k.innerRadius=function(t){return arguments.length?(s=typeof t==`function`?t:e(+t),k):s},k.outerRadius=function(t){return arguments.length?(x=typeof t==`function`?t:e(+t),k):x},k.cornerRadius=function(t){return arguments.length?(S=typeof t==`function`?t:e(+t),k):S},k.padRadius=function(t){return arguments.length?(C=t==null?null:typeof t==`function`?t:e(+t),k):C},k.startAngle=function(t){return arguments.length?(w=typeof t==`function`?t:e(+t),k):w},k.endAngle=function(t){return arguments.length?(T=typeof t==`function`?t:e(+t),k):T},k.padAngle=function(t){return arguments.length?(E=typeof t==`function`?t:e(+t),k):E},k.context=function(e){return arguments.length?(D=e??null,k):D},k}export{x as t};
|
package/dist/web/assets/{architecture-WOLXFQ4H-D5R4yrK5.js → architecture-WOLXFQ4H-DurVyzju.js}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-NGNAAXSQ-C2Wy9Xmz.js";export{M as createArchitectureServices}from"./mermaid-parser.core-
|
|
1
|
+
import"./chunk-NGNAAXSQ-C2Wy9Xmz.js";export{M as createArchitectureServices}from"./mermaid-parser.core-CagmNEON.js";
|