@eutobias/serenojs 0.1.1 → 0.1.2

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.
@@ -5,7 +5,7 @@
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <meta name="robots" content="noindex, nofollow" />
7
7
  <title>%SERENOJS_TITLE%</title>
8
- <script type="module" crossorigin src="/_serenojs/admin/assets/index-B3EgqtT6.js"></script>
8
+ <script type="module" crossorigin src="/_serenojs/admin/assets/index-Ddgw58Iy.js"></script>
9
9
  <link rel="stylesheet" crossorigin href="/_serenojs/admin/assets/index-D2m0Eb4k.css">
10
10
  </head>
11
11
  <body class="bg-gray-50 text-gray-900 antialiased">
package/dist/config.d.ts CHANGED
@@ -48,6 +48,10 @@ export type CmsConfig = {
48
48
  intervalHours?: number;
49
49
  keep?: number;
50
50
  };
51
+ /** Host directory where restore writes the restored schema modules. */
52
+ schemas?: {
53
+ path?: string;
54
+ };
51
55
  db?: {
52
56
  path?: string;
53
57
  };
@@ -80,6 +84,9 @@ export type ResolvedCmsConfig = {
80
84
  intervalHours: number;
81
85
  keep: number;
82
86
  };
87
+ schemas: {
88
+ path: string;
89
+ };
83
90
  db: {
84
91
  path: string;
85
92
  };
package/dist/config.js CHANGED
@@ -30,6 +30,7 @@ export function resolveCmsConfig(config) {
30
30
  intervalHours: config.backup?.intervalHours ?? 24,
31
31
  keep: config.backup?.keep ?? 10,
32
32
  },
33
+ schemas: { path: config.schemas?.path ?? "src/schemas" },
33
34
  db: { path: config.db?.path ?? ".data/admin.db" },
34
35
  };
35
36
  }
@@ -1,5 +1,5 @@
1
1
  export declare const BACKUP_FORMAT = "serenojs-backup";
2
- export declare const BACKUP_VERSION = 1;
2
+ export declare const BACKUP_VERSION = 2;
3
3
  export declare const BACKUP_EXTENSION = ".serenojs";
4
4
  export declare const BACKUP_DIR: string;
5
5
  export declare const PUBLIC_DIR: string;
@@ -20,6 +20,8 @@ export type BackupManifest = {
20
20
  createdAt: string;
21
21
  databaseBytes: number;
22
22
  assets: number;
23
+ /** Number of schema modules written during restore. */
24
+ schemas: number;
23
25
  };
24
26
  /** Create an in-memory backup archive (gzip). */
25
27
  export declare function createBackupBuffer(): Buffer;
@@ -42,7 +44,8 @@ export declare function pruneBackups(keep: number): number;
42
44
  * Instead of replacing the SQLite file on disk (which conflicts with the live
43
45
  * connection and any duplicated module instances), the uploaded database is
44
46
  * attached and its tables are copied into the running database inside a single
45
- * transaction. Bundled assets are rewritten to `public/`.
47
+ * transaction. The schema modules are rewritten to `schemas.path` and bundled
48
+ * assets to `public/`.
46
49
  */
47
50
  export declare function restoreBackup(buffer: Buffer): BackupManifest;
