@dyrected/core 2.5.25 → 2.5.27

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 (162) hide show
  1. package/dist/__tests__/app.test.d.ts +2 -0
  2. package/dist/__tests__/app.test.d.ts.map +1 -0
  3. package/dist/__tests__/app.test.js +27 -0
  4. package/dist/__tests__/app.test.js.map +1 -0
  5. package/dist/__tests__/config.test.d.ts +2 -0
  6. package/dist/__tests__/config.test.d.ts.map +1 -0
  7. package/dist/__tests__/config.test.js +34 -0
  8. package/dist/__tests__/config.test.js.map +1 -0
  9. package/dist/__tests__/deleteMany.test.d.ts +2 -0
  10. package/dist/__tests__/deleteMany.test.d.ts.map +1 -0
  11. package/dist/__tests__/deleteMany.test.js +75 -0
  12. package/dist/__tests__/deleteMany.test.js.map +1 -0
  13. package/dist/__tests__/depth.test.d.ts +2 -0
  14. package/dist/__tests__/depth.test.d.ts.map +1 -0
  15. package/dist/__tests__/depth.test.js +81 -0
  16. package/dist/__tests__/depth.test.js.map +1 -0
  17. package/dist/__tests__/dynamic-options.test.d.ts +2 -0
  18. package/dist/__tests__/dynamic-options.test.d.ts.map +1 -0
  19. package/dist/__tests__/dynamic-options.test.js +132 -0
  20. package/dist/__tests__/dynamic-options.test.js.map +1 -0
  21. package/dist/__tests__/field-inference.test-types.d.ts +24 -0
  22. package/dist/__tests__/field-inference.test-types.d.ts.map +1 -0
  23. package/dist/__tests__/field-inference.test-types.js +87 -0
  24. package/dist/__tests__/field-inference.test-types.js.map +1 -0
  25. package/dist/__tests__/hooks.test.d.ts +2 -0
  26. package/dist/__tests__/hooks.test.d.ts.map +1 -0
  27. package/dist/__tests__/hooks.test.js +320 -0
  28. package/dist/__tests__/hooks.test.js.map +1 -0
  29. package/dist/__tests__/mocks.d.ts +68 -0
  30. package/dist/__tests__/mocks.d.ts.map +1 -0
  31. package/dist/__tests__/mocks.js +151 -0
  32. package/dist/__tests__/mocks.js.map +1 -0
  33. package/dist/__tests__/router.test.d.ts +2 -0
  34. package/dist/__tests__/router.test.d.ts.map +1 -0
  35. package/dist/__tests__/router.test.js +48 -0
  36. package/dist/__tests__/router.test.js.map +1 -0
  37. package/dist/__tests__/where.test.d.ts +2 -0
  38. package/dist/__tests__/where.test.d.ts.map +1 -0
  39. package/dist/__tests__/where.test.js +97 -0
  40. package/dist/__tests__/where.test.js.map +1 -0
  41. package/dist/app-BOrsS7Tz.d.cts +1771 -0
  42. package/dist/app-BOrsS7Tz.d.ts +1771 -0
  43. package/dist/app.d.ts +21 -0
  44. package/dist/app.d.ts.map +1 -0
  45. package/dist/app.js +56 -0
  46. package/dist/app.js.map +1 -0
  47. package/dist/auth/jexl.d.ts +10 -0
  48. package/dist/auth/jexl.d.ts.map +1 -0
  49. package/dist/auth/jexl.js +22 -0
  50. package/dist/auth/jexl.js.map +1 -0
  51. package/dist/auth/password.d.ts +10 -0
  52. package/dist/auth/password.d.ts.map +1 -0
  53. package/dist/auth/password.js +28 -0
  54. package/dist/auth/password.js.map +1 -0
  55. package/dist/auth/token.d.ts +20 -0
  56. package/dist/auth/token.d.ts.map +1 -0
  57. package/dist/auth/token.js +40 -0
  58. package/dist/auth/token.js.map +1 -0
  59. package/dist/chunk-SUGK7UYL.js +311 -0
  60. package/dist/chunk-ZFAOBRHT.js +2709 -0
  61. package/dist/controllers/auth.controller.d.ts +125 -0
  62. package/dist/controllers/auth.controller.d.ts.map +1 -0
  63. package/dist/controllers/auth.controller.js +323 -0
  64. package/dist/controllers/auth.controller.js.map +1 -0
  65. package/dist/controllers/collection.controller.d.ts +88 -0
  66. package/dist/controllers/collection.controller.d.ts.map +1 -0
  67. package/dist/controllers/collection.controller.js +554 -0
  68. package/dist/controllers/collection.controller.js.map +1 -0
  69. package/dist/controllers/global.controller.d.ts +17 -0
  70. package/dist/controllers/global.controller.d.ts.map +1 -0
  71. package/dist/controllers/global.controller.js +116 -0
  72. package/dist/controllers/global.controller.js.map +1 -0
  73. package/dist/controllers/media.controller.d.ts +36 -0
  74. package/dist/controllers/media.controller.d.ts.map +1 -0
  75. package/dist/controllers/media.controller.js +155 -0
  76. package/dist/controllers/media.controller.js.map +1 -0
  77. package/dist/controllers/preview.controller.d.ts +37 -0
  78. package/dist/controllers/preview.controller.d.ts.map +1 -0
  79. package/dist/controllers/preview.controller.js +48 -0
  80. package/dist/controllers/preview.controller.js.map +1 -0
  81. package/dist/index-Bp7PDOYG.d.cts +1750 -0
  82. package/dist/index-Bp7PDOYG.d.ts +1750 -0
  83. package/dist/index-DfAmTZXk.d.cts +1749 -0
  84. package/dist/index-DfAmTZXk.d.ts +1749 -0
  85. package/dist/index.cjs +2 -2396
  86. package/dist/index.d.cts +2 -4
  87. package/dist/index.d.ts +2 -4
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +3 -5
  90. package/dist/index.js.map +1 -0
  91. package/dist/middleware/auth.d.ts +18 -0
  92. package/dist/middleware/auth.d.ts.map +1 -0
  93. package/dist/middleware/auth.js +45 -0
  94. package/dist/middleware/auth.js.map +1 -0
  95. package/dist/router.d.ts +8 -0
  96. package/dist/router.d.ts.map +1 -0
  97. package/dist/router.js +463 -0
  98. package/dist/router.js.map +1 -0
  99. package/dist/server.cjs +103 -0
  100. package/dist/server.d.cts +22 -4
  101. package/dist/server.d.ts +22 -4
  102. package/dist/server.d.ts.map +1 -0
  103. package/dist/server.js +2429 -8
  104. package/dist/server.js.map +1 -0
  105. package/dist/services/audit.service.d.ts +23 -0
  106. package/dist/services/audit.service.d.ts.map +1 -0
  107. package/dist/services/audit.service.js +28 -0
  108. package/dist/services/audit.service.js.map +1 -0
  109. package/dist/services/defaults.service.d.ts +8 -0
  110. package/dist/services/defaults.service.d.ts.map +1 -0
  111. package/dist/services/defaults.service.js +55 -0
  112. package/dist/services/defaults.service.js.map +1 -0
  113. package/dist/services/email.service.d.ts +33 -0
  114. package/dist/services/email.service.d.ts.map +1 -0
  115. package/dist/services/email.service.js +219 -0
  116. package/dist/services/email.service.js.map +1 -0
  117. package/dist/services/media.service.d.ts +20 -0
  118. package/dist/services/media.service.d.ts.map +1 -0
  119. package/dist/services/media.service.js +49 -0
  120. package/dist/services/media.service.js.map +1 -0
  121. package/dist/services/population.service.d.ts +20 -0
  122. package/dist/services/population.service.d.ts.map +1 -0
  123. package/dist/services/population.service.js +168 -0
  124. package/dist/services/population.service.js.map +1 -0
  125. package/dist/types/index.d.ts +1749 -0
  126. package/dist/types/index.d.ts.map +1 -0
  127. package/dist/types/index.js +3 -0
  128. package/dist/types/index.js.map +1 -0
  129. package/dist/utils/config.d.ts +8 -0
  130. package/dist/utils/config.d.ts.map +1 -0
  131. package/dist/utils/config.js +153 -0
  132. package/dist/utils/config.js.map +1 -0
  133. package/dist/utils/hooks.d.ts +41 -0
  134. package/dist/utils/hooks.d.ts.map +1 -0
  135. package/dist/utils/hooks.js +169 -0
  136. package/dist/utils/hooks.js.map +1 -0
  137. package/dist/utils/openapi.d.ts +6 -0
  138. package/dist/utils/openapi.d.ts.map +1 -0
  139. package/dist/utils/openapi.js +331 -0
  140. package/dist/utils/openapi.js.map +1 -0
  141. package/dist/utils/parse-where.d.ts +63 -0
  142. package/dist/utils/parse-where.d.ts.map +1 -0
  143. package/dist/utils/parse-where.js +196 -0
  144. package/dist/utils/parse-where.js.map +1 -0
  145. package/dist/utils/readonly-db.d.ts +9 -0
  146. package/dist/utils/readonly-db.d.ts.map +1 -0
  147. package/dist/utils/readonly-db.js +21 -0
  148. package/dist/utils/readonly-db.js.map +1 -0
  149. package/dist/utils/setup-prompt.d.ts +11 -0
  150. package/dist/utils/setup-prompt.d.ts.map +1 -0
  151. package/dist/utils/setup-prompt.js +863 -0
  152. package/dist/utils/setup-prompt.js.map +1 -0
  153. package/dist/utils/swagger.d.ts +5 -0
  154. package/dist/utils/swagger.d.ts.map +1 -0
  155. package/dist/utils/swagger.js +51 -0
  156. package/dist/utils/swagger.js.map +1 -0
  157. package/dist/utils/where-sanitizer.d.ts +10 -0
  158. package/dist/utils/where-sanitizer.d.ts.map +1 -0
  159. package/dist/utils/where-sanitizer.js +63 -0
  160. package/dist/utils/where-sanitizer.js.map +1 -0
  161. package/dist/where-sanitizer-DQIWTQZW.js +50 -0
  162. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,20 +15,11 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/index.ts
31
21
  var index_exports = {};
