@eutobias/serenojs 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 (158) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +682 -2
  3. package/admin-dist/assets/index-B3EgqtT6.js +9 -0
  4. package/admin-dist/assets/index-D2m0Eb4k.css +2 -0
  5. package/admin-dist/index.html +17 -0
  6. package/dist/auth/auth.server.d.ts +31 -0
  7. package/dist/auth/auth.server.js +141 -0
  8. package/dist/auth/config.d.ts +32 -0
  9. package/dist/auth/config.js +25 -0
  10. package/dist/auth/cookies.server.d.ts +7 -0
  11. package/dist/auth/cookies.server.js +65 -0
  12. package/dist/auth/http.server.d.ts +8 -0
  13. package/dist/auth/http.server.js +30 -0
  14. package/dist/auth/password.server.d.ts +2 -0
  15. package/dist/auth/password.server.js +21 -0
  16. package/dist/auth/session.server.d.ts +2 -0
  17. package/dist/auth/session.server.js +14 -0
  18. package/dist/auth/users.server.d.ts +16 -0
  19. package/dist/auth/users.server.js +123 -0
  20. package/dist/config.d.ts +91 -0
  21. package/dist/config.js +39 -0
  22. package/dist/core/backup.server.d.ts +52 -0
  23. package/dist/core/backup.server.js +349 -0
  24. package/dist/core/db.server.d.ts +24 -0
  25. package/dist/core/db.server.js +526 -0
  26. package/dist/core/media.d.ts +22 -0
  27. package/dist/core/media.js +76 -0
  28. package/dist/core/media.server.d.ts +18 -0
  29. package/dist/core/media.server.js +102 -0
  30. package/dist/core/schema.d.ts +26 -0
  31. package/dist/core/schema.js +99 -0
  32. package/dist/core/types.d.ts +143 -0
  33. package/dist/core/types.js +1 -0
  34. package/dist/core/validation.d.ts +16 -0
  35. package/dist/core/validation.js +192 -0
  36. package/dist/locale.d.ts +2 -0
  37. package/dist/locale.js +14 -0
  38. package/dist/runtime.d.ts +8 -0
  39. package/dist/runtime.js +37 -0
  40. package/dist/server/app.d.ts +20 -0
  41. package/dist/server/app.js +661 -0
  42. package/dist/ui/admin/admin-shell.d.ts +16 -0
  43. package/dist/ui/admin/admin-shell.js +38 -0
  44. package/dist/ui/admin/backup-manager.d.ts +5 -0
  45. package/dist/ui/admin/backup-manager.js +165 -0
  46. package/dist/ui/admin/collection-icon.d.ts +22 -0
  47. package/dist/ui/admin/collection-icon.js +34 -0
  48. package/dist/ui/admin/collection-manager.d.ts +7 -0
  49. package/dist/ui/admin/collection-manager.js +212 -0
  50. package/dist/ui/admin/display.d.ts +7 -0
  51. package/dist/ui/admin/display.js +65 -0
  52. package/dist/ui/admin/field-control.d.ts +14 -0
  53. package/dist/ui/admin/field-control.js +58 -0
  54. package/dist/ui/admin/i18n.d.ts +27 -0
  55. package/dist/ui/admin/i18n.js +324 -0
  56. package/dist/ui/admin/item-form.d.ts +20 -0
  57. package/dist/ui/admin/item-form.js +60 -0
  58. package/dist/ui/admin/list-control.d.ts +13 -0
  59. package/dist/ui/admin/list-control.js +31 -0
  60. package/dist/ui/admin/locales.d.ts +4 -0
  61. package/dist/ui/admin/locales.js +8 -0
  62. package/dist/ui/admin/login-form.d.ts +3 -0
  63. package/dist/ui/admin/login-form.js +52 -0
  64. package/dist/ui/admin/media-control.d.ts +14 -0
  65. package/dist/ui/admin/media-control.js +74 -0
  66. package/dist/ui/admin/media-list-control.d.ts +14 -0
  67. package/dist/ui/admin/media-list-control.js +91 -0
  68. package/dist/ui/admin/pagination.d.ts +11 -0
  69. package/dist/ui/admin/pagination.js +14 -0
  70. package/dist/ui/admin/relation-control.d.ts +14 -0
  71. package/dist/ui/admin/relation-control.js +33 -0
  72. package/dist/ui/admin/router.d.ts +17 -0
  73. package/dist/ui/admin/router.js +58 -0
  74. package/dist/ui/admin/runtime.d.ts +28 -0
  75. package/dist/ui/admin/runtime.js +29 -0
  76. package/dist/ui/admin/sidebar.d.ts +13 -0
  77. package/dist/ui/admin/sidebar.js +29 -0
  78. package/dist/ui/admin/standalone-manager.d.ts +11 -0
  79. package/dist/ui/admin/standalone-manager.js +51 -0
  80. package/dist/ui/admin/table.d.ts +21 -0
  81. package/dist/ui/admin/table.js +23 -0
  82. package/dist/ui/admin/toast.d.ts +16 -0
  83. package/dist/ui/admin/toast.js +59 -0
  84. package/dist/ui/admin/users-manager.d.ts +6 -0
  85. package/dist/ui/admin/users-manager.js +157 -0
  86. package/dist/ui/badge.d.ts +9 -0
  87. package/dist/ui/badge.js +14 -0
  88. package/dist/ui/box.d.ts +17 -0
  89. package/dist/ui/box.js +14 -0
  90. package/dist/ui/button.d.ts +25 -0
  91. package/dist/ui/button.js +28 -0
  92. package/dist/ui/card.d.ts +45 -0
  93. package/dist/ui/card.js +49 -0
  94. package/dist/ui/container.d.ts +13 -0
  95. package/dist/ui/container.js +13 -0
  96. package/dist/ui/drawer.d.ts +15 -0
  97. package/dist/ui/drawer.js +31 -0
  98. package/dist/ui/field-wrapper.d.ts +15 -0
  99. package/dist/ui/field-wrapper.js +11 -0
  100. package/dist/ui/index.d.ts +8 -0
  101. package/dist/ui/index.js +8 -0
  102. package/dist/ui/text.d.ts +19 -0
  103. package/dist/ui/text.js +40 -0
  104. package/package.json +81 -3
  105. package/src/admin/app.tsx +371 -0
  106. package/src/admin/index.html +16 -0
  107. package/src/admin/main.tsx +42 -0
  108. package/src/admin/styles.css +9 -0
  109. package/src/auth/auth.server.ts +203 -0
  110. package/src/auth/config.ts +46 -0
  111. package/src/auth/cookies.server.ts +84 -0
  112. package/src/auth/http.server.ts +32 -0
  113. package/src/auth/password.server.ts +25 -0
  114. package/src/auth/session.server.ts +16 -0
  115. package/src/auth/users.server.ts +159 -0
  116. package/src/config.ts +120 -0
  117. package/src/core/backup.server.ts +446 -0
  118. package/src/core/db.server.ts +685 -0
  119. package/src/core/media.server.ts +136 -0
  120. package/src/core/media.ts +91 -0
  121. package/src/core/schema.ts +126 -0
  122. package/src/core/types.ts +194 -0
  123. package/src/core/validation.ts +215 -0
  124. package/src/global.d.ts +1 -0
  125. package/src/locale.ts +16 -0
  126. package/src/runtime.ts +54 -0
  127. package/src/server/app.ts +737 -0
  128. package/src/ui/admin/admin-shell.tsx +106 -0
  129. package/src/ui/admin/backup-manager.tsx +327 -0
  130. package/src/ui/admin/collection-icon.tsx +69 -0
  131. package/src/ui/admin/collection-manager.tsx +408 -0
  132. package/src/ui/admin/display.tsx +138 -0
  133. package/src/ui/admin/field-control.tsx +214 -0
  134. package/src/ui/admin/i18n.tsx +401 -0
  135. package/src/ui/admin/item-form.tsx +200 -0
  136. package/src/ui/admin/list-control.tsx +121 -0
  137. package/src/ui/admin/locales.ts +12 -0
  138. package/src/ui/admin/login-form.tsx +98 -0
  139. package/src/ui/admin/media-control.tsx +161 -0
  140. package/src/ui/admin/media-list-control.tsx +242 -0
  141. package/src/ui/admin/pagination.tsx +58 -0
  142. package/src/ui/admin/relation-control.tsx +142 -0
  143. package/src/ui/admin/router.tsx +105 -0
  144. package/src/ui/admin/runtime.tsx +58 -0
  145. package/src/ui/admin/sidebar.tsx +178 -0
  146. package/src/ui/admin/standalone-manager.tsx +103 -0
  147. package/src/ui/admin/table.tsx +129 -0
  148. package/src/ui/admin/toast.tsx +126 -0
  149. package/src/ui/admin/users-manager.tsx +344 -0
  150. package/src/ui/badge.tsx +27 -0
  151. package/src/ui/box.tsx +33 -0
  152. package/src/ui/button.tsx +77 -0
  153. package/src/ui/card.tsx +92 -0
  154. package/src/ui/container.tsx +28 -0
  155. package/src/ui/drawer.tsx +104 -0
  156. package/src/ui/field-wrapper.tsx +54 -0
  157. package/src/ui/index.ts +8 -0
  158. package/src/ui/text.tsx +93 -0
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Public configuration surface of the CMS package.
3
+ *
4
+ * `serenojs.config.ts` in the host project is the single source of truth for
5
+ * collections, locales and every mount path. Nothing inside the package may
6
+ * import host code (`@/schemas`) directly — everything is read through
7
+ * `runtime.ts`, configured once by `createCmsMiddleware`.
8
+ */
9
+ import type { CollectionDef, CollectionIconName, FieldDef, FieldValue, Item, ListResult, MediaItem, RelationOptionsMap } from "./core/types.js";
10
+ export type { CollectionDef, CollectionIconName, FieldDef, FieldValue, Item, ListResult, MediaItem, RelationOptionsMap };
11
+ /** A locale known to the admin UI. */
12
+ export type LocaleDef = {
13
+ code: string;
14
+ label: string;
15
+ };
16
+ export type CmsAdminOptions = {
17
+ /** Mount path for the admin SPA. Default: `/admin`. */
18
+ path?: string;
19
+ /** When `false`, the admin SPA and its assets answer `404`. */
20
+ enabled?: boolean;
21
+ /** Emit `X-Robots-Tag: noindex, nofollow` on admin responses. */
22
+ noindex?: boolean;
23
+ };
24
+ export type CmsConfig = {
25
+ /** Title shown in the admin UI. */
26
+ title?: string;
27
+ collections: CollectionDef[];
28
+ /** Locale registry shown in the admin tabs. */
29
+ locales?: LocaleDef[];
30
+ /** Fallback locale. Default: `pt`. */
31
+ defaultLocale?: string;
32
+ admin?: CmsAdminOptions;
33
+ api?: {
34
+ path?: string;
35
+ };
36
+ auth?: {
37
+ path?: string;
38
+ };
39
+ media?: {
40
+ path?: string;
41
+ };
42
+ files?: {
43
+ path?: string;
44
+ };
45
+ backup?: {
46
+ path?: string;
47
+ enabled?: boolean;
48
+ intervalHours?: number;
49
+ keep?: number;
50
+ };
51
+ db?: {
52
+ path?: string;
53
+ };
54
+ };
55
+ export type ResolvedCmsConfig = {
56
+ title: string;
57
+ collections: CollectionDef[];
58
+ locales: LocaleDef[];
59
+ defaultLocale: string;
60
+ admin: {
61
+ path: string;
62
+ enabled: boolean;
63
+ noindex: boolean;
64
+ };
65
+ api: {
66
+ path: string;
67
+ };
68
+ auth: {
69
+ path: string;
70
+ };
71
+ media: {
72
+ path: string;
73
+ };
74
+ files: {
75
+ path: string;
76
+ };
77
+ backup: {
78
+ path: string;
79
+ enabled: boolean;
80
+ intervalHours: number;
81
+ keep: number;
82
+ };
83
+ db: {
84
+ path: string;
85
+ };
86
+ };
87
+ export declare const DEFAULT_LOCALES: LocaleDef[];
88
+ /** Normalize a user-supplied config into the shape used at runtime. */
89
+ export declare function resolveCmsConfig(config: CmsConfig): ResolvedCmsConfig;
90
+ /** Identity helper for editor autocomplete in `serenojs.config.ts`. */
91
+ export declare function defineCmsConfig(config: CmsConfig): CmsConfig;
package/dist/config.js ADDED
@@ -0,0 +1,39 @@
1
+ export const DEFAULT_LOCALES = [
2
+ { code: "pt", label: "Português" },
3
+ { code: "en", label: "English" },
4
+ ];
5
+ function mount(value, fallback) {
6
+ const raw = (value ?? fallback).trim() || fallback;
7
+ const withSlash = raw.startsWith("/") ? raw : `/${raw}`;
8
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
9
+ }
10
+ /** Normalize a user-supplied config into the shape used at runtime. */
11
+ export function resolveCmsConfig(config) {
12
+ const locales = config.locales && config.locales.length > 0 ? config.locales : DEFAULT_LOCALES;
13
+ return {
14
+ title: config.title ?? "SerenoJS",
15
+ collections: config.collections,
16
+ locales,
17
+ defaultLocale: config.defaultLocale ?? "pt",
18
+ admin: {
19
+ path: mount(config.admin?.path, "/admin"),
20
+ enabled: config.admin?.enabled !== false,
21
+ noindex: config.admin?.noindex !== false,
22
+ },
23
+ api: { path: mount(config.api?.path, "/api") },
24
+ auth: { path: mount(config.auth?.path, "/auth") },
25
+ media: { path: mount(config.media?.path, "/media") },
26
+ files: { path: mount(config.files?.path, "/files") },
27
+ backup: {
28
+ path: mount(config.backup?.path, "/backup"),
29
+ enabled: config.backup?.enabled !== false,
30
+ intervalHours: config.backup?.intervalHours ?? 24,
31
+ keep: config.backup?.keep ?? 10,
32
+ },
33
+ db: { path: config.db?.path ?? ".data/admin.db" },
34
+ };
35
+ }
36
+ /** Identity helper for editor autocomplete in `serenojs.config.ts`. */
37
+ export function defineCmsConfig(config) {
38
+ return config;
39
+ }
@@ -0,0 +1,52 @@
1
+ export declare const BACKUP_FORMAT = "serenojs-backup";
2
+ export declare const BACKUP_VERSION = 1;
3
+ export declare const BACKUP_EXTENSION = ".serenojs";
4
+ export declare const BACKUP_DIR: string;
5
+ export declare const PUBLIC_DIR: string;
6
+ export declare class BackupError extends Error {
7
+ status: number;
8
+ constructor(message: string, status?: number);
9
+ }
10
+ export type BackupInfo = {
11
+ name: string;
12
+ size: number;
13
+ createdAt: string;
14
+ /** Number of bundled assets, or `null` when unknown (list view). */
15
+ assets: number | null;
16
+ };
17
+ export type BackupManifest = {
18
+ format: string;
19
+ version: number;
20
+ createdAt: string;
21
+ databaseBytes: number;
22
+ assets: number;
23
+ };
24
+ /** Create an in-memory backup archive (gzip). */
25
+ export declare function createBackupBuffer(): Buffer;
26
+ /** Create a backup and persist it under `.data/backups`. Returns its metadata. */
27
+ export declare function createBackup(): BackupInfo;
28
+ /** List stored backups, newest first. */
29
+ export declare function listBackups(): BackupInfo[];
30
+ /** Read a stored backup into memory. */
31
+ export declare function readBackup(name: string): {
32
+ info: BackupInfo;
33
+ buffer: Buffer;
34
+ };
35
+ /** Delete a stored backup. Returns true when a file was removed. */
36
+ export declare function deleteBackup(name: string): boolean;
37
+ /** Keep only the `keep` most recent backups. */
38
+ export declare function pruneBackups(keep: number): number;
39
+ /**
40
+ * Restore a backup archive.
41
+ *
42
+ * Instead of replacing the SQLite file on disk (which conflicts with the live
43
+ * connection and any duplicated module instances), the uploaded database is
44
+ * attached and its tables are copied into the running database inside a single
45
+ * transaction. Bundled assets are rewritten to `public/`.
46
+ */
47
+ export declare function restoreBackup(buffer: Buffer): BackupManifest;
48
+ /**
49
+ * Start the periodic backup routine. Idempotent: safe to call on every request
50
+ * or module load, only the first call schedules anything.
51
+ */
52
+ export declare function startBackupScheduler(): void;
@@ -0,0 +1,349 @@
1
+ /**
2
+ * Database + uploaded-assets backup and restore.
3
+ *
4
+ * A backup is a single gzip-compressed JSON archive (`<name>.serenojs`) that
5
+ * bundles:
6
+ * - a consistent SQLite snapshot of `.data/admin.db` (via `VACUUM INTO`),
7
+ * - every file under `public/images` (committed assets) and `public/files`
8
+ * (runtime uploads), stored as base64.
9
+ *
10
+ * The module also runs a lightweight scheduler that drops a fresh backup into
11
+ * `.data/backups` on startup (when overdue) and then every N hours.
12
+ *
13
+ * Server-only: reads/writes the filesystem and talks to the DB layer.
14
+ */
15
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join, relative, resolve, sep } from "node:path";
18
+ import { gunzipSync, gzipSync } from "node:zlib";
19
+ import { getDb } from "./db.server.js";
20
+ import { getCmsConfig } from "../runtime.js";
21
+ export const BACKUP_FORMAT = "serenojs-backup";
22
+ export const BACKUP_VERSION = 1;
23
+ export const BACKUP_EXTENSION = ".serenojs";
24
+ export const BACKUP_DIR = resolve(process.cwd(), ".data/backups");
25
+ export const PUBLIC_DIR = resolve(process.cwd(), "public");
26
+ /** Directories (relative to `public/`) included in a backup. */
27
+ const ASSET_DIRS = ["images", "files"];
28
+ const SQLITE_MAGIC = "SQLite format 3\u0000";
29
+ export class BackupError extends Error {
30
+ status;
31
+ constructor(message, status = 422) {
32
+ super(message);
33
+ this.status = status;
34
+ }
35
+ }
36
+ const NAME_RE = /^[a-zA-Z0-9._-]+\.serenojs$/;
37
+ function nowStamp() {
38
+ return new Date().toISOString().replace(/[:.]/g, "-");
39
+ }
40
+ function ensureDir(dir) {
41
+ mkdirSync(dir, { recursive: true });
42
+ }
43
+ /** Recursively collect files under `dir`, keyed by their path relative to `base`. */
44
+ function collectFiles(dir, base, out) {
45
+ if (!existsSync(dir))
46
+ return;
47
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
48
+ const full = join(dir, entry.name);
49
+ if (entry.isDirectory()) {
50
+ collectFiles(full, base, out);
51
+ }
52
+ else if (entry.isFile()) {
53
+ const rel = relative(base, full).split(sep).join("/");
54
+ out.set(rel, full);
55
+ }
56
+ }
57
+ }
58
+ /** Consistent snapshot of the live database file. */
59
+ function snapshotDatabase() {
60
+ const db = getDb();
61
+ const tmp = join(tmpdir(), `serenojs-${Date.now()}-${Math.random().toString(16).slice(2)}.db`);
62
+ try {
63
+ // `VACUUM INTO` writes a transactionally consistent copy, WAL included.
64
+ db.exec(`VACUUM INTO '${tmp.replace(/'/g, "''")}'`);
65
+ return readFileSync(tmp);
66
+ }
67
+ finally {
68
+ rmSync(tmp, { force: true });
69
+ }
70
+ }
71
+ /** Build the raw (uncompressed) `.serenojs` payload. */
72
+ function buildPayload() {
73
+ const database = snapshotDatabase();
74
+ const files = new Map();
75
+ for (const dir of ASSET_DIRS) {
76
+ collectFiles(join(PUBLIC_DIR, dir), PUBLIC_DIR, files);
77
+ }
78
+ const assets = [];
79
+ for (const [path, full] of files) {
80
+ assets.push({ path, data: readFileSync(full).toString("base64") });
81
+ }
82
+ assets.sort((a, b) => a.path.localeCompare(b.path));
83
+ return {
84
+ format: BACKUP_FORMAT,
85
+ version: BACKUP_VERSION,
86
+ createdAt: new Date().toISOString(),
87
+ database: database.toString("base64"),
88
+ assets,
89
+ };
90
+ }
91
+ /** Create an in-memory backup archive (gzip). */
92
+ export function createBackupBuffer() {
93
+ return gzipSync(Buffer.from(JSON.stringify(buildPayload()), "utf8"));
94
+ }
95
+ /** Create a backup and persist it under `.data/backups`. Returns its metadata. */
96
+ export function createBackup() {
97
+ ensureDir(BACKUP_DIR);
98
+ const name = `backup-${nowStamp()}-${Math.random().toString(16).slice(2, 8)}${BACKUP_EXTENSION}`;
99
+ const buffer = createBackupBuffer();
100
+ const path = join(BACKUP_DIR, name);
101
+ writeFileSync(path, buffer);
102
+ const info = inspectBackup(buffer);
103
+ return { name, size: buffer.length, ...info };
104
+ }
105
+ function inspectBackup(buffer) {
106
+ const payload = parsePayload(buffer);
107
+ return { createdAt: payload.createdAt, assets: payload.assets.length };
108
+ }
109
+ function parsePayload(buffer) {
110
+ let json;
111
+ try {
112
+ json = JSON.parse(gunzipSync(buffer).toString("utf8"));
113
+ }
114
+ catch {
115
+ throw new BackupError("Arquivo de backup inválido ou corrompido.");
116
+ }
117
+ const payload = json;
118
+ if (payload?.format !== BACKUP_FORMAT ||
119
+ typeof payload.database !== "string" ||
120
+ !Array.isArray(payload.assets)) {
121
+ throw new BackupError("Formato de backup não reconhecido.");
122
+ }
123
+ return payload;
124
+ }
125
+ /** List stored backups, newest first. */
126
+ export function listBackups() {
127
+ if (!existsSync(BACKUP_DIR))
128
+ return [];
129
+ return readdirSync(BACKUP_DIR)
130
+ .filter((name) => NAME_RE.test(name))
131
+ .map((name) => {
132
+ const full = join(BACKUP_DIR, name);
133
+ const stat = statSync(full);
134
+ return {
135
+ name,
136
+ size: stat.size,
137
+ createdAt: stat.mtime.toISOString(),
138
+ assets: null,
139
+ };
140
+ })
141
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
142
+ }
143
+ function safeBackupPath(name) {
144
+ if (!NAME_RE.test(name)) {
145
+ throw new BackupError("Nome de backup inválido.", 400);
146
+ }
147
+ const full = join(BACKUP_DIR, name);
148
+ if (!full.startsWith(BACKUP_DIR)) {
149
+ throw new BackupError("Nome de backup inválido.", 400);
150
+ }
151
+ if (!existsSync(full)) {
152
+ throw new BackupError("Backup não encontrado.", 404);
153
+ }
154
+ return full;
155
+ }
156
+ /** Read a stored backup into memory. */
157
+ export function readBackup(name) {
158
+ const full = safeBackupPath(name);
159
+ const buffer = readFileSync(full);
160
+ const stat = statSync(full);
161
+ return {
162
+ info: {
163
+ name,
164
+ size: stat.size,
165
+ createdAt: stat.mtime.toISOString(),
166
+ assets: null,
167
+ },
168
+ buffer,
169
+ };
170
+ }
171
+ /** Delete a stored backup. Returns true when a file was removed. */
172
+ export function deleteBackup(name) {
173
+ const full = safeBackupPath(name);
174
+ rmSync(full, { force: true });
175
+ return true;
176
+ }
177
+ /** Keep only the `keep` most recent backups. */
178
+ export function pruneBackups(keep) {
179
+ const limit = Math.max(1, Math.floor(keep));
180
+ const list = listBackups();
181
+ let removed = 0;
182
+ for (const backup of list.slice(limit)) {
183
+ rmSync(join(BACKUP_DIR, backup.name), { force: true });
184
+ removed += 1;
185
+ }
186
+ return removed;
187
+ }
188
+ function writeAsset(path, data) {
189
+ const normalized = path.replace(/\\/g, "/");
190
+ if (normalized.includes("..") ||
191
+ !ASSET_DIRS.some((dir) => normalized.startsWith(`${dir}/`))) {
192
+ throw new BackupError(`Caminho de arquivo inválido no backup: ${path}`);
193
+ }
194
+ const target = resolve(PUBLIC_DIR, normalized);
195
+ if (!target.startsWith(PUBLIC_DIR + sep)) {
196
+ throw new BackupError(`Caminho de arquivo inválido no backup: ${path}`);
197
+ }
198
+ ensureDir(resolve(target, ".."));
199
+ writeFileSync(target, data);
200
+ }
201
+ /** Table names present in `main` (excluding SQLite internals). */
202
+ function mainTables(db) {
203
+ return db
204
+ .prepare(`SELECT name FROM main.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
205
+ .all().map((row) => row.name);
206
+ }
207
+ function tableColumns(db, schema, table) {
208
+ return db.prepare(`PRAGMA ${schema}.table_info(${quoteIdent(table)})`).all().map((row) => row.name);
209
+ }
210
+ function quoteIdent(name) {
211
+ return `"${name.replace(/"/g, '""')}"`;
212
+ }
213
+ /**
214
+ * Restore a backup archive.
215
+ *
216
+ * Instead of replacing the SQLite file on disk (which conflicts with the live
217
+ * connection and any duplicated module instances), the uploaded database is
218
+ * attached and its tables are copied into the running database inside a single
219
+ * transaction. Bundled assets are rewritten to `public/`.
220
+ */
221
+ export function restoreBackup(buffer) {
222
+ const payload = parsePayload(buffer);
223
+ let database;
224
+ try {
225
+ database = Buffer.from(payload.database, "base64");
226
+ }
227
+ catch {
228
+ throw new BackupError("Banco de dados do backup é inválido.");
229
+ }
230
+ if (database.length < SQLITE_MAGIC.length ||
231
+ database.subarray(0, SQLITE_MAGIC.length).toString("latin1") !== SQLITE_MAGIC) {
232
+ throw new BackupError("Banco de dados do backup é inválido.");
233
+ }
234
+ const db = getDb();
235
+ const tmp = join(tmpdir(), `serenojs-restore-${Date.now()}-${Math.random().toString(16).slice(2)}.db`);
236
+ writeFileSync(tmp, database);
237
+ try {
238
+ db.exec(`ATTACH DATABASE '${tmp.replace(/'/g, "''")}' AS restore`);
239
+ }
240
+ catch (error) {
241
+ rmSync(tmp, { force: true });
242
+ throw new BackupError(`Não foi possível ler o banco do backup: ${error.message}`);
243
+ }
244
+ try {
245
+ const restored = new Set(db
246
+ .prepare(`SELECT name FROM restore.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
247
+ .all().map((row) => row.name));
248
+ const existing = new Set(mainTables(db));
249
+ db.exec("BEGIN");
250
+ try {
251
+ // Wipe tables that are not part of the backup.
252
+ for (const table of existing) {
253
+ if (!restored.has(table)) {
254
+ db.exec(`DELETE FROM main.${quoteIdent(table)}`);
255
+ }
256
+ }
257
+ // Copy every shared table, column by column (intersection).
258
+ for (const table of restored) {
259
+ if (!existing.has(table))
260
+ continue;
261
+ const target = tableColumns(db, "main", table);
262
+ const source = new Set(tableColumns(db, "restore", table));
263
+ const columns = target.filter((column) => source.has(column));
264
+ if (columns.length === 0)
265
+ continue;
266
+ const list = columns.map(quoteIdent).join(", ");
267
+ db.exec(`DELETE FROM main.${quoteIdent(table)}`);
268
+ db.exec(`INSERT INTO main.${quoteIdent(table)} (${list}) SELECT ${list} FROM restore.${quoteIdent(table)}`);
269
+ }
270
+ db.exec("COMMIT");
271
+ }
272
+ catch (error) {
273
+ db.exec("ROLLBACK");
274
+ throw error;
275
+ }
276
+ }
277
+ finally {
278
+ db.exec("DETACH DATABASE restore");
279
+ rmSync(tmp, { force: true });
280
+ }
281
+ for (const asset of payload.assets) {
282
+ if (!asset || typeof asset.path !== "string" || typeof asset.data !== "string") {
283
+ continue;
284
+ }
285
+ writeAsset(asset.path, Buffer.from(asset.data, "base64"));
286
+ }
287
+ return {
288
+ format: payload.format,
289
+ version: payload.version,
290
+ createdAt: payload.createdAt,
291
+ databaseBytes: database.length,
292
+ assets: payload.assets.length,
293
+ };
294
+ }
295
+ /* -------------------------------------------------------------------------- */
296
+ /* Scheduled routine */
297
+ /* -------------------------------------------------------------------------- */
298
+ function backupDisabled() {
299
+ return (process.env.ADMIN_BACKUP === "false" || !getCmsConfig().backup.enabled);
300
+ }
301
+ function intervalHours() {
302
+ return Number(process.env.ADMIN_BACKUP_INTERVAL_HOURS ??
303
+ getCmsConfig().backup.intervalHours);
304
+ }
305
+ function keepCount() {
306
+ return Number(process.env.ADMIN_BACKUP_KEEP ?? getCmsConfig().backup.keep);
307
+ }
308
+ const globalScope = globalThis;
309
+ const SCHEDULER_KEY = Symbol.for("serenojs.backup-scheduler");
310
+ function intervalMs() {
311
+ const configured = intervalHours();
312
+ const hours = Number.isFinite(configured) && configured > 0 ? configured : 24;
313
+ return hours * 60 * 60 * 1000;
314
+ }
315
+ function isDue() {
316
+ const [latest] = listBackups();
317
+ if (!latest)
318
+ return true;
319
+ const age = Date.now() - new Date(latest.createdAt).getTime();
320
+ return age >= intervalMs();
321
+ }
322
+ function runBackup() {
323
+ try {
324
+ createBackup();
325
+ const keep = keepCount();
326
+ pruneBackups(Number.isFinite(keep) && keep > 0 ? keep : 10);
327
+ }
328
+ catch (error) {
329
+ console.error("[backup] falha ao criar backup automático:", error);
330
+ }
331
+ }
332
+ /**
333
+ * Start the periodic backup routine. Idempotent: safe to call on every request
334
+ * or module load, only the first call schedules anything.
335
+ */
336
+ export function startBackupScheduler() {
337
+ if (backupDisabled())
338
+ return;
339
+ if (globalScope[SCHEDULER_KEY])
340
+ return;
341
+ globalScope[SCHEDULER_KEY] = true;
342
+ // Defer the first run so it never blocks the request that triggers startup.
343
+ setTimeout(() => {
344
+ if (isDue())
345
+ runBackup();
346
+ const timer = setInterval(runBackup, intervalMs());
347
+ timer.unref?.();
348
+ }, 2_000).unref?.();
349
+ }
@@ -0,0 +1,24 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import type { CollectionDef, FieldValue, Item, ListResult } from "./types.js";
3
+ export declare function getDb(): DatabaseSync;
4
+ export declare function listItems(collection: CollectionDef, { page, limit, q, }?: {
5
+ page?: number;
6
+ limit?: number;
7
+ q?: string;
8
+ }): ListResult;
9
+ export declare function getItem(collection: CollectionDef, id: number): Item | null;
10
+ /** Throw-free check that every referenced id actually exists. */
11
+ export declare function checkRelationTargets(collection: CollectionDef, values: Record<string, FieldValue>): Record<string, string>;
12
+ export declare function createItem(collection: CollectionDef, values: Record<string, FieldValue>): Item;
13
+ export declare function updateItem(collection: CollectionDef, id: number, values: Record<string, FieldValue>): Item | null;
14
+ /**
15
+ * Read the single record of a standalone collection, creating it with its
16
+ * field defaults on first access.
17
+ */
18
+ export declare function getStandalone(collection: CollectionDef): Item;
19
+ /**
20
+ * Upsert the single record of a standalone collection. Values are merged over
21
+ * the field defaults so a fresh record is always fully populated.
22
+ */
23
+ export declare function saveStandalone(collection: CollectionDef, values: Record<string, FieldValue>): Item;
24
+ export declare function deleteItem(collection: CollectionDef, id: number): boolean;