48
51
  /**
@@ -1,8 +1,9 @@
1
1
  /**
2
- * Database + uploaded-assets backup and restore.
2
+ * Schemas, database and uploaded-asset backup and restore.
3
3
  *
4
4
  * A backup is a single gzip-compressed JSON archive (`<name>.serenojs`) that
5
5
  * bundles:
6
+ * - the collection descriptors from `src/schemas` (the source of truth),
6
7
  * - a consistent SQLite snapshot of `.data/admin.db` (via `VACUUM INTO`),
7
8
  * - every file under `public/images` (committed assets) and `public/files`
8
9
  * (runtime uploads), stored as base64.
@@ -17,9 +18,10 @@ import { tmpdir } from "node:os";
17
18
  import { join, relative, resolve, sep } from "node:path";
18
19
  import { gunzipSync, gzipSync } from "node:zlib";
19
20
  import { getDb } from "./db.server.js";
20
- import { getCmsConfig } from "../runtime.js";
21
+ import { writeSchemaFiles, } from "./schema-codegen.server.js";
22
+ import { configureCms, getCmsConfig } from "../runtime.js";
21
23
  export const BACKUP_FORMAT = "serenojs-backup";
22
- export const BACKUP_VERSION = 1;
24
+ export const BACKUP_VERSION = 2;
23
25
  export const BACKUP_EXTENSION = ".serenojs";
24
26
  export const BACKUP_DIR = resolve(process.cwd(), ".data/backups");
25
27
  export const PUBLIC_DIR = resolve(process.cwd(), "public");
@@ -86,6 +88,7 @@ function buildPayload() {
86
88
  createdAt: new Date().toISOString(),
87
89
  database: database.toString("base64"),
88
90
  assets,
91
+ schemas: currentSchemas(),
89
92
  };
90
93
  }
91
94
  /** Create an in-memory backup archive (gzip). */
