@dyrected/core 2.5.58 → 2.5.60

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.
@@ -0,0 +1,1580 @@
1
+ import { icons } from 'lucide-react';
2
+
3
+ /**
4
+ * Minimum HTTP request context passed to every server-side hook and resolver.
5
+ *
6
+ * The full Web Standard `Request` is available as `raw` when you need it, but
7
+ * most hooks only need `query` (URL search parameters).
8
+ */
9
+ interface HookRequestContext {
10
+ /** Parsed URL query-string parameters, e.g. `{ page: '2', search: 'hello' }`. */
11
+ query: Record<string, string>;
12
+ /** Incoming HTTP headers, lowercased. */
13
+ headers: Record<string, string>;
14
+ /** The raw Web Standard `Request` object. Useful for streaming or advanced header inspection. */
15
+ raw?: Request;
16
+ }
17
+ /**
18
+ * Base shape of an authenticated user as decoded from the JWT.
19
+ *
20
+ * The actual shape will include every field on your auth collection — this
21
+ * interface only guarantees the properties that Dyrected always stamps on the
22
+ * token. Extend it in your own codebase for stronger typing:
23
+ *
24
+ * @example
25
+ * declare module '@dyrected/core' {
26
+ * interface AuthenticatedUser {
27
+ * role: 'admin' | 'editor'
28
+ * organizationId: string
29
+ * }
30
+ * }
31
+ */
32
+ interface AuthenticatedUser {
33
+ /** The user's document ID in the database. */
34
+ sub: string;
35
+ /** The user's email address. */
36
+ email?: string;
37
+ /** Slug of the collection this user was authenticated against. */
38
+ collection: string;
39
+ /** Array of role strings, if your auth collection has a `roles` field. */
40
+ roles?: string[];
41
+ /** Any additional fields from the auth collection document. */
42
+ [key: string]: unknown;
43
+ }
44
+
45
+ interface AccessFunctionArgs<TDoc extends object = Record<string, unknown>, TUser extends AuthenticatedUser = AuthenticatedUser> {
46
+ user: TUser | undefined;
47
+ doc?: TDoc;
48
+ data?: Partial<TDoc>;
49
+ req: HookRequestContext;
50
+ }
51
+ interface NamedAccessPolicy<TDoc extends object = Record<string, unknown>> {
52
+ policy: string;
53
+ params?: Record<string, unknown>;
54
+ }
55
+ type AccessResult = boolean | Record<string, unknown>;
56
+ /**
57
+ * A function that determines whether the current user can perform an operation.
58
+ *
59
+ * Return `true` to allow, `false` to deny.
60
+ * Return a `where`-style object to allow access only to matching documents
61
+ * (useful for multi-tenant setups where users can only see their own data).
62
+ *
63
+ * Can also be expressed as a Jexl expression **string** for simple role checks
64
+ * that need to be serialised (e.g. stored in the database or sent to the Admin UI).
65
+ *
66
+ * @template TDoc The shape of the collection's document.
67
+ *
68
+ * @example
69
+ * // Simple role check
70
+ * access: {
71
+ * delete: ({ user }) => user?.roles?.includes('admin') ?? false,
72
+ * }
73
+ *
74
+ * @example
75
+ * // Row-level: users can only read their own documents
76
+ * access: {
77
+ * read: ({ user }) => ({ owner: { equals: user?.sub } }),
78
+ * }
79
+ *
80
+ * @example
81
+ * // Jexl string — evaluated server-side
82
+ * access: {
83
+ * update: "user.roles contains 'editor'",
84
+ * }
85
+ */
86
+ type AccessFunction<TDoc extends object = Record<string, unknown>, TUser extends AuthenticatedUser = AuthenticatedUser> = (args: AccessFunctionArgs<TDoc, TUser>) => AccessResult | Promise<AccessResult>;
87
+ type AccessRule<TDoc extends object = Record<string, unknown>, TUser extends AuthenticatedUser = AuthenticatedUser> = boolean | string | AccessFunction<TDoc, TUser> | NamedAccessPolicy<TDoc>;
88
+ type AccessPolicyResolver<TDoc extends object = Record<string, unknown>, TUser extends AuthenticatedUser = AuthenticatedUser> = (args: AccessFunctionArgs<TDoc, TUser> & {
89
+ params?: Record<string, unknown>;
90
+ }) => AccessResult | Promise<AccessResult>;
91
+
92
+ /**
93
+ * The minimum shape of every document returned by the database layer.
94
+ *
95
+ * All documents have an `id` field assigned by the adapter. Additional fields
96
+ * are stored as `unknown` until you narrow them with your own interface.
97
+ *
98
+ * Use this as the base when declaring your collection document types:
99
+ * ```ts
100
+ * interface Post extends BaseDocument {
101
+ * title: string
102
+ * slug: string
103
+ * }
104
+ * ```
105
+ */
106
+ interface BaseDocument {
107
+ /** The document's unique identifier, assigned by the database adapter. */
108
+ id: string;
109
+ [key: string]: any;
110
+ }
111
+ /**
112
+ * The envelope returned by collection list endpoints (`GET /api/collections/:slug`).
113
+ *
114
+ * @template T The document type.
115
+ */
116
+ interface PaginatedResult<T = Record<string, any>> {
117
+ /** The documents on the current page. */
118
+ docs: T[];
119
+ /** Total number of documents matching the query (across all pages). */
120
+ total: number;
121
+ /** Maximum number of documents per page as requested. */
122
+ limit: number;
123
+ /** The current page number (1-indexed). */
124
+ page: number;
125
+ /** Total number of pages given the current `limit`. */
126
+ totalPages: number;
127
+ /** Whether a next page exists. */
128
+ hasNextPage: boolean;
129
+ /** Whether a previous page exists. */
130
+ hasPrevPage: boolean;
131
+ }
132
+ /**
133
+ * Metadata returned after a file is uploaded and stored.
134
+ * Stored on the document in upload collections.
135
+ */
136
+ interface FileData {
137
+ filename: string;
138
+ filesize?: number;
139
+ mimeType: string;
140
+ /** Public URL of the stored file. */
141
+ url: string;
142
+ width?: number;
143
+ height?: number;
144
+ focalPoint?: {
145
+ x: number;
146
+ y: number;
147
+ };
148
+ /** Base64-encoded BlurHash string for progressive image loading. */
149
+ blurhash?: string;
150
+ /** `'upload'` for server-stored files; `'external'` for provider-managed files. */
151
+ type?: "upload" | "external";
152
+ provider?: string;
153
+ provider_metadata?: unknown;
154
+ [key: string]: unknown;
155
+ }
156
+
157
+ /** A valid icon component name from the Lucide icon set bundled with Dyrected Admin. */
158
+ type AdminIconName = keyof typeof icons;
159
+ /** Ordered custom component keys rendered around the built-in Admin dashboard. */
160
+ interface AdminDashboardComponentSlots {
161
+ beforeDashboard?: string[];
162
+ afterDashboard?: string[];
163
+ }
164
+ /** Ordered custom component keys rendered around a collection's list content. */
165
+ interface CollectionListComponentSlots {
166
+ beforeList?: string[];
167
+ beforeListTable?: string[];
168
+ afterListTable?: string[];
169
+ afterList?: string[];
170
+ }
171
+ /**
172
+ * Branding and metadata options for the Dyrected Admin UI.
173
+ *
174
+ * @example
175
+ * admin: {
176
+ * branding: {
177
+ * logo: '/logo.svg',
178
+ * primaryColor: '#6366f1',
179
+ * },
180
+ * meta: {
181
+ * titleSuffix: '- My App',
182
+ * },
183
+ * }
184
+ */
185
+ interface AdminConfig {
186
+ /** Custom component slots around the built-in dashboard. */
187
+ components?: AdminDashboardComponentSlots;
188
+ branding?: {
189
+ /** Full logo image shown in the expanded sidebar. URL or imported image asset. */
190
+ logo?: string;
191
+ /** Compact logo mark used in the collapsed sidebar state. */
192
+ logoMark?: string;
193
+ /** Text alternative or addition to the logo image. */
194
+ logoText?: string;
195
+ /**
196
+ * Primary accent colour as any CSS colour value.
197
+ * @example '#6366f1'
198
+ * @example 'hsl(240 50% 60%)'
199
+ */
200
+ primaryColor?: string;
201
+ /** Browser tab favicon URL. */
202
+ favicon?: string;
203
+ /** Font family for body and UI text. Must be loaded separately. */
204
+ fontSans?: string;
205
+ /** Font family for headings. Must be loaded separately. */
206
+ fontSerif?: string;
207
+ };
208
+ meta?: {
209
+ /**
210
+ * String appended to every Admin page's `<title>`.
211
+ * @default '- Dyrected'
212
+ */
213
+ titleSuffix?: string;
214
+ };
215
+ /**
216
+ * The canonical/base URL of the frontend website for links and iframe live previews.
217
+ */
218
+ siteUrl?: string;
219
+ }
220
+
221
+ /**
222
+ * @deprecated Use {@link FieldBeforeChangeHook} or `FieldAfterReadHook` instead.
223
+ * This alias remains for backwards compatibility.
224
+ */
225
+ type FieldHook<TDoc extends object = Record<string, unknown>, TValue = unknown> = FieldBeforeChangeHook<TValue, TDoc>;
226
+ /**
227
+ * Runs before Dyrected queries the database for a list or single-document fetch.
228
+ *
229
+ * Return a new `where` query object to override or extend the current filter.
230
+ * Return `undefined` (or nothing) to leave the query unchanged.
231
+ */
232
+ type CollectionBeforeReadHook = (args: {
233
+ req: HookRequestContext;
234
+ query?: Record<string, unknown>;
235
+ user?: AuthenticatedUser;
236
+ db: ReadonlyDatabaseAdapter;
237
+ }) => Record<string, unknown> | void | Promise<Record<string, unknown> | void>;
238
+ /**
239
+ * Runs after a document (or list of documents) is fetched from the database,
240
+ * before the response is sent to the client.
241
+ */
242
+ type CollectionAfterReadHook<TDoc extends object = Record<string, unknown>> = (args: {
243
+ doc: TDoc;
244
+ req: HookRequestContext;
245
+ user?: AuthenticatedUser;
246
+ db: ReadonlyDatabaseAdapter;
247
+ }) => TDoc | Promise<TDoc>;
248
+ /**
249
+ * Runs **before** a document is created or updated in the database.
250
+ */
251
+ type CollectionBeforeChangeHook<TDoc extends object = Record<string, unknown>> = (args: {
252
+ data: Partial<TDoc>;
253
+ doc?: TDoc;
254
+ req: HookRequestContext;
255
+ user?: AuthenticatedUser;
256
+ operation: "create" | "update";
257
+ db: ReadonlyDatabaseAdapter;
258
+ }) => Partial<TDoc> | void | Promise<Partial<TDoc> | void>;
259
+ /**
260
+ * Runs **after** a document is created or updated in the database.
261
+ */
262
+ type CollectionAfterChangeHook<TDoc extends object = Record<string, unknown>> = (args: {
263
+ doc: TDoc;
264
+ previousDoc?: TDoc;
265
+ req: HookRequestContext;
266
+ user?: AuthenticatedUser;
267
+ operation: "create" | "update";
268
+ db: DatabaseAdapter;
269
+ }) => void | Promise<void>;
270
+ /**
271
+ * Runs **before** a document is deleted from the database.
272
+ */
273
+ type CollectionBeforeDeleteHook<TDoc extends object = Record<string, unknown>> = (args: {
274
+ id: string;
275
+ doc: TDoc;
276
+ req: HookRequestContext;
277
+ user?: AuthenticatedUser;
278
+ db: ReadonlyDatabaseAdapter;
279
+ }) => void | Promise<void>;
280
+ /**
281
+ * Runs **after** a document has been deleted from the database.
282
+ */
283
+ type CollectionAfterDeleteHook<TDoc extends object = Record<string, unknown>> = (args: {
284
+ id: string;
285
+ doc: TDoc;
286
+ req: HookRequestContext;
287
+ user?: AuthenticatedUser;
288
+ db: DatabaseAdapter;
289
+ }) => void | Promise<void>;
290
+ /** @see {@link CollectionBeforeReadHook} */
291
+ type GlobalBeforeReadHook = CollectionBeforeReadHook;
292
+ /**
293
+ * Runs after the global document is fetched, before the response is sent.
294
+ */
295
+ type GlobalAfterReadHook<TDoc extends object = Record<string, unknown>> = (args: {
296
+ doc: TDoc;
297
+ req: HookRequestContext;
298
+ user?: AuthenticatedUser;
299
+ db: ReadonlyDatabaseAdapter;
300
+ }) => TDoc | Promise<TDoc>;
301
+ /**
302
+ * Runs before the global document is updated.
303
+ * Operation is always `'update'` (globals cannot be created or deleted).
304
+ */
305
+ type GlobalBeforeChangeHook<TDoc extends object = Record<string, unknown>> = (args: {
306
+ data: Partial<TDoc>;
307
+ doc?: TDoc;
308
+ req: HookRequestContext;
309
+ user?: AuthenticatedUser;
310
+ operation: "update";
311
+ db: ReadonlyDatabaseAdapter;
312
+ }) => Partial<TDoc> | void | Promise<Partial<TDoc> | void>;
313
+ /**
314
+ * Runs after the global document is updated. Side-effects only.
315
+ */
316
+ type GlobalAfterChangeHook<TDoc extends object = Record<string, unknown>> = (args: {
317
+ doc: TDoc;
318
+ previousDoc?: TDoc;
319
+ req: HookRequestContext;
320
+ user?: AuthenticatedUser;
321
+ operation: "update";
322
+ db: DatabaseAdapter;
323
+ }) => void | Promise<void>;
324
+ /**
325
+ * @deprecated Use the specific hook types instead:
326
+ * `CollectionBeforeChangeHook`, `CollectionAfterReadHook`, etc.
327
+ *
328
+ * This broad type remains for backwards compatibility with the internal hook runner.
329
+ */
330
+ type HookFunction<TDoc extends object = Record<string, unknown>> = (args: {
331
+ data?: Partial<TDoc>;
332
+ doc?: TDoc;
333
+ user?: AuthenticatedUser;
334
+ req?: HookRequestContext;
335
+ operation?: "create" | "update" | "delete";
336
+ db?: DatabaseAdapter;
337
+ [key: string]: unknown;
338
+ }) => unknown | Promise<unknown>;
339
+
340
+ declare const LIFECYCLE_EVENT_NAMES: readonly ["revision.created", "workflow.transitioned", "entry.published", "entry.unpublished"];
341
+ type LifecycleEventName = (typeof LIFECYCLE_EVENT_NAMES)[number];
342
+ interface WorkflowState {
343
+ /** Stable machine-readable state key. */
344
+ name: string;
345
+ /** Label rendered in the Admin UI. */
346
+ label: string;
347
+ /** Marks the state whose revision is visible to public readers. */
348
+ published?: boolean;
349
+ /** Optional visual tone used by the Admin UI. */
350
+ color?: "neutral" | "warning" | "success" | "danger" | "info";
351
+ }
352
+ interface WorkflowTransition {
353
+ /** Stable transition key used by the REST and SDK APIs. */
354
+ name: string;
355
+ label: string;
356
+ from: string | string[];
357
+ to: string;
358
+ /** Every listed capability is required. */
359
+ requiredCapabilities?: string[];
360
+ /** Require a non-empty comment when performing the transition. */
361
+ requireComment?: boolean;
362
+ /** Remove the public snapshot after this transition commits. */
363
+ unpublish?: boolean;
364
+ }
365
+ interface WorkflowRole {
366
+ /** Existing user role value, for example `editor` or `publisher`. */
367
+ role: string;
368
+ capabilities: string[];
369
+ }
370
+ interface WorkflowConfig<TDoc extends object = Record<string, unknown>> {
371
+ initialState: string;
372
+ /** State used for a new working revision created from published content. */
373
+ draftState?: string;
374
+ states: WorkflowState[];
375
+ transitions: WorkflowTransition[];
376
+ /** Maps values in `user.roles` to workflow capabilities. */
377
+ roles?: WorkflowRole[];
378
+ hooks?: {
379
+ beforeTransition?: CollectionBeforeTransitionHook<TDoc>[];
380
+ afterTransition?: CollectionAfterTransitionHook<TDoc>[];
381
+ };
382
+ }
383
+ interface WorkflowMetadata {
384
+ state: string;
385
+ revision: number;
386
+ publishedRevision?: number;
387
+ publishedAt?: string;
388
+ publishedBy?: string;
389
+ /** Transitions currently allowed for the requesting user. Response-only. */
390
+ availableTransitions?: string[];
391
+ }
392
+ interface WorkflowTransitionContext<TDoc extends object = Record<string, unknown>> {
393
+ transition: WorkflowTransition;
394
+ from: string;
395
+ to: string;
396
+ doc: TDoc;
397
+ user?: AuthenticatedUser;
398
+ comment?: string;
399
+ req: HookRequestContext;
400
+ db: DatabaseAdapter;
401
+ }
402
+ type CollectionBeforeTransitionHook<TDoc extends object = Record<string, unknown>> = (args: WorkflowTransitionContext<TDoc>) => void | Promise<void>;
403
+ type CollectionAfterTransitionHook<TDoc extends object = Record<string, unknown>> = (args: WorkflowTransitionContext<TDoc> & {
404
+ event: LifecycleEvent;
405
+ }) => void | Promise<void>;
406
+ interface LifecycleEvent<TPayload = Record<string, unknown>> {
407
+ id: string;
408
+ name: LifecycleEventName;
409
+ collection: string;
410
+ documentId: string;
411
+ occurredAt: string;
412
+ actorId?: string;
413
+ payload: TPayload;
414
+ attempts: number;
415
+ status: "pending" | "processing" | "delivered" | "failed";
416
+ nextAttemptAt?: string;
417
+ deliveredAt?: string;
418
+ lastError?: string;
419
+ }
420
+ type LifecycleEventHandler = (event: LifecycleEvent) => void | Promise<void>;
421
+
422
+ /**
423
+ * Use this contract when you want the exact shape of a collection config.
424
+ *
425
+ * Most collection work comes down to a small set of top-level options: giving
426
+ * the collection a stable slug, defining its fields, deciding how it should
427
+ * appear in the Admin UI, and choosing whether it also handles access, hooks,
428
+ * auth, uploads, workflows, or other optional behavior.
429
+ *
430
+ * Pass your document's TypeScript type as the generic parameter `TDoc` to get
431
+ * fully typed hooks and access functions.
432
+ *
433
+ * @example
434
+ * ```ts
435
+ * interface Post {
436
+ * id: string
437
+ * title: string
438
+ * slug: string
439
+ * status: 'draft' | 'published'
440
+ * publishedAt?: string
441
+ * }
442
+ *
443
+ * export const Posts = defineCollection<Post>({
444
+ * slug: 'posts',
445
+ * hooks: {
446
+ * beforeChange: [({ data, operation }) => {
447
+ * // `data` is typed as Partial<Post>
448
+ * if (operation === 'create') return { ...data, status: 'draft' }
449
+ * return data
450
+ * }],
451
+ * afterChange: [({ doc, previousDoc }) => {
452
+ * // `doc` and `previousDoc` are typed as Post
453
+ * if (doc.status !== previousDoc?.status) notifySubscribers(doc)
454
+ * }],
455
+ * },
456
+ * fields: [...],
457
+ * })
458
+ * ```
459
+ *
460
+ * @see {@link https://dyrected.com/new-docs/basics/configuration/collections Collections documentation}
461
+ * @template TDoc The TypeScript shape of a document in this collection.
462
+ * Defaults to `Record<string, unknown>` for untyped usage.
463
+ */
464
+ interface CollectionConfig<TDoc extends object = Record<string, unknown>> {
465
+ /**
466
+ * Unique identifier for this collection.
467
+ *
468
+ * Dyrected uses the slug for API routes, SDK calls, Admin URLs, and as the
469
+ * underlying database table or collection name. Treat it as part of the
470
+ * long-term data contract rather than a cosmetic label.
471
+ *
472
+ * Use kebab-case, for example `'blog-posts'`, `'team-members'`, or
473
+ * `'contact-submissions'`.
474
+ */
475
+ slug: string;
476
+ /**
477
+ * Restricts this collection to one specific site in a multi-tenant setup.
478
+ *
479
+ * Use this when the collection should belong to a single site rather than
480
+ * the whole installation. When set, only requests bearing a matching
481
+ * `X-Site-Id` header can access it.
482
+ */
483
+ siteId?: string;
484
+ /**
485
+ * If `true`, this collection is shared across all sites in a multi-tenant
486
+ * setup and accessible regardless of the `X-Site-Id` header.
487
+ *
488
+ * Use this for content that should stay common across sites, such as shared
489
+ * taxonomies, reusable assets, or centrally managed reference data.
490
+ */
491
+ shared?: boolean;
492
+ /**
493
+ * Human-readable names for documents in this collection, shown in the Admin UI.
494
+ *
495
+ * Use this when the slug is technical or when you want the dashboard to read
496
+ * more naturally. For example, `slug: 'people'` might use
497
+ * `labels: { singular: 'Person', plural: 'People' }`.
498
+ *
499
+ * @see {@link https://dyrected.com/new-docs/basics/configuration/collections#labels Collections labels}
500
+ */
501
+ labels?: {
502
+ singular: string;
503
+ plural: string;
504
+ };
505
+ /**
506
+ * If `true`, this collection is an auth collection. It gains
507
+ * `POST /api/collections/:slug/login` and `POST /api/collections/:slug/logout`
508
+ * endpoints, and documents are expected to have a `password` field.
509
+ *
510
+ * Turn this on when each document should behave like an account that can log
511
+ * in, hold credentials, and participate in user flows. Typical examples are
512
+ * `users`, `admins`, `members`, or `customers`.
513
+ *
514
+ * @see {@link https://dyrected.com/new-docs/features/authentication/overview Authentication overview}
515
+ */
516
+ auth?: boolean;
517
+ /**
518
+ * If `true` or a config object, this collection supports file uploads.
519
+ * Documents gain file-related fields (`url`, `filename`, `mimeType`, etc.)
520
+ * and the create endpoint accepts `multipart/form-data`.
521
+ *
522
+ * Turn this on when each document in the collection should represent a
523
+ * stored file, such as an image, PDF, video, or downloadable asset.
524
+ *
525
+ * @see {@link https://dyrected.com/new-docs/features/upload/overview Upload overview}
526
+ */
527
+ upload?: boolean | UploadConfig;
528
+ /**
529
+ * Field definitions that make up the document schema for this collection.
530
+ *
531
+ * This is the main schema contract for every document in the collection. It
532
+ * decides what editors can fill in, how data is validated, how records are
533
+ * stored, and what the API and SDK return.
534
+ *
535
+ * In practice, fields are where you model the actual content structure of the
536
+ * collection: simple values such as text and dates, relationships to other
537
+ * collections, nested objects and arrays, and flexible `blocks` fields for
538
+ * reusable page sections or long-form layouts.
539
+ *
540
+ * @see {@link https://dyrected.com/new-docs/basics/fields/overview Fields overview}
541
+ * @see {@link https://dyrected.com/new-docs/basics/fields/blocks Blocks and page sections}
542
+ */
543
+ fields: Field[];
544
+ /**
545
+ * If `true`, Dyrected automatically adds the built-in system fields
546
+ * `createdAt`, `updatedAt`, `createdBy`, and `updatedBy` to every document.
547
+ * Defaults to `true`.
548
+ */
549
+ timestamps?: boolean;
550
+ /**
551
+ * Initial documents to seed into this collection the first time it is
552
+ * fetched and found to be empty.
553
+ *
554
+ * Use this for starter records, demo content, or sensible defaults that
555
+ * should appear automatically before editors create anything themselves.
556
+ */
557
+ initialData?: Partial<TDoc>[];
558
+ /**
559
+ * If `true`, every create, update, and delete operation on this collection
560
+ * is logged to the `__audit` collection with before/after snapshots and the
561
+ * acting user's identity.
562
+ *
563
+ * Turn this on when you need accountability around changes, such as knowing
564
+ * who changed what, inspecting before-and-after state, or supporting
565
+ * compliance and operational review.
566
+ */
567
+ audit?: boolean;
568
+ /**
569
+ * Optional state-machine workflow for this collection. Workflow-enabled
570
+ * entries keep an editable working revision and an independent public
571
+ * snapshot, so editing published content never changes the live response.
572
+ *
573
+ * Use this when content moves through stages such as draft, review, and
574
+ * published, or when teams need an approval process before changes go live.
575
+ */
576
+ workflow?: WorkflowConfig<TDoc>;
577
+ /**
578
+ * Collection-level access control.
579
+ *
580
+ * Each key is an operation; the value can be a function, a Jexl string, a
581
+ * boolean, or a named policy reference. Returning `true` allows access and
582
+ * `false` denies it. Returning a `where`-style object grants access only to
583
+ * matching documents.
584
+ *
585
+ * @example
586
+ * access: {
587
+ * read: () => true,
588
+ * create: ({ user }) => !!user,
589
+ * update: ({ user }) => user?.roles?.includes('editor') ?? false,
590
+ * delete: ({ user }) => user?.roles?.includes('admin') ?? false,
591
+ * }
592
+ *
593
+ * @see {@link https://dyrected.com/new-docs/basics/access-control/overview Access control overview}
594
+ */
595
+ access?: {
596
+ read?: AccessRule<TDoc>;
597
+ create?: AccessRule<TDoc>;
598
+ update?: AccessRule<TDoc>;
599
+ delete?: AccessRule<TDoc>;
600
+ /**
601
+ * Controls who can read this collection's audit log (`GET /:slug/__audit`),
602
+ * for collections with `audit` enabled. Falls back to the `read` rule when
603
+ * omitted, so the audit trail is visible to whoever can read the documents.
604
+ * Set it explicitly to gate the audit log separately — for example, admins
605
+ * only, even on a collection anyone can read.
606
+ */
607
+ readAudit?: AccessRule<TDoc>;
608
+ };
609
+ /**
610
+ * Collection-level lifecycle hooks.
611
+ *
612
+ * Hooks run in the order they appear in the array. The return value of each
613
+ * hook is passed as the input to the next. Throwing inside any hook aborts
614
+ * the operation and returns a `500` error.
615
+ *
616
+ * See the Hooks reference for the full lifecycle diagram.
617
+ *
618
+ * @see {@link https://dyrected.com/new-docs/basics/hooks/overview Hooks overview}
619
+ * @see {@link https://dyrected.com/new-docs/basics/hooks/collections Collection hooks}
620
+ */
621
+ hooks?: {
622
+ /**
623
+ * Runs before the database is queried. Return a modified `where` object
624
+ * to override the query filter.
625
+ */
626
+ beforeRead?: CollectionBeforeReadHook[];
627
+ /**
628
+ * Runs after documents are fetched. Return a modified doc to change what
629
+ * the client receives. Runs on every document in a list response.
630
+ */
631
+ afterRead?: CollectionAfterReadHook<TDoc>[];
632
+ /**
633
+ * Runs before create or update. Return modified data to change what is
634
+ * written to the database. Throw to abort the write entirely.
635
+ */
636
+ beforeChange?: CollectionBeforeChangeHook<TDoc>[];
637
+ /**
638
+ * Runs after create or update is committed. For side-effects only:
639
+ * webhooks, cache busting, and notifications. Return value is ignored.
640
+ *
641
+ * Errors are isolated: caught, logged, and discarded so a failing
642
+ * side-effect never turns a successful write into an HTTP 500.
643
+ * See `CollectionAfterChangeHook` for await-vs-fire-and-forget guidance.
644
+ */
645
+ afterChange?: CollectionAfterChangeHook<TDoc>[];
646
+ /** Runs before a document is deleted. Throw to cancel the deletion. */
647
+ beforeDelete?: CollectionBeforeDeleteHook<TDoc>[];
648
+ /**
649
+ * Runs after a document has been deleted. For cleanup side-effects only.
650
+ *
651
+ * Errors are isolated: caught, logged, and discarded. The deletion is
652
+ * already committed and will not be undone.
653
+ */
654
+ afterDelete?: CollectionAfterDeleteHook<TDoc>[];
655
+ };
656
+ /**
657
+ * Admin UI configuration for this collection.
658
+ *
659
+ * @see {@link https://dyrected.com/new-docs/basics/configuration/collections#admin-options Admin options}
660
+ */
661
+ admin?: {
662
+ /**
663
+ * Lucide icon displayed beside this collection in the Admin sidebar.
664
+ * Uses Lucide component names, e.g. `'Newspaper'` or `'ShoppingBag'`.
665
+ */
666
+ icon?: AdminIconName;
667
+ /** Custom component slots for this collection's list view. */
668
+ components?: CollectionListComponentSlots;
669
+ /**
670
+ * The field name used as the document's display title in the Admin list
671
+ * view and breadcrumbs. Defaults to `'title'` if the field exists.
672
+ */
673
+ useAsTitle?: string;
674
+ /**
675
+ * Field names to show as columns in the Admin list view.
676
+ * Defaults to a sensible set of the first few non-structural fields.
677
+ */
678
+ defaultColumns?: string[];
679
+ /**
680
+ * Groups this collection under a named section in the Admin sidebar.
681
+ * Collections with the same `group` are visually grouped together.
682
+ */
683
+ group?: string;
684
+ /** If `true`, this collection is not shown in the Admin UI sidebar. */
685
+ hidden?: boolean;
686
+ /** If `false`, disables the filter UI entirely for this collection. Defaults to `true`. */
687
+ filterable?: boolean;
688
+ /**
689
+ * URL to open in the Live Preview pane when editing a document.
690
+ *
691
+ * Pass a Jexl string to keep the config serializable, for example
692
+ * `'slug == "home" ? "/" : "/blog/" + slug'`. This is usually the best
693
+ * default, especially when the schema needs to stay portable across
694
+ * environments such as Dyrected Cloud.
695
+ *
696
+ * Pass a function when you need custom runtime logic in a self-hosted
697
+ * project.
698
+ *
699
+ * @example
700
+ * previewUrl: 'slug == "home" ? "/" : "/blog/" + slug'
701
+ *
702
+ * @example
703
+ * previewUrl: (doc) => `https://mysite.com/blog/${doc.slug}`
704
+ */
705
+ previewUrl?: string | ((doc: TDoc, opts: {
706
+ locale?: string;
707
+ }) => string | null);
708
+ /**
709
+ * How the Live Preview pane communicates with the frontend.
710
+ * - `postMessage` sends a `postMessage` with the current doc data.
711
+ * - `token` passes a short-lived preview token as a query parameter.
712
+ */
713
+ previewMode?: "postMessage" | "token";
714
+ /**
715
+ * Frontend URL pattern for this collection, used by `url` fields to
716
+ * resolve internal links. Use `{fieldName}` placeholders.
717
+ *
718
+ * This is a plain route pattern string, not a Jexl expression.
719
+ *
720
+ * @example
721
+ * urlPattern: '/blog/{slug}' // /blog/my-post
722
+ * urlPattern: '/{slug}' // /about
723
+ */
724
+ urlPattern?: string;
725
+ };
726
+ }
727
+ /**
728
+ * Defines a Dyrected global — a singleton document without pagination or IDs.
729
+ *
730
+ * Globals are ideal for site-wide settings, feature flags, or any data where
731
+ * there is always exactly one record, such as `site-settings`, `navigation`,
732
+ * or `theme`.
733
+ *
734
+ * Pass your document's TypeScript type as the generic parameter `TDoc` to get
735
+ * fully typed hooks.
736
+ *
737
+ * @example
738
+ * ```ts
739
+ * interface SiteSettings {
740
+ * siteName: string
741
+ * tagline: string
742
+ * maintenanceMode: boolean
743
+ * }
744
+ *
745
+ * export const Settings = defineGlobal<SiteSettings>({
746
+ * slug: 'site-settings',
747
+ * hooks: {
748
+ * afterChange: [({ doc }) => {
749
+ * // `doc` is typed as SiteSettings
750
+ * if (doc.maintenanceMode) alertOnCall()
751
+ * }],
752
+ * },
753
+ * fields: [...],
754
+ * })
755
+ * ```
756
+ *
757
+ * @template TDoc The TypeScript shape of this global's document.
758
+ */
759
+ interface GlobalConfig<TDoc extends object = Record<string, unknown>> {
760
+ /**
761
+ * Unique identifier for this global.
762
+ * Used as the URL segment (`/api/globals/:slug`) and the storage key.
763
+ */
764
+ slug: string;
765
+ /** Restricts this global to a specific site in a multi-tenant deployment. */
766
+ siteId?: string;
767
+ /**
768
+ * If `true`, this global is shared across all sites in a multi-tenant
769
+ * deployment.
770
+ */
771
+ shared?: boolean;
772
+ /** Human-readable label shown in the Admin UI sidebar. */
773
+ label?: string;
774
+ /** Field definitions for this global's document schema. */
775
+ fields: Field[];
776
+ /** Access control for reading and updating this global. */
777
+ access?: {
778
+ read?: AccessRule<TDoc>;
779
+ update?: AccessRule<TDoc>;
780
+ };
781
+ /**
782
+ * Global-level lifecycle hooks.
783
+ * Globals support `beforeRead`, `afterRead`, `beforeChange`, and `afterChange`.
784
+ * There are no delete hooks since globals cannot be deleted.
785
+ */
786
+ hooks?: {
787
+ beforeRead?: GlobalBeforeReadHook[];
788
+ afterRead?: GlobalAfterReadHook<TDoc>[];
789
+ beforeChange?: GlobalBeforeChangeHook<TDoc>[];
790
+ afterChange?: GlobalAfterChangeHook<TDoc>[];
791
+ };
792
+ /** Admin UI configuration for this global. */
793
+ admin?: {
794
+ /**
795
+ * Lucide icon displayed beside this global in the Admin sidebar.
796
+ * Uses Lucide component names, e.g. `'Settings2'` or `'Palette'`.
797
+ */
798
+ icon?: AdminIconName;
799
+ /** Groups this global under a named section in the Admin sidebar. */
800
+ group?: string;
801
+ /** If `true`, this global is not shown in the Admin UI sidebar. */
802
+ hidden?: boolean;
803
+ };
804
+ /**
805
+ * Initial data to seed this global with the first time it is fetched and
806
+ * found to be empty.
807
+ */
808
+ initialData?: Partial<TDoc>;
809
+ }
810
+
811
+ /**
812
+ * The interface every database adapter must implement.
813
+ *
814
+ * Dyrected ships adapters for PostgreSQL, MySQL, SQLite, and MongoDB.
815
+ * Implement this interface to connect any other database.
816
+ */
817
+ interface DatabaseAdapter {
818
+ /** Find a paginated list of documents in a collection. */
819
+ find(args: {
820
+ collection: string;
821
+ where?: Record<string, unknown>;
822
+ limit?: number;
823
+ page?: number;
824
+ sort?: string;
825
+ }): Promise<PaginatedResult>;
826
+ /** Find a single document by its ID. Returns `null` if not found. */
827
+ findOne(args: {
828
+ collection: string;
829
+ id: string;
830
+ }): Promise<BaseDocument | null>;
831
+ /** Insert a new document and return it with its generated `id`. */
832
+ create(args: {
833
+ collection: string;
834
+ data: Record<string, unknown>;
835
+ }): Promise<BaseDocument>;
836
+ /** Update a document by ID and return the updated document. */
837
+ update(args: {
838
+ collection: string;
839
+ id: string;
840
+ data: Record<string, unknown>;
841
+ }): Promise<BaseDocument>;
842
+ /** Delete a document by ID. Return value is intentionally untyped — callers do not use it. */
843
+ delete(args: {
844
+ collection: string;
845
+ id: string;
846
+ }): Promise<unknown>;
847
+ /** Fetch the singleton document for a global. Returns an empty object if not yet initialised. */
848
+ getGlobal(args: {
849
+ slug: string;
850
+ }): Promise<Record<string, unknown>>;
851
+ /** Create or replace the singleton document for a global. */
852
+ updateGlobal(args: {
853
+ slug: string;
854
+ data: Record<string, unknown>;
855
+ }): Promise<Record<string, unknown>>;
856
+ /**
857
+ * Sync the database schema with the current collection and global configs.
858
+ * Called on startup to create tables/collections that don't exist yet.
859
+ * Not all adapters implement this (e.g. MongoDB is schema-less).
860
+ */
861
+ sync?(collections: CollectionConfig[], globals: GlobalConfig[]): Promise<void>;
862
+ /**
863
+ * Execute a raw SQL query or database command.
864
+ * Optional — not all adapters support raw access.
865
+ */
866
+ execute?(query: string, params?: unknown[]): Promise<unknown>;
867
+ /**
868
+ * Run all adapter operations in `callback` as one atomic transaction.
869
+ * Shipped adapters implement this; workflow transitions require it.
870
+ */
871
+ transaction?<T>(callback: (db: DatabaseAdapter) => Promise<T>): Promise<T>;
872
+ }
873
+ /**
874
+ * Read-only view of the database adapter. Exposes only `find`, `findOne`,
875
+ * and `getGlobal` — no write operations.
876
+ *
877
+ * Passed to `beforeChange`, `beforeDelete`, `beforeRead`, `afterRead`,
878
+ * and field-level hooks. Write operations are available in `afterChange`
879
+ * and `afterDelete` hooks where the full {@link DatabaseAdapter} is provided.
880
+ */
881
+ type ReadonlyDatabaseAdapter = Pick<DatabaseAdapter, "find" | "findOne" | "getGlobal">;
882
+ /**
883
+ * The interface every storage adapter must implement.
884
+ *
885
+ * Dyrected ships adapters for local disk, S3, Cloudflare R2, Cloudinary, and
886
+ * Backblaze B2. Implement this interface to use any other storage provider.
887
+ */
888
+ interface StorageAdapter {
889
+ /**
890
+ * Upload a file and return its metadata (URL, dimensions, etc.).
891
+ * The `prefix` is a path prefix used for multi-tenant setups.
892
+ */
893
+ upload(args: {
894
+ filename: string;
895
+ buffer: Uint8Array;
896
+ mimeType: string;
897
+ prefix?: string;
898
+ }): Promise<FileData>;
899
+ /** Delete a file by its stored filename. */
900
+ delete(args: {
901
+ filename: string;
902
+ }): Promise<void>;
903
+ /** Return the public URL for a stored file. */
904
+ getURL(args: {
905
+ filename: string;
906
+ }): string;
907
+ /**
908
+ * Retrieve the file's raw bytes and MIME type for serving via the API.
909
+ * Only needed by adapters that serve files through the Dyrected API
910
+ * (e.g. `LocalStorage`). Cloud adapters return `null` here and rely on
911
+ * direct CDN URLs instead.
912
+ */
913
+ resolve?(args: {
914
+ filename: string;
915
+ }): Promise<{
916
+ buffer: Uint8Array;
917
+ mimeType: string;
918
+ } | null>;
919
+ }
920
+ /**
921
+ * Processes uploaded images — generates metadata (dimensions, BlurHash) and
922
+ * produces resized variants defined in `UploadConfig.imageSizes`.
923
+ *
924
+ * @example
925
+ * import { SharpImageService } from '@dyrected/image-sharp'
926
+ * defineConfig({ image: new SharpImageService(), ... })
927
+ */
928
+ interface ImageService {
929
+ process(args: {
930
+ buffer: Uint8Array;
931
+ mimeType: string;
932
+ config?: boolean | UploadConfig;
933
+ focalPoint?: {
934
+ x: number;
935
+ y: number;
936
+ };
937
+ }): Promise<{
938
+ metadata: {
939
+ width?: number;
940
+ height?: number;
941
+ /** Base64-encoded BlurHash for progressive loading. */
942
+ blurhash?: string;
943
+ };
944
+ /** Generated image sizes keyed by their `name`. */
945
+ sizes?: Record<string, {
946
+ buffer: Uint8Array;
947
+ width: number;
948
+ height: number;
949
+ filename: string;
950
+ }>;
951
+ }>;
952
+ }
953
+
954
+ type FieldType = "text" | "textarea" | "richText" | "number" | "boolean" | "date" | "datetime" | "time" | "select" | "multiSelect" | "radio" | "relationship" | "array" | "object" | "json" | "blocks" | "image" | "email" | "url" | "icon" | "join" | "row";
955
+ interface DynamicOptionsResolverArgs {
956
+ /** Database adapter available to server-side option resolvers. */
957
+ db?: DatabaseAdapter;
958
+ /** Authenticated user making the request, if any. */
959
+ user?: AuthenticatedUser;
960
+ /** Current HTTP request context, including query parameters. */
961
+ req: HookRequestContext;
962
+ }
963
+ type DynamicOptionsResolver = (args: DynamicOptionsResolverArgs) => Promise<DynamicOptionItem[]> | DynamicOptionItem[];
964
+ interface DynamicOptionsConfig {
965
+ /** Resolver function executed on the server to produce option items. */
966
+ resolve: DynamicOptionsResolver;
967
+ /** Cache duration in seconds for identical resolver calls. */
968
+ cacheTTL?: number;
969
+ }
970
+ type DynamicOptionItem = string | {
971
+ label: string;
972
+ value: unknown;
973
+ };
974
+ interface Block {
975
+ /** Stable identifier stored in each block row as `blockType`. */
976
+ slug: string;
977
+ /** Human-readable labels shown in the Admin block picker. */
978
+ labels?: {
979
+ /** Singular label, for example `Hero`. */
980
+ singular: string;
981
+ /** Plural label, for example `Heroes`. */
982
+ plural: string;
983
+ };
984
+ /**
985
+ * Lucide icon name shown on the block card and in the block library.
986
+ * Falls back to a generic layout icon when omitted.
987
+ */
988
+ icon?: AdminIconName;
989
+ /** Short one-line summary shown under the block name (block card subtitle). */
990
+ description?: string;
991
+ /**
992
+ * Presentation variants for this block. All variants share the same `fields`;
993
+ * only the rendered layout differs. The chosen variant is stored on each block
994
+ * row under the reserved `variant` key and passed to the render component as a
995
+ * `variant` prop. Switching variant preserves the author's content.
996
+ */
997
+ variants?: BlockVariant[];
998
+ /** Fields that make up this block's payload. */
999
+ fields: Field[];
1000
+ }
1001
+ /**
1002
+ * A single presentation variant of a {@link Block}. Variants are a layout choice
1003
+ * over a shared field set — for example a Hero rendered "centered" vs "split".
1004
+ */
1005
+ interface BlockVariant {
1006
+ /** Stable identifier stored on the block row as `variant`. */
1007
+ slug: string;
1008
+ /** Human-readable label shown in the variant switcher. Defaults to `slug`. */
1009
+ label?: string;
1010
+ /** Lucide icon name shown beside the variant label. */
1011
+ icon?: AdminIconName;
1012
+ /** Short one-line summary of what this variant looks like. */
1013
+ description?: string;
1014
+ }
1015
+ interface FieldBase {
1016
+ /** Stored key for this field. Omit only for layout-only fields such as `row` or `join`. */
1017
+ name?: string;
1018
+ /** Human-readable label shown in the Admin UI. */
1019
+ label?: string;
1020
+ /** Whether the field must have a value when saving. */
1021
+ required?: boolean;
1022
+ /** Whether values for this field must be unique across the collection. */
1023
+ unique?: boolean;
1024
+ /** Default value used when a new document omits this field. */
1025
+ defaultValue?: unknown;
1026
+ /** Static or dynamic option source for supported selection fields. */
1027
+ options?: string[] | {
1028
+ label: string;
1029
+ value: unknown;
1030
+ }[] | DynamicOptionsResolver | DynamicOptionsConfig;
1031
+ /** Target collection slug for `relationship` fields. */
1032
+ relationTo?: string;
1033
+ /** Whether the field stores multiple values instead of one. */
1034
+ hasMany?: boolean;
1035
+ /** Child fields for `object` and `array` field types. */
1036
+ fields?: Field[];
1037
+ /** Allowed block definitions for a `blocks` field. */
1038
+ blocks?: Block[];
1039
+ /** Target collection slug for `join` fields. */
1040
+ collection?: string;
1041
+ /** Back-reference field name on the joined collection. */
1042
+ on?: string;
1043
+ /** Maximum number of joined documents returned by a `join` field. */
1044
+ limit?: number;
1045
+ /** Field-level read, create, and update access rules. Supports functions, Jexl strings, booleans, and named policies. */
1046
+ access?: {
1047
+ /** Controls whether this field is returned in API responses. */
1048
+ read?: AccessRule;
1049
+ /** Controls whether this field may be set when creating a document. Falls back to `update` when omitted. */
1050
+ create?: AccessRule;
1051
+ /** Controls whether incoming writes may change this field on update. */
1052
+ update?: AccessRule;
1053
+ };
1054
+ /** Admin-only presentation options for this field. */
1055
+ admin?: BaseFieldAdmin;
1056
+ /** Previous storage key this field falls back to. When the field has no value, its value is read from the old key at read time, then rewritten under the new key on the next save. */
1057
+ renameTo?: string;
1058
+ /** Whether SQL adapters should promote this field into a first-class column. */
1059
+ promoted?: boolean;
1060
+ }
1061
+ interface BaseFieldAdmin {
1062
+ /** Placeholder text shown when the input has no value. */
1063
+ placeholder?: string;
1064
+ /** Custom component key registered in the Admin UI. */
1065
+ component?: string;
1066
+ /** Help text rendered below the field. */
1067
+ description?: string;
1068
+ /** Hides the field from the Admin form without deleting stored data. */
1069
+ hidden?: boolean;
1070
+ /** Excludes the field from Admin list filtering. */
1071
+ filterable?: boolean;
1072
+ /** Renders the field as non-editable in the Admin UI. */
1073
+ readOnly?: boolean;
1074
+ /** Hides the field's label in the Admin form (e.g. single-field array rows where the label is redundant). */
1075
+ hideLabel?: boolean;
1076
+ /** Reactive condition controlling whether the field is visible in the Admin UI. */
1077
+ condition?: ((data: Record<string, unknown>, siblingData: Record<string, unknown>) => boolean) | string;
1078
+ /** Tab name used when the edit form is rendered as tabs. */
1079
+ tab?: string;
1080
+ /** CSS width hint used when the field appears inside a `row`. */
1081
+ width?: string;
1082
+ }
1083
+ interface FieldBeforeChangeHookArgs<TValue = unknown, TDoc extends object = Record<string, unknown>> {
1084
+ /** Current field value after previous hooks in the chain. */
1085
+ value: TValue;
1086
+ /** Existing stored document before the write, if this is an update. */
1087
+ originalDoc?: TDoc;
1088
+ /** Full incoming payload being written. */
1089
+ data: Record<string, unknown>;
1090
+ /** Authenticated user performing the write, if any. */
1091
+ user?: AuthenticatedUser;
1092
+ /** Read-only database adapter for related lookups. */
1093
+ db: ReadonlyDatabaseAdapter;
1094
+ }
1095
+ type FieldBeforeChangeHook<TValue = unknown, TDoc extends object = Record<string, unknown>> = (args: FieldBeforeChangeHookArgs<TValue, TDoc>) => unknown;
1096
+ interface FieldAfterReadHookArgs<TValue = unknown, TDoc extends object = Record<string, unknown>> {
1097
+ /** Raw stored field value before this hook transforms it. */
1098
+ value: TValue;
1099
+ /** Full document currently being returned to the caller. */
1100
+ doc: TDoc;
1101
+ /** Authenticated user requesting the document, if any. */
1102
+ user?: AuthenticatedUser;
1103
+ /** Read-only database adapter for related lookups. */
1104
+ db: ReadonlyDatabaseAdapter;
1105
+ }
1106
+ type FieldAfterReadHook<TValue = unknown, TDoc extends object = Record<string, unknown>> = (args: FieldAfterReadHookArgs<TValue, TDoc>) => unknown;
1107
+ type FieldHooks<TValue> = {
1108
+ hooks?: {
1109
+ beforeChange?: Array<FieldBeforeChangeHook<TValue>>;
1110
+ afterRead?: Array<FieldAfterReadHook<TValue>>;
1111
+ };
1112
+ };
1113
+ interface FieldAdminOnChangeHookArgs<TValue = unknown> {
1114
+ /** Current field value in the form state. */
1115
+ value: TValue;
1116
+ /** Current values for sibling fields at the same nesting level. */
1117
+ siblingData: Record<string, unknown>;
1118
+ /** Current values for the entire form. */
1119
+ data: Record<string, unknown>;
1120
+ /** Imperative setter for async or derived updates. */
1121
+ setValue: (value: unknown) => void;
1122
+ }
1123
+ type FieldAdminOnChangeHook<TValue = unknown> = (args: FieldAdminOnChangeHookArgs<TValue>) => unknown;
1124
+ type FieldAdminHooks<TValue> = {
1125
+ admin?: {
1126
+ hooks?: {
1127
+ onChange?: FieldAdminOnChangeHook<TValue>;
1128
+ };
1129
+ };
1130
+ };
1131
+ interface FieldAdminOptionsHookArgs {
1132
+ /** Current values for sibling fields at the same nesting level. */
1133
+ siblingData: Record<string, unknown>;
1134
+ /** Current values for the entire form. */
1135
+ data: Record<string, unknown>;
1136
+ }
1137
+ type FieldAdminOptionsHookResult = Array<string | {
1138
+ label: string;
1139
+ value: unknown;
1140
+ }>;
1141
+ type FieldAdminOptionsHook = (args: FieldAdminOptionsHookArgs) => FieldAdminOptionsHookResult | Promise<FieldAdminOptionsHookResult>;
1142
+ type TypedField<TType extends FieldType, TValue, TAdminExtra = Record<never, never>> = Omit<FieldBase, "admin"> & {
1143
+ type: TType;
1144
+ admin?: BaseFieldAdmin & TAdminExtra;
1145
+ } & FieldHooks<TValue> & FieldAdminHooks<TValue>;
1146
+ type BooleanFieldAdmin = {
1147
+ /** Boolean presentation style. */
1148
+ layout?: "checkbox" | "switch";
1149
+ };
1150
+ type SelectFieldAdmin = {
1151
+ /** Select presentation style. */
1152
+ layout?: "radio" | "select";
1153
+ /** Radio orientation when `layout: 'radio'` is used. */
1154
+ direction?: "horizontal" | "vertical";
1155
+ hooks?: {
1156
+ /** Client-side option recalculation for dependent dropdowns or radios. */
1157
+ options?: FieldAdminOptionsHook;
1158
+ };
1159
+ };
1160
+ type RadioFieldAdmin = {
1161
+ /** Radio group orientation. */
1162
+ direction?: "horizontal" | "vertical";
1163
+ hooks?: {
1164
+ /** Client-side option recalculation for dependent radio groups. */
1165
+ options?: FieldAdminOptionsHook;
1166
+ };
1167
+ };
1168
+ type MultiSelectFieldAdmin = {
1169
+ hooks?: {
1170
+ /** Client-side option recalculation for dependent multi-select fields. */
1171
+ options?: FieldAdminOptionsHook;
1172
+ };
1173
+ };
1174
+ interface CharacterLimitFieldConfig {
1175
+ /** Advisory maximum character count exposed to editors and client tooling. */
1176
+ maxLength?: number;
1177
+ }
1178
+ interface WordLimitFieldConfig {
1179
+ /** Advisory maximum word count exposed to editors and client tooling. */
1180
+ maxWords?: number;
1181
+ }
1182
+ interface NumberLimitFieldConfig {
1183
+ /** Advisory minimum numeric value exposed to editors and client tooling. */
1184
+ min?: number;
1185
+ /** Advisory maximum numeric value exposed to editors and client tooling. */
1186
+ max?: number;
1187
+ }
1188
+ type CharacterLimitFieldAdmin = {
1189
+ /** Admin-only compatibility alias for `field.maxLength`. Prefer the top-level field property. */
1190
+ maxLength?: number;
1191
+ };
1192
+ type WordLimitFieldAdmin = {
1193
+ /** Admin-only compatibility alias for `field.maxWords`. Prefer the top-level field property. */
1194
+ maxWords?: number;
1195
+ };
1196
+ type NumberLimitFieldAdmin = {
1197
+ /** Admin-only compatibility alias for `field.min`. Prefer the top-level field property. */
1198
+ min?: number;
1199
+ /** Admin-only compatibility alias for `field.max`. Prefer the top-level field property. */
1200
+ max?: number;
1201
+ };
1202
+ type TextFieldAdmin = CharacterLimitFieldAdmin & WordLimitFieldAdmin;
1203
+ type TextareaFieldAdmin = CharacterLimitFieldAdmin & WordLimitFieldAdmin;
1204
+ type EmailFieldAdmin = CharacterLimitFieldAdmin;
1205
+ type UrlFieldAdmin = CharacterLimitFieldAdmin;
1206
+ type IconFieldAdmin = CharacterLimitFieldAdmin;
1207
+ type NumberFieldAdmin = NumberLimitFieldAdmin;
1208
+ interface UrlLinkValue {
1209
+ /** Whether the link is a custom URL or a reference to an internal document. */
1210
+ type: "custom" | "internal";
1211
+ /** The link URL. Absolute for custom links; may be a site-relative path for internal links. */
1212
+ url?: string;
1213
+ /** For internal links, the collection slug of the referenced document. */
1214
+ relationTo?: string;
1215
+ /** For internal links, the ID of the referenced document. */
1216
+ value?: string;
1217
+ /** Optional display label shown for the link. */
1218
+ label?: string;
1219
+ }
1220
+ /**
1221
+ * Editor capabilities available on a `richText` field. Each feature maps to a
1222
+ * formatting control in the Admin editor toolbar and to the underlying editor
1223
+ * schema, so disabling a feature removes both its toolbar button and the
1224
+ * capability itself (including keyboard shortcuts and paste handling).
1225
+ */
1226
+ type RichTextFeature = "bold" | "italic" | "underline" | "strike" | "heading" | "bulletList" | "orderedList" | "blockquote" | "align" | "link" | "table" | "image";
1227
+ /** Heading levels offered by the `heading` rich-text feature. */
1228
+ type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
1229
+ interface RichTextFieldConfig {
1230
+ /**
1231
+ * Editor capabilities to enable, in toolbar order. When omitted, every
1232
+ * {@link RichTextFeature} is enabled (the default toolbar). Provide a subset
1233
+ * to restrict what editors can do — for example `['bold', 'italic', 'link']`
1234
+ * for a lightweight inline editor.
1235
+ */
1236
+ features?: RichTextFeature[];
1237
+ /**
1238
+ * Heading levels offered when the `heading` feature is enabled.
1239
+ * Defaults to `[1, 2, 3]`.
1240
+ */
1241
+ headingLevels?: HeadingLevel[];
1242
+ /**
1243
+ * Upload collection slug used by the `image` feature's media picker.
1244
+ * Defaults to the first collection configured with `upload: true`.
1245
+ */
1246
+ uploadCollection?: string;
1247
+ }
1248
+ type TextField = TypedField<"text", string, TextFieldAdmin> & CharacterLimitFieldConfig & WordLimitFieldConfig;
1249
+ type TextareaField = TypedField<"textarea", string, TextareaFieldAdmin> & CharacterLimitFieldConfig & WordLimitFieldConfig;
1250
+ type EmailField = TypedField<"email", string, EmailFieldAdmin> & CharacterLimitFieldConfig;
1251
+ type UrlField = TypedField<"url", string | UrlLinkValue, UrlFieldAdmin> & CharacterLimitFieldConfig;
1252
+ type IconField = TypedField<"icon", string, IconFieldAdmin> & CharacterLimitFieldConfig;
1253
+ type DateField = TypedField<"date", string>;
1254
+ type DateTimeField = TypedField<"datetime", string>;
1255
+ type TimeField = TypedField<"time", string>;
1256
+ type SelectField = TypedField<"select", string, SelectFieldAdmin>;
1257
+ type RadioField = TypedField<"radio", string, RadioFieldAdmin>;
1258
+ type NumberField = TypedField<"number", number, NumberFieldAdmin> & NumberLimitFieldConfig;
1259
+ type BooleanField = TypedField<"boolean", boolean, BooleanFieldAdmin>;
1260
+ type MultiSelectField = TypedField<"multiSelect", string[], MultiSelectFieldAdmin>;
1261
+ type RelationshipField = TypedField<"relationship", string | string[]>;
1262
+ type ImageField = TypedField<"image", string | string[]>;
1263
+ type RichTextField = TypedField<"richText", string> & RichTextFieldConfig;
1264
+ type JsonField = TypedField<"json", Record<string, unknown>>;
1265
+ type ObjectField = TypedField<"object", unknown>;
1266
+ type ArrayField = TypedField<"array", unknown>;
1267
+ type BlocksField = TypedField<"blocks", unknown>;
1268
+ type JoinField = TypedField<"join", unknown>;
1269
+ type RowField = TypedField<"row", unknown>;
1270
+ type Field = TextField | TextareaField | EmailField | UrlField | IconField | DateField | DateTimeField | TimeField | SelectField | RadioField | NumberField | BooleanField | MultiSelectField | RelationshipField | ImageField | RichTextField | JsonField | ObjectField | ArrayField | BlocksField | JoinField | RowField;
1271
+ interface UploadConfig {
1272
+ /** Allowed MIME types for uploaded files. */
1273
+ allowedMimeTypes?: string[];
1274
+ /** Maximum upload size in bytes. */
1275
+ maxFileSize?: number;
1276
+ /** Local filesystem destination used by disk-based storage adapters. */
1277
+ staticDir?: string;
1278
+ /** Public URL prefix for disk-based uploads. */
1279
+ staticURL?: string;
1280
+ /** Generated image size name used as the Admin media thumbnail. */
1281
+ adminThumbnail?: string;
1282
+ imageSizes?: {
1283
+ /** Stable name used to reference this generated size. */
1284
+ name: string;
1285
+ /** Target width in pixels. */
1286
+ width?: number;
1287
+ /** Target height in pixels. */
1288
+ height?: number;
1289
+ /** Crop strategy forwarded to the image processor. */
1290
+ crop?: string;
1291
+ /** Resize fit strategy forwarded to the image processor. */
1292
+ fit?: string;
1293
+ /** Prevents upscaling smaller source images. */
1294
+ withoutEnlargement?: boolean;
1295
+ /** Format-specific options forwarded to the image processor. */
1296
+ formatOptions?: Record<string, unknown>;
1297
+ }[];
1298
+ }
1299
+
1300
+ interface AdminAuthMember {
1301
+ id: string;
1302
+ email: string;
1303
+ name?: string;
1304
+ roles: string[];
1305
+ siteAccess?: string[];
1306
+ status?: "active" | "pending";
1307
+ [key: string]: any;
1308
+ }
1309
+ type AdminAuthProvisioningMode = "jit_only" | "jit_plus_membership_management" | "preprovisioned_only";
1310
+ interface AdminAuthClaimMapping {
1311
+ sub?: string;
1312
+ email?: string;
1313
+ name?: string;
1314
+ roles?: string;
1315
+ groups?: string;
1316
+ siteIds?: string;
1317
+ workspaceIds?: string;
1318
+ }
1319
+ interface AdminAuthResolvedIdentity {
1320
+ sub: string;
1321
+ email?: string;
1322
+ name?: string;
1323
+ roles?: string[];
1324
+ groups?: string[];
1325
+ siteIds?: string[];
1326
+ workspaceIds?: string[];
1327
+ rawClaims?: Record<string, unknown>;
1328
+ }
1329
+ interface AdminAuthAccessResolution {
1330
+ allowed: boolean;
1331
+ roles?: string[];
1332
+ data?: Record<string, unknown>;
1333
+ }
1334
+ interface AdminAuthResolveAccessArgs {
1335
+ identity: AdminAuthResolvedIdentity;
1336
+ providerId: string;
1337
+ siteId?: string;
1338
+ workspaceId?: string;
1339
+ req: {
1340
+ method: string;
1341
+ path: string;
1342
+ url: string;
1343
+ headers: Record<string, string | undefined>;
1344
+ };
1345
+ user: Record<string, unknown> | null;
1346
+ }
1347
+ interface AdminAuthProviderMembersConfig {
1348
+ list?: (args: {
1349
+ limit?: number;
1350
+ page?: number;
1351
+ sort?: string;
1352
+ where?: Record<string, any>;
1353
+ req: HookRequestContext;
1354
+ }) => Promise<{
1355
+ docs: AdminAuthMember[];
1356
+ totalDocs: number;
1357
+ limit: number;
1358
+ page: number;
1359
+ totalPages: number;
1360
+ hasNextPage: boolean;
1361
+ hasPrevPage: boolean;
1362
+ }>;
1363
+ get?: (args: {
1364
+ externalSubject: string;
1365
+ req: HookRequestContext;
1366
+ }) => Promise<AdminAuthMember | null>;
1367
+ create?: (args: {
1368
+ data: Record<string, any>;
1369
+ req: HookRequestContext;
1370
+ }) => Promise<AdminAuthMember>;
1371
+ update?: (args: {
1372
+ externalSubject: string;
1373
+ data: Record<string, any>;
1374
+ req: HookRequestContext;
1375
+ }) => Promise<AdminAuthMember>;
1376
+ delete?: (args: {
1377
+ externalSubject: string;
1378
+ req: HookRequestContext;
1379
+ }) => Promise<void>;
1380
+ }
1381
+ interface BaseAdminAuthProvider {
1382
+ id: string;
1383
+ type: "oidc" | "custom" | "cloud";
1384
+ displayName?: string;
1385
+ autoRedirect?: boolean;
1386
+ allowJitProvisioning?: boolean;
1387
+ claimMapping?: AdminAuthClaimMapping;
1388
+ members?: AdminAuthProviderMembersConfig;
1389
+ }
1390
+ interface OIDCAdminAuthProvider extends BaseAdminAuthProvider {
1391
+ type: "oidc";
1392
+ issuer: string;
1393
+ clientId: string;
1394
+ clientSecret: string;
1395
+ redirectUri?: string;
1396
+ scopes?: string[];
1397
+ authorizationEndpoint?: string;
1398
+ tokenEndpoint?: string;
1399
+ userInfoEndpoint?: string;
1400
+ }
1401
+ interface CustomAdminAuthProvider extends BaseAdminAuthProvider {
1402
+ type: "custom" | "cloud";
1403
+ startUrl?: string;
1404
+ issuer?: string;
1405
+ audience?: string;
1406
+ secret?: string;
1407
+ jwksUri?: string;
1408
+ tokenParam?: string;
1409
+ }
1410
+ type AdminAuthProvider = OIDCAdminAuthProvider | CustomAdminAuthProvider;
1411
+ interface PublicAdminAuthProvider {
1412
+ id: string;
1413
+ type: AdminAuthProvider["type"];
1414
+ displayName: string;
1415
+ autoRedirect?: boolean;
1416
+ }
1417
+ interface PublicAdminAuthConfig {
1418
+ mode: "local" | "external";
1419
+ collectionSlug?: string;
1420
+ provisioningMode?: AdminAuthProvisioningMode;
1421
+ providers: PublicAdminAuthProvider[];
1422
+ }
1423
+ interface AdminAuthConfig {
1424
+ mode: "local" | "external";
1425
+ collectionSlug?: string;
1426
+ provisioningMode?: AdminAuthProvisioningMode;
1427
+ providers: AdminAuthProvider[];
1428
+ resolveAccess?: (args: AdminAuthResolveAccessArgs) => Promise<AdminAuthAccessResolution> | AdminAuthAccessResolution;
1429
+ }
1430
+
1431
+ /**
1432
+ * The root configuration object passed to `createDyrectedApp`.
1433
+ *
1434
+ * This is the single source of truth for your entire Dyrected instance —
1435
+ * collections, globals, database adapter, storage, email, and more.
1436
+ *
1437
+ * @example
1438
+ * import { defineConfig } from '@dyrected/core'
1439
+ * import { SQLiteAdapter } from '@dyrected/db-sqlite'
1440
+ *
1441
+ * export default defineConfig({
1442
+ * db: new SQLiteAdapter({ filename: './db.sqlite' }),
1443
+ * collections: [Posts, Users],
1444
+ * globals: [SiteSettings],
1445
+ * })
1446
+ */
1447
+ interface DyrectedConfig<TUser extends AuthenticatedUser = AuthenticatedUser> {
1448
+ /** Collection definitions. Each collection maps to a database table/collection. */
1449
+ collections: CollectionConfig<any>[];
1450
+ /** Global (singleton) definitions. Each global maps to a single document. */
1451
+ globals: GlobalConfig<any>[];
1452
+ /**
1453
+ * The database adapter. Required for all data operations.
1454
+ * @see DatabaseAdapter
1455
+ */
1456
+ db?: DatabaseAdapter;
1457
+ /**
1458
+ * The storage adapter for file uploads.
1459
+ * Required when any collection has `upload: true`.
1460
+ * @see StorageAdapter
1461
+ */
1462
+ storage?: StorageAdapter;
1463
+ /**
1464
+ * The image processing service. Required when any upload collection
1465
+ * defines `imageSizes`.
1466
+ * @see ImageService
1467
+ */
1468
+ image?: ImageService;
1469
+ /** Admin UI branding and metadata. */
1470
+ admin?: AdminConfig;
1471
+ /**
1472
+ * Deployment-level authentication strategy for the CMS dashboard (`/admin`).
1473
+ * This is separate from collection-level `auth: true`, which continues to
1474
+ * power application/customer auth independently.
1475
+ */
1476
+ adminAuth?: AdminAuthConfig;
1477
+ /**
1478
+ * Named access policies available to collection, global, and field access
1479
+ * rules via `{ policy: 'name' }`.
1480
+ *
1481
+ * A policy can be a **function** (full server logic, evaluated to a static
1482
+ * boolean when serialized for the admin panel) or a **Jexl string** (or
1483
+ * boolean). String policies are inlined when the schema is sent to the admin,
1484
+ * so the admin panel evaluates them live against the current form — the same
1485
+ * way it evaluates inline Jexl rules.
1486
+ */
1487
+ accessPolicies?: Record<string, AccessPolicyResolver<Record<string, unknown>, TUser> | string | boolean>;
1488
+ /**
1489
+ * Email transport configuration. Required for welcome emails, password
1490
+ * resets, and invite links.
1491
+ *
1492
+ * @example
1493
+ * email: {
1494
+ * from: 'no-reply@myapp.com',
1495
+ * send: async ({ to, subject, html }) => {
1496
+ * await resend.emails.send({ from, to, subject, html })
1497
+ * },
1498
+ * }
1499
+ */
1500
+ email?: {
1501
+ /** The `From` address for all outbound emails. */
1502
+ from: string;
1503
+ /** The send function. Wire in any email provider (Resend, SendGrid, SES, etc.). */
1504
+ send: (args: {
1505
+ to: string;
1506
+ subject: string;
1507
+ html: string;
1508
+ }) => Promise<void>;
1509
+ /** Override the default email templates. */
1510
+ templates?: {
1511
+ welcome?: (args: {
1512
+ email: string;
1513
+ }) => {
1514
+ subject?: string;
1515
+ html: string;
1516
+ };
1517
+ invite?: (args: {
1518
+ token: string;
1519
+ invitedByEmail?: string;
1520
+ }) => {
1521
+ subject?: string;
1522
+ html: string;
1523
+ };
1524
+ resetPassword?: (args: {
1525
+ token: string;
1526
+ url?: string;
1527
+ }) => {
1528
+ subject?: string;
1529
+ html: string;
1530
+ };
1531
+ passwordChanged?: (args: {
1532
+ email: string;
1533
+ }) => {
1534
+ subject?: string;
1535
+ html: string;
1536
+ };
1537
+ };
1538
+ };
1539
+ /**
1540
+ * Redis connection URL. Required for distributed caching of dynamic option
1541
+ * resolvers and other server-side caches in multi-instance deployments.
1542
+ *
1543
+ * @example
1544
+ * redis: { url: process.env.REDIS_URL }
1545
+ */
1546
+ redis?: {
1547
+ url: string;
1548
+ };
1549
+ /** Durable lifecycle-event delivery configuration. */
1550
+ events?: {
1551
+ handlers: LifecycleEventHandler[];
1552
+ /** Maximum delivery attempts before an event remains failed. Defaults to 8. */
1553
+ maxAttempts?: number;
1554
+ /** Initial exponential-backoff delay in milliseconds. Defaults to 1000. */
1555
+ retryDelayMs?: number;
1556
+ };
1557
+ /**
1558
+ * Cross-Origin Resource Sharing (CORS) configuration.
1559
+ * List all origins that are allowed to call the Dyrected API.
1560
+ *
1561
+ * @example
1562
+ * cors: { origins: ['https://myapp.com', 'https://www.myapp.com'] }
1563
+ */
1564
+ cors?: {
1565
+ origins: string[];
1566
+ };
1567
+ /**
1568
+ * Callback to dynamically fetch additional collections and globals for a
1569
+ * given site ID at request time. Used in multi-tenant deployments where each
1570
+ * site has its own schema stored in the database.
1571
+ */
1572
+ onSchemaFetch?: (siteId: string) => Promise<{
1573
+ collections?: CollectionConfig<any>[];
1574
+ globals?: GlobalConfig<any>[];
1575
+ admin?: AdminConfig;
1576
+ adminAuth?: AdminAuthConfig;
1577
+ }>;
1578
+ }
1579
+
1580
+ export { type BaseFieldAdmin as $, type AdminAuthConfig as A, type Block as B, type CollectionConfig as C, type DyrectedConfig as D, type EmailField as E, type Field as F, type GlobalConfig as G, type HookRequestContext as H, type IconField as I, type JoinField as J, type AdminAuthProvisioningMode as K, type LifecycleEventName as L, type MultiSelectField as M, type NumberField as N, type ObjectField as O, type PublicAdminAuthConfig as P, type AdminAuthResolveAccessArgs as Q, type RadioField as R, type SelectField as S, type TextField as T, type UrlField as U, type AdminAuthResolvedIdentity as V, type WorkflowConfig as W, type AdminConfig as X, type AdminDashboardComponentSlots as Y, type AdminIconName as Z, type BaseAdminAuthProvider as _, type AuthenticatedUser as a, type UrlFieldAdmin as a$, type BlockVariant as a0, type BooleanFieldAdmin as a1, type CharacterLimitFieldAdmin as a2, type CharacterLimitFieldConfig as a3, type CollectionAfterChangeHook as a4, type CollectionAfterDeleteHook as a5, type CollectionAfterReadHook as a6, type CollectionAfterTransitionHook as a7, type CollectionBeforeChangeHook as a8, type CollectionBeforeDeleteHook as a9, type GlobalAfterReadHook as aA, type GlobalBeforeChangeHook as aB, type GlobalBeforeReadHook as aC, type HeadingLevel as aD, type HookFunction as aE, type IconFieldAdmin as aF, type ImageService as aG, LIFECYCLE_EVENT_NAMES as aH, type LifecycleEventHandler as aI, type MultiSelectFieldAdmin as aJ, type NamedAccessPolicy as aK, type NumberFieldAdmin as aL, type NumberLimitFieldAdmin as aM, type NumberLimitFieldConfig as aN, type OIDCAdminAuthProvider as aO, type PaginatedResult as aP, type PublicAdminAuthProvider as aQ, type RadioFieldAdmin as aR, type ReadonlyDatabaseAdapter as aS, type RichTextFeature as aT, type RichTextFieldConfig as aU, type SelectFieldAdmin as aV, type StorageAdapter as aW, type TextFieldAdmin as aX, type TextareaFieldAdmin as aY, type TypedField as aZ, type UploadConfig as a_, type CollectionBeforeReadHook as aa, type CollectionBeforeTransitionHook as ab, type CollectionListComponentSlots as ac, type CustomAdminAuthProvider as ad, type DatabaseAdapter as ae, type DynamicOptionItem as af, type DynamicOptionsConfig as ag, type DynamicOptionsResolver as ah, type DynamicOptionsResolverArgs as ai, type EmailFieldAdmin as aj, type FieldAdminHooks as ak, type FieldAdminOnChangeHook as al, type FieldAdminOnChangeHookArgs as am, type FieldAdminOptionsHook as an, type FieldAdminOptionsHookArgs as ao, type FieldAdminOptionsHookResult as ap, type FieldAfterReadHook as aq, type FieldAfterReadHookArgs as ar, type FieldBase as as, type FieldBeforeChangeHook as at, type FieldBeforeChangeHookArgs as au, type FieldHook as av, type FieldHooks as aw, type FieldType as ax, type FileData as ay, type GlobalAfterChangeHook as az, type WorkflowTransition as b, type UrlLinkValue as b0, type WordLimitFieldAdmin as b1, type WordLimitFieldConfig as b2, type WorkflowMetadata as b3, type WorkflowRole as b4, type WorkflowState as b5, type WorkflowTransitionContext as b6, type LifecycleEvent as c, type BaseDocument as d, type ArrayField as e, type BlocksField as f, type BooleanField as g, type DateField as h, type DateTimeField as i, type ImageField as j, type JsonField as k, type RelationshipField as l, type RichTextField as m, type RowField as n, type TextareaField as o, type TimeField as p, type AccessFunction as q, type AccessFunctionArgs as r, type AccessPolicyResolver as s, type AccessResult as t, type AccessRule as u, type AdminAuthAccessResolution as v, type AdminAuthClaimMapping as w, type AdminAuthMember as x, type AdminAuthProvider as y, type AdminAuthProviderMembersConfig as z };