local-lite 2.0.5 → 2.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/bin/local-lite.mjs +215 -2
- package/dist/core/client.d.ts +3 -3
- package/dist/core/client.js +6 -6
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/kv-store/index.d.ts +3 -0
- package/dist/kv-store/index.js +19 -0
- package/dist/kv-store/manager.d.ts +52 -0
- package/dist/kv-store/manager.js +167 -0
- package/dist/kv-store/store.d.ts +13 -0
- package/dist/kv-store/store.js +85 -0
- package/dist/kv-store/types.d.ts +27 -0
- package/dist/kv-store/types.js +2 -0
- package/dist/react/index.d.ts +1 -1
- package/dist/react/index.js +1 -1
- package/dist/react/kv-store.d.ts +9 -0
- package/dist/react/kv-store.js +53 -0
- package/dist/schema/index.d.ts +0 -1
- package/dist/schema/index.js +0 -1
- package/dist/server/dashboard.d.ts +16 -0
- package/dist/server/dashboard.js +1412 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +1 -0
- package/package.json +10 -5
- package/skills/local-lite-offline-actions/SKILL.md +11 -11
- package/skills/local-lite-react/SKILL.md +7 -7
|
@@ -0,0 +1,1412 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createDashboardHandler = createDashboardHandler;
|
|
4
|
+
const encryption_js_1 = require("../backups/encryption.js");
|
|
5
|
+
const store_js_1 = require("../kv-store/store.js");
|
|
6
|
+
const sql_js_1 = require("../utils/sql.js");
|
|
7
|
+
function jsonResponse(data, status = 200) {
|
|
8
|
+
return new Response(JSON.stringify(data), {
|
|
9
|
+
status,
|
|
10
|
+
headers: {
|
|
11
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
12
|
+
'Cache-Control': 'no-store',
|
|
13
|
+
},
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function errorResponse(message, status = 400) {
|
|
17
|
+
return jsonResponse({ error: message }, status);
|
|
18
|
+
}
|
|
19
|
+
function isAuthorized(request, url, authToken) {
|
|
20
|
+
if (!authToken)
|
|
21
|
+
return true;
|
|
22
|
+
const header = request.headers.get('authorization');
|
|
23
|
+
if (header === `Bearer ${authToken}`)
|
|
24
|
+
return true;
|
|
25
|
+
if (url.searchParams.get('token') === authToken)
|
|
26
|
+
return true;
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
async function listTables(db) {
|
|
30
|
+
const tablesRows = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name ASC;`);
|
|
31
|
+
const summaries = [];
|
|
32
|
+
for (const row of tablesRows ?? []) {
|
|
33
|
+
const name = String(row.name ?? '');
|
|
34
|
+
if (!name)
|
|
35
|
+
continue;
|
|
36
|
+
const quoted = (0, sql_js_1.escapeIdentifier)(name);
|
|
37
|
+
const [infoRows, countRows, indexListRows] = await Promise.all([
|
|
38
|
+
db.execute(`PRAGMA table_info(${quoted});`),
|
|
39
|
+
db.execute(`SELECT COUNT(*) AS cnt FROM ${quoted};`),
|
|
40
|
+
db.execute(`PRAGMA index_list(${quoted});`).catch(() => []),
|
|
41
|
+
]);
|
|
42
|
+
const columns = (infoRows ?? []).map((col) => ({
|
|
43
|
+
cid: Number(col.cid ?? 0),
|
|
44
|
+
name: String(col.name ?? ''),
|
|
45
|
+
type: String(col.type ?? ''),
|
|
46
|
+
notnull: Number(col.notnull ?? 0),
|
|
47
|
+
dflt_value: col.dflt_value ?? null,
|
|
48
|
+
pk: Number(col.pk ?? 0),
|
|
49
|
+
}));
|
|
50
|
+
const indexes = [];
|
|
51
|
+
for (const idx of indexListRows ?? []) {
|
|
52
|
+
const idxName = String(idx.name ?? '');
|
|
53
|
+
if (!idxName)
|
|
54
|
+
continue;
|
|
55
|
+
const idxInfoRows = await db
|
|
56
|
+
.execute(`PRAGMA index_info(${(0, sql_js_1.escapeIdentifier)(idxName)});`)
|
|
57
|
+
.catch(() => []);
|
|
58
|
+
indexes.push({
|
|
59
|
+
name: idxName,
|
|
60
|
+
unique: Boolean(idx.unique),
|
|
61
|
+
columns: (idxInfoRows ?? [])
|
|
62
|
+
.map((item) => String(item.name ?? ''))
|
|
63
|
+
.filter(Boolean),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
const fkRows = await db
|
|
67
|
+
.execute(`PRAGMA foreign_key_list(${quoted});`)
|
|
68
|
+
.catch(() => []);
|
|
69
|
+
const foreignKeys = (fkRows ?? [])
|
|
70
|
+
.map((fk) => ({
|
|
71
|
+
table: String(fk.table ?? ''),
|
|
72
|
+
from: String(fk.from ?? ''),
|
|
73
|
+
to: String(fk.to ?? ''),
|
|
74
|
+
}))
|
|
75
|
+
.filter((fk) => fk.table && fk.from && fk.to);
|
|
76
|
+
const rowCount = Number(countRows?.[0]?.cnt ?? 0);
|
|
77
|
+
summaries.push({
|
|
78
|
+
name,
|
|
79
|
+
internal: (0, sql_js_1.isInternalTable)(name),
|
|
80
|
+
rowCount,
|
|
81
|
+
columns,
|
|
82
|
+
indexes,
|
|
83
|
+
foreignKeys,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
return summaries;
|
|
87
|
+
}
|
|
88
|
+
async function readRowsIfTableExists(db, tableName, limit = 100) {
|
|
89
|
+
const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?;`, [tableName]);
|
|
90
|
+
if (!exists?.length)
|
|
91
|
+
return null;
|
|
92
|
+
const rows = await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(tableName)} LIMIT ?;`, [limit]);
|
|
93
|
+
return rows ?? [];
|
|
94
|
+
}
|
|
95
|
+
function toCsv(columns, rows) {
|
|
96
|
+
const escapeCell = (val) => {
|
|
97
|
+
if (val === null || val === undefined)
|
|
98
|
+
return '';
|
|
99
|
+
const str = typeof val === 'object' ? JSON.stringify(val) : String(val);
|
|
100
|
+
if (/[",\n\r]/.test(str)) {
|
|
101
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
102
|
+
}
|
|
103
|
+
return str;
|
|
104
|
+
};
|
|
105
|
+
const header = columns.map(escapeCell).join(',');
|
|
106
|
+
const lines = rows.map((row) => columns.map((col) => escapeCell(row?.[col])).join(','));
|
|
107
|
+
return [header, ...lines].join('\r\n');
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Creates a Web Standard Request/Response handler for the local-lite dashboard.
|
|
111
|
+
* Can be mounted on any Node, Bun, Deno, or Edge server, or launched via `local-lite dashboard`.
|
|
112
|
+
*/
|
|
113
|
+
function createDashboardHandler(db, options = {}) {
|
|
114
|
+
const title = options.title ?? 'local-lite Dashboard';
|
|
115
|
+
const readOnly = Boolean(options.readOnly);
|
|
116
|
+
const basePath = (options.basePath ?? '').replace(/\/+$/, '');
|
|
117
|
+
const logs = [];
|
|
118
|
+
let nextLogId = 1;
|
|
119
|
+
const recordLog = (method, path, status, startedAt, detail) => {
|
|
120
|
+
if (path === '/api/logs')
|
|
121
|
+
return;
|
|
122
|
+
logs.unshift({
|
|
123
|
+
id: nextLogId++,
|
|
124
|
+
timestamp: Date.now(),
|
|
125
|
+
method,
|
|
126
|
+
path,
|
|
127
|
+
status,
|
|
128
|
+
durationMs: Math.round((performance.now() - startedAt) * 100) / 100,
|
|
129
|
+
detail,
|
|
130
|
+
});
|
|
131
|
+
if (logs.length > 200)
|
|
132
|
+
logs.length = 200;
|
|
133
|
+
};
|
|
134
|
+
return async (request) => {
|
|
135
|
+
const startedAt = performance.now();
|
|
136
|
+
const url = new URL(request.url);
|
|
137
|
+
let pathname = url.pathname;
|
|
138
|
+
if (basePath && pathname.startsWith(basePath)) {
|
|
139
|
+
pathname = pathname.slice(basePath.length) || '/';
|
|
140
|
+
}
|
|
141
|
+
if (!isAuthorized(request, url, options.authToken)) {
|
|
142
|
+
recordLog(request.method, pathname, 401, startedAt, 'Unauthorized');
|
|
143
|
+
return errorResponse('Unauthorized.', 401);
|
|
144
|
+
}
|
|
145
|
+
let loggedThisRequest = false;
|
|
146
|
+
const reply = (res, detail) => {
|
|
147
|
+
if (pathname.startsWith('/api/')) {
|
|
148
|
+
loggedThisRequest = true;
|
|
149
|
+
recordLog(request.method, pathname, res.status, startedAt, detail);
|
|
150
|
+
}
|
|
151
|
+
return res;
|
|
152
|
+
};
|
|
153
|
+
const res = await (async () => {
|
|
154
|
+
try {
|
|
155
|
+
if (request.method === 'GET' &&
|
|
156
|
+
(pathname === '/' || pathname === '/index.html' || pathname.startsWith('/assets/'))) {
|
|
157
|
+
const staticRes = await tryServeDashboardAsset(pathname, title);
|
|
158
|
+
if (staticRes)
|
|
159
|
+
return staticRes;
|
|
160
|
+
return new Response(`<!DOCTYPE html><html><head><meta charset="utf-8"/><title>${escapeHtml(title)}</title></head><body style="font-family:sans-serif;background:#0b0d12;color:#e6ebf5;padding:32px;"><h2>${escapeHtml(title)}</h2><p>Dashboard UI not built. Run <code>npm --prefix dashboard run build</code> or launch via <code>npx local-lite dashboard</code>.</p></body></html>`, {
|
|
161
|
+
status: 200,
|
|
162
|
+
headers: {
|
|
163
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
164
|
+
'Cache-Control': 'no-store',
|
|
165
|
+
},
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
if (request.method === 'GET' && pathname === '/api/overview') {
|
|
169
|
+
const [tables, versionRows, journalRows, pageSizeRows, pageCountRows] = await Promise.all([
|
|
170
|
+
listTables(db),
|
|
171
|
+
db.execute('SELECT sqlite_version() AS version;'),
|
|
172
|
+
db.execute('PRAGMA journal_mode;').catch(() => []),
|
|
173
|
+
db.execute('PRAGMA page_size;').catch(() => []),
|
|
174
|
+
db.execute('PRAGMA page_count;').catch(() => []),
|
|
175
|
+
]);
|
|
176
|
+
const dataTables = tables.filter((t) => !t.internal);
|
|
177
|
+
const systemTables = tables.filter((t) => t.internal);
|
|
178
|
+
const totalRows = dataTables.reduce((acc, t) => acc + t.rowCount, 0);
|
|
179
|
+
const totalIndexes = tables.reduce((acc, t) => acc + t.indexes.length, 0);
|
|
180
|
+
const pageSize = Number(pageSizeRows?.[0]?.page_size ?? 0);
|
|
181
|
+
const pageCount = Number(pageCountRows?.[0]?.page_count ?? 0);
|
|
182
|
+
return jsonResponse({
|
|
183
|
+
title,
|
|
184
|
+
readOnly,
|
|
185
|
+
sqliteVersion: String(versionRows?.[0]?.version ?? 'unknown'),
|
|
186
|
+
journalMode: String(journalRows?.[0]?.journal_mode ?? 'unknown'),
|
|
187
|
+
databaseSizeBytes: pageSize * pageCount,
|
|
188
|
+
dataTableCount: dataTables.length,
|
|
189
|
+
systemTableCount: systemTables.length,
|
|
190
|
+
totalDataRows: totalRows,
|
|
191
|
+
totalIndexes,
|
|
192
|
+
topTables: [...dataTables]
|
|
193
|
+
.sort((a, b) => b.rowCount - a.rowCount)
|
|
194
|
+
.slice(0, 8)
|
|
195
|
+
.map((t) => ({ name: t.name, rowCount: t.rowCount })),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
if (request.method === 'GET' && pathname === '/api/tables') {
|
|
199
|
+
const tables = await listTables(db);
|
|
200
|
+
return jsonResponse({ tables });
|
|
201
|
+
}
|
|
202
|
+
if (request.method === 'GET' && pathname === '/api/schema/sql') {
|
|
203
|
+
const dialectRaw = (url.searchParams.get('dialect') ?? 'sqlite').toLowerCase();
|
|
204
|
+
const dialect = ['sqlite', 'postgres', 'mysql'].includes(dialectRaw)
|
|
205
|
+
? dialectRaw
|
|
206
|
+
: 'sqlite';
|
|
207
|
+
const includeSystem = url.searchParams.get('includeSystem') === '1';
|
|
208
|
+
const onlyTable = url.searchParams.get('table');
|
|
209
|
+
const allTables = await listTables(db);
|
|
210
|
+
const selected = allTables.filter((t) => {
|
|
211
|
+
if (onlyTable && t.name !== onlyTable)
|
|
212
|
+
return false;
|
|
213
|
+
if (!onlyTable && !includeSystem && t.internal)
|
|
214
|
+
return false;
|
|
215
|
+
return true;
|
|
216
|
+
});
|
|
217
|
+
const quoteId = (id) => dialect === 'mysql'
|
|
218
|
+
? `\`${id.replace(/`/g, '``')}\``
|
|
219
|
+
: (0, sql_js_1.escapeIdentifier)(id);
|
|
220
|
+
const mapColType = (rawType, isPk) => {
|
|
221
|
+
const upper = (rawType || 'TEXT').toUpperCase();
|
|
222
|
+
if (dialect === 'sqlite')
|
|
223
|
+
return upper;
|
|
224
|
+
if (dialect === 'postgres') {
|
|
225
|
+
if (upper.includes('INT'))
|
|
226
|
+
return 'BIGINT';
|
|
227
|
+
if (upper.includes('REAL') || upper.includes('FLOA') || upper.includes('DOUB'))
|
|
228
|
+
return 'DOUBLE PRECISION';
|
|
229
|
+
if (upper.includes('BLOB'))
|
|
230
|
+
return 'BYTEA';
|
|
231
|
+
if (upper.includes('NUM') || upper.includes('DEC'))
|
|
232
|
+
return 'NUMERIC';
|
|
233
|
+
return 'TEXT';
|
|
234
|
+
}
|
|
235
|
+
// mysql
|
|
236
|
+
if (upper.includes('INT'))
|
|
237
|
+
return 'BIGINT';
|
|
238
|
+
if (upper.includes('REAL') || upper.includes('FLOA') || upper.includes('DOUB'))
|
|
239
|
+
return 'DOUBLE';
|
|
240
|
+
if (upper.includes('BLOB'))
|
|
241
|
+
return 'LONGBLOB';
|
|
242
|
+
if (upper.includes('NUM') || upper.includes('DEC'))
|
|
243
|
+
return 'DECIMAL(18, 4)';
|
|
244
|
+
return isPk ? 'VARCHAR(255)' : 'TEXT';
|
|
245
|
+
};
|
|
246
|
+
const statements = [];
|
|
247
|
+
for (const t of selected) {
|
|
248
|
+
const pkCols = t.columns.filter((c) => c.pk > 0).sort((a, b) => a.pk - b.pk);
|
|
249
|
+
const singlePk = pkCols.length === 1;
|
|
250
|
+
const lines = t.columns.map((c) => {
|
|
251
|
+
const parts = [quoteId(c.name), mapColType(c.type, c.pk > 0)];
|
|
252
|
+
if (singlePk && c.pk > 0)
|
|
253
|
+
parts.push('PRIMARY KEY');
|
|
254
|
+
if (c.notnull > 0 && !(singlePk && c.pk > 0))
|
|
255
|
+
parts.push('NOT NULL');
|
|
256
|
+
if (c.dflt_value != null)
|
|
257
|
+
parts.push(`DEFAULT ${String(c.dflt_value)}`);
|
|
258
|
+
return ` ${parts.join(' ')}`;
|
|
259
|
+
});
|
|
260
|
+
if (pkCols.length > 1) {
|
|
261
|
+
lines.push(` PRIMARY KEY (${pkCols.map((c) => quoteId(c.name)).join(', ')})`);
|
|
262
|
+
}
|
|
263
|
+
statements.push(`CREATE TABLE IF NOT EXISTS ${quoteId(t.name)} (\n${lines.join(',\n')}\n);`);
|
|
264
|
+
for (const idx of t.indexes) {
|
|
265
|
+
if (idx.name.startsWith('sqlite_autoindex_') || idx.columns.length === 0) {
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const uniqueSql = idx.unique ? 'UNIQUE ' : '';
|
|
269
|
+
const ifNotExists = dialect === 'mysql' ? '' : 'IF NOT EXISTS ';
|
|
270
|
+
statements.push(`CREATE ${uniqueSql}INDEX ${ifNotExists}${quoteId(idx.name)} ON ${quoteId(t.name)} (${idx.columns.map(quoteId).join(', ')});`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const sql = statements.join('\n\n');
|
|
274
|
+
if (url.searchParams.get('download') === '1') {
|
|
275
|
+
return new Response(sql, {
|
|
276
|
+
status: 200,
|
|
277
|
+
headers: {
|
|
278
|
+
'Content-Type': 'application/sql; charset=utf-8',
|
|
279
|
+
'Content-Disposition': `attachment; filename="schema-${dialect}.sql"`,
|
|
280
|
+
},
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
return jsonResponse({ dialect, tableCount: selected.length, sql });
|
|
284
|
+
}
|
|
285
|
+
if (request.method === 'POST' && pathname === '/api/tables') {
|
|
286
|
+
if (readOnly) {
|
|
287
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
288
|
+
}
|
|
289
|
+
const body = (await request.json().catch(() => null));
|
|
290
|
+
const name = String(body?.name ?? '').trim();
|
|
291
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name)) {
|
|
292
|
+
return errorResponse('Invalid table name. Use letters, numbers, and underscores.', 400);
|
|
293
|
+
}
|
|
294
|
+
if ((0, sql_js_1.isInternalTable)(name)) {
|
|
295
|
+
return errorResponse('Cannot create an internal system table.', 400);
|
|
296
|
+
}
|
|
297
|
+
const cols = Array.isArray(body?.columns) ? body.columns : [];
|
|
298
|
+
if (cols.length === 0) {
|
|
299
|
+
return errorResponse('At least one column is required.', 400);
|
|
300
|
+
}
|
|
301
|
+
const allowedTypes = new Set(['TEXT', 'INTEGER', 'REAL', 'BLOB', 'NUMERIC']);
|
|
302
|
+
const colDefs = cols.map((c) => {
|
|
303
|
+
const colName = String(c.name ?? '').trim();
|
|
304
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
|
|
305
|
+
throw new Error(`Invalid column name: ${colName}`);
|
|
306
|
+
}
|
|
307
|
+
const colType = allowedTypes.has(String(c.type ?? 'TEXT').toUpperCase())
|
|
308
|
+
? String(c.type ?? 'TEXT').toUpperCase()
|
|
309
|
+
: 'TEXT';
|
|
310
|
+
const parts = [(0, sql_js_1.escapeIdentifier)(colName), colType];
|
|
311
|
+
if (c.pk)
|
|
312
|
+
parts.push('PRIMARY KEY');
|
|
313
|
+
if (c.notnull && !c.pk)
|
|
314
|
+
parts.push('NOT NULL');
|
|
315
|
+
return parts.join(' ');
|
|
316
|
+
});
|
|
317
|
+
await db.execute(`CREATE TABLE ${(0, sql_js_1.escapeIdentifier)(name)} (${colDefs.join(', ')});`);
|
|
318
|
+
return jsonResponse({ ok: true, name }, 201);
|
|
319
|
+
}
|
|
320
|
+
const tableTargetMatch = pathname.match(/^\/api\/tables\/([^/]+)$/);
|
|
321
|
+
if (tableTargetMatch && request.method === 'PATCH') {
|
|
322
|
+
if (readOnly) {
|
|
323
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
324
|
+
}
|
|
325
|
+
const tableName = decodeURIComponent(tableTargetMatch[1]);
|
|
326
|
+
if ((0, sql_js_1.isInternalTable)(tableName)) {
|
|
327
|
+
return errorResponse('Cannot modify internal system tables.', 403);
|
|
328
|
+
}
|
|
329
|
+
const body = (await request.json().catch(() => null));
|
|
330
|
+
if (body?.newName) {
|
|
331
|
+
const nextName = String(body.newName).trim();
|
|
332
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(nextName) || (0, sql_js_1.isInternalTable)(nextName)) {
|
|
333
|
+
return errorResponse('Invalid target table name.', 400);
|
|
334
|
+
}
|
|
335
|
+
await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} RENAME TO ${(0, sql_js_1.escapeIdentifier)(nextName)};`);
|
|
336
|
+
return jsonResponse({ ok: true, name: nextName });
|
|
337
|
+
}
|
|
338
|
+
if (body?.addColumn) {
|
|
339
|
+
const colName = String(body.addColumn.name ?? '').trim();
|
|
340
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
|
|
341
|
+
return errorResponse('Invalid column name.', 400);
|
|
342
|
+
}
|
|
343
|
+
const allowedTypes = new Set(['TEXT', 'INTEGER', 'REAL', 'BLOB', 'NUMERIC']);
|
|
344
|
+
const colType = allowedTypes.has(String(body.addColumn.type ?? 'TEXT').toUpperCase())
|
|
345
|
+
? String(body.addColumn.type ?? 'TEXT').toUpperCase()
|
|
346
|
+
: 'TEXT';
|
|
347
|
+
const parts = [(0, sql_js_1.escapeIdentifier)(colName), colType];
|
|
348
|
+
const dflt = body.addColumn.defaultValue;
|
|
349
|
+
if (dflt !== undefined && dflt !== '') {
|
|
350
|
+
const escapedDflt = `'${String(dflt).replace(/'/g, "''")}'`;
|
|
351
|
+
if (body.addColumn.notnull)
|
|
352
|
+
parts.push('NOT NULL');
|
|
353
|
+
parts.push(`DEFAULT ${escapedDflt}`);
|
|
354
|
+
}
|
|
355
|
+
else if (body.addColumn.notnull) {
|
|
356
|
+
parts.push("NOT NULL DEFAULT ''");
|
|
357
|
+
}
|
|
358
|
+
await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} ADD COLUMN ${parts.join(' ')};`);
|
|
359
|
+
return jsonResponse({ ok: true });
|
|
360
|
+
}
|
|
361
|
+
if (body?.dropColumn) {
|
|
362
|
+
const colName = String(body.dropColumn).trim();
|
|
363
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(colName)) {
|
|
364
|
+
return errorResponse('Invalid column name.', 400);
|
|
365
|
+
}
|
|
366
|
+
await db.execute(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(tableName)} DROP COLUMN ${(0, sql_js_1.escapeIdentifier)(colName)};`);
|
|
367
|
+
return jsonResponse({ ok: true });
|
|
368
|
+
}
|
|
369
|
+
return errorResponse('Provide newName, addColumn, or dropColumn.', 400);
|
|
370
|
+
}
|
|
371
|
+
if (tableTargetMatch && request.method === 'DELETE') {
|
|
372
|
+
if (readOnly) {
|
|
373
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
374
|
+
}
|
|
375
|
+
const tableName = decodeURIComponent(tableTargetMatch[1]);
|
|
376
|
+
if ((0, sql_js_1.isInternalTable)(tableName)) {
|
|
377
|
+
return errorResponse('Cannot drop internal system tables.', 403);
|
|
378
|
+
}
|
|
379
|
+
await db.execute(`DROP TABLE IF EXISTS ${(0, sql_js_1.escapeIdentifier)(tableName)};`);
|
|
380
|
+
return jsonResponse({ ok: true });
|
|
381
|
+
}
|
|
382
|
+
const clearTableMatch = pathname.match(/^\/api\/tables\/([^/]+)\/clear$/);
|
|
383
|
+
if (clearTableMatch && request.method === 'POST') {
|
|
384
|
+
if (readOnly) {
|
|
385
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
386
|
+
}
|
|
387
|
+
const tableName = decodeURIComponent(clearTableMatch[1]);
|
|
388
|
+
if ((0, sql_js_1.isInternalTable)(tableName)) {
|
|
389
|
+
return errorResponse('Cannot clear internal system tables from here.', 403);
|
|
390
|
+
}
|
|
391
|
+
await db.execute(`DELETE FROM ${(0, sql_js_1.escapeIdentifier)(tableName)};`);
|
|
392
|
+
return jsonResponse({ ok: true });
|
|
393
|
+
}
|
|
394
|
+
const importTableMatch = pathname.match(/^\/api\/tables\/([^/]+)\/import$/);
|
|
395
|
+
if (importTableMatch && request.method === 'POST') {
|
|
396
|
+
if (readOnly) {
|
|
397
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
398
|
+
}
|
|
399
|
+
const tableName = decodeURIComponent(importTableMatch[1]);
|
|
400
|
+
const tables = await listTables(db);
|
|
401
|
+
const tableMeta = tables.find((t) => t.name === tableName);
|
|
402
|
+
if (!tableMeta) {
|
|
403
|
+
return errorResponse(`Table "${tableName}" not found.`, 404);
|
|
404
|
+
}
|
|
405
|
+
const body = (await request.json().catch(() => null));
|
|
406
|
+
const rows = Array.isArray(body?.rows) ? body.rows : [];
|
|
407
|
+
if (rows.length === 0) {
|
|
408
|
+
return errorResponse('rows array is required.', 400);
|
|
409
|
+
}
|
|
410
|
+
const validCols = new Set(tableMeta.columns.map((c) => c.name));
|
|
411
|
+
let imported = 0;
|
|
412
|
+
for (const row of rows) {
|
|
413
|
+
if (!row || typeof row !== 'object')
|
|
414
|
+
continue;
|
|
415
|
+
const entries = Object.entries(row).filter(([k]) => validCols.has(k));
|
|
416
|
+
if (entries.length === 0)
|
|
417
|
+
continue;
|
|
418
|
+
const cols = entries.map(([k]) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
|
|
419
|
+
const placeholders = entries.map(() => '?').join(', ');
|
|
420
|
+
await db.execute(`INSERT OR REPLACE INTO ${(0, sql_js_1.escapeIdentifier)(tableName)} (${cols}) VALUES (${placeholders});`, entries.map(([, v]) => v));
|
|
421
|
+
imported += 1;
|
|
422
|
+
}
|
|
423
|
+
return jsonResponse({ ok: true, imported });
|
|
424
|
+
}
|
|
425
|
+
const indexCreateMatch = pathname.match(/^\/api\/tables\/([^/]+)\/indexes$/);
|
|
426
|
+
if (indexCreateMatch && request.method === 'POST') {
|
|
427
|
+
if (readOnly) {
|
|
428
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
429
|
+
}
|
|
430
|
+
const tableName = decodeURIComponent(indexCreateMatch[1]);
|
|
431
|
+
const body = (await request.json().catch(() => null));
|
|
432
|
+
const idxName = String(body?.name ?? '').trim();
|
|
433
|
+
const cols = Array.isArray(body?.columns) ? body.columns.filter(Boolean) : [];
|
|
434
|
+
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(idxName) || cols.length === 0) {
|
|
435
|
+
return errorResponse('Valid index name and at least one column are required.', 400);
|
|
436
|
+
}
|
|
437
|
+
const uniqueSql = body?.unique ? 'UNIQUE ' : '';
|
|
438
|
+
const colSql = cols.map((c) => (0, sql_js_1.escapeIdentifier)(c)).join(', ');
|
|
439
|
+
await db.execute(`CREATE ${uniqueSql}INDEX IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(idxName)} ON ${(0, sql_js_1.escapeIdentifier)(tableName)} (${colSql});`);
|
|
440
|
+
return jsonResponse({ ok: true }, 201);
|
|
441
|
+
}
|
|
442
|
+
const indexDropMatch = pathname.match(/^\/api\/tables\/([^/]+)\/indexes\/([^/]+)$/);
|
|
443
|
+
if (indexDropMatch && request.method === 'DELETE') {
|
|
444
|
+
if (readOnly) {
|
|
445
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
446
|
+
}
|
|
447
|
+
const idxName = decodeURIComponent(indexDropMatch[2]);
|
|
448
|
+
await db.execute(`DROP INDEX IF EXISTS ${(0, sql_js_1.escapeIdentifier)(idxName)};`);
|
|
449
|
+
return jsonResponse({ ok: true });
|
|
450
|
+
}
|
|
451
|
+
const exportMatch = pathname.match(/^\/api\/tables\/([^/]+)\/export$/);
|
|
452
|
+
if (exportMatch && request.method === 'GET') {
|
|
453
|
+
const tableName = decodeURIComponent(exportMatch[1]);
|
|
454
|
+
const tables = await listTables(db);
|
|
455
|
+
const tableMeta = tables.find((t) => t.name === tableName);
|
|
456
|
+
if (!tableMeta) {
|
|
457
|
+
return errorResponse(`Table "${tableName}" not found.`, 404);
|
|
458
|
+
}
|
|
459
|
+
const format = url.searchParams.get('format') === 'csv' ? 'csv' : 'json';
|
|
460
|
+
const rows = (await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(tableName)} LIMIT 10000;`)) ?? [];
|
|
461
|
+
if (format === 'csv') {
|
|
462
|
+
const cols = tableMeta.columns.map((c) => c.name);
|
|
463
|
+
return new Response(toCsv(cols, rows), {
|
|
464
|
+
status: 200,
|
|
465
|
+
headers: {
|
|
466
|
+
'Content-Type': 'text/csv; charset=utf-8',
|
|
467
|
+
'Content-Disposition': `attachment; filename="${tableName}.csv"`,
|
|
468
|
+
},
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
return new Response(JSON.stringify(rows, null, 2), {
|
|
472
|
+
status: 200,
|
|
473
|
+
headers: {
|
|
474
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
475
|
+
'Content-Disposition': `attachment; filename="${tableName}.json"`,
|
|
476
|
+
},
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
const tableRowsMatch = pathname.match(/^\/api\/tables\/([^/]+)\/rows$/);
|
|
480
|
+
if (tableRowsMatch) {
|
|
481
|
+
const tableName = decodeURIComponent(tableRowsMatch[1]);
|
|
482
|
+
const tables = await listTables(db);
|
|
483
|
+
const tableMeta = tables.find((t) => t.name === tableName);
|
|
484
|
+
if (!tableMeta) {
|
|
485
|
+
return errorResponse(`Table "${tableName}" not found.`, 404);
|
|
486
|
+
}
|
|
487
|
+
const quotedTable = (0, sql_js_1.escapeIdentifier)(tableName);
|
|
488
|
+
if (request.method === 'GET') {
|
|
489
|
+
const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit') ?? 50)));
|
|
490
|
+
const offset = Math.max(0, Number(url.searchParams.get('offset') ?? 0));
|
|
491
|
+
const search = (url.searchParams.get('search') ?? '').trim();
|
|
492
|
+
const filterCol = (url.searchParams.get('filterCol') ?? '').trim();
|
|
493
|
+
const filterVal = url.searchParams.get('filterVal') ?? '';
|
|
494
|
+
const orderBy = url.searchParams.get('orderBy') ?? '';
|
|
495
|
+
const orderDir = url.searchParams.get('orderDir')?.toUpperCase() === 'DESC'
|
|
496
|
+
? 'DESC'
|
|
497
|
+
: 'ASC';
|
|
498
|
+
const validColNames = new Set(tableMeta.columns.map((c) => c.name));
|
|
499
|
+
const params = [];
|
|
500
|
+
const conditions = [];
|
|
501
|
+
if (search && tableMeta.columns.length > 0) {
|
|
502
|
+
const likeTerm = `%${search.replace(/[%_\\]/g, '\\$&')}%`;
|
|
503
|
+
const predicates = tableMeta.columns.map((col) => {
|
|
504
|
+
params.push(likeTerm);
|
|
505
|
+
return `CAST(${(0, sql_js_1.escapeIdentifier)(col.name)} AS TEXT) LIKE ? ESCAPE '\\'`;
|
|
506
|
+
});
|
|
507
|
+
conditions.push(`(${predicates.join(' OR ')})`);
|
|
508
|
+
}
|
|
509
|
+
if (filterCol && validColNames.has(filterCol) && filterVal !== '') {
|
|
510
|
+
params.push(filterVal);
|
|
511
|
+
conditions.push(`CAST(${(0, sql_js_1.escapeIdentifier)(filterCol)} AS TEXT) = ?`);
|
|
512
|
+
}
|
|
513
|
+
const whereClause = conditions.length > 0 ? ` WHERE ${conditions.join(' AND ')}` : '';
|
|
514
|
+
let orderClause = '';
|
|
515
|
+
if (orderBy && validColNames.has(orderBy)) {
|
|
516
|
+
orderClause = ` ORDER BY ${(0, sql_js_1.escapeIdentifier)(orderBy)} ${orderDir}`;
|
|
517
|
+
}
|
|
518
|
+
const countRows = await db.execute(`SELECT COUNT(*) AS cnt FROM ${quotedTable}${whereClause};`, params);
|
|
519
|
+
const total = Number(countRows?.[0]?.cnt ?? 0);
|
|
520
|
+
const rows = await db.execute(`SELECT * FROM ${quotedTable}${whereClause}${orderClause} LIMIT ? OFFSET ?;`, [...params, limit, offset]);
|
|
521
|
+
return jsonResponse({
|
|
522
|
+
table: tableMeta,
|
|
523
|
+
rows: rows ?? [],
|
|
524
|
+
total,
|
|
525
|
+
limit,
|
|
526
|
+
offset,
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
if (readOnly) {
|
|
530
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
531
|
+
}
|
|
532
|
+
const body = (await request.json().catch(() => null));
|
|
533
|
+
if (!body || typeof body !== 'object') {
|
|
534
|
+
return errorResponse('JSON object body is required.', 400);
|
|
535
|
+
}
|
|
536
|
+
const validColNames = new Set(tableMeta.columns.map((c) => c.name));
|
|
537
|
+
const pkColumns = tableMeta.columns
|
|
538
|
+
.filter((c) => c.pk > 0)
|
|
539
|
+
.sort((a, b) => a.pk - b.pk);
|
|
540
|
+
if (request.method === 'POST') {
|
|
541
|
+
const entries = Object.entries(body).filter(([key]) => validColNames.has(key));
|
|
542
|
+
if (entries.length === 0) {
|
|
543
|
+
return errorResponse('At least one valid column is required.', 400);
|
|
544
|
+
}
|
|
545
|
+
const cols = entries.map(([k]) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
|
|
546
|
+
const placeholders = entries.map(() => '?').join(', ');
|
|
547
|
+
const values = entries.map(([, v]) => v);
|
|
548
|
+
await db.execute(`INSERT INTO ${quotedTable} (${cols}) VALUES (${placeholders});`, values);
|
|
549
|
+
return jsonResponse({ ok: true }, 201);
|
|
550
|
+
}
|
|
551
|
+
if (request.method === 'PATCH') {
|
|
552
|
+
if (pkColumns.length === 0) {
|
|
553
|
+
return errorResponse(`Table "${tableName}" has no primary key for row updates.`, 400);
|
|
554
|
+
}
|
|
555
|
+
const updates = body.updates;
|
|
556
|
+
const key = body.key;
|
|
557
|
+
if (!updates || !key) {
|
|
558
|
+
return errorResponse('Both "key" and "updates" objects are required.', 400);
|
|
559
|
+
}
|
|
560
|
+
const setEntries = Object.entries(updates).filter(([col]) => validColNames.has(col));
|
|
561
|
+
if (setEntries.length === 0) {
|
|
562
|
+
return errorResponse('No valid update columns provided.', 400);
|
|
563
|
+
}
|
|
564
|
+
const setClause = setEntries
|
|
565
|
+
.map(([col]) => `${(0, sql_js_1.escapeIdentifier)(col)} = ?`)
|
|
566
|
+
.join(', ');
|
|
567
|
+
const whereClause = pkColumns
|
|
568
|
+
.map((pk) => `${(0, sql_js_1.escapeIdentifier)(pk.name)} = ?`)
|
|
569
|
+
.join(' AND ');
|
|
570
|
+
const params = [
|
|
571
|
+
...setEntries.map(([, val]) => val),
|
|
572
|
+
...pkColumns.map((pk) => key[pk.name]),
|
|
573
|
+
];
|
|
574
|
+
await db.execute(`UPDATE ${quotedTable} SET ${setClause} WHERE ${whereClause};`, params);
|
|
575
|
+
return jsonResponse({ ok: true });
|
|
576
|
+
}
|
|
577
|
+
if (request.method === 'DELETE') {
|
|
578
|
+
if (pkColumns.length === 0) {
|
|
579
|
+
return errorResponse(`Table "${tableName}" has no primary key for row deletion.`, 400);
|
|
580
|
+
}
|
|
581
|
+
const key = (body.key ?? body);
|
|
582
|
+
const whereClause = pkColumns
|
|
583
|
+
.map((pk) => `${(0, sql_js_1.escapeIdentifier)(pk.name)} = ?`)
|
|
584
|
+
.join(' AND ');
|
|
585
|
+
const params = pkColumns.map((pk) => key[pk.name]);
|
|
586
|
+
await db.execute(`DELETE FROM ${quotedTable} WHERE ${whereClause};`, params);
|
|
587
|
+
return jsonResponse({ ok: true });
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
if (request.method === 'POST' && pathname === '/api/query') {
|
|
591
|
+
const body = (await request.json().catch(() => null));
|
|
592
|
+
const sql = String(body?.sql ?? '').trim();
|
|
593
|
+
if (!sql) {
|
|
594
|
+
return errorResponse('SQL query is required.', 400);
|
|
595
|
+
}
|
|
596
|
+
if (readOnly && !(0, sql_js_1.isReadQuery)(sql)) {
|
|
597
|
+
return errorResponse('Only read-only SELECT / WITH / EXPLAIN / PRAGMA queries are allowed in read-only mode.', 403);
|
|
598
|
+
}
|
|
599
|
+
const started = performance.now();
|
|
600
|
+
const rows = (await db.execute(sql, Array.isArray(body?.params) ? body.params : [])) ?? [];
|
|
601
|
+
const durationMs = Math.round((performance.now() - started) * 100) / 100;
|
|
602
|
+
const columns = rows.length > 0 && typeof rows[0] === 'object' && rows[0] !== null
|
|
603
|
+
? Object.keys(rows[0])
|
|
604
|
+
: [];
|
|
605
|
+
return reply(jsonResponse({
|
|
606
|
+
columns,
|
|
607
|
+
rows,
|
|
608
|
+
rowsAffected: 0,
|
|
609
|
+
durationMs,
|
|
610
|
+
}), sql.slice(0, 160));
|
|
611
|
+
}
|
|
612
|
+
if (request.method === 'GET' && pathname === '/api/system') {
|
|
613
|
+
const [outbox, kvStore, scheduler, actions, users, sessions, migrations] = await Promise.all([
|
|
614
|
+
readRowsIfTableExists(db, 'sync_outbox', 200),
|
|
615
|
+
readRowsIfTableExists(db, store_js_1.DEFAULT_KV_STORE_TABLE, 200),
|
|
616
|
+
readRowsIfTableExists(db, '_local_scheduler', 100),
|
|
617
|
+
readRowsIfTableExists(db, '_local_actions', 100),
|
|
618
|
+
readRowsIfTableExists(db, '_local_users', 100),
|
|
619
|
+
readRowsIfTableExists(db, '_local_sessions', 100),
|
|
620
|
+
readRowsIfTableExists(db, 'schema_migrations', 100),
|
|
621
|
+
]);
|
|
622
|
+
return jsonResponse({
|
|
623
|
+
outbox,
|
|
624
|
+
kvStore,
|
|
625
|
+
scheduler,
|
|
626
|
+
actions,
|
|
627
|
+
users,
|
|
628
|
+
sessions,
|
|
629
|
+
migrations,
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
if (request.method === 'GET' && pathname === '/api/settings') {
|
|
633
|
+
const [journalRows, syncRows, busyRows, cacheRows, fkRows, pageSizeRows, pageCountRows, freelistRows, kvRows, outboxRows, scheduledJobsRows, schedulerRows,] = await Promise.all([
|
|
634
|
+
db.execute('PRAGMA journal_mode;').catch(() => []),
|
|
635
|
+
db.execute('PRAGMA synchronous;').catch(() => []),
|
|
636
|
+
db.execute('PRAGMA busy_timeout;').catch(() => []),
|
|
637
|
+
db.execute('PRAGMA cache_size;').catch(() => []),
|
|
638
|
+
db.execute('PRAGMA foreign_keys;').catch(() => []),
|
|
639
|
+
db.execute('PRAGMA page_size;').catch(() => []),
|
|
640
|
+
db.execute('PRAGMA page_count;').catch(() => []),
|
|
641
|
+
db.execute('PRAGMA freelist_count;').catch(() => []),
|
|
642
|
+
readRowsIfTableExists(db, store_js_1.DEFAULT_KV_STORE_TABLE, 500),
|
|
643
|
+
readRowsIfTableExists(db, 'sync_outbox', 1000),
|
|
644
|
+
readRowsIfTableExists(db, '_local_scheduled_jobs', 100),
|
|
645
|
+
readRowsIfTableExists(db, '_local_scheduler', 100),
|
|
646
|
+
]);
|
|
647
|
+
const outboxList = outboxRows ?? [];
|
|
648
|
+
return jsonResponse({
|
|
649
|
+
dashboard: {
|
|
650
|
+
title,
|
|
651
|
+
readOnly,
|
|
652
|
+
authEnabled: Boolean(options.authToken),
|
|
653
|
+
basePath,
|
|
654
|
+
},
|
|
655
|
+
pragmas: {
|
|
656
|
+
journalMode: String(journalRows?.[0]?.journal_mode ?? 'unknown'),
|
|
657
|
+
synchronous: Number(syncRows?.[0]?.synchronous ?? 0),
|
|
658
|
+
busyTimeout: Number(busyRows?.[0]?.timeout ?? busyRows?.[0]?.busy_timeout ?? 0),
|
|
659
|
+
cacheSize: Number(cacheRows?.[0]?.cache_size ?? 0),
|
|
660
|
+
foreignKeys: Boolean(Number(fkRows?.[0]?.foreign_keys ?? 0)),
|
|
661
|
+
pageSize: Number(pageSizeRows?.[0]?.page_size ?? 0),
|
|
662
|
+
pageCount: Number(pageCountRows?.[0]?.page_count ?? 0),
|
|
663
|
+
freelistCount: Number(freelistRows?.[0]?.freelist_count ?? 0),
|
|
664
|
+
},
|
|
665
|
+
kvStore: {
|
|
666
|
+
exists: kvRows !== null,
|
|
667
|
+
entries: kvRows ?? [],
|
|
668
|
+
},
|
|
669
|
+
sync: {
|
|
670
|
+
outboxExists: outboxRows !== null,
|
|
671
|
+
outboxTotal: outboxList.length,
|
|
672
|
+
outboxPending: outboxList.filter((r) => r.status === 'pending' || !r.status).length,
|
|
673
|
+
outboxFailed: outboxList.filter((r) => r.status === 'failed').length,
|
|
674
|
+
schedulerJobs: scheduledJobsRows ?? schedulerRows ?? null,
|
|
675
|
+
},
|
|
676
|
+
});
|
|
677
|
+
}
|
|
678
|
+
if (request.method === 'POST' && pathname === '/api/settings/pragma') {
|
|
679
|
+
if (readOnly) {
|
|
680
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
681
|
+
}
|
|
682
|
+
const body = (await request.json().catch(() => null));
|
|
683
|
+
const pragma = String(body?.pragma ?? '');
|
|
684
|
+
const val = body?.value;
|
|
685
|
+
if (pragma === 'journal_mode') {
|
|
686
|
+
const allowed = new Set(['DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', 'OFF']);
|
|
687
|
+
const mode = String(val ?? '').toUpperCase();
|
|
688
|
+
if (!allowed.has(mode)) {
|
|
689
|
+
return errorResponse(`Unsupported journal_mode: ${mode}`, 400);
|
|
690
|
+
}
|
|
691
|
+
const rows = await db.execute(`PRAGMA journal_mode = ${mode};`);
|
|
692
|
+
return jsonResponse({ ok: true, pragma, value: rows?.[0]?.journal_mode ?? mode });
|
|
693
|
+
}
|
|
694
|
+
if (pragma === 'synchronous') {
|
|
695
|
+
const num = Number(val);
|
|
696
|
+
if (!Number.isInteger(num) || num < 0 || num > 3) {
|
|
697
|
+
return errorResponse('synchronous must be 0 (OFF), 1 (NORMAL), 2 (FULL), or 3 (EXTRA).', 400);
|
|
698
|
+
}
|
|
699
|
+
await db.execute(`PRAGMA synchronous = ${num};`);
|
|
700
|
+
return jsonResponse({ ok: true, pragma, value: num });
|
|
701
|
+
}
|
|
702
|
+
if (pragma === 'busy_timeout') {
|
|
703
|
+
const ms = Number(val);
|
|
704
|
+
if (!Number.isInteger(ms) || ms < 0 || ms > 600000) {
|
|
705
|
+
return errorResponse('busy_timeout must be an integer between 0 and 600000 ms.', 400);
|
|
706
|
+
}
|
|
707
|
+
await db.execute(`PRAGMA busy_timeout = ${ms};`);
|
|
708
|
+
return jsonResponse({ ok: true, pragma, value: ms });
|
|
709
|
+
}
|
|
710
|
+
if (pragma === 'cache_size') {
|
|
711
|
+
const size = Number(val);
|
|
712
|
+
if (!Number.isInteger(size) || size < -1048576 || size > 1048576) {
|
|
713
|
+
return errorResponse('cache_size must be an integer between -1048576 and 1048576.', 400);
|
|
714
|
+
}
|
|
715
|
+
await db.execute(`PRAGMA cache_size = ${size};`);
|
|
716
|
+
return jsonResponse({ ok: true, pragma, value: size });
|
|
717
|
+
}
|
|
718
|
+
if (pragma === 'foreign_keys') {
|
|
719
|
+
const enabled = val === true || val === 1 || val === '1' || String(val).toUpperCase() === 'ON';
|
|
720
|
+
await db.execute(`PRAGMA foreign_keys = ${enabled ? 'ON' : 'OFF'};`);
|
|
721
|
+
return jsonResponse({ ok: true, pragma, value: enabled });
|
|
722
|
+
}
|
|
723
|
+
return errorResponse(`Unsupported pragma "${pragma}".`, 400);
|
|
724
|
+
}
|
|
725
|
+
if (request.method === 'POST' && pathname === '/api/settings/maintenance') {
|
|
726
|
+
const body = (await request.json().catch(() => null));
|
|
727
|
+
const action = String(body?.action ?? '');
|
|
728
|
+
if (action === 'integrity_check') {
|
|
729
|
+
const rows = await db.execute('PRAGMA integrity_check;');
|
|
730
|
+
const result = (rows ?? []).map((r) => Object.values(r)[0]).join(', ') || 'ok';
|
|
731
|
+
return jsonResponse({ ok: true, action, message: `Integrity check: ${result}` });
|
|
732
|
+
}
|
|
733
|
+
if (readOnly) {
|
|
734
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
735
|
+
}
|
|
736
|
+
if (action === 'vacuum') {
|
|
737
|
+
await db.execute('VACUUM;');
|
|
738
|
+
return jsonResponse({ ok: true, action, message: 'VACUUM completed.' });
|
|
739
|
+
}
|
|
740
|
+
if (action === 'checkpoint') {
|
|
741
|
+
const rows = await db.execute('PRAGMA wal_checkpoint(TRUNCATE);');
|
|
742
|
+
return jsonResponse({ ok: true, action, message: 'WAL checkpoint completed.', detail: rows?.[0] ?? null });
|
|
743
|
+
}
|
|
744
|
+
if (action === 'prune_kv_expired') {
|
|
745
|
+
const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?;`, [store_js_1.DEFAULT_KV_STORE_TABLE]);
|
|
746
|
+
if (exists?.length) {
|
|
747
|
+
await store_js_1.KVStore.pruneExpired(db, store_js_1.DEFAULT_KV_STORE_TABLE);
|
|
748
|
+
}
|
|
749
|
+
return jsonResponse({ ok: true, action, message: 'Expired KV Store entries pruned.' });
|
|
750
|
+
}
|
|
751
|
+
if (action === 'prune_outbox') {
|
|
752
|
+
const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sync_outbox';`);
|
|
753
|
+
if (exists?.length) {
|
|
754
|
+
await db.execute(`DELETE FROM sync_outbox WHERE status = 'synced';`);
|
|
755
|
+
}
|
|
756
|
+
return jsonResponse({ ok: true, action, message: 'Synced outbox entries pruned.' });
|
|
757
|
+
}
|
|
758
|
+
if (action === 'clear_failed_outbox') {
|
|
759
|
+
const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'sync_outbox';`);
|
|
760
|
+
if (exists?.length) {
|
|
761
|
+
await db.execute(`DELETE FROM sync_outbox WHERE status = 'failed';`);
|
|
762
|
+
}
|
|
763
|
+
return jsonResponse({ ok: true, action, message: 'Failed outbox mutations cleared.' });
|
|
764
|
+
}
|
|
765
|
+
return errorResponse(`Unsupported maintenance action "${action}".`, 400);
|
|
766
|
+
}
|
|
767
|
+
if (request.method === 'GET' && pathname === '/api/settings/export') {
|
|
768
|
+
const includeInternal = url.searchParams.get('includeInternal') === '1';
|
|
769
|
+
const tables = await listTables(db);
|
|
770
|
+
const selected = includeInternal ? tables : tables.filter((t) => !t.internal);
|
|
771
|
+
const data = {};
|
|
772
|
+
for (const t of selected) {
|
|
773
|
+
data[t.name] =
|
|
774
|
+
(await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(t.name)} LIMIT 50000;`)) ?? [];
|
|
775
|
+
}
|
|
776
|
+
return new Response(JSON.stringify({ exportedAt: new Date().toISOString(), tables: data }, null, 2), {
|
|
777
|
+
status: 200,
|
|
778
|
+
headers: {
|
|
779
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
780
|
+
'Content-Disposition': 'attachment; filename="local-lite-export.json"',
|
|
781
|
+
},
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
if (pathname === '/api/kv-store') {
|
|
785
|
+
if (readOnly) {
|
|
786
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
787
|
+
}
|
|
788
|
+
const body = (await request.json().catch(() => null));
|
|
789
|
+
if (request.method === 'POST') {
|
|
790
|
+
const key = String(body?.key ?? '').trim();
|
|
791
|
+
if (!key) {
|
|
792
|
+
return errorResponse('Key is required.', 400);
|
|
793
|
+
}
|
|
794
|
+
await store_js_1.KVStore.ensureSchema(db, store_js_1.DEFAULT_KV_STORE_TABLE);
|
|
795
|
+
const type = ['string', 'number', 'boolean', 'json'].includes(String(body?.type))
|
|
796
|
+
? String(body?.type)
|
|
797
|
+
: 'string';
|
|
798
|
+
let valueStr;
|
|
799
|
+
if (type === 'number') {
|
|
800
|
+
const n = Number(body?.value);
|
|
801
|
+
if (Number.isNaN(n))
|
|
802
|
+
return errorResponse('Invalid number value.', 400);
|
|
803
|
+
valueStr = String(n);
|
|
804
|
+
}
|
|
805
|
+
else if (type === 'boolean') {
|
|
806
|
+
const b = body?.value === true || body?.value === 'true' || body?.value === '1' || body?.value === 1;
|
|
807
|
+
valueStr = b ? '1' : '0';
|
|
808
|
+
}
|
|
809
|
+
else if (type === 'json') {
|
|
810
|
+
try {
|
|
811
|
+
const parsed = typeof body?.value === 'string' ? JSON.parse(body.value) : body?.value;
|
|
812
|
+
valueStr = JSON.stringify(parsed ?? null);
|
|
813
|
+
}
|
|
814
|
+
catch {
|
|
815
|
+
return errorResponse('Invalid JSON value.', 400);
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
else {
|
|
819
|
+
valueStr = String(body?.value ?? '');
|
|
820
|
+
}
|
|
821
|
+
const now = Date.now();
|
|
822
|
+
const expiresAt = body?.ttlMs != null && Number(body.ttlMs) > 0 ? now + Number(body.ttlMs) : null;
|
|
823
|
+
await store_js_1.KVStore.set(db, store_js_1.DEFAULT_KV_STORE_TABLE, key, valueStr, type, now, expiresAt);
|
|
824
|
+
return jsonResponse({ ok: true });
|
|
825
|
+
}
|
|
826
|
+
if (request.method === 'DELETE') {
|
|
827
|
+
const key = String(body?.key ?? '').trim();
|
|
828
|
+
if (!key) {
|
|
829
|
+
return errorResponse('Key is required.', 400);
|
|
830
|
+
}
|
|
831
|
+
await store_js_1.KVStore.ensureSchema(db, store_js_1.DEFAULT_KV_STORE_TABLE);
|
|
832
|
+
await store_js_1.KVStore.delete(db, store_js_1.DEFAULT_KV_STORE_TABLE, key);
|
|
833
|
+
return jsonResponse({ ok: true });
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
if (request.method === 'GET' && pathname === '/api/files') {
|
|
837
|
+
const blobs = await readRowsIfTableExists(db, '_local_blobs', 500);
|
|
838
|
+
return jsonResponse({ exists: blobs !== null, files: blobs ?? [] });
|
|
839
|
+
}
|
|
840
|
+
const fileDeleteMatch = pathname.match(/^\/api\/files\/([^/]+)$/);
|
|
841
|
+
if (fileDeleteMatch && request.method === 'DELETE') {
|
|
842
|
+
if (readOnly) {
|
|
843
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
844
|
+
}
|
|
845
|
+
const fileId = decodeURIComponent(fileDeleteMatch[1]);
|
|
846
|
+
const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_local_blobs';`);
|
|
847
|
+
if (exists?.length) {
|
|
848
|
+
await db.execute(`DELETE FROM _local_blobs WHERE id = ?;`, [fileId]);
|
|
849
|
+
}
|
|
850
|
+
return jsonResponse({ ok: true });
|
|
851
|
+
}
|
|
852
|
+
if (pathname === '/api/auth-admin') {
|
|
853
|
+
if (request.method === 'GET') {
|
|
854
|
+
const [users, sessions, apiKeys] = await Promise.all([
|
|
855
|
+
readRowsIfTableExists(db, '_local_users', 500),
|
|
856
|
+
readRowsIfTableExists(db, '_local_sessions', 500),
|
|
857
|
+
readRowsIfTableExists(db, '_local_api_keys', 500),
|
|
858
|
+
]);
|
|
859
|
+
return jsonResponse({ users, sessions, apiKeys });
|
|
860
|
+
}
|
|
861
|
+
if (request.method === 'POST') {
|
|
862
|
+
if (readOnly) {
|
|
863
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
864
|
+
}
|
|
865
|
+
const body = (await request.json().catch(() => null));
|
|
866
|
+
const action = String(body?.action ?? '');
|
|
867
|
+
const id = String(body?.id ?? '');
|
|
868
|
+
if (!id)
|
|
869
|
+
return errorResponse('id is required.', 400);
|
|
870
|
+
if (action === 'revoke_session') {
|
|
871
|
+
await db.execute(`DELETE FROM _local_sessions WHERE id = ?;`, [id]);
|
|
872
|
+
return jsonResponse({ ok: true });
|
|
873
|
+
}
|
|
874
|
+
if (action === 'unlock_user') {
|
|
875
|
+
await db.execute(`UPDATE _local_users SET failed_attempts = 0, locked_until = NULL WHERE id = ?;`, [id]);
|
|
876
|
+
return jsonResponse({ ok: true });
|
|
877
|
+
}
|
|
878
|
+
if (action === 'revoke_api_key') {
|
|
879
|
+
await db.execute(`UPDATE _local_api_keys SET revoked_at = ? WHERE id = ?;`, [Date.now(), id]).catch(async () => {
|
|
880
|
+
await db.execute(`DELETE FROM _local_api_keys WHERE id = ?;`, [id]);
|
|
881
|
+
});
|
|
882
|
+
return jsonResponse({ ok: true });
|
|
883
|
+
}
|
|
884
|
+
return errorResponse(`Unsupported auth action "${action}".`, 400);
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
if (pathname === '/api/jobs') {
|
|
888
|
+
if (request.method === 'GET') {
|
|
889
|
+
const [actions, scheduledJobs, jobRuns, outbox] = await Promise.all([
|
|
890
|
+
readRowsIfTableExists(db, '_local_actions', 500),
|
|
891
|
+
readRowsIfTableExists(db, '_local_scheduled_jobs', 200),
|
|
892
|
+
readRowsIfTableExists(db, '_local_job_runs', 200),
|
|
893
|
+
readRowsIfTableExists(db, 'sync_outbox', 500),
|
|
894
|
+
]);
|
|
895
|
+
return jsonResponse({ actions, scheduledJobs, jobRuns, outbox });
|
|
896
|
+
}
|
|
897
|
+
if (request.method === 'POST') {
|
|
898
|
+
if (readOnly) {
|
|
899
|
+
return errorResponse('Dashboard is running in read-only mode.', 403);
|
|
900
|
+
}
|
|
901
|
+
const body = (await request.json().catch(() => null));
|
|
902
|
+
const action = String(body?.action ?? '');
|
|
903
|
+
const id = String(body?.id ?? '');
|
|
904
|
+
if (action === 'retry_action' && id) {
|
|
905
|
+
await db.execute(`UPDATE _local_actions SET status = 'pending', attempts = 0, last_error = NULL WHERE id = ?;`, [id]);
|
|
906
|
+
return jsonResponse({ ok: true });
|
|
907
|
+
}
|
|
908
|
+
if (action === 'delete_action' && id) {
|
|
909
|
+
await db.execute(`DELETE FROM _local_actions WHERE id = ?;`, [id]);
|
|
910
|
+
return jsonResponse({ ok: true });
|
|
911
|
+
}
|
|
912
|
+
if (action === 'clear_completed_actions') {
|
|
913
|
+
const exists = await db.execute(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '_local_actions';`);
|
|
914
|
+
if (exists?.length) {
|
|
915
|
+
await db.execute(`DELETE FROM _local_actions WHERE status = 'completed';`);
|
|
916
|
+
}
|
|
917
|
+
return jsonResponse({ ok: true });
|
|
918
|
+
}
|
|
919
|
+
if (action === 'retry_outbox' && id) {
|
|
920
|
+
await db.execute(`UPDATE sync_outbox SET status = 'pending', retry_count = 0, last_error = NULL WHERE id = ?;`, [id]);
|
|
921
|
+
return jsonResponse({ ok: true });
|
|
922
|
+
}
|
|
923
|
+
if (action === 'delete_outbox' && id) {
|
|
924
|
+
await db.execute(`DELETE FROM sync_outbox WHERE id = ?;`, [id]);
|
|
925
|
+
return jsonResponse({ ok: true });
|
|
926
|
+
}
|
|
927
|
+
if (action === 'toggle_job' && id) {
|
|
928
|
+
await db.execute(`UPDATE _local_scheduled_jobs SET enabled = ? WHERE id = ?;`, [body?.enabled ? 1 : 0, id]);
|
|
929
|
+
return jsonResponse({ ok: true });
|
|
930
|
+
}
|
|
931
|
+
if (action === 'delete_job' && id) {
|
|
932
|
+
await db.execute(`DELETE FROM _local_scheduled_jobs WHERE id = ?;`, [id]);
|
|
933
|
+
return jsonResponse({ ok: true });
|
|
934
|
+
}
|
|
935
|
+
return errorResponse(`Unsupported job action "${action}".`, 400);
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
// ── Live Logs & Query Telemetry ────────────────────────────────────
|
|
939
|
+
if (pathname === '/api/logs') {
|
|
940
|
+
if (request.method === 'GET') {
|
|
941
|
+
const level = url.searchParams.get('level')?.trim() || '';
|
|
942
|
+
const search = url.searchParams.get('q')?.trim().toLowerCase() || '';
|
|
943
|
+
const filtered = logs.filter((entry) => {
|
|
944
|
+
if (level === 'error' && entry.status < 400)
|
|
945
|
+
return false;
|
|
946
|
+
if (level === 'ok' && entry.status >= 400)
|
|
947
|
+
return false;
|
|
948
|
+
if (search) {
|
|
949
|
+
const hay = `${entry.method} ${entry.path} ${entry.detail ?? ''}`.toLowerCase();
|
|
950
|
+
if (!hay.includes(search))
|
|
951
|
+
return false;
|
|
952
|
+
}
|
|
953
|
+
return true;
|
|
954
|
+
});
|
|
955
|
+
return jsonResponse({ logs: filtered });
|
|
956
|
+
}
|
|
957
|
+
if (request.method === 'DELETE') {
|
|
958
|
+
logs.length = 0;
|
|
959
|
+
return jsonResponse({ ok: true });
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
// ── Sample Row Seeder ──────────────────────────────────────────────
|
|
963
|
+
const seedMatch = pathname.match(/^\/api\/tables\/([^/]+)\/seed$/);
|
|
964
|
+
if (seedMatch && request.method === 'POST') {
|
|
965
|
+
if (readOnly)
|
|
966
|
+
return reply(errorResponse('Dashboard is in read-only mode.', 403));
|
|
967
|
+
const tableName = decodeURIComponent(seedMatch[1]);
|
|
968
|
+
const quoted = (0, sql_js_1.escapeIdentifier)(tableName);
|
|
969
|
+
const colRows = (await db.execute(`PRAGMA table_info(${quoted});`)) ?? [];
|
|
970
|
+
if (colRows.length === 0) {
|
|
971
|
+
return reply(errorResponse(`Table "${tableName}" not found.`, 404));
|
|
972
|
+
}
|
|
973
|
+
const body = (await request.json().catch(() => null));
|
|
974
|
+
const count = Math.min(100, Math.max(1, Number(body?.count ?? 10) || 10));
|
|
975
|
+
const cols = colRows.map((r) => ({
|
|
976
|
+
name: String(r.name),
|
|
977
|
+
type: String(r.type ?? 'TEXT').toUpperCase(),
|
|
978
|
+
notnull: Boolean(r.notnull),
|
|
979
|
+
pk: Number(r.pk) > 0,
|
|
980
|
+
}));
|
|
981
|
+
const fkRows = (await db.execute(`PRAGMA foreign_key_list(${quoted});`)) ?? [];
|
|
982
|
+
const fkValues = new Map();
|
|
983
|
+
for (const fk of fkRows) {
|
|
984
|
+
const fromCol = String(fk.from ?? '');
|
|
985
|
+
const refTable = String(fk.table ?? '');
|
|
986
|
+
const refCol = String(fk.to ?? '');
|
|
987
|
+
if (!fromCol || !refTable || !refCol)
|
|
988
|
+
continue;
|
|
989
|
+
try {
|
|
990
|
+
const refRows = (await db.execute(`SELECT ${(0, sql_js_1.escapeIdentifier)(refCol)} AS val FROM ${(0, sql_js_1.escapeIdentifier)(refTable)} LIMIT 20;`)) ?? [];
|
|
991
|
+
fkValues.set(fromCol.toLowerCase(), refRows.map((r) => r.val));
|
|
992
|
+
}
|
|
993
|
+
catch {
|
|
994
|
+
// ignore
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
const now = Date.now();
|
|
998
|
+
let inserted = 0;
|
|
999
|
+
for (let i = 0; i < count; i++) {
|
|
1000
|
+
const insertCols = [];
|
|
1001
|
+
const placeholders = [];
|
|
1002
|
+
const params = [];
|
|
1003
|
+
for (const col of cols) {
|
|
1004
|
+
const lower = col.name.toLowerCase();
|
|
1005
|
+
if (col.pk && col.type.includes('INT')) {
|
|
1006
|
+
continue;
|
|
1007
|
+
}
|
|
1008
|
+
insertCols.push((0, sql_js_1.escapeIdentifier)(col.name));
|
|
1009
|
+
placeholders.push('?');
|
|
1010
|
+
const n = i + 1;
|
|
1011
|
+
const suffix = `${now.toString(36)}_${n}`;
|
|
1012
|
+
const fkCandidates = fkValues.get(lower);
|
|
1013
|
+
if (fkCandidates !== undefined) {
|
|
1014
|
+
params.push(fkCandidates.length > 0
|
|
1015
|
+
? fkCandidates[i % fkCandidates.length]
|
|
1016
|
+
: col.notnull
|
|
1017
|
+
? `${tableName.slice(0, 4)}_${suffix}`
|
|
1018
|
+
: null);
|
|
1019
|
+
}
|
|
1020
|
+
else if (col.pk || lower === 'id' || lower.endsWith('_id')) {
|
|
1021
|
+
params.push(`${tableName.slice(0, 4)}_${suffix}`);
|
|
1022
|
+
}
|
|
1023
|
+
else if (lower.includes('email')) {
|
|
1024
|
+
params.push(`user${n}_${now.toString(36)}@example.com`);
|
|
1025
|
+
}
|
|
1026
|
+
else if (lower.includes('name') || lower.includes('title')) {
|
|
1027
|
+
params.push(`Sample ${col.name} ${n}`);
|
|
1028
|
+
}
|
|
1029
|
+
else if (lower.includes('created') || lower.includes('updated') || lower.includes('date') || lower.includes('time')) {
|
|
1030
|
+
params.push(col.type.includes('INT') ? now + i : new Date(now + i * 1000).toISOString());
|
|
1031
|
+
}
|
|
1032
|
+
else if (lower.includes('active') || lower.includes('enabled') || lower.startsWith('is_') || col.type.includes('BOOL')) {
|
|
1033
|
+
params.push(i % 2 === 0 ? 1 : 0);
|
|
1034
|
+
}
|
|
1035
|
+
else if (col.type.includes('INT')) {
|
|
1036
|
+
params.push(n * 10);
|
|
1037
|
+
}
|
|
1038
|
+
else if (col.type.includes('REAL') || col.type.includes('FLOAT') || col.type.includes('NUM') || col.type.includes('DEC')) {
|
|
1039
|
+
params.push(Number((n * 12.5).toFixed(2)));
|
|
1040
|
+
}
|
|
1041
|
+
else {
|
|
1042
|
+
params.push(`${col.name}_${n}`);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
if (insertCols.length === 0) {
|
|
1046
|
+
await db.execute(`INSERT INTO ${quoted} DEFAULT VALUES;`);
|
|
1047
|
+
}
|
|
1048
|
+
else {
|
|
1049
|
+
await db.execute(`INSERT INTO ${quoted} (${insertCols.join(', ')}) VALUES (${placeholders.join(', ')});`, params);
|
|
1050
|
+
}
|
|
1051
|
+
inserted++;
|
|
1052
|
+
}
|
|
1053
|
+
return reply(jsonResponse({ ok: true, inserted }), `Seeded ${inserted} rows into ${tableName}`);
|
|
1054
|
+
}
|
|
1055
|
+
// ── Migration & Schema Diff Generator ──────────────────────────────
|
|
1056
|
+
if (pathname === '/api/schema/diff' && request.method === 'POST') {
|
|
1057
|
+
const body = (await request.json().catch(() => null));
|
|
1058
|
+
const targetSql = typeof body?.targetSql === 'string' ? body.targetSql : '';
|
|
1059
|
+
const targetTablesInput = Array.isArray(body?.tables) ? body.tables : null;
|
|
1060
|
+
const liveTables = (await listTables(db)).filter((t) => !(0, sql_js_1.isInternalTable)(t.name));
|
|
1061
|
+
const parseTargetSql = (sqlText) => {
|
|
1062
|
+
const parsed = [];
|
|
1063
|
+
const regex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`[]?([A-Za-z_][A-Za-z0-9_]*)["`\]]?\s*\(([\s\S]*?)\)\s*;/gi;
|
|
1064
|
+
let match;
|
|
1065
|
+
while ((match = regex.exec(sqlText)) !== null) {
|
|
1066
|
+
const tName = match[1];
|
|
1067
|
+
const bodyStr = match[2];
|
|
1068
|
+
const cols = [];
|
|
1069
|
+
for (const rawLine of bodyStr.split(',')) {
|
|
1070
|
+
const line = rawLine.trim();
|
|
1071
|
+
if (!line || /^(PRIMARY\s+KEY|FOREIGN\s+KEY|UNIQUE|CHECK|CONSTRAINT)\b/i.test(line))
|
|
1072
|
+
continue;
|
|
1073
|
+
const colMatch = line.match(/^["`[]?([A-Za-z_][A-Za-z0-9_]*)["`\]]?\s+([A-Za-z0-9_()]+)?([\s\S]*)$/i);
|
|
1074
|
+
if (!colMatch)
|
|
1075
|
+
continue;
|
|
1076
|
+
const colName = colMatch[1];
|
|
1077
|
+
const colType = (colMatch[2] || 'TEXT').toUpperCase();
|
|
1078
|
+
const rest = (colMatch[3] || '').toUpperCase();
|
|
1079
|
+
cols.push({
|
|
1080
|
+
name: colName,
|
|
1081
|
+
type: colType,
|
|
1082
|
+
notnull: rest.includes('NOT NULL'),
|
|
1083
|
+
pk: rest.includes('PRIMARY KEY'),
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
parsed.push({ name: tName, columns: cols });
|
|
1087
|
+
}
|
|
1088
|
+
return parsed;
|
|
1089
|
+
};
|
|
1090
|
+
const targetTables = targetTablesInput
|
|
1091
|
+
? targetTablesInput
|
|
1092
|
+
: targetSql.trim()
|
|
1093
|
+
? parseTargetSql(targetSql)
|
|
1094
|
+
: [];
|
|
1095
|
+
const statements = [];
|
|
1096
|
+
const summary = [];
|
|
1097
|
+
if (targetTables.length === 0) {
|
|
1098
|
+
for (const t of liveTables) {
|
|
1099
|
+
const colDefs = t.columns.map((c) => {
|
|
1100
|
+
const parts = [(0, sql_js_1.escapeIdentifier)(c.name), c.type || 'TEXT'];
|
|
1101
|
+
if (c.pk)
|
|
1102
|
+
parts.push('PRIMARY KEY');
|
|
1103
|
+
if (c.notnull && !c.pk)
|
|
1104
|
+
parts.push('NOT NULL');
|
|
1105
|
+
if (c.dflt_value !== null && c.dflt_value !== undefined)
|
|
1106
|
+
parts.push(`DEFAULT ${c.dflt_value}`);
|
|
1107
|
+
return ` ${parts.join(' ')}`;
|
|
1108
|
+
});
|
|
1109
|
+
statements.push(`CREATE TABLE IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(t.name)} (\n${colDefs.join(',\n')}\n);`);
|
|
1110
|
+
summary.push({ type: 'baseline', table: t.name, detail: `${t.columns.length} columns` });
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
else {
|
|
1114
|
+
const liveMap = new Map(liveTables.map((t) => [t.name.toLowerCase(), t]));
|
|
1115
|
+
const targetMap = new Map(targetTables.map((t) => [t.name.toLowerCase(), t]));
|
|
1116
|
+
for (const target of targetTables) {
|
|
1117
|
+
const live = liveMap.get(target.name.toLowerCase());
|
|
1118
|
+
if (!live) {
|
|
1119
|
+
const colDefs = target.columns.map((c) => {
|
|
1120
|
+
const parts = [(0, sql_js_1.escapeIdentifier)(c.name), c.type || 'TEXT'];
|
|
1121
|
+
if (c.pk)
|
|
1122
|
+
parts.push('PRIMARY KEY');
|
|
1123
|
+
if (c.notnull && !c.pk)
|
|
1124
|
+
parts.push('NOT NULL');
|
|
1125
|
+
if (c.dflt_value !== null && c.dflt_value !== undefined)
|
|
1126
|
+
parts.push(`DEFAULT ${c.dflt_value}`);
|
|
1127
|
+
return ` ${parts.join(' ')}`;
|
|
1128
|
+
});
|
|
1129
|
+
statements.push(`CREATE TABLE IF NOT EXISTS ${(0, sql_js_1.escapeIdentifier)(target.name)} (\n${colDefs.join(',\n')}\n);`);
|
|
1130
|
+
summary.push({ type: 'create_table', table: target.name, detail: `New table (${target.columns.length} columns)` });
|
|
1131
|
+
}
|
|
1132
|
+
else {
|
|
1133
|
+
const liveCols = new Set(live.columns.map((c) => c.name.toLowerCase()));
|
|
1134
|
+
for (const tc of target.columns) {
|
|
1135
|
+
if (!liveCols.has(tc.name.toLowerCase())) {
|
|
1136
|
+
const def = `${(0, sql_js_1.escapeIdentifier)(tc.name)} ${tc.type || 'TEXT'}${tc.notnull ? " NOT NULL DEFAULT ''" : ''}`;
|
|
1137
|
+
statements.push(`ALTER TABLE ${(0, sql_js_1.escapeIdentifier)(target.name)} ADD COLUMN ${def};`);
|
|
1138
|
+
summary.push({ type: 'add_column', table: target.name, detail: `Add column ${tc.name} (${tc.type || 'TEXT'})` });
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
for (const live of liveTables) {
|
|
1144
|
+
if (!targetMap.has(live.name.toLowerCase())) {
|
|
1145
|
+
statements.push(`-- Table "${live.name}" exists in DB but not in target schema`);
|
|
1146
|
+
statements.push(`-- DROP TABLE IF EXISTS ${(0, sql_js_1.escapeIdentifier)(live.name)};`);
|
|
1147
|
+
summary.push({ type: 'extra_table', table: live.name, detail: 'Exists in DB only (commented DROP)' });
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
1151
|
+
return reply(jsonResponse({
|
|
1152
|
+
sql: statements.join('\n\n'),
|
|
1153
|
+
changes: summary,
|
|
1154
|
+
}));
|
|
1155
|
+
}
|
|
1156
|
+
// ── FTS5 Full-Text Search Explorer ─────────────────────────────────
|
|
1157
|
+
if (pathname === '/api/search/indexes' && request.method === 'GET') {
|
|
1158
|
+
const ftsRows = (await db.execute(`SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name LIKE '_fts_%' AND sql LIKE 'CREATE VIRTUAL TABLE%' ORDER BY name;`)) ?? [];
|
|
1159
|
+
const indexes = [];
|
|
1160
|
+
for (const row of ftsRows) {
|
|
1161
|
+
const ftsName = String(row.name);
|
|
1162
|
+
const sourceTable = ftsName.replace(/^_fts_/, '');
|
|
1163
|
+
let count = 0;
|
|
1164
|
+
try {
|
|
1165
|
+
const cnt = (await db.execute(`SELECT COUNT(*) AS count FROM ${(0, sql_js_1.escapeIdentifier)(ftsName)};`)) ?? [];
|
|
1166
|
+
count = Number(cnt[0]?.count ?? 0);
|
|
1167
|
+
}
|
|
1168
|
+
catch {
|
|
1169
|
+
// ignore
|
|
1170
|
+
}
|
|
1171
|
+
indexes.push({
|
|
1172
|
+
ftsTable: ftsName,
|
|
1173
|
+
sourceTable,
|
|
1174
|
+
rowCount: count,
|
|
1175
|
+
sql: row.sql ? String(row.sql) : null,
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
return reply(jsonResponse({ indexes }));
|
|
1179
|
+
}
|
|
1180
|
+
if (pathname === '/api/search/index' && request.method === 'POST') {
|
|
1181
|
+
if (readOnly)
|
|
1182
|
+
return reply(errorResponse('Dashboard is in read-only mode.', 403));
|
|
1183
|
+
const body = (await request.json().catch(() => null));
|
|
1184
|
+
const tableName = typeof body?.table === 'string' ? body.table.trim() : '';
|
|
1185
|
+
if (!tableName)
|
|
1186
|
+
return reply(errorResponse('Table name is required.', 400));
|
|
1187
|
+
const quotedSource = (0, sql_js_1.escapeIdentifier)(tableName);
|
|
1188
|
+
const info = (await db.execute(`PRAGMA table_info(${quotedSource});`)) ?? [];
|
|
1189
|
+
if (info.length === 0)
|
|
1190
|
+
return reply(errorResponse(`Table "${tableName}" not found.`, 404));
|
|
1191
|
+
const requestedCols = Array.isArray(body?.columns)
|
|
1192
|
+
? body.columns.map(String).filter(Boolean)
|
|
1193
|
+
: info
|
|
1194
|
+
.filter((r) => !String(r.type ?? '').toUpperCase().includes('BLOB'))
|
|
1195
|
+
.map((r) => String(r.name));
|
|
1196
|
+
if (requestedCols.length === 0) {
|
|
1197
|
+
return reply(errorResponse('No searchable columns found.', 400));
|
|
1198
|
+
}
|
|
1199
|
+
const ftsName = `_fts_${tableName}`;
|
|
1200
|
+
const quotedFts = (0, sql_js_1.escapeIdentifier)(ftsName);
|
|
1201
|
+
const colList = requestedCols.map((c) => (0, sql_js_1.escapeIdentifier)(c)).join(', ');
|
|
1202
|
+
const newColList = requestedCols.map((c) => `new.${(0, sql_js_1.escapeIdentifier)(c)}`).join(', ');
|
|
1203
|
+
await db.execute(`DROP TABLE IF EXISTS ${quotedFts};`);
|
|
1204
|
+
await db.execute(`CREATE VIRTUAL TABLE ${quotedFts} USING fts5(${colList});`);
|
|
1205
|
+
await db.execute(`INSERT INTO ${quotedFts}(rowid, ${colList}) SELECT rowid, ${colList} FROM ${quotedSource};`);
|
|
1206
|
+
const aiTrig = (0, sql_js_1.escapeIdentifier)(`_fts_${tableName}_ai`);
|
|
1207
|
+
const auTrig = (0, sql_js_1.escapeIdentifier)(`_fts_${tableName}_au`);
|
|
1208
|
+
const adTrig = (0, sql_js_1.escapeIdentifier)(`_fts_${tableName}_ad`);
|
|
1209
|
+
await db.execute(`DROP TRIGGER IF EXISTS ${aiTrig};`);
|
|
1210
|
+
await db.execute(`DROP TRIGGER IF EXISTS ${auTrig};`);
|
|
1211
|
+
await db.execute(`DROP TRIGGER IF EXISTS ${adTrig};`);
|
|
1212
|
+
await db.execute(`CREATE TRIGGER ${aiTrig} AFTER INSERT ON ${quotedSource} BEGIN
|
|
1213
|
+
INSERT INTO ${quotedFts}(rowid, ${colList}) VALUES (new.rowid, ${newColList});
|
|
1214
|
+
END;`);
|
|
1215
|
+
await db.execute(`CREATE TRIGGER ${adTrig} AFTER DELETE ON ${quotedSource} BEGIN
|
|
1216
|
+
DELETE FROM ${quotedFts} WHERE rowid = old.rowid;
|
|
1217
|
+
END;`);
|
|
1218
|
+
await db.execute(`CREATE TRIGGER ${auTrig} AFTER UPDATE ON ${quotedSource} BEGIN
|
|
1219
|
+
DELETE FROM ${quotedFts} WHERE rowid = old.rowid;
|
|
1220
|
+
INSERT INTO ${quotedFts}(rowid, ${colList}) VALUES (new.rowid, ${newColList});
|
|
1221
|
+
END;`);
|
|
1222
|
+
const cnt = (await db.execute(`SELECT COUNT(*) AS count FROM ${quotedFts};`)) ?? [];
|
|
1223
|
+
return reply(jsonResponse({
|
|
1224
|
+
ok: true,
|
|
1225
|
+
ftsTable: ftsName,
|
|
1226
|
+
sourceTable: tableName,
|
|
1227
|
+
columns: requestedCols,
|
|
1228
|
+
rowCount: Number(cnt[0]?.count ?? 0),
|
|
1229
|
+
}, 201), `Indexed ${tableName} into ${ftsName}`);
|
|
1230
|
+
}
|
|
1231
|
+
if (pathname === '/api/search' && request.method === 'GET') {
|
|
1232
|
+
const tableName = url.searchParams.get('table')?.trim() || '';
|
|
1233
|
+
const q = url.searchParams.get('q')?.trim() || '';
|
|
1234
|
+
const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit') ?? 25) || 25));
|
|
1235
|
+
if (!tableName)
|
|
1236
|
+
return reply(errorResponse('Query parameter "table" is required.', 400));
|
|
1237
|
+
const ftsName = tableName.startsWith('_fts_') ? tableName : `_fts_${tableName}`;
|
|
1238
|
+
const quotedFts = (0, sql_js_1.escapeIdentifier)(ftsName);
|
|
1239
|
+
if (!q) {
|
|
1240
|
+
const rows = (await db.execute(`SELECT rowid, * FROM ${quotedFts} LIMIT ?;`, [limit])) ?? [];
|
|
1241
|
+
const columns = rows.length > 0 ? Object.keys(rows[0]) : [];
|
|
1242
|
+
return reply(jsonResponse({ rows, columns }));
|
|
1243
|
+
}
|
|
1244
|
+
const safeQuery = q.includes('"') ? q : `"${q.replace(/"/g, '""')}"*`;
|
|
1245
|
+
const info = (await db.execute(`PRAGMA table_info(${quotedFts});`)) ?? [];
|
|
1246
|
+
const snippetExpr = info.length > 0
|
|
1247
|
+
? `snippet(${quotedFts}, 0, '<mark>', '</mark>', '...', 24) AS _snippet,`
|
|
1248
|
+
: '';
|
|
1249
|
+
const rows = (await db.execute(`SELECT rowid, bm25(${quotedFts}) AS _rank, ${snippetExpr} * FROM ${quotedFts} WHERE ${quotedFts} MATCH ? ORDER BY _rank LIMIT ?;`, [safeQuery, limit])) ?? [];
|
|
1250
|
+
const columns = rows.length > 0 ? Object.keys(rows[0]) : [];
|
|
1251
|
+
return reply(jsonResponse({ rows, columns }), `FTS5 "${q}" on ${ftsName}`);
|
|
1252
|
+
}
|
|
1253
|
+
// ── Encrypted Backup & Restore ─────────────────────────────────────
|
|
1254
|
+
if (pathname === '/api/backups/export' && request.method === 'POST') {
|
|
1255
|
+
const body = (await request.json().catch(() => null));
|
|
1256
|
+
const passphrase = typeof body?.passphrase === 'string' ? body.passphrase : '';
|
|
1257
|
+
if (passphrase.length < 4) {
|
|
1258
|
+
return reply(errorResponse('Passphrase must be at least 4 characters.', 400));
|
|
1259
|
+
}
|
|
1260
|
+
const allTables = (await listTables(db)).filter((t) => !t.name.startsWith('_fts_') && !t.name.startsWith('sqlite_'));
|
|
1261
|
+
const tablesData = {};
|
|
1262
|
+
for (const t of allTables) {
|
|
1263
|
+
const dataRows = (await db.execute(`SELECT * FROM ${(0, sql_js_1.escapeIdentifier)(t.name)};`)) ?? [];
|
|
1264
|
+
const sqlRow = (await db.execute(`SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?;`, [t.name])) ?? [];
|
|
1265
|
+
tablesData[t.name] = {
|
|
1266
|
+
sql: sqlRow[0]?.sql ? String(sqlRow[0].sql) : null,
|
|
1267
|
+
rows: dataRows,
|
|
1268
|
+
};
|
|
1269
|
+
}
|
|
1270
|
+
const payload = JSON.stringify({
|
|
1271
|
+
version: 1,
|
|
1272
|
+
exportedAt: new Date().toISOString(),
|
|
1273
|
+
tables: tablesData,
|
|
1274
|
+
});
|
|
1275
|
+
const encrypted = await (0, encryption_js_1.encryptBackupData)(new TextEncoder().encode(payload), passphrase);
|
|
1276
|
+
return reply(jsonResponse({
|
|
1277
|
+
filename: `local-lite-backup-${new Date().toISOString().slice(0, 10)}.localbackup`,
|
|
1278
|
+
sizeBytes: encrypted.byteLength,
|
|
1279
|
+
tableCount: Object.keys(tablesData).length,
|
|
1280
|
+
dataBase64: Buffer.from(encrypted).toString('base64'),
|
|
1281
|
+
}), `Exported ${Object.keys(tablesData).length} tables`);
|
|
1282
|
+
}
|
|
1283
|
+
if (pathname === '/api/backups/restore' && request.method === 'POST') {
|
|
1284
|
+
if (readOnly)
|
|
1285
|
+
return reply(errorResponse('Dashboard is in read-only mode.', 403));
|
|
1286
|
+
const body = (await request.json().catch(() => null));
|
|
1287
|
+
const passphrase = typeof body?.passphrase === 'string' ? body.passphrase : '';
|
|
1288
|
+
const dataBase64 = typeof body?.dataBase64 === 'string' ? body.dataBase64 : '';
|
|
1289
|
+
if (!passphrase || !dataBase64) {
|
|
1290
|
+
return reply(errorResponse('Passphrase and backup data are required.', 400));
|
|
1291
|
+
}
|
|
1292
|
+
const encryptedBytes = new Uint8Array(Buffer.from(dataBase64, 'base64'));
|
|
1293
|
+
let decryptedBytes;
|
|
1294
|
+
try {
|
|
1295
|
+
decryptedBytes = await (0, encryption_js_1.decryptBackupData)(encryptedBytes, passphrase);
|
|
1296
|
+
}
|
|
1297
|
+
catch {
|
|
1298
|
+
return reply(errorResponse('Failed to decrypt backup. Check passphrase or file integrity.', 400));
|
|
1299
|
+
}
|
|
1300
|
+
const snapshot = JSON.parse(new TextDecoder().decode(decryptedBytes));
|
|
1301
|
+
if (!snapshot?.tables || typeof snapshot.tables !== 'object') {
|
|
1302
|
+
return reply(errorResponse('Invalid backup payload.', 400));
|
|
1303
|
+
}
|
|
1304
|
+
let restoredTables = 0;
|
|
1305
|
+
let restoredRows = 0;
|
|
1306
|
+
const fkRes = (await db.execute(`PRAGMA foreign_keys;`)) ?? [];
|
|
1307
|
+
const prevFk = Number(fkRes[0]?.foreign_keys ?? 0) === 1;
|
|
1308
|
+
if (prevFk) {
|
|
1309
|
+
await db.execute(`PRAGMA foreign_keys = OFF;`);
|
|
1310
|
+
}
|
|
1311
|
+
await db.execute(`BEGIN IMMEDIATE;`);
|
|
1312
|
+
try {
|
|
1313
|
+
for (const [tableName, tableEntry] of Object.entries(snapshot.tables)) {
|
|
1314
|
+
if (tableEntry.sql) {
|
|
1315
|
+
const createSql = tableEntry.sql.replace(/^CREATE\s+TABLE\s+/i, 'CREATE TABLE IF NOT EXISTS ');
|
|
1316
|
+
await db.execute(createSql);
|
|
1317
|
+
}
|
|
1318
|
+
const quoted = (0, sql_js_1.escapeIdentifier)(tableName);
|
|
1319
|
+
await db.execute(`DELETE FROM ${quoted};`);
|
|
1320
|
+
for (const row of tableEntry.rows ?? []) {
|
|
1321
|
+
const keys = Object.keys(row);
|
|
1322
|
+
if (keys.length === 0)
|
|
1323
|
+
continue;
|
|
1324
|
+
const colsSql = keys.map((k) => (0, sql_js_1.escapeIdentifier)(k)).join(', ');
|
|
1325
|
+
const placeholders = keys.map(() => '?').join(', ');
|
|
1326
|
+
await db.execute(`INSERT INTO ${quoted} (${colsSql}) VALUES (${placeholders});`, keys.map((k) => row[k]));
|
|
1327
|
+
restoredRows++;
|
|
1328
|
+
}
|
|
1329
|
+
restoredTables++;
|
|
1330
|
+
}
|
|
1331
|
+
await db.execute(`COMMIT;`);
|
|
1332
|
+
}
|
|
1333
|
+
catch (restoreErr) {
|
|
1334
|
+
try {
|
|
1335
|
+
await db.execute(`ROLLBACK;`);
|
|
1336
|
+
}
|
|
1337
|
+
catch {
|
|
1338
|
+
// ignore rollback error
|
|
1339
|
+
}
|
|
1340
|
+
throw restoreErr;
|
|
1341
|
+
}
|
|
1342
|
+
finally {
|
|
1343
|
+
if (prevFk) {
|
|
1344
|
+
await db.execute(`PRAGMA foreign_keys = ON;`);
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
return reply(jsonResponse({ ok: true, restoredTables, restoredRows }), `Restored ${restoredTables} tables (${restoredRows} rows)`);
|
|
1348
|
+
}
|
|
1349
|
+
return reply(errorResponse('Not found.', 404));
|
|
1350
|
+
}
|
|
1351
|
+
catch (err) {
|
|
1352
|
+
return reply(errorResponse(err?.message ?? 'Internal server error.', 500), err?.message);
|
|
1353
|
+
}
|
|
1354
|
+
})();
|
|
1355
|
+
if (!loggedThisRequest && pathname.startsWith('/api/')) {
|
|
1356
|
+
recordLog(request.method, pathname, res.status, startedAt);
|
|
1357
|
+
}
|
|
1358
|
+
return res;
|
|
1359
|
+
};
|
|
1360
|
+
}
|
|
1361
|
+
function escapeHtml(text) {
|
|
1362
|
+
return text
|
|
1363
|
+
.replace(/&/g, '&')
|
|
1364
|
+
.replace(/</g, '<')
|
|
1365
|
+
.replace(/>/g, '>')
|
|
1366
|
+
.replace(/"/g, '"');
|
|
1367
|
+
}
|
|
1368
|
+
async function tryServeDashboardAsset(pathname, title) {
|
|
1369
|
+
try {
|
|
1370
|
+
const [{ readFile }, path] = await Promise.all([
|
|
1371
|
+
import('node:fs/promises'),
|
|
1372
|
+
import('node:path'),
|
|
1373
|
+
]);
|
|
1374
|
+
const here = typeof __dirname !== 'undefined' ? __dirname : process.cwd();
|
|
1375
|
+
const distDir = path.resolve(here, '..', '..', 'dashboard', 'dist');
|
|
1376
|
+
const rel = pathname === '/' || pathname === '/index.html'
|
|
1377
|
+
? 'index.html'
|
|
1378
|
+
: pathname.replace(/^\/+/, '');
|
|
1379
|
+
const target = path.resolve(distDir, rel);
|
|
1380
|
+
if (!target.startsWith(distDir + path.sep) && target !== path.join(distDir, 'index.html')) {
|
|
1381
|
+
return null;
|
|
1382
|
+
}
|
|
1383
|
+
const content = await readFile(target);
|
|
1384
|
+
if (rel === 'index.html') {
|
|
1385
|
+
const html = content
|
|
1386
|
+
.toString('utf8')
|
|
1387
|
+
.replace(/<title>.*?<\/title>/, `<title>${escapeHtml(title)}</title>`);
|
|
1388
|
+
return new Response(html, {
|
|
1389
|
+
status: 200,
|
|
1390
|
+
headers: {
|
|
1391
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
1392
|
+
'Cache-Control': 'no-store',
|
|
1393
|
+
},
|
|
1394
|
+
});
|
|
1395
|
+
}
|
|
1396
|
+
const ext = path.extname(target).toLowerCase();
|
|
1397
|
+
const mime = ext === '.js'
|
|
1398
|
+
? 'application/javascript; charset=utf-8'
|
|
1399
|
+
: ext === '.css'
|
|
1400
|
+
? 'text/css; charset=utf-8'
|
|
1401
|
+
: ext === '.svg'
|
|
1402
|
+
? 'image/svg+xml'
|
|
1403
|
+
: 'application/octet-stream';
|
|
1404
|
+
return new Response(content, {
|
|
1405
|
+
status: 200,
|
|
1406
|
+
headers: { 'Content-Type': mime },
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
catch {
|
|
1410
|
+
return null;
|
|
1411
|
+
}
|
|
1412
|
+
}
|