32
22
  __export(index_exports, {
33
- createDyrectedApp: () => createDyrectedApp,
34
23
  defineCollection: () => defineCollection,
35
24
  defineConfig: () => defineConfig,
36
25
  defineGlobal: () => defineGlobal,
@@ -1040,10 +1029,10 @@ function parseSqlWhere(where, getJsonField, placeholder = "?") {
1040
1029
  function buildSingleOp(c, op, operand) {
1041
1030
  switch (op) {
1042
1031
  case "equals":
1043
- params.push(operand);
1032
+ params.push(typeof operand === "boolean" ? String(operand) : operand);
1044
1033
  return `${c} = ${next()}`;
1045
1034
  case "not_equals":
1046
- params.push(operand);
1035
+ params.push(typeof operand === "boolean" ? String(operand) : operand);
1047
1036
  return `${c} != ${next()}`;
1048
1037
  case "in": {
1049
1038
  const vals = Array.isArray(operand) ? operand : [operand];
@@ -1328,2388 +1317,6 @@ async function executeFieldAfterRead(fields, doc, user, db) {
1328
1317
  return result;
1329
1318
  }
1330
1319
 
1331
- // src/app.ts
1332
- var import_hono = require("hono");
1333
- var import_cors = require("hono/cors");
1334
- var import_request_id = require("hono/request-id");
1335
-
1336
- // src/services/defaults.service.ts
1337
- var DefaultsService = class {
1338
- /**
1339
- * Recursively apply default values to a data object based on field definitions.
1340
- */
1341
- static apply(fields, data = {}) {
1342
- const result = { ...data || {} };
1343
- fields.forEach((field) => {
1344
- if (field.type === "join") return;
1345
- if (field.type === "row" && field.fields) {
1346
- Object.assign(result, this.apply(field.fields, data));
1347
- return;
1348
- }
1349
- if (!field.name) return;
1350
- let value = result[field.name];
1351
- if ((value === void 0 || value === null) && field.renameTo) {
1352
- const legacyValue = result[field.renameTo];
1353
- if (legacyValue !== void 0 && legacyValue !== null) {
1354
- value = legacyValue;
1355
- result[field.name] = legacyValue;
1356
- }
1357
- }
1358
- if (value === void 0 || value === null) {
1359
- if (field.defaultValue !== void 0) {
1360
- result[field.name] = field.defaultValue;
1361
- } else {
1362
- if (field.type === "boolean") result[field.name] = false;
1363
- else if (field.type === "array") result[field.name] = [];
1364
- else if (field.type === "multiSelect") result[field.name] = [];
1365
- else if (field.type === "object") {
1366
- result[field.name] = this.apply(field.fields || [], {});
1367
- }
1368
- }
1369
- } else if (field.type === "object" && field.fields) {
1370
- result[field.name] = this.apply(field.fields, value);
1371
- } else if (field.type === "array" && field.fields && Array.isArray(value)) {
1372
- result[field.name] = value.map((item) => this.apply(field.fields, item));
1373
- }
1374
- });
1375
- return result;
1376
- }
1377
- };
1378
-
1379
- // src/services/population.service.ts
1380
- var PopulationService = class {
1381
- db;
1382
- collections;
1383
- constructor(db, collections) {
1384
- this.db = db;
1385
- this.collections = collections;
1386
- }
1387
- /**
1388
- * Recursively populate relationship fields in a document or array of documents.
1389
- */
1390
- async populate(args) {
1391
- const { data, fields, currentDepth = 0, maxDepth = 10 } = args;
1392
- if (currentDepth >= maxDepth || !data) {
1393
- return data;
1394
- }
1395
- if (Array.isArray(data)) {
1396
- return Promise.all(data.map((item) => this.populate({ ...args, data: item })));
1397
- }
1398
- const populatedDoc = { ...data };
1399
- for (const field of fields) {
1400
- if (field.type === "join" && field.collection && field.on && currentDepth === 0) {
1401
- const targetCollection = this.collections.find((c) => c.slug === field.collection);
1402
- if (targetCollection) {
1403
- const docId = populatedDoc.id;
1404
- if (docId) {
1405
- const where = { [field.on]: { equals: docId } };
1406
- const joinLimit = field.limit ?? 10;
1407
- const result = await this.db.find({
1408
- collection: field.collection,
1409
- where,
1410
- limit: joinLimit
1411
- });
1412
- const populatedDocs = await this.populate({
1413
- data: result.docs.map((doc) => DefaultsService.apply(targetCollection.fields, doc)),
1414
- fields: targetCollection.fields,
1415
- currentDepth: 1,
1416
- maxDepth
1417
- });
1418
- populatedDoc[field.name] = {
1419
- docs: populatedDocs,
1420
- hasNextPage: result.page * result.limit < result.total,
1421
- totalDocs: result.total
1422
- };
1423
- }
1424
- }
1425
- continue;
1426
- }
1427
- if (field.type === "row" && field.fields) {
1428
- const rowPopulated = await this.populate({ data, fields: field.fields, currentDepth, maxDepth });
1429
- Object.assign(populatedDoc, rowPopulated);
1430
- continue;
1431
- }
1432
- if (!field.name) continue;
1433
- const value = populatedDoc[field.name];
1434
- if (field.type === "relationship" && field.relationTo && value) {
1435
- const relatedCollection = this.collections.find((c) => c.slug === field.relationTo);
1436
- if (!relatedCollection) continue;
1437
- if (Array.isArray(value)) {
1438
- populatedDoc[field.name] = await Promise.all(
1439
- value.map(async (id) => {
1440
- if (!id) return id;
1441
- let doc = id;
1442
- if (typeof id === "string") {
1443
- doc = await this.db.findOne({ collection: field.relationTo, id });
1444
- }
1445
- if (!doc || typeof doc !== "object") return id;
1446
- const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
1447
- return this.populate({
1448
- data: docWithDefaults,
1449
- fields: relatedCollection.fields,
1450
- currentDepth: currentDepth + 1,
1451
- maxDepth
1452
- });
1453
- })
1454
- );
1455
- } else if (value) {
1456
- let doc = value;
1457
- if (typeof value === "string") {
1458
- doc = await this.db.findOne({ collection: field.relationTo, id: value });
1459
- }
1460
- if (doc && typeof doc === "object") {
1461
- const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
1462
- populatedDoc[field.name] = await this.populate({
1463
- data: docWithDefaults,
1464
- fields: relatedCollection.fields,
1465
- currentDepth: currentDepth + 1,
1466
- maxDepth
1467
- });
1468
- }
1469
- }
1470
- }
1471
- if (field.type === "url" && value && typeof value === "object" && value.type === "internal" && value.relationTo && value.value) {
1472
- const relatedCollection = this.collections.find((c) => c.slug === value.relationTo);
1473
- if (relatedCollection) {
1474
- const doc = await this.db.findOne({ collection: value.relationTo, id: value.value });
1475
- if (doc && typeof doc === "object") {
1476
- const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
1477
- const populatedDocValue = await this.populate({
1478
- data: docWithDefaults,
1479
- fields: relatedCollection.fields,
1480
- currentDepth: currentDepth + 1,
1481
- maxDepth
1482
- });
1483
- const identifier = docWithDefaults.slug || docWithDefaults.id;
1484
- const resolvedUrl = `/collections/${value.relationTo}/${identifier}`;
1485
- populatedDoc[field.name] = {
1486
- ...value,
1487
- url: resolvedUrl,
1488
- doc: populatedDocValue
1489
- };
1490
- }
1491
- }
1492
- }
1493
- if ((field.type === "array" || field.type === "object") && field.fields && value) {
1494
- populatedDoc[field.name] = await this.populate({
1495
- data: value,
1496
- fields: field.fields,
1497
- currentDepth,
1498
- // Nested fields don't consume depth, only relationships do
1499
- maxDepth
1500
- });
1501
- }
1502
- if (field.type === "blocks" && field.blocks && Array.isArray(value)) {
1503
- populatedDoc[field.name] = await Promise.all(
1504
- value.map(async (blockData) => {
1505
- const blockConfig = field.blocks.find((b) => b.slug === blockData.blockType);
1506
- if (!blockConfig) return blockData;
1507
- return this.populate({
1508
- data: blockData,
1509
- fields: blockConfig.fields,
1510
- currentDepth,
1511
- maxDepth
1512
- });
1513
- })
1514
- );
1515
- }
1516
- }
1517
- return populatedDoc;
1518
- }
1519
- /**
1520
- * Helper to populate a PaginatedResult
1521
- */
1522
- async populateResult(result, fields, maxDepth) {
1523
- if (maxDepth <= 0) return result;
1524
- const populatedDocs = await this.populate({
1525
- data: result.docs,
1526
- fields,
1527
- currentDepth: 0,
1528
- maxDepth
1529
- });
1530
- return {
1531
- ...result,
1532
- docs: populatedDocs
1533
- };
1534
- }
1535
- };
1536
-
1537
- // src/services/audit.service.ts
1538
- var AuditService = class {
1539
- /**
1540
- * Writes a single entry to the __audit collection.
1541
- * Called without await — runs asynchronously and never blocks the primary operation.
1542
- */
1543
- static async log(db, args) {
1544
- try {
1545
- await db.create({
1546
- collection: "__audit",
1547
- data: {
1548
- collection: args.collection,
1549
- documentId: args.documentId ?? null,
1550
- operation: args.operation,
1551
- user: args.user?.id ?? null,
1552
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1553
- changes: JSON.stringify({
1554
- before: args.before ?? null,
1555
- after: args.after ?? null
1556
- })
1557
- }
1558
- });
1559
- } catch (err) {
1560
- console.error("[dyrected/audit] Failed to write audit log:", err);
1561
- }
1562
- }
1563
- };
1564
-
1565
- // src/auth/password.ts
1566
- var import_node_util = require("util");
1567
- var import_node_crypto = require("crypto");
1568
- var scryptAsync = (0, import_node_util.promisify)(import_node_crypto.scrypt);
1569
- var SALT_LEN = 16;
1570
- var KEY_LEN = 64;
1571
- async function hashPassword(plain) {
1572
- const salt = (0, import_node_crypto.randomBytes)(SALT_LEN).toString("hex");
1573
- const derivedKey = await scryptAsync(plain, salt, KEY_LEN);
1574
- return `${salt}:${derivedKey.toString("hex")}`;
1575
- }
1576
- async function verifyPassword(plain, stored) {
1577
- const [salt, storedHash] = stored.split(":");
1578
- if (!salt || !storedHash) return false;
1579
- const derivedKey = await scryptAsync(plain, salt, KEY_LEN);
1580
- const storedBuffer = Buffer.from(storedHash, "hex");
1581
- if (derivedKey.length !== storedBuffer.length) return false;
1582
- return (0, import_node_crypto.timingSafeEqual)(derivedKey, storedBuffer);
1583
- }
1584
-
1585
- // src/utils/readonly-db.ts
1586
- var WRITE_METHODS = ["create", "update", "delete", "updateGlobal", "execute"];
1587
- function createReadonlyDb(db) {
1588
- return new Proxy(db, {
1589
- get(target, prop) {
1590
- if (WRITE_METHODS.includes(prop)) {
1591
- return () => {
1592
- throw new Error(
1593
- `[dyrected] Write operation "${String(prop)}" is not allowed in this hook phase. Use afterChange/afterDelete hooks for write operations.`
1594
- );
1595
- };
1596
- }
1597
- return Reflect.get(target, prop);
1598
- }
1599
- });
1600
- }
1601
-
1602
- // src/controllers/collection.controller.ts
1603
- var CollectionController = class {
1604
- collection;
1605
- constructor(collection) {
1606
- this.collection = collection;
1607
- }
1608
- async find(c) {
1609
- const config = c.get("config");
1610
- const db = config.db;
1611
- if (!db) return c.json({ message: "Database not configured" }, 500);
1612
- const readonlyDb = createReadonlyDb(db);
1613
- const limit = Number(c.req.query("limit")) || 10;
1614
- const page = Number(c.req.query("page")) || 1;
1615
- const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 2;
1616
- const sort = c.req.query("sort") || void 0;
1617
- const user = c.get("user");
1618
- let where = void 0;
1619
- const whereRaw = c.req.query("where");
1620
- if (whereRaw) {
1621
- try {
1622
- where = JSON.parse(decodeURIComponent(whereRaw));
1623
- } catch {
1624
- }
1625
- }
1626
- const beforeReadResult = await runCollectionHooks(this.collection.hooks?.beforeRead, {
1627
- req: c.req,
1628
- query: where,
1629
- user,
1630
- db: readonlyDb
1631
- });
1632
- if (beforeReadResult !== void 0) {
1633
- where = beforeReadResult;
1634
- }
1635
- let result = await db.find({
1636
- collection: this.collection.slug,
1637
- limit,
1638
- page,
1639
- sort,
1640
- where
1641
- });
1642
- if (result.total === 0 && this.collection.initialData && !where && page === 1) {
1643
- console.log(`[dyrected/core] Auto-seeding collection "${this.collection.slug}" from config.initialData`);
1644
- for (const data of this.collection.initialData) {
1645
- await db.create({ collection: this.collection.slug, data });
1646
- }
1647
- result = await db.find({
1648
- collection: this.collection.slug,
1649
- limit,
1650
- page,
1651
- sort,
1652
- where
1653
- });
1654
- }
1655
- result.docs = result.docs.map((doc) => DefaultsService.apply(this.collection.fields, doc));
1656
- const processedDocs = [];
1657
- for (const doc of result.docs) {
1658
- const docWithCollectionHooks = await runCollectionHooks(this.collection.hooks?.afterRead, {
1659
- doc,
1660
- req: c.req,
1661
- user,
1662
- db: readonlyDb
1663
- });
1664
- const docWithFieldHooks = await executeFieldAfterRead(this.collection.fields, docWithCollectionHooks, user, readonlyDb);
1665
- processedDocs.push(docWithFieldHooks);
1666
- }
1667
- result.docs = processedDocs;
1668
- if (depth > 0) {
1669
- const populationService = new PopulationService(db, config.collections);
1670
- result = await populationService.populateResult(result, this.collection.fields, depth);
1671
- }
1672
- return c.json(result);
1673
- }
1674
- async findOne(c) {
1675
- const config = c.get("config");
1676
- const db = config.db;
1677
- if (!db) return c.json({ message: "Database not configured" }, 500);
1678
- const readonlyDb = createReadonlyDb(db);
1679
- const id = c.req.param("id");
1680
- const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 10;
1681
- const user = c.get("user");
1682
- if (!id) return c.json({ message: "Missing ID" }, 400);
1683
- const doc = await db.findOne({ collection: this.collection.slug, id });
1684
- if (!doc) return c.json({ message: "Not Found" }, 404);
1685
- const docWithDefaults = DefaultsService.apply(this.collection.fields, doc);
1686
- const docWithCollectionHooks = await runCollectionHooks(this.collection.hooks?.afterRead, {
1687
- doc: docWithDefaults,
1688
- req: c.req,
1689
- user,
1690
- db: readonlyDb
1691
- });
1692
- const docWithFieldHooks = await executeFieldAfterRead(this.collection.fields, docWithCollectionHooks, user, readonlyDb);
1693
- if (depth > 0 && docWithFieldHooks) {
1694
- const populationService = new PopulationService(db, config.collections);
1695
- const populatedDoc = await populationService.populate({
1696
- data: docWithFieldHooks,
1697
- fields: this.collection.fields,
1698
- currentDepth: 0,
1699
- maxDepth: depth
1700
- });
1701
- return c.json(populatedDoc);
1702
- }
1703
- return c.json(docWithFieldHooks);
1704
- }
1705
- async create(c) {
1706
- const config = c.get("config");
1707
- const db = config.db;
1708
- if (!db) return c.json({ message: "Database not configured" }, 500);
1709
- const readonlyDb = createReadonlyDb(db);
1710
- const contentType = c.req.header("Content-Type") || "";
1711
- if (contentType.toLowerCase().includes("multipart/form-data")) {
1712
- return this.upload(c);
1713
- }
1714
- const body = await c.req.json();
1715
- const user = c.get("user");
1716
- const now = (/* @__PURE__ */ new Date()).toISOString();
1717
- let data = {
1718
- ...body,
1719
- createdAt: now,
1720
- updatedAt: now,
1721
- createdBy: user?.sub ?? null,
1722
- updatedBy: user?.sub ?? null
1723
- };
1724
- if (this.collection.auth && data.password) {
1725
- data.password = await hashPassword(data.password);
1726
- }
1727
- data = await executeFieldBeforeChange(this.collection.fields, data, null, user, readonlyDb);
1728
- data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
1729
- data,
1730
- req: c.req,
1731
- user,
1732
- operation: "create",
1733
- db: readonlyDb
1734
- });
1735
- const doc = await db.create({ collection: this.collection.slug, data });
1736
- if (this.collection.audit && db) {
1737
- AuditService.log(db, {
1738
- operation: "create",
1739
- collection: this.collection.slug,
1740
- documentId: doc.id,
1741
- user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
1742
- before: null,
1743
- after: doc
1744
- });
1745
- }
1746
- await runCollectionHooks(this.collection.hooks?.afterChange, {
1747
- doc,
1748
- user,
1749
- req: c.req,
1750
- operation: "create",
1751
- db
1752
- }, { isolated: true });
1753
- const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
1754
- doc,
1755
- req: c.req,
1756
- user,
1757
- db: readonlyDb
1758
- });
1759
- const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user, readonlyDb);
1760
- return c.json(finalDoc, 201);
1761
- }
1762
- async upload(c) {
1763
- const config = c.get("config");
1764
- const storage = config.storage;
1765
- if (!storage) return c.json({ message: "Storage not configured" }, 500);
1766
- const db = config.db;
1767
- if (!db) return c.json({ message: "Database not configured" }, 500);
1768
- const readonlyDb = createReadonlyDb(db);
1769
- const formData = await c.req.formData();
1770
- const file = formData.get("file");
1771
- if (!file) return c.json({ message: "No file uploaded" }, 400);
1772
- const buffer = new Uint8Array(await file.arrayBuffer());
1773
- const siteId = c.get("siteId");
1774
- const workspaceId = c.get("workspaceId");
1775
- const prefix = workspaceId ? `${workspaceId}/${siteId}` : siteId;
1776
- const fileData = await storage.upload({
1777
- filename: file.name,
1778
- buffer,
1779
- mimeType: file.type,
1780
- prefix
1781
- });
1782
- const otherData = {};
1783
- formData.forEach((value, key) => {
1784
- if (key !== "file" && typeof value === "string") {
1785
- otherData[key] = value;
1786
- }
1787
- });
1788
- const user = c.get("user");
1789
- const now = (/* @__PURE__ */ new Date()).toISOString();
1790
- let data = {
1791
- ...otherData,
1792
- ...fileData,
1793
- createdAt: now,
1794
- updatedAt: now,
1795
- createdBy: user?.sub ?? null,
1796
- updatedBy: user?.sub ?? null
1797
- };
1798
- data = await executeFieldBeforeChange(this.collection.fields, data, null, user, readonlyDb);
1799
- data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
1800
- data,
1801
- req: c.req,
1802
- user,
1803
- operation: "create",
1804
- db: readonlyDb
1805
- });
1806
- const doc = await db.create({
1807
- collection: this.collection.slug,
1808
- data
1809
- });
1810
- await runCollectionHooks(this.collection.hooks?.afterChange, {
1811
- doc,
1812
- user,
1813
- req: c.req,
1814
- operation: "create",
1815
- db
1816
- }, { isolated: true });
1817
- const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
1818
- doc,
1819
- req: c.req,
1820
- user,
1821
- db: readonlyDb
1822
- });
1823
- const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user, readonlyDb);
1824
- return c.json(finalDoc, 201);
1825
- }
1826
- async update(c) {
1827
- const config = c.get("config");
1828
- const db = config.db;
1829
- if (!db) return c.json({ message: "Database not configured" }, 500);
1830
- const readonlyDb = createReadonlyDb(db);
1831
- const id = c.req.param("id");
1832
- if (!id) return c.json({ message: "Missing ID" }, 400);
1833
- const body = await c.req.json();
1834
- const user = c.get("user");
1835
- let data = { ...body };
1836
- if (this.collection.auth) {
1837
- delete data.password;
1838
- delete data.oldPassword;
1839
- delete data.confirmPassword;
1840
- }
1841
- Object.assign(data, {
1842
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1843
- updatedBy: user?.sub ?? null
1844
- });
1845
- const originalDoc = await db.findOne({ collection: this.collection.slug, id });
1846
- if (!originalDoc) return c.json({ message: "Not Found" }, 404);
1847
- let before = null;
1848
- if (this.collection.audit) {
1849
- before = originalDoc;
1850
- }
1851
- data = await executeFieldBeforeChange(this.collection.fields, data, originalDoc, user, readonlyDb);
1852
- data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
1853
- data,
1854
- doc: originalDoc,
1855
- req: c.req,
1856
- user,
1857
- operation: "update",
1858
- db: readonlyDb
1859
- });
1860
- const doc = await db.update({ collection: this.collection.slug, id, data });
1861
- if (this.collection.audit && db) {
1862
- AuditService.log(db, {
1863
- operation: "update",
1864
- collection: this.collection.slug,
1865
- documentId: id,
1866
- user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
1867
- before,
1868
- after: doc
1869
- });
1870
- }
1871
- await runCollectionHooks(this.collection.hooks?.afterChange, {
1872
- doc,
1873
- previousDoc: originalDoc,
1874
- user,
1875
- req: c.req,
1876
- operation: "update",
1877
- db
1878
- }, { isolated: true });
1879
- const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
1880
- doc,
1881
- req: c.req,
1882
- user,
1883
- db: readonlyDb
1884
- });
1885
- const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user, readonlyDb);
1886
- return c.json(finalDoc);
1887
- }
1888
- /**
1889
- * POST /api/collections/:slug/:id/change-password
1890
- *
1891
- * Dedicated endpoint for password changes. Requires the caller to supply:
1892
- * { oldPassword, newPassword, confirmPassword }
1893
- *
1894
- * Rules:
1895
- * - Only the account owner or an admin may change the password.
1896
- * - Non-admin callers MUST provide a valid oldPassword.
1897
- * - newPassword and confirmPassword must match.
1898
- */
1899
- async changePassword(c) {
1900
- const config = c.get("config");
1901
- const db = config.db;
1902
- if (!db) return c.json({ message: "Database not configured" }, 500);
1903
- if (!this.collection.auth) {
1904
- return c.json({ message: "This collection does not support authentication" }, 400);
1905
- }
1906
- const id = c.req.param("id");
1907
- if (!id) return c.json({ message: "Missing ID" }, 400);
1908
- const user = c.get("user");
1909
- if (!user) return c.json({ message: "Authentication required" }, 401);
1910
- const body = await c.req.json().catch(() => null);
1911
- const { oldPassword, newPassword, confirmPassword } = body ?? {};
1912
- if (!newPassword) {
1913
- return c.json({ message: "newPassword is required" }, 400);
1914
- }
1915
- if (newPassword !== confirmPassword) {
1916
- return c.json({ message: "Passwords do not match" }, 400);
1917
- }
1918
- if (newPassword.length < 8) {
1919
- return c.json({ message: "Password must be at least 8 characters" }, 400);
1920
- }
1921
- const isAdmin = Array.isArray(user.roles) && user.roles.includes("admin");
1922
- const isSelf = user.sub === id;
1923
- if (!isAdmin && !isSelf) {
1924
- return c.json({ message: "You are not authorised to change this password" }, 403);
1925
- }
1926
- if (!isAdmin) {
1927
- if (!oldPassword) {
1928
- return c.json({ message: "Current password is required" }, 400);
1929
- }
1930
- const existing = await db.findOne({ collection: this.collection.slug, id });
1931
- if (!existing) return c.json({ message: "User not found" }, 404);
1932
- const valid = await verifyPassword(oldPassword, existing.password);
1933
- if (!valid) {
1934
- return c.json({ message: "Invalid current password" }, 400);
1935
- }
1936
- }
1937
- const hashed = await hashPassword(newPassword);
1938
- const doc = await db.update({
1939
- collection: this.collection.slug,
1940
- id,
1941
- data: {
1942
- password: hashed,
1943
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1944
- updatedBy: user.sub
1945
- }
1946
- });
1947
- if (this.collection.audit) {
1948
- AuditService.log(db, {
1949
- operation: "update",
1950
- collection: this.collection.slug,
1951
- documentId: id,
1952
- user: { id: user.sub, collection: user.collection, email: user.email },
1953
- before: null,
1954
- after: { id }
1955
- });
1956
- }
1957
- return c.json({ success: true, message: "Password updated successfully" });
1958
- }
1959
- async delete(c) {
1960
- const config = c.get("config");
1961
- const db = config.db;
1962
- if (!db) return c.json({ message: "Database not configured" }, 500);
1963
- const readonlyDb = createReadonlyDb(db);
1964
- const id = c.req.param("id");
1965
- if (!id) return c.json({ message: "Missing ID" }, 400);
1966
- const user = c.get("user");
1967
- const doc = await db.findOne({ collection: this.collection.slug, id });
1968
- if (!doc) return c.json({ message: "Not Found" }, 404);
1969
- let before = null;
1970
- if (this.collection.audit) {
1971
- before = doc;
1972
- }
1973
- await runCollectionHooks(this.collection.hooks?.beforeDelete, {
1974
- id,
1975
- doc,
1976
- user,
1977
- req: c.req,
1978
- db: readonlyDb
1979
- });
1980
- await db.delete({ collection: this.collection.slug, id });
1981
- if (this.collection.audit && db) {
1982
- AuditService.log(db, {
1983
- operation: "delete",
1984
- collection: this.collection.slug,
1985
- documentId: id,
1986
- user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
1987
- before,
1988
- after: null
1989
- });
1990
- }
1991
- await runCollectionHooks(this.collection.hooks?.afterDelete, {
1992
- id,
1993
- doc,
1994
- user,
1995
- req: c.req,
1996
- db
1997
- }, { isolated: true });
1998
- return c.json({ message: "Deleted" });
1999
- }
2000
- async deleteMany(c) {
2001
- const config = c.get("config");
2002
- const db = config.db;
2003
- if (!db) return c.json({ message: "Database not configured" }, 500);
2004
- const readonlyDb = createReadonlyDb(db);
2005
- const user = c.get("user");
2006
- let ids = [];
2007
- try {
2008
- const body = await c.req.json().catch(() => null);
2009
- if (body?.ids && Array.isArray(body.ids)) {
2010
- ids = body.ids;
2011
- }
2012
- } catch {
2013
- }
2014
- if (!ids.length) {
2015
- const raw = c.req.queries("ids") ?? c.req.queries("ids[]") ?? [];
2016
- ids = raw.filter(Boolean);
2017
- }
2018
- if (!ids.length) return c.json({ message: "No IDs provided" }, 400);
2019
- const deleted = [];
2020
- const failed = [];
2021
- for (const id of ids) {
2022
- try {
2023
- const doc = await db.findOne({ collection: this.collection.slug, id });
2024
- if (!doc) {
2025
- failed.push({ id, error: "Not Found" });
2026
- continue;
2027
- }
2028
- let before = null;
2029
- if (this.collection.audit) {
2030
- before = doc;
2031
- }
2032
- await runCollectionHooks(this.collection.hooks?.beforeDelete, {
2033
- id,
2034
- doc,
2035
- user,
2036
- req: c.req,
2037
- db: readonlyDb
2038
- });
2039
- await db.delete({ collection: this.collection.slug, id });
2040
- deleted.push(id);
2041
- if (this.collection.audit) {
2042
- AuditService.log(db, {
2043
- operation: "delete",
2044
- collection: this.collection.slug,
2045
- documentId: id,
2046
- user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
2047
- before,
2048
- after: null
2049
- });
2050
- }
2051
- await runCollectionHooks(this.collection.hooks?.afterDelete, {
2052
- id,
2053
- doc,
2054
- user,
2055
- req: c.req,
2056
- db
2057
- }, { isolated: true });
2058
- } catch (err) {
2059
- failed.push({ id, error: err?.message ?? "Unknown error" });
2060
- }
2061
- }
2062
- return c.json({
2063
- message: `Deleted ${deleted.length} document(s)`,
2064
- deleted,
2065
- ...failed.length ? { failed } : {}
2066
- });
2067
- }
2068
- async seed(c) {
2069
- const config = c.get("config");
2070
- const db = config.db;
2071
- if (!db) return c.json({ message: "Database not configured" }, 500);
2072
- const body = await c.req.json();
2073
- const initialData = body.data;
2074
- if (!initialData || !Array.isArray(initialData)) {
2075
- return c.json({ message: "Invalid initial data" }, 400);
2076
- }
2077
- const result = await db.find({ collection: this.collection.slug, limit: 1 });
2078
- if (result.total > 0) {
2079
- return c.json({ message: "Collection is not empty, skipping seed" });
2080
- }
2081
- console.log(`[dyrected/core] Auto-seeding collection: ${this.collection.slug}`);
2082
- const createdDocs = [];
2083
- for (const data of initialData) {
2084
- const doc = await db.create({ collection: this.collection.slug, data });
2085
- createdDocs.push(doc);
2086
- }
2087
- return c.json({ message: "Seed successful", count: createdDocs.length }, 201);
2088
- }
2089
- };
2090
-
2091
- // src/controllers/global.controller.ts
2092
- var GlobalController = class {
2093
- global;
2094
- constructor(global) {
2095
- this.global = global;
2096
- }
2097
- async get(c) {
2098
- const config = c.get("config");
2099
- const db = config.db;
2100
- if (!db) return c.json({ message: "Database not configured" }, 500);
2101
- const readonlyDb = createReadonlyDb(db);
2102
- const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 10;
2103
- const user = c.get("user");
2104
- let query = void 0;
2105
- const beforeReadResult = await runCollectionHooks(this.global.hooks?.beforeRead, {
2106
- req: c.req,
2107
- query,
2108
- user,
2109
- db: readonlyDb
2110
- });
2111
- if (beforeReadResult !== void 0) {
2112
- query = beforeReadResult;
2113
- }
2114
- let data = await db.getGlobal({ slug: this.global.slug });
2115
- const isEmpty = !data || Object.keys(data).length === 0;
2116
- if (isEmpty && this.global.initialData) {
2117
- console.log(`[dyrected/core] Auto-seeding global "${this.global.slug}" from config.initialData`);
2118
- await db.updateGlobal({ slug: this.global.slug, data: this.global.initialData });
2119
- data = this.global.initialData;
2120
- }
2121
- const dataWithDefaults = DefaultsService.apply(this.global.fields, data);
2122
- const docWithCollectionHooks = await runCollectionHooks(this.global.hooks?.afterRead, {
2123
- doc: dataWithDefaults,
2124
- req: c.req,
2125
- user,
2126
- db: readonlyDb
2127
- });
2128
- const docWithFieldHooks = await executeFieldAfterRead(this.global.fields, docWithCollectionHooks, user, readonlyDb);
2129
- if (depth > 0 && docWithFieldHooks) {
2130
- const populationService = new PopulationService(db, config.collections);
2131
- const populatedData = await populationService.populate({
2132
- data: docWithFieldHooks,
2133
- fields: this.global.fields,
2134
- currentDepth: 0,
2135
- maxDepth: depth
2136
- });
2137
- return c.json(populatedData);
2138
- }
2139
- return c.json(docWithFieldHooks);
2140
- }
2141
- async update(c) {
2142
- const config = c.get("config");
2143
- const db = config.db;
2144
- if (!db) return c.json({ message: "Database not configured" }, 500);
2145
- const readonlyDb = createReadonlyDb(db);
2146
- const body = await c.req.json();
2147
- const user = c.get("user");
2148
- const originalDoc = await db.getGlobal({ slug: this.global.slug }) || {};
2149
- let data = await executeFieldBeforeChange(this.global.fields, body, originalDoc, user, readonlyDb);
2150
- data = await runCollectionHooks(this.global.hooks?.beforeChange, {
2151
- data,
2152
- doc: originalDoc,
2153
- req: c.req,
2154
- user,
2155
- operation: "update",
2156
- db: readonlyDb
2157
- });
2158
- const updated = await db.updateGlobal({ slug: this.global.slug, data });
2159
- await runCollectionHooks(this.global.hooks?.afterChange, {
2160
- doc: updated,
2161
- previousDoc: originalDoc,
2162
- user,
2163
- req: c.req,
2164
- operation: "update",
2165
- db
2166
- }, { isolated: true });
2167
- const readDoc = await runCollectionHooks(this.global.hooks?.afterRead, {
2168
- doc: updated,
2169
- req: c.req,
2170
- user,
2171
- db: readonlyDb
2172
- });
2173
- const finalDoc = await executeFieldAfterRead(this.global.fields, readDoc, user, readonlyDb);
2174
- return c.json(finalDoc);
2175
- }
2176
- async seed(c) {
2177
- const config = c.get("config");
2178
- const db = config.db;
2179
- if (!db) return c.json({ message: "Database not configured" }, 500);
2180
- const body = await c.req.json();
2181
- const initialData = body.data;
2182
- if (!initialData) {
2183
- return c.json({ message: "Invalid initial data" }, 400);
2184
- }
2185
- const existing = await db.getGlobal({ slug: this.global.slug });
2186
- if (existing && Object.keys(existing).length > 0) {
2187
- return c.json({ message: "Global is not empty, skipping seed" });
2188
- }
2189
- console.log(`[dyrected/core] Auto-seeding global: ${this.global.slug}`);
2190
- await db.updateGlobal({ slug: this.global.slug, data: initialData });
2191
- return c.json({ message: "Seed successful", data: initialData }, 201);
2192
- }
2193
- };
2194
-
2195
- // src/controllers/media.controller.ts
2196
- var MediaController = class {
2197
- collection;
2198
- constructor(collection = "media") {
2199
- this.collection = collection;
2200
- }
2201
- async upload(c) {
2202
- const config = c.get("config");
2203
- const storage = config.storage;
2204
- const imageService = config.image;
2205
- if (!storage) {
2206
- return c.json({ message: "Storage not configured" }, 500);
2207
- }
2208
- const body = await c.req.parseBody();
2209
- const file = body["file"];
2210
- const focalPointStr = body["focalPoint"];
2211
- const focalPoint = focalPointStr ? JSON.parse(focalPointStr) : void 0;
2212
- if (!file) {
2213
- return c.json({ message: "No file uploaded" }, 400);
2214
- }
2215
- const buffer = new Uint8Array(await file.arrayBuffer());
2216
- const siteId = c.get("siteId");
2217
- const workspaceId = c.get("workspaceId");
2218
- const prefix = workspaceId ? `${workspaceId}/${siteId}` : siteId || "default";
2219
- let imageMetadata = {};
2220
- let imageSizes = {};
2221
- if (imageService && file.type.startsWith("image/")) {
2222
- let colConfig = config.collections.find((col) => col.slug === this.collection);
2223
- if (!colConfig && config.onSchemaFetch && siteId) {
2224
- const dynamic = await config.onSchemaFetch(siteId);
2225
- colConfig = dynamic.collections?.find((col) => col.slug === this.collection);
2226
- }
2227
- try {
2228
- const processed = await imageService.process({
2229
- buffer,
2230
- mimeType: file.type,
2231
- config: colConfig?.upload,
2232
- focalPoint
2233
- });
2234
- imageMetadata = processed.metadata;
2235
- imageSizes = processed.sizes;
2236
- } catch (err) {
2237
- console.error("[MediaController] Image processing failed:", err);
2238
- }
2239
- }
2240
- const fileData = await storage.upload({
2241
- filename: file.name,
2242
- buffer,
2243
- mimeType: file.type,
2244
- prefix
2245
- });
2246
- const finalFileData = {
2247
- ...fileData,
2248
- ...imageMetadata,
2249
- focalPoint,
2250
- sizes: {}
2251
- };
2252
- if (imageSizes) {
2253
- for (const [sizeName, sizeData] of Object.entries(imageSizes)) {
2254
- const ext = file.name.split(".").pop();
2255
- const baseName = file.name.substring(0, file.name.lastIndexOf("."));
2256
- const sizeFilename = `${baseName}-${sizeName}.${ext}`;
2257
- try {
2258
- const sizeFileData = await storage.upload({
2259
- filename: sizeFilename,
2260
- buffer: sizeData.buffer,
2261
- mimeType: file.type,
2262
- prefix
2263
- });
2264
- finalFileData.sizes[sizeName] = {
2265
- ...sizeFileData,
2266
- width: sizeData.width,
2267
- height: sizeData.height
2268
- };
2269
- } catch (err) {
2270
- console.error(`[MediaController] Failed to upload size ${sizeName}:`, err);
2271
- }
2272
- }
2273
- }
2274
- const db = config.db;
2275
- if (!db) return c.json({ message: "Database not configured" }, 500);
2276
- const doc = await db.create({
2277
- collection: this.collection,
2278
- data: finalFileData
2279
- });
2280
- return c.json(doc, 201);
2281
- }
2282
- async find(c) {
2283
- const db = c.get("config").db;
2284
- if (!db) return c.json({ message: "Database not configured" }, 500);
2285
- const limit = Number(c.req.query("limit")) || 10;
2286
- const page = Number(c.req.query("page")) || 1;
2287
- const result = await db.find({
2288
- collection: this.collection,
2289
- limit,
2290
- page
2291
- });
2292
- return c.json(result);
2293
- }
2294
- async delete(c) {
2295
- const config = c.get("config");
2296
- const storage = config.storage;
2297
- const db = config.db;
2298
- if (!db) return c.json({ message: "Database not configured" }, 500);
2299
- const id = c.req.param("id");
2300
- if (!id) return c.json({ message: "Missing ID" }, 400);
2301
- const doc = await db.findOne({ collection: this.collection, id });
2302
- if (!doc) return c.json({ message: "Not Found" }, 404);
2303
- if (storage) {
2304
- await storage.delete({ filename: doc.filename });
2305
- if (doc.sizes) {
2306
- for (const size of Object.values(doc.sizes)) {
2307
- if (size.filename) {
2308
- await storage.delete({ filename: size.filename });
2309
- }
2310
- }
2311
- }
2312
- }
2313
- await db.delete({ collection: this.collection, id });
2314
- return c.json({ message: "Deleted" });
2315
- }
2316
- async serve(c) {
2317
- const config = c.get("config");
2318
- const storage = config.storage;
2319
- if (!storage || !storage.resolve) {
2320
- return c.json({ message: "Storage not configured for serving" }, 404);
2321
- }
2322
- const filename = c.req.param("filename");
2323
- if (!filename) return c.json({ message: "Missing filename" }, 400);
2324
- let res = await storage.resolve({ filename });
2325
- if (!res && !filename.includes("/")) {
2326
- res = await storage.resolve({ filename: `default/${filename}` });
2327
- }
2328
- if (!res) return c.json({ message: "Not Found" }, 404);
2329
- c.header("Content-Type", res.mimeType);
2330
- return c.body(res.buffer);
2331
- }
2332
- };
2333
-
2334
- // src/auth/token.ts
2335
- var import_jose = require("jose");
2336
- var import_node_util2 = require("util");
2337
- function getSecret() {
2338
- const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET;
2339
- if (!secret) {
2340
- throw new Error(
2341
- "[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
2342
- );
2343
- }
2344
- return new import_node_util2.TextEncoder().encode(secret);
2345
- }
2346
- var DEFAULT_EXPIRY = "7d";
2347
- async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
2348
- return new import_jose.SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
2349
- }
2350
- async function verifyCollectionToken(token) {
2351
- const { payload } = await (0, import_jose.jwtVerify)(token, getSecret());
2352
- return payload;
2353
- }
2354
-
2355
- // src/services/email.service.ts
2356
- var _devSend = null;
2357
- var _devSendPromise = null;
2358
- async function getDevSend() {
2359
- if (_devSend) return _devSend;
2360
- if (_devSendPromise) return _devSendPromise;
2361
- _devSendPromise = (async () => {
2362
- try {
2363
- const nodemailer = await import("nodemailer");
2364
- const account = await nodemailer.default.createTestAccount();
2365
- const transport = nodemailer.default.createTransport({
2366
- host: "smtp.ethereal.email",
2367
- port: 587,
2368
- auth: { user: account.user, pass: account.pass }
2369
- });
2370
- console.log("[dyrected/core] No email config \u2014 using Ethereal for dev email preview.");
2371
- console.log(`[dyrected/core] Ethereal login: https://ethereal.email user: ${account.user} pass: ${account.pass}`);
2372
- _devSend = async ({ to, subject, html }) => {
2373
- const info = await transport.sendMail({ from: '"Dyrected Dev" <dev@dyrected.local>', to, subject, html });
2374
- console.log(`[dyrected/core] Email preview URL: ${nodemailer.default.getTestMessageUrl(info)}`);
2375
- };
2376
- return _devSend;
2377
- } catch {
2378
- console.warn("[dyrected/core] nodemailer not available \u2014 emails will not be sent in dev.");
2379
- return null;
2380
- }
2381
- })();
2382
- return _devSendPromise;
2383
- }
2384
- async function sendEmail(config, payload) {
2385
- if (config.email) {
2386
- await config.email.send(payload);
2387
- return;
2388
- }
2389
- if (process.env.NODE_ENV !== "production") {
2390
- const devSend = await getDevSend();
2391
- await devSend?.(payload);
2392
- }
2393
- }
2394
- function buildWelcomeEmail(config, args) {
2395
- const custom = config.email?.templates?.welcome?.(args);
2396
- return {
2397
- subject: custom?.subject ?? "Welcome \u2014 your account is ready",
2398
- html: custom?.html ?? `
2399
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f9fafb;table-layout:fixed">
2400
- <tr>
2401
- <td align="center" style="padding:40px 16px">
2402
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;background-color:#ffffff;border-radius:12px;border:1px solid #e5e7eb;table-layout:fixed">
2403
- <tr>
2404
- <td style="padding:32px 32px 0">
2405
- <p style="margin:0 0 4px;font-size:12px;font-weight:600;color:#6b7280;font-family:sans-serif;text-transform:uppercase;letter-spacing:0.05em">Dyrected</p>
2406
- <h1 style="margin:0 0 24px;font-size:22px;font-weight:700;color:#111827;font-family:sans-serif">Welcome!</h1>
2407
- </td>
2408
- </tr>
2409
- <tr>
2410
- <td style="padding:0 32px">
2411
- <p style="margin:0 0 12px;font-size:14px;color:#4b5563;line-height:1.6;font-family:sans-serif">Your account has been created. You can now log in with:</p>
2412
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f3f4f6;border-radius:6px;table-layout:fixed">
2413
- <tr>
2414
- <td style="padding:12px 16px;font-size:14px;font-weight:600;color:#111827;font-family:sans-serif;word-break:break-all">
2415
- ${args.email}
2416
- </td>
2417
- </tr>
2418
- </table>
2419
- </td>
2420
- </tr>
2421
- <tr>
2422
- <td style="padding:32px">
2423
- <p style="margin:0;font-size:12px;color:#9ca3af;font-family:sans-serif">If you didn't create this account, you can safely ignore this email.</p>
2424
- </td>
2425
- </tr>
2426
- </table>
2427
- </td>
2428
- </tr>
2429
- </table>`
2430
- };
2431
- }
2432
- function buildInviteEmail(config, args) {
2433
- const custom = config.email?.templates?.invite?.(args);
2434
- return {
2435
- subject: custom?.subject ?? "You've been invited",
2436
- html: custom?.html ?? `
2437
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f9fafb;table-layout:fixed">
2438
- <tr>
2439
- <td align="center" style="padding:40px 16px">
2440
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;background-color:#ffffff;border-radius:12px;border:1px solid #e5e7eb;table-layout:fixed">
2441
- <tr>
2442
- <td style="padding:32px 32px 0">
2443
- <p style="margin:0 0 4px;font-size:12px;font-weight:600;color:#6b7280;font-family:sans-serif;text-transform:uppercase;letter-spacing:0.05em">Dyrected</p>
2444
- <h1 style="margin:0 0 24px;font-size:22px;font-weight:700;color:#111827;font-family:sans-serif">You've been invited</h1>
2445
- </td>
2446
- </tr>
2447
- <tr>
2448
- <td style="padding:0 32px">
2449
- ${args.invitedByEmail ? `<p style="margin:0 0 12px;font-size:14px;color:#4b5563;line-height:1.6;font-family:sans-serif">You were invited by <strong style="color:#111827">${args.invitedByEmail}</strong>.</p>` : ""}
2450
- <p style="margin:0 0 16px;font-size:14px;color:#4b5563;line-height:1.6;font-family:sans-serif">Use the token below to accept your invitation. It expires in 7 days.</p>
2451
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f3f4f6;border-radius:6px;table-layout:fixed">
2452
- <tr>
2453
- <td style="padding:12px 16px;font-family:monospace;font-size:12px;color:#374151;word-break:break-all;white-space:normal;line-height:1.4">
2454
- ${args.token}
2455
- </td>
2456
- </tr>
2457
- </table>
2458
- </td>
2459
- </tr>
2460
- <tr>
2461
- <td style="padding:32px">
2462
- <p style="margin:0;font-size:12px;color:#9ca3af;font-family:sans-serif">If you weren't expecting this invitation, you can safely ignore this email.</p>
2463
- </td>
2464
- </tr>
2465
- </table>
2466
- </td>
2467
- </tr>
2468
- </table>`
2469
- };
2470
- }
2471
- function buildResetPasswordEmail(config, args) {
2472
- const custom = config.email?.templates?.resetPassword?.(args);
2473
- const resetLink = args.url;
2474
- return {
2475
- subject: custom?.subject ?? "Reset your password",
2476
- html: custom?.html ?? `
2477
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f9fafb;table-layout:fixed">
2478
- <tr>
2479
- <td align="center" style="padding:40px 16px">
2480
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;background-color:#ffffff;border-radius:12px;border:1px solid #e5e7eb;table-layout:fixed">
2481
- <tr>
2482
- <td style="padding:32px 32px 0">
2483
- <p style="margin:0 0 4px;font-size:12px;font-weight:600;color:#6b7280;font-family:sans-serif;text-transform:uppercase;letter-spacing:0.05em">Dyrected</p>
2484
- <h1 style="margin:0 0 24px;font-size:22px;font-weight:700;color:#111827;font-family:sans-serif">Reset your password</h1>
2485
- </td>
2486
- </tr>
2487
- <tr>
2488
- <td style="padding:0 32px">
2489
- <p style="margin:0 0 24px;font-size:14px;color:#4b5563;line-height:1.6;font-family:sans-serif">We received a request to reset your password. Use the button below to set a new password. It will expire in 1 hour.</p>
2490
- ${resetLink ? `
2491
- <table cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px">
2492
- <tr>
2493
- <td style="border-radius:6px;background-color:#111827">
2494
- <a href="${resetLink}" style="display:inline-block;padding:12px 28px;font-size:14px;font-weight:600;color:#ffffff;text-decoration:none;font-family:sans-serif;border-radius:6px">
2495
- Reset Password
2496
- </a>
2497
- </td>
2498
- </tr>
2499
- </table>
2500
- ` : ""}
2501
- <p style="margin:0 0 8px;font-size:12px;color:#9ca3af;font-family:sans-serif">Or copy and paste this token manually in the admin dashboard:</p>
2502
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f3f4f6;border-radius:6px;table-layout:fixed">
2503
- <tr>
2504
- <td style="padding:12px 16px;font-family:monospace;font-size:12px;color:#374151;word-break:break-all;white-space:normal;line-height:1.4">
2505
- ${args.token}
2506
- </td>
2507
- </tr>
2508
- </table>
2509
- </td>
2510
- </tr>
2511
- <tr>
2512
- <td style="padding:32px">
2513
- <p style="margin:0;font-size:12px;color:#9ca3af;font-family:sans-serif">If you didn't request a password reset, you can safely ignore this email.</p>
2514
- </td>
2515
- </tr>
2516
- </table>
2517
- </td>
2518
- </tr>
2519
- </table>`
2520
- };
2521
- }
2522
- function buildPasswordChangedEmail(config, args) {
2523
- const custom = config.email?.templates?.passwordChanged?.(args);
2524
- return {
2525
- subject: custom?.subject ?? "Your password has been changed",
2526
- html: custom?.html ?? `
2527
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f9fafb;table-layout:fixed">
2528
- <tr>
2529
- <td align="center" style="padding:40px 16px">
2530
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px;background-color:#ffffff;border-radius:12px;border:1px solid #e5e7eb;table-layout:fixed">
2531
- <tr>
2532
- <td style="padding:32px 32px 0">
2533
- <p style="margin:0 0 4px;font-size:12px;font-weight:600;color:#6b7280;font-family:sans-serif;text-transform:uppercase;letter-spacing:0.05em">Dyrected</p>
2534
- <h1 style="margin:0 0 24px;font-size:22px;font-weight:700;color:#111827;font-family:sans-serif">Password changed</h1>
2535
- </td>
2536
- </tr>
2537
- <tr>
2538
- <td style="padding:0 32px">
2539
- <p style="margin:0 0 12px;font-size:14px;color:#4b5563;line-height:1.6;font-family:sans-serif">The password for your account was just changed:</p>
2540
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;background-color:#f3f4f6;border-radius:6px;table-layout:fixed">
2541
- <tr>
2542
- <td style="padding:12px 16px;font-size:14px;font-weight:600;color:#111827;font-family:sans-serif;word-break:break-all">
2543
- ${args.email}
2544
- </td>
2545
- </tr>
2546
- </table>
2547
- <table cellpadding="0" cellspacing="0" border="0" style="width:100%;margin-top:16px;background-color:#fef2f2;border-radius:6px;border:1px solid #fecaca;table-layout:fixed">
2548
- <tr>
2549
- <td style="padding:12px 16px;font-size:13px;color:#b91c1c;line-height:1.5;font-family:sans-serif">
2550
- If you did not make this change, please contact support immediately.
2551
- </td>
2552
- </tr>
2553
- </table>
2554
- </td>
2555
- </tr>
2556
- <tr>
2557
- <td style="padding:32px">
2558
- <p style="margin:0;font-size:12px;color:#9ca3af;font-family:sans-serif">This is an automated security notification.</p>
2559
- </td>
2560
- </tr>
2561
- </table>
2562
- </td>
2563
- </tr>
2564
- </table>`
2565
- };
2566
- }
2567
-
2568
- // src/controllers/auth.controller.ts
2569
- var AuthController = class {
2570
- collection;
2571
- constructor(collection) {
2572
- this.collection = collection;
2573
- }
2574
- // ---------------------------------------------------------------------------
2575
- // GET /init
2576
- // Checks if the first user needs to be created.
2577
- // ---------------------------------------------------------------------------
2578
- async init(c) {
2579
- const db = c.get("config").db;
2580
- if (!db) return c.json({ message: "Database not configured" }, 500);
2581
- const result = await db.find({
2582
- collection: this.collection.slug,
2583
- limit: 1
2584
- });
2585
- return c.json({
2586
- initialized: result.total > 0
2587
- });
2588
- }
2589
- // ---------------------------------------------------------------------------
2590
- // POST /first-user
2591
- // Creates the first user if none exist.
2592
- // ---------------------------------------------------------------------------
2593
- async registerFirstUser(c) {
2594
- const config = c.get("config");
2595
- const db = config.db;
2596
- if (!db) return c.json({ message: "Database not configured" }, 500);
2597
- const check = await db.find({
2598
- collection: this.collection.slug,
2599
- limit: 1
2600
- });
2601
- if (check.total > 0) {
2602
- return c.json({ error: true, message: "Initial user already exists." }, 403);
2603
- }
2604
- const body = await c.req.json().catch(() => null);
2605
- if (!body?.email || !body?.password) {
2606
- return c.json({ error: true, message: "email and password are required." }, 400);
2607
- }
2608
- const hashedPassword = await hashPassword(body.password);
2609
- const user = await db.create({
2610
- collection: this.collection.slug,
2611
- data: {
2612
- ...body,
2613
- password: hashedPassword,
2614
- roles: ["admin"]
2615
- // Default first user to admin
2616
- }
2617
- });
2618
- const token = await signCollectionToken({
2619
- sub: user.id,
2620
- email: user.email,
2621
- collection: this.collection.slug
2622
- });
2623
- const { subject, html } = buildWelcomeEmail(config, { email: body.email });
2624
- sendEmail(config, { to: body.email, subject, html }).catch(
2625
- (err) => console.error("[dyrected/core] Failed to send welcome email:", err)
2626
- );
2627
- const { password: _, ...safeUser } = user;
2628
- return c.json({ token, user: safeUser });
2629
- }
2630
- // ---------------------------------------------------------------------------
2631
- // POST /login
2632
- // ---------------------------------------------------------------------------
2633
- async login(c) {
2634
- const db = c.get("config").db;
2635
- if (!db) return c.json({ message: "Database not configured" }, 500);
2636
- const body = await c.req.json().catch(() => null);
2637
- if (!body?.email || !body?.password) {
2638
- return c.json({ error: true, message: "email and password are required." }, 400);
2639
- }
2640
- const result = await db.find({
2641
- collection: this.collection.slug,
2642
- where: { email: body.email },
2643
- limit: 1
2644
- });
2645
- const user = result.docs[0];
2646
- if (!user) {
2647
- return c.json({ error: true, message: "Invalid email or password." }, 401);
2648
- }
2649
- const valid = await verifyPassword(body.password, user.password);
2650
- if (!valid) {
2651
- return c.json({ error: true, message: "Invalid email or password." }, 401);
2652
- }
2653
- const token = await signCollectionToken({
2654
- sub: user.id,
2655
- email: user.email,
2656
- collection: this.collection.slug
2657
- });
2658
- const { password: _, ...safeUser } = user;
2659
- return c.json({ token, user: safeUser });
2660
- }
2661
- // ---------------------------------------------------------------------------
2662
- // POST /logout
2663
- // Auth collections use stateless JWTs — logout is handled client-side.
2664
- // This endpoint exists so clients have a consistent API surface.
2665
- // ---------------------------------------------------------------------------
2666
- async logout(c) {
2667
- return c.json({ success: true, message: "Logged out. Discard your token." });
2668
- }
2669
- // ---------------------------------------------------------------------------
2670
- // GET /me
2671
- // ---------------------------------------------------------------------------
2672
- async me(c) {
2673
- const db = c.get("config").db;
2674
- if (!db) return c.json({ message: "Database not configured" }, 500);
2675
- const requestUser = c.get("user");
2676
- if (!requestUser) {
2677
- return c.json({ error: true, message: "Authentication required." }, 401);
2678
- }
2679
- const user = await db.findOne({ collection: this.collection.slug, id: requestUser.sub });
2680
- if (!user) {
2681
- return c.json({ error: true, message: "User not found." }, 404);
2682
- }
2683
- const { password: _, ...safeUser } = user;
2684
- return c.json(safeUser);
2685
- }
2686
- // ---------------------------------------------------------------------------
2687
- // POST /refresh-token
2688
- // ---------------------------------------------------------------------------
2689
- async refreshToken(c) {
2690
- const requestUser = c.get("user");
2691
- if (!requestUser) {
2692
- return c.json({ error: true, message: "Authentication required." }, 401);
2693
- }
2694
- const token = await signCollectionToken({
2695
- sub: requestUser.sub,
2696
- email: requestUser.email,
2697
- collection: this.collection.slug
2698
- });
2699
- return c.json({ token });
2700
- }
2701
- // ---------------------------------------------------------------------------
2702
- // POST /forgot-password
2703
- // Requires config.email to be set. Silently succeeds if email not found
2704
- // to prevent email enumeration.
2705
- // ---------------------------------------------------------------------------
2706
- async forgotPassword(c) {
2707
- const config = c.get("config");
2708
- const db = config.db;
2709
- if (!db) return c.json({ message: "Database not configured" }, 500);
2710
- const body = await c.req.json().catch(() => null);
2711
- if (!body?.email) {
2712
- return c.json({ error: true, message: "email is required." }, 400);
2713
- }
2714
- const result = await db.find({
2715
- collection: this.collection.slug,
2716
- where: { email: body.email },
2717
- limit: 1
2718
- });
2719
- const user = result.docs[0];
2720
- if (user) {
2721
- const resetToken = await signCollectionToken(
2722
- { sub: user.id, email: user.email, collection: this.collection.slug, purpose: "reset" },
2723
- "1h"
2724
- );
2725
- const resetUrl = body?.resetUrl;
2726
- const url = resetUrl ? `${resetUrl}${resetUrl.includes("?") ? "&" : "?"}token=${encodeURIComponent(resetToken)}` : void 0;
2727
- try {
2728
- const { subject, html } = buildResetPasswordEmail(config, { token: resetToken, url });
2729
- await sendEmail(config, { to: user.email, subject, html });
2730
- } catch (err) {
2731
- console.error("[dyrected/core] Failed to send password reset email:", err);
2732
- }
2733
- }
2734
- return c.json({
2735
- success: true,
2736
- message: "If an account with that email exists, a reset link has been sent."
2737
- });
2738
- }
2739
- // ---------------------------------------------------------------------------
2740
- // POST /reset-password
2741
- // Expects { token: string, password: string } in body.
2742
- // The token is the reset JWT issued by /forgot-password.
2743
- // ---------------------------------------------------------------------------
2744
- async resetPassword(c) {
2745
- const config = c.get("config");
2746
- const db = config.db;
2747
- if (!db) return c.json({ message: "Database not configured" }, 500);
2748
- const body = await c.req.json().catch(() => null);
2749
- if (!body?.token || !body?.password) {
2750
- return c.json({ error: true, message: "token and password are required." }, 400);
2751
- }
2752
- let payload;
2753
- try {
2754
- payload = await verifyCollectionToken(body.token);
2755
- } catch {
2756
- return c.json({ error: true, message: "Reset token is invalid or has expired." }, 400);
2757
- }
2758
- if (payload.collection !== this.collection.slug || payload.purpose !== "reset") {
2759
- return c.json({ error: true, message: "Reset token is invalid or has expired." }, 400);
2760
- }
2761
- const hashedPassword = await hashPassword(body.password);
2762
- await db.update({
2763
- collection: this.collection.slug,
2764
- id: payload.sub,
2765
- data: { password: hashedPassword }
2766
- });
2767
- const { subject, html } = buildPasswordChangedEmail(config, { email: payload.email });
2768
- sendEmail(config, { to: payload.email, subject, html }).catch(
2769
- (err) => console.error("[dyrected/core] Failed to send password-changed email:", err)
2770
- );
2771
- return c.json({ success: true, message: "Password has been reset. You can now log in." });
2772
- }
2773
- // ---------------------------------------------------------------------------
2774
- // POST /invite
2775
- // Requires auth. Issues a signed invite token and emails it to the invitee.
2776
- // ---------------------------------------------------------------------------
2777
- async invite(c) {
2778
- const config = c.get("config");
2779
- const db = config.db;
2780
- if (!db) return c.json({ message: "Database not configured" }, 500);
2781
- const requestUser = c.get("user");
2782
- if (!requestUser) {
2783
- return c.json({ error: true, message: "Authentication required." }, 401);
2784
- }
2785
- const body = await c.req.json().catch(() => null);
2786
- if (!body?.email) {
2787
- return c.json({ error: true, message: "email is required." }, 400);
2788
- }
2789
- const existing = await db.find({
2790
- collection: this.collection.slug,
2791
- where: { email: body.email },
2792
- limit: 1
2793
- });
2794
- if (existing.total > 0) {
2795
- return c.json({ error: true, message: "An account with that email already exists." }, 409);
2796
- }
2797
- const inviteToken = await signCollectionToken(
2798
- { sub: body.email, email: body.email, collection: this.collection.slug, purpose: "invite" },
2799
- "7d"
2800
- );
2801
- try {
2802
- const { subject, html } = buildInviteEmail(config, {
2803
- token: inviteToken,
2804
- invitedByEmail: requestUser.email
2805
- });
2806
- await sendEmail(config, { to: body.email, subject, html });
2807
- } catch (err) {
2808
- console.error("[dyrected/core] Failed to send invite email:", err);
2809
- }
2810
- return c.json({ success: true, message: `Invite sent to ${body.email}.` });
2811
- }
2812
- // ---------------------------------------------------------------------------
2813
- // POST /accept-invite
2814
- // Public. Validates the invite token and creates the user account.
2815
- // Body: { token, password, ...extraFields }
2816
- // ---------------------------------------------------------------------------
2817
- async acceptInvite(c) {
2818
- const config = c.get("config");
2819
- const db = config.db;
2820
- if (!db) return c.json({ message: "Database not configured" }, 500);
2821
- const body = await c.req.json().catch(() => null);
2822
- if (!body?.token || !body?.password) {
2823
- return c.json({ error: true, message: "token and password are required." }, 400);
2824
- }
2825
- let payload;
2826
- try {
2827
- payload = await verifyCollectionToken(body.token);
2828
- } catch {
2829
- return c.json({ error: true, message: "Invite token is invalid or has expired." }, 400);
2830
- }
2831
- if (payload.collection !== this.collection.slug || payload.purpose !== "invite") {
2832
- return c.json({ error: true, message: "Invite token is invalid or has expired." }, 400);
2833
- }
2834
- const inviteeEmail = payload.sub;
2835
- const existing = await db.find({
2836
- collection: this.collection.slug,
2837
- where: { email: inviteeEmail },
2838
- limit: 1
2839
- });
2840
- if (existing.total > 0) {
2841
- return c.json({ error: true, message: "An account with that email already exists." }, 409);
2842
- }
2843
- const { token: _t, password: _p, ...extraFields } = body;
2844
- const hashedPassword = await hashPassword(body.password);
2845
- const user = await db.create({
2846
- collection: this.collection.slug,
2847
- data: { ...extraFields, email: inviteeEmail, password: hashedPassword }
2848
- });
2849
- const sessionToken = await signCollectionToken({
2850
- sub: user.id,
2851
- email: inviteeEmail,
2852
- collection: this.collection.slug
2853
- });
2854
- const { subject, html } = buildWelcomeEmail(config, { email: inviteeEmail });
2855
- sendEmail(config, { to: inviteeEmail, subject, html }).catch(
2856
- (err) => console.error("[dyrected/core] Failed to send welcome email:", err)
2857
- );
2858
- const { password: _, ...safeUser } = user;
2859
- return c.json({ token: sessionToken, user: safeUser }, 201);
2860
- }
2861
- };
2862
-
2863
- // src/controllers/preview.controller.ts
2864
- var import_jose2 = require("jose");
2865
- var import_node_util3 = require("util");
2866
- var PreviewController = class {
2867
- getSecret() {
2868
- const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET || "dyrected-preview-secret-change-me";
2869
- return new import_node_util3.TextEncoder().encode(secret);
2870
- }
2871
- /**
2872
- * POST /api/preview-token
2873
- * Generates a short-lived token for previewing unsaved data.
2874
- */
2875
- async createToken(c) {
2876
- const body = await c.req.json().catch(() => null);
2877
- if (!body?.collectionSlug || !body?.data) {
2878
- return c.json({ error: true, message: "collectionSlug and data are required." }, 400);
2879
- }
2880
- const token = await new import_jose2.SignJWT({
2881
- collectionSlug: body.collectionSlug,
2882
- documentId: body.documentId,
2883
- data: body.data
2884
- }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("15m").sign(this.getSecret());
2885
- const expiresAt = new Date(Date.now() + 15 * 60 * 1e3).toISOString();
2886
- return c.json({ token, expiresAt });
2887
- }
2888
- /**
2889
- * GET /api/preview-data?token=<jwt>
2890
- * Returns the data stored in the preview token.
2891
- */
2892
- async getData(c) {
2893
- const token = c.req.query("token");
2894
- if (!token) {
2895
- return c.json({ error: true, message: "token query parameter is required." }, 400);
2896
- }
2897
- try {
2898
- const { payload } = await (0, import_jose2.jwtVerify)(token, this.getSecret());
2899
- return c.json(payload);
2900
- } catch (err) {
2901
- return c.json({ error: true, message: "Invalid or expired preview token." }, 401);
2902
- }
2903
- }
2904
- };
2905
-
2906
- // src/middleware/auth.ts
2907
- function requireAuth() {
2908
- return async (c, next) => {
2909
- const authHeader = c.req.header("Authorization");
2910
- const token = authHeader?.replace(/^Bearer\s+/i, "");
2911
- if (!token) {
2912
- return c.json({ error: true, message: "Authentication required." }, 401);
2913
- }
2914
- try {
2915
- const user = await verifyCollectionToken(token);
2916
- c.set("user", user);
2917
- await next();
2918
- } catch {
2919
- return c.json({ error: true, message: "Invalid or expired token." }, 401);
2920
- }
2921
- };
2922
- }
2923
- function optionalAuth() {
2924
- return async (c, next) => {
2925
- const authHeader = c.req.header("Authorization");
2926
- const token = authHeader?.replace(/^Bearer\s+/i, "");
2927
- if (token) {
2928
- try {
2929
- const user = await verifyCollectionToken(token);
2930
- c.set("user", user);
2931
- } catch {
2932
- }
2933
- }
2934
- await next();
2935
- };
2936
- }
2937
-
2938
- // src/utils/openapi.ts
2939
- function generateOpenApi(config) {
2940
- const spec = {
2941
- openapi: "3.0.0",
2942
- info: {
2943
- title: "Dyrected API",
2944
- version: "1.0.0",
2945
- description: "Automatically generated OpenAPI specification for the Dyrected project."
2946
- },
2947
- components: {
2948
- schemas: {},
2949
- securitySchemes: {
2950
- ApiKeyAuth: {
2951
- type: "apiKey",
2952
- in: "header",
2953
- name: "x-api-key"
2954
- }
2955
- }
2956
- },
2957
- paths: {},
2958
- security: [{ ApiKeyAuth: [] }]
2959
- };
2960
- for (const collection of config.collections) {
2961
- spec.components.schemas[collection.slug] = collectionToSchema(collection);
2962
- }
2963
- for (const global of config.globals) {
2964
- spec.components.schemas[global.slug] = globalToSchema(global);
2965
- }
2966
- for (const collection of config.collections) {
2967
- const slug = collection.slug;
2968
- const path = `/api/collections/${slug}`;
2969
- const labels = collection.labels || { singular: slug, plural: `${slug}s` };
2970
- spec.paths[path] = {
2971
- get: {
2972
- tags: ["Collections"],
2973
- summary: `Find ${labels.plural}`,
2974
- parameters: [
2975
- { name: "limit", in: "query", schema: { type: "integer", default: 10 } },
2976
- { name: "page", in: "query", schema: { type: "integer", default: 1 } },
2977
- { name: "where", in: "query", schema: { type: "string" }, description: "JSON filter" },
2978
- { name: "sort", in: "query", schema: { type: "string" }, description: "Sort field (e.g. -createdAt)" }
2979
- ],
2980
- responses: {
2981
- 200: {
2982
- description: "Success",
2983
- content: {
2984
- "application/json": {
2985
- schema: {
2986
- type: "object",
2987
- properties: {
2988
- docs: { type: "array", items: { $ref: `#/components/schemas/${slug}` } },
2989
- total: { type: "integer" },
2990
- limit: { type: "integer" },
2991
- page: { type: "integer" }
2992
- }
2993
- }
2994
- }
2995
- }
2996
- }
2997
- }
2998
- },
2999
- post: {
3000
- tags: ["Collections"],
3001
- summary: `Create ${labels.singular}`,
3002
- requestBody: {
3003
- required: true,
3004
- content: {
3005
- "application/json": {
3006
- schema: { $ref: `#/components/schemas/${slug}` }
3007
- }
3008
- }
3009
- },
3010
- responses: {
3011
- 201: {
3012
- description: "Created",
3013
- content: {
3014
- "application/json": {
3015
- schema: { $ref: `#/components/schemas/${slug}` }
3016
- }
3017
- }
3018
- }
3019
- }
3020
- }
3021
- };
3022
- spec.paths[`${path}/{id}`] = {
3023
- get: {
3024
- tags: ["Collections"],
3025
- summary: `Get a single ${labels.singular}`,
3026
- parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3027
- responses: {
3028
- 200: {
3029
- description: "Success",
3030
- content: {
3031
- "application/json": {
3032
- schema: { $ref: `#/components/schemas/${slug}` }
3033
- }
3034
- }
3035
- }
3036
- }
3037
- },
3038
- patch: {
3039
- tags: ["Collections"],
3040
- summary: `Update ${labels.singular}`,
3041
- parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3042
- requestBody: {
3043
- required: true,
3044
- content: {
3045
- "application/json": {
3046
- schema: { $ref: `#/components/schemas/${slug}` }
3047
- }
3048
- }
3049
- },
3050
- responses: {
3051
- 200: {
3052
- description: "Updated",
3053
- content: {
3054
- "application/json": {
3055
- schema: { $ref: `#/components/schemas/${slug}` }
3056
- }
3057
- }
3058
- }
3059
- }
3060
- },
3061
- delete: {
3062
- tags: ["Collections"],
3063
- summary: `Delete ${labels.singular}`,
3064
- parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
3065
- responses: {
3066
- 204: { description: "Deleted" }
3067
- }
3068
- }
3069
- };
3070
- }
3071
- for (const global of config.globals) {
3072
- const slug = global.slug;
3073
- const path = `/api/globals/${slug}`;
3074
- spec.paths[path] = {
3075
- get: {
3076
- tags: ["Globals"],
3077
- summary: `Get ${global.label || slug}`,
3078
- responses: {
3079
- 200: {
3080
- description: "Success",
3081
- content: {
3082
- "application/json": {
3083
- schema: { $ref: `#/components/schemas/${slug}` }
3084
- }
3085
- }
3086
- }
3087
- }
3088
- },
3089
- patch: {
3090
- tags: ["Globals"],
3091
- summary: `Update ${global.label || slug}`,
3092
- requestBody: {
3093
- required: true,
3094
- content: {
3095
- "application/json": {
3096
- schema: { $ref: `#/components/schemas/${slug}` }
3097
- }
3098
- }
3099
- },
3100
- responses: {
3101
- 200: {
3102
- description: "Updated",
3103
- content: {
3104
- "application/json": {
3105
- schema: { $ref: `#/components/schemas/${slug}` }
3106
- }
3107
- }
3108
- }
3109
- }
3110
- }
3111
- };
3112
- }
3113
- if (config.storage) {
3114
- spec.paths["/api/media"] = {
3115
- get: {
3116
- tags: ["Media"],
3117
- summary: "List Media",
3118
- responses: {
3119
- 200: {
3120
- description: "Success",
3121
- content: {
3122
- "application/json": {
3123
- schema: {
3124
- type: "object",
3125
- properties: {
3126
- docs: { type: "array", items: { type: "object", additionalProperties: true } }
3127
- }
3128
- }
3129
- }
3130
- }
3131
- }
3132
- }
3133
- },
3134
- post: {
3135
- tags: ["Media"],
3136
- summary: "Upload Media",
3137
- requestBody: {
3138
- content: {
3139
- "multipart/form-data": {
3140
- schema: {
3141
- type: "object",
3142
- properties: {
3143
- file: { type: "string", format: "binary" }
3144
- }
3145
- }
3146
- }
3147
- }
3148
- },
3149
- responses: {
3150
- 201: { description: "Uploaded" }
3151
- }
3152
- }
3153
- };
3154
- }
3155
- return spec;
3156
- }
3157
- function collectionToSchema(collection) {
3158
- const { properties, required } = fieldsToProperties(collection.fields);
3159
- return {
3160
- type: "object",
3161
- properties: {
3162
- id: { type: "string" },
3163
- createdAt: { type: "string", format: "date-time" },
3164
- updatedAt: { type: "string", format: "date-time" },
3165
- ...properties
3166
- },
3167
- required: ["id", ...required]
3168
- };
3169
- }
3170
- function globalToSchema(global) {
3171
- const { properties, required } = fieldsToProperties(global.fields);
3172
- return {
3173
- type: "object",
3174
- properties,
3175
- required
3176
- };
3177
- }
3178
- function fieldsToProperties(fields) {
3179
- const props = {};
3180
- const required = [];
3181
- for (const field of fields) {
3182
- if (!field.name || field.type === "join" || field.type === "row") continue;
3183
- props[field.name] = fieldToSchema(field);
3184
- if (field.required) {
3185
- required.push(field.name);
3186
- }
3187
- }
3188
- return { properties: props, required };
3189
- }
3190
- function fieldToSchema(field) {
3191
- let schema = {};
3192
- switch (field.type) {
3193
- case "text":
3194
- case "textarea":
3195
- case "email":
3196
- case "url":
3197
- schema = { type: "string" };
3198
- break;
3199
- case "number":
3200
- schema = { type: "number" };
3201
- break;
3202
- case "boolean":
3203
- schema = { type: "boolean" };
3204
- break;
3205
- case "date":
3206
- schema = { type: "string", format: "date-time" };
3207
- break;
3208
- case "select":
3209
- case "radio":
3210
- schema = { type: "string", enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0 };
3211
- break;
3212
- case "multiSelect":
3213
- schema = {
3214
- type: "array",
3215
- items: { type: "string", enum: Array.isArray(field.options) ? field.options.map((o) => typeof o === "string" ? o : o.value) : void 0 }
3216
- };
3217
- break;
3218
- case "relationship":
3219
- schema = { type: "string", description: `ID of a ${field.relationTo} record` };
3220
- break;
3221
- case "object": {
3222
- const { properties, required } = fieldsToProperties(field.fields || []);
3223
- schema = { type: "object", properties, required };
3224
- break;
3225
- }
3226
- case "array": {
3227
- const { properties, required } = fieldsToProperties(field.fields || []);
3228
- schema = { type: "array", items: { type: "object", properties, required } };
3229
- break;
3230
- }
3231
- case "json":
3232
- case "richText":
3233
- schema = { type: "object", additionalProperties: true };
3234
- break;
3235
- case "blocks":
3236
- schema = {
3237
- type: "array",
3238
- items: {
3239
- oneOf: field.blocks?.map((block) => {
3240
- const { properties, required } = fieldsToProperties(block.fields);
3241
- return {
3242
- type: "object",
3243
- properties: {
3244
- blockType: { type: "string", enum: [block.slug] },
3245
- ...properties
3246
- },
3247
- required: ["blockType", ...required]
3248
- };
3249
- })
3250
- }
3251
- };
3252
- break;
3253
- default:
3254
- schema = { type: "string" };
3255
- }
3256
- if (field.label) schema.description = field.label;
3257
- return schema;
3258
- }
3259
-
3260
- // src/utils/swagger.ts
3261
- function getSwaggerHtml(specUrl = "/api/openapi.json") {
3262
- return `
3263
- <!DOCTYPE html>
3264
- <html lang="en">
3265
- <head>
3266
- <meta charset="utf-8" />
3267
- <meta name="viewport" content="width=device-width, initial-scale=1" />
3268
- <meta name="description" content="SwaggerUI" />
3269
- <title>Dyrected API Documentation</title>
3270
- <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css" />
3271
- </head>
3272
- <body>
3273
- <div id="swagger-ui"></div>
3274
- <script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-bundle.js" charset="UTF-8"></script>
3275
- <script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-standalone-preset.js" charset="UTF-8"></script>
3276
- <script>
3277
- window.onload = () => {
3278
- // Forward the apikey query param when loading the spec and making API calls
3279
- const params = new URLSearchParams(window.location.search);
3280
- const apiKey = params.get('apikey');
3281
- const specUrlWithKey = apiKey ? '${specUrl}?apikey=' + encodeURIComponent(apiKey) : '${specUrl}';
3282
-
3283
- window.ui = SwaggerUIBundle({
3284
- url: specUrlWithKey,
3285
- dom_id: '#swagger-ui',
3286
- presets: [
3287
- SwaggerUIBundle.presets.apis,
3288
- SwaggerUIStandalonePreset
3289
- ],
3290
- layout: "BaseLayout",
3291
- deepLinking: true,
3292
- showExtensions: true,
3293
- showCommonExtensions: true,
3294
- // Inject x-api-key header on every request made from the Swagger UI
3295
- requestInterceptor: (request) => {
3296
- if (apiKey) {
3297
- request.headers['x-api-key'] = apiKey;
3298
- }
3299
- return request;
3300
- }
3301
- });
3302
- };
3303
- </script>
3304
- </body>
3305
- </html>
3306
- `;
3307
- }
3308
-
3309
- // src/auth/jexl.ts
3310
- var import_jexl = __toESM(require("jexl"), 1);
3311
- async function evaluateAccess(expression, context) {
3312
- if (expression === void 0 || expression === null) return false;
3313
- if (typeof expression === "boolean") return expression;
3314
- try {
3315
- const result = await import_jexl.default.eval(expression, context);
3316
- return !!result;
3317
- } catch (err) {
3318
- console.error("[dyrected/core] Jexl evaluation failed:", err);
3319
- return false;
3320
- }
3321
- }
3322
-
3323
- // src/router.ts
3324
- function accessGate(target, action) {
3325
- return async (c, next) => {
3326
- const user = c.get("user");
3327
- const accessExpr = target.access?.[action];
3328
- if (accessExpr === void 0 || accessExpr === null) {
3329
- return await next();
3330
- }
3331
- const accessArgs = { user, req: c.req, doc: null };
3332
- const allowed = await evaluateAccess(accessExpr, accessArgs);
3333
- if (!allowed) {
3334
- return c.json({ error: true, message: `Access denied: ${action} on ${target.slug}` }, 403);
3335
- }
3336
- await next();
3337
- };
3338
- }
3339
- async function checkAccess(access, accessArgs) {
3340
- if (access === void 0 || access === null) return true;
3341
- if (typeof access === "function") {
3342
- try {
3343
- const result = await access(accessArgs);
3344
- return typeof result === "boolean" ? result : !!result;
3345
- } catch (err) {
3346
- console.error("[dyrected/core] Functional access check failed:", err);
3347
- return false;
3348
- }
3349
- }
3350
- if (typeof access === "string" || typeof access === "boolean") {
3351
- return evaluateAccess(access, accessArgs);
3352
- }
3353
- return true;
3354
- }
3355
- function serializeFieldForApi(f) {
3356
- if (!f) return f;
3357
- const serialized = { ...f };
3358
- if (serialized.admin?.hooks) {
3359
- const hooks = { ...serialized.admin.hooks };
3360
- if (typeof hooks.onChange === "function") {
3361
- hooks.onChange = hooks.onChange.toString();
3362
- }
3363
- if (typeof hooks.options === "function") {
3364
- hooks.options = hooks.options.toString();
3365
- }
3366
- serialized.admin = { ...serialized.admin, hooks };
3367
- }
3368
- if (typeof serialized.options === "function" || serialized.options && typeof serialized.options === "object" && "resolve" in serialized.options) {
3369
- serialized.options = { _dynamic: true };
3370
- }
3371
- if (serialized.fields) {
3372
- serialized.fields = serialized.fields.map(serializeFieldForApi);
3373
- }
3374
- if (serialized.blocks) {
3375
- serialized.blocks = serialized.blocks.map((b) => ({
3376
- ...b,
3377
- fields: b.fields?.map(serializeFieldForApi)
3378
- }));
3379
- }
3380
- return serialized;
3381
- }
3382
- function registerRoutes(app, config) {
3383
- app.get("/api/schemas", optionalAuth(), async (c) => {
3384
- const siteId = c.req.header("X-Site-Id");
3385
- let collections = [...config.collections];
3386
- let globals = [...config.globals];
3387
- if (siteId && config.onSchemaFetch) {
3388
- const dynamic = await config.onSchemaFetch(siteId);
3389
- if (dynamic.collections) collections = [...collections, ...dynamic.collections];
3390
- if (dynamic.globals) globals = [...globals, ...dynamic.globals];
3391
- if (dynamic.admin) {
3392
- config.admin = { ...config.admin, ...dynamic.admin };
3393
- }
3394
- }
3395
- const user = c.get("user");
3396
- const accessArgs = { user, req: c.req, doc: null };
3397
- const serializeAccess = async (access) => {
3398
- if (typeof access === "string") return access;
3399
- if (typeof access === "boolean") return access;
3400
- return checkAccess(access, accessArgs);
3401
- };
3402
- const filteredCollections = await Promise.all(collections.filter((col) => !siteId || col.shared || !col.siteId || col.siteId === siteId).map(async (col) => ({
3403
- slug: col.slug,
3404
- labels: col.labels,
3405
- access: {
3406
- read: await serializeAccess(col.access?.read),
3407
- create: await serializeAccess(col.access?.create),
3408
- update: await serializeAccess(col.access?.update),
3409
- delete: await serializeAccess(col.access?.delete)
3410
- },
3411
- fields: await Promise.all(col.fields.map(serializeFieldForApi).map(async (f) => ({
3412
- name: f.name,
3413
- type: f.type,
3414
- label: f.label,
3415
- required: f.required,
3416
- defaultValue: f.defaultValue,
3417
- options: f.options,
3418
- relationTo: f.relationTo,
3419
- hasMany: f.hasMany,
3420
- fields: f.fields,
3421
- blocks: f.blocks,
3422
- collection: f.collection,
3423
- on: f.on,
3424
- limit: f.limit,
3425
- admin: f.admin,
3426
- access: {
3427
- read: await serializeAccess(f.access?.read),
3428
- update: await serializeAccess(f.access?.update)
3429
- }
3430
- }))),
3431
- upload: !!col.upload,
3432
- auth: !!col.auth,
3433
- admin: col.admin
3434
- })));
3435
- const filteredGlobals = await Promise.all(globals.filter((glb) => !siteId || glb.shared || !glb.siteId || glb.siteId === siteId).map(async (glb) => ({
3436
- slug: glb.slug,
3437
- label: glb.label,
3438
- access: {
3439
- read: await serializeAccess(glb.access?.read),
3440
- update: await serializeAccess(glb.access?.update)
3441
- },
3442
- fields: await Promise.all(glb.fields.map(serializeFieldForApi).map(async (f) => ({
3443
- name: f.name,
3444
- type: f.type,
3445
- label: f.label,
3446
- required: f.required,
3447
- defaultValue: f.defaultValue,
3448
- options: f.options,
3449
- relationTo: f.relationTo,
3450
- hasMany: f.hasMany,
3451
- fields: f.fields,
3452
- blocks: f.blocks,
3453
- collection: f.collection,
3454
- on: f.on,
3455
- limit: f.limit,
3456
- admin: f.admin,
3457
- access: {
3458
- read: await serializeAccess(f.access?.read),
3459
- update: await serializeAccess(f.access?.update)
3460
- }
3461
- }))),
3462
- admin: glb.admin
3463
- })));
3464
- return c.json({
3465
- collections: filteredCollections,
3466
- globals: filteredGlobals,
3467
- admin: config.admin || {}
3468
- });
3469
- });
3470
- app.get("/api/dyrected/options/:collection/:field", optionalAuth(), async (c) => {
3471
- const { collection: colSlug, field: fieldName } = c.req.param();
3472
- const siteId = c.req.header("X-Site-Id");
3473
- let collections = [...config.collections];
3474
- if (siteId && config.onSchemaFetch) {
3475
- const dynamic = await config.onSchemaFetch(siteId);
3476
- if (dynamic.collections) collections = [...collections, ...dynamic.collections];
3477
- }
3478
- const user = c.get("user");
3479
- let collection = collections.find((col) => col.slug === colSlug);
3480
- let field;
3481
- if (collection) {
3482
- const accessExpr = collection.access?.read;
3483
- if (accessExpr !== void 0 && accessExpr !== null) {
3484
- const accessArgs = { user, req: c.req, doc: null };
3485
- const allowed = await checkAccess(accessExpr, accessArgs);
3486
- if (!allowed) {
3487
- return c.json({ error: true, message: `Access denied: read on ${colSlug}` }, 403);
3488
- }
3489
- }
3490
- field = collection.fields.find((f) => f.name === fieldName);
3491
- } else {
3492
- let globals = [...config.globals];
3493
- if (siteId && config.onSchemaFetch) {
3494
- const dynamic = await config.onSchemaFetch(siteId);
3495
- if (dynamic.globals) globals = [...globals, ...dynamic.globals];
3496
- }
3497
- const glb = globals.find((g) => g.slug === colSlug);
3498
- if (!glb) {
3499
- return c.json({ error: true, message: `${colSlug} not found as collection or global` }, 404);
3500
- }
3501
- const accessExpr = glb.access?.read;
3502
- if (accessExpr !== void 0 && accessExpr !== null) {
3503
- const accessArgs = { user, req: c.req, doc: null };
3504
- const allowed = await checkAccess(accessExpr, accessArgs);
3505
- if (!allowed) {
3506
- return c.json({ error: true, message: `Access denied: read on global ${colSlug}` }, 403);
3507
- }
3508
- }
3509
- field = glb.fields.find((f) => f.name === fieldName);
3510
- }
3511
- if (!field) {
3512
- return c.json({ error: true, message: `Field ${fieldName} not found in ${colSlug}` }, 404);
3513
- }
3514
- let resolver;
3515
- if (typeof field.options === "function") {
3516
- resolver = field.options;
3517
- } else if (field.options && typeof field.options === "object" && "resolve" in field.options) {
3518
- resolver = field.options.resolve;
3519
- }
3520
- if (!resolver) {
3521
- return c.json({ error: true, message: `Field ${fieldName} in ${colSlug} is not dynamic` }, 400);
3522
- }
3523
- try {
3524
- const db = c.get("db") || config.db;
3525
- const queryParams = c.req.query();
3526
- const reqContext = {
3527
- query: queryParams,
3528
- headers: c.req.header(),
3529
- raw: c.req.raw
3530
- };
3531
- const result = await resolver({
3532
- db,
3533
- user,
3534
- req: reqContext
3535
- });
3536
- return c.json(result);
3537
- } catch (err) {
3538
- console.error(`[dyrected/core] Failed to resolve dynamic options for field ${fieldName}:`, err);
3539
- return c.json({ error: true, message: err.message || "Failed to resolve dynamic options" }, 500);
3540
- }
3541
- });
3542
- app.get("/api/openapi.json", (c) => {
3543
- return c.json(generateOpenApi(config));
3544
- });
3545
- app.get("/api/docs", (c) => {
3546
- return c.html(getSwaggerHtml());
3547
- });
3548
- app.get("/api/media/:filename{.+$}", async (c) => {
3549
- const mediaController = new MediaController("media");
3550
- return mediaController.serve(c);
3551
- });
3552
- app.get("/media/:filename{.+$}", async (c) => {
3553
- const mediaController = new MediaController("media");
3554
- return mediaController.serve(c);
3555
- });
3556
- if (config.storage) {
3557
- const uploadCollections = config.collections.filter((c) => c.upload);
3558
- for (const col of uploadCollections) {
3559
- const mediaController = new MediaController(col.slug);
3560
- const prefix = `/api/collections/${col.slug}`;
3561
- app.get(`${prefix}/media`, accessGate(col, "read"), (c) => mediaController.find(c));
3562
- app.get(`${prefix}/media/:filename{.+$}`, (c) => mediaController.serve(c));
3563
- app.post(`${prefix}/media`, accessGate(col, "create"), (c) => mediaController.upload(c));
3564
- app.delete(`${prefix}/media/:id`, accessGate(col, "delete"), (c) => mediaController.delete(c));
3565
- }
3566
- }
3567
- for (const collection of config.collections) {
3568
- if (!collection.auth) continue;
3569
- const path = `/api/collections/${collection.slug}`;
3570
- const authController = new AuthController(collection);
3571
- app.post(`${path}/login`, (c) => authController.login(c));
3572
- app.post(`${path}/logout`, (c) => authController.logout(c));
3573
- app.get(`${path}/init`, (c) => authController.init(c));
3574
- app.post(`${path}/first-user`, (c) => authController.registerFirstUser(c));
3575
- app.get(`${path}/me`, requireAuth(), (c) => authController.me(c));
3576
- app.post(`${path}/refresh-token`, requireAuth(), (c) => authController.refreshToken(c));
3577
- app.post(`${path}/forgot-password`, (c) => authController.forgotPassword(c));
3578
- app.post(`${path}/reset-password`, (c) => authController.resetPassword(c));
3579
- app.post(`${path}/invite`, requireAuth(), (c) => authController.invite(c));
3580
- app.post(`${path}/accept-invite`, (c) => authController.acceptInvite(c));
3581
- }
3582
- for (const collection of config.collections) {
3583
- const path = `/api/collections/${collection.slug}`;
3584
- const controller = new CollectionController(collection);
3585
- app.get(path, accessGate(collection, "read"), (c) => controller.find(c));
3586
- app.post(path, accessGate(collection, "create"), (c) => controller.create(c));
3587
- app.post(`${path}/media`, accessGate(collection, "create"), (c) => controller.create(c));
3588
- app.delete(`${path}/delete-many`, accessGate(collection, "delete"), (c) => controller.deleteMany(c));
3589
- app.get(`${path}/:id`, accessGate(collection, "read"), (c) => controller.findOne(c));
3590
- app.patch(`${path}/:id`, accessGate(collection, "update"), (c) => controller.update(c));
3591
- app.delete(`${path}/:id`, accessGate(collection, "delete"), (c) => controller.delete(c));
3592
- app.post(`${path}/seed`, (c) => controller.seed(c));
3593
- if (collection.auth) {
3594
- app.post(`${path}/:id/change-password`, requireAuth(), (c) => controller.changePassword(c));
3595
- }
3596
- }
3597
- for (const global of config.globals) {
3598
- const path = `/api/globals/${global.slug}`;
3599
- const controller = new GlobalController(global);
3600
- app.get(path, accessGate(global, "read"), (c) => controller.get(c));
3601
- app.patch(path, accessGate(global, "update"), (c) => controller.update(c));
3602
- app.post(`${path}/seed`, (c) => controller.seed(c));
3603
- }
3604
- const previewController = new PreviewController();
3605
- app.post("/api/preview-token", requireAuth(), (c) => previewController.createToken(c));
3606
- app.get("/api/preview-data", (c) => previewController.getData(c));
3607
- app.all("/api/collections/:slug/:id?", async (c) => {
3608
- const slug = c.req.param("slug");
3609
- const id = c.req.param("id");
3610
- const siteId = c.req.header("X-Site-Id") || c.get("siteId");
3611
- const config2 = c.get("config");
3612
- if (config2.collections.some((col) => col.slug === slug)) {
3613
- return c.json({ message: "Method Not Allowed" }, 405);
3614
- }
3615
- if (config2.onSchemaFetch && siteId) {
3616
- const dynamic = await config2.onSchemaFetch(siteId);
3617
- let collection = dynamic.collections?.find((col) => col.slug === slug);
3618
- if (!collection && slug === "media") {
3619
- collection = {
3620
- slug: "media",
3621
- labels: { singular: "Media", plural: "Media" },
3622
- upload: true,
3623
- fields: []
3624
- };
3625
- }
3626
- if (collection) {
3627
- if (collection.auth && id) {
3628
- const authController = new AuthController(collection);
3629
- const method2 = c.req.method;
3630
- if (method2 === "POST" && id === "login") return authController.login(c);
3631
- if (method2 === "POST" && id === "logout") return authController.logout(c);
3632
- if (method2 === "GET" && id === "me") return authController.me(c);
3633
- if (method2 === "POST" && id === "refresh-token") return authController.refreshToken(c);
3634
- if (method2 === "POST" && id === "forgot-password") return authController.forgotPassword(c);
3635
- if (method2 === "POST" && id === "reset-password") return authController.resetPassword(c);
3636
- }
3637
- const controller = new CollectionController(collection);
3638
- const method = c.req.method;
3639
- if (id) {
3640
- if (method === "GET") return controller.findOne(c);
3641
- if (method === "PATCH") return controller.update(c);
3642
- if (method === "DELETE" && id === "delete-many") return controller.deleteMany(c);
3643
- if (method === "DELETE") return controller.delete(c);
3644
- if (method === "POST" && id === "media") return controller.create(c);
3645
- if (method === "POST" && id === "seed") return controller.seed(c);
3646
- } else {
3647
- if (method === "GET") return controller.find(c);
3648
- if (method === "POST") return controller.create(c);
3649
- }
3650
- }
3651
- }
3652
- return c.json({ message: `Collection "${slug}" not found` }, 404);
3653
- });
3654
- app.all("/api/globals/:slug", async (c) => {
3655
- const slug = c.req.param("slug");
3656
- const siteId = c.req.header("X-Site-Id") || c.get("siteId");
3657
- const config2 = c.get("config");
3658
- if (config2.globals.some((glb) => glb.slug === slug)) {
3659
- return c.json({ message: "Method Not Allowed" }, 405);
3660
- }
3661
- if (config2.onSchemaFetch && siteId) {
3662
- const dynamic = await config2.onSchemaFetch(siteId);
3663
- const global = dynamic.globals?.find((glb) => glb.slug === slug);
3664
- if (global) {
3665
- const controller = new GlobalController(global);
3666
- if (c.req.method === "GET") return controller.get(c);
3667
- if (c.req.method === "PATCH") return controller.update(c);
3668
- }
3669
- }
3670
- return c.json({ message: `Global "${slug}" not found` }, 404);
3671
- });
3672
- }
3673
-
3674
- // src/app.ts
3675
- async function createDyrectedApp(rawConfig) {
3676
- const config = normalizeConfig(rawConfig);
3677
- const app = new import_hono.Hono();
3678
- if (config.db?.sync) {
3679
- await config.db.sync(config.collections, config.globals);
3680
- }
3681
- app.use("*", (0, import_request_id.requestId)());
3682
- app.use("*", optionalAuth());
3683
- app.use("*", async (c, next) => {
3684
- const start = Date.now();
3685
- await next();
3686
- const ms = Date.now() - start;
3687
- console.log(`[dyrected/api] ${c.req.method} ${c.req.path} ${c.res.status} - ${ms}ms`);
3688
- });
3689
- app.use("*", (0, import_cors.cors)());
3690
- app.use("*", async (c, next) => {
3691
- c.set("config", config);
3692
- if (!c.get("siteId")) {
3693
- c.set("siteId", "default");
3694
- }
3695
- await next();
3696
- });
3697
- app.get("/health", (c) => c.json({ status: "ok", version: "0.0.1" }));
3698
- app.get("/routes", (c) => {
3699
- const routes = app.routes.map((r) => ({ method: r.method, path: r.path }));
3700
- return c.json({ routes });
3701
- });
3702
- app.onError((err, c) => {
3703
- console.error(`[dyrected/core] Uncaught Error:`, err);
3704
- return c.json({
3705
- message: err.message || "Internal Server Error",
3706
- stack: process.env.NODE_ENV === "development" ? err.stack : void 0
3707
- }, 500);
3708
- });
3709
- registerRoutes(app, config);
3710
- return app;
3711
- }
3712
-
3713
1320
  // src/index.ts
3714
1321
  function defineCollection(config) {
3715
1322
  return config;
@@ -3722,7 +1329,6 @@ function defineConfig(config) {
3722
1329
  }
3723
1330
  // Annotate the CommonJS export names for ESM import in node:
3724
1331
  0 && (module.exports = {
3725
- createDyrectedApp,
3726
1332
  defineCollection,
3727
1333
  defineConfig,
3728
1334
  defineGlobal,