local-lite-server 0.0.0-stage → 0.1.1

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 (90) hide show
  1. package/README.md +103 -2
  2. package/admin/dist/assets/index-B2nX9Pef.js +18 -0
  3. package/admin/dist/assets/index-Dt3bXEks.css +2 -0
  4. package/admin/dist/favicon.svg +11 -0
  5. package/admin/dist/index.html +14 -0
  6. package/dist/admin/console.d.ts +19 -0
  7. package/dist/admin/console.js +166 -0
  8. package/dist/admin/index.d.ts +28 -0
  9. package/dist/admin/index.js +13 -0
  10. package/dist/admin/ops.d.ts +11 -0
  11. package/dist/admin/ops.js +279 -0
  12. package/dist/admin/session.d.ts +14 -0
  13. package/dist/admin/session.js +160 -0
  14. package/dist/apiKeys.d.ts +36 -0
  15. package/dist/apiKeys.js +91 -0
  16. package/dist/app.d.ts +1 -0
  17. package/dist/app.js +10 -0
  18. package/dist/auth.d.ts +16 -0
  19. package/dist/auth.js +99 -0
  20. package/dist/cli.d.ts +2 -0
  21. package/dist/cli.js +127 -0
  22. package/dist/codegen.d.ts +4 -0
  23. package/dist/codegen.js +74 -0
  24. package/dist/config.d.ts +39 -0
  25. package/dist/config.js +51 -0
  26. package/dist/core/broker.d.ts +12 -0
  27. package/dist/core/broker.js +78 -0
  28. package/dist/core/changes.d.ts +17 -0
  29. package/dist/core/changes.js +68 -0
  30. package/dist/core/http.d.ts +8 -0
  31. package/dist/core/http.js +72 -0
  32. package/dist/core/mailer.d.ts +3 -0
  33. package/dist/core/mailer.js +11 -0
  34. package/dist/cpanel.d.ts +1 -0
  35. package/dist/cpanel.js +96 -0
  36. package/dist/crons.d.ts +24 -0
  37. package/dist/crons.js +124 -0
  38. package/dist/db.d.ts +7 -0
  39. package/dist/db.js +37 -0
  40. package/dist/functions/index.d.ts +3 -0
  41. package/dist/functions/index.js +3 -0
  42. package/dist/functions/loader.d.ts +4 -0
  43. package/dist/functions/loader.js +64 -0
  44. package/dist/functions/runtime.d.ts +21 -0
  45. package/dist/functions/runtime.js +238 -0
  46. package/dist/functions/types.d.ts +59 -0
  47. package/dist/functions/types.js +16 -0
  48. package/dist/index.d.ts +12 -0
  49. package/dist/index.js +7 -0
  50. package/dist/migrations.d.ts +16 -0
  51. package/dist/migrations.js +254 -0
  52. package/dist/oauth.d.ts +7 -0
  53. package/dist/oauth.js +152 -0
  54. package/dist/rateLimit.d.ts +12 -0
  55. package/dist/rateLimit.js +54 -0
  56. package/dist/routes.d.ts +15 -0
  57. package/dist/routes.js +29 -0
  58. package/dist/rules.d.ts +23 -0
  59. package/dist/rules.js +73 -0
  60. package/dist/schema.d.ts +18 -0
  61. package/dist/schema.js +89 -0
  62. package/dist/server.d.ts +13 -0
  63. package/dist/server.js +340 -0
  64. package/dist/start.d.ts +8 -0
  65. package/dist/start.js +168 -0
  66. package/dist/storage.d.ts +4 -0
  67. package/dist/storage.js +82 -0
  68. package/dist/tableStorage.d.ts +63 -0
  69. package/dist/tableStorage.js +261 -0
  70. package/docs/api.md +181 -0
  71. package/docs/client-usage.md +104 -0
  72. package/docs/cpanel.md +63 -0
  73. package/docs/functions.md +78 -0
  74. package/docs/schema-and-migrations.md +54 -0
  75. package/docs/vps.md +67 -0
  76. package/package.json +54 -4
  77. package/templates/.env +16 -0
  78. package/templates/.env.example +49 -0
  79. package/templates/README.md +23 -0
  80. package/templates/data/backups/.gitkeep +1 -0
  81. package/templates/data/uploads/.gitkeep +1 -0
  82. package/templates/gitignore +29 -0
  83. package/templates/package.json +14 -0
  84. package/templates/src/functions/notes.ts +47 -0
  85. package/templates/src/lib/validators.ts +9 -0
  86. package/templates/src/rules.ts +12 -0
  87. package/templates/src/schema.ts +9 -0
  88. package/templates/src/types.ts +9 -0
  89. package/templates/tests/notes.test.ts +26 -0
  90. package/templates/tsconfig.json +13 -0
