local-lite-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +103 -2
  2. package/admin/dist/assets/index-DMJ7Ri2R.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.js +166 -0
  7. package/dist/admin/index.js +13 -0
  8. package/dist/admin/ops.js +279 -0
  9. package/dist/admin/session.js +160 -0
  10. package/dist/apiKeys.js +91 -0
  11. package/dist/app.js +6 -0
  12. package/dist/auth.js +99 -0
  13. package/dist/cli.js +127 -0
  14. package/dist/codegen.js +74 -0
  15. package/dist/config.js +51 -0
  16. package/dist/core/broker.js +78 -0
  17. package/dist/core/changes.js +68 -0
  18. package/dist/core/http.js +72 -0
  19. package/dist/core/mailer.js +11 -0
  20. package/dist/cpanel.js +78 -0
  21. package/dist/crons.js +124 -0
  22. package/dist/db.js +37 -0
  23. package/dist/functions/index.js +3 -0
  24. package/dist/functions/loader.js +64 -0
  25. package/dist/functions/runtime.js +238 -0
  26. package/dist/functions/types.js +16 -0
  27. package/dist/index.js +6 -0
  28. package/dist/migrations.js +254 -0
  29. package/dist/rateLimit.js +54 -0
  30. package/dist/rules.js +73 -0
  31. package/dist/schema.js +89 -0
  32. package/dist/server.js +314 -0
  33. package/dist/start.js +161 -0
  34. package/dist/storage.js +82 -0
  35. package/dist/tableStorage.js +261 -0
  36. package/docs/api.md +181 -0
  37. package/docs/client-usage.md +104 -0
  38. package/docs/cpanel.md +63 -0
  39. package/docs/functions.md +78 -0
  40. package/docs/schema-and-migrations.md +54 -0
  41. package/docs/vps.md +67 -0
  42. package/package.json +54 -4
  43. package/templates/.env +16 -0
  44. package/templates/.env.example +16 -0
  45. package/templates/README.md +23 -0
  46. package/templates/data/backups/.gitkeep +1 -0
  47. package/templates/data/uploads/.gitkeep +1 -0
  48. package/templates/gitignore +29 -0
  49. package/templates/package.json +14 -0
  50. package/templates/src/functions/notes.ts +47 -0
  51. package/templates/src/lib/validators.ts +9 -0
  52. package/templates/src/rules.ts +12 -0
  53. package/templates/src/schema.ts +9 -0
  54. package/templates/src/types.ts +9 -0
  55. package/templates/tests/notes.test.ts +26 -0
  56. package/templates/tsconfig.json +13 -0
