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