@dyrected/core 2.5.13 → 2.5.16

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 (48) hide show
  1. package/dist/app-B2tg7Djj.d.cts +1575 -0
  2. package/dist/app-B2tg7Djj.d.ts +1575 -0
  3. package/dist/app-Bh4_Opv0.d.cts +1522 -0
  4. package/dist/app-Bh4_Opv0.d.ts +1522 -0
  5. package/dist/app-Bv9gaDAN.d.cts +561 -0
  6. package/dist/app-Bv9gaDAN.d.ts +561 -0
  7. package/dist/app-BvG3bRc8.d.cts +419 -0
  8. package/dist/app-BvG3bRc8.d.ts +419 -0
  9. package/dist/app-C3B9N1KR.d.cts +1522 -0
  10. package/dist/app-C3B9N1KR.d.ts +1522 -0
  11. package/dist/app-DDJJa0ep.d.cts +1621 -0
  12. package/dist/app-DDJJa0ep.d.ts +1621 -0
  13. package/dist/app-DO1s9YW1.d.cts +1621 -0
  14. package/dist/app-DO1s9YW1.d.ts +1621 -0
  15. package/dist/app-DTP3-9PJ.d.cts +561 -0
  16. package/dist/app-DTP3-9PJ.d.ts +561 -0
  17. package/dist/app-DbKDGYTI.d.cts +566 -0
  18. package/dist/app-DbKDGYTI.d.ts +566 -0
  19. package/dist/app-DqRO-CMi.d.cts +1457 -0
  20. package/dist/app-DqRO-CMi.d.ts +1457 -0
  21. package/dist/app-DvaFpOtj.d.cts +398 -0
  22. package/dist/app-DvaFpOtj.d.ts +398 -0
  23. package/dist/app-FGzip4XM.d.cts +1563 -0
  24. package/dist/app-FGzip4XM.d.ts +1563 -0
  25. package/dist/app-T0alZAE0.d.cts +383 -0
  26. package/dist/app-T0alZAE0.d.ts +383 -0
  27. package/dist/app-oQt5-9MU.d.cts +1560 -0
  28. package/dist/app-oQt5-9MU.d.ts +1560 -0
  29. package/dist/app-rZj1VFer.d.cts +1621 -0
  30. package/dist/app-rZj1VFer.d.ts +1621 -0
  31. package/dist/app-wo82JRHl.d.cts +445 -0
  32. package/dist/app-wo82JRHl.d.ts +445 -0
  33. package/dist/chunk-23URSKPI.js +2371 -0
  34. package/dist/chunk-2JMA3M5S.js +2475 -0
  35. package/dist/chunk-3FZEUK36.js +2470 -0
  36. package/dist/chunk-DOJHZ7XN.js +2394 -0
  37. package/dist/chunk-PKNFV7KE.js +2469 -0
  38. package/dist/chunk-UBTRANFX.js +2476 -0
  39. package/dist/chunk-W6KURRMW.js +2471 -0
  40. package/dist/index.cjs +457 -48
  41. package/dist/index.d.cts +117 -8
  42. package/dist/index.d.ts +117 -8
  43. package/dist/index.js +9 -3
  44. package/dist/server.cjs +449 -46
  45. package/dist/server.d.cts +57 -15
  46. package/dist/server.d.ts +57 -15
  47. package/dist/server.js +1 -1
  48. package/package.json +1 -1