@@ -0,0 +1,261 @@
1
+ import { quoteIdent, } from 'local-lite/server';
2
+ import { appendChangeLog, commitClock, lockClock, setRowDeleted, upsertTableRow, } from './core/changes.js';
3
+ /** Thrown for bad client input; the HTTP layer maps it to 400. */
4
+ export class ClientError extends Error {
5
+ }
6
+ /** Thrown when a row-level access rule rejects the operation; mapped to 403. */
7
+ export class ForbiddenError extends Error {
8
+ }
9
+ const MAX_BATCH = 1000;
10
+ const baseType = (t) => t.replace(' | null', '');
11
+ /** Client value -> DB parameter. */
12
+ export function toDbValue(type, value, dialect) {
13
+ if (value === undefined || value === null)
14
+ return null;
15
+ switch (baseType(type)) {
16
+ case 'boolean':
17
+ return dialect === 'postgres' ? Boolean(value) : value ? 1 : 0;
18
+ case 'number':
19
+ return Number(value);
20
+ case 'json':
21
+ case 'string[]':
22
+ return typeof value === 'string' ? value : JSON.stringify(value);
23
+ default:
24
+ return typeof value === 'string' ? value : String(value);
25
+ }
26
+ }
27
+ /** DB row -> client payload. */
28
+ export function fromDbRow(fields, row) {
29
+ const out = {};
30
+ for (const [col, type] of Object.entries(fields)) {
31
+ const v = row[col];
32
+ if (v === undefined)
33
+ continue;
34
+ if (v === null) {
35
+ out[col] = null;
36
+ continue;
37
+ }
38
+ switch (baseType(type)) {
39
+ case 'boolean':
40
+ out[col] = Boolean(v);
41
+ break;
42
+ case 'number':
43
+ out[col] = Number(v);
44
+ break;
45
+ case 'json':
46
+ case 'string[]':
47
+ if (typeof v === 'string') {
48
+ try {
49
+ out[col] = JSON.parse(v);
50
+ }
51
+ catch {
52
+ out[col] = v;
53
+ }
54
+ }
55
+ else
56
+ out[col] = v;
57
+ break;
58
+ default:
59
+ out[col] = v;
60
+ }
61
+ }
62
+ out.deleted = Boolean(row.deleted);
63
+ out.updated_at = Number(row.updated_at ?? 0);
64
+ return out;
65
+ }
66
+ /**
67
+ * Stores every synced table as a real SQL table. `_server_changes` keeps only
68
+ * (table_name, row_id, timestamp) as a monotonic cursor/event log.
69
+ */
70
+ export class TableSyncStorage {
71
+ db;
72
+ schema;
73
+ rules;
74
+ broker;
75
+ changes;
76
+ clock;
77
+ scopeField;
78
+ constructor(db, opts) {
79
+ this.db = db;
80
+ this.schema = opts.schema;
81
+ this.rules = opts.rules ?? {};
82
+ this.broker = opts.broker;
83
+ this.changes = opts.changesTable ?? '_server_changes';
84
+ this.clock = opts.clockTable ?? '_server_sync_clock';
85
+ this.scopeField = opts.scopeField ?? 'scope_id';
86
+ }
87
+ get tables() {
88
+ return Object.keys(this.schema);
89
+ }
90
+ q = (name) => quoteIdent(name, this.db.dialect);
91
+ fields(table) {
92
+ const f = Object.hasOwn(this.schema, table) ? this.schema[table] : undefined;
93
+ if (!f)
94
+ throw new ClientError(`Unknown table "${table}".`);
95
+ return f;
96
+ }
97
+ async applyOperations(operations, _serverTime, auth = { isAdmin: true }) {
98
+ if (operations.length > MAX_BATCH)
99
+ throw new ClientError('Batch is too large.');
100
+ const emitted = [];
101
+ const successfulIds = [];
102
+ let cursor = 0;
103
+ await this.db.withTransaction(async (tx) => {
104
+ cursor = await lockClock(tx, this.clock);
105
+ // Prefetch existing rows in batches for any table with a write RLS rule.
106
+ const existingByKey = new Map();
107
+ if (!auth.isAdmin) {
108
+ const idsByTable = new Map();
109
+ for (const op of operations) {
110
+ if (!op || typeof op.rowId !== 'string' || !op.rowId || op.rowId.length > 128) {
111
+ throw new ClientError('Each operation needs a rowId string (max 128 chars).');
112
+ }
113
+ this.fields(op.tableName);
114
+ const tableRule = this.rules[op.tableName];
115
+ const needsCheck = op.operation === 'DELETE' ? (tableRule?.delete ?? tableRule?.write) : tableRule?.write;
116
+ if (needsCheck) {
117
+ const set = idsByTable.get(op.tableName) ?? new Set();
118
+ set.add(op.rowId);
119
+ idsByTable.set(op.tableName, set);
120
+ }
121
+ }
122
+ for (const [table, idSet] of idsByTable) {
123
+ const fields = this.fields(table);
124
+ const ids = [...idSet];
125
+ for (let i = 0; i < ids.length; i += 400) {
126
+ const chunk = ids.slice(i, i + 400);
127
+ const found = await tx.query(`SELECT * FROM ${this.q(table)} WHERE ${this.q('id')} IN (${chunk.map(() => '?').join(', ')})`, chunk);
128
+ for (const r of found) {
129
+ existingByKey.set(`${table}\u0000${r.id}`, {
130
+ id: String(r.id),
131
+ ...fromDbRow(fields, r),
132
+ });
133
+ }
134
+ }
135
+ }
136
+ }
137
+ for (const op of operations) {
138
+ if (!op || typeof op.rowId !== 'string' || !op.rowId || op.rowId.length > 128) {
139
+ throw new ClientError('Each operation needs a rowId string (max 128 chars).');
140
+ }
141
+ const fields = this.fields(op.tableName);
142
+ const payload = op.payload && typeof op.payload === 'object' ? op.payload : {};
143
+ const tableRule = !auth.isAdmin ? this.rules[op.tableName] : undefined;
144
+ const writeRule = op.operation === 'DELETE' ? (tableRule?.delete ?? tableRule?.write) : tableRule?.write;
145
+ if (writeRule) {
146
+ const existing = existingByKey.get(`${op.tableName}\u0000${op.rowId}`);
147
+ if (existing) {
148
+ if (!(await writeRule(auth, existing))) {
149
+ throw new ForbiddenError(`Write denied on ${op.tableName}/${op.rowId}.`);
150
+ }
151
+ }
152
+ else if (op.operation === 'DELETE') {
153
+ if (!(await writeRule(auth, { id: op.rowId, ...payload }))) {
154
+ throw new ForbiddenError(`Delete denied on ${op.tableName}/${op.rowId}.`);
155
+ }
156
+ }
157
+ if (op.operation !== 'DELETE') {
158
+ if (!(await writeRule(auth, { id: op.rowId, ...payload }))) {
159
+ throw new ForbiddenError(`Write denied on ${op.tableName}/${op.rowId}.`);
160
+ }
161
+ }
162
+ }
163
+ cursor = Math.max(Date.now(), cursor + 1);
164
+ if (op.operation === 'DELETE') {
165
+ await setRowDeleted(tx, op.tableName, op.rowId, true, cursor);
166
+ }
167
+ else {
168
+ await upsertTableRow(tx, op.tableName, fields, op.rowId, payload, cursor);
169
+ existingByKey.set(`${op.tableName}\u0000${op.rowId}`, { id: op.rowId, ...payload });
170
+ }
171
+ await appendChangeLog(tx, op.tableName, op.rowId, cursor, this.changes);
172
+ const scope = payload[this.scopeField];
173
+ emitted.push({
174
+ scopeId: typeof scope === 'string' && scope ? scope : 'default',
175
+ tableName: op.tableName,
176
+ checkpoint: cursor,
177
+ });
178
+ successfulIds.push(op.id);
179
+ }
180
+ if (operations.length > 0) {
181
+ await commitClock(tx, cursor, this.clock);
182
+ }
183
+ });
184
+ for (const e of emitted)
185
+ this.broker?.publish(e);
186
+ return { applied: successfulIds.length, successfulIds, serverTime: Date.now(), cursor };
187
+ }
188
+ async getDeltas(tables, since, limit = 500, auth = { isAdmin: true }) {
189
+ const names = tables.length ? tables : this.tables;
190
+ for (const t of names)
191
+ this.fields(t);
192
+ const checkpoint = Number.isFinite(since) && since >= 0 ? Math.floor(since) : 0;
193
+ const safeLimit = Math.max(1, Math.min(2000, Math.floor(Number(limit) || 500)));
194
+ const empty = {
195
+ changes: { timestamp: checkpoint, changes: [] },
196
+ cursor: checkpoint,
197
+ hasMore: false,
198
+ serverTime: Date.now(),
199
+ };
200
+ if (!names.length)
201
+ return empty;
202
+ const raw = await this.db.query(`SELECT table_name, row_id, ${this.q('timestamp')} AS ts FROM ${this.q(this.changes)} ` +
203
+ `WHERE ${this.q('timestamp')} > ? AND table_name IN (${names.map(() => '?').join(', ')}) ` +
204
+ `ORDER BY ${this.q('timestamp')} ASC LIMIT ${safeLimit + 1}`, [checkpoint, ...names]);
205
+ const hasMore = raw.length > safeLimit;
206
+ const page = hasMore ? raw.slice(0, safeLimit) : raw;
207
+ if (!page.length)
208
+ return empty;
209
+ // Collapse repeated edits of one row to its latest change.
210
+ const latest = new Map();
211
+ for (const c of page) {
212
+ const key = `${c.table_name}\u0000${c.row_id}`;
213
+ latest.delete(key);
214
+ latest.set(key, { table: c.table_name, id: String(c.row_id), ts: Number(c.ts) });
215
+ }
216
+ const byTable = new Map();
217
+ for (const e of latest.values()) {
218
+ const ids = byTable.get(e.table) ?? [];
219
+ ids.push(e.id);
220
+ byTable.set(e.table, ids);
221
+ }
222
+ const rows = new Map();
223
+ for (const [table, ids] of byTable) {
224
+ for (let i = 0; i < ids.length; i += 400) {
225
+ const chunk = ids.slice(i, i + 400);
226
+ const found = await this.db.query(`SELECT * FROM ${this.q(table)} WHERE ${this.q('id')} IN (${chunk.map(() => '?').join(', ')})`, chunk);
227
+ for (const r of found)
228
+ rows.set(`${table}\u0000${r.id}`, r);
229
+ }
230
+ }
231
+ const allChanges = [...latest.values()].map((e) => {
232
+ const row = rows.get(`${e.table}\u0000${e.id}`);
233
+ const gone = !row || Boolean(row.deleted);
234
+ return {
235
+ tableName: e.table,
236
+ rowId: e.id,
237
+ operation: gone ? 'DELETE' : 'UPDATE',
238
+ payload: row ? fromDbRow(this.fields(e.table), row) : null,
239
+ timestamp: e.ts,
240
+ };
241
+ });
242
+ const changes = [];
243
+ for (const c of allChanges) {
244
+ const readRule = !auth.isAdmin ? this.rules[c.tableName]?.read : undefined;
245
+ if (!readRule) {
246
+ changes.push(c);
247
+ continue;
248
+ }
249
+ const subject = { id: c.rowId, ...(c.payload ?? { deleted: true }) };
250
+ if (await readRule(auth, subject))
251
+ changes.push(c);
252
+ }
253
+ const cursor = Number(page[page.length - 1].ts);
254
+ return {
255
+ changes: { timestamp: cursor, changes },
256
+ cursor,
257
+ hasMore,
258
+ serverTime: Date.now(),
259
+ };
260
+ }
261
+ }
package/docs/api.md ADDED
@@ -0,0 +1,181 @@
1
+ # HTTP & SSE API Reference
2
+
3
+ All JSON endpoints accept and return `application/json` (max body size: `6 MB`).
4
+
5
+ ## Authentication
6
+
7
+ Endpoints use one of three credentials:
8
+ - **Admin API Key:** `Authorization: Bearer <SERVER_API_KEY>` (full access, bypasses RLS).
9
+ - **User JWT** *(when `APP_SECRET` is set)*: `Authorization: Bearer <jwt>` (or `?token=<jwt>` for `EventSource` SSE routes). Subject to `src/rules.ts` RLS on `/sync`.
10
+ - **Admin Session Cookie:** `lls_admin_session` (HTTP-only cookie set by `POST /admin/login`).
11
+
12
+ ---
13
+
14
+ ## Health
15
+
16
+ ### `GET /health`
17
+ Public health check (no auth required).
18
+
19
+ **Response `200`:**
20
+ ```json
21
+ { "ok": true, "dialect": "mysql" }
22
+ ```
23
+
24
+ ---
25
+
26
+ ## Sync
27
+
28
+ ### `GET /sync?tables=notes&since=0&limit=500`
29
+ Pull delta changes after `since` (monotonic cursor). `limit` is clamped to `1..2000`.
30
+ **Auth:** Admin key or User JWT.
31
+
32
+ **Response `200`:**
33
+ ```json
34
+ {
35
+ "success": true,
36
+ "changes": {
37
+ "timestamp": 1732541000123,
38
+ "changes": [
39
+ {
40
+ "tableName": "notes",
41
+ "rowId": "n1",
42
+ "operation": "UPDATE",
43
+ "payload": { "title": "Hello", "deleted": false, "updated_at": 1732541000123 },
44
+ "timestamp": 1732541000123
45
+ }
46
+ ]
47
+ },
48
+ "cursor": 1732541000123,
49
+ "hasMore": false,
50
+ "serverTime": 1732541000500
51
+ }
52
+ ```
53
+
54
+ ### `POST /sync`
55
+ Push up to `1000` operations atomically.
56
+ **Auth:** Admin key or User JWT.
57
+
58
+ **Body:**
59
+ ```json
60
+ {
61
+ "operations": [
62
+ {
63
+ "id": "op-1",
64
+ "tableName": "notes",
65
+ "rowId": "n1",
66
+ "operation": "INSERT",
67
+ "payload": { "title": "Hello", "pinned": true },
68
+ "timestamp": 1732541000000
69
+ }
70
+ ]
71
+ }
72
+ ```
73
+ `operation` is `"INSERT" | "UPDATE" | "DELETE"`.
74
+
75
+ **Response `200`:**
76
+ ```json
77
+ {
78
+ "success": true,
79
+ "processed": 1,
80
+ "applied": 1,
81
+ "successfulIds": ["op-1"],
82
+ "serverTime": 1732541000500,
83
+ "cursor": 1732541000123
84
+ }
85
+ ```
86
+
87
+ ### `GET /sync/events?token=<key_or_jwt>&scopeId=<scope>`
88
+ Server-Sent Events (SSE) stream emitting change notifications whenever tables are modified.
89
+ **Auth:** Admin key or User JWT (header or `?token=`).
90
+
91
+ ---
92
+
93
+ ## Server Functions
94
+
95
+ ### `GET /fn`
96
+ List all loaded functions from `src/functions/` (or `functions/`).
97
+ **Auth:** Admin key, User JWT, or Admin cookie.
98
+
99
+ **Response `200`:**
100
+ ```json
101
+ {
102
+ "functions": [
103
+ { "name": "notes/list", "kind": "query" },
104
+ { "name": "notes/create", "kind": "mutation" }
105
+ ]
106
+ }
107
+ ```
108
+
109
+ ### `POST /fn/:module/:name`
110
+ Invoke a `query`, `mutation`, or `action`.
111
+ **Auth:** Admin key, User JWT, or Admin cookie.
112
+
113
+ **Body:** `{ "args": { ... } }` (or pass args at the top level).
114
+ **Response `200`:**
115
+ ```json
116
+ { "success": true, "result": ... }
117
+ ```
118
+
119
+ ### `GET /subscribe/:module/:name?args={}&token=<key_or_jwt>`
120
+ Reactive SSE stream for a `query` function. Sends an initial `event: data` frame, then re-runs and pushes updated `event: data` frames whenever any table read by the query changes.
121
+ **Auth:** Admin key, User JWT, or Admin cookie (`?token=` supported for `EventSource`).
122
+
123
+ ---
124
+
125
+ ## User Authentication (`/auth/*`)
126
+
127
+ Requires `APP_SECRET` to be set (otherwise returns `503`). Rate-limited to **20 requests / minute per IP**.
128
+
129
+ - **`POST /auth/signup`**: `{ "mode": "signup", "email", "password", "displayName"? }` → `200 { token, user }`
130
+ - **`POST /auth/signin`**: `{ "mode": "signin", "email", "password" }` → `200 { token, user }`
131
+ - **`POST /auth/refresh`**: `Authorization: Bearer <token>` → `200 { token }`
132
+ - **`POST /auth/forgot-password`**: `{ "email" }` → `200 { ok: true }` (sends 6-digit OTP via SMTP)
133
+ - **`POST /auth/reset-password`**: `{ "email", "otp", "newPassword" }` → `200 { success: true }`
134
+
135
+ ---
136
+
137
+ ## File Storage (`/storage/*` & `/public/files/*`)
138
+
139
+ Backed by `UPLOAD_DIR`, `_lls_storage_buckets`, and `_lls_storage_files`.
140
+
141
+ - **`POST /storage/upload`**: `multipart/form-data` with `bucket` and `file` → `200 { key, bucket, visibility, remoteUrl }`
142
+ - **`GET /storage/files/:bucket/:key`**: Download file (requires auth or valid signed `?token=` for private buckets)
143
+ - **`GET /public/files/:bucket/:key`**: Direct read for `public` buckets (no auth required)
144
+ - **`POST /storage/sign`**: `{ "key", "bucket"?, "expiresInMs"? }` → `200 { url, expiresAt }`
145
+ - **`DELETE /storage/files/:bucket/:key`**: Delete file
146
+ - **`GET / POST / DELETE /storage/buckets`**: List, create (`{ "name", "visibility": "public" | "private" }`), or delete empty buckets
147
+
148
+ ---
149
+
150
+ ## Admin Console API (`/admin/*`)
151
+
152
+ Protected by Admin session cookie (`lls_admin_session`) or `Authorization: Bearer <SERVER_API_KEY>` (except `/admin/login` and static UI assets).
153
+
154
+ | Endpoint | Methods | Purpose |
155
+ |---|---|---|
156
+ | `/admin/login` | `GET`, `POST` | Check session/bootstrap status; sign in or bootstrap first `super_admin` |
157
+ | `/admin/logout` | `POST` | Clear session cookie (`?all=1` revokes all sessions) |
158
+ | `/admin/overview` | `GET` | Health, table counts, account/backup counts, console role |
159
+ | `/admin/endpoints` | `GET` | Registered HTTP & function routes |
160
+ | `/admin/table` | `GET`, `POST`, `PATCH`, `DELETE` | Paginated row browser & CRUD |
161
+ | `/admin/users` | `GET`, `POST` | List accounts; unlock, revoke sessions, or set console role |
162
+ | `/admin/logs` | `GET` | Paginated `_server_changes` log |
163
+ | `/admin/env` | `GET`, `POST`, `DELETE` | DB-backed environment variables (including `action: "reveal"`) |
164
+ | `/admin/backups` | `GET`, `POST`, `DELETE` | List, download (`?file=`), create, or delete JSON backups |
165
+ | `/admin/storage` | `GET`, `POST`, `DELETE` | Admin storage browser & bucket management |
166
+ | `/admin/crons` | `GET`, `POST`, `DELETE` | Manage schedules, run jobs (`{ job_key }`), or prune orphans |
167
+ | `/admin/settings` | `GET`, `POST` | Runtime info, `test_health`, `apply_schema`, `test_email` |
168
+
169
+ ---
170
+
171
+ ## Standard Error Codes
172
+
173
+ | Status | Meaning |
174
+ |---|---|
175
+ | `400` | Invalid JSON, unknown table/column, or validation error |
176
+ | `401` | Missing or invalid token / session |
177
+ | `403` | Rejected by `src/rules.ts` RLS policy or invalid bootstrap secret |
178
+ | `404` | Unknown function, bucket, or file |
179
+ | `413` | Request body exceeds `6 MB` |
180
+ | `429` | Rate limit exceeded (`Retry-After` header included) |
181
+ | `503` | Database unavailable or `/auth` disabled (`APP_SECRET` unset) |
@@ -0,0 +1,104 @@
1
+ # Client Usage & Authentication
2
+
3
+ ## 1. Local-First Sync (`local-lite/self-hosted`)
4
+
5
+ Point `SelfHostedRemoteAdapter` at your server's `/sync` endpoint:
6
+
7
+ ```ts
8
+ import { LocalFirstClient } from 'local-lite/core';
9
+ import { SelfHostedRemoteAdapter } from 'local-lite/self-hosted';
10
+
11
+ const remote = new SelfHostedRemoteAdapter({
12
+ url: 'https://api.yourdomain.com/sync',
13
+ token: userJwtOrApiKey,
14
+ tables: ['notes'],
15
+ pollIntervalMs: 5000,
16
+ });
17
+
18
+ const client = new LocalFirstClient({
19
+ local: mySqliteAdapter,
20
+ remote,
21
+ });
22
+
23
+ await client.initialize();
24
+ client.syncWorker.start();
25
+ ```
26
+
27
+ ### Realtime Sync Events (SSE)
28
+
29
+ Listen for change notifications on `/sync/events`:
30
+
31
+ ```ts
32
+ const es = new EventSource(
33
+ `https://api.yourdomain.com/sync/events?token=${encodeURIComponent(token)}`
34
+ );
35
+ es.onmessage = () => {
36
+ void client.syncWorker.pullRemoteChanges();
37
+ };
38
+ ```
39
+
40
+ ## 2. User Accounts (`/auth/*`)
41
+
42
+ Set `APP_SECRET` in `.env` to enable user accounts (rate-limited to 20 requests/min per IP):
43
+
44
+ - **Sign Up:**
45
+ ```http
46
+ POST /auth/signup
47
+ Content-Type: application/json
48
+
49
+ { "mode": "signup", "email": "user@example.com", "password": "strongpassword", "displayName": "Alex" }
50
+ ```
51
+ Returns `{ token, user }`.
52
+ - **Sign In:**
53
+ ```http
54
+ POST /auth/signin
55
+ Content-Type: application/json
56
+
57
+ { "mode": "signin", "email": "user@example.com", "password": "strongpassword" }
58
+ ```
59
+ - **Refresh Token:** `POST /auth/refresh` with `Authorization: Bearer <token>`
60
+ - **Password Reset (6-digit Email OTP, requires `SMTP_*`):**
61
+ 1. `POST /auth/forgot-password` with `{ "email": "user@example.com" }`
62
+ 2. `POST /auth/reset-password` with `{ "email": "user@example.com", "otp": "123456", "newPassword": "newpassword" }`
63
+
64
+ ## 3. Typed Client SDK (`codegen`)
65
+
66
+ Generate a zero-dependency TypeScript client from your `schema.ts` and `functions/` directly into your frontend or mobile app:
67
+
68
+ ```bash
69
+ npx local-lite-server codegen --out ../my-frontend/src/api.ts
70
+ ```
71
+
72
+ Then import and use `createClient`:
73
+
74
+ ```ts
75
+ import { createClient, type NotesRow } from './api';
76
+
77
+ const api = createClient({
78
+ url: 'https://api.yourdomain.com',
79
+ getToken: () => localStorage.getItem('token'),
80
+ });
81
+
82
+ // Query & mutation
83
+ const notes = await api.notes.list<NotesRow[]>();
84
+ await api.notes.create({ title: 'My Note', pinned: true });
85
+
86
+ // Live SSE subscription
87
+ const unsubscribe = api.notes.subscribeList<NotesRow[]>({}, (liveNotes) => {
88
+ console.log('Notes updated:', liveNotes);
89
+ });
90
+ ```
91
+
92
+ Or call `/fn/:module/:name` directly with `fetch`:
93
+
94
+ ```ts
95
+ const res = await fetch('https://api.yourdomain.com/fn/notes/create', {
96
+ method: 'POST',
97
+ headers: {
98
+ 'Content-Type': 'application/json',
99
+ Authorization: `Bearer ${token}`,
100
+ },
101
+ body: JSON.stringify({ args: { title: 'My Note', pinned: true } }),
102
+ });
103
+ const { result } = await res.json();
104
+ ```
package/docs/cpanel.md ADDED
@@ -0,0 +1,63 @@
1
+ # Deploying on cPanel
2
+
3
+ No Docker, and no `npm install` on the server: `dist/cpanel/` is a self-contained, code-split ESM bundle.
4
+
5
+ ## 1. Create the database
6
+ cPanel → **MySQL® Databases**
7
+ 1. Create a database and a user, then add the user to the database with **ALL PRIVILEGES**.
8
+ 2. Note the full names (cPanel prefixes them, e.g. `acct_mydb`, `acct_user`).
9
+
10
+ ## 2. Upload
11
+ Upload everything in `dist/cpanel/` to a directory **outside** `public_html`, e.g. `~/local-lite-server/`:
12
+ `app.mjs`, `chunks/`, `admin-ui/`, `schema.ts`, `functions/`, `.env.example`.
13
+
14
+ ## 3. Create the Node.js app
15
+ cPanel → **Setup Node.js App** → **Create Application**
16
+ | Field | Value |
17
+ |---|---|
18
+ | Node.js version | **24** or newer |
19
+ | Application mode | Production |
20
+ | Application root | `local-lite-server` |
21
+ | Application URL | e.g. `api.yourdomain.com` |
22
+ | Application startup file | `app.mjs` |
23
+
24
+ ## 4. Environment variables
25
+ Add these in the same screen (**Environment variables**):
26
+
27
+ | Name | Value |
28
+ |---|---|
29
+ | `DB_DIALECT` | `mysql` |
30
+ | `DB_HOST` | `localhost` |
31
+ | `DB_USER` / `DB_PASSWORD` / `DB_NAME` | from step 1 |
32
+ | `SERVER_API_KEY` | long random string |
33
+ | `APP_SECRET` | another long random string (enables accounts) |
34
+ | `AUTO_MIGRATE` | `true` |
35
+ | `CORS_ORIGINS` | your app's origin(s), or `*` |
36
+
37
+ Optional: `SMTP_*` for password-reset emails, `ADMIN_UI=false` to hide `/admin`.
38
+ You can alternatively upload a `.env` file; do not put it in a web-served directory.
39
+
40
+ ## 5. Your tables
41
+ Edit `schema.ts` (see the example), upload it, and **Restart** the app.
42
+ With `AUTO_MIGRATE=true`, new tables and columns are created on boot. Nothing is ever dropped.
43
+
44
+ ## 6. Verify
45
+ - `https://api.yourdomain.com/health` → `{"ok":true,...}`
46
+ - `https://api.yourdomain.com/admin` → enter `SERVER_API_KEY` to see status and rows.
47
+
48
+ ## Notes
49
+ - **Realtime:** `/sync/events` (SSE) works, but shared hosts may close idle connections. Clients should keep polling as a fallback.
50
+ - **Logs:** cPanel shows stderr in the app's log file (`stderr.log` in the app root).
51
+ - **Limits:** keep `DB_POOL_SIZE` small (default 5) on shared hosting.
52
+ - **Updating:** upload the new `app.cjs`, then Restart.
53
+
54
+ ## Using it from a client
55
+ ```ts
56
+ import { SelfHostedRemoteAdapter } from 'local-lite/self-hosted';
57
+ const remote = new SelfHostedRemoteAdapter({
58
+ url: 'https://api.yourdomain.com/sync',
59
+ token: userToken, // from POST /auth/signin, or SERVER_API_KEY for trusted servers
60
+ tables: ['notes'],
61
+ });
62
+ ```
63
+ Account endpoints (POST JSON): `/auth/signin` and `/auth/signup` (with `{ "mode": "signup", "email", "password" }`), `/auth/refresh`, `/auth/forgot-password`, `/auth/reset-password`.
@@ -0,0 +1,78 @@
1
+ # Server Functions & Reactive Queries
2
+
3
+ Place TypeScript or JavaScript modules in `functions/` (or set `FUNCTIONS_DIR`). Each exported function with `__kind: 'query' | 'mutation' | 'action'` is automatically registered as `<filename>/<exportName>`.
4
+
5
+ ## Writing Functions
6
+
7
+ Using `import type` keeps functions compatible with both local development and the zero-`node_modules` cPanel bundle:
8
+
9
+ ```ts
10
+ // functions/notes.ts
11
+ import type { ActionContext, MutationContext, QueryContext } from '../src/index.js';
12
+
13
+ function badRequest(message: string, status = 400): Error {
14
+ return Object.assign(new Error(message), { status });
15
+ }
16
+
17
+ export const list = {
18
+ __kind: 'query' as const,
19
+ handler: ({ db }: QueryContext) =>
20
+ db.list('notes', {
21
+ where: { pinned: true },
22
+ orderBy: 'updated_at',
23
+ order: 'desc',
24
+ limit: 50,
25
+ }),
26
+ };
27
+
28
+ export const create = {
29
+ __kind: 'mutation' as const,
30
+ args: (raw: Record<string, unknown>) => {
31
+ const title = typeof raw.title === 'string' ? raw.title.trim() : '';
32
+ if (!title) throw badRequest('title is required.');
33
+ return { title, body: typeof raw.body === 'string' ? raw.body : null, pinned: false };
34
+ },
35
+ handler: ({ db }: MutationContext, args: { title: string; body: string | null; pinned: boolean }) =>
36
+ db.insert('notes', args),
37
+ };
38
+
39
+ export const summary = {
40
+ __kind: 'action' as const,
41
+ handler: async (ctx: ActionContext) => {
42
+ const notes = await ctx.runQuery<any[]>('notes/list');
43
+ return { count: notes.length };
44
+ },
45
+ };
46
+ ```
47
+
48
+ > **Note:** In `npm run dev`, edits to `functions/` hot-reload in place without dropping open SSE connections.
49
+
50
+ ## Context API
51
+
52
+ - **`ctx.auth`**: `{ isAdmin: boolean; userId?: string }`
53
+ - **`ctx.db.get(table, id)`**: Fetch a single non-deleted row (tracks `table` for reactive subscriptions).
54
+ - **`ctx.db.list(table, { where?, orderBy?, order?, limit?, offset?, includeDeleted? })`**: Query rows (tracks `table`).
55
+ - **`ctx.db.sql(query, params?, touchesTables?)`**: Raw SQL escape hatch.
56
+ - **`ctx.db.insert(table, data)`** *(mutations only)*: Inserts row inside a transaction, updates `_server_sync_clock` & `_server_changes`, and notifies subscribers.
57
+ - **`ctx.db.patch(table, id, patch)`** *(mutations only)*: Updates fields inside a transaction and emits change events.
58
+ - **`ctx.db.remove(table, id)`** *(mutations only)*: Soft-deletes (`deleted = true/1`) inside a transaction and emits change events.
59
+
60
+ ## HTTP & SSE Endpoints
61
+
62
+ All `/fn` and `/subscribe` endpoints accept `Authorization: Bearer <SERVER_API_KEY_or_user_JWT>` (or `?token=` for `EventSource`), plus Admin Console cookies.
63
+
64
+ - **List functions:** `GET /fn`
65
+ - **Invoke function:** `POST /fn/:module/:name` with body `{ "args": { ... } }`
66
+ - **Reactive query subscription (SSE):**
67
+ ```js
68
+ const es = new EventSource(
69
+ 'https://api.yourdomain.com/subscribe/notes/list?token=' + encodeURIComponent(token) + '&args=' + encodeURIComponent('{}')
70
+ );
71
+ es.addEventListener('data', (ev) => {
72
+ const rows = JSON.parse(ev.data);
73
+ console.log('Live update:', rows);
74
+ });
75
+ ```
76
+ Whenever any mutation or `/sync` operation modifies a table that the query read, the server re-runs the query and pushes a new `event: data` frame if the JSON output changed.
77
+
78
+ > **Note:** Reactive invalidation is **table-level** and backed by standard SQL transactions.