@prompt-optimizer/mcp-server 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +669 -0
- package/README.md +267 -0
- package/THIRD_PARTY_NOTICES.txt +4476 -0
- package/bin/prompt-optimizer-desktop-mcp.cjs +10 -0
- package/bin/prompt-optimizer-mcp.cjs +20 -0
- package/dist/browser.cjs +1 -0
- package/dist/browser.js +4202 -0
- package/dist/chunk-3FYJ3FRD.js +57 -0
- package/dist/chunk-E7Z4Y3F4.js +36402 -0
- package/dist/chunk-GBDJTSRW.js +298 -0
- package/dist/chunk-HLCN3DLS.js +19745 -0
- package/dist/chunk-HYVN7FZZ.js +4787 -0
- package/dist/chunk-MEUCFQGU.js +537 -0
- package/dist/chunk-N6AUTPPS.js +10647 -0
- package/dist/chunk-Q52SACHI.js +304 -0
- package/dist/chunk-Q5B3KFB3.js +31 -0
- package/dist/chunk-QSPNNVX3.js +49017 -0
- package/dist/chunk-SO4YJHYW.js +13450 -0
- package/dist/chunk-SV2GETJH.js +65 -0
- package/dist/chunk-TFH2LO2H.js +58 -0
- package/dist/chunk-TFJEYQ3G.js +786 -0
- package/dist/chunk-TLOFCHZI.js +70 -0
- package/dist/chunk-TQGHULC7.js +188 -0
- package/dist/chunk-UTOMPKTK.js +2209 -0
- package/dist/chunk-XXALDAL7.js +1838 -0
- package/dist/chunk-YT3U6B54.js +21 -0
- package/dist/desktop-business.cjs +1 -0
- package/dist/desktop-business.js +1227 -0
- package/dist/desktop-comparison-HDIQ6K45.js +22 -0
- package/dist/desktop-storage-YRABQCLF.js +14 -0
- package/dist/desktop.cjs +1 -0
- package/dist/desktop.js +26 -0
- package/dist/dist-O5VNBF5I.js +622 -0
- package/dist/dist-UMX52UME.js +481 -0
- package/dist/index.cjs +1 -0
- package/dist/index.js +12 -0
- package/dist/legacy.cjs +1 -0
- package/dist/legacy.js +26933 -0
- package/dist/multipart-parser-XE6WGDAU.js +373 -0
- package/dist/node-2RBNZOSK.js +2225 -0
- package/dist/node-4Z3USCHW.js +21 -0
- package/dist/node-QHGLD5ST.js +25 -0
- package/dist/registry-H5F4DGAM-UHR4F6LL.js +13 -0
- package/dist/src-7PBMYCGI.js +1398 -0
- package/dist/start.cjs +1 -0
- package/dist/start.js +16 -0
- package/package.json +30 -0
- package/preload-env.cjs +352 -0
- package/skills/prompt-optimizer-compare/SKILL.md +21 -0
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
import { createRequire as __mcpCreateRequire } from "node:module";
|
|
2
|
+
const require = __mcpCreateRequire(import.meta.url);
|
|
3
|
+
import {
|
|
4
|
+
StorageError
|
|
5
|
+
} from "./chunk-Q5B3KFB3.js";
|
|
6
|
+
import {
|
|
7
|
+
__publicField
|
|
8
|
+
} from "./chunk-TQGHULC7.js";
|
|
9
|
+
|
|
10
|
+
// ../core/dist/node.js
|
|
11
|
+
import { DatabaseSync } from "node:sqlite";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { mkdirSync, statSync } from "node:fs";
|
|
14
|
+
import { dirname, isAbsolute, resolve } from "node:path";
|
|
15
|
+
import { pathToFileURL } from "node:url";
|
|
16
|
+
import { readFileSync } from "node:fs";
|
|
17
|
+
import { isAbsolute as isAbsolute2, join } from "node:path";
|
|
18
|
+
var DESKTOP_STORAGE_DIVERGENCE_REASON = "DESKTOP_STORAGE_DIVERGED";
|
|
19
|
+
var BOOTSTRAP_KEY = "legacy-json-migration";
|
|
20
|
+
function isFingerprint(value) {
|
|
21
|
+
return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
|
|
22
|
+
}
|
|
23
|
+
function migrationResult(marker) {
|
|
24
|
+
return { version: marker.version, source: marker.source, itemCount: marker.itemCount };
|
|
25
|
+
}
|
|
26
|
+
function fingerprintEntries(entries) {
|
|
27
|
+
const sorted = [...entries.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
28
|
+
return createHash("sha256").update(JSON.stringify(sorted)).digest("hex");
|
|
29
|
+
}
|
|
30
|
+
function parseMigrationMarker(marker) {
|
|
31
|
+
let result;
|
|
32
|
+
try {
|
|
33
|
+
if (typeof marker !== "string") throw new Error("Missing marker");
|
|
34
|
+
result = JSON.parse(marker);
|
|
35
|
+
} catch {
|
|
36
|
+
throw new StorageError("Missing or invalid SQLite migration state", "config");
|
|
37
|
+
}
|
|
38
|
+
if (!result || typeof result !== "object" || Array.isArray(result)) {
|
|
39
|
+
throw new StorageError("Unsupported SQLite migration state", "config");
|
|
40
|
+
}
|
|
41
|
+
const value = result;
|
|
42
|
+
if (value.version !== 1 || !["json", "backup", "empty"].includes(value.source ?? "") || !Number.isSafeInteger(value.itemCount) || value.itemCount < 0 || value.source === "empty" && value.itemCount !== 0 || value.sourceFingerprint !== void 0 && !isFingerprint(value.sourceFingerprint) || value.backupFingerprint !== void 0 && (!value.sourceFingerprint || !isFingerprint(value.backupFingerprint))) {
|
|
43
|
+
throw new StorageError("Unsupported SQLite migration state", "config");
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
version: 1,
|
|
47
|
+
source: value.source,
|
|
48
|
+
itemCount: value.itemCount,
|
|
49
|
+
sourceFingerprint: value.sourceFingerprint,
|
|
50
|
+
backupFingerprint: value.backupFingerprint
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
var isBusy = (error) => {
|
|
54
|
+
const code = error?.errcode;
|
|
55
|
+
return typeof code === "number" && (code & 255) === 5;
|
|
56
|
+
};
|
|
57
|
+
var SQLiteStorageProvider = class _SQLiteStorageProvider {
|
|
58
|
+
constructor(databasePath, options = {}) {
|
|
59
|
+
__publicField(this, "databasePath");
|
|
60
|
+
__publicField(this, "db");
|
|
61
|
+
__publicField(this, "queue", Promise.resolve());
|
|
62
|
+
__publicField(this, "closing", false);
|
|
63
|
+
__publicField(this, "unusable", false);
|
|
64
|
+
__publicField(this, "closePromise");
|
|
65
|
+
__publicField(this, "options");
|
|
66
|
+
__publicField(this, "existingOnly", false);
|
|
67
|
+
__publicField(this, "existingWriter");
|
|
68
|
+
__publicField(this, "existingFile");
|
|
69
|
+
__publicField(this, "existingMigration");
|
|
70
|
+
if (!databasePath || databasePath === ":memory:") {
|
|
71
|
+
throw new StorageError("SQLite storage requires a persistent database path", "config");
|
|
72
|
+
}
|
|
73
|
+
this.databasePath = resolve(databasePath);
|
|
74
|
+
this.options = { busyTimeoutMs: 50, maxRetries: 12, retryDelayMs: 25, ...options };
|
|
75
|
+
for (const value of Object.values(this.options)) {
|
|
76
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
77
|
+
throw new StorageError("SQLite wait and retry options must be nonnegative integers", "config");
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
get readOnly() {
|
|
82
|
+
return this.existingOnly && !this.existingWriter;
|
|
83
|
+
}
|
|
84
|
+
/** Never creates directories, tables, migration state or business defaults. */
|
|
85
|
+
static openExistingReadOnly(databasePath, options) {
|
|
86
|
+
return this.openExisting(databasePath, options);
|
|
87
|
+
}
|
|
88
|
+
/** Validates migration provenance on open and within every existing-only write transaction. */
|
|
89
|
+
static openExistingWritable(databasePath, loadLegacy2, options) {
|
|
90
|
+
return this.openExisting(databasePath, options, loadLegacy2);
|
|
91
|
+
}
|
|
92
|
+
static async openExisting(databasePath, options, loadLegacy2) {
|
|
93
|
+
if (typeof databasePath !== "string" || !isAbsolute(databasePath)) {
|
|
94
|
+
throw new StorageError("Existing SQLite storage requires an absolute database path", "config");
|
|
95
|
+
}
|
|
96
|
+
const provider = new _SQLiteStorageProvider(databasePath, options);
|
|
97
|
+
provider.existingOnly = true;
|
|
98
|
+
provider.existingWriter = loadLegacy2;
|
|
99
|
+
try {
|
|
100
|
+
const migration = await provider.run("read", () => ({ ...provider.existingMigration }));
|
|
101
|
+
return { provider, migration };
|
|
102
|
+
} catch (error) {
|
|
103
|
+
await provider.close();
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async waitForLock(action) {
|
|
108
|
+
for (let attempt = 0; ; attempt++) {
|
|
109
|
+
try {
|
|
110
|
+
action();
|
|
111
|
+
return;
|
|
112
|
+
} catch (error) {
|
|
113
|
+
if (!isBusy(error) || attempt >= this.options.maxRetries) throw error;
|
|
114
|
+
await new Promise((resolve2) => setTimeout(resolve2, this.options.retryDelayMs));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
requireExistingFile() {
|
|
119
|
+
let file;
|
|
120
|
+
try {
|
|
121
|
+
file = statSync(this.databasePath, { bigint: true });
|
|
122
|
+
} catch (error) {
|
|
123
|
+
throw new StorageError(error.code === "ENOENT" ? "Existing SQLite database does not exist" : "Cannot access existing SQLite database", "config");
|
|
124
|
+
}
|
|
125
|
+
if (!file.isFile()) throw new StorageError("Existing SQLite path must be a database file", "config");
|
|
126
|
+
if (this.existingFile && (file.dev !== this.existingFile.dev || file.ino !== this.existingFile.ino || file.birthtimeNs !== this.existingFile.birthtimeNs)) {
|
|
127
|
+
throw new StorageError("Existing SQLite database changed; reconnect to the intended source", "config");
|
|
128
|
+
}
|
|
129
|
+
return file;
|
|
130
|
+
}
|
|
131
|
+
async database() {
|
|
132
|
+
if (this.unusable) throw new StorageError("SQLite connection is unusable; reopen storage", "config");
|
|
133
|
+
if (this.db) {
|
|
134
|
+
if (this.existingWriter) this.requireExistingFile();
|
|
135
|
+
return this.db;
|
|
136
|
+
}
|
|
137
|
+
if (this.existingOnly) {
|
|
138
|
+
const file = this.requireExistingFile();
|
|
139
|
+
if (this.existingWriter) this.existingFile = file;
|
|
140
|
+
} else {
|
|
141
|
+
mkdirSync(dirname(this.databasePath), { recursive: true });
|
|
142
|
+
for (let attempt = 0; ; attempt++) {
|
|
143
|
+
try {
|
|
144
|
+
const file = statSync(this.databasePath);
|
|
145
|
+
if (!file.isFile()) throw new StorageError("SQLite path must be a database file", "config");
|
|
146
|
+
if (file.size > 0) break;
|
|
147
|
+
if (attempt >= this.options.maxRetries) {
|
|
148
|
+
throw new StorageError("Existing SQLite database is empty or truncated; explicit reconciliation required", "config");
|
|
149
|
+
}
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (error.code === "ENOENT") break;
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
await new Promise((resolve2) => setTimeout(resolve2, this.options.retryDelayMs));
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const location = this.existingWriter ? pathToFileURL(this.databasePath).href + "?mode=rw" : this.databasePath;
|
|
158
|
+
const db = new DatabaseSync(location, {
|
|
159
|
+
timeout: this.options.busyTimeoutMs,
|
|
160
|
+
readOnly: this.readOnly,
|
|
161
|
+
enableDoubleQuotedStringLiterals: false,
|
|
162
|
+
allowExtension: false
|
|
163
|
+
});
|
|
164
|
+
try {
|
|
165
|
+
const loadLegacy2 = this.existingWriter;
|
|
166
|
+
if (loadLegacy2) {
|
|
167
|
+
db.exec("PRAGMA synchronous=FULL");
|
|
168
|
+
await this.transaction(db, () => {
|
|
169
|
+
this.validateExistingSchema(db);
|
|
170
|
+
this.existingMigration = migrationResult(this.verifyLegacySource(db, this.readMigrationMarker(db), loadLegacy2));
|
|
171
|
+
});
|
|
172
|
+
this.db = db;
|
|
173
|
+
return db;
|
|
174
|
+
}
|
|
175
|
+
if (this.readOnly) {
|
|
176
|
+
db.exec("PRAGMA query_only=ON");
|
|
177
|
+
db.exec("BEGIN");
|
|
178
|
+
try {
|
|
179
|
+
this.validateExistingSchema(db);
|
|
180
|
+
this.existingMigration = migrationResult(this.readMigrationMarker(db));
|
|
181
|
+
db.exec("COMMIT");
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (db.isTransaction) db.exec("ROLLBACK");
|
|
184
|
+
throw error;
|
|
185
|
+
}
|
|
186
|
+
this.db = db;
|
|
187
|
+
return db;
|
|
188
|
+
}
|
|
189
|
+
if (!this.isUninitializedSchema(db)) this.validateExistingSchema(db);
|
|
190
|
+
await this.waitForLock(() => {
|
|
191
|
+
db.exec("PRAGMA journal_mode=WAL");
|
|
192
|
+
});
|
|
193
|
+
const mode = db.prepare("PRAGMA journal_mode").get();
|
|
194
|
+
if (mode?.journal_mode !== "wal") throw new StorageError("SQLite WAL mode is required", "config");
|
|
195
|
+
db.exec("PRAGMA synchronous=FULL");
|
|
196
|
+
await this.transaction(db, () => {
|
|
197
|
+
if (this.isUninitializedSchema(db)) {
|
|
198
|
+
db.exec(`
|
|
199
|
+
CREATE TABLE storage_kv (key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT;
|
|
200
|
+
CREATE TABLE storage_metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL) STRICT;
|
|
201
|
+
`);
|
|
202
|
+
} else this.validateExistingSchema(db);
|
|
203
|
+
});
|
|
204
|
+
this.db = db;
|
|
205
|
+
return db;
|
|
206
|
+
} catch (error) {
|
|
207
|
+
if (db.isOpen) db.close();
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
isUninitializedSchema(db) {
|
|
212
|
+
return db.prepare("PRAGMA user_version").get()?.user_version === 0 && db.prepare("PRAGMA schema_version").get()?.schema_version === 0 && !db.prepare("SELECT 1 FROM sqlite_schema LIMIT 1").get();
|
|
213
|
+
}
|
|
214
|
+
validateExistingSchema(db) {
|
|
215
|
+
const invalid = () => new StorageError("Existing SQLite schema or integrity is incompatible", "config");
|
|
216
|
+
if (db.prepare("PRAGMA journal_mode").get()?.journal_mode !== "wal" || db.prepare("PRAGMA user_version").get()?.user_version !== 0) throw invalid();
|
|
217
|
+
for (const name of ["storage_kv", "storage_metadata"]) {
|
|
218
|
+
const table = db.prepare("SELECT type, ncol, wr, strict FROM pragma_table_list WHERE schema = ? AND name = ?").get("main", name);
|
|
219
|
+
const columns = db.prepare(`PRAGMA main.table_xinfo('${name}')`).all();
|
|
220
|
+
if (table?.type !== "table" || table.ncol !== 2 || table.wr !== 0 || table.strict !== 1 || columns.length !== 2) throw invalid();
|
|
221
|
+
for (const [index, columnName] of ["key", "value"].entries()) {
|
|
222
|
+
const column = columns[index];
|
|
223
|
+
if (column.name !== columnName || column.type !== "TEXT" || column.notnull !== 1 || column.pk !== (index === 0 ? 1 : 0) || column.hidden !== 0 || column.dflt_value !== null) throw invalid();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (db.prepare("PRAGMA quick_check(1)").get()?.quick_check !== "ok") throw invalid();
|
|
227
|
+
}
|
|
228
|
+
run(operation, action) {
|
|
229
|
+
if (this.closing) return Promise.reject(new StorageError("SQLite storage is closed", operation));
|
|
230
|
+
if (this.readOnly && operation !== "read") {
|
|
231
|
+
return Promise.reject(new StorageError("SQLite storage is read-only", operation));
|
|
232
|
+
}
|
|
233
|
+
const result = this.queue.then(async () => {
|
|
234
|
+
try {
|
|
235
|
+
return await action(await this.database());
|
|
236
|
+
} catch (error) {
|
|
237
|
+
if (error?.code === "ERR_SQLITE_ERROR") {
|
|
238
|
+
const message = isBusy(error) ? "SQLite storage is busy; retry later" : operation === "read" && this.existingOnly ? "Cannot open or read existing SQLite database; it may be corrupt or incompatible" : "SQLite operation failed";
|
|
239
|
+
const wrapped = new StorageError(message, operation);
|
|
240
|
+
Object.defineProperty(wrapped, "cause", { value: error });
|
|
241
|
+
throw wrapped;
|
|
242
|
+
}
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
this.queue = result.catch(() => {
|
|
247
|
+
});
|
|
248
|
+
return result;
|
|
249
|
+
}
|
|
250
|
+
async transaction(db, action) {
|
|
251
|
+
await this.waitForLock(() => db.exec("BEGIN IMMEDIATE"));
|
|
252
|
+
try {
|
|
253
|
+
if (this.existingWriter) {
|
|
254
|
+
this.requireExistingFile();
|
|
255
|
+
if (this.db) this.verifyLegacySource(db, this.readMigrationMarker(db), this.existingWriter);
|
|
256
|
+
}
|
|
257
|
+
const result = action();
|
|
258
|
+
db.exec("COMMIT");
|
|
259
|
+
return result;
|
|
260
|
+
} catch (error) {
|
|
261
|
+
try {
|
|
262
|
+
if (db.isTransaction) db.exec("ROLLBACK");
|
|
263
|
+
} catch {
|
|
264
|
+
this.closing = true;
|
|
265
|
+
this.unusable = true;
|
|
266
|
+
if (db.isOpen) db.close();
|
|
267
|
+
this.db = void 0;
|
|
268
|
+
}
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
read(db, key) {
|
|
273
|
+
return db.prepare("SELECT value FROM storage_kv WHERE key = ?").get(key)?.value ?? null;
|
|
274
|
+
}
|
|
275
|
+
write(db, key, value) {
|
|
276
|
+
if (typeof key !== "string" || typeof value !== "string") {
|
|
277
|
+
throw new StorageError("SQLite keys and values must be strings", "write");
|
|
278
|
+
}
|
|
279
|
+
db.prepare("INSERT INTO storage_kv(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, value);
|
|
280
|
+
}
|
|
281
|
+
getItem(key) {
|
|
282
|
+
return this.run("read", (db) => this.read(db, key));
|
|
283
|
+
}
|
|
284
|
+
setItem(key, value) {
|
|
285
|
+
return this.run("write", (db) => this.transaction(db, () => this.write(db, key, value)));
|
|
286
|
+
}
|
|
287
|
+
removeItem(key) {
|
|
288
|
+
return this.run("delete", (db) => this.transaction(db, () => {
|
|
289
|
+
db.prepare("DELETE FROM storage_kv WHERE key = ?").run(key);
|
|
290
|
+
}));
|
|
291
|
+
}
|
|
292
|
+
clearAll() {
|
|
293
|
+
return this.run("clear", (db) => this.transaction(db, () => db.exec("DELETE FROM storage_kv")));
|
|
294
|
+
}
|
|
295
|
+
compareAndSetItem(key, expected, value) {
|
|
296
|
+
return this.run("write", (db) => this.transaction(db, () => {
|
|
297
|
+
if (this.read(db, key) !== expected) return false;
|
|
298
|
+
if (value === null) db.prepare("DELETE FROM storage_kv WHERE key = ?").run(key);
|
|
299
|
+
else this.write(db, key, value);
|
|
300
|
+
return true;
|
|
301
|
+
}));
|
|
302
|
+
}
|
|
303
|
+
updateData(key, modifier) {
|
|
304
|
+
return this.run("write", (db) => this.transaction(db, () => {
|
|
305
|
+
const raw = this.read(db, key);
|
|
306
|
+
const value = modifier(raw === null ? null : JSON.parse(raw));
|
|
307
|
+
if (value && typeof value.then === "function") {
|
|
308
|
+
throw new StorageError("SQLite updateData modifiers must be synchronous", "write");
|
|
309
|
+
}
|
|
310
|
+
const serialized = JSON.stringify(value);
|
|
311
|
+
if (serialized === void 0) throw new StorageError("Value is not JSON serializable", "write");
|
|
312
|
+
this.write(db, key, serialized);
|
|
313
|
+
}));
|
|
314
|
+
}
|
|
315
|
+
batchUpdate(operations) {
|
|
316
|
+
const batch = operations.map((op) => ({ ...op }));
|
|
317
|
+
return this.run("write", (db) => this.transaction(db, () => {
|
|
318
|
+
for (const op of batch) {
|
|
319
|
+
if (op.operation === "set" && op.value !== void 0) this.write(db, op.key, op.value);
|
|
320
|
+
else if (op.operation === "remove") db.prepare("DELETE FROM storage_kv WHERE key = ?").run(op.key);
|
|
321
|
+
else throw new StorageError("Invalid SQLite batch operation", "write");
|
|
322
|
+
}
|
|
323
|
+
}));
|
|
324
|
+
}
|
|
325
|
+
getAllKeys() {
|
|
326
|
+
return this.run("read", (db) => db.prepare("SELECT key FROM storage_kv ORDER BY key").all().map((row) => row.key));
|
|
327
|
+
}
|
|
328
|
+
/** One SQL statement provides one complete business KV snapshot, including unknown keys. */
|
|
329
|
+
getAllEntries() {
|
|
330
|
+
return this.run("read", (db) => db.prepare("SELECT key, value FROM storage_kv ORDER BY key").all().map((row) => [row.key, row.value]));
|
|
331
|
+
}
|
|
332
|
+
getEntriesByPrefix(prefix) {
|
|
333
|
+
return this.run("read", (db) => db.prepare("SELECT key, value FROM storage_kv WHERE instr(key, ?) = 1 ORDER BY key").all(prefix).map((row) => [row.key, row.value]));
|
|
334
|
+
}
|
|
335
|
+
/** Atomically reads and writes several keys without retaining a transaction across awaits. */
|
|
336
|
+
withWriteTransaction(modifier) {
|
|
337
|
+
return this.run("write", (db) => this.transaction(db, () => {
|
|
338
|
+
let active = true;
|
|
339
|
+
const assertActive = () => {
|
|
340
|
+
if (!active) throw new StorageError("SQLite write transaction has ended", "write");
|
|
341
|
+
};
|
|
342
|
+
try {
|
|
343
|
+
const result = modifier({
|
|
344
|
+
getItem: (key) => {
|
|
345
|
+
assertActive();
|
|
346
|
+
return this.read(db, key);
|
|
347
|
+
},
|
|
348
|
+
setItem: (key, value) => {
|
|
349
|
+
assertActive();
|
|
350
|
+
this.write(db, key, value);
|
|
351
|
+
},
|
|
352
|
+
removeItem: (key) => {
|
|
353
|
+
assertActive();
|
|
354
|
+
db.prepare("DELETE FROM storage_kv WHERE key = ?").run(key);
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
if (result && typeof result.then === "function") {
|
|
358
|
+
void Promise.resolve(result).catch(() => {
|
|
359
|
+
});
|
|
360
|
+
throw new StorageError("SQLite transaction modifiers must be synchronous", "write");
|
|
361
|
+
}
|
|
362
|
+
return result;
|
|
363
|
+
} finally {
|
|
364
|
+
active = false;
|
|
365
|
+
}
|
|
366
|
+
}));
|
|
367
|
+
}
|
|
368
|
+
readMigrationMarker(db) {
|
|
369
|
+
return parseMigrationMarker(db.prepare("SELECT value FROM storage_metadata WHERE key = ?").get(BOOTSTRAP_KEY)?.value);
|
|
370
|
+
}
|
|
371
|
+
matchesSnapshot(db, entries) {
|
|
372
|
+
const rows = db.prepare("SELECT key, value FROM storage_kv").all();
|
|
373
|
+
return rows.length === entries.size && rows.every((row) => entries.get(row.key) === row.value);
|
|
374
|
+
}
|
|
375
|
+
recordSource(marker, legacy, fingerprint) {
|
|
376
|
+
const backupEntries = legacy.readBackupEntries?.();
|
|
377
|
+
return {
|
|
378
|
+
...migrationResult(marker),
|
|
379
|
+
sourceFingerprint: fingerprint,
|
|
380
|
+
backupFingerprint: backupEntries && fingerprintEntries(backupEntries)
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
verifyLegacySource(db, marker, loadLegacy2) {
|
|
384
|
+
const legacy = loadLegacy2(true);
|
|
385
|
+
if (legacy.source === "empty") return marker;
|
|
386
|
+
const fingerprint = fingerprintEntries(legacy.entries);
|
|
387
|
+
if (fingerprint === marker.sourceFingerprint || legacy.source === "backup" && fingerprint === marker.backupFingerprint) return marker;
|
|
388
|
+
if (!this.matchesSnapshot(db, legacy.entries)) {
|
|
389
|
+
throw new StorageError(
|
|
390
|
+
"Legacy JSON and SQLite contain different data. Close older versions and reconcile the retained stores before writing to SQLite.",
|
|
391
|
+
"config",
|
|
392
|
+
{ reason: DESKTOP_STORAGE_DIVERGENCE_REASON }
|
|
393
|
+
);
|
|
394
|
+
}
|
|
395
|
+
const verified = this.recordSource(marker, legacy, fingerprint);
|
|
396
|
+
db.prepare("UPDATE storage_metadata SET value = ? WHERE key = ?").run(JSON.stringify(verified), BOOTSTRAP_KEY);
|
|
397
|
+
return verified;
|
|
398
|
+
}
|
|
399
|
+
/** For desktop bootstrap only. Source loading, copy, verification and marker share one transaction. */
|
|
400
|
+
initializeFromLegacy(load) {
|
|
401
|
+
if (this.existingWriter) {
|
|
402
|
+
return Promise.reject(new StorageError("Migration requires the desktop storage bootstrap", "config"));
|
|
403
|
+
}
|
|
404
|
+
return this.run("write", (db) => this.transaction(db, () => {
|
|
405
|
+
const marker = db.prepare("SELECT value FROM storage_metadata WHERE key = ?").get(BOOTSTRAP_KEY)?.value;
|
|
406
|
+
if (marker !== void 0) {
|
|
407
|
+
return migrationResult(this.verifyLegacySource(db, parseMigrationMarker(marker), load));
|
|
408
|
+
}
|
|
409
|
+
if (db.prepare("SELECT 1 FROM storage_kv LIMIT 1").get()) {
|
|
410
|
+
throw new StorageError("Unmarked SQLite data requires explicit reconciliation", "config");
|
|
411
|
+
}
|
|
412
|
+
const legacy = load(false);
|
|
413
|
+
for (const [key, value] of legacy.entries) this.write(db, key, value);
|
|
414
|
+
if (!this.matchesSnapshot(db, legacy.entries)) {
|
|
415
|
+
throw new StorageError("SQLite migration verification failed", "write");
|
|
416
|
+
}
|
|
417
|
+
const result = { version: 1, source: legacy.source, itemCount: legacy.entries.size };
|
|
418
|
+
const completed = this.recordSource(result, legacy, fingerprintEntries(legacy.entries));
|
|
419
|
+
db.prepare("INSERT INTO storage_metadata(key, value) VALUES (?, ?)").run(BOOTSTRAP_KEY, JSON.stringify(completed));
|
|
420
|
+
return result;
|
|
421
|
+
}));
|
|
422
|
+
}
|
|
423
|
+
getCapabilities() {
|
|
424
|
+
return { supportsAtomic: !this.readOnly, supportsBatch: !this.readOnly, readOnly: this.readOnly };
|
|
425
|
+
}
|
|
426
|
+
/** Writes are already committed durably when their promises resolve. No forced checkpoint. */
|
|
427
|
+
flush() {
|
|
428
|
+
return this.run("write", () => {
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
close() {
|
|
432
|
+
if (this.closePromise) return this.closePromise;
|
|
433
|
+
this.closing = true;
|
|
434
|
+
this.closePromise = this.queue.then(() => {
|
|
435
|
+
if (this.db?.isOpen) this.db.close();
|
|
436
|
+
this.db = void 0;
|
|
437
|
+
});
|
|
438
|
+
this.queue = this.closePromise.catch(() => {
|
|
439
|
+
});
|
|
440
|
+
return this.closePromise;
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
var DESKTOP_DATABASE_FILENAME = "prompt-optimizer-data.sqlite";
|
|
444
|
+
var LEGACY_STORAGE_FILENAME = "prompt-optimizer-data.json";
|
|
445
|
+
function validateExistingUserDataPath(userDataPath) {
|
|
446
|
+
if (typeof userDataPath !== "string" || !isAbsolute2(userDataPath)) {
|
|
447
|
+
throw new StorageError("Existing desktop storage requires an absolute user data directory", "config");
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
async function openExistingDesktopStorage(userDataPath, options) {
|
|
451
|
+
validateExistingUserDataPath(userDataPath);
|
|
452
|
+
return SQLiteStorageProvider.openExistingReadOnly(join(userDataPath, DESKTOP_DATABASE_FILENAME), options);
|
|
453
|
+
}
|
|
454
|
+
async function openExistingDesktopStorageForWriting(userDataPath, options) {
|
|
455
|
+
validateExistingUserDataPath(userDataPath);
|
|
456
|
+
return SQLiteStorageProvider.openExistingWritable(
|
|
457
|
+
join(userDataPath, DESKTOP_DATABASE_FILENAME),
|
|
458
|
+
(alreadyMigrated) => loadLegacy(userDataPath, alreadyMigrated),
|
|
459
|
+
options
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
async function exportDesktopStorageAsLegacyJSON(userDataPath, options) {
|
|
463
|
+
const { provider } = await openExistingDesktopStorage(userDataPath, options);
|
|
464
|
+
try {
|
|
465
|
+
return JSON.stringify(Object.fromEntries(await provider.getAllEntries()));
|
|
466
|
+
} finally {
|
|
467
|
+
await provider.close();
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
function readLegacyFile(filename) {
|
|
471
|
+
let content;
|
|
472
|
+
try {
|
|
473
|
+
content = readFileSync(filename, "utf8");
|
|
474
|
+
} catch (error) {
|
|
475
|
+
if (error.code === "ENOENT") return { status: "missing" };
|
|
476
|
+
throw new StorageError("Cannot read legacy storage; source has been retained", "read");
|
|
477
|
+
}
|
|
478
|
+
try {
|
|
479
|
+
const parsed = JSON.parse(content);
|
|
480
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { status: "invalid" };
|
|
481
|
+
const entries = /* @__PURE__ */ new Map();
|
|
482
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
483
|
+
entries.set(key, typeof value === "string" ? value : JSON.stringify(value));
|
|
484
|
+
}
|
|
485
|
+
return { status: "valid", entries };
|
|
486
|
+
} catch {
|
|
487
|
+
return { status: "invalid" };
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
function loadLegacy(userDataPath, alreadyMigrated) {
|
|
491
|
+
const filename = join(userDataPath, LEGACY_STORAGE_FILENAME);
|
|
492
|
+
const backupFilename = filename + ".backup";
|
|
493
|
+
const main = readLegacyFile(filename);
|
|
494
|
+
if (main.status === "valid") {
|
|
495
|
+
return {
|
|
496
|
+
source: "json",
|
|
497
|
+
entries: main.entries,
|
|
498
|
+
readBackupEntries: () => {
|
|
499
|
+
try {
|
|
500
|
+
const backup2 = readLegacyFile(backupFilename);
|
|
501
|
+
return backup2.status === "valid" ? backup2.entries : void 0;
|
|
502
|
+
} catch (error) {
|
|
503
|
+
if (error instanceof StorageError) return void 0;
|
|
504
|
+
throw error;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
const backup = readLegacyFile(backupFilename);
|
|
510
|
+
if (backup.status === "valid") return { source: "backup", entries: backup.entries };
|
|
511
|
+
if (!alreadyMigrated && (main.status === "invalid" || backup.status === "invalid")) {
|
|
512
|
+
throw new StorageError("Legacy storage is invalid; source has been retained", "read");
|
|
513
|
+
}
|
|
514
|
+
return { source: "empty", entries: /* @__PURE__ */ new Map() };
|
|
515
|
+
}
|
|
516
|
+
async function openDesktopStorage(userDataPath, options) {
|
|
517
|
+
if (!userDataPath) throw new StorageError("Desktop storage requires a user data directory", "config");
|
|
518
|
+
const provider = new SQLiteStorageProvider(join(userDataPath, DESKTOP_DATABASE_FILENAME), options);
|
|
519
|
+
try {
|
|
520
|
+
const migration = await provider.initializeFromLegacy((alreadyMigrated) => loadLegacy(userDataPath, alreadyMigrated));
|
|
521
|
+
return { provider, migration };
|
|
522
|
+
} catch (error) {
|
|
523
|
+
await provider.close();
|
|
524
|
+
throw error;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
export {
|
|
529
|
+
DESKTOP_STORAGE_DIVERGENCE_REASON,
|
|
530
|
+
SQLiteStorageProvider,
|
|
531
|
+
DESKTOP_DATABASE_FILENAME,
|
|
532
|
+
LEGACY_STORAGE_FILENAME,
|
|
533
|
+
openExistingDesktopStorage,
|
|
534
|
+
openExistingDesktopStorageForWriting,
|
|
535
|
+
exportDesktopStorageAsLegacyJSON,
|
|
536
|
+
openDesktopStorage
|
|
537
|
+
};
|