@@ -0,0 +1,39 @@
1
+ import type { SqlDialect } from 'local-lite/server';
2
+ export interface SmtpSettings {
3
+ host: string;
4
+ port: number;
5
+ secure: boolean;
6
+ user?: string;
7
+ pass?: string;
8
+ from: string;
9
+ }
10
+ export interface ServerSettings {
11
+ /** Number, or a socket path when the host (Passenger/lsnode) provides one. */
12
+ port: number | string;
13
+ dialect: SqlDialect;
14
+ db: {
15
+ host: string;
16
+ port: number;
17
+ user: string;
18
+ password: string;
19
+ database: string;
20
+ ssl: boolean;
21
+ poolSize: number;
22
+ };
23
+ autoMigrate: boolean;
24
+ schemaPath?: string;
25
+ rulesPath?: string;
26
+ functionsDir?: string;
27
+ uploadDir: string;
28
+ backupDir: string;
29
+ internalCrons: boolean;
30
+ multiInstance: boolean;
31
+ apiKey: string;
32
+ /** Signs user tokens. Enables /auth when set. */
33
+ appSecret?: string;
34
+ appName: string;
35
+ adminUi: boolean;
36
+ smtp?: SmtpSettings;
37
+ corsOrigins: string[];
38
+ }
39
+ export declare function loadSettings(env?: NodeJS.ProcessEnv): ServerSettings;
package/dist/config.js ADDED
@@ -0,0 +1,51 @@
1
+ export function loadSettings(env = process.env) {
2
+ const dialect = (env.DB_DIALECT ?? 'mysql').toLowerCase();
3
+ if (dialect !== 'mysql' && dialect !== 'postgres') {
4
+ throw new Error(`DB_DIALECT must be "mysql" or "postgres", got "${dialect}".`);
5
+ }
6
+ const missing = ['DB_HOST', 'DB_USER', 'DB_NAME', 'SERVER_API_KEY'].filter((k) => !env[k]);
7
+ if (missing.length) {
8
+ throw new Error(`Missing required environment variables: ${missing.join(', ')}`);
9
+ }
10
+ const rawPort = env.PORT || env.SERVER_PORT || '3000';
11
+ const smtpPort = Number(env.SMTP_PORT || 465);
12
+ return {
13
+ port: /^\d+$/.test(rawPort) ? Number(rawPort) : rawPort,
14
+ dialect,
15
+ db: {
16
+ host: env.DB_HOST,
17
+ port: Number(env.DB_PORT || (dialect === 'postgres' ? 5432 : 3306)),
18
+ user: env.DB_USER,
19
+ password: env.DB_PASSWORD ?? '',
20
+ database: env.DB_NAME,
21
+ ssl: env.DB_SSL === 'true',
22
+ poolSize: Number(env.DB_POOL_SIZE || 5),
23
+ },
24
+ autoMigrate: env.AUTO_MIGRATE !== 'false',
25
+ schemaPath: env.SCHEMA_PATH || undefined,
26
+ rulesPath: env.RULES_PATH || undefined,
27
+ functionsDir: env.FUNCTIONS_DIR || undefined,
28
+ uploadDir: env.UPLOAD_DIR || './uploads',
29
+ backupDir: env.BACKUP_DIR || './backups',
30
+ internalCrons: env.ENABLE_INTERNAL_CRONS === 'true',
31
+ multiInstance: env.MULTI_INSTANCE === 'true',
32
+ apiKey: env.SERVER_API_KEY,
33
+ appSecret: env.APP_SECRET?.trim() || undefined,
34
+ appName: env.APP_NAME || 'local-lite-server',
35
+ adminUi: env.ADMIN_UI !== 'false',
36
+ smtp: env.SMTP_HOST
37
+ ? {
38
+ host: env.SMTP_HOST,
39
+ port: smtpPort,
40
+ secure: env.SMTP_SECURE ? env.SMTP_SECURE === 'true' : smtpPort === 465,
41
+ user: env.SMTP_USER || undefined,
42
+ pass: env.SMTP_PASS || undefined,
43
+ from: env.SMTP_FROM || env.SMTP_USER || 'no-reply@localhost',
44
+ }
45
+ : undefined,
46
+ corsOrigins: (env.CORS_ORIGINS ?? '*')
47
+ .split(',')
48
+ .map((s) => s.trim())
49
+ .filter(Boolean),
50
+ };
51
+ }
@@ -0,0 +1,12 @@
1
+ import { type SqlExecutor, type SyncEventBroker } from 'local-lite/server';
2
+ import type { ServerSettings } from '../config.js';
3
+ export interface ManagedBroker extends SyncEventBroker {
4
+ close(): Promise<void>;
5
+ }
6
+ /**
7
+ * Single-node in-memory broker by default.
8
+ * When `MULTI_INSTANCE=true`:
9
+ * - Postgres: uses native LISTEN/NOTIFY on `lls_sync_events` (zero extra deps).
10
+ * - MySQL: polls `_server_changes` every 1s for changes from sibling instances.
11
+ */
12
+ export declare function createClusterBroker(settings: ServerSettings, db: SqlExecutor): Promise<ManagedBroker>;
@@ -0,0 +1,78 @@
1
+ import { createSyncEventBroker, quoteIdent, } from 'local-lite/server';
2
+ /**
3
+ * Single-node in-memory broker by default.
4
+ * When `MULTI_INSTANCE=true`:
5
+ * - Postgres: uses native LISTEN/NOTIFY on `lls_sync_events` (zero extra deps).
6
+ * - MySQL: polls `_server_changes` every 1s for changes from sibling instances.
7
+ */
8
+ export async function createClusterBroker(settings, db) {
9
+ const local = createSyncEventBroker();
10
+ if (!settings.multiInstance) {
11
+ return { ...local, close: async () => { } };
12
+ }
13
+ if (settings.dialect === 'postgres') {
14
+ const pg = (await import('pg')).default;
15
+ const sub = new pg.Client({
16
+ host: settings.db.host,
17
+ port: settings.db.port,
18
+ user: settings.db.user,
19
+ password: settings.db.password,
20
+ database: settings.db.database,
21
+ ssl: settings.db.ssl ? { rejectUnauthorized: false } : undefined,
22
+ });
23
+ await sub.connect();
24
+ sub.on('notification', (msg) => {
25
+ if (msg.channel !== 'lls_sync_events' || !msg.payload)
26
+ return;
27
+ try {
28
+ local.publish(JSON.parse(msg.payload));
29
+ }
30
+ catch {
31
+ // ignore malformed payload
32
+ }
33
+ });
34
+ await sub.query('LISTEN lls_sync_events');
35
+ return {
36
+ publish(event) {
37
+ void db.query('SELECT pg_notify($1, $2)', ['lls_sync_events', JSON.stringify(event)]).catch(() => {
38
+ local.publish(event);
39
+ });
40
+ },
41
+ subscribe: (listener) => local.subscribe(listener),
42
+ close: () => sub.end().catch(() => { }),
43
+ };
44
+ }
45
+ // MySQL multi-instance: tail `_server_changes` for events written by other nodes.
46
+ const qChanges = quoteIdent('_server_changes', 'mysql');
47
+ const qTs = quoteIdent('timestamp', 'mysql');
48
+ let lastId = 0;
49
+ try {
50
+ const rows = await db.query(`SELECT COALESCE(MAX(id), 0) AS max_id FROM ${qChanges}`);
51
+ lastId = Number(rows[0]?.max_id ?? 0);
52
+ }
53
+ catch {
54
+ lastId = 0;
55
+ }
56
+ const timer = setInterval(async () => {
57
+ try {
58
+ const rows = await db.query(`SELECT id, table_name, ${qTs} AS ts FROM ${qChanges} WHERE id > ? ORDER BY id ASC LIMIT 200`, [lastId]);
59
+ for (const r of rows) {
60
+ lastId = Math.max(lastId, Number(r.id));
61
+ local.publish({
62
+ scopeId: 'default',
63
+ tableName: String(r.table_name),
64
+ checkpoint: Number(r.ts),
65
+ });
66
+ }
67
+ }
68
+ catch {
69
+ // ignore transient poll errors
70
+ }
71
+ }, 1000);
72
+ timer.unref?.();
73
+ return {
74
+ publish: (ev) => local.publish(ev),
75
+ subscribe: (listener) => local.subscribe(listener),
76
+ close: async () => clearInterval(timer),
77
+ };
78
+ }
@@ -0,0 +1,17 @@
1
+ import { type SqlExecutor } from 'local-lite/server';
2
+ import type { SchemaFieldType } from '../schema.js';
3
+ /** Locks and reads `_server_sync_clock` inside an active transaction. */
4
+ export declare function lockClock(tx: SqlExecutor, clockTable?: string): Promise<number>;
5
+ /** Appends a row entry to `_server_changes` with an already-computed timestamp. */
6
+ export declare function appendChangeLog(tx: SqlExecutor, table: string, rowId: string, timestamp: number, changesTable?: string): Promise<void>;
7
+ /** Updates `_server_sync_clock` to `timestamp`. */
8
+ export declare function commitClock(tx: SqlExecutor, timestamp: number, clockTable?: string): Promise<void>;
9
+ /** Advances `_server_sync_clock` inside an active transaction and logs to `_server_changes`. */
10
+ export declare function recordChange(tx: SqlExecutor, table: string, rowId: string, changesTable?: string, clockTable?: string): Promise<number>;
11
+ /** Upserts a row into a schema-defined table using dialect-safe column conversion. */
12
+ export declare function upsertTableRow(tx: SqlExecutor, table: string, fields: Record<string, SchemaFieldType>, rowId: string, data: Record<string, any>, timestamp: number): Promise<void>;
13
+ /** Updates specified schema columns on an existing row. */
14
+ export declare function patchTableRow(tx: SqlExecutor, table: string, fields: Record<string, SchemaFieldType>, rowId: string, patch: Record<string, any>, timestamp: number): Promise<void>;
15
+ /** Soft-deletes or restores a row in a schema-defined table. */
16
+ export declare function setRowDeleted(tx: SqlExecutor, table: string, rowId: string, deleted: boolean, timestamp: number): Promise<void>;
17
+ export declare function newRowId(raw?: unknown): string;
@@ -0,0 +1,68 @@
1
+ import crypto from 'node:crypto';
2
+ import { buildUpsertSql, quoteIdent } from 'local-lite/server';
3
+ import { toDbValue } from '../tableStorage.js';
4
+ const SYSTEM_COLS = new Set(['id', 'updated_at', 'deleted']);
5
+ /** Locks and reads `_server_sync_clock` inside an active transaction. */
6
+ export async function lockClock(tx, clockTable = '_server_sync_clock') {
7
+ const q = (n) => quoteIdent(n, tx.dialect);
8
+ const clock = await tx.query(`SELECT checkpoint FROM ${q(clockTable)} WHERE id = 1 FOR UPDATE`);
9
+ return Number(clock[0]?.checkpoint ?? 0);
10
+ }
11
+ /** Appends a row entry to `_server_changes` with an already-computed timestamp. */
12
+ export async function appendChangeLog(tx, table, rowId, timestamp, changesTable = '_server_changes') {
13
+ const q = (n) => quoteIdent(n, tx.dialect);
14
+ await tx.execute(`INSERT INTO ${q(changesTable)} (table_name, row_id, ${q('timestamp')}) VALUES (?, ?, ?)`, [table, rowId, timestamp]);
15
+ }
16
+ /** Updates `_server_sync_clock` to `timestamp`. */
17
+ export async function commitClock(tx, timestamp, clockTable = '_server_sync_clock') {
18
+ const q = (n) => quoteIdent(n, tx.dialect);
19
+ await tx.execute(`UPDATE ${q(clockTable)} SET checkpoint = ? WHERE id = 1`, [timestamp]);
20
+ }
21
+ /** Advances `_server_sync_clock` inside an active transaction and logs to `_server_changes`. */
22
+ export async function recordChange(tx, table, rowId, changesTable = '_server_changes', clockTable = '_server_sync_clock') {
23
+ const prev = await lockClock(tx, clockTable);
24
+ const ts = Math.max(Date.now(), prev + 1);
25
+ await appendChangeLog(tx, table, rowId, ts, changesTable);
26
+ await commitClock(tx, ts, clockTable);
27
+ return ts;
28
+ }
29
+ /** Upserts a row into a schema-defined table using dialect-safe column conversion. */
30
+ export async function upsertTableRow(tx, table, fields, rowId, data, timestamp) {
31
+ const dialect = tx.dialect;
32
+ const cols = Object.keys(fields).filter((c) => !SYSTEM_COLS.has(c) && c !== 'created_at' && Object.hasOwn(data, c));
33
+ const insertCols = ['id', ...cols, 'updated_at', 'deleted'];
34
+ const params = [
35
+ rowId,
36
+ ...cols.map((c) => toDbValue(fields[c], data[c], dialect)),
37
+ timestamp,
38
+ dialect === 'postgres' ? Boolean(data.deleted) : data.deleted ? 1 : 0,
39
+ ];
40
+ if (fields.created_at) {
41
+ insertCols.push('created_at');
42
+ params.push(data.created_at != null ? toDbValue(fields.created_at, data.created_at, dialect) : timestamp);
43
+ }
44
+ await tx.execute(buildUpsertSql({
45
+ table,
46
+ conflictCols: ['id'],
47
+ insertCols,
48
+ updateCols: [...cols, 'updated_at', 'deleted'],
49
+ dialect,
50
+ }), params);
51
+ }
52
+ /** Updates specified schema columns on an existing row. */
53
+ export async function patchTableRow(tx, table, fields, rowId, patch, timestamp) {
54
+ const q = (n) => quoteIdent(n, tx.dialect);
55
+ const cols = Object.keys(fields).filter((c) => !SYSTEM_COLS.has(c) && Object.hasOwn(patch, c));
56
+ const sets = [...cols.map((c) => `${q(c)} = ?`), `${q('updated_at')} = ?`];
57
+ const params = [...cols.map((c) => toDbValue(fields[c], patch[c], tx.dialect)), timestamp, rowId];
58
+ await tx.execute(`UPDATE ${q(table)} SET ${sets.join(', ')} WHERE ${q('id')} = ?`, params);
59
+ }
60
+ /** Soft-deletes or restores a row in a schema-defined table. */
61
+ export async function setRowDeleted(tx, table, rowId, deleted, timestamp) {
62
+ const q = (n) => quoteIdent(n, tx.dialect);
63
+ const delVal = tx.dialect === 'postgres' ? deleted : deleted ? 1 : 0;
64
+ await tx.execute(`UPDATE ${q(table)} SET ${q('deleted')} = ?, ${q('updated_at')} = ? WHERE ${q('id')} = ?`, [delVal, timestamp, rowId]);
65
+ }
66
+ export function newRowId(raw) {
67
+ return typeof raw === 'string' && raw.trim() ? raw.trim() : crypto.randomUUID();
68
+ }
@@ -0,0 +1,8 @@
1
+ import http from 'node:http';
2
+ import type { ServerSettings } from '../config.js';
3
+ export declare function safeEqual(a: string, b: string): boolean;
4
+ export declare function corsHeaders(request: Request, s: ServerSettings): Record<string, string>;
5
+ /** Node `http.Server` -> Web `Request`/`Response` bridge with streaming SSE support. */
6
+ export declare function createHttpServer(app: {
7
+ fetch(req: Request): Promise<Response>;
8
+ }): http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
@@ -0,0 +1,72 @@
1
+ import crypto from 'node:crypto';
2
+ import http from 'node:http';
3
+ const MAX_BODY_BYTES = 6_000_000;
4
+ export function safeEqual(a, b) {
5
+ const ab = Buffer.from(a);
6
+ const bb = Buffer.from(b);
7
+ return ab.length === bb.length && crypto.timingSafeEqual(ab, bb);
8
+ }
9
+ export function corsHeaders(request, s) {
10
+ const origin = request.headers.get('origin');
11
+ const allowAll = s.corsOrigins.includes('*');
12
+ const allowed = allowAll ? '*' : origin && s.corsOrigins.includes(origin) ? origin : '';
13
+ const h = {
14
+ 'Access-Control-Allow-Methods': 'GET,POST,PATCH,DELETE,OPTIONS',
15
+ 'Access-Control-Allow-Headers': 'Authorization,Content-Type,X-API-Key,X-Captcha-Token',
16
+ 'Access-Control-Max-Age': '600',
17
+ };
18
+ if (allowed)
19
+ h['Access-Control-Allow-Origin'] = allowed;
20
+ if (!allowAll)
21
+ h['Vary'] = 'Origin';
22
+ return h;
23
+ }
24
+ /** Node `http.Server` -> Web `Request`/`Response` bridge with streaming SSE support. */
25
+ export function createHttpServer(app) {
26
+ return http.createServer(async (req, res) => {
27
+ try {
28
+ const proto = req.headers['x-forwarded-proto'] === 'https' ? 'https' : 'http';
29
+ const url = `${proto}://${req.headers.host ?? 'localhost'}${req.url}`;
30
+ const chunks = [];
31
+ let size = 0;
32
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
33
+ for await (const chunk of req) {
34
+ size += chunk.length;
35
+ if (size > MAX_BODY_BYTES) {
36
+ res.writeHead(413, { 'Content-Type': 'application/json' });
37
+ res.end(JSON.stringify({ error: 'Request body is too large.' }));
38
+ return;
39
+ }
40
+ chunks.push(chunk);
41
+ }
42
+ }
43
+ const init = {
44
+ method: req.method,
45
+ headers: req.headers,
46
+ };
47
+ if (chunks.length) {
48
+ init.body = Buffer.concat(chunks);
49
+ init.duplex = 'half';
50
+ }
51
+ const response = await app.fetch(new Request(url, init));
52
+ res.writeHead(response.status, Object.fromEntries(response.headers));
53
+ if (!response.body)
54
+ return void res.end();
55
+ const reader = response.body.getReader();
56
+ res.on('close', () => void reader.cancel().catch(() => { }));
57
+ for (;;) {
58
+ const { done, value } = await reader.read();
59
+ if (done)
60
+ break;
61
+ res.write(value);
62
+ }
63
+ res.end();
64
+ }
65
+ catch (error) {
66
+ console.error('[local-lite-server]', error);
67
+ if (!res.headersSent)
68
+ res.writeHead(500, { 'Content-Type': 'application/json' });
69
+ res.end(JSON.stringify({ error: 'Request failed.' }));
70
+ }
71
+ });
72
+ }
@@ -0,0 +1,3 @@
1
+ import type { SmtpSettings } from '../config.js';
2
+ /** Sends a plain-text email via SMTP (lazy-loads nodemailer only when called). */
3
+ export declare function sendSmtpMail(smtp: SmtpSettings, to: string, subject: string, text: string): Promise<void>;
@@ -0,0 +1,11 @@
1
+ /** Sends a plain-text email via SMTP (lazy-loads nodemailer only when called). */
2
+ export async function sendSmtpMail(smtp, to, subject, text) {
3
+ const nodemailer = await import('nodemailer');
4
+ const transport = (nodemailer.default ?? nodemailer).createTransport({
5
+ host: smtp.host,
6
+ port: smtp.port,
7
+ secure: smtp.secure,
8
+ auth: smtp.user ? { user: smtp.user, pass: smtp.pass } : undefined,
9
+ });
10
+ await transport.sendMail({ from: smtp.from, to, subject, text });
11
+ }
@@ -0,0 +1 @@
1
+ export declare function buildCpanelBundle(cwd?: string, outDir?: string): Promise<void>;
package/dist/cpanel.js ADDED
@@ -0,0 +1,96 @@
1
+ import fs from 'node:fs';
2
+ import { createRequire } from 'node:module';
3
+ import path from 'node:path';
4
+ import { build } from 'esbuild';
5
+ import { resolveRoutesFile } from './routes.js';
6
+ import { resolveRulesFile } from './rules.js';
7
+ import { resolveSchemaFile } from './schema.js';
8
+ const require = createRequire(import.meta.url);
9
+ const EXTERNAL_PEERS = [
10
+ 'react-native', 'react-native/*', '@react-native/*', '@react-native-community/*',
11
+ 'expo', 'expo-*', 'expo-modules-core', 'react', 'react/*',
12
+ 'better-sqlite3', '@libsql/*', 'op-sqlite', '@op-engineering/*',
13
+ 'pg-native',
14
+ ];
15
+ export async function buildCpanelBundle(cwd = process.cwd(), outDir = 'dist/cpanel') {
16
+ const pkgRoot = path.resolve(import.meta.dirname, '..');
17
+ const isOwnRepo = fs.existsSync(path.resolve(cwd, 'src/cli.ts'));
18
+ const entryPoint = isOwnRepo
19
+ ? path.resolve(cwd, 'src/app.ts')
20
+ : path.resolve(import.meta.dirname, 'app.js');
21
+ const absOut = path.resolve(cwd, outDir);
22
+ const nodemailerDir = path.dirname(require.resolve('nodemailer/package.json'));
23
+ fs.rmSync(absOut, { recursive: true, force: true });
24
+ await build({
25
+ entryPoints: [entryPoint],
26
+ bundle: true,
27
+ platform: 'node',
28
+ target: 'node24',
29
+ format: 'esm',
30
+ splitting: true,
31
+ treeShaking: true,
32
+ legalComments: 'none',
33
+ drop: ['debugger'],
34
+ alias: {
35
+ nodemailer: nodemailerDir,
36
+ },
37
+ outdir: absOut,
38
+ entryNames: 'app',
39
+ chunkNames: 'chunks/[name]-[hash]',
40
+ outExtension: { '.js': '.mjs' },
41
+ banner: {
42
+ js: "import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);",
43
+ },
44
+ minify: true,
45
+ logLevel: 'info',
46
+ external: EXTERNAL_PEERS,
47
+ });
48
+ try {
49
+ const schemaFile = resolveSchemaFile(undefined, cwd);
50
+ fs.copyFileSync(schemaFile, path.join(absOut, 'schema.ts'));
51
+ }
52
+ catch {
53
+ // User may upload schema.ts separately
54
+ }
55
+ const rulesFile = resolveRulesFile(undefined, cwd);
56
+ if (rulesFile) {
57
+ fs.copyFileSync(rulesFile, path.join(absOut, 'rules.ts'));
58
+ }
59
+ const routesFile = resolveRoutesFile(undefined, cwd);
60
+ if (routesFile) {
61
+ await build({
62
+ entryPoints: [routesFile],
63
+ bundle: true,
64
+ platform: 'node',
65
+ target: 'node24',
66
+ format: 'esm',
67
+ treeShaking: true,
68
+ legalComments: 'none',
69
+ outfile: path.join(absOut, 'routes.mjs'),
70
+ minify: true,
71
+ logLevel: 'info',
72
+ external: EXTERNAL_PEERS,
73
+ });
74
+ }
75
+ const envExample = fs.existsSync(path.resolve(cwd, '.env.example'))
76
+ ? path.resolve(cwd, '.env.example')
77
+ : path.resolve(pkgRoot, 'templates/.env.example');
78
+ if (fs.existsSync(envExample)) {
79
+ fs.copyFileSync(envExample, path.join(absOut, '.env.example'));
80
+ }
81
+ const cpanelDoc = path.resolve(pkgRoot, 'docs/cpanel.md');
82
+ if (fs.existsSync(cpanelDoc)) {
83
+ fs.copyFileSync(cpanelDoc, path.join(absOut, 'README-cpanel.md'));
84
+ }
85
+ const srcFns = path.resolve(cwd, 'src/functions');
86
+ const rootFns = path.resolve(cwd, 'functions');
87
+ const fnsDir = !isOwnRepo && fs.existsSync(srcFns) ? srcFns : fs.existsSync(rootFns) ? rootFns : null;
88
+ if (fnsDir) {
89
+ fs.cpSync(fnsDir, path.join(absOut, 'functions'), { recursive: true });
90
+ }
91
+ const adminDist = path.resolve(pkgRoot, 'admin/dist');
92
+ if (fs.existsSync(adminDist)) {
93
+ fs.cpSync(adminDist, path.join(absOut, 'admin-ui'), { recursive: true });
94
+ }
95
+ console.log(`\ncPanel package ready: ${outDir}/ (app.mjs, chunks/, schema.ts, .env.example, README-cpanel.md)`);
96
+ }
@@ -0,0 +1,24 @@
1
+ import { type SqlExecutor } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ import type { FunctionRuntime } from './functions/index.js';
4
+ export interface CronJobRecord {
5
+ job_key: string;
6
+ label: string;
7
+ action_type: string;
8
+ cron_expr: string;
9
+ timezone: string;
10
+ enabled: boolean | number;
11
+ config_json?: string | null;
12
+ last_run_at?: number | null;
13
+ }
14
+ export declare function matchesCron(expr: string, date: Date, timeZone?: string): boolean;
15
+ export declare function runCronAction(actionType: string, configJson: string | null | undefined, deps: {
16
+ settings: ServerSettings;
17
+ db: SqlExecutor;
18
+ fnRuntime?: FunctionRuntime;
19
+ }): Promise<string>;
20
+ export declare function startCronScheduler(deps: {
21
+ settings: ServerSettings;
22
+ db: SqlExecutor;
23
+ fnRuntime?: FunctionRuntime;
24
+ }): () => void;
package/dist/crons.js ADDED
@@ -0,0 +1,124 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { quoteIdent } from 'local-lite/server';
4
+ function matchField(expr, value) {
5
+ for (const part of expr.split(',')) {
6
+ const s = part.trim();
7
+ if (s === '*')
8
+ return true;
9
+ if (s.startsWith('*/')) {
10
+ const step = Number(s.slice(2));
11
+ if (step > 0 && value % step === 0)
12
+ return true;
13
+ }
14
+ else if (s.includes('-')) {
15
+ const [a, b] = s.split('-').map(Number);
16
+ if (value >= a && value <= b)
17
+ return true;
18
+ }
19
+ else if (Number(s) === value) {
20
+ return true;
21
+ }
22
+ }
23
+ return false;
24
+ }
25
+ export function matchesCron(expr, date, timeZone = 'UTC') {
26
+ const fields = expr.trim().split(/\s+/);
27
+ if (fields.length !== 5)
28
+ return false;
29
+ const parts = new Intl.DateTimeFormat('en-US', {
30
+ timeZone,
31
+ hour12: false,
32
+ minute: 'numeric',
33
+ hour: 'numeric',
34
+ day: 'numeric',
35
+ month: 'numeric',
36
+ weekday: 'short',
37
+ }).formatToParts(date);
38
+ const get = (t) => parts.find((p) => p.type === t)?.value ?? '0';
39
+ const dowMap = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
40
+ const vals = [
41
+ Number(get('minute')),
42
+ Number(get('hour')) % 24,
43
+ Number(get('day')),
44
+ Number(get('month')),
45
+ dowMap[get('weekday')] ?? date.getUTCDay(),
46
+ ];
47
+ return fields.every((f, i) => matchField(f, vals[i]));
48
+ }
49
+ export async function runCronAction(actionType, configJson, deps) {
50
+ const cfg = configJson ? JSON.parse(configJson) : {};
51
+ if (actionType === 'http_webhook') {
52
+ const url = String(cfg.url ?? '').trim();
53
+ if (!url)
54
+ throw new Error('Webhook URL is not configured.');
55
+ const res = await fetch(url, {
56
+ method: 'POST',
57
+ headers: { 'content-type': 'application/json', ...(cfg.headers || {}) },
58
+ body: cfg.body ? JSON.stringify(cfg.body) : JSON.stringify({ timestamp: Date.now() }),
59
+ signal: AbortSignal.timeout(15_000),
60
+ });
61
+ if (!res.ok)
62
+ throw new Error(`Webhook returned HTTP ${res.status}`);
63
+ return `HTTP ${res.status}`;
64
+ }
65
+ if (actionType === 'function_call') {
66
+ if (!deps.fnRuntime)
67
+ throw new Error('Function runtime unavailable.');
68
+ const fnName = String(cfg.fnName ?? cfg.function ?? '').trim();
69
+ if (!fnName)
70
+ throw new Error('Function name is not configured.');
71
+ await deps.fnRuntime.run(fnName, cfg.args ?? {}, { isAdmin: true });
72
+ return `Ran ${fnName}`;
73
+ }
74
+ if (actionType === 'trim_old_logs') {
75
+ const days = Math.max(1, Number(cfg.keepDays ?? 30));
76
+ const cutoff = Date.now() - days * 86_400_000;
77
+ const res = await deps.db.execute(`DELETE FROM ${quoteIdent('_server_changes', deps.db.dialect)} WHERE ${quoteIdent('timestamp')} < ?`, [cutoff]);
78
+ return `Trimmed ${res.affectedRows} log row(s)`;
79
+ }
80
+ if (actionType === 'storage_orphan_prune') {
81
+ const rows = await deps.db.query('SELECT id, bucket, storage_key FROM _lls_storage_files');
82
+ let removedDbRows = 0;
83
+ for (const r of rows) {
84
+ const inBucket = r.bucket ? path.resolve(deps.settings.uploadDir, r.bucket, r.storage_key) : '';
85
+ const direct = path.resolve(deps.settings.uploadDir, r.storage_key);
86
+ if ((!inBucket || !fs.existsSync(inBucket)) && !fs.existsSync(direct)) {
87
+ await deps.db.execute('DELETE FROM _lls_storage_files WHERE id = ?', [r.id]);
88
+ removedDbRows += 1;
89
+ }
90
+ }
91
+ return `Pruned ${removedDbRows} missing file record(s)`;
92
+ }
93
+ return 'Executed';
94
+ }
95
+ export function startCronScheduler(deps) {
96
+ if (!deps.settings.internalCrons)
97
+ return () => { };
98
+ const timer = setInterval(async () => {
99
+ const now = new Date();
100
+ const currentMinute = Math.floor(now.getTime() / 60_000);
101
+ try {
102
+ const jobs = await deps.db.query('SELECT * FROM _lls_crons');
103
+ for (const job of jobs) {
104
+ if (!job.enabled || !matchesCron(job.cron_expr, now, job.timezone || 'UTC'))
105
+ continue;
106
+ if (job.last_run_at && Math.floor(Number(job.last_run_at) / 60_000) === currentMinute) {
107
+ continue;
108
+ }
109
+ try {
110
+ const summary = await runCronAction(job.action_type, job.config_json, deps);
111
+ await deps.db.execute('UPDATE _lls_crons SET last_run_at = ?, last_status = ?, last_summary = ? WHERE job_key = ?', [Date.now(), 'ok', summary, job.job_key]);
112
+ }
113
+ catch (err) {
114
+ await deps.db.execute('UPDATE _lls_crons SET last_run_at = ?, last_status = ?, last_summary = ? WHERE job_key = ?', [Date.now(), 'error', err instanceof Error ? err.message : 'Failed', job.job_key]);
115
+ }
116
+ }
117
+ }
118
+ catch (err) {
119
+ console.error('[local-lite-server] cron tick error:', err);
120
+ }
121
+ }, 60_000);
122
+ timer.unref?.();
123
+ return () => clearInterval(timer);
124
+ }
package/dist/db.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type SqlExecutor } from 'local-lite/server';
2
+ import type { ServerSettings } from './config.js';
3
+ export interface Database {
4
+ executor: SqlExecutor;
5
+ close(): Promise<void>;
6
+ }
7
+ export declare function createDatabase(settings: ServerSettings): Promise<Database>;
package/dist/db.js ADDED
@@ -0,0 +1,37 @@
1
+ import { createSqlExecutor } from 'local-lite/server';
2
+ export async function createDatabase(settings) {
3
+ const { db, dialect } = settings;
4
+ if (dialect === 'postgres') {
5
+ const pg = (await import('pg')).default;
6
+ // Parse Postgres BIGINT as number to match mysql2 (epoch-ms timestamps).
7
+ pg.types.setTypeParser(20, (v) => Number(v));
8
+ const pool = new pg.Pool({
9
+ host: db.host,
10
+ port: db.port,
11
+ user: db.user,
12
+ password: db.password,
13
+ database: db.database,
14
+ ssl: db.ssl ? { rejectUnauthorized: false } : undefined,
15
+ max: db.poolSize,
16
+ });
17
+ return {
18
+ executor: createSqlExecutor(pool, 'postgres'),
19
+ close: () => pool.end(),
20
+ };
21
+ }
22
+ const mysql = (await import('mysql2/promise')).default;
23
+ const pool = mysql.createPool({
24
+ host: db.host,
25
+ port: db.port,
26
+ user: db.user,
27
+ password: db.password,
28
+ database: db.database,
29
+ waitForConnections: true,
30
+ connectionLimit: db.poolSize,
31
+ queueLimit: 0,
32
+ });
33
+ return {
34
+ executor: createSqlExecutor(pool, 'mysql'),
35
+ close: () => pool.end(),
36
+ };
37
+ }