@@ -0,0 +1,2470 @@
1
+ // src/utils/config.ts
2
+ var AUDIT_COLLECTION_SLUG = "__audit";
3
+ var SYSTEM_FIELDS = [
4
+ {
5
+ name: "createdAt",
6
+ type: "date",
7
+ label: "Created At",
8
+ admin: { readOnly: true, hidden: true }
9
+ },
10
+ {
11
+ name: "updatedAt",
12
+ type: "date",
13
+ label: "Updated At",
14
+ admin: { readOnly: true, hidden: true }
15
+ },
16
+ {
17
+ name: "createdBy",
18
+ type: "text",
19
+ label: "Created By",
20
+ admin: { readOnly: true, hidden: true }
21
+ },
22
+ {
23
+ name: "updatedBy",
24
+ type: "text",
25
+ label: "Updated By",
26
+ admin: { readOnly: true, hidden: true }
27
+ }
28
+ ];
29
+ var AUDIT_COLLECTION = {
30
+ slug: AUDIT_COLLECTION_SLUG,
31
+ labels: { singular: "Audit Log", plural: "Audit Logs" },
32
+ fields: [
33
+ { name: "collection", type: "text", label: "Collection", required: true },
34
+ { name: "documentId", type: "text", label: "Document ID" },
35
+ { name: "operation", type: "select", label: "Operation", options: ["create", "update", "delete"], required: true },
36
+ { name: "user", type: "text", label: "User ID" },
37
+ { name: "timestamp", type: "date", label: "Timestamp", required: true },
38
+ { name: "changes", type: "json", label: "Changes" }
39
+ ],
40
+ admin: { hidden: true }
41
+ };
42
+ function normalizeConfig(config) {
43
+ const collections = config?.collections || [];
44
+ const globals = config?.globals || [];
45
+ const needsAudit = collections.some((col) => col.audit);
46
+ const normalizedCollections = collections.map((col) => {
47
+ let fields = col.fields || [];
48
+ const existingFieldNames = new Set(fields.map((f) => f.name));
49
+ if (col.auth) {
50
+ if (!existingFieldNames.has("email")) {
51
+ fields = [
52
+ ...fields,
53
+ {
54
+ name: "email",
55
+ type: "email",
56
+ label: "Email",
57
+ required: true,
58
+ unique: true,
59
+ promoted: true,
60
+ access: {
61
+ update: "!id"
62
+ }
63
+ }
64
+ ];
65
+ }
66
+ if (!existingFieldNames.has("password")) {
67
+ fields = [
68
+ ...fields,
69
+ {
70
+ name: "password",
71
+ type: "text",
72
+ label: "Password",
73
+ required: true,
74
+ access: {
75
+ update: "!id || user.id == id"
76
+ }
77
+ }
78
+ ];
79
+ }
80
+ if (!existingFieldNames.has("roles")) {
81
+ fields = [
82
+ ...fields,
83
+ {
84
+ name: "roles",
85
+ type: "select",
86
+ label: "Roles",
87
+ defaultValue: [],
88
+ options: [
89
+ { value: "admin", label: "Admin" },
90
+ { value: "editor", label: "Editor" },
91
+ { value: "viewer", label: "Viewer" }
92
+ ],
93
+ access: {
94
+ update: "user.roles && 'admin' in user.roles"
95
+ }
96
+ }
97
+ ];
98
+ }
99
+ fields = fields.map((field) => {
100
+ if (field.name === "email") {
101
+ return {
102
+ ...field,
103
+ access: {
104
+ ...field.access || {},
105
+ update: "!id"
106
+ }
107
+ };
108
+ }
109
+ if (field.name === "password") {
110
+ return {
111
+ ...field,
112
+ admin: { ...field.admin || {} },
113
+ access: {
114
+ ...field.access || {},
115
+ update: "!id || user.id == id"
116
+ }
117
+ };
118
+ }
119
+ if (field.name === "roles") {
120
+ return {
121
+ ...field,
122
+ access: {
123
+ ...field.access || {},
124
+ // Must be an admin; cannot edit own roles (no self-elevation).
125
+ update: "user.roles && 'admin' in user.roles && user.id != id"
126
+ }
127
+ };
128
+ }
129
+ return field;
130
+ });
131
+ }
132
+ const updatedFieldNames = new Set(fields.map((f) => f.name));
133
+ const fieldsToInject = SYSTEM_FIELDS.filter((f) => !updatedFieldNames.has(f.name));
134
+ return {
135
+ ...col,
136
+ fields: [...fields, ...fieldsToInject]
137
+ };
138
+ });
139
+ const hasAuditCollection = normalizedCollections.some((col) => col.slug === AUDIT_COLLECTION_SLUG);
140
+ return {
141
+ ...config,
142
+ collections: [...normalizedCollections, ...needsAudit && !hasAuditCollection ? [AUDIT_COLLECTION] : []],
143
+ globals
144
+ };
145
+ }
146
+
147
+ // src/utils/hooks.ts
148
+ async function runCollectionHooks(hooks, args) {
149
+ if (!hooks || hooks.length === 0) {
150
+ return args.data ?? args.doc ?? void 0;
151
+ }
152
+ let currentPayload = args.data ?? args.doc ?? void 0;
153
+ for (const hook of hooks) {
154
+ const result = await hook({
155
+ ...args,
156
+ data: args.data !== void 0 ? currentPayload : void 0,
157
+ doc: args.doc !== void 0 ? currentPayload : void 0
158
+ });
159
+ if (result !== void 0) {
160
+ currentPayload = result;
161
+ }
162
+ }
163
+ return currentPayload;
164
+ }
165
+ async function executeFieldBeforeChange(fields, data, originalDoc, user) {
166
+ if (!data || typeof data !== "object") return data;
167
+ const result = { ...data };
168
+ for (const field of fields) {
169
+ if (!field.name) continue;
170
+ const value = result[field.name];
171
+ const origValue = originalDoc?.[field.name];
172
+ let updatedValue = value;
173
+ if (field.hooks?.beforeChange) {
174
+ for (const hook of field.hooks.beforeChange) {
175
+ updatedValue = await hook({
176
+ value: updatedValue,
177
+ originalDoc,
178
+ data: result,
179
+ user
180
+ });
181
+ }
182
+ result[field.name] = updatedValue;
183
+ }
184
+ if (updatedValue !== void 0 && updatedValue !== null) {
185
+ if (field.type === "object" && field.fields) {
186
+ result[field.name] = await executeFieldBeforeChange(
187
+ field.fields,
188
+ updatedValue,
189
+ origValue,
190
+ user
191
+ );
192
+ } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
193
+ const arrayResult = [];
194
+ for (let i = 0; i < updatedValue.length; i++) {
195
+ const item = updatedValue[i];
196
+ const origItem = Array.isArray(origValue) ? origValue[i] : void 0;
197
+ const processedItem = await executeFieldBeforeChange(
198
+ field.fields,
199
+ item,
200
+ origItem,
201
+ user
202
+ );
203
+ arrayResult.push(processedItem);
204
+ }
205
+ result[field.name] = arrayResult;
206
+ } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
207
+ const blocksResult = [];
208
+ for (let i = 0; i < updatedValue.length; i++) {
209
+ const blockData = updatedValue[i];
210
+ const origBlock = Array.isArray(origValue) ? origValue[i] : void 0;
211
+ const blockConfig = field.blocks.find((b) => b.slug === blockData.blockType);
212
+ if (blockConfig) {
213
+ const processedBlock = await executeFieldBeforeChange(
214
+ blockConfig.fields,
215
+ blockData,
216
+ origBlock,
217
+ user
218
+ );
219
+ blocksResult.push(processedBlock);
220
+ } else {
221
+ blocksResult.push(blockData);
222
+ }
223
+ }
224
+ result[field.name] = blocksResult;
225
+ }
226
+ }
227
+ }
228
+ return result;
229
+ }
230
+ async function executeFieldAfterRead(fields, doc, user) {
231
+ if (!doc || typeof doc !== "object") return doc;
232
+ const result = { ...doc };
233
+ for (const field of fields) {
234
+ if (!field.name) continue;
235
+ const value = result[field.name];
236
+ let updatedValue = value;
237
+ if (field.hooks?.afterRead) {
238
+ for (const hook of field.hooks.afterRead) {
239
+ updatedValue = await hook({
240
+ value: updatedValue,
241
+ doc: result,
242
+ user
243
+ });
244
+ }
245
+ result[field.name] = updatedValue;
246
+ }
247
+ if (updatedValue !== void 0 && updatedValue !== null) {
248
+ if (field.type === "object" && field.fields) {
249
+ result[field.name] = await executeFieldAfterRead(
250
+ field.fields,
251
+ updatedValue,
252
+ user
253
+ );
254
+ } else if (field.type === "array" && field.fields && Array.isArray(updatedValue)) {
255
+ const arrayResult = [];
256
+ for (const item of updatedValue) {
257
+ const processedItem = await executeFieldAfterRead(
258
+ field.fields,
259
+ item,
260
+ user
261
+ );
262
+ arrayResult.push(processedItem);
263
+ }
264
+ result[field.name] = arrayResult;
265
+ } else if (field.type === "blocks" && field.blocks && Array.isArray(updatedValue)) {
266
+ const blocksResult = [];
267
+ for (const blockData of updatedValue) {
268
+ const blockConfig = field.blocks.find((b) => b.slug === blockData.blockType);
269
+ if (blockConfig) {
270
+ const processedBlock = await executeFieldAfterRead(
271
+ blockConfig.fields,
272
+ blockData,
273
+ user
274
+ );
275
+ blocksResult.push(processedBlock);
276
+ } else {
277
+ blocksResult.push(blockData);
278
+ }
279
+ }
280
+ result[field.name] = blocksResult;
281
+ }
282
+ }
283
+ }
284
+ return result;
285
+ }
286
+
287
+ // src/services/defaults.service.ts
288
+ var DefaultsService = class {
289
+ /**
290
+ * Recursively apply default values to a data object based on field definitions.
291
+ */
292
+ static apply(fields, data = {}) {
293
+ const result = { ...data || {} };
294
+ fields.forEach((field) => {
295
+ if (field.type === "join") return;
296
+ if (field.type === "row" && field.fields) {
297
+ Object.assign(result, this.apply(field.fields, data));
298
+ return;
299
+ }
300
+ if (!field.name) return;
301
+ let value = result[field.name];
302
+ if ((value === void 0 || value === null) && field.renameTo) {
303
+ const legacyValue = result[field.renameTo];
304
+ if (legacyValue !== void 0 && legacyValue !== null) {
305
+ value = legacyValue;
306
+ result[field.name] = legacyValue;
307
+ }
308
+ }
309
+ if (value === void 0 || value === null) {
310
+ if (field.defaultValue !== void 0) {
311
+ result[field.name] = field.defaultValue;
312
+ } else {
313
+ if (field.type === "boolean") result[field.name] = false;
314
+ else if (field.type === "array") result[field.name] = [];
315
+ else if (field.type === "multiSelect") result[field.name] = [];
316
+ else if (field.type === "object") {
317
+ result[field.name] = this.apply(field.fields || [], {});
318
+ }
319
+ }
320
+ } else if (field.type === "object" && field.fields) {
321
+ result[field.name] = this.apply(field.fields, value);
322
+ } else if (field.type === "array" && field.fields && Array.isArray(value)) {
323
+ result[field.name] = value.map((item) => this.apply(field.fields, item));
324
+ }
325
+ });
326
+ return result;
327
+ }
328
+ };
329
+
330
+ // src/services/population.service.ts
331
+ var PopulationService = class {
332
+ db;
333
+ collections;
334
+ constructor(db, collections) {
335
+ this.db = db;
336
+ this.collections = collections;
337
+ }
338
+ /**
339
+ * Recursively populate relationship fields in a document or array of documents.
340
+ */
341
+ async populate(args) {
342
+ const { data, fields, currentDepth = 0, maxDepth = 10 } = args;
343
+ if (currentDepth >= maxDepth || !data) {
344
+ return data;
345
+ }
346
+ if (Array.isArray(data)) {
347
+ return Promise.all(data.map((item) => this.populate({ ...args, data: item })));
348
+ }
349
+ const populatedDoc = { ...data };
350
+ for (const field of fields) {
351
+ if (field.type === "join") continue;
352
+ if (field.type === "row" && field.fields) {
353
+ const rowPopulated = await this.populate({ data, fields: field.fields, currentDepth, maxDepth });
354
+ Object.assign(populatedDoc, rowPopulated);
355
+ continue;
356
+ }
357
+ if (!field.name) continue;
358
+ const value = populatedDoc[field.name];
359
+ if (field.type === "relationship" && field.relationTo && value) {
360
+ const relatedCollection = this.collections.find((c) => c.slug === field.relationTo);
361
+ if (!relatedCollection) continue;
362
+ if (Array.isArray(value)) {
363
+ populatedDoc[field.name] = await Promise.all(
364
+ value.map(async (id) => {
365
+ if (!id) return id;
366
+ let doc = id;
367
+ if (typeof id === "string") {
368
+ doc = await this.db.findOne({ collection: field.relationTo, id });
369
+ }
370
+ if (!doc || typeof doc !== "object") return id;
371
+ const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
372
+ return this.populate({
373
+ data: docWithDefaults,
374
+ fields: relatedCollection.fields,
375
+ currentDepth: currentDepth + 1,
376
+ maxDepth
377
+ });
378
+ })
379
+ );
380
+ } else if (value) {
381
+ let doc = value;
382
+ if (typeof value === "string") {
383
+ doc = await this.db.findOne({ collection: field.relationTo, id: value });
384
+ }
385
+ if (doc && typeof doc === "object") {
386
+ const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
387
+ populatedDoc[field.name] = await this.populate({
388
+ data: docWithDefaults,
389
+ fields: relatedCollection.fields,
390
+ currentDepth: currentDepth + 1,
391
+ maxDepth
392
+ });
393
+ }
394
+ }
395
+ }
396
+ if (field.type === "url" && value && typeof value === "object" && value.type === "internal" && value.relationTo && value.value) {
397
+ const relatedCollection = this.collections.find((c) => c.slug === value.relationTo);
398
+ if (relatedCollection) {
399
+ const doc = await this.db.findOne({ collection: value.relationTo, id: value.value });
400
+ if (doc && typeof doc === "object") {
401
+ const docWithDefaults = DefaultsService.apply(relatedCollection.fields, doc);
402
+ const populatedDocValue = await this.populate({
403
+ data: docWithDefaults,
404
+ fields: relatedCollection.fields,
405
+ currentDepth: currentDepth + 1,
406
+ maxDepth
407
+ });
408
+ const identifier = docWithDefaults.slug || docWithDefaults.id;
409
+ const resolvedUrl = `/collections/${value.relationTo}/${identifier}`;
410
+ populatedDoc[field.name] = {
411
+ ...value,
412
+ url: resolvedUrl,
413
+ doc: populatedDocValue
414
+ };
415
+ }
416
+ }
417
+ }
418
+ if ((field.type === "array" || field.type === "object") && field.fields && value) {
419
+ populatedDoc[field.name] = await this.populate({
420
+ data: value,
421
+ fields: field.fields,
422
+ currentDepth,
423
+ // Nested fields don't consume depth, only relationships do
424
+ maxDepth
425
+ });
426
+ }
427
+ if (field.type === "blocks" && field.blocks && Array.isArray(value)) {
428
+ populatedDoc[field.name] = await Promise.all(
429
+ value.map(async (blockData) => {
430
+ const blockConfig = field.blocks.find((b) => b.slug === blockData.blockType);
431
+ if (!blockConfig) return blockData;
432
+ return this.populate({
433
+ data: blockData,
434
+ fields: blockConfig.fields,
435
+ currentDepth,
436
+ maxDepth
437
+ });
438
+ })
439
+ );
440
+ }
441
+ }
442
+ return populatedDoc;
443
+ }
444
+ /**
445
+ * Helper to populate a PaginatedResult
446
+ */
447
+ async populateResult(result, fields, maxDepth) {
448
+ if (maxDepth <= 0) return result;
449
+ const populatedDocs = await this.populate({
450
+ data: result.docs,
451
+ fields,
452
+ currentDepth: 0,
453
+ maxDepth
454
+ });
455
+ return {
456
+ ...result,
457
+ docs: populatedDocs
458
+ };
459
+ }
460
+ };
461
+
462
+ // src/services/audit.service.ts
463
+ var AuditService = class {
464
+ /**
465
+ * Writes a single entry to the __audit collection.
466
+ * Called without await — runs asynchronously and never blocks the primary operation.
467
+ */
468
+ static async log(db, args) {
469
+ try {
470
+ await db.create({
471
+ collection: "__audit",
472
+ data: {
473
+ collection: args.collection,
474
+ documentId: args.documentId ?? null,
475
+ operation: args.operation,
476
+ user: args.user?.id ?? null,
477
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
478
+ changes: JSON.stringify({
479
+ before: args.before ?? null,
480
+ after: args.after ?? null
481
+ })
482
+ }
483
+ });
484
+ } catch (err) {
485
+ console.error("[dyrected/audit] Failed to write audit log:", err);
486
+ }
487
+ }
488
+ };
489
+
490
+ // src/auth/password.ts
491
+ import { promisify } from "util";
492
+ import { scrypt, randomBytes, timingSafeEqual } from "crypto";
493
+ var scryptAsync = promisify(scrypt);
494
+ var SALT_LEN = 16;
495
+ var KEY_LEN = 64;
496
+ async function hashPassword(plain) {
497
+ const salt = randomBytes(SALT_LEN).toString("hex");
498
+ const derivedKey = await scryptAsync(plain, salt, KEY_LEN);
499
+ return `${salt}:${derivedKey.toString("hex")}`;
500
+ }
501
+ async function verifyPassword(plain, stored) {
502
+ const [salt, storedHash] = stored.split(":");
503
+ if (!salt || !storedHash) return false;
504
+ const derivedKey = await scryptAsync(plain, salt, KEY_LEN);
505
+ const storedBuffer = Buffer.from(storedHash, "hex");
506
+ if (derivedKey.length !== storedBuffer.length) return false;
507
+ return timingSafeEqual(derivedKey, storedBuffer);
508
+ }
509
+
510
+ // src/controllers/collection.controller.ts
511
+ var CollectionController = class {
512
+ collection;
513
+ constructor(collection) {
514
+ this.collection = collection;
515
+ }
516
+ async find(c) {
517
+ const config = c.get("config");
518
+ const db = config.db;
519
+ if (!db) return c.json({ message: "Database not configured" }, 500);
520
+ const limit = Number(c.req.query("limit")) || 10;
521
+ const page = Number(c.req.query("page")) || 1;
522
+ const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 2;
523
+ const sort = c.req.query("sort") || void 0;
524
+ const user = c.get("user");
525
+ let where = void 0;
526
+ const whereRaw = c.req.query("where");
527
+ if (whereRaw) {
528
+ try {
529
+ where = JSON.parse(decodeURIComponent(whereRaw));
530
+ } catch {
531
+ }
532
+ }
533
+ const beforeReadResult = await runCollectionHooks(this.collection.hooks?.beforeRead, {
534
+ req: c.req,
535
+ query: where,
536
+ user
537
+ });
538
+ if (beforeReadResult !== void 0) {
539
+ where = beforeReadResult;
540
+ }
541
+ let result = await db.find({
542
+ collection: this.collection.slug,
543
+ limit,
544
+ page,
545
+ sort,
546
+ where
547
+ });
548
+ if (result.total === 0 && this.collection.initialData && !where && page === 1) {
549
+ console.log(`[dyrected/core] Auto-seeding collection "${this.collection.slug}" from config.initialData`);
550
+ for (const data of this.collection.initialData) {
551
+ await db.create({ collection: this.collection.slug, data });
552
+ }
553
+ result = await db.find({
554
+ collection: this.collection.slug,
555
+ limit,
556
+ page,
557
+ sort,
558
+ where
559
+ });
560
+ }
561
+ result.docs = result.docs.map((doc) => DefaultsService.apply(this.collection.fields, doc));
562
+ const processedDocs = [];
563
+ for (const doc of result.docs) {
564
+ const docWithCollectionHooks = await runCollectionHooks(this.collection.hooks?.afterRead, {
565
+ doc,
566
+ req: c.req,
567
+ user
568
+ });
569
+ const docWithFieldHooks = await executeFieldAfterRead(this.collection.fields, docWithCollectionHooks, user);
570
+ processedDocs.push(docWithFieldHooks);
571
+ }
572
+ result.docs = processedDocs;
573
+ if (depth > 0) {
574
+ const populationService = new PopulationService(db, config.collections);
575
+ result = await populationService.populateResult(result, this.collection.fields, depth);
576
+ }
577
+ return c.json(result);
578
+ }
579
+ async findOne(c) {
580
+ const config = c.get("config");
581
+ const db = config.db;
582
+ if (!db) return c.json({ message: "Database not configured" }, 500);
583
+ const id = c.req.param("id");
584
+ const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 10;
585
+ const user = c.get("user");
586
+ if (!id) return c.json({ message: "Missing ID" }, 400);
587
+ const doc = await db.findOne({ collection: this.collection.slug, id });
588
+ if (!doc) return c.json({ message: "Not Found" }, 404);
589
+ const docWithDefaults = DefaultsService.apply(this.collection.fields, doc);
590
+ const docWithCollectionHooks = await runCollectionHooks(this.collection.hooks?.afterRead, {
591
+ doc: docWithDefaults,
592
+ req: c.req,
593
+ user
594
+ });
595
+ const docWithFieldHooks = await executeFieldAfterRead(this.collection.fields, docWithCollectionHooks, user);
596
+ if (depth > 0 && docWithFieldHooks) {
597
+ const populationService = new PopulationService(db, config.collections);
598
+ const populatedDoc = await populationService.populate({
599
+ data: docWithFieldHooks,
600
+ fields: this.collection.fields,
601
+ currentDepth: 0,
602
+ maxDepth: depth
603
+ });
604
+ return c.json(populatedDoc);
605
+ }
606
+ return c.json(docWithFieldHooks);
607
+ }
608
+ async create(c) {
609
+ const config = c.get("config");
610
+ const db = config.db;
611
+ if (!db) return c.json({ message: "Database not configured" }, 500);
612
+ const contentType = c.req.header("Content-Type") || "";
613
+ if (contentType.toLowerCase().includes("multipart/form-data")) {
614
+ return this.upload(c);
615
+ }
616
+ const body = await c.req.json();
617
+ const user = c.get("user");
618
+ const now = (/* @__PURE__ */ new Date()).toISOString();
619
+ let data = {
620
+ ...body,
621
+ createdAt: now,
622
+ updatedAt: now,
623
+ createdBy: user?.sub ?? null,
624
+ updatedBy: user?.sub ?? null
625
+ };
626
+ if (this.collection.auth && data.password) {
627
+ data.password = await hashPassword(data.password);
628
+ }
629
+ data = await executeFieldBeforeChange(this.collection.fields, data, null, user);
630
+ data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
631
+ data,
632
+ req: c.req,
633
+ user,
634
+ operation: "create"
635
+ });
636
+ const doc = await db.create({ collection: this.collection.slug, data });
637
+ if (this.collection.audit && db) {
638
+ AuditService.log(db, {
639
+ operation: "create",
640
+ collection: this.collection.slug,
641
+ documentId: doc.id,
642
+ user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
643
+ before: null,
644
+ after: doc
645
+ });
646
+ }
647
+ await runCollectionHooks(this.collection.hooks?.afterChange, {
648
+ doc,
649
+ user,
650
+ req: c.req,
651
+ operation: "create"
652
+ });
653
+ const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
654
+ doc,
655
+ req: c.req,
656
+ user
657
+ });
658
+ const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
659
+ return c.json(finalDoc, 201);
660
+ }
661
+ async upload(c) {
662
+ const config = c.get("config");
663
+ const storage = config.storage;
664
+ if (!storage) return c.json({ message: "Storage not configured" }, 500);
665
+ const formData = await c.req.formData();
666
+ const file = formData.get("file");
667
+ if (!file) return c.json({ message: "No file uploaded" }, 400);
668
+ const buffer = new Uint8Array(await file.arrayBuffer());
669
+ const siteId = c.get("siteId");
670
+ const workspaceId = c.get("workspaceId");
671
+ const prefix = workspaceId ? `${workspaceId}/${siteId}` : siteId;
672
+ const fileData = await storage.upload({
673
+ filename: file.name,
674
+ buffer,
675
+ mimeType: file.type,
676
+ prefix
677
+ });
678
+ const otherData = {};
679
+ formData.forEach((value, key) => {
680
+ if (key !== "file" && typeof value === "string") {
681
+ otherData[key] = value;
682
+ }
683
+ });
684
+ const user = c.get("user");
685
+ const now = (/* @__PURE__ */ new Date()).toISOString();
686
+ let data = {
687
+ ...otherData,
688
+ ...fileData,
689
+ createdAt: now,
690
+ updatedAt: now,
691
+ createdBy: user?.sub ?? null,
692
+ updatedBy: user?.sub ?? null
693
+ };
694
+ data = await executeFieldBeforeChange(this.collection.fields, data, null, user);
695
+ data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
696
+ data,
697
+ req: c.req,
698
+ user,
699
+ operation: "create"
700
+ });
701
+ const doc = await config.db.create({
702
+ collection: this.collection.slug,
703
+ data
704
+ });
705
+ await runCollectionHooks(this.collection.hooks?.afterChange, {
706
+ doc,
707
+ user,
708
+ req: c.req,
709
+ operation: "create"
710
+ });
711
+ const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
712
+ doc,
713
+ req: c.req,
714
+ user
715
+ });
716
+ const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
717
+ return c.json(finalDoc, 201);
718
+ }
719
+ async update(c) {
720
+ const config = c.get("config");
721
+ const db = config.db;
722
+ if (!db) return c.json({ message: "Database not configured" }, 500);
723
+ const id = c.req.param("id");
724
+ if (!id) return c.json({ message: "Missing ID" }, 400);
725
+ const body = await c.req.json();
726
+ const user = c.get("user");
727
+ let data = { ...body };
728
+ if (this.collection.auth) {
729
+ delete data.password;
730
+ delete data.oldPassword;
731
+ delete data.confirmPassword;
732
+ }
733
+ Object.assign(data, {
734
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
735
+ updatedBy: user?.sub ?? null
736
+ });
737
+ const originalDoc = await db.findOne({ collection: this.collection.slug, id });
738
+ if (!originalDoc) return c.json({ message: "Not Found" }, 404);
739
+ let before = null;
740
+ if (this.collection.audit) {
741
+ before = originalDoc;
742
+ }
743
+ data = await executeFieldBeforeChange(this.collection.fields, data, originalDoc, user);
744
+ data = await runCollectionHooks(this.collection.hooks?.beforeChange, {
745
+ data,
746
+ doc: originalDoc,
747
+ req: c.req,
748
+ user,
749
+ operation: "update"
750
+ });
751
+ const doc = await db.update({ collection: this.collection.slug, id, data });
752
+ if (this.collection.audit && db) {
753
+ AuditService.log(db, {
754
+ operation: "update",
755
+ collection: this.collection.slug,
756
+ documentId: id,
757
+ user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
758
+ before,
759
+ after: doc
760
+ });
761
+ }
762
+ await runCollectionHooks(this.collection.hooks?.afterChange, {
763
+ doc,
764
+ previousDoc: originalDoc,
765
+ user,
766
+ req: c.req,
767
+ operation: "update"
768
+ });
769
+ const readDoc = await runCollectionHooks(this.collection.hooks?.afterRead, {
770
+ doc,
771
+ req: c.req,
772
+ user
773
+ });
774
+ const finalDoc = await executeFieldAfterRead(this.collection.fields, readDoc, user);
775
+ return c.json(finalDoc);
776
+ }
777
+ /**
778
+ * POST /api/collections/:slug/:id/change-password
779
+ *
780
+ * Dedicated endpoint for password changes. Requires the caller to supply:
781
+ * { oldPassword, newPassword, confirmPassword }
782
+ *
783
+ * Rules:
784
+ * - Only the account owner or an admin may change the password.
785
+ * - Non-admin callers MUST provide a valid oldPassword.
786
+ * - newPassword and confirmPassword must match.
787
+ */
788
+ async changePassword(c) {
789
+ const config = c.get("config");
790
+ const db = config.db;
791
+ if (!db) return c.json({ message: "Database not configured" }, 500);
792
+ if (!this.collection.auth) {
793
+ return c.json({ message: "This collection does not support authentication" }, 400);
794
+ }
795
+ const id = c.req.param("id");
796
+ if (!id) return c.json({ message: "Missing ID" }, 400);
797
+ const user = c.get("user");
798
+ if (!user) return c.json({ message: "Authentication required" }, 401);
799
+ const body = await c.req.json().catch(() => null);
800
+ const { oldPassword, newPassword, confirmPassword } = body ?? {};
801
+ if (!newPassword) {
802
+ return c.json({ message: "newPassword is required" }, 400);
803
+ }
804
+ if (newPassword !== confirmPassword) {
805
+ return c.json({ message: "Passwords do not match" }, 400);
806
+ }
807
+ if (newPassword.length < 8) {
808
+ return c.json({ message: "Password must be at least 8 characters" }, 400);
809
+ }
810
+ const isAdmin = Array.isArray(user.roles) && user.roles.includes("admin");
811
+ const isSelf = user.sub === id;
812
+ if (!isAdmin && !isSelf) {
813
+ return c.json({ message: "You are not authorised to change this password" }, 403);
814
+ }
815
+ if (!isAdmin) {
816
+ if (!oldPassword) {
817
+ return c.json({ message: "Current password is required" }, 400);
818
+ }
819
+ const existing = await db.findOne({ collection: this.collection.slug, id });
820
+ if (!existing) return c.json({ message: "User not found" }, 404);
821
+ const valid = await verifyPassword(oldPassword, existing.password);
822
+ if (!valid) {
823
+ return c.json({ message: "Invalid current password" }, 400);
824
+ }
825
+ }
826
+ const hashed = await hashPassword(newPassword);
827
+ const doc = await db.update({
828
+ collection: this.collection.slug,
829
+ id,
830
+ data: {
831
+ password: hashed,
832
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
833
+ updatedBy: user.sub
834
+ }
835
+ });
836
+ if (this.collection.audit) {
837
+ AuditService.log(db, {
838
+ operation: "update",
839
+ collection: this.collection.slug,
840
+ documentId: id,
841
+ user: { id: user.sub, collection: user.collection, email: user.email },
842
+ before: null,
843
+ after: { id }
844
+ });
845
+ }
846
+ return c.json({ success: true, message: "Password updated successfully" });
847
+ }
848
+ async delete(c) {
849
+ const config = c.get("config");
850
+ const db = config.db;
851
+ if (!db) return c.json({ message: "Database not configured" }, 500);
852
+ const id = c.req.param("id");
853
+ if (!id) return c.json({ message: "Missing ID" }, 400);
854
+ const user = c.get("user");
855
+ const doc = await db.findOne({ collection: this.collection.slug, id });
856
+ if (!doc) return c.json({ message: "Not Found" }, 404);
857
+ let before = null;
858
+ if (this.collection.audit) {
859
+ before = doc;
860
+ }
861
+ await runCollectionHooks(this.collection.hooks?.beforeDelete, {
862
+ id,
863
+ doc,
864
+ user,
865
+ req: c.req
866
+ });
867
+ await db.delete({ collection: this.collection.slug, id });
868
+ if (this.collection.audit && db) {
869
+ AuditService.log(db, {
870
+ operation: "delete",
871
+ collection: this.collection.slug,
872
+ documentId: id,
873
+ user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
874
+ before,
875
+ after: null
876
+ });
877
+ }
878
+ await runCollectionHooks(this.collection.hooks?.afterDelete, {
879
+ id,
880
+ doc,
881
+ user,
882
+ req: c.req
883
+ });
884
+ return c.json({ message: "Deleted" });
885
+ }
886
+ async deleteMany(c) {
887
+ const config = c.get("config");
888
+ const db = config.db;
889
+ if (!db) return c.json({ message: "Database not configured" }, 500);
890
+ const user = c.get("user");
891
+ let ids = [];
892
+ try {
893
+ const body = await c.req.json().catch(() => null);
894
+ if (body?.ids && Array.isArray(body.ids)) {
895
+ ids = body.ids;
896
+ }
897
+ } catch {
898
+ }
899
+ if (!ids.length) {
900
+ const raw = c.req.queries("ids") ?? c.req.queries("ids[]") ?? [];
901
+ ids = raw.filter(Boolean);
902
+ }
903
+ if (!ids.length) return c.json({ message: "No IDs provided" }, 400);
904
+ const deleted = [];
905
+ const failed = [];
906
+ for (const id of ids) {
907
+ try {
908
+ const doc = await db.findOne({ collection: this.collection.slug, id });
909
+ if (!doc) {
910
+ failed.push({ id, error: "Not Found" });
911
+ continue;
912
+ }
913
+ let before = null;
914
+ if (this.collection.audit) {
915
+ before = doc;
916
+ }
917
+ await runCollectionHooks(this.collection.hooks?.beforeDelete, {
918
+ id,
919
+ doc,
920
+ user,
921
+ req: c.req
922
+ });
923
+ await db.delete({ collection: this.collection.slug, id });
924
+ deleted.push(id);
925
+ if (this.collection.audit) {
926
+ AuditService.log(db, {
927
+ operation: "delete",
928
+ collection: this.collection.slug,
929
+ documentId: id,
930
+ user: user ? { id: user.sub, collection: user.collection, email: user.email } : void 0,
931
+ before,
932
+ after: null
933
+ });
934
+ }
935
+ await runCollectionHooks(this.collection.hooks?.afterDelete, {
936
+ id,
937
+ doc,
938
+ user,
939
+ req: c.req
940
+ });
941
+ } catch (err) {
942
+ failed.push({ id, error: err?.message ?? "Unknown error" });
943
+ }
944
+ }
945
+ return c.json({
946
+ message: `Deleted ${deleted.length} document(s)`,
947
+ deleted,
948
+ ...failed.length ? { failed } : {}
949
+ });
950
+ }
951
+ async seed(c) {
952
+ const config = c.get("config");
953
+ const db = config.db;
954
+ if (!db) return c.json({ message: "Database not configured" }, 500);
955
+ const body = await c.req.json();
956
+ const initialData = body.data;
957
+ if (!initialData || !Array.isArray(initialData)) {
958
+ return c.json({ message: "Invalid initial data" }, 400);
959
+ }
960
+ const result = await db.find({ collection: this.collection.slug, limit: 1 });
961
+ if (result.total > 0) {
962
+ return c.json({ message: "Collection is not empty, skipping seed" });
963
+ }
964
+ console.log(`[dyrected/core] Auto-seeding collection: ${this.collection.slug}`);
965
+ const createdDocs = [];
966
+ for (const data of initialData) {
967
+ const doc = await db.create({ collection: this.collection.slug, data });
968
+ createdDocs.push(doc);
969
+ }
970
+ return c.json({ message: "Seed successful", count: createdDocs.length }, 201);
971
+ }
972
+ };
973
+
974
+ // src/controllers/global.controller.ts
975
+ var GlobalController = class {
976
+ global;
977
+ constructor(global) {
978
+ this.global = global;
979
+ }
980
+ async get(c) {
981
+ const config = c.get("config");
982
+ const db = config.db;
983
+ if (!db) return c.json({ message: "Database not configured" }, 500);
984
+ const depth = c.req.query("depth") !== void 0 ? Number(c.req.query("depth")) : 10;
985
+ const user = c.get("user");
986
+ let query = void 0;
987
+ const beforeReadResult = await runCollectionHooks(this.global.hooks?.beforeRead, {
988
+ req: c.req,
989
+ query,
990
+ user
991
+ });
992
+ if (beforeReadResult !== void 0) {
993
+ query = beforeReadResult;
994
+ }
995
+ let data = await db.getGlobal({ slug: this.global.slug });
996
+ const isEmpty = !data || Object.keys(data).length === 0;
997
+ if (isEmpty && this.global.initialData) {
998
+ console.log(`[dyrected/core] Auto-seeding global "${this.global.slug}" from config.initialData`);
999
+ await db.updateGlobal({ slug: this.global.slug, data: this.global.initialData });
1000
+ data = this.global.initialData;
1001
+ }
1002
+ const dataWithDefaults = DefaultsService.apply(this.global.fields, data);
1003
+ const docWithCollectionHooks = await runCollectionHooks(this.global.hooks?.afterRead, {
1004
+ doc: dataWithDefaults,
1005
+ req: c.req,
1006
+ user
1007
+ });
1008
+ const docWithFieldHooks = await executeFieldAfterRead(this.global.fields, docWithCollectionHooks, user);
1009
+ if (depth > 0 && docWithFieldHooks) {
1010
+ const populationService = new PopulationService(db, config.collections);
1011
+ const populatedData = await populationService.populate({
1012
+ data: docWithFieldHooks,
1013
+ fields: this.global.fields,
1014
+ currentDepth: 0,
1015
+ maxDepth: depth
1016
+ });
1017
+ return c.json(populatedData);
1018
+ }
1019
+ return c.json(docWithFieldHooks);
1020
+ }
1021
+ async update(c) {
1022
+ const db = c.get("config").db;
1023
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1024
+ const body = await c.req.json();
1025
+ const user = c.get("user");
1026
+ const originalDoc = await db.getGlobal({ slug: this.global.slug }) || {};
1027
+ let data = await executeFieldBeforeChange(this.global.fields, body, originalDoc, user);
1028
+ data = await runCollectionHooks(this.global.hooks?.beforeChange, {
1029
+ data,
1030
+ doc: originalDoc,
1031
+ req: c.req,
1032
+ user,
1033
+ operation: "update"
1034
+ });
1035
+ const updated = await db.updateGlobal({ slug: this.global.slug, data });
1036
+ await runCollectionHooks(this.global.hooks?.afterChange, {
1037
+ doc: updated,
1038
+ previousDoc: originalDoc,
1039
+ user,
1040
+ req: c.req,
1041
+ operation: "update"
1042
+ });
1043
+ const readDoc = await runCollectionHooks(this.global.hooks?.afterRead, {
1044
+ doc: updated,
1045
+ req: c.req,
1046
+ user
1047
+ });
1048
+ const finalDoc = await executeFieldAfterRead(this.global.fields, readDoc, user);
1049
+ return c.json(finalDoc);
1050
+ }
1051
+ async seed(c) {
1052
+ const config = c.get("config");
1053
+ const db = config.db;
1054
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1055
+ const body = await c.req.json();
1056
+ const initialData = body.data;
1057
+ if (!initialData) {
1058
+ return c.json({ message: "Invalid initial data" }, 400);
1059
+ }
1060
+ const existing = await db.getGlobal({ slug: this.global.slug });
1061
+ if (existing && Object.keys(existing).length > 0) {
1062
+ return c.json({ message: "Global is not empty, skipping seed" });
1063
+ }
1064
+ console.log(`[dyrected/core] Auto-seeding global: ${this.global.slug}`);
1065
+ await db.updateGlobal({ slug: this.global.slug, data: initialData });
1066
+ return c.json({ message: "Seed successful", data: initialData }, 201);
1067
+ }
1068
+ };
1069
+
1070
+ // src/controllers/media.controller.ts
1071
+ var MediaController = class {
1072
+ collection;
1073
+ constructor(collection = "media") {
1074
+ this.collection = collection;
1075
+ }
1076
+ async upload(c) {
1077
+ const config = c.get("config");
1078
+ const storage = config.storage;
1079
+ const imageService = config.image;
1080
+ if (!storage) {
1081
+ return c.json({ message: "Storage not configured" }, 500);
1082
+ }
1083
+ const body = await c.req.parseBody();
1084
+ const file = body["file"];
1085
+ const focalPointStr = body["focalPoint"];
1086
+ const focalPoint = focalPointStr ? JSON.parse(focalPointStr) : void 0;
1087
+ if (!file) {
1088
+ return c.json({ message: "No file uploaded" }, 400);
1089
+ }
1090
+ const buffer = new Uint8Array(await file.arrayBuffer());
1091
+ const siteId = c.get("siteId");
1092
+ const workspaceId = c.get("workspaceId");
1093
+ const prefix = workspaceId ? `${workspaceId}/${siteId}` : siteId || "default";
1094
+ let imageMetadata = {};
1095
+ let imageSizes = {};
1096
+ if (imageService && file.type.startsWith("image/")) {
1097
+ let colConfig = config.collections.find((col) => col.slug === this.collection);
1098
+ if (!colConfig && config.onSchemaFetch && siteId) {
1099
+ const dynamic = await config.onSchemaFetch(siteId);
1100
+ colConfig = dynamic.collections?.find((col) => col.slug === this.collection);
1101
+ }
1102
+ try {
1103
+ const processed = await imageService.process({
1104
+ buffer,
1105
+ mimeType: file.type,
1106
+ config: colConfig?.upload,
1107
+ focalPoint
1108
+ });
1109
+ imageMetadata = processed.metadata;
1110
+ imageSizes = processed.sizes;
1111
+ } catch (err) {
1112
+ console.error("[MediaController] Image processing failed:", err);
1113
+ }
1114
+ }
1115
+ const fileData = await storage.upload({
1116
+ filename: file.name,
1117
+ buffer,
1118
+ mimeType: file.type,
1119
+ prefix
1120
+ });
1121
+ const finalFileData = {
1122
+ ...fileData,
1123
+ ...imageMetadata,
1124
+ focalPoint,
1125
+ sizes: {}
1126
+ };
1127
+ if (imageSizes) {
1128
+ for (const [sizeName, sizeData] of Object.entries(imageSizes)) {
1129
+ const ext = file.name.split(".").pop();
1130
+ const baseName = file.name.substring(0, file.name.lastIndexOf("."));
1131
+ const sizeFilename = `${baseName}-${sizeName}.${ext}`;
1132
+ try {
1133
+ const sizeFileData = await storage.upload({
1134
+ filename: sizeFilename,
1135
+ buffer: sizeData.buffer,
1136
+ mimeType: file.type,
1137
+ prefix
1138
+ });
1139
+ finalFileData.sizes[sizeName] = {
1140
+ ...sizeFileData,
1141
+ width: sizeData.width,
1142
+ height: sizeData.height
1143
+ };
1144
+ } catch (err) {
1145
+ console.error(`[MediaController] Failed to upload size ${sizeName}:`, err);
1146
+ }
1147
+ }
1148
+ }
1149
+ const db = config.db;
1150
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1151
+ const doc = await db.create({
1152
+ collection: this.collection,
1153
+ data: finalFileData
1154
+ });
1155
+ return c.json(doc, 201);
1156
+ }
1157
+ async find(c) {
1158
+ const db = c.get("config").db;
1159
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1160
+ const limit = Number(c.req.query("limit")) || 10;
1161
+ const page = Number(c.req.query("page")) || 1;
1162
+ const result = await db.find({
1163
+ collection: this.collection,
1164
+ limit,
1165
+ page
1166
+ });
1167
+ return c.json(result);
1168
+ }
1169
+ async delete(c) {
1170
+ const config = c.get("config");
1171
+ const storage = config.storage;
1172
+ const db = config.db;
1173
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1174
+ const id = c.req.param("id");
1175
+ if (!id) return c.json({ message: "Missing ID" }, 400);
1176
+ const doc = await db.findOne({ collection: this.collection, id });
1177
+ if (!doc) return c.json({ message: "Not Found" }, 404);
1178
+ if (storage) {
1179
+ await storage.delete({ filename: doc.filename });
1180
+ if (doc.sizes) {
1181
+ for (const size of Object.values(doc.sizes)) {
1182
+ if (size.filename) {
1183
+ await storage.delete({ filename: size.filename });
1184
+ }
1185
+ }
1186
+ }
1187
+ }
1188
+ await db.delete({ collection: this.collection, id });
1189
+ return c.json({ message: "Deleted" });
1190
+ }
1191
+ async serve(c) {
1192
+ const config = c.get("config");
1193
+ const storage = config.storage;
1194
+ if (!storage || !storage.resolve) {
1195
+ return c.json({ message: "Storage not configured for serving" }, 404);
1196
+ }
1197
+ const filename = c.req.param("filename");
1198
+ if (!filename) return c.json({ message: "Missing filename" }, 400);
1199
+ let res = await storage.resolve({ filename });
1200
+ if (!res && !filename.includes("/")) {
1201
+ res = await storage.resolve({ filename: `default/${filename}` });
1202
+ }
1203
+ if (!res) return c.json({ message: "Not Found" }, 404);
1204
+ c.header("Content-Type", res.mimeType);
1205
+ return c.body(res.buffer);
1206
+ }
1207
+ };
1208
+
1209
+ // src/auth/token.ts
1210
+ import { SignJWT, jwtVerify, decodeJwt } from "jose";
1211
+ import { TextEncoder } from "util";
1212
+ function getSecret() {
1213
+ const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET;
1214
+ if (!secret) {
1215
+ throw new Error(
1216
+ "[dyrected/core] DYRECTED_JWT_SECRET is not set. Add it to your environment variables to enable auth collections."
1217
+ );
1218
+ }
1219
+ return new TextEncoder().encode(secret);
1220
+ }
1221
+ var DEFAULT_EXPIRY = "7d";
1222
+ async function signCollectionToken(payload, expiresIn = DEFAULT_EXPIRY) {
1223
+ return new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(getSecret());
1224
+ }
1225
+ async function verifyCollectionToken(token) {
1226
+ const { payload } = await jwtVerify(token, getSecret());
1227
+ return payload;
1228
+ }
1229
+
1230
+ // src/services/email.service.ts
1231
+ var _devSend = null;
1232
+ var _devSendPromise = null;
1233
+ async function getDevSend() {
1234
+ if (_devSend) return _devSend;
1235
+ if (_devSendPromise) return _devSendPromise;
1236
+ _devSendPromise = (async () => {
1237
+ try {
1238
+ const nodemailer = await import("nodemailer");
1239
+ const account = await nodemailer.default.createTestAccount();
1240
+ const transport = nodemailer.default.createTransport({
1241
+ host: "smtp.ethereal.email",
1242
+ port: 587,
1243
+ auth: { user: account.user, pass: account.pass }
1244
+ });
1245
+ console.log("[dyrected/core] No email config \u2014 using Ethereal for dev email preview.");
1246
+ console.log(`[dyrected/core] Ethereal login: https://ethereal.email user: ${account.user} pass: ${account.pass}`);
1247
+ _devSend = async ({ to, subject, html }) => {
1248
+ const info = await transport.sendMail({ from: '"Dyrected Dev" <dev@dyrected.local>', to, subject, html });
1249
+ console.log(`[dyrected/core] Email preview URL: ${nodemailer.default.getTestMessageUrl(info)}`);
1250
+ };
1251
+ return _devSend;
1252
+ } catch {
1253
+ console.warn("[dyrected/core] nodemailer not available \u2014 emails will not be sent in dev.");
1254
+ return null;
1255
+ }
1256
+ })();
1257
+ return _devSendPromise;
1258
+ }
1259
+ async function sendEmail(config, payload) {
1260
+ if (config.email) {
1261
+ await config.email.send(payload);
1262
+ return;
1263
+ }
1264
+ if (process.env.NODE_ENV !== "production") {
1265
+ const devSend = await getDevSend();
1266
+ await devSend?.(payload);
1267
+ }
1268
+ }
1269
+ function buildWelcomeEmail(config, args) {
1270
+ const custom = config.email?.templates?.welcome?.(args);
1271
+ return {
1272
+ subject: custom?.subject ?? "Welcome \u2014 your account is ready",
1273
+ html: custom?.html ?? `
1274
+ <div style="font-family:sans-serif;max-width:600px;margin:0 auto">
1275
+ <h2>Welcome!</h2>
1276
+ <p>Your account has been created. You can now log in with:</p>
1277
+ <p><strong>${args.email}</strong></p>
1278
+ </div>`
1279
+ };
1280
+ }
1281
+ function buildInviteEmail(config, args) {
1282
+ const custom = config.email?.templates?.invite?.(args);
1283
+ return {
1284
+ subject: custom?.subject ?? "You've been invited",
1285
+ html: custom?.html ?? `
1286
+ <div style="font-family:sans-serif;max-width:600px;margin:0 auto">
1287
+ <h2>You've been invited</h2>
1288
+ ${args.invitedByEmail ? `<p>Invited by <strong>${args.invitedByEmail}</strong>.</p>` : ""}
1289
+ <p>Use the token below to accept your invitation. It expires in 7 days.</p>
1290
+ <pre style="background:#f4f4f4;padding:12px;border-radius:4px;word-break:break-all">${args.token}</pre>
1291
+ </div>`
1292
+ };
1293
+ }
1294
+ function buildResetPasswordEmail(config, args) {
1295
+ const custom = config.email?.templates?.resetPassword?.(args);
1296
+ return {
1297
+ subject: custom?.subject ?? "Reset your password",
1298
+ html: custom?.html ?? `
1299
+ <div style="font-family:sans-serif;max-width:600px;margin:0 auto">
1300
+ <h2>Reset your password</h2>
1301
+ <p>Use the token below to reset your password. It expires in 1 hour.</p>
1302
+ <pre style="background:#f4f4f4;padding:12px;border-radius:4px;word-break:break-all">${args.token}</pre>
1303
+ </div>`
1304
+ };
1305
+ }
1306
+ function buildPasswordChangedEmail(config, args) {
1307
+ const custom = config.email?.templates?.passwordChanged?.(args);
1308
+ return {
1309
+ subject: custom?.subject ?? "Your password has been changed",
1310
+ html: custom?.html ?? `
1311
+ <div style="font-family:sans-serif;max-width:600px;margin:0 auto">
1312
+ <h2>Password changed</h2>
1313
+ <p>The password for <strong>${args.email}</strong> was just changed.</p>
1314
+ <p>If you did not make this change, please contact support immediately.</p>
1315
+ </div>`
1316
+ };
1317
+ }
1318
+
1319
+ // src/controllers/auth.controller.ts
1320
+ var AuthController = class {
1321
+ collection;
1322
+ constructor(collection) {
1323
+ this.collection = collection;
1324
+ }
1325
+ // ---------------------------------------------------------------------------
1326
+ // GET /init
1327
+ // Checks if the first user needs to be created.
1328
+ // ---------------------------------------------------------------------------
1329
+ async init(c) {
1330
+ const db = c.get("config").db;
1331
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1332
+ const result = await db.find({
1333
+ collection: this.collection.slug,
1334
+ limit: 1
1335
+ });
1336
+ return c.json({
1337
+ initialized: result.total > 0
1338
+ });
1339
+ }
1340
+ // ---------------------------------------------------------------------------
1341
+ // POST /first-user
1342
+ // Creates the first user if none exist.
1343
+ // ---------------------------------------------------------------------------
1344
+ async registerFirstUser(c) {
1345
+ const config = c.get("config");
1346
+ const db = config.db;
1347
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1348
+ const check = await db.find({
1349
+ collection: this.collection.slug,
1350
+ limit: 1
1351
+ });
1352
+ if (check.total > 0) {
1353
+ return c.json({ error: true, message: "Initial user already exists." }, 403);
1354
+ }
1355
+ const body = await c.req.json().catch(() => null);
1356
+ if (!body?.email || !body?.password) {
1357
+ return c.json({ error: true, message: "email and password are required." }, 400);
1358
+ }
1359
+ const hashedPassword = await hashPassword(body.password);
1360
+ const user = await db.create({
1361
+ collection: this.collection.slug,
1362
+ data: {
1363
+ ...body,
1364
+ password: hashedPassword,
1365
+ roles: ["admin"]
1366
+ // Default first user to admin
1367
+ }
1368
+ });
1369
+ const token = await signCollectionToken({
1370
+ sub: user.id,
1371
+ email: user.email,
1372
+ collection: this.collection.slug
1373
+ });
1374
+ const { subject, html } = buildWelcomeEmail(config, { email: body.email });
1375
+ sendEmail(config, { to: body.email, subject, html }).catch(
1376
+ (err) => console.error("[dyrected/core] Failed to send welcome email:", err)
1377
+ );
1378
+ const { password: _, ...safeUser } = user;
1379
+ return c.json({ token, user: safeUser });
1380
+ }
1381
+ // ---------------------------------------------------------------------------
1382
+ // POST /login
1383
+ // ---------------------------------------------------------------------------
1384
+ async login(c) {
1385
+ const db = c.get("config").db;
1386
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1387
+ const body = await c.req.json().catch(() => null);
1388
+ if (!body?.email || !body?.password) {
1389
+ return c.json({ error: true, message: "email and password are required." }, 400);
1390
+ }
1391
+ const result = await db.find({
1392
+ collection: this.collection.slug,
1393
+ where: { email: body.email },
1394
+ limit: 1
1395
+ });
1396
+ const user = result.docs[0];
1397
+ if (!user) {
1398
+ return c.json({ error: true, message: "Invalid email or password." }, 401);
1399
+ }
1400
+ const valid = await verifyPassword(body.password, user.password);
1401
+ if (!valid) {
1402
+ return c.json({ error: true, message: "Invalid email or password." }, 401);
1403
+ }
1404
+ const token = await signCollectionToken({
1405
+ sub: user.id,
1406
+ email: user.email,
1407
+ collection: this.collection.slug
1408
+ });
1409
+ const { password: _, ...safeUser } = user;
1410
+ return c.json({ token, user: safeUser });
1411
+ }
1412
+ // ---------------------------------------------------------------------------
1413
+ // POST /logout
1414
+ // Auth collections use stateless JWTs — logout is handled client-side.
1415
+ // This endpoint exists so clients have a consistent API surface.
1416
+ // ---------------------------------------------------------------------------
1417
+ async logout(c) {
1418
+ return c.json({ success: true, message: "Logged out. Discard your token." });
1419
+ }
1420
+ // ---------------------------------------------------------------------------
1421
+ // GET /me
1422
+ // ---------------------------------------------------------------------------
1423
+ async me(c) {
1424
+ const db = c.get("config").db;
1425
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1426
+ const requestUser = c.get("user");
1427
+ if (!requestUser) {
1428
+ return c.json({ error: true, message: "Authentication required." }, 401);
1429
+ }
1430
+ const user = await db.findOne({ collection: this.collection.slug, id: requestUser.sub });
1431
+ if (!user) {
1432
+ return c.json({ error: true, message: "User not found." }, 404);
1433
+ }
1434
+ const { password: _, ...safeUser } = user;
1435
+ return c.json(safeUser);
1436
+ }
1437
+ // ---------------------------------------------------------------------------
1438
+ // POST /refresh-token
1439
+ // ---------------------------------------------------------------------------
1440
+ async refreshToken(c) {
1441
+ const requestUser = c.get("user");
1442
+ if (!requestUser) {
1443
+ return c.json({ error: true, message: "Authentication required." }, 401);
1444
+ }
1445
+ const token = await signCollectionToken({
1446
+ sub: requestUser.sub,
1447
+ email: requestUser.email,
1448
+ collection: this.collection.slug
1449
+ });
1450
+ return c.json({ token });
1451
+ }
1452
+ // ---------------------------------------------------------------------------
1453
+ // POST /forgot-password
1454
+ // Requires config.email to be set. Silently succeeds if email not found
1455
+ // to prevent email enumeration.
1456
+ // ---------------------------------------------------------------------------
1457
+ async forgotPassword(c) {
1458
+ const config = c.get("config");
1459
+ const db = config.db;
1460
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1461
+ const body = await c.req.json().catch(() => null);
1462
+ if (!body?.email) {
1463
+ return c.json({ error: true, message: "email is required." }, 400);
1464
+ }
1465
+ const result = await db.find({
1466
+ collection: this.collection.slug,
1467
+ where: { email: body.email },
1468
+ limit: 1
1469
+ });
1470
+ const user = result.docs[0];
1471
+ if (user) {
1472
+ const resetToken = await signCollectionToken(
1473
+ { sub: user.id, email: user.email, collection: this.collection.slug, purpose: "reset" },
1474
+ "1h"
1475
+ );
1476
+ try {
1477
+ const { subject, html } = buildResetPasswordEmail(config, { token: resetToken });
1478
+ await sendEmail(config, { to: user.email, subject, html });
1479
+ } catch (err) {
1480
+ console.error("[dyrected/core] Failed to send password reset email:", err);
1481
+ }
1482
+ }
1483
+ return c.json({
1484
+ success: true,
1485
+ message: "If an account with that email exists, a reset link has been sent."
1486
+ });
1487
+ }
1488
+ // ---------------------------------------------------------------------------
1489
+ // POST /reset-password
1490
+ // Expects { token: string, password: string } in body.
1491
+ // The token is the reset JWT issued by /forgot-password.
1492
+ // ---------------------------------------------------------------------------
1493
+ async resetPassword(c) {
1494
+ const config = c.get("config");
1495
+ const db = config.db;
1496
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1497
+ const body = await c.req.json().catch(() => null);
1498
+ if (!body?.token || !body?.password) {
1499
+ return c.json({ error: true, message: "token and password are required." }, 400);
1500
+ }
1501
+ let payload;
1502
+ try {
1503
+ payload = await verifyCollectionToken(body.token);
1504
+ } catch {
1505
+ return c.json({ error: true, message: "Reset token is invalid or has expired." }, 400);
1506
+ }
1507
+ if (payload.collection !== this.collection.slug || payload.purpose !== "reset") {
1508
+ return c.json({ error: true, message: "Reset token is invalid or has expired." }, 400);
1509
+ }
1510
+ const hashedPassword = await hashPassword(body.password);
1511
+ await db.update({
1512
+ collection: this.collection.slug,
1513
+ id: payload.sub,
1514
+ data: { password: hashedPassword }
1515
+ });
1516
+ const { subject, html } = buildPasswordChangedEmail(config, { email: payload.email });
1517
+ sendEmail(config, { to: payload.email, subject, html }).catch(
1518
+ (err) => console.error("[dyrected/core] Failed to send password-changed email:", err)
1519
+ );
1520
+ return c.json({ success: true, message: "Password has been reset. You can now log in." });
1521
+ }
1522
+ // ---------------------------------------------------------------------------
1523
+ // POST /invite
1524
+ // Requires auth. Issues a signed invite token and emails it to the invitee.
1525
+ // ---------------------------------------------------------------------------
1526
+ async invite(c) {
1527
+ const config = c.get("config");
1528
+ const db = config.db;
1529
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1530
+ const requestUser = c.get("user");
1531
+ if (!requestUser) {
1532
+ return c.json({ error: true, message: "Authentication required." }, 401);
1533
+ }
1534
+ const body = await c.req.json().catch(() => null);
1535
+ if (!body?.email) {
1536
+ return c.json({ error: true, message: "email is required." }, 400);
1537
+ }
1538
+ const existing = await db.find({
1539
+ collection: this.collection.slug,
1540
+ where: { email: body.email },
1541
+ limit: 1
1542
+ });
1543
+ if (existing.total > 0) {
1544
+ return c.json({ error: true, message: "An account with that email already exists." }, 409);
1545
+ }
1546
+ const inviteToken = await signCollectionToken(
1547
+ { sub: body.email, email: body.email, collection: this.collection.slug, purpose: "invite" },
1548
+ "7d"
1549
+ );
1550
+ try {
1551
+ const { subject, html } = buildInviteEmail(config, {
1552
+ token: inviteToken,
1553
+ invitedByEmail: requestUser.email
1554
+ });
1555
+ await sendEmail(config, { to: body.email, subject, html });
1556
+ } catch (err) {
1557
+ console.error("[dyrected/core] Failed to send invite email:", err);
1558
+ }
1559
+ return c.json({ success: true, message: `Invite sent to ${body.email}.` });
1560
+ }
1561
+ // ---------------------------------------------------------------------------
1562
+ // POST /accept-invite
1563
+ // Public. Validates the invite token and creates the user account.
1564
+ // Body: { token, password, ...extraFields }
1565
+ // ---------------------------------------------------------------------------
1566
+ async acceptInvite(c) {
1567
+ const config = c.get("config");
1568
+ const db = config.db;
1569
+ if (!db) return c.json({ message: "Database not configured" }, 500);
1570
+ const body = await c.req.json().catch(() => null);
1571
+ if (!body?.token || !body?.password) {
1572
+ return c.json({ error: true, message: "token and password are required." }, 400);
1573
+ }
1574
+ let payload;
1575
+ try {
1576
+ payload = await verifyCollectionToken(body.token);
1577
+ } catch {
1578
+ return c.json({ error: true, message: "Invite token is invalid or has expired." }, 400);
1579
+ }
1580
+ if (payload.collection !== this.collection.slug || payload.purpose !== "invite") {
1581
+ return c.json({ error: true, message: "Invite token is invalid or has expired." }, 400);
1582
+ }
1583
+ const inviteeEmail = payload.sub;
1584
+ const existing = await db.find({
1585
+ collection: this.collection.slug,
1586
+ where: { email: inviteeEmail },
1587
+ limit: 1
1588
+ });
1589
+ if (existing.total > 0) {
1590
+ return c.json({ error: true, message: "An account with that email already exists." }, 409);
1591
+ }
1592
+ const { token: _t, password: _p, ...extraFields } = body;
1593
+ const hashedPassword = await hashPassword(body.password);
1594
+ const user = await db.create({
1595
+ collection: this.collection.slug,
1596
+ data: { ...extraFields, email: inviteeEmail, password: hashedPassword }
1597
+ });
1598
+ const sessionToken = await signCollectionToken({
1599
+ sub: user.id,
1600
+ email: inviteeEmail,
1601
+ collection: this.collection.slug
1602
+ });
1603
+ const { subject, html } = buildWelcomeEmail(config, { email: inviteeEmail });
1604
+ sendEmail(config, { to: inviteeEmail, subject, html }).catch(
1605
+ (err) => console.error("[dyrected/core] Failed to send welcome email:", err)
1606
+ );
1607
+ const { password: _, ...safeUser } = user;
1608
+ return c.json({ token: sessionToken, user: safeUser }, 201);
1609
+ }
1610
+ };
1611
+
1612
+ // src/controllers/preview.controller.ts
1613
+ import { SignJWT as SignJWT2, jwtVerify as jwtVerify2 } from "jose";
1614
+ import { TextEncoder as TextEncoder2 } from "util";
1615
+ var PreviewController = class {
1616
+ getSecret() {
1617
+ const secret = process.env.DYRECTED_JWT_SECRET || process.env.JWT_SECRET || "dyrected-preview-secret-change-me";
1618
+ return new TextEncoder2().encode(secret);
1619
+ }
1620
+ /**
1621
+ * POST /api/preview-token
1622
+ * Generates a short-lived token for previewing unsaved data.
1623
+ */
1624
+ async createToken(c) {
1625
+ const body = await c.req.json().catch(() => null);
1626
+ if (!body?.collectionSlug || !body?.data) {
1627
+ return c.json({ error: true, message: "collectionSlug and data are required." }, 400);
1628
+ }
1629
+ const token = await new SignJWT2({
1630
+ collectionSlug: body.collectionSlug,
1631
+ documentId: body.documentId,
1632
+ data: body.data
1633
+ }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime("15m").sign(this.getSecret());
1634
+ const expiresAt = new Date(Date.now() + 15 * 60 * 1e3).toISOString();
1635
+ return c.json({ token, expiresAt });
1636
+ }
1637
+ /**
1638
+ * GET /api/preview-data?token=<jwt>
1639
+ * Returns the data stored in the preview token.
1640
+ */
1641
+ async getData(c) {
1642
+ const token = c.req.query("token");
1643
+ if (!token) {
1644
+ return c.json({ error: true, message: "token query parameter is required." }, 400);
1645
+ }
1646
+ try {
1647
+ const { payload } = await jwtVerify2(token, this.getSecret());
1648
+ return c.json(payload);
1649
+ } catch (err) {
1650
+ return c.json({ error: true, message: "Invalid or expired preview token." }, 401);
1651
+ }
1652
+ }
1653
+ };
1654
+
1655
+ // src/middleware/auth.ts
1656
+ function requireAuth() {
1657
+ return async (c, next) => {
1658
+ const authHeader = c.req.header("Authorization");
1659
+ const token = authHeader?.replace(/^Bearer\s+/i, "");
1660
+ if (!token) {
1661
+ return c.json({ error: true, message: "Authentication required." }, 401);
1662
+ }
1663
+ try {
1664
+ const user = await verifyCollectionToken(token);
1665
+ c.set("user", user);
1666
+ await next();
1667
+ } catch {
1668
+ return c.json({ error: true, message: "Invalid or expired token." }, 401);
1669
+ }
1670
+ };
1671
+ }
1672
+ function optionalAuth() {
1673
+ return async (c, next) => {
1674
+ const authHeader = c.req.header("Authorization");
1675
+ const token = authHeader?.replace(/^Bearer\s+/i, "");
1676
+ if (token) {
1677
+ try {
1678
+ const user = await verifyCollectionToken(token);
1679
+ c.set("user", user);
1680
+ } catch {
1681
+ }
1682
+ }
1683
+ await next();
1684
+ };
1685
+ }
1686
+
1687
+ // src/utils/openapi.ts
1688
+ function generateOpenApi(config) {
1689
+ const spec = {
1690
+ openapi: "3.0.0",
1691
+ info: {
1692
+ title: "Dyrected API",
1693
+ version: "1.0.0",
1694
+ description: "Automatically generated OpenAPI specification for the Dyrected project."
1695
+ },
1696
+ components: {
1697
+ schemas: {},
1698
+ securitySchemes: {
1699
+ ApiKeyAuth: {
1700
+ type: "apiKey",
1701
+ in: "header",
1702
+ name: "x-api-key"
1703
+ }
1704
+ }
1705
+ },
1706
+ paths: {},
1707
+ security: [{ ApiKeyAuth: [] }]
1708
+ };
1709
+ for (const collection of config.collections) {
1710
+ spec.components.schemas[collection.slug] = collectionToSchema(collection);
1711
+ }
1712
+ for (const global of config.globals) {
1713
+ spec.components.schemas[global.slug] = globalToSchema(global);
1714
+ }
1715
+ for (const collection of config.collections) {
1716
+ const slug = collection.slug;
1717
+ const path = `/api/collections/${slug}`;
1718
+ const labels = collection.labels || { singular: slug, plural: `${slug}s` };
1719
+ spec.paths[path] = {
1720
+ get: {
1721
+ tags: ["Collections"],
1722
+ summary: `Find ${labels.plural}`,
1723
+ parameters: [
1724
+ { name: "limit", in: "query", schema: { type: "integer", default: 10 } },
1725
+ { name: "page", in: "query", schema: { type: "integer", default: 1 } },
1726
+ { name: "where", in: "query", schema: { type: "string" }, description: "JSON filter" },
1727
+ { name: "sort", in: "query", schema: { type: "string" }, description: "Sort field (e.g. -createdAt)" }
1728
+ ],
1729
+ responses: {
1730
+ 200: {
1731
+ description: "Success",
1732
+ content: {
1733
+ "application/json": {
1734
+ schema: {
1735
+ type: "object",
1736
+ properties: {
1737
+ docs: { type: "array", items: { $ref: `#/components/schemas/${slug}` } },
1738
+ total: { type: "integer" },
1739
+ limit: { type: "integer" },
1740
+ page: { type: "integer" }
1741
+ }
1742
+ }
1743
+ }
1744
+ }
1745
+ }
1746
+ }
1747
+ },
1748
+ post: {
1749
+ tags: ["Collections"],
1750
+ summary: `Create ${labels.singular}`,
1751
+ requestBody: {
1752
+ required: true,
1753
+ content: {
1754
+ "application/json": {
1755
+ schema: { $ref: `#/components/schemas/${slug}` }
1756
+ }
1757
+ }
1758
+ },
1759
+ responses: {
1760
+ 201: {
1761
+ description: "Created",
1762
+ content: {
1763
+ "application/json": {
1764
+ schema: { $ref: `#/components/schemas/${slug}` }
1765
+ }
1766
+ }
1767
+ }
1768
+ }
1769
+ }
1770
+ };
1771
+ spec.paths[`${path}/{id}`] = {
1772
+ get: {
1773
+ tags: ["Collections"],
1774
+ summary: `Get a single ${labels.singular}`,
1775
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
1776
+ responses: {
1777
+ 200: {
1778
+ description: "Success",
1779
+ content: {
1780
+ "application/json": {
1781
+ schema: { $ref: `#/components/schemas/${slug}` }
1782
+ }
1783
+ }
1784
+ }
1785
+ }
1786
+ },
1787
+ patch: {
1788
+ tags: ["Collections"],
1789
+ summary: `Update ${labels.singular}`,
1790
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
1791
+ requestBody: {
1792
+ required: true,
1793
+ content: {
1794
+ "application/json": {
1795
+ schema: { $ref: `#/components/schemas/${slug}` }
1796
+ }
1797
+ }
1798
+ },
1799
+ responses: {
1800
+ 200: {
1801
+ description: "Updated",
1802
+ content: {
1803
+ "application/json": {
1804
+ schema: { $ref: `#/components/schemas/${slug}` }
1805
+ }
1806
+ }
1807
+ }
1808
+ }
1809
+ },
1810
+ delete: {
1811
+ tags: ["Collections"],
1812
+ summary: `Delete ${labels.singular}`,
1813
+ parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
1814
+ responses: {
1815
+ 204: { description: "Deleted" }
1816
+ }
1817
+ }
1818
+ };
1819
+ }
1820
+ for (const global of config.globals) {
1821
+ const slug = global.slug;
1822
+ const path = `/api/globals/${slug}`;
1823
+ spec.paths[path] = {
1824
+ get: {
1825
+ tags: ["Globals"],
1826
+ summary: `Get ${global.label || slug}`,
1827
+ responses: {
1828
+ 200: {
1829
+ description: "Success",
1830
+ content: {
1831
+ "application/json": {
1832
+ schema: { $ref: `#/components/schemas/${slug}` }
1833
+ }
1834
+ }
1835
+ }
1836
+ }
1837
+ },
1838
+ patch: {
1839
+ tags: ["Globals"],
1840
+ summary: `Update ${global.label || slug}`,
1841
+ requestBody: {
1842
+ required: true,
1843
+ content: {
1844
+ "application/json": {
1845
+ schema: { $ref: `#/components/schemas/${slug}` }
1846
+ }
1847
+ }
1848
+ },
1849
+ responses: {
1850
+ 200: {
1851
+ description: "Updated",
1852
+ content: {
1853
+ "application/json": {
1854
+ schema: { $ref: `#/components/schemas/${slug}` }
1855
+ }
1856
+ }
1857
+ }
1858
+ }
1859
+ }
1860
+ };
1861
+ }
1862
+ if (config.storage) {
1863
+ spec.paths["/api/media"] = {
1864
+ get: {
1865
+ tags: ["Media"],
1866
+ summary: "List Media",
1867
+ responses: {
1868
+ 200: {
1869
+ description: "Success",
1870
+ content: {
1871
+ "application/json": {
1872
+ schema: {
1873
+ type: "object",
1874
+ properties: {
1875
+ docs: { type: "array", items: { type: "object", additionalProperties: true } }
1876
+ }
1877
+ }
1878
+ }
1879
+ }
1880
+ }
1881
+ }
1882
+ },
1883
+ post: {
1884
+ tags: ["Media"],
1885
+ summary: "Upload Media",
1886
+ requestBody: {
1887
+ content: {
1888
+ "multipart/form-data": {
1889
+ schema: {
1890
+ type: "object",
1891
+ properties: {
1892
+ file: { type: "string", format: "binary" }
1893
+ }
1894
+ }
1895
+ }
1896
+ }
1897
+ },
1898
+ responses: {
1899
+ 201: { description: "Uploaded" }
1900
+ }
1901
+ }
1902
+ };
1903
+ }
1904
+ return spec;
1905
+ }
1906
+ function collectionToSchema(collection) {
1907
+ const { properties, required } = fieldsToProperties(collection.fields);
1908
+ return {
1909
+ type: "object",
1910
+ properties: {
1911
+ id: { type: "string" },
1912
+ createdAt: { type: "string", format: "date-time" },
1913
+ updatedAt: { type: "string", format: "date-time" },
1914
+ ...properties
1915
+ },
1916
+ required: ["id", ...required]
1917
+ };
1918
+ }
1919
+ function globalToSchema(global) {
1920
+ const { properties, required } = fieldsToProperties(global.fields);
1921
+ return {
1922
+ type: "object",
1923
+ properties,
1924
+ required
1925
+ };
1926
+ }
1927
+ function fieldsToProperties(fields) {
1928
+ const props = {};
1929
+ const required = [];
1930
+ for (const field of fields) {
1931
+ if (!field.name || field.type === "join" || field.type === "row") continue;
1932
+ props[field.name] = fieldToSchema(field);
1933
+ if (field.required) {
1934
+ required.push(field.name);
1935
+ }
1936
+ }
1937
+ return { properties: props, required };
1938
+ }
1939
+ function fieldToSchema(field) {
1940
+ let schema = {};
1941
+ switch (field.type) {
1942
+ case "text":
1943
+ case "textarea":
1944
+ case "email":
1945
+ case "url":
1946
+ schema = { type: "string" };
1947
+ break;
1948
+ case "number":
1949
+ schema = { type: "number" };
1950
+ break;
1951
+ case "boolean":
1952
+ schema = { type: "boolean" };
1953
+ break;
1954
+ case "date":
1955
+ schema = { type: "string", format: "date-time" };
1956
+ break;
1957
+ case "select":
1958
+ schema = { type: "string", enum: field.options?.map((o) => typeof o === "string" ? o : o.value) };
1959
+ break;
1960
+ case "multiSelect":
1961
+ schema = {
1962
+ type: "array",
1963
+ items: { type: "string", enum: field.options?.map((o) => typeof o === "string" ? o : o.value) }
1964
+ };
1965
+ break;
1966
+ case "relationship":
1967
+ schema = { type: "string", description: `ID of a ${field.relationTo} record` };
1968
+ break;
1969
+ case "object": {
1970
+ const { properties, required } = fieldsToProperties(field.fields || []);
1971
+ schema = { type: "object", properties, required };
1972
+ break;
1973
+ }
1974
+ case "array": {
1975
+ const { properties, required } = fieldsToProperties(field.fields || []);
1976
+ schema = { type: "array", items: { type: "object", properties, required } };
1977
+ break;
1978
+ }
1979
+ case "json":
1980
+ case "richText":
1981
+ schema = { type: "object", additionalProperties: true };
1982
+ break;
1983
+ case "blocks":
1984
+ schema = {
1985
+ type: "array",
1986
+ items: {
1987
+ oneOf: field.blocks?.map((block) => {
1988
+ const { properties, required } = fieldsToProperties(block.fields);
1989
+ return {
1990
+ type: "object",
1991
+ properties: {
1992
+ blockType: { type: "string", enum: [block.slug] },
1993
+ ...properties
1994
+ },
1995
+ required: ["blockType", ...required]
1996
+ };
1997
+ })
1998
+ }
1999
+ };
2000
+ break;
2001
+ default:
2002
+ schema = { type: "string" };
2003
+ }
2004
+ if (field.label) schema.description = field.label;
2005
+ return schema;
2006
+ }
2007
+
2008
+ // src/utils/swagger.ts
2009
+ function getSwaggerHtml(specUrl = "/api/openapi.json") {
2010
+ return `
2011
+ <!DOCTYPE html>
2012
+ <html lang="en">
2013
+ <head>
2014
+ <meta charset="utf-8" />
2015
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
2016
+ <meta name="description" content="SwaggerUI" />
2017
+ <title>Dyrected API Documentation</title>
2018
+ <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css" />
2019
+ </head>
2020
+ <body>
2021
+ <div id="swagger-ui"></div>
2022
+ <script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-bundle.js" charset="UTF-8"></script>
2023
+ <script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-standalone-preset.js" charset="UTF-8"></script>
2024
+ <script>
2025
+ window.onload = () => {
2026
+ // Forward the apikey query param when loading the spec and making API calls
2027
+ const params = new URLSearchParams(window.location.search);
2028
+ const apiKey = params.get('apikey');
2029
+ const specUrlWithKey = apiKey ? '${specUrl}?apikey=' + encodeURIComponent(apiKey) : '${specUrl}';
2030
+
2031
+ window.ui = SwaggerUIBundle({
2032
+ url: specUrlWithKey,
2033
+ dom_id: '#swagger-ui',
2034
+ presets: [
2035
+ SwaggerUIBundle.presets.apis,
2036
+ SwaggerUIStandalonePreset
2037
+ ],
2038
+ layout: "BaseLayout",
2039
+ deepLinking: true,
2040
+ showExtensions: true,
2041
+ showCommonExtensions: true,
2042
+ // Inject x-api-key header on every request made from the Swagger UI
2043
+ requestInterceptor: (request) => {
2044
+ if (apiKey) {
2045
+ request.headers['x-api-key'] = apiKey;
2046
+ }
2047
+ return request;
2048
+ }
2049
+ });
2050
+ };
2051
+ </script>
2052
+ </body>
2053
+ </html>
2054
+ `;
2055
+ }
2056
+
2057
+ // src/auth/jexl.ts
2058
+ import jexl from "jexl";
2059
+ async function evaluateAccess(expression, context) {
2060
+ if (expression === void 0 || expression === null) return false;
2061
+ if (typeof expression === "boolean") return expression;
2062
+ try {
2063
+ const result = await jexl.eval(expression, context);
2064
+ return !!result;
2065
+ } catch (err) {
2066
+ console.error("[dyrected/core] Jexl evaluation failed:", err);
2067
+ return false;
2068
+ }
2069
+ }
2070
+
2071
+ // src/router.ts
2072
+ function accessGate(target, action) {
2073
+ return async (c, next) => {
2074
+ const user = c.get("user");
2075
+ const accessExpr = target.access?.[action];
2076
+ if (accessExpr === void 0 || accessExpr === null) {
2077
+ return await next();
2078
+ }
2079
+ const accessArgs = { user, req: c.req, doc: null };
2080
+ const allowed = await evaluateAccess(accessExpr, accessArgs);
2081
+ if (!allowed) {
2082
+ return c.json({ error: true, message: `Access denied: ${action} on ${target.slug}` }, 403);
2083
+ }
2084
+ await next();
2085
+ };
2086
+ }
2087
+ async function checkAccess(access, accessArgs) {
2088
+ if (access === void 0 || access === null) return true;
2089
+ if (typeof access === "function") {
2090
+ try {
2091
+ const result = await access(accessArgs);
2092
+ return typeof result === "boolean" ? result : !!result;
2093
+ } catch (err) {
2094
+ console.error("[dyrected/core] Functional access check failed:", err);
2095
+ return false;
2096
+ }
2097
+ }
2098
+ if (typeof access === "string" || typeof access === "boolean") {
2099
+ return evaluateAccess(access, accessArgs);
2100
+ }
2101
+ return true;
2102
+ }
2103
+ function serializeFieldForApi(f) {
2104
+ if (!f) return f;
2105
+ const serialized = { ...f };
2106
+ if (serialized.admin?.hooks) {
2107
+ const hooks = { ...serialized.admin.hooks };
2108
+ if (typeof hooks.onChange === "function") {
2109
+ hooks.onChange = hooks.onChange.toString();
2110
+ }
2111
+ if (typeof hooks.options === "function") {
2112
+ hooks.options = hooks.options.toString();
2113
+ }
2114
+ serialized.admin = { ...serialized.admin, hooks };
2115
+ }
2116
+ if (typeof serialized.options === "function" || serialized.options && typeof serialized.options === "object" && "resolve" in serialized.options) {
2117
+ serialized.options = { _dynamic: true };
2118
+ }
2119
+ if (serialized.fields) {
2120
+ serialized.fields = serialized.fields.map(serializeFieldForApi);
2121
+ }
2122
+ if (serialized.blocks) {
2123
+ serialized.blocks = serialized.blocks.map((b) => ({
2124
+ ...b,
2125
+ fields: b.fields?.map(serializeFieldForApi)
2126
+ }));
2127
+ }
2128
+ return serialized;
2129
+ }
2130
+ function registerRoutes(app, config) {
2131
+ app.get("/api/schemas", optionalAuth(), async (c) => {
2132
+ const siteId = c.req.header("X-Site-Id");
2133
+ let collections = [...config.collections];
2134
+ let globals = [...config.globals];
2135
+ if (siteId && config.onSchemaFetch) {
2136
+ const dynamic = await config.onSchemaFetch(siteId);
2137
+ if (dynamic.collections) collections = [...collections, ...dynamic.collections];
2138
+ if (dynamic.globals) globals = [...globals, ...dynamic.globals];
2139
+ if (dynamic.admin) {
2140
+ config.admin = { ...config.admin, ...dynamic.admin };
2141
+ }
2142
+ }
2143
+ const user = c.get("user");
2144
+ const accessArgs = { user, req: c.req, doc: null };
2145
+ const serializeAccess = async (access) => {
2146
+ if (typeof access === "string") return access;
2147
+ if (typeof access === "boolean") return access;
2148
+ return checkAccess(access, accessArgs);
2149
+ };
2150
+ const filteredCollections = await Promise.all(collections.filter((col) => !siteId || col.shared || !col.siteId || col.siteId === siteId).map(async (col) => ({
2151
+ slug: col.slug,
2152
+ labels: col.labels,
2153
+ access: {
2154
+ read: await serializeAccess(col.access?.read),
2155
+ create: await serializeAccess(col.access?.create),
2156
+ update: await serializeAccess(col.access?.update),
2157
+ delete: await serializeAccess(col.access?.delete)
2158
+ },
2159
+ fields: await Promise.all(col.fields.map(serializeFieldForApi).map(async (f) => ({
2160
+ name: f.name,
2161
+ type: f.type,
2162
+ label: f.label,
2163
+ required: f.required,
2164
+ defaultValue: f.defaultValue,
2165
+ options: f.options,
2166
+ relationTo: f.relationTo,
2167
+ hasMany: f.hasMany,
2168
+ fields: f.fields,
2169
+ blocks: f.blocks,
2170
+ admin: f.admin,
2171
+ access: {
2172
+ read: await serializeAccess(f.access?.read),
2173
+ update: await serializeAccess(f.access?.update)
2174
+ }
2175
+ }))),
2176
+ upload: !!col.upload,
2177
+ auth: !!col.auth,
2178
+ admin: col.admin
2179
+ })));
2180
+ const filteredGlobals = await Promise.all(globals.filter((glb) => !siteId || glb.shared || !glb.siteId || glb.siteId === siteId).map(async (glb) => ({
2181
+ slug: glb.slug,
2182
+ label: glb.label,
2183
+ access: {
2184
+ read: await serializeAccess(glb.access?.read),
2185
+ update: await serializeAccess(glb.access?.update)
2186
+ },
2187
+ fields: await Promise.all(glb.fields.map(serializeFieldForApi).map(async (f) => ({
2188
+ name: f.name,
2189
+ type: f.type,
2190
+ label: f.label,
2191
+ required: f.required,
2192
+ defaultValue: f.defaultValue,
2193
+ options: f.options,
2194
+ relationTo: f.relationTo,
2195
+ hasMany: f.hasMany,
2196
+ fields: f.fields,
2197
+ blocks: f.blocks,
2198
+ admin: f.admin,
2199
+ access: {
2200
+ read: await serializeAccess(f.access?.read),
2201
+ update: await serializeAccess(f.access?.update)
2202
+ }
2203
+ }))),
2204
+ admin: glb.admin
2205
+ })));
2206
+ return c.json({
2207
+ collections: filteredCollections,
2208
+ globals: filteredGlobals,
2209
+ admin: config.admin || {}
2210
+ });
2211
+ });
2212
+ app.get("/api/dyrected/options/:collection/:field", optionalAuth(), async (c) => {
2213
+ const { collection: colSlug, field: fieldName } = c.req.param();
2214
+ const siteId = c.req.header("X-Site-Id");
2215
+ let collections = [...config.collections];
2216
+ if (siteId && config.onSchemaFetch) {
2217
+ const dynamic = await config.onSchemaFetch(siteId);
2218
+ if (dynamic.collections) collections = [...collections, ...dynamic.collections];
2219
+ }
2220
+ const user = c.get("user");
2221
+ let collection = collections.find((col) => col.slug === colSlug);
2222
+ let field;
2223
+ if (collection) {
2224
+ const accessExpr = collection.access?.read;
2225
+ if (accessExpr !== void 0 && accessExpr !== null) {
2226
+ const accessArgs = { user, req: c.req, doc: null };
2227
+ const allowed = await checkAccess(accessExpr, accessArgs);
2228
+ if (!allowed) {
2229
+ return c.json({ error: true, message: `Access denied: read on ${colSlug}` }, 403);
2230
+ }
2231
+ }
2232
+ field = collection.fields.find((f) => f.name === fieldName);
2233
+ } else {
2234
+ let globals = [...config.globals];
2235
+ if (siteId && config.onSchemaFetch) {
2236
+ const dynamic = await config.onSchemaFetch(siteId);
2237
+ if (dynamic.globals) globals = [...globals, ...dynamic.globals];
2238
+ }
2239
+ const glb = globals.find((g) => g.slug === colSlug);
2240
+ if (!glb) {
2241
+ return c.json({ error: true, message: `${colSlug} not found as collection or global` }, 404);
2242
+ }
2243
+ const accessExpr = glb.access?.read;
2244
+ if (accessExpr !== void 0 && accessExpr !== null) {
2245
+ const accessArgs = { user, req: c.req, doc: null };
2246
+ const allowed = await checkAccess(accessExpr, accessArgs);
2247
+ if (!allowed) {
2248
+ return c.json({ error: true, message: `Access denied: read on global ${colSlug}` }, 403);
2249
+ }
2250
+ }
2251
+ field = glb.fields.find((f) => f.name === fieldName);
2252
+ }
2253
+ if (!field) {
2254
+ return c.json({ error: true, message: `Field ${fieldName} not found in ${colSlug}` }, 404);
2255
+ }
2256
+ let resolver;
2257
+ if (typeof field.options === "function") {
2258
+ resolver = field.options;
2259
+ } else if (field.options && typeof field.options === "object" && "resolve" in field.options) {
2260
+ resolver = field.options.resolve;
2261
+ }
2262
+ if (!resolver) {
2263
+ return c.json({ error: true, message: `Field ${fieldName} in ${colSlug} is not dynamic` }, 400);
2264
+ }
2265
+ try {
2266
+ const db = c.get("db") || config.db;
2267
+ const queryParams = c.req.query();
2268
+ const reqContext = {
2269
+ query: queryParams,
2270
+ headers: c.req.header(),
2271
+ raw: c.req.raw
2272
+ };
2273
+ const result = await resolver({
2274
+ db,
2275
+ user,
2276
+ req: reqContext
2277
+ });
2278
+ return c.json(result);
2279
+ } catch (err) {
2280
+ console.error(`[dyrected/core] Failed to resolve dynamic options for field ${fieldName}:`, err);
2281
+ return c.json({ error: true, message: err.message || "Failed to resolve dynamic options" }, 500);
2282
+ }
2283
+ });
2284
+ app.get("/api/openapi.json", (c) => {
2285
+ return c.json(generateOpenApi(config));
2286
+ });
2287
+ app.get("/api/docs", (c) => {
2288
+ return c.html(getSwaggerHtml());
2289
+ });
2290
+ app.get("/api/media/:filename{.+$}", async (c) => {
2291
+ const mediaController = new MediaController("media");
2292
+ return mediaController.serve(c);
2293
+ });
2294
+ app.get("/media/:filename{.+$}", async (c) => {
2295
+ const mediaController = new MediaController("media");
2296
+ return mediaController.serve(c);
2297
+ });
2298
+ if (config.storage) {
2299
+ const uploadCollections = config.collections.filter((c) => c.upload);
2300
+ for (const col of uploadCollections) {
2301
+ const mediaController = new MediaController(col.slug);
2302
+ const prefix = `/api/collections/${col.slug}`;
2303
+ app.get(`${prefix}/media`, accessGate(col, "read"), (c) => mediaController.find(c));
2304
+ app.get(`${prefix}/media/:filename{.+$}`, (c) => mediaController.serve(c));
2305
+ app.post(`${prefix}/media`, accessGate(col, "create"), (c) => mediaController.upload(c));
2306
+ app.delete(`${prefix}/media/:id`, accessGate(col, "delete"), (c) => mediaController.delete(c));
2307
+ }
2308
+ }
2309
+ for (const collection of config.collections) {
2310
+ if (!collection.auth) continue;
2311
+ const path = `/api/collections/${collection.slug}`;
2312
+ const authController = new AuthController(collection);
2313
+ app.post(`${path}/login`, (c) => authController.login(c));
2314
+ app.post(`${path}/logout`, (c) => authController.logout(c));
2315
+ app.get(`${path}/init`, (c) => authController.init(c));
2316
+ app.post(`${path}/first-user`, (c) => authController.registerFirstUser(c));
2317
+ app.get(`${path}/me`, requireAuth(), (c) => authController.me(c));
2318
+ app.post(`${path}/refresh-token`, requireAuth(), (c) => authController.refreshToken(c));
2319
+ app.post(`${path}/forgot-password`, (c) => authController.forgotPassword(c));
2320
+ app.post(`${path}/reset-password`, (c) => authController.resetPassword(c));
2321
+ app.post(`${path}/invite`, requireAuth(), (c) => authController.invite(c));
2322
+ app.post(`${path}/accept-invite`, (c) => authController.acceptInvite(c));
2323
+ }
2324
+ for (const collection of config.collections) {
2325
+ const path = `/api/collections/${collection.slug}`;
2326
+ const controller = new CollectionController(collection);
2327
+ app.get(path, accessGate(collection, "read"), (c) => controller.find(c));
2328
+ app.post(path, accessGate(collection, "create"), (c) => controller.create(c));
2329
+ app.post(`${path}/media`, accessGate(collection, "create"), (c) => controller.create(c));
2330
+ app.delete(`${path}/delete-many`, accessGate(collection, "delete"), (c) => controller.deleteMany(c));
2331
+ app.get(`${path}/:id`, accessGate(collection, "read"), (c) => controller.findOne(c));
2332
+ app.patch(`${path}/:id`, accessGate(collection, "update"), (c) => controller.update(c));
2333
+ app.delete(`${path}/:id`, accessGate(collection, "delete"), (c) => controller.delete(c));
2334
+ app.post(`${path}/seed`, (c) => controller.seed(c));
2335
+ if (collection.auth) {
2336
+ app.post(`${path}/:id/change-password`, requireAuth(), (c) => controller.changePassword(c));
2337
+ }
2338
+ }
2339
+ for (const global of config.globals) {
2340
+ const path = `/api/globals/${global.slug}`;
2341
+ const controller = new GlobalController(global);
2342
+ app.get(path, accessGate(global, "read"), (c) => controller.get(c));
2343
+ app.patch(path, accessGate(global, "update"), (c) => controller.update(c));
2344
+ app.post(`${path}/seed`, (c) => controller.seed(c));
2345
+ }
2346
+ const previewController = new PreviewController();
2347
+ app.post("/api/preview-token", requireAuth(), (c) => previewController.createToken(c));
2348
+ app.get("/api/preview-data", (c) => previewController.getData(c));
2349
+ app.all("/api/collections/:slug/:id?", async (c) => {
2350
+ const slug = c.req.param("slug");
2351
+ const id = c.req.param("id");
2352
+ const siteId = c.req.header("X-Site-Id") || c.get("siteId");
2353
+ const config2 = c.get("config");
2354
+ if (config2.collections.some((col) => col.slug === slug)) {
2355
+ return c.json({ message: "Method Not Allowed" }, 405);
2356
+ }
2357
+ if (config2.onSchemaFetch && siteId) {
2358
+ const dynamic = await config2.onSchemaFetch(siteId);
2359
+ let collection = dynamic.collections?.find((col) => col.slug === slug);
2360
+ if (!collection && slug === "media") {
2361
+ collection = {
2362
+ slug: "media",
2363
+ labels: { singular: "Media", plural: "Media" },
2364
+ upload: true,
2365
+ fields: []
2366
+ };
2367
+ }
2368
+ if (collection) {
2369
+ if (collection.auth && id) {
2370
+ const authController = new AuthController(collection);
2371
+ const method2 = c.req.method;
2372
+ if (method2 === "POST" && id === "login") return authController.login(c);
2373
+ if (method2 === "POST" && id === "logout") return authController.logout(c);
2374
+ if (method2 === "GET" && id === "me") return authController.me(c);
2375
+ if (method2 === "POST" && id === "refresh-token") return authController.refreshToken(c);
2376
+ if (method2 === "POST" && id === "forgot-password") return authController.forgotPassword(c);
2377
+ if (method2 === "POST" && id === "reset-password") return authController.resetPassword(c);
2378
+ }
2379
+ const controller = new CollectionController(collection);
2380
+ const method = c.req.method;
2381
+ if (id) {
2382
+ if (method === "GET") return controller.findOne(c);
2383
+ if (method === "PATCH") return controller.update(c);
2384
+ if (method === "DELETE" && id === "delete-many") return controller.deleteMany(c);
2385
+ if (method === "DELETE") return controller.delete(c);
2386
+ if (method === "POST" && id === "media") return controller.create(c);
2387
+ if (method === "POST" && id === "seed") return controller.seed(c);
2388
+ } else {
2389
+ if (method === "GET") return controller.find(c);
2390
+ if (method === "POST") return controller.create(c);
2391
+ }
2392
+ }
2393
+ }
2394
+ return c.json({ message: `Collection "${slug}" not found` }, 404);
2395
+ });
2396
+ app.all("/api/globals/:slug", async (c) => {
2397
+ const slug = c.req.param("slug");
2398
+ const siteId = c.req.header("X-Site-Id") || c.get("siteId");
2399
+ const config2 = c.get("config");
2400
+ if (config2.globals.some((glb) => glb.slug === slug)) {
2401
+ return c.json({ message: "Method Not Allowed" }, 405);
2402
+ }
2403
+ if (config2.onSchemaFetch && siteId) {
2404
+ const dynamic = await config2.onSchemaFetch(siteId);
2405
+ const global = dynamic.globals?.find((glb) => glb.slug === slug);
2406
+ if (global) {
2407
+ const controller = new GlobalController(global);
2408
+ if (c.req.method === "GET") return controller.get(c);
2409
+ if (c.req.method === "PATCH") return controller.update(c);
2410
+ }
2411
+ }
2412
+ return c.json({ message: `Global "${slug}" not found` }, 404);
2413
+ });
2414
+ }
2415
+
2416
+ // src/app.ts
2417
+ import { Hono } from "hono";
2418
+ import { cors } from "hono/cors";
2419
+ import { requestId } from "hono/request-id";
2420
+ async function createDyrectedApp(rawConfig) {
2421
+ const config = normalizeConfig(rawConfig);
2422
+ const app = new Hono();
2423
+ if (config.db?.sync) {
2424
+ await config.db.sync(config.collections, config.globals);
2425
+ }
2426
+ app.use("*", requestId());
2427
+ app.use("*", optionalAuth());
2428
+ app.use("*", async (c, next) => {
2429
+ const start = Date.now();
2430
+ await next();
2431
+ const ms = Date.now() - start;
2432
+ console.log(`[dyrected/api] ${c.req.method} ${c.req.path} ${c.res.status} - ${ms}ms`);
2433
+ });
2434
+ app.use("*", cors());
2435
+ app.use("*", async (c, next) => {
2436
+ c.set("config", config);
2437
+ if (!c.get("siteId")) {
2438
+ c.set("siteId", "default");
2439
+ }
2440
+ await next();
2441
+ });
2442
+ app.get("/health", (c) => c.json({ status: "ok", version: "0.0.1" }));
2443
+ app.get("/routes", (c) => {
2444
+ const routes = app.routes.map((r) => ({ method: r.method, path: r.path }));
2445
+ return c.json({ routes });
2446
+ });
2447
+ app.onError((err, c) => {
2448
+ console.error(`[dyrected/core] Uncaught Error:`, err);
2449
+ return c.json({
2450
+ message: err.message || "Internal Server Error",
2451
+ stack: process.env.NODE_ENV === "development" ? err.stack : void 0
2452
+ }, 500);
2453
+ });
2454
+ registerRoutes(app, config);
2455
+ return app;
2456
+ }
2457
+
2458
+ export {
2459
+ normalizeConfig,
2460
+ runCollectionHooks,
2461
+ executeFieldBeforeChange,
2462
+ executeFieldAfterRead,
2463
+ CollectionController,
2464
+ GlobalController,
2465
+ MediaController,
2466
+ AuthController,
2467
+ PreviewController,
2468
+ registerRoutes,
2469
+ createDyrectedApp
2470
+ };