@@ -210,13 +213,257 @@ function tableColumns(db, schema, table) {
210
213
  function quoteIdent(name) {
211
214
  return `"${name.replace(/"/g, '""')}"`;
212
215
  }
216
+ /** Tables declared in an attached schema (excluding SQLite internals). */
217
+ function attachedTables(db, schema) {
218
+ return db
219
+ .prepare(`SELECT name, sql FROM ${schema}.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
220
+ .all();
221
+ }
222
+ /** Recreate a table that does not exist in the live database yet. */
223
+ function createMissingTable(db, table) {
224
+ if (!table.sql)
225
+ return;
226
+ db.exec(table.sql);
227
+ }
228
+ /**
229
+ * Add columns that exist in the backup but not in the live table. Without this,
230
+ * data stored in newer columns would be silently dropped on restore.
231
+ */
232
+ function addMissingColumns(db, table, target) {
233
+ const source = db
234
+ .prepare(`PRAGMA restore.table_info(${quoteIdent(table)})`)
235
+ .all();
236
+ for (const column of source) {
237
+ if (target.has(column.name))
238
+ continue;
239
+ let definition = `${quoteIdent(column.name)} ${column.type || "TEXT"}`;
240
+ if (column.dflt_value !== null) {
241
+ definition += ` NOT NULL DEFAULT ${column.dflt_value}`;
242
+ }
243
+ // SQLite cannot add a NOT NULL column without a default; keep it nullable.
244
+ db.exec(`ALTER TABLE main.${quoteIdent(table)} ADD COLUMN ${definition}`);
245
+ target.add(column.name);
246
+ }
247
+ }
248
+ /** Recreate indexes/triggers from the backup whose names are absent live. */
249
+ function createMissingSchemaObjects(db) {
250
+ const existing = new Set(db
251
+ .prepare(`SELECT name FROM main.sqlite_master WHERE type IN ('index', 'trigger')`)
252
+ .all().map((row) => row.name));
253
+ const objects = db
254
+ .prepare(`SELECT name, sql FROM restore.sqlite_master WHERE type IN ('index', 'trigger') AND sql IS NOT NULL`)
255
+ .all();
256
+ for (const object of objects) {
257
+ if (existing.has(object.name))
258
+ continue;
259
+ db.exec(object.sql);
260
+ existing.add(object.name);
261
+ }
262
+ }
263
+ /** Current descriptors, persisted inside every new backup. */
264
+ function currentSchemas() {
265
+ const config = getCmsConfig();
266
+ return {
267
+ title: config.title,
268
+ defaultLocale: config.defaultLocale,
269
+ locales: config.locales,
270
+ collections: config.collections,
271
+ };
272
+ }
273
+ /** Validate the schema section of an uploaded archive. */
274
+ function normalizeSchemas(value, fallback) {
275
+ if (!value || typeof value !== "object")
276
+ return null;
277
+ const record = value;
278
+ if (!Array.isArray(record.collections))
279
+ return null;
280
+ const locales = Array.isArray(record.locales)
281
+ ? record.locales.filter((locale) => Boolean(locale) &&
282
+ typeof locale === "object" &&
283
+ typeof locale.code === "string" &&
284
+ typeof locale.label === "string")
285
+ : fallback.locales;
286
+ const collections = record.collections.filter((collection) => Boolean(collection) &&
287
+ typeof collection === "object" &&
288
+ typeof collection.slug === "string" &&
289
+ typeof collection.label === "string" &&
290
+ Array.isArray(collection.fields));
291
+ // A malformed archive must not overwrite the host schemas with a partial set.
292
+ if (collections.length !== record.collections.length)
293
+ return null;
294
+ return {
295
+ title: typeof record.title === "string" && record.title ? record.title : fallback.title,
296
+ locales: locales.length > 0 ? locales : fallback.locales,
297
+ defaultLocale: typeof record.defaultLocale === "string" && record.defaultLocale
298
+ ? record.defaultLocale
299
+ : fallback.defaultLocale,
300
+ collections,
301
+ };
302
+ }
303
+ function humanize(name) {
304
+ const words = name
305
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
306
+ .replace(/[_-]+/g, " ")
307
+ .trim()
308
+ .split(/\s+/)
309
+ .filter(Boolean);
310
+ if (words.length === 0)
311
+ return name;
312
+ return words
313
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
314
+ .join(" ");
315
+ }
316
+ function inferFieldType(sqlType, samples) {
317
+ const type = (sqlType || "").toUpperCase();
318
+ if (type.includes("INT")) {
319
+ const numbers = samples.map((value) => Number(value));
320
+ if (numbers.length > 0 &&
321
+ numbers.every((value) => value === 0 || value === 1)) {
322
+ return "boolean";
323
+ }
324
+ return "number";
325
+ }
326
+ if (type.includes("REAL") ||
327
+ type.includes("NUM") ||
328
+ type.includes("DEC") ||
329
+ type.includes("FLOA") ||
330
+ type.includes("DOUB")) {
331
+ return "number";
332
+ }
333
+ for (const value of samples) {
334
+ if (typeof value !== "string")
335
+ continue;
336
+ const text = value.trim();
337
+ if (!text)
338
+ continue;
339
+ if ((text.startsWith("/files/") || text.startsWith("/images/")) &&
340
+ /\.(png|jpe?g|gif|webp|avif|svg|pdf)(\?|$)/i.test(text)) {
341
+ return "media";
342
+ }
343
+ if (text.startsWith("[") && text.endsWith("]")) {
344
+ try {
345
+ const parsed = JSON.parse(text);
346
+ if (Array.isArray(parsed) && parsed.length > 0) {
347
+ if (parsed.every((entry) => Boolean(entry) &&
348
+ typeof entry === "object" &&
349
+ typeof entry.url === "string")) {
350
+ return "media-list";
351
+ }
352
+ if (parsed.every((entry) => typeof entry === "string")) {
353
+ return "list";
354
+ }
355
+ }
356
+ }
357
+ catch {
358
+ // Not JSON; keep it as text.
359
+ }
360
+ }
361
+ }
362
+ return "text";
363
+ }
364
+ /**
365
+ * Reconstruct descriptors from the backup database for archives created before
366
+ * schemas were embedded. Types are inferred from SQLite columns and samples.
367
+ */
368
+ function inferSchemas(db, schema, fallback) {
369
+ const localeCodes = [...fallback.locales.map((locale) => locale.code)].sort((a, b) => b.length - a.length);
370
+ const collections = [];
371
+ for (const table of attachedTables(db, schema)) {
372
+ if (!table.name.startsWith("c_"))
373
+ continue;
374
+ const slug = table.name.slice(2);
375
+ const columns = db
376
+ .prepare(`PRAGMA ${schema}.table_info(${quoteIdent(table.name)})`)
377
+ .all();
378
+ const rows = db
379
+ .prepare(`SELECT * FROM ${schema}.${quoteIdent(table.name)} LIMIT 100`)
380
+ .all();
381
+ const groups = new Map();
382
+ for (const column of columns) {
383
+ if (column.name === "id" || column.name === "created_at" || column.name === "updated_at") {
384
+ continue;
385
+ }
386
+ let base = column.name;
387
+ let localized = false;
388
+ let locale = null;
389
+ for (const code of localeCodes) {
390
+ if (column.name.endsWith(`_${code}`)) {
391
+ base = column.name.slice(0, -code.length - 1);
392
+ localized = true;
393
+ locale = code;
394
+ break;
395
+ }
396
+ }
397
+ let group = groups.get(base);
398
+ if (!group) {
399
+ group = { base, localized: false, locales: new Set(), sqlType: column.type, samples: [] };
400
+ groups.set(base, group);
401
+ }
402
+ if (localized && locale) {
403
+ group.localized = true;
404
+ group.locales.add(locale);
405
+ }
406
+ if (!group.sqlType)
407
+ group.sqlType = column.type;
408
+ for (const row of rows) {
409
+ const value = row[column.name];
410
+ if (value !== null && value !== undefined)
411
+ group.samples.push(value);
412
+ }
413
+ }
414
+ const fields = [];
415
+ const usedLocales = new Set();
416
+ for (const group of groups.values()) {
417
+ fields.push({
418
+ name: group.base,
419
+ label: humanize(group.base),
420
+ type: inferFieldType(group.sqlType, group.samples.slice(0, 50)),
421
+ localized: group.localized,
422
+ });
423
+ for (const code of group.locales)
424
+ usedLocales.add(code);
425
+ }
426
+ const collection = {
427
+ slug,
428
+ label: humanize(slug),
429
+ fields,
430
+ };
431
+ if (usedLocales.size > 0) {
432
+ collection.locales = fallback.locales
433
+ .map((locale) => locale.code)
434
+ .filter((code) => usedLocales.has(code));
435
+ }
436
+ collections.push(collection);
437
+ }
438
+ return {
439
+ title: fallback.title,
440
+ defaultLocale: fallback.defaultLocale,
441
+ locales: fallback.locales,
442
+ collections,
443
+ };
444
+ }
445
+ function schemaDirectory() {
446
+ return resolve(process.cwd(), getCmsConfig().schemas.path);
447
+ }
448
+ /** Make the restored descriptors active immediately, not only after reboot. */
449
+ function applySchemas(schemas) {
450
+ const current = getCmsConfig();
451
+ configureCms({
452
+ ...current,
453
+ title: schemas.title,
454
+ collections: schemas.collections,
455
+ locales: schemas.locales,
456
+ defaultLocale: schemas.defaultLocale,
457
+ });
458
+ }
213
459
  /**
214
460
  * Restore a backup archive.
215
461
  *
216
462
  * Instead of replacing the SQLite file on disk (which conflicts with the live
217
463
  * connection and any duplicated module instances), the uploaded database is
218
464
  * attached and its tables are copied into the running database inside a single
219
- * transaction. Bundled assets are rewritten to `public/`.
465
+ * transaction. The schema modules are rewritten to `schemas.path` and bundled
466
+ * assets to `public/`.
220
467
  */
221
468
  export function restoreBackup(buffer) {
222
469
  const payload = parsePayload(buffer);
@@ -232,6 +479,8 @@ export function restoreBackup(buffer) {
232
479
  throw new BackupError("Banco de dados do backup é inválido.");
233
480
  }
234
481
  const db = getDb();
482
+ const fallback = currentSchemas();
483
+ let schemas = normalizeSchemas(payload.schemas, fallback);
235
484
  const tmp = join(tmpdir(), `serenojs-restore-${Date.now()}-${Math.random().toString(16).slice(2)}.db`);
236
485
  writeFileSync(tmp, database);
237
486
  try {
@@ -242,10 +491,10 @@ export function restoreBackup(buffer) {
242
491
  throw new BackupError(`Não foi possível ler o banco do backup: ${error.message}`);
243
492
  }
244
493
  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));
494
+ const restoredTables = attachedTables(db, "restore");
495
+ const restored = new Set(restoredTables.map((table) => table.name));
248
496
  const existing = new Set(mainTables(db));
497
+ schemas ??= inferSchemas(db, "restore", fallback);
249
498
  db.exec("BEGIN");
250
499
  try {
251
500
  // Wipe tables that are not part of the backup.
@@ -254,19 +503,27 @@ export function restoreBackup(buffer) {
254
503
  db.exec(`DELETE FROM main.${quoteIdent(table)}`);
255
504
  }
256
505
  }
257
- // Copy every shared table, column by column (intersection).
258
- for (const table of restored) {
259
- if (!existing.has(table))
506
+ // Recreate missing tables so the backup schema itself is restored.
507
+ for (const table of restoredTables) {
508
+ if (existing.has(table.name))
260
509
  continue;
261
- const target = tableColumns(db, "main", table);
510
+ createMissingTable(db, table);
511
+ existing.add(table.name);
512
+ }
513
+ // Copy every shared table, column by column.
514
+ for (const table of restored) {
515
+ const target = new Set(tableColumns(db, "main", table));
516
+ addMissingColumns(db, table, target);
262
517
  const source = new Set(tableColumns(db, "restore", table));
263
- const columns = target.filter((column) => source.has(column));
518
+ const columns = [...target].filter((column) => source.has(column));
264
519
  if (columns.length === 0)
265
520
  continue;
266
521
  const list = columns.map(quoteIdent).join(", ");
267
522
  db.exec(`DELETE FROM main.${quoteIdent(table)}`);
268
523
  db.exec(`INSERT INTO main.${quoteIdent(table)} (${list}) SELECT ${list} FROM restore.${quoteIdent(table)}`);
269
524
  }
525
+ // Restore indexes/triggers declared by the backup.
526
+ createMissingSchemaObjects(db);
270
527
  db.exec("COMMIT");
271
528
  }
272
529
  catch (error) {
@@ -284,12 +541,22 @@ export function restoreBackup(buffer) {
284
541
  }
285
542
  writeAsset(asset.path, Buffer.from(asset.data, "base64"));
286
543
  }
544
+ const restoredSchemas = schemas ?? fallback;
545
+ let written;
546
+ try {
547
+ written = writeSchemaFiles(schemaDirectory(), restoredSchemas);
548
+ }
549
+ catch (error) {
550
+ throw new BackupError(`Banco e arquivos restaurados, mas não foi possível gravar os schemas: ${error.message}`, 500);
551
+ }
552
+ applySchemas(restoredSchemas);
287
553
  return {
288
554
  format: payload.format,
289
555
  version: payload.version,
290
556
  createdAt: payload.createdAt,
291
557
  databaseBytes: database.length,
292
558
  assets: payload.assets.length,
559
+ schemas: written.files,
293
560
  };
294
561
  }
295
562
  /* -------------------------------------------------------------------------- */
@@ -0,0 +1,17 @@
1
+ import type { LocaleDef } from "../config.js";
2
+ import type { CollectionDef } from "./types.js";
3
+ export type BackupSchemas = {
4
+ title: string;
5
+ defaultLocale: string;
6
+ locales: LocaleDef[];
7
+ collections: CollectionDef[];
8
+ };
9
+ export type SchemaWriteResult = {
10
+ files: number;
11
+ collections: number;
12
+ };
13
+ /**
14
+ * Write the backup schemas into `dir` as the conventional starter layout:
15
+ * `index.ts`, `locales.ts` and one module per collection.
16
+ */
17
+ export declare function writeSchemaFiles(dir: string, schemas: BackupSchemas): SchemaWriteResult;
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Schema source-code generation used by the backup restore routine.
3
+ *
4
+ * The collection descriptors in `src/schemas` are the source of truth for the
5
+ * whole CMS, so a backup stores them and restore writes them back as TypeScript
6
+ * modules. Server-only: uses the filesystem.
7
+ */
8
+ import { mkdirSync, writeFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ const RESERVED_IDENTIFIERS = new Set([
11
+ "break",
12
+ "case",
13
+ "catch",
14
+ "class",
15
+ "const",
16
+ "continue",
17
+ "debugger",
18
+ "default",
19
+ "delete",
20
+ "do",
21
+ "else",
22
+ "enum",
23
+ "export",
24
+ "extends",
25
+ "false",
26
+ "finally",
27
+ "for",
28
+ "function",
29
+ "if",
30
+ "implements",
31
+ "import",
32
+ "in",
33
+ "instanceof",
34
+ "interface",
35
+ "let",
36
+ "new",
37
+ "null",
38
+ "package",
39
+ "private",
40
+ "protected",
41
+ "public",
42
+ "return",
43
+ "static",
44
+ "super",
45
+ "switch",
46
+ "this",
47
+ "throw",
48
+ "true",
49
+ "try",
50
+ "typeof",
51
+ "var",
52
+ "void",
53
+ "while",
54
+ "with",
55
+ "yield",
56
+ ]);
57
+ function identifier(raw, fallback) {
58
+ let value = raw.replace(/[^a-zA-Z0-9_]/g, "_");
59
+ if (!value)
60
+ value = fallback;
61
+ if (/^[0-9]/.test(value))
62
+ value = `_${value}`;
63
+ if (RESERVED_IDENTIFIERS.has(value))
64
+ value = `${value}_`;
65
+ return value;
66
+ }
67
+ function fileBase(raw) {
68
+ const value = raw.replace(/[^a-zA-Z0-9_-]/g, "_").replace(/^[-_]+/, "");
69
+ return value || "collection";
70
+ }
71
+ function literal(value) {
72
+ return JSON.stringify(value, null, 2) ?? "null";
73
+ }
74
+ function collectionModule(exportName, collection) {
75
+ return [
76
+ `import type { CollectionDef } from "@eutobias/serenojs/config";`,
77
+ "",
78
+ `export const ${exportName}: CollectionDef = ${literal(collection)};`,
79
+ "",
80
+ ].join("\n");
81
+ }
82
+ function localesModule(schemas) {
83
+ return [
84
+ `/** Locale registry restored from a SerenoJS backup. */`,
85
+ "",
86
+ `export type LocaleDef = {`,
87
+ ` code: string;`,
88
+ ` label: string;`,
89
+ `};`,
90
+ "",
91
+ `export const locales: LocaleDef[] = ${literal(schemas.locales)};`,
92
+ "",
93
+ `/** Locale used as fallback and for the seed of legacy single-column data. */`,
94
+ `export const defaultLocale = ${literal(schemas.defaultLocale)};`,
95
+ "",
96
+ `/** Display label for a locale code (falls back to the uppercased code). */`,
97
+ `export function localeLabel(code: string): string {`,
98
+ ` return (`,
99
+ ` locales.find((locale) => locale.code === code)?.label ?? code.toUpperCase()`,
100
+ ` );`,
101
+ `}`,
102
+ "",
103
+ ].join("\n");
104
+ }
105
+ function indexModule(schemas, entries) {
106
+ const imports = entries
107
+ .map(({ base, exportName }) => `import { ${exportName} } from "./${base}";`)
108
+ .join("\n");
109
+ const values = entries.map(({ exportName }) => exportName).join(", ");
110
+ return [
111
+ `import type { CollectionDef } from "@eutobias/serenojs/config";`,
112
+ "",
113
+ imports,
114
+ "",
115
+ `export { defaultLocale, localeLabel, locales } from "./locales";`,
116
+ `export type { LocaleDef } from "./locales";`,
117
+ "",
118
+ `/** Title shown across the admin panel. */`,
119
+ `export const schemaTitle = ${literal(schemas.title)};`,
120
+ "",
121
+ `/** Every collection available in the admin/API. */`,
122
+ `export const collections: CollectionDef[] = [${values}];`,
123
+ "",
124
+ ].join("\n");
125
+ }
126
+ /**
127
+ * Write the backup schemas into `dir` as the conventional starter layout:
128
+ * `index.ts`, `locales.ts` and one module per collection.
129
+ */
130
+ export function writeSchemaFiles(dir, schemas) {
131
+ mkdirSync(dir, { recursive: true });
132
+ const usedFiles = new Set(["index", "locales"]);
133
+ const usedExports = new Set();
134
+ const entries = [];
135
+ for (const collection of schemas.collections) {
136
+ const rawBase = fileBase(collection.slug);
137
+ let base = rawBase;
138
+ let suffix = 2;
139
+ while (usedFiles.has(base))
140
+ base = `${rawBase}_${suffix++}`;
141
+ usedFiles.add(base);
142
+ const rawExport = identifier(collection.slug, "collection");
143
+ let exportName = rawExport;
144
+ suffix = 2;
145
+ while (usedExports.has(exportName)) {
146
+ exportName = `${rawExport}_${suffix++}`;
147
+ }
148
+ usedExports.add(exportName);
149
+ writeFileSync(join(dir, `${base}.ts`), collectionModule(exportName, collection), "utf8");
150
+ entries.push({ base, exportName });
151
+ }
152
+ writeFileSync(join(dir, "locales.ts"), localesModule(schemas), "utf8");
153
+ writeFileSync(join(dir, "index.ts"), indexModule(schemas, entries), "utf8");
154
+ return { files: entries.length + 2, collections: entries.length };
155
+ }
@@ -118,12 +118,12 @@ const en = {
118
118
  "users.removeError": "Could not remove the user.",
119
119
  "users.networkRemove": "Network error while removing the user.",
120
120
  "backup.title": "Backup",
121
- "backup.subtitle": "Download or restore the database and system images.",
121
+ "backup.subtitle": "Download or restore schemas, database and system images.",
122
122
  "backup.refresh": "Refresh",
123
123
  "backup.downloadCurrent": "Download current",
124
124
  "backup.restoreAction": "Restore",
125
125
  "backup.create": "Create backup",
126
- "backup.description": "The backup bundles a consistent SQLite snapshot and every file under public/images and public/files. Restoring replaces the current database and rewrites the images.",
126
+ "backup.description": "The backup bundles the collection schemas, a consistent SQLite snapshot and every file under public/images and public/files. Restoring rewrites the schema modules, replaces the current database and rewrites the images.",
127
127
  "backup.file": "File",
128
128
  "backup.size": "Size",
129
129
  "backup.download": "Download",
@@ -255,12 +255,12 @@ const pt = {
255
255
  "users.removeError": "Não foi possível remover o usuário.",
256
256
  "users.networkRemove": "Erro de rede ao remover o usuário.",
257
257
  "backup.title": "Backup",
258
- "backup.subtitle": "Baixe ou restaure o banco de dados e as imagens do sistema.",
258
+ "backup.subtitle": "Baixe ou restaure os schemas, o banco de dados e as imagens do sistema.",
259
259
  "backup.refresh": "Atualizar",
260
260
  "backup.downloadCurrent": "Baixar atual",
261
261
  "backup.restoreAction": "Restaurar",
262
262
  "backup.create": "Criar backup",
263
- "backup.description": "O backup reúne um snapshot consistente do banco SQLite e todos os arquivos de public/images e public/files. Restaurar substitui o banco atual e regrava as imagens.",
263
+ "backup.description": "O backup reúne os schemas das coleções, um snapshot consistente do banco SQLite e todos os arquivos de public/images e public/files. Restaurar regrava os módulos de schema, substitui o banco atual e regrava as imagens.",
264
264
  "backup.file": "Arquivo",
265
265
  "backup.size": "Tamanho",
266
266
  "backup.download": "Baixar",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eutobias/serenojs",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "SerenoJS — schema-driven CMS for Waku: auto-generated admin SPA + Hono REST API.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/config.ts CHANGED
@@ -53,6 +53,8 @@ export type CmsConfig = {
53
53
  intervalHours?: number;
54
54
  keep?: number;
55
55
  };
56
+ /** Host directory where restore writes the restored schema modules. */
57
+ schemas?: { path?: string };
56
58
  db?: { path?: string };
57
59
  };
58
60
 
@@ -72,6 +74,7 @@ export type ResolvedCmsConfig = {
72
74
  intervalHours: number;
73
75
  keep: number;
74
76
  };
77
+ schemas: { path: string };
75
78
  db: { path: string };
76
79
  };
77
80
 
@@ -110,6 +113,7 @@ export function resolveCmsConfig(config: CmsConfig): ResolvedCmsConfig {
110
113
  intervalHours: config.backup?.intervalHours ?? 24,
111
114
  keep: config.backup?.keep ?? 10,
112
115
  },
116
+ schemas: { path: config.schemas?.path ?? "src/schemas" },
113
117
  db: { path: config.db?.path ?? ".data/admin.db" },
114
118
  };
115